janja 4.4.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
@@ -1816,7 +1816,7 @@ function isStringLit(exp) {
1816
1816
  return exp.type === 'LIT' && typeof exp.value === 'string';
1817
1817
  }
1818
1818
  class IncludeNode extends Traversal {
1819
- constructor(val, loc, strip, withExp = null) {
1819
+ constructor(val, loc, strip, withExp = null, modifier = null) {
1820
1820
  super();
1821
1821
  Object.defineProperty(this, "val", {
1822
1822
  enumerable: true,
@@ -1842,6 +1842,12 @@ class IncludeNode extends Traversal {
1842
1842
  writable: true,
1843
1843
  value: withExp
1844
1844
  });
1845
+ Object.defineProperty(this, "modifier", {
1846
+ enumerable: true,
1847
+ configurable: true,
1848
+ writable: true,
1849
+ value: modifier
1850
+ });
1845
1851
  Object.defineProperty(this, "type", {
1846
1852
  enumerable: true,
1847
1853
  configurable: true,
@@ -2002,7 +2008,9 @@ class Compiler extends Context {
2002
2008
  if (this.partials.size || this.hasDynamicInclude) {
2003
2009
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
2004
2010
  // Alias the render data before partials shadow `c` with their argument.
2005
- 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={');
2006
2014
  for (const [path, code] of this.partials) {
2007
2015
  this.pushRaw(null,
2008
2016
  // Partials take the context they should render with: plain include
@@ -2143,6 +2151,7 @@ class Compiler extends Context {
2143
2151
  const partials = new Map();
2144
2152
  const blocks = [];
2145
2153
  const stylesheets = [];
2154
+ const includeLast = new Map();
2146
2155
  const traverse = (node) => {
2147
2156
  if (node.type === 'INCLUDE') {
2148
2157
  const include = node;
@@ -2150,6 +2159,15 @@ class Compiler extends Context {
2150
2159
  if (!partials.has(include.val.value)) {
2151
2160
  partials.set(include.val.value, include);
2152
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
+ }
2153
2171
  }
2154
2172
  else {
2155
2173
  this.hasDynamicInclude = true;
@@ -2164,6 +2182,7 @@ class Compiler extends Context {
2164
2182
  node.traverse(traverse);
2165
2183
  };
2166
2184
  traverse(this.rootNode);
2185
+ this.state.includeLast = includeLast;
2167
2186
  return {
2168
2187
  partials,
2169
2188
  blocks,
@@ -3628,39 +3647,71 @@ const plugin$9 = {
3628
3647
  parsers: parsers$9,
3629
3648
  };
3630
3649
 
3631
- async function compileInclude({ val, loc, withExp }, compiler) {
3650
+ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3632
3651
  const expCompiler = new ExpCompiler();
3633
3652
  const path = isStringLit(val)
3634
3653
  ? JSON.stringify(val.value)
3635
3654
  : expCompiler.compile(val, compiler.context);
3636
- if (withExp) {
3637
- const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3638
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
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}}`);
3639
3665
  return;
3640
3666
  }
3641
- // Plain include always sees the top-level context, not loop/with scopes.
3642
- 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);
3643
3682
  }
3644
3683
  const compilers$8 = {
3645
3684
  INCLUDE: compileInclude,
3646
3685
  };
3647
3686
 
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*$/;
3648
3690
  function* parseInclude(token, parser) {
3649
3691
  if (!token.expression) {
3650
3692
  parser.emitExpErr(token);
3651
3693
  return;
3652
3694
  }
3653
3695
  yield 'NEXT';
3654
- 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 });
3655
3706
  if (!exp) {
3656
3707
  return;
3657
3708
  }
3658
3709
  if (exp.type === 'WITH') {
3659
3710
  const { left, right } = exp;
3660
- yield new IncludeNode(left, token.loc, token.strip, right);
3711
+ yield new IncludeNode(left, token.loc, token.strip, right, modifier);
3661
3712
  return;
3662
3713
  }
3663
- yield new IncludeNode(exp, token.loc, token.strip);
3714
+ yield new IncludeNode(exp, token.loc, token.strip, null, modifier);
3664
3715
  }
3665
3716
  const parsers$8 = {
3666
3717
  include: parseInclude,
@@ -5678,10 +5729,12 @@ function indentHtml(source, options) {
5678
5729
  /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5679
5730
  let bodyBuf = null;
5680
5731
  const out = [];
5732
+ /** Open `{{#` comment: inner lines are never scanned for pieces. */
5733
+ const state = { inComment: false };
5681
5734
  for (const line of lines) {
5682
5735
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5683
5736
  const content = line.slice(leading);
5684
- const { pieces, prefixClosers } = scanLine(content, options);
5737
+ const { pieces, prefixClosers } = scanLine(content, options, state);
5685
5738
  const activeSensitive = sensitive;
5686
5739
  const closesSensitive = activeSensitive !== null &&
5687
5740
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
@@ -5737,16 +5790,35 @@ function indentHtml(source, options) {
5737
5790
  }
5738
5791
  }
5739
5792
  }
5740
- function scanLine(line, options) {
5793
+ function scanLine(line, options, state) {
5741
5794
  const pieces = [];
5742
5795
  let prefixClosers = 0;
5743
5796
  let atPrefix = true;
5744
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
+ }
5745
5806
  while (i < line.length) {
5746
5807
  if (/\s/.test(line[i])) {
5747
5808
  i += 1;
5748
5809
  continue;
5749
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
+ }
5750
5822
  const next = readAt(line, i, options);
5751
5823
  if (!next) {
5752
5824
  // Plain text ends the leading-closer prefix
@@ -5773,12 +5845,7 @@ function scanLine(line, options) {
5773
5845
  return { pieces, prefixClosers };
5774
5846
  }
5775
5847
  function readAt(line, i, options) {
5776
- const { commentOpen, directiveOpen, outputOpen } = options;
5777
- if (line.startsWith(commentOpen, i)) {
5778
- return {
5779
- end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5780
- };
5781
- }
5848
+ const { directiveOpen, outputOpen } = options;
5782
5849
  if (line.startsWith(outputOpen, i)) {
5783
5850
  return {
5784
5851
  end: endOfDelimited(line, i + outputOpen.length, options.outputClose),
package/dist/index.esm.js CHANGED
@@ -1814,7 +1814,7 @@ function isStringLit(exp) {
1814
1814
  return exp.type === 'LIT' && typeof exp.value === 'string';
1815
1815
  }
1816
1816
  class IncludeNode extends Traversal {
1817
- constructor(val, loc, strip, withExp = null) {
1817
+ constructor(val, loc, strip, withExp = null, modifier = null) {
1818
1818
  super();
1819
1819
  Object.defineProperty(this, "val", {
1820
1820
  enumerable: true,
@@ -1840,6 +1840,12 @@ class IncludeNode extends Traversal {
1840
1840
  writable: true,
1841
1841
  value: withExp
1842
1842
  });
1843
+ Object.defineProperty(this, "modifier", {
1844
+ enumerable: true,
1845
+ configurable: true,
1846
+ writable: true,
1847
+ value: modifier
1848
+ });
1843
1849
  Object.defineProperty(this, "type", {
1844
1850
  enumerable: true,
1845
1851
  configurable: true,
@@ -2000,7 +2006,9 @@ class Compiler extends Context {
2000
2006
  if (this.partials.size || this.hasDynamicInclude) {
2001
2007
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
2002
2008
  // Alias the render data before partials shadow `c` with their argument.
2003
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
2009
+ // `inc_` tracks `include … once` occurrences across the whole render,
2010
+ // root template and partials alike (they share this closure).
2011
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
2004
2012
  for (const [path, code] of this.partials) {
2005
2013
  this.pushRaw(null,
2006
2014
  // Partials take the context they should render with: plain include
@@ -2141,6 +2149,7 @@ class Compiler extends Context {
2141
2149
  const partials = new Map();
2142
2150
  const blocks = [];
2143
2151
  const stylesheets = [];
2152
+ const includeLast = new Map();
2144
2153
  const traverse = (node) => {
2145
2154
  if (node.type === 'INCLUDE') {
2146
2155
  const include = node;
@@ -2148,6 +2157,15 @@ class Compiler extends Context {
2148
2157
  if (!partials.has(include.val.value)) {
2149
2158
  partials.set(include.val.value, include);
2150
2159
  }
2160
+ if (include.modifier === 'last') {
2161
+ const existing = includeLast.get(include.val.value);
2162
+ if (existing) {
2163
+ existing.total += 1;
2164
+ }
2165
+ else {
2166
+ includeLast.set(include.val.value, { total: 1, emitted: 0 });
2167
+ }
2168
+ }
2151
2169
  }
2152
2170
  else {
2153
2171
  this.hasDynamicInclude = true;
@@ -2162,6 +2180,7 @@ class Compiler extends Context {
2162
2180
  node.traverse(traverse);
2163
2181
  };
2164
2182
  traverse(this.rootNode);
2183
+ this.state.includeLast = includeLast;
2165
2184
  return {
2166
2185
  partials,
2167
2186
  blocks,
@@ -3626,39 +3645,71 @@ const plugin$9 = {
3626
3645
  parsers: parsers$9,
3627
3646
  };
3628
3647
 
3629
- async function compileInclude({ val, loc, withExp }, compiler) {
3648
+ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3630
3649
  const expCompiler = new ExpCompiler();
3631
3650
  const path = isStringLit(val)
3632
3651
  ? JSON.stringify(val.value)
3633
3652
  : expCompiler.compile(val, compiler.context);
3634
- if (withExp) {
3635
- const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3636
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3653
+ // Emit the partial call, against the top context for a plain include or a
3654
+ // merged scope for `include … with`.
3655
+ const emit = withExp
3656
+ ? `s+=await p[${path}]?.({...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}})??"";`
3657
+ : `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`;
3658
+ // `once`: render the first occurrence only. The registry lives in the root
3659
+ // script's closure, so occurrences spread across different files (a root
3660
+ // template and its partials) still deduplicate at runtime.
3661
+ if (modifier === 'once') {
3662
+ compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3637
3663
  return;
3638
3664
  }
3639
- // Plain include always sees the top-level context, not loop/with scopes.
3640
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`);
3665
+ // `last`: emit only at the final occurrence within the template file,
3666
+ // determined at compile time from the counts collected alongside partials.
3667
+ // Static string paths only — a dynamic path has no stable identity to count.
3668
+ if (modifier === 'last' && isStringLit(val)) {
3669
+ const counts = compiler.state.includeLast;
3670
+ const entry = counts?.get(val.value);
3671
+ if (entry) {
3672
+ entry.emitted += 1;
3673
+ if (entry.emitted < entry.total) {
3674
+ // Not the last occurrence — emit nothing.
3675
+ return;
3676
+ }
3677
+ }
3678
+ }
3679
+ compiler.pushRaw(loc, emit);
3641
3680
  }
3642
3681
  const compilers$8 = {
3643
3682
  INCLUDE: compileInclude,
3644
3683
  };
3645
3684
 
3685
+ // Modifier keywords that may appear after the path expression.
3686
+ // e.g. `{{ include "foo" once }}` or `{{ include "foo" last }}`
3687
+ const MODIFIER_RE = /\s+(once|last)\s*$/;
3646
3688
  function* parseInclude(token, parser) {
3647
3689
  if (!token.expression) {
3648
3690
  parser.emitExpErr(token);
3649
3691
  return;
3650
3692
  }
3651
3693
  yield 'NEXT';
3652
- const exp = parser.parseExp(token.expression);
3694
+ // Strip a trailing `once` or `last` keyword before parsing the expression,
3695
+ // so the expression parser does not trip over an unknown identifier.
3696
+ let rawVal = token.expression.val;
3697
+ let modifier = null;
3698
+ const modifierMatch = MODIFIER_RE.exec(rawVal);
3699
+ if (modifierMatch) {
3700
+ modifier = modifierMatch[1];
3701
+ rawVal = rawVal.slice(0, modifierMatch.index);
3702
+ }
3703
+ const exp = parser.parseExp({ val: rawVal, loc: token.expression.loc });
3653
3704
  if (!exp) {
3654
3705
  return;
3655
3706
  }
3656
3707
  if (exp.type === 'WITH') {
3657
3708
  const { left, right } = exp;
3658
- yield new IncludeNode(left, token.loc, token.strip, right);
3709
+ yield new IncludeNode(left, token.loc, token.strip, right, modifier);
3659
3710
  return;
3660
3711
  }
3661
- yield new IncludeNode(exp, token.loc, token.strip);
3712
+ yield new IncludeNode(exp, token.loc, token.strip, null, modifier);
3662
3713
  }
3663
3714
  const parsers$8 = {
3664
3715
  include: parseInclude,
@@ -5676,10 +5727,12 @@ function indentHtml(source, options) {
5676
5727
  /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5677
5728
  let bodyBuf = null;
5678
5729
  const out = [];
5730
+ /** Open `{{#` comment: inner lines are never scanned for pieces. */
5731
+ const state = { inComment: false };
5679
5732
  for (const line of lines) {
5680
5733
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5681
5734
  const content = line.slice(leading);
5682
- const { pieces, prefixClosers } = scanLine(content, options);
5735
+ const { pieces, prefixClosers } = scanLine(content, options, state);
5683
5736
  const activeSensitive = sensitive;
5684
5737
  const closesSensitive = activeSensitive !== null &&
5685
5738
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
@@ -5735,16 +5788,35 @@ function indentHtml(source, options) {
5735
5788
  }
5736
5789
  }
5737
5790
  }
5738
- function scanLine(line, options) {
5791
+ function scanLine(line, options, state) {
5739
5792
  const pieces = [];
5740
5793
  let prefixClosers = 0;
5741
5794
  let atPrefix = true;
5742
5795
  let i = 0;
5796
+ if (state.inComment) {
5797
+ const close = line.indexOf(options.commentClose);
5798
+ if (close === -1) {
5799
+ return { pieces, prefixClosers };
5800
+ }
5801
+ state.inComment = false;
5802
+ i = close + options.commentClose.length;
5803
+ }
5743
5804
  while (i < line.length) {
5744
5805
  if (/\s/.test(line[i])) {
5745
5806
  i += 1;
5746
5807
  continue;
5747
5808
  }
5809
+ if (line.startsWith(options.commentOpen, i)) {
5810
+ const close = line.indexOf(options.commentClose, i + options.commentOpen.length);
5811
+ // Comment runs past this line; the rest is comment text
5812
+ if (close === -1) {
5813
+ state.inComment = true;
5814
+ return { pieces, prefixClosers };
5815
+ }
5816
+ atPrefix = false;
5817
+ i = close + options.commentClose.length;
5818
+ continue;
5819
+ }
5748
5820
  const next = readAt(line, i, options);
5749
5821
  if (!next) {
5750
5822
  // Plain text ends the leading-closer prefix
@@ -5771,12 +5843,7 @@ function scanLine(line, options) {
5771
5843
  return { pieces, prefixClosers };
5772
5844
  }
5773
5845
  function readAt(line, i, options) {
5774
- const { commentOpen, directiveOpen, outputOpen } = options;
5775
- if (line.startsWith(commentOpen, i)) {
5776
- return {
5777
- end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5778
- };
5779
- }
5846
+ const { directiveOpen, outputOpen } = options;
5780
5847
  if (line.startsWith(outputOpen, i)) {
5781
5848
  return {
5782
5849
  end: endOfDelimited(line, i + outputOpen.length, options.outputClose),
package/dist/index.js CHANGED
@@ -1817,7 +1817,7 @@ ${suggestionText}`;
1817
1817
  return exp.type === 'LIT' && typeof exp.value === 'string';
1818
1818
  }
1819
1819
  class IncludeNode extends Traversal {
1820
- constructor(val, loc, strip, withExp = null) {
1820
+ constructor(val, loc, strip, withExp = null, modifier = null) {
1821
1821
  super();
1822
1822
  Object.defineProperty(this, "val", {
1823
1823
  enumerable: true,
@@ -1843,6 +1843,12 @@ ${suggestionText}`;
1843
1843
  writable: true,
1844
1844
  value: withExp
1845
1845
  });
1846
+ Object.defineProperty(this, "modifier", {
1847
+ enumerable: true,
1848
+ configurable: true,
1849
+ writable: true,
1850
+ value: modifier
1851
+ });
1846
1852
  Object.defineProperty(this, "type", {
1847
1853
  enumerable: true,
1848
1854
  configurable: true,
@@ -2003,7 +2009,9 @@ ${suggestionText}`;
2003
2009
  if (this.partials.size || this.hasDynamicInclude) {
2004
2010
  const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
2005
2011
  // Alias the render data before partials shadow `c` with their argument.
2006
- this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const p={');
2012
+ // `inc_` tracks `include … once` occurrences across the whole render,
2013
+ // root template and partials alike (they share this closure).
2014
+ this.pushRaw(null, `const ${TOP_CONTEXT}=${CONTEXT};`, 'let d_=0;', 'const inc_={};', 'const p={');
2007
2015
  for (const [path, code] of this.partials) {
2008
2016
  this.pushRaw(null,
2009
2017
  // Partials take the context they should render with: plain include
@@ -2144,6 +2152,7 @@ ${suggestionText}`;
2144
2152
  const partials = new Map();
2145
2153
  const blocks = [];
2146
2154
  const stylesheets = [];
2155
+ const includeLast = new Map();
2147
2156
  const traverse = (node) => {
2148
2157
  if (node.type === 'INCLUDE') {
2149
2158
  const include = node;
@@ -2151,6 +2160,15 @@ ${suggestionText}`;
2151
2160
  if (!partials.has(include.val.value)) {
2152
2161
  partials.set(include.val.value, include);
2153
2162
  }
2163
+ if (include.modifier === 'last') {
2164
+ const existing = includeLast.get(include.val.value);
2165
+ if (existing) {
2166
+ existing.total += 1;
2167
+ }
2168
+ else {
2169
+ includeLast.set(include.val.value, { total: 1, emitted: 0 });
2170
+ }
2171
+ }
2154
2172
  }
2155
2173
  else {
2156
2174
  this.hasDynamicInclude = true;
@@ -2165,6 +2183,7 @@ ${suggestionText}`;
2165
2183
  node.traverse(traverse);
2166
2184
  };
2167
2185
  traverse(this.rootNode);
2186
+ this.state.includeLast = includeLast;
2168
2187
  return {
2169
2188
  partials,
2170
2189
  blocks,
@@ -3629,39 +3648,71 @@ ${suggestionText}`;
3629
3648
  parsers: parsers$9,
3630
3649
  };
3631
3650
 
3632
- async function compileInclude({ val, loc, withExp }, compiler) {
3651
+ async function compileInclude({ val, loc, withExp, modifier }, compiler) {
3633
3652
  const expCompiler = new ExpCompiler();
3634
3653
  const path = isStringLit(val)
3635
3654
  ? JSON.stringify(val.value)
3636
3655
  : expCompiler.compile(val, compiler.context);
3637
- if (withExp) {
3638
- const merged = `{...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}}`;
3639
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${merged})??"";`);
3656
+ // Emit the partial call, against the top context for a plain include or a
3657
+ // merged scope for `include … with`.
3658
+ const emit = withExp
3659
+ ? `s+=await p[${path}]?.({...${compiler.context},...${expCompiler.compile(withExp, compiler.context)}})??"";`
3660
+ : `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`;
3661
+ // `once`: render the first occurrence only. The registry lives in the root
3662
+ // script's closure, so occurrences spread across different files (a root
3663
+ // template and its partials) still deduplicate at runtime.
3664
+ if (modifier === 'once') {
3665
+ compiler.pushRaw(loc, `if(!inc_[${path}]){inc_[${path}]=1;${emit}}`);
3640
3666
  return;
3641
3667
  }
3642
- // Plain include always sees the top-level context, not loop/with scopes.
3643
- compiler.pushRaw(loc, `s+=await p[${path}]?.(${TOP_CONTEXT})??"";`);
3668
+ // `last`: emit only at the final occurrence within the template file,
3669
+ // determined at compile time from the counts collected alongside partials.
3670
+ // Static string paths only — a dynamic path has no stable identity to count.
3671
+ if (modifier === 'last' && isStringLit(val)) {
3672
+ const counts = compiler.state.includeLast;
3673
+ const entry = counts?.get(val.value);
3674
+ if (entry) {
3675
+ entry.emitted += 1;
3676
+ if (entry.emitted < entry.total) {
3677
+ // Not the last occurrence — emit nothing.
3678
+ return;
3679
+ }
3680
+ }
3681
+ }
3682
+ compiler.pushRaw(loc, emit);
3644
3683
  }
3645
3684
  const compilers$8 = {
3646
3685
  INCLUDE: compileInclude,
3647
3686
  };
3648
3687
 
3688
+ // Modifier keywords that may appear after the path expression.
3689
+ // e.g. `{{ include "foo" once }}` or `{{ include "foo" last }}`
3690
+ const MODIFIER_RE = /\s+(once|last)\s*$/;
3649
3691
  function* parseInclude(token, parser) {
3650
3692
  if (!token.expression) {
3651
3693
  parser.emitExpErr(token);
3652
3694
  return;
3653
3695
  }
3654
3696
  yield 'NEXT';
3655
- const exp = parser.parseExp(token.expression);
3697
+ // Strip a trailing `once` or `last` keyword before parsing the expression,
3698
+ // so the expression parser does not trip over an unknown identifier.
3699
+ let rawVal = token.expression.val;
3700
+ let modifier = null;
3701
+ const modifierMatch = MODIFIER_RE.exec(rawVal);
3702
+ if (modifierMatch) {
3703
+ modifier = modifierMatch[1];
3704
+ rawVal = rawVal.slice(0, modifierMatch.index);
3705
+ }
3706
+ const exp = parser.parseExp({ val: rawVal, loc: token.expression.loc });
3656
3707
  if (!exp) {
3657
3708
  return;
3658
3709
  }
3659
3710
  if (exp.type === 'WITH') {
3660
3711
  const { left, right } = exp;
3661
- yield new IncludeNode(left, token.loc, token.strip, right);
3712
+ yield new IncludeNode(left, token.loc, token.strip, right, modifier);
3662
3713
  return;
3663
3714
  }
3664
- yield new IncludeNode(exp, token.loc, token.strip);
3715
+ yield new IncludeNode(exp, token.loc, token.strip, null, modifier);
3665
3716
  }
3666
3717
  const parsers$8 = {
3667
3718
  include: parseInclude,
@@ -5679,10 +5730,12 @@ export default script;
5679
5730
  /** Raw lines inside a reindented body (`stylesheet` / `script` / `style`). */
5680
5731
  let bodyBuf = null;
5681
5732
  const out = [];
5733
+ /** Open `{{#` comment: inner lines are never scanned for pieces. */
5734
+ const state = { inComment: false };
5682
5735
  for (const line of lines) {
5683
5736
  const leading = line.match(/^[ \t]*/)?.[0].length ?? 0;
5684
5737
  const content = line.slice(leading);
5685
- const { pieces, prefixClosers } = scanLine(content, options);
5738
+ const { pieces, prefixClosers } = scanLine(content, options, state);
5686
5739
  const activeSensitive = sensitive;
5687
5740
  const closesSensitive = activeSensitive !== null &&
5688
5741
  pieces.some((piece) => piece.kind === 'close' && piece.sensitive === activeSensitive);
@@ -5738,16 +5791,35 @@ export default script;
5738
5791
  }
5739
5792
  }
5740
5793
  }
5741
- function scanLine(line, options) {
5794
+ function scanLine(line, options, state) {
5742
5795
  const pieces = [];
5743
5796
  let prefixClosers = 0;
5744
5797
  let atPrefix = true;
5745
5798
  let i = 0;
5799
+ if (state.inComment) {
5800
+ const close = line.indexOf(options.commentClose);
5801
+ if (close === -1) {
5802
+ return { pieces, prefixClosers };
5803
+ }
5804
+ state.inComment = false;
5805
+ i = close + options.commentClose.length;
5806
+ }
5746
5807
  while (i < line.length) {
5747
5808
  if (/\s/.test(line[i])) {
5748
5809
  i += 1;
5749
5810
  continue;
5750
5811
  }
5812
+ if (line.startsWith(options.commentOpen, i)) {
5813
+ const close = line.indexOf(options.commentClose, i + options.commentOpen.length);
5814
+ // Comment runs past this line; the rest is comment text
5815
+ if (close === -1) {
5816
+ state.inComment = true;
5817
+ return { pieces, prefixClosers };
5818
+ }
5819
+ atPrefix = false;
5820
+ i = close + options.commentClose.length;
5821
+ continue;
5822
+ }
5751
5823
  const next = readAt(line, i, options);
5752
5824
  if (!next) {
5753
5825
  // Plain text ends the leading-closer prefix
@@ -5774,12 +5846,7 @@ export default script;
5774
5846
  return { pieces, prefixClosers };
5775
5847
  }
5776
5848
  function readAt(line, i, options) {
5777
- const { commentOpen, directiveOpen, outputOpen } = options;
5778
- if (line.startsWith(commentOpen, i)) {
5779
- return {
5780
- end: endOfDelimited(line, i + commentOpen.length, options.commentClose),
5781
- };
5782
- }
5849
+ const { directiveOpen, outputOpen } = options;
5783
5850
  if (line.startsWith(outputOpen, i)) {
5784
5851
  return {
5785
5852
  end: endOfDelimited(line, i + outputOpen.length, options.outputClose),
package/dist/index.min.js CHANGED
@@ -1 +1 @@
1
- !function(e){"use strict";class t{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=new Map,this.maxSize=e.maxSize??1e3,this.ttl=e.ttl??36e5,this.stats={hits:0,misses:0,evictions:0}}get(e){const t=this.cache.get(e);return t?this.ttl>0&&Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),this.stats.misses++,null):(this.cache.delete(e),this.cache.set(e,t),t.hits++,this.stats.hits++,t.value):(this.stats.misses++,null)}peek(e){const t=this.cache.get(e);return!t||this.ttl>0&&Date.now()-t.timestamp>this.ttl?null:t.value}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){const e=this.cache.keys().next().value;void 0!==e&&(this.cache.delete(e),this.stats.evictions++)}this.cache.set(e,{value:t,timestamp:Date.now(),hits:0})}has(e){const t=this.cache.get(e);return!!t&&(!(this.ttl>0&&Date.now()-t.timestamp>this.ttl)||(this.cache.delete(e),!1))}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.stats={hits:0,misses:0,evictions:0}}invalidate(e){if(e)for(const t of this.cache.keys())e(t)&&this.cache.delete(t);else this.clear()}getStats(){return{...this.stats,size:this.cache.size,hitRate:this.stats.hits+this.stats.misses>0?this.stats.hits/(this.stats.hits+this.stats.misses):0}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}}function n(e,t,n){const i=[];if("ExpError"===e&&(t.includes("Unexpected end of expression")&&i.push({message:"The expression is incomplete. Make sure you have closed all parentheses, brackets, and quotes.",fix:"Check for missing closing characters: ), ], }"}),t.includes('Expected "RP" after "LP"')&&i.push({message:"Missing closing parenthesis in your expression.",fix:"Add a closing parenthesis ) to match the opening one.",example:"(foo.bar) instead of (foo.bar"}),t.includes("No left operand")&&i.push({message:"An operator is missing its left operand.",fix:"Add a value or variable before the operator.",example:"x + 1 instead of + 1"}),t.includes("No right operand")&&i.push({message:"An operator is missing its right operand.",fix:"Add a value or variable after the operator.",example:"x + 1 instead of x +"}),t.includes('Expected "ID" after "PIPE"')&&i.push({message:"The pipe operator | must be followed by a filter name.",fix:"Add a filter name after the pipe.",example:"value|upper instead of value|"}),t.includes('Expected "ID" after "DOT"')&&i.push({message:"The dot operator . must be followed by a property name.",fix:"Add a property name after the dot.",example:"object.property instead of object."}),t.includes("Left operand of assignment must be an identifier")&&i.push({message:"Assignment targets must be valid identifiers.",fix:"Use a simple variable name or sequence of variable names.",example:"x = 1 or (a, b) = [1, 2]"}),t.includes("Expected test expression")&&i.push({message:"The conditional expression is missing its test condition.",fix:"Add a condition after the if keyword.",example:"if x > 0 then y else z"}),t.includes("Expected alternative expression")&&i.push({message:"The conditional expression is missing its else clause.",fix:"Add an alternative expression after then.",example:"if x > 0 then y else z"}),t.startsWith("Unexpect")&&i.push({message:"An unexpected character was found in the expression.",fix:"Check for typos or invalid characters in your expression."})),"CompileError"===e){if(t.includes("Unclosed")){const e=t.match(/Unclosed "([^"]+)"/),n=e?e[1]:"marker";i.push({message:`The ${n} marker is not closed properly.`,fix:`Add the closing marker for ${n}.`,example:"{%"===n?"{% ... %}":"{#"===n?"{# ... #}":"{{ ... }}"})}t.includes("Unexpected")&&i.push({message:"An unexpected token was found in the template.",fix:"Check your template syntax and ensure all markers are properly formatted."})}return n&&i.push({message:"Context information:",fix:n}),i}class i extends SyntaxError{constructor(e,t,n,r){super(e),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:r}),this.name="CompileError",i.captureStackTrace?.(this,this.constructor)}get details(){const e=this.loc?function(e,t,{start:{line:n,column:i},end:{line:r,column:s}}){const o=[],a=new Set,l=e=>{a.add(e-2),a.add(e-1),a.add(e),a.add(e+1),a.add(e+2)},c=t.split("\n"),u=String(c.length).length+2;let p=0;c.forEach((e,t)=>{if(e){if(o.push(`${`${t+1}│ `.padStart(u," ")}${e}`),n===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(i-1)}^${n===r&&s>i+1?`${" ".repeat(s-i-2)}^`:""}`;/\S/.test(e)&&o.push(e),l(++p+t)}if(n!==r&&r===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(s-1)}${"^".repeat(1)}`;/\S/.test(e)&&o.push(e),l(++p+t)}}});const h=`${" ".repeat(u)}...`;return`${e}\n\n${o.map((e,t)=>a.has(t)?e:h).reduce((e,t)=>t===h&&e.at(-1)===t?e:[...e,t],[]).join("\n")}\n`}(this.message,this.src,this.loc):this.message;return function(e,t,i,r){const s=n(e,t,r);return 0===s.length?i:`${i}\n\nSuggestions:\n${s.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n")}`}(this.name,this.message,e,this.context)}get suggestions(){return n(this.name,this.message,this.context)}}const r=/[&<>"']/,s=/[&<>"']/g,o={"&":"&amp;",'"':"&#34;","'":"&#39;","<":"&lt;",">":"&gt;"},a=e=>o[e];function l(e){const t="string"==typeof e?e:`${e}`;return r.test(t)?t.replace(s,a):t}class c extends String{constructor(e){super(`${e}`)}}function u(e={}){return{maxIncludeDepth:e.maxIncludeDepth??100,maxLoopIterations:e.maxLoopIterations,maxCallDepth:e.maxCallDepth,timeoutMs:e.timeoutMs}}class p{constructor(e={}){Object.defineProperty(this,"allowedGlobals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cspNonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.allowedGlobals=new Set(e.allowedGlobals||[]),this.cspNonce=e.cspNonce}sanitizeGlobals(e){const t={};for(const[n,i]of Object.entries(e))this.allowedGlobals.has(n)&&(t[n]=i);return t}validateExpression(e){const t=[/\bprocess\b/,/\brequire\b/,/\bimport\b/,/\bexport\b/,/\beval\b/,/\bFunction\b/,/\b__proto__\b/,/\bconstructor\b/];for(const n of t)if(n.test(e))return!1;return!0}createSecureContext(e){return{...this.sanitizeGlobals(e),Math:Math,Date:Date,JSON:JSON}}getCSPNonce(){return this.cspNonce}generateCSPHeaders(){const e={};return this.cspNonce&&(e["Content-Security-Policy"]=`script-src 'nonce-${this.cspNonce}'`),e}}function h(e,t=new WeakSet){if(null==e)return"";if(e instanceof c)return`${e}`;if("object"==typeof e){if(t.has(e))return"";t.add(e);return(Array.isArray(e)?e:Object.values(e)).map(e=>h(e,t)).join("")}return l(e)}class f{auditTemplate(e){const t=[],n=[{pattern:/\beval\s*\(/,type:"dangerous-eval",message:"Use of eval() is dangerous and should be avoided",severity:"critical"},{pattern:/\bFunction\s*\(/,type:"dangerous-function",message:"Use of Function constructor is dangerous",severity:"critical"},{pattern:/\brequire\s*\(/,type:"require-usage",message:"Direct require() usage in templates is unsafe",severity:"high"},{pattern:/\bimport\s*\(/,type:"dynamic-import",message:"Dynamic import() usage in templates may be unsafe",severity:"high"}];for(const{pattern:i,type:r,message:s,severity:o}of n){const n=e.match(i);n&&t.push({type:r,message:s,location:`at index ${n.index}`,severity:o})}return{issues:t,severity:this.calculateOverallSeverity(t)}}calculateOverallSeverity(e){if(0===e.length)return"low";const t={critical:4,high:3,medium:2,low:1},n=Math.max(...e.map(e=>t[e.severity]));return Object.entries(t).find(([,e])=>e===n)[0]}}const d=new WeakMap;function b(e,t=!1){return t?`\0stream:${e}`:e}function m(e){let t=d.get(e);if(void 0===t){const{trimWhitespace:n,stripComments:i,commentOpen:r,commentClose:s,directiveOpen:o,directiveClose:a,outputOpen:l,outputClose:c,preloadIncludes:p}=e,{maxIncludeDepth:h,maxLoopIterations:f,maxCallDepth:b}=u(e.security);t=JSON.stringify([n,i,r,s,o,a,l,c,h,f??null,b??null,p]),d.set(e,t)}return t}const y="c",g="f",w="r_";class v{constructor(){Object.defineProperty(this,"mappings",{enumerable:!0,configurable:!0,writable:!0,value:[]})}addMapping(e,t){this.mappings.push({source:e,target:t})}getSourceLoc({line:e,column:t}){return this.mappings.filter(({target:{start:n,end:i}})=>n.line<=e&&i.line>=e&&(n.line<e||n.column<=t)&&(i.line>e||i.column>=t)).map(({source:e})=>e)}}class x extends v{constructor(){super(...arguments),Object.defineProperty(this,"codeParts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"codeLength",{enumerable:!0,configurable:!0,writable:!0,value:0})}get code(){return this.codeParts.join("")}set code(e){this.codeParts=[e],this.codeLength=e.length}get script(){return new Function(y,"e",g,"w",this.code)}checkpoint(){return[this.codeParts.length,this.mappings.length,this.codeLength]}rollback(e){const[t,n,i]=e;this.codeParts.length=t,this.mappings.length=n,this.codeLength=i}start(e=!0){this.pushRaw(null,"return(async()=>{",`let s="",${w};`),e&&this.pushRaw(null,"const u_=(n)=>{throw new Error('Unknown filter \"'+n+'\"')};")}end(){this.pushRaw(null,"return s;","})();")}pushRaw(e,...t){const n=this.codeLength;for(const e of t)this.codeParts.push(e),this.codeLength+=e.length;e&&this.addMapping(e,{start:{line:1,column:n},end:{line:1,column:this.codeLength}})}pushStr(e,t){t&&this.pushRaw(e,`s+=${JSON.stringify(t)};`)}pushFlush(){this.pushRaw(null,'if(s.length>1024){await w(s);s="";}')}pushVar(e,t){this.pushRaw(e,`s+=e(${t});`)}}class O extends x{constructor(){super(...arguments),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:y}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:[y]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0})}checkpoint(){return[super.checkpoint(),this.context,[...this.stack]]}rollback(e){const[t,n,i]=e;super.rollback(t),this.context=n,this.stack=i}in(){return this.context=`${this.context}_${this.index++}`,this.stack.push(this.context),this.context}out(){this.context!==y&&(this.stack.pop(),this.context=this.stack.at(-1))}}class E extends SyntaxError{constructor(e,t,n){super(e),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="ExpError",E.captureStackTrace?.(this,this.constructor)}get suggestions(){return n(this.name,this.message,this.context)}get details(){const{suggestions:e}=this;if(0===e.length)return this.message;const t=e.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n");return`${this.message}\n\nSuggestions:\n${t}`}}function P(e,t){const n=(e.match(/\n/g)||[]).length;if(n>0){t.line+=n;const i=e.lastIndexOf("\n");t.column=e.length-i}else t.column+=e.length;return{line:t.line,column:t.column}}const T={and:"AND",or:"OR",not:"NOT",is:"IS",eq:"EQ",ne:"NE",gt:"GT",lt:"LT",ge:"GE",le:"LE",in:"IN",ni:"NI",of:"OF",with:"WITH","+":"ADD","-":"SUB","*":"MUL","/":"DIV","%":"MOD",if:"IF",else:"ELSE",true:"LIT",false:"LIT",null:"LIT",undefined:"LIT","|":"PIPE","=":"ASSIGN","(":"LP",")":"RP",",":"COMMA",".":"DOT"},j=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(e){return"string"==typeof e&&j.has(e)}const k={n:"\n",t:"\t",r:"\r","\\":"\\",'"':'"',"'":"'","`":"`"};function S(e){switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return;default:return e}}class I{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}tokenize(e,t){for(this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=[];this.index<this.val.length;){const e=this.val[this.index];if(N(e))"\n"===e?(this.line++,this.column=1):this.column++,this.index++;else if("'"!==e&&'"'!==e&&"`"!==e)if(C(e)||"-"===e&&C(this.val[this.index+1]??"")&&!this.afterOperand())this.readNumber(e);else if(R(e))this.readIdentifier(e);else{if(!L(e))throw new E(`Unexpected "${e}"`,{start:{line:this.line,column:this.column},end:{line:this.line,column:this.column+1}});this.readSymbol(e)}else this.readString(e)}return this.tokens}afterOperand(){const e=this.tokens.at(-1)?.type;return"ID"===e||"LIT"===e||"RP"===e}readString(e){let t="",n="",i=!1;const r={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const r=this.val[this.index];if(i)t+=k[r]??`\\${r}`,n+=r,i=!1;else if("\\"===r)n+=r,i=!0;else{if(r===e)break;t+=r,n+=r}this.index++}this.index++,this.tokens.push({type:"LIT",value:t,loc:{start:r,end:P(`${e}${n}${e}`,this)},raw:`${e}${n}${e}`})}readNumber(e){let t=e,n=!1;const i={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(C(e))t+=e;else{if("."!==e||n)break;t+=e,n=!0}this.index++}this.tokens.push({type:"LIT",value:Number.parseFloat(t),loc:{start:i,end:P(t,this)},raw:t})}readIdentifier(e){let t=e;const n={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(!D(e))break;t+=e,this.index++}if($(t))throw new E(`"${t}" is not allowed in expressions`,{start:n,end:{line:this.line,column:this.column+t.length}});const i=Object.prototype.hasOwnProperty.call(T,t)?T[t]:"ID";this.tokens.push({type:i,value:"LIT"===i?S(t):t,loc:{start:n,end:P(t,this)},raw:t})}readSymbol(e){const t={line:this.line,column:this.column};this.index++,this.tokens.push({type:T[e],value:e,loc:{start:t,end:P(e,this)},raw:e})}}function N(e){return/\s/.test(e)}function L(e){return/[+\-*/%|=(),.]/.test(e)}function C(e){return/\d/.test(e)}function R(e){return/[a-z_$]/i.test(e)}function D(e){return/[\w$]/.test(e)}const A={COMMA:5,IF:10,ELSE:10,ASSIGN:15,LP:20,RP:20,OR:25,AND:30,IS:40,EQ:40,NE:40,GT:40,LT:40,GE:40,LE:40,IN:40,NI:40,OF:40,WITH:40,ADD:50,SUB:50,MUL:60,DIV:60,MOD:60,NOT:70,PIPE:80,DOT:90,ID:90,LIT:90};class M{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}parse(e,t){return this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=(new I).tokenize(e,t),this.val?this.parseExp():null}parseExp(e){let t=null;for(;;){const n=this.next();if(!n)break;const i=e?.(n);if("BACK"===i){this.back();break}if("BREAK"===i)break;if(t&&F(n),"LP"===n.type){if(!this.peek())throw new E("Unexpected end of expression",n.loc);const e=this.parseSequence(),i=this.consume("RP");if(!i)throw new E('Expected "RP" after "LP"',n.loc);t={...n,type:"SEQ",elements:e,loc:{start:n.loc.start,end:i.loc.end}};continue}if("NOT"!==n.type){if("ID"===n.type){t={...n,type:"ID",value:n.value},this.match("DOT")&&(t.path=this.parsePath());const e=this.consume("LP");if(e){if(t.args=this.parseSequence(),!this.consume("RP"))throw new E('Expected "RP" after "LP"',e.loc);continue}continue}if("LIT"!==n.type){if("IF"===n.type){const e=this.parseExp(e=>"ELSE"===e.type||X(n,e)?"BACK":void 0);if(!e)throw new E("Expected test expression",n.loc);if(t={...n,type:"IF",test:e,consequent:t},this.consume("ELSE")){const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E("Expected alternative expression",n.loc);t.alternative=e}continue}if(_(n.type)){if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);"ASSIGN"===n.type&&W(t,n);const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E(`No right operand for "${n.type}"`,n.loc);t={...n,type:n.type,left:t,right:e};continue}if("PIPE"!==n.type){this.back();break}if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);if(!this.match("ID"))throw new E('Expected "ID" after "PIPE"',n.loc);t={...n,type:"PIPE",left:t,right:this.parsePipe()}}else t={...n,type:"LIT"}}else{if(!this.peek())throw new E("Unexpected end of expression",n.loc);t={...n,type:"NOT",argument:this.parseExp(e=>X(n,e)?"BACK":void 0)}}}return t}parsePath(){const e=[];for(;;){const t=this.consume("DOT");if(!t)break;const n=this.next();if(!n)throw new E('Expected "ID" after "DOT"',t.loc);if("ID"!==n.type)throw new E('Expected "ID" after "DOT"',t.loc);e.push({...n,type:"ID",value:n.value})}return e}parseSequence(){const e=[];for(;!this.match("RP");){const t=this.parseExp(e=>"COMMA"===e.type?"BREAK":void 0);if(!t)break;e.push(t)}return e}parsePipe(){const e=this.next(),t={...e,type:"ID",value:e.value},n=this.consume("LP");if(n&&(t.args=this.parseSequence(),!this.consume("RP")))throw new E('Expected "RP" after "LP"',n.loc);return t}next(){return this.tokens[this.index++]??null}back(){return this.tokens[this.index--]}peek(){return this.tokens.at(this.index)??null}match(e){return this.peek()?.type===e}consume(e){if(this.match(e))return this.next()}}const U=new Set(["AND","OR","IS","EQ","NE","GT","LT","GE","LE","IN","NI","OF","WITH","ADD","SUB","MUL","DIV","MOD","ASSIGN"]);function _(e){return U.has(e)}function F(e){if("ID"===e.type||"LIT"===e.type||"LP"===e.type)throw new E(`Unexpected "${e.raw??e.value}"`,e.loc)}function W(e,t){if("SEQ"===e.type){if(e.elements.some(e=>"ID"!==e.type||e.path||e.args))throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}else if("ID"!==e.type||e.path||e.args)throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}function X(e,t){return"LP"!==t.type&&A[e.type]>A[t.type]}class G{constructor(){Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}traverse(e){this.body?.forEach(e)}}class z extends G{constructor(e,t){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEMPLATE"})}}var B;function q(e){return e.replace(/\\([{}])/g,"$1")}e.TokenType=void 0,(B=e.TokenType||(e.TokenType={})).TEXT="TEXT",B.OUTPUT="OUTPUT",B.DIRECTIVE="DIRECTIVE",B.COMMENT="COMMENT";class K{constructor(t){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenPatterns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"markerIndices",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1});const{commentOpen:n,commentClose:i,directiveOpen:r,directiveClose:s,outputOpen:o,outputClose:a}=this.options;this.tokenPatterns=[[e.TokenType.COMMENT,n,i],[e.TokenType.DIRECTIVE,r,s],[e.TokenType.OUTPUT,o,a]].sort(([,e],[,t])=>e.length>t.length?-1:1),this.markerIndices=new Map;for(const[,e]of this.tokenPatterns)e.length>0&&this.markerIndices.set(e[0],this.markerIndices.get(e[0])||0)}tokenize(e){for(this.template=e,this.length=e.length,this.index=0,this.line=1,this.column=1,this.tokens=[];this.index<this.length;)this.consumeSpecialTokens()||this.consumeTextToken();return this.tokens}consumeSpecialTokens(){return this.tokenPatterns.some(([t,n,r])=>{if(!this.lookahead(n))return!1;const s={line:this.line,column:this.column},o=this.template.indexOf(r,this.index+n.length);if(-1===o)throw new i(`Unclosed "${n}"`,this.template,{start:s,end:P(n,{...s})});const a=this.lookahead("-",n.length),l="-"===this.template[o-1],c=this.template.slice(this.index+n.length+ +a,o-+l),u=P(this.template.slice(this.index,this.index=o+r.length),this),p={type:t,val:q(c),strip:{before:a,after:l},loc:{start:s,end:u}};if(t===e.TokenType.DIRECTIVE){let e=0,t="";for(;e<c.length;){const n=c[e];if(/\S/.test(n))t+=n;else if(t)break;e++}Object.assign(p,{name:t,expression:e===c.length||/^\s*$/m.test(c.slice(e+1))?null:{val:c.slice(e+1),loc:{start:P(c.slice(0,e+1),P(`${n}${a?"-":""}`,{...s})),end:{line:this.line,column:this.column-r.length-+l}}}})}return this.tokens.push(p),!0})}consumeTextToken(){const t=this.findNextSpecialIndex(),n={line:this.line,column:this.column},i=this.template.slice(this.index,t);this.tokens.push({type:e.TokenType.TEXT,val:q(i),loc:{start:n,end:P(i,this)},strip:{}}),this.index=t}lookahead(e,t=0){return this.template.startsWith(e,this.index+t)}findNextSpecialIndex(){const{outputOpen:e,directiveOpen:t,commentOpen:n}=this.options;let i=this.length;for(let r=this.index;r<this.length;r++){if(this.template.startsWith(n,r)){i=r;break}if(this.template.startsWith(t,r)){i=r;break}if(this.template.startsWith(e,r)){i=r;break}}return i}}class H extends K{constructor(){super(...arguments),Object.defineProperty(this,"expParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}parse(t){this.tokenize(t),this.tokens.forEach((t,n)=>{t.type===e.TokenType.TEXT&&(this.tokens[n-1]?.strip?.after&&(t.strip.start=!0),this.tokens[n+1]?.strip?.before&&(t.strip.end=!0))});const n=this.tokens[0]?.loc.start??{line:1,column:1},i=this.tokens.at(-1)?.loc.end??{line:1,column:1};return this.expParser=new M,this.cursor=0,new z(this.parseUntil(),{start:n,end:i})}parseUntil(t){const n=[];let i=null;for(;;){const r=this.peek();if(!r||r.type===e.TokenType.DIRECTIVE&&t&&this.match(t,r))break;i?.strip?.after&&r.type===e.TokenType.TEXT&&(r.strip.start=!0),r.strip?.before&&i?.type===e.TokenType.TEXT&&(i.strip.end=!0);let s=this.options.parsers[r.name?.toLowerCase()??r.type?.toLowerCase()];"string"==typeof s&&(s=this.options.parsers[s]),s||(s=this.options.parsers.unknown);const{cursor:o}=this,a=s?.(r,this);if(a)for(;;){const{value:e,done:t}=a.next();if(t)break;"NEXT"===e?this.advance():e&&n.push(e)}this.cursor===o&&this.advance(),i=r}return n}parseExp({val:e,loc:t}){try{return this.expParser.parse(e,t)}catch(e){this.options.debug(e.loc?new i(e.message,this.template,e.loc):e)}}peek(){return this.tokens.at(this.cursor)??null}advance(){this.cursor++}match(e,t=this.peek()){return e.includes(t?.name?.toLowerCase())}emitExpErr({name:e,loc:t},n=!0){this.options.debug(new i(n?`"${e}" requires expression`:`"${e}" should not have expression`,this.template,t))}}function J(e){return"LIT"===e.type&&"string"==typeof e.value}class V extends G{constructor(e,t,n,i=null){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"withExp",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"INCLUDE"})}}const Q={start:{line:1,column:1},end:{line:1,column:1}},Y=new Set(["IF","FOR"]);class Z extends O{constructor(e,t,n=!0,i=!1){super(),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"revalidate",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isRoot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rootNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partials",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheets",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheetKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sources",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hasDynamicInclude",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"flushable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.cache=t}async compile(e,t=!0,n=new Map,i=new Map,r=new Map,s=new Map,o="\0root"){this.template=e,this.isRoot=t,this.partials=n,this.blocks=i,this.stylesheets=s,this.stylesheetKey=o,this.sources=r,this.hasDynamicInclude=!1;const a=this.generateCacheKey(e);if(this.cache&&t){const e=this.cache.get(a);if(e){if(e.fingerprint===this.fingerprint()&&await this.isFresh(e))return this.code=e.code,this.mappings=e.mappings,this.compiled=e,this;this.cache.delete(a)}}if(this.rootNode=new H(this.options).parse(e),this.state={},this.start(this.isRoot),this.isRoot&&(this.pushResourceLimitCounters(),this.pushRaw(null,"let ss_u=0;")),await this.parseTemplates(),this.isRoot){if(this.partials.size||this.hasDynamicInclude){const{maxIncludeDepth:e}=u(this.options.security);this.pushRaw(null,`const tc_=${y};`,"let d_=0;","const p={");for(const[t,n]of this.partials)this.pushRaw(null,`${JSON.stringify(t)}:async(c)=>{`,`if(d_>=${e})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(t)} are nested too deeply`)});`,"d_++;","try{return await(async()=>{",n,"})();}finally{d_--;}","},");this.pushRaw(null,"};")}if(this.blocks.size){this.pushRaw(null,"const b={");for(const[e,t]of this.blocks){this.pushRaw(null,`${JSON.stringify(e)}:{`,"u:0,","s:["),this.state.block=e;for(const e of t)this.pushRaw(null,"async()=>{",'let s="";'),await this.compileNodes(e.body),this.pushRaw(null,"return s;","},");this.state.block=void 0,this.pushRaw(null,"],","},")}this.pushRaw(null,"};")}this.pushRaw(null,"const ss_=[");for(const[,e]of this.stylesheets){this.pushRaw(null,"async()=>{",'let s="";');for(const t of e)await this.compileNodes(t.body);this.pushRaw(null,"return s;","},")}this.pushRaw(null,"];")}return this.flushable=this.isRoot&&this.stream,await this.compileNode(this.rootNode),this.flushable=!1,this.end(),this.cache&&t&&(this.compiled={code:this.code,mappings:this.mappings,sources:this.sources,fingerprint:this.fingerprint()},this.cache.set(a,this.compiled)),this}get script(){var e;return this.compiled?(e=this.compiled).script??(e.script=super.script):super.script}generateCacheKey(e){return b(e,this.stream)}fingerprint(){return m(this.options)}pushResourceLimitCounters(){const{maxLoopIterations:e,maxCallDepth:t}=u(this.options.security);null!=e&&this.pushRaw(null,"let li_=0;"),null!=t&&this.pushRaw(null,"let cd_=0;")}async isFresh({sources:e}){if(!this.revalidate)return!0;try{for(const[t,n]of e)if(await this.options.loader(t)!==n)return!1}catch{return!1}return!0}async parseTemplates(){const{partials:e,blocks:t,stylesheets:n}=this.collectPartialsAndBlocks();if(this.isRoot)for(const t of this.options.preloadIncludes)e.has(t)||e.set(t,new V({type:"LIT",value:t,loc:Q},Q,{before:!1,after:!1}));for(const[t,n]of e)if(!this.partials.has(t)){let e;try{e=await this.options.loader(t)}catch{throw new i(`Failed to load template from "${t}"`,this.template,n.loc)}this.sources.set(t,e??""),this.partials.set(t,""),e&&await this.compilePartial(t,n,e)}for(const e of t){const{val:{value:t}}=e;this.blocks.has(t)||this.blocks.set(t,[]),this.blocks.get(t).push(e)}n.length&&!this.stylesheets.has(this.stylesheetKey)&&this.stylesheets.set(this.stylesheetKey,n)}collectPartialsAndBlocks(){const e=new Map,t=[],n=[],i=r=>{if("INCLUDE"===r.type){const t=r;J(t.val)?e.has(t.val.value)||e.set(t.val.value,t):this.hasDynamicInclude=!0}"BLOCK"===r.type&&t.push(r),"STYLESHEET"===r.type&&n.push(r),r.traverse(i)};return i(this.rootNode),{partials:e,blocks:t,stylesheets:n}}async compileNode(e){if("TEMPLATE"===e.type){for(const t of e.body)await this.compileNode(t),this.flushable&&"TEXT"!==t.type&&this.pushFlush();return}let t=this.options.compilers[e.type];"string"==typeof t&&(t=this.options.compilers[t]),t||(t=this.options.compilers.UNKNOWN);const n=this.checkpoint(),{flushable:r}=this;Y.has(e.type)||(this.flushable=!1);try{await(t?.(e,this))}catch(t){if(this.flushable=r,"CompileError"===t?.name)throw t;this.rollback(n),this.options.debug(new i(`Invalid "${e.type.toLowerCase()}" directive`,this.template,e.loc))}this.flushable=r}async compileNodes(e){for(const t of e)await this.compileNode(t)}async compilePartial(e,t,n){try{const{code:t}=await new Z(this.options).compile(n,!1,this.partials,this.blocks,this.sources,this.stylesheets,e);this.partials.set(e,t)}catch{this.options.debug(new i("Failed to compile template",this.template,t.loc))}}}var ee=Object.freeze({__proto__:null,abs:function(e=0){return Math.abs(e)},add:function(e=0,t=0){return e+t},capitalize:function(e=""){return e.replace(/\b\w/g,e=>e.toUpperCase())},ceil:function(e=0){return Math.ceil(e)},chunk:function(e,t){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},compact:function(e=[]){return e.filter(e=>null!=e)},currency:function(e,t="USD",n="en-US"){return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(e)},date:function(e,t="ISO"){const n=e instanceof Date?e:new Date(e);if(isNaN(n.getTime()))return"";switch(t){case"ISO":default:return n.toISOString();case"date":return n.toISOString().split("T")[0];case"time":return n.toTimeString().split(" ")[0];case"locale":return n.toLocaleDateString();case"locale-time":return n.toLocaleTimeString();case"locale-datetime":return n.toLocaleString()}},defaults:function(e,t){return{...t,...e}},delay:async function(e,t){return await new Promise(e=>setTimeout(e,t)),e},div:function(e=0,t=1){return e/t},entries:function(e={}){return Object.entries(e)},escape:l,even:function(e=0){return+e%2==0},fallback:function(e,t,n=!1){return n?e||t:e??t},fetchUrl:async function(e,t={}){return(await fetch(e,t)).text()},first:function(e=[]){return[...e][0]},fixed:function(e,t=2){return Number(e).toFixed(t)},get:function(e,...t){return t.reduce((e,t)=>e&&"object"==typeof e&&!$(t)&&t in e?e[t]:void 0,e)},groupby:function(e=[],t){return e.reduce((e,n)=>{const i=n[t];return{...e,[i]:[...e[i]||[],n]}},{})},invert:function(e){return Object.entries(e).reduce((e,[t,n])=>({...e,[String(n)]:t}),{})},join:function(e=[],t=""){return[...e].join(t)},json:function(e=null,t=0){return new c(JSON.stringify(e,null,t))},keys:function(e={}){return Object.keys(e)},last:function(e=[]){return[...e].reverse()[0]},length:function(e=""){return e.length},lower:function(e=""){return e.toLowerCase()},map:function(e=[],t,n){return e.map(e=>$(t)?n:e[t]??n)},max:function(e=0,...t){return Math.max(e,...t)},merge:function(e,...t){return Object.assign({},e,...t)},min:function(e=0,...t){return Math.min(e,...t)},mul:function(e=0,t=1){return e*t},odd:function(e=0){return+e%2==1},omit:function(e={},...t){return Object.entries(e).reduce((e,[n,i])=>t.includes(n)?e:{...e,[n]:i},{})},percent:function(e,t=0){return`${(100*e).toFixed(t)}%`},pick:function(e={},...t){return t.reduce((t,n)=>$(n)?t:{...t,[n]:e[n]},{})},pluck:function(e,t){return e.map(e=>e[t])},repeat:function(e="",t=0){return e.repeat(t)},replace:function(e="",t,n){return e.replace(new RegExp(t,"g"),n)},reverse:function(e=[]){return Array.isArray(e)?[...e].reverse():[...e].reverse().join("")},round:function(e,t=0){return Number(`${Math.round(Number(`${e}e${t}`))}e-${t}`)},safe:function(e=""){return new c(e)},shuffle:function(e){const t=[...e];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t},slice:function(e="",t=0,n){return e.slice(t,n)},slugify:function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")},sort:function(e=[]){return Array.isArray(e)?[...e].sort():[...e].sort().join("")},split:function(e="",t=""){return e.split(t)},stripTags:function(e){return e.replace(/<[^>]*>/g,"")},sub:function(e=0,t=0){return e-t},sum:function(e=[]){return e.reduce((e,t)=>e+t,0)},timeAgo:function(e){const t=e instanceof Date?e:new Date(e),n=new Date,i=Math.floor((n.getTime()-t.getTime())/1e3),r=[{label:"year",seconds:31536e3},{label:"month",seconds:2592e3},{label:"day",seconds:86400},{label:"hour",seconds:3600},{label:"minute",seconds:60}];for(const e of r){const t=Math.floor(i/e.seconds);if(t>=1)return`${t} ${e.label}${t>1?"s":""} ago`}return"just now"},trim:function(e=""){return e.trim()},truncate:function(e="",t=0,n="..."){return e.slice(0,t)+(e.length>t?n:"")},unique:function(e=""){return Array.isArray(e)?Array.from(new Set(e)):Array.from(new Set(e)).join("")},upper:function(e=""){return e.toUpperCase()},urldecode:function(e=""){return decodeURIComponent(e)},urlencode:function(e=""){return encodeURIComponent(e)},values:function(e={}){return Object.values(e)},wordCount:function(e){return e.trim().split(/\s+/).filter(Boolean).length}});const te={filters:{},parsers:{},compilers:{},plugins:[],debug:e=>{throw e}},ne={...te,commentOpen:"{{#",commentClose:"#}}",directiveOpen:"{{",directiveClose:"}}",outputOpen:"{{=",outputClose:"}}"},ie={...ne,trimWhitespace:!1,stripComments:!1,loader:async()=>"",preloadIncludes:[]},re={...ie,globals:{},autoEscape:!0,cache:{enabled:!0,maxSize:1e3,ttl:36e5,revalidate:!0},security:{}},se=(e,...t)=>{const n={...e},i=e=>{n.filters={...n.filters,...e.filters},n.parsers={...n.parsers,...e.parsers},n.compilers={...n.compilers,...e.compilers}};return e.plugins?.forEach(i),t.forEach(({plugins:e,filters:t,parsers:r,compilers:s,...o})=>{for(const[e,t]of Object.entries(o))void 0!==t&&(n[e]=t);i({filters:t,parsers:r,compilers:s}),e?.forEach(i)}),n};const oe={BLOCK:async function({val:{value:e},loc:t},n){const i=JSON.stringify(e);n.pushRaw(t,`if(b[${i}]&&!(b[${i}].u++)){`,`s+=await b[${i}].s?.pop()?.()??"";`,"}")},SUPER:async function({loc:e},t){t.state.block?t.pushRaw(e,`s+=await b[${JSON.stringify(t.state.block)}]?.s?.pop()?.()??"";`):t.options.debug?.(new i('"super" should be used inside a block',t.template,e))}};class ae extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BLOCK"})}}class le extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SUPER"})}}const ce={compilers:oe,parsers:{block:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endblock"]);t.match(["endblock"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ae(t.parseExp(e.expression),n,e.loc,e.strip)},super:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new le(e.val,e.loc,e.strip))},endblock:"unexpected"}},ue={AND:"&&",OR:"||",IS:"",NOT:"!",EQ:"===",NE:"!==",GT:">",LT:"<",GE:">=",LE:"<=",IN:" in ",NI:" in ",OF:" of ",WITH:" with ",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",ID:"",LIT:"",IF:"",ELSE:""},pe=new Set(Object.getOwnPropertyNames(Object.prototype));class he{constructor(){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}compile(e,t=y,n=g){return this.context=t,this.filters=n,e?this.compileExp(e):'""'}compileExp(e){switch(e.type){case"NOT":return this.compileNot(e);case"ID":return this.compileId(e);case"LIT":return this.compileLit(e);case"PIPE":return this.compilePipe(e);case"ASSIGN":return this.compileAssign(e);case"IS":return this.compileIs(e);case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.compileBinary(e);case"IF":return this.compileTernary(e);case"SEQ":return this.compileSeq(e);default:return""}}compileNot({argument:e}){return`!${this.compileExp(e)}`}compileId({value:e,path:t,args:n}){let i=pe.has(e)?`(Object.hasOwn(${this.context},"${e}")?${this.context}.${e}:undefined)`:`${this.context}.${e}`;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=`(${this.compileArgs(n).join(",")})`),i}compileArgs(e){const t=[],n=[];for(const i of e)if("ASSIGN"===i.type){const{left:e,right:t}=i;n.push(`${e.value}:${this.compileExp(t)}`)}else t.push(this.compileExp(i));return n.length&&t.push(`{${n.join(",")}}`),t}compileLit({value:e}){return void 0===e?"undefined":"number"==typeof e&&e<0?`(${e})`:JSON.stringify(e)}compileSeq({elements:e}){return`(${e.map(e=>this.compileExp(e)).join(",")})`}compilePipe({left:e,right:t}){const{value:n,args:i=[]}=t,r=`(${this.filters}.${n}||u_("${n}")).call(${[this.context,this.compileExp(e),...this.compileArgs(i)].join(",")})`;return`(${w}=${r},${w} instanceof Promise?await ${w}:${w})`}compileAssign({left:e,right:t}){return"ID"===e.type?`Object.assign(${this.context},{${e.value}:${this.compileExp(t)}});`:`Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(t)},${e.elements.map(({value:e})=>`"${e}"`).join(",")}));`}compileIs({left:e,right:t}){return`typeof ${this.compileExp(e)}===${this.compileExp(t)}`}compileBinary({type:e,left:t,right:n}){const i=`${this.compileExp(t)}${ue[e]}${this.compileExp(n)}`;return"NI"===e?`!(${i})`:i}compileTernary({test:e,consequent:t,alternative:n}){return`${this.compileExp(e)}?${this.compileExp(t)}:${n?this.compileExp(n):'""'}`}}const fe={CALL:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`s+=await ${(new he).compile(e,i.context)}(async()=>{`,'let s="";'),await i.compileNodes(t),i.pushRaw(null,"return s;",'})??"";')}};class de extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALL"})}}const be={compilers:fe,parsers:{call:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcall"]);t.match(["endcall"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new de(t.parseExp(e.expression),n,e.loc,e.strip)},endcall:"unexpected"}};const me={CAPTURE:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`${i.context}.${e.value}=${g}.safe.call(${i.context},await(async(s)=>{`),await i.compileNodes(t),i.pushRaw(null,'return s;})(""));')}};class ye extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CAPTURE"})}}const ge={compilers:me,parsers:{capture:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcapture"]);t.match(["endcapture"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ye(t.parseExp(e.expression),n,e.loc,e.strip)},endcapture:"unexpected"}};const we={COMMENT:async function({val:e,loc:t},n){n.options.stripComments||n.pushStr(t,`\x3c!--${e}--\x3e`)}};class ve extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"COMMENT"})}}const xe={compilers:we,parsers:{comment:function*({val:e,loc:t,strip:n}){yield"NEXT",yield new ve(e,t,n)}}},Oe="loop:{first:i_===0,index:i_++,last:i_===n_}";function Ee(e,t=new Set){return!(!e||"object"!=typeof e||t.has(e))&&(t.add(e),"ASSIGN"===e.type||Object.entries(e).some(([e,n])=>"args"===e&&Array.isArray(n)?n.some(e=>Ee("ASSIGN"===e.type?e.right:e,t)):Ee(n,t)))}function Pe(e){return e.every(e=>{switch(e.type){case"TEXT":case"COMMENT":case"BREAK":case"CONTINUE":return!0;case"OUTPUT":return!Ee(e.val);case"IF":return!Ee(e.test)&&Pe(e.body)&&e.alternatives.every(e=>!Ee(e.test)&&Pe(e.body));case"FOR":return!Ee(e.loop.right)&&Pe(e.alternative?.body??[]);default:return!1}})}const Te={FOR:async function({loop:{left:e,right:t,loc:n},body:i,alternative:r},s){const{context:o}=s,a=new he;s.pushRaw(n,"{",`const t_=${a.compile(t,o)},`,"a_=Array.isArray(t_)?t_:Array.from(t_??[]),n_=a_.length;"),r&&(s.pushRaw(n,"if(!n_){"),await s.compileNodes(r.body),s.pushRaw(n,"}else{"));const l="SEQ"===e.type?e.elements.map(e=>"ASSIGN"===e.type?[e.left.value,`v_.${e.left.value}===undefined?${a.compile(e.right,o)}:v_.${e.left.value}`]:[e.value,`v_.${e.value}`]):[[e.value,"v_"]],c=s.in();s.pushRaw(n,"let i_=0;");const{maxLoopIterations:p}=u(s.options.security),h=null==p?[]:[`if(++li_>${p})throw new Error(${JSON.stringify(`Loop iteration limit of ${p} exceeded`)});`];Pe(i)?s.pushRaw(n,`const ${c}={...${o}};`,"for(const v_ of a_){",...h,`${c}.loop={${Oe.slice(6)};`,...l.map(([e,t])=>`${c}.${e}=${t};`)):s.pushRaw(n,"for(const v_ of a_){",...h,`const ${c}={`,`...${o},`,`${Oe},`,...l.map(([e,t])=>`${e}:${t},`),"};"),await s.compileNodes(i),s.out(),s.flushable&&s.pushFlush(),s.pushRaw(null,r?"}}}":"}}")},BREAK:function({loc:e},t){t.pushRaw(e,"break;")},CONTINUE:function({loc:e},t){t.pushRaw(e,"continue;")}};class je extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternative",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"FOR"})}traverse(e){this.body.forEach(e),this.alternative?.body.forEach(e)}}let $e=class extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}};class ke extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BREAK"})}}class Se extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CONTINUE"})}}const Ie=new WeakMap;const Ne={for:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Ie.set(t,!0),yield"NEXT";const n=t.parseUntil(["else","endfor"]);Ie.set(t,!1);let r=null;if(t.match(["else"])){const e=function*(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endfor"]);yield"NEXT",yield new $e(t.parseUntil(["endfor"]),e.loc,e.strip)}(t.peek(),t);for(;;){const{value:t,done:n}=e.next();if(n)break;if(t){if("NEXT"===t){yield"NEXT";continue}r=t}}}t.match(["endfor"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const s=t.parseExp(e.expression);"OF"===s?.type?yield new je(s,n,r,e.loc,e.strip):s&&t.options.debug?.(new i(`"${e.name}" expects "item of items"`,t.template,e.loc))},break:function*(e,t){e.expression?t.emitExpErr(e,!1):Ie.get(t)?(yield"NEXT",yield new ke(e.val,e.loc,e.strip)):t.options.debug?.(new i('"break" directive used outside of a loop',t.template,e.loc))},continue:function*(e,t){e.expression?t.emitExpErr(e,!1):Ie.get(t)?(yield"NEXT",yield new Se(e.val,e.loc,e.strip)):t.options.debug?.(new i('"continue" directive used outside of a loop',t.template,e.loc))},endfor:"unexpected"},Le={compilers:Te,parsers:Ne};const Ce={IF:async function({test:e,body:t,alternatives:n},i){i.pushRaw(e.loc,`if(${(new he).compile(e,i.context)}){`),await i.compileNodes(t),i.pushRaw(null,"}");for(const e of n)"ELSE_IF"===e.type?i.pushRaw(e.test.loc,`else if(${(new he).compile(e.test,i.context)}){`):i.pushRaw(null,"else{"),await i.compileNodes(e.body),i.pushRaw(null,"}")}};class Re extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternatives",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"IF"})}traverse(e){this.body?.forEach(e),this.alternatives?.forEach(t=>t.body?.forEach(e))}}class De extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE_IF"})}}class Ae extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}}function*Me(e,t){if(!e.expression)return t.emitExpErr(e),yield"NEXT",void t.parseUntil(["else","elseif","elsif","elif","endif"]);yield"NEXT",yield new De(t.parseExp(e.expression),t.parseUntil(["else","elseif","elsif","elif","endif"]),e.loc,e.strip)}function*Ue(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endif"]);yield"NEXT",yield new Ae(t.parseUntil(["endif"]),e.loc,e.strip)}const _e={compilers:Ce,parsers:{if:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["else","elseif","elsif","elif","endif"]),r=[];for(;t.match(["else","elseif","elsif","elif"]);){const e=t.peek();if("else"===e.name.toLowerCase()){const n=Ue(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}else{const n=Me(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}}t.match(["endif"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new Re(t.parseExp(e.expression),n,r,e.loc,e.strip)},elseif:"unexpected",elsif:"unexpected",elif:"unexpected",endif:"unexpected"}};const Fe={compilers:{INCLUDE:async function({val:e,loc:t,withExp:n},i){const r=new he,s=J(e)?JSON.stringify(e.value):r.compile(e,i.context);if(n){const e=`{...${i.context},...${r.compile(n,i.context)}}`;return void i.pushRaw(t,`s+=await p[${s}]?.(${e})??"";`)}i.pushRaw(t,`s+=await p[${s}]?.(tc_)??"";`)}},parsers:{include:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseExp(e.expression);if(n){if("WITH"===n.type){const{left:t,right:i}=n;return void(yield new V(t,e.loc,e.strip,i))}yield new V(n,e.loc,e.strip)}}}};const We={MACRO:async function({val:{value:e,args:t},loc:n,body:i},r){const{context:s}=r,o=new he,{maxCallDepth:a}=u(r.options.security);r.pushRaw(n,`${s}.${e}=(...a_)=>async(_c)=>{`,...null==a?[]:[`if(cd_>=${a})throw new Error(${JSON.stringify(`Macro call depth limit of ${a} exceeded`)});`,"cd_++;","try{"],'let s="";',`const ${r.in()}={`,`...${s},`,...(t??[]).map((e,t)=>"ASSIGN"===e.type?`${e.left.value}:a_[${t}]===undefined?${o.compile(e.right)}:a_[${t}],`:`${e.value}:a_[${t}],`),"};"),await r.compileNodes(i),r.out(),r.pushRaw(null,"return s;",...null==a?[]:["}finally{cd_--;}"],"};")},CALLER:function({loc:e},t){t.pushRaw(e,'s+=await _c?.()??"";')}};class Xe extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"MACRO"})}}class Ge extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALLER"})}}const ze=new WeakMap;const Be={compilers:We,parsers:{macro:function*(e,t){if(!e.expression)return void t.emitExpErr(e);ze.set(t,!0),yield"NEXT";const n=t.parseUntil(["endmacro"]);ze.set(t,!1),t.match(["endmacro"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const r=t.parseExp(e.expression);if("ID"===r.type){if(r.args?.length)for(const n of r.args)if("ASSIGN"===n.type){if("ID"!==n.left.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc))}else if("ID"!==n.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc));yield new Xe(r,n,e.loc,e.strip)}else t.options.debug?.(new i("Invalid macro definition",t.template,e.loc))},caller:function*(e,t){e.expression?t.emitExpErr(e,!1):ze.get(t)?(yield"NEXT",yield new Ge(e.val,e.loc,e.strip)):t.options.debug?.(new i('"caller" directive used outside of a macro',t.template,e.loc))},endmacro:"unexpected"}};const qe={OUTPUT:async function({val:e},t){t.pushVar(e.loc,(new he).compile(e,t.context))}};class Ke extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"OUTPUT"})}}const He={compilers:qe,parsers:{output:function*(e,t){yield"NEXT";const n=P(`${t.options.outputOpen}${e.strip.before?"-":""}`,{...e.loc.start});yield new Ke(t.parseExp({val:e.val,loc:{start:n,end:e.loc.end}}),e.loc,e.strip)}}};const Je={SET:async function({val:e,loc:t},n){n.pushRaw(t,(new he).compile(e,n.context))}};class Ve extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SET"})}}const Qe={compilers:Je,parsers:{set:function*(e,t){e.expression?(yield"NEXT",yield new Ve(t.parseExp(e.expression),e.loc,e.strip)):t.emitExpErr(e)}}};const Ye={STYLESHEET:async function(){},STYLESHEETS:async function({loc:e},t){t.pushRaw(e,"if(!ss_u++){","for(const f_ of ss_)s+=await f_();","}")}};class Ze extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEET"})}}class et extends G{constructor(e,t){super(),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEETS"})}}const tt={compilers:Ye,parsers:{stylesheet:function*(e,t){if(e.expression)return void t.emitExpErr(e,!1);yield"NEXT";const n=t.parseUntil(["endstylesheet"]);t.match(["endstylesheet"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new Ze(n,e.loc,e.strip)},endstylesheet:"unexpected",stylesheets:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new et(e.loc,e.strip))}}};const nt={TEXT:async function({val:e,loc:t,strip:{start:n,end:i}},r){(n||r.options.trimWhitespace)&&(e=e.replace(/^\s+/,"")),(i||r.options.trimWhitespace)&&(e=e.replace(/\s+$/,"")),r.pushStr(t,e)}};class it extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEXT"})}}const rt={compilers:nt,parsers:{text:function*(e){yield"NEXT",yield new it(e.val,e.loc,e.strip)}}};const st={UNEXPECTED:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unexpected "${e}"--\x3e`)}};class ot extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNEXPECTED"})}}const at={compilers:st,parsers:{unexpected:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unexpected "${n}"`,t.template,e.loc)),yield"NEXT",yield new ot(n,e.val,e.loc,e.strip)}}};const lt={UNKNOWN:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unknown "${e}"--\x3e`)}};class ct extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNKNOWN"})}}const ut={compilers:lt,parsers:{unknown:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unknown "${n}"`,t.template,e.loc)),yield"NEXT",yield new ct(n,e.val,e.loc,e.strip)}}};const pt={WITH:async function(e,t){const{context:n}=t,i=new he;t.pushRaw(e.loc,`const ${t.in()}={...${i.compile(e.expression,n)}};`),await t.compileNodes(e.body),t.out()}};class ht extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"expression",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"WITH"})}traverse(e){this.body?.forEach(e)}}const ft=[ce,be,xe,ge,Le,_e,Fe,Be,Qe,tt,rt,He,at,ut,{parsers:{with:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endwith"]);t.match(["endwith"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ht(t.parseExp(e.expression),n,e.loc,e.strip)},endwith:"unexpected"},compilers:pt}];class dt extends i{constructor(e,t,n,i){super(e,t,void 0,i),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"getLoc",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="RenderError",dt.captureStackTrace?.(this,this.constructor)}get details(){return this.loc=this.getLoc(),super.details}}const bt=new Error("Stream cancelled");class mt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sandbox",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"escape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiling",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.options=se(re,{filters:ee,plugins:ft},e),this.filters=Object.assign(Object.create(null),this.options.filters);const n=this.options.security?.deepEscape?h:l,{autoEscape:i}=this.options;this.escape=e=>"string"==typeof e?i?l(e):e:null==e?"":e instanceof c?`${e}`:i?n(e):e,!1!==this.options.cache?.enabled&&(this.cache=new t(this.options.cache)),this.options.security?.sandbox&&(this.sandbox=new p(this.options.security))}async render(e,t){const n=this.cache?.peek(b(e));if(n?.script&&0===n.sources.size&&n.fingerprint===m(this.options)){this.cache.get(b(e));try{return await this.run(n.script,t)}catch(t){const i=new v;return i.mappings=n.mappings,this.options.debug(this.wrapError(t,e,i)),""}}let i;try{return i=await this.compile(e),await this.run(i.script,t)}catch(t){this.options.debug(this.wrapError(t,e,i??new v))}return""}template(e){return t=>this.render(e,t)}async renderCompiled(e,t={}){try{return await this.run(e,t)}catch(e){this.options.debug(e)}return""}renderStream(e,t={}){let n,i=!1;return new ReadableStream({start:r=>{const s=e=>{if(i)throw bt;if(r.enqueue(e),(r.desiredSize??1)<=0)return new Promise(e=>{n=e})};let o;(async()=>{try{o=await this.compile(e,!0);const n=await this.run(o.script,t,s);n&&!i&&r.enqueue(n),r.close()}catch(t){if(t===bt)return;try{this.options.debug(this.wrapError(t,e,o??new v)),r.close()}catch(e){r.error(e)}}})()},pull:()=>{n?.(),n=void 0},cancel:()=>{i=!0,n?.()}})}compile(e,t=!1){const n=b(e,t);let i=this.compiling.get(n);return i||(i=new Z(this.options,this.cache,this.options.cache?.revalidate??!0,t).compile(e).finally(()=>this.compiling.delete(n)),this.compiling.set(n,i)),i}wrapError(e,t,n){return"CompileError"===e?.name?e:new dt(`${e?.message??e}`,t,()=>{const t=e?.stack?.match(/<anonymous>:(\d+):(\d+)\)/);if(!t)return e?.stack??"";const[i]=n.getSourceLoc({line:+t[1]-2,column:+t[2]});return i})}run(e,t,n){const i=e(this.sandbox?{...this.sandbox.createSecureContext(this.options.globals),...t}:{...this.options.globals,...t},this.escape,this.filters,n),{timeoutMs:r}=this.options.security??{};if(null==r)return i;let s;return Promise.race([Promise.resolve(i).finally(()=>{clearTimeout(s)}),new Promise((e,t)=>{s=setTimeout(()=>{t(new Error(`Render timed out after ${r}ms`))},r)})])}async renderFile(e,t){return this.render(await this.options.loader(e),t)}clearCache(){this.cache?.clear()}invalidateCache(e){this.cache?.invalidate(e)}getCacheStats(){return this.cache?this.cache.getStats():null}resetCacheStats(){this.cache?.resetStats()}auditTemplate(e){return(new f).auditTemplate(e)}getCSPHeaders(){return new p(this.options.security).generateCSPHeaders()}}class yt{constructor(e){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"variables",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"includes",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"macros",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}async analyze(e,t=new Set){const n=new H(this.options).parse(e);await this.nodes(n.body,t)}async nodes(e=[],t){for(const n of e)await this.node(n,t)}async node(e,t){switch(e.type){case"OUTPUT":this.exp(e.val,t);break;case"IF":this.exp(e.test,t),await this.nodes(e.body,t);for(const n of e.alternatives)this.exp(n.test,t),await this.nodes(n.body,t);break;case"FOR":{this.exp(e.loop.right,t),await this.nodes(e.alternative?.body,t);const n=new Set(t).add("loop");this.bind(e.loop.left,n,t),await this.nodes(e.body,n);break}case"SET":this.exp(e.val.right,t),this.bind(e.val.left,t,t);break;case"CAPTURE":await this.nodes(e.body,t),t.add(e.val.value);break;case"MACRO":{const n=new Set(t);for(const i of e.val.args??[])this.bind(i,n,t);t.add(e.val.value),this.macros.add(e.val.value),await this.nodes(e.body,n);break}case"CALL":this.exp(e.val,t),await this.nodes(e.body,t);break;case"WITH":this.exp(e.expression,t),await this.nodes(e.body,gt);break;case"BLOCK":this.blocks.add(e.val.value),await this.nodes(e.body,t);break;case"STYLESHEET":default:await this.nodes(e.body,t);break;case"INCLUDE":this.exp(e.val,t),e.withExp&&this.exp(e.withExp,t),"LIT"===e.val.type&&"string"==typeof e.val.value&&await this.include(e.val.value,t)}}async include(e,t){if(this.includes.has(e))return;let n;this.includes.add(e);try{n=await this.options.loader(e)}catch{}n&&await this.analyze(n,new Set(t))}bind(e,t,n){"ID"===e.type?t.add(e.value):"SEQ"===e.type?e.elements.forEach(e=>this.bind(e,t,n)):"ASSIGN"===e.type&&(this.exp(e.right,n),this.bind(e.left,t,n))}exp(e,t){if(e)switch(e.type){case"ID":t===gt||t.has(e.value)||this.variables.add(e.value),e.args?.forEach(e=>this.exp(e,t));break;case"LIT":break;case"NOT":this.exp(e.argument,t);break;case"IF":this.exp(e.test,t),this.exp(e.consequent,t),this.exp(e.alternative,t);break;case"SEQ":e.elements.forEach(e=>this.exp(e,t));break;case"PIPE":{const{left:n,right:i}=e;this.exp(n,t),this.filters.add(i.value);for(const e of i.args??[])this.exp("ASSIGN"===e.type?e.right:e,t);break}default:this.exp(e.left,t),this.exp(e.right,t)}}}const gt=new Set;async function wt(e,t={}){const n=new yt(se(ie,{filters:ee,plugins:ft},t));await n.analyze(e);const i=e=>[...e].sort();return{variables:i(n.variables),filters:i(n.filters),includes:i(n.includes),blocks:i(n.blocks),macros:i(n.macros)}}function vt({variables:e},{includeRuntime:t=!1}={}){const n=e.map(e=>` ${e}?: unknown;`).join("\n");return`// Generated by the Janja precompiler. Do not edit.\nimport type { ${t?"RendererOptions, ":""}Script } from 'janja';\n\n/** The data this template reads. */\nexport interface TemplateData {${n?`\n${n}\n`:""}}\n\nexport declare const script: Script;\n\n${t?"export default function render(\n data?: TemplateData,\n options?: RendererOptions,\n): Promise<string>;":"export default script;"}\n`}function xt(e){let t=e<0?-e<<1|1:e<<1,n="";do{let e=31&t;t>>>=5,t>0&&(e|=32),n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]}while(t>0);return n}function Ot(e,{file:t,source:n,sourceContent:i,line:r}){const s=new Map;for(const t of e)s.set(t.target.start.column,t.source.start);let o=0,a=0,l=0;const c=[...s.entries()].sort(([e],[t])=>e-t).map(([e,t])=>{const n=t.line-1,i=t.column-1,r=xt(e-o)+xt(0)+xt(n-a)+xt(i-l);return o=e,a=n,l=i,r}).join(",");return{version:3,...t?{file:t}:{},sources:[n],sourcesContent:[i],names:[],mappings:`${";".repeat(r)}${c}`}}async function Et(e,{includeRuntime:t,sourceMap:n,filename:i,dts:r,...s}={}){const o=new Z(se(ie,{filters:ee,plugins:ft},s));await o.compile(e);const a=`// Generated by the Janja precompiler. Do not edit.${t?"\nimport { renderCompiled } from 'janja';\n":""}\nexport function script(${y}, e, ${g}, w) {\n`,l=t?"\n}\n\nexport default function render(globals = {}, options) {\n return renderCompiled(script, globals, options);\n}\n":"\n}\n\nexport default script;\n";return{code:`${a}${o.code}${l}`,map:n?Ot(o.mappings,{source:i??"template.janja",sourceContent:e,line:a.split("\n").length-1}):void 0,dts:r?vt(await wt(e,s),{includeRuntime:t}):void 0}}class Pt{constructor(e={}){Object.defineProperty(this,"defaultLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"translations",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pluralRules",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.locale||this.defaultLocale,this.translations=e.translations||{},this.pluralRules=e.pluralRules||this.getDefaultPluralRules()}setLocale(e){this.currentLocale=e}getLocale(){return this.currentLocale}addTranslations(e,t){this.translations[e]||(this.translations[e]={}),this.translations[e]=this.mergeDeep(this.translations[e],t)}translate(e,t={}){const n=this.getTranslation(e);return n?this.interpolate(n,t):e}t(e,t={}){return this.translate(e,t)}pluralize(e,t,n={}){const i=`${e}.${this.getPluralForm(t)}`,r=this.getTranslation(i);if(r)return this.interpolate(r,{...n,count:t});const s=this.getTranslation(e);return s?this.interpolate(s,{...n,count:t}):e}formatDate(e,t){const n="string"==typeof e?new Date(e):e;return new Intl.DateTimeFormat(this.currentLocale,t).format(n)}formatNumber(e,t){return new Intl.NumberFormat(this.currentLocale,t).format(e)}formatCurrency(e,t,n){return new Intl.NumberFormat(this.currentLocale,{...n,style:"currency",currency:t}).format(e)}getTranslation(e){const t=e.split(".");let n=this.translations[this.currentLocale];for(const e of t){if(!n||"object"!=typeof n||!(e in n))return null;n=n[e]}return"string"==typeof n?n:null}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>void 0!==t[n]?String(t[n]):n)}getPluralForm(e){const t=this.pluralRules[this.currentLocale];return t?t(e):this.pluralRules[this.defaultLocale](e)}getDefaultPluralRules(){return{en:e=>1===e?"one":"other",es:e=>1===e?"one":"other",fr:e=>0===e||1===e?"one":"other",de:e=>1===e?"one":"other",ru:e=>{const t=e%10,n=e%100;return 1===t&&11!==n?"one":t>=2&&t<=4&&!(n>=12&&n<=14)?"few":0===t||t>=5&&t<=9?"many":"other"},ja:()=>"other",zh:()=>"other",ar:e=>0===e?"zero":1===e?"one":2===e?"two":e%100>=3&&e%100<=10?"few":e%100>=11&&e%100<=99?"many":"other"}}mergeDeep(e,t){const n={...e};return this.isObject(e)&&this.isObject(t)&&Object.keys(t).forEach(i=>{this.isObject(t[i])?i in e?n[i]=this.mergeDeep(e[i],t[i]):Object.assign(n,{[i]:t[i]}):Object.assign(n,{[i]:t[i]})}),n}isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}}const Tt=new Pt;async function jt(e,t={}){let n="";const{data:i={},options:r}=t,s=new mt(r);for(const t of e)n=await s.render(t,{...i,_content:n});return n}const $t={trim:!1,stripComments:!1,collapseWhitespace:!1,preserveNewlines:!0};function kt(e){return{...$t,...e}}class St{constructor(){Object.defineProperty(this,"mixins",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}register(e){this.mixins.set(e.name,e)}registerMultiple(e){for(const t of e)this.register(t)}get(e){return this.mixins.get(e)}has(e){return this.mixins.has(e)}delete(e){return this.mixins.delete(e)}clear(){this.mixins.clear()}list(){return Array.from(this.mixins.keys())}}const It=new St;async function Nt(e,t={},n=It){const i=n.get(e);if(!i)throw new Error(`Mixin "${e}" not found in registry`);const{data:r={},options:s}=t,o={...i.data,...r};return new mt(s).render(i.template,o)}class Lt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e})}async validate(e){const t=[],n=[],i=e=>{const[n]=e?.suggestions??[];t.push({type:"error",message:`${e?.message??e}`,line:e?.loc?.start.line,column:e?.loc?.start.column,suggestion:n?.fix??n?.message})},r=se(ie,{filters:ee,plugins:ft},this.options,{debug:i});try{const t=new H(r).parse(e);this.checkFilters(t,r.filters,n)}catch(e){i(e)}return{valid:0===t.length,errors:t,warnings:n}}checkFilters(e,t,n,i=new Set){if(e&&"object"==typeof e&&!i.has(e)){i.add(e),"PIPE"!==e.type||"ID"!==e.right?.type||Object.prototype.hasOwnProperty.call(t,e.right.value)||n.push({type:"warning",message:`Unknown filter "${e.right.value}"`,line:e.right.loc?.start.line,column:e.right.loc?.start.column});for(const r of Object.values(e))this.checkFilters(r,t,n,i)}}}const Ct={AND:"and",OR:"or",IS:"is",NOT:"not",EQ:"eq",NE:"ne",GT:"gt",LT:"lt",GE:"ge",LE:"le",IN:"in",NI:"ni",OF:"of",WITH:"with",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"|",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",IF:"if",ELSE:"else"};class Rt{format(e){return e?this.formatExp(e):'""'}formatExp(e){switch(e.type){case"NOT":return this.formatNot(e);case"ID":return this.formatId(e);case"LIT":return this.formatLit(e);case"PIPE":case"IS":case"ASSIGN":case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"OF":case"WITH":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.formatBinary(e);case"IF":return this.formatTernary(e);case"SEQ":return this.formatSeq(e);default:return""}}formatNot({argument:e}){return`${Ct.NOT} ${this.formatExp(e)}`}formatId({value:e,path:t,args:n}){let i=e;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=this.formatSeq({elements:n})),i}formatLit({value:e}){return void 0===e?"undefined":JSON.stringify(e)}formatSeq({elements:e}){return`(${e.map(e=>this.formatExp(e)).join(", ")})`}formatBinary({type:e,left:t,right:n}){return`${this.formatExp(t)} ${Ct[e]} ${this.formatExp(n)}`}formatTernary({test:e,consequent:t,alternative:n}){return`${this.formatExp(t)} ${Ct.IF} ${this.formatExp(e)}${n?` ${Ct.ELSE} ${this.formatExp(n)}`:""}`}}function Dt(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=At(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function At(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if('"'!==s&&"'"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1}return{opens:t,closes:n}}function Mt(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=Ut(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function Ut(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if("{"!==s||"{"!==e[r+1])if('"'!==s&&"'"!==s&&"`"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1;else r=_t(e,r)}return{opens:t,closes:n}}function _t(e,t){if(e.startsWith("{{#",t)){const n=e.indexOf("#}}",t+3);return-1===n?e.length:n+3}const n=e.indexOf("}}",t+2);return-1===n?e.length:n+2}const Ft=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Wt=new Set(["pre","textarea","script","style"]),Xt=new Set(["script","style"]),Gt=new Set(["if","for","macro","block","call","capture","with","stylesheet"]),zt=new Set(["stylesheet"]),Bt=new Set(["else","elif","elseif","elsif"]),qt=new Set(["endif","endfor","endmacro","endblock","endcall","endcapture","endwith","endstylesheet"]);function Kt(e,t){const n=t.tabWidth??2,i=" ".repeat(Math.max(0,n)),r=e.includes("\r\n")?"\r\n":"\n",s=e.split(/\r?\n/);let o=0,a=null,l=null;const c=[];for(const e of s){const s=e.match(/^[ \t]*/)?.[0].length??0,p=e.slice(s),{pieces:h,prefixClosers:f}=Ht(p,t),d=a,b=null!==d&&h.some(e=>"close"===e.kind&&e.sensitive===d),m="stylesheet"===d||null!==d&&Xt.has(d);if(m&&!b){(l??(l=[])).push(e);continue}if(l&&b&&m){const e="stylesheet"===d?Math.max(0,o-1):o,s=l.join(r),a="stylesheet"===d?Kt(s,t):"style"===d?Dt(s,n):Mt(s,n);for(const t of a.split(/\r?\n/))c.push(0===t.length?"":i.repeat(e)+t);l=null}else if(a&&!b){c.push(e),u(h);continue}const y=Math.max(0,o-f);c.push(0===p.length?"":i.repeat(y)+p),u(h)}return c.join(r);function u(e){for(const t of e)"open"===t.kind?(o+=1,t.sensitive&&!a&&({sensitive:a}=t)):"close"===t.kind?(o=Math.max(0,o-1),t.sensitive&&a===t.sensitive&&(a=null)):t.kind}}function Ht(e,t){const n=[];let i=0,r=!0,s=0;for(;s<e.length;){if(/\s/.test(e[s])){s+=1;continue}const o=Jt(e,s,t);o?(o.piece?(n.push(o.piece),!r||"close"!==o.piece.kind&&"mid"!==o.piece.kind?r=!1:i+=1):r=!1,s=o.end):(r=!1,s+=1)}return{pieces:n,prefixClosers:i}}function Jt(e,t,n){const{commentOpen:i,directiveOpen:r,outputOpen:s}=n;if(e.startsWith(i,t))return{end:Yt(e,t+i.length,n.commentClose)};if(e.startsWith(s,t))return{end:Yt(e,t+s.length,n.outputClose)};if(e.startsWith(r,t))return function(e,t,n){const{directiveOpen:i,directiveClose:r}=n,s=Yt(e,t+i.length,r),o=e.slice(t+i.length,s-r.length),a=o.replace(/^\s*-?\s*/,"").match(/^([A-Za-z_]\w*)/)?.[1]?.toLowerCase();if(!a)return{end:s};if(qt.has(a)){const e=a.startsWith("end")?a.slice(3):a;return{end:s,piece:{kind:"close",sensitive:zt.has(e)?e:void 0}}}if(Bt.has(a))return{end:s,piece:{kind:"mid"}};if(Gt.has(a))return{end:s,piece:{kind:"open",sensitive:zt.has(a)?a:void 0}};return{end:s}}(e,t,n);if(e.startsWith("\x3c!--",t)){const n=e.indexOf("--\x3e",t+4);return{end:-1===n?e.length:n+3}}return"<"===e[t]?function(e,t,n){if(e.startsWith("</",t)){let i=t+2;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=Vt(e,i,n);return!s||Ft.has(s)?{end:o}:{end:o,piece:{kind:"close",sensitive:Wt.has(s)?s:void 0}}}if(e.startsWith("<!",t)||e.startsWith("<?",t))return{end:Vt(e,t+2,n)};let i=t+1;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=Vt(e,i,n),a=e.slice(t,o),l=/\/\s*>$/.test(a)||Ft.has(s);if(!s||l)return{end:o};return{end:o,piece:{kind:"open",sensitive:Wt.has(s)?s:void 0}}}(e,t,n):null}function Vt(e,t,n){let i=t,r=null;for(;i<e.length;){const t=e[i];if(r){if(t===r)r=null;else{const t=Qt(e,i,n);if(null!==t){i=t;continue}}i+=1;continue}const s=Qt(e,i,n);if(null===s)if('"'!==t&&"'"!==t){if(">"===t)return i+1;i+=1}else r=t,i+=1;else i=s}return e.length}function Qt(e,t,n){const{commentOpen:i,commentClose:r,outputOpen:s,outputClose:o,directiveOpen:a,directiveClose:l}=n;return e.startsWith(i,t)?Yt(e,t+i.length,r):e.startsWith(s,t)?Yt(e,t+s.length,o):e.startsWith(a,t)?Yt(e,t+a.length,l):null}function Yt(e,t,n){const i=e.indexOf(n,t);return-1===i?e.length:i+n.length}const Zt=e=>JSON.stringify(e,(e,t)=>"loc"===e||"raw"===e?void 0:t??null);class en{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options={continueOnError:!1,undefinedFallback:"",ignoreMissingFilters:!1,onError:()=>{},...e}}safeEvaluate(e,t,n={}){try{const n=this.evaluateExpression(e,t);return void 0===n&&void 0!==this.options.undefinedFallback?this.options.undefinedFallback:n}catch(i){const r={template:n.template||"",data:t,expression:e},s=this.options.onError(i,r);if(this.options.continueOnError)return s;throw i}}safeApplyFilter(e,t,n,i=[],r={}){try{if(!n){if(this.options.ignoreMissingFilters)return e;throw new Error(`Filter "${t}" is not defined`)}return n(e,...i)}catch(e){const n={template:r.template||"",data:r.data||{},filter:t},i=this.options.onError(e,n);if(this.options.continueOnError)return i;throw e}}wrapRender(e,t={}){return(...n)=>{try{return e(...n)}catch(e){const i={template:t.template||"",data:n[1]||{}},r=this.options.onError(e,i);if(this.options.continueOnError)return r;throw e}}}evaluateExpression(e,t){try{const n=e.split(".");let i=t;for(const e of n){if(null==i)return;i=i[e]}return i}catch{return}}createSafeAccessor(e){return t=>{try{const n=t.split(".");let i=e;for(const e of n){if(null==i)return this.options.undefinedFallback;i=i[e]}return void 0===i?this.options.undefinedFallback:i}catch{return this.options.undefinedFallback}}}}let tn;const nn=new WeakMap;function rn(e){if(!e)return tn??(tn=new mt);let t=nn.get(e);return t||(t=new mt(e),nn.set(e,t)),t}e.CompileError=i,e.Compiler=Z,e.ErrorRecovery=en,e.ExpCompiler=he,e.ExpError=E,e.ExpParser=M,e.ExpTokenizer=I,e.I18n=Pt,e.MAX_INCLUDE_DEPTH=100,e.MixinRegistry=St,e.Parser=H,e.RenderError=dt,e.Renderer=mt,e.RootNode=z,e.Safe=c,e.SecurityAuditor=f,e.SecuritySandbox=p,e.TemplatePipeline=class{constructor(e){Object.defineProperty(this,"templates",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options=e}addTemplate(e){return this.templates.push(e),this}setData(e){return this.data={...this.data,...e},this}setOptions(e){return this.options={...this.options,...e},this}async execute(){return jt(this.templates,{data:this.data,options:this.options})}},e.TemplateValidator=Lt,e.Tokenizer=K,e.Traversal=G,e.analyzeTemplate=wt,e.applyMixin=Nt,e.applyMixins=async function(e,t={},n=It){const i=[];for(const r of e){const e=await Nt(r,t,n);i.push(e)}return i},e.applyWhitespaceControl=function(e,t){let n=e;return t.stripComments&&(n=n.replace(/<!--[\s\S]*?-->/g,"")),t.collapseWhitespace&&(n=t.preserveNewlines?n.replace(/[ \t]+/g," "):n.replace(/\s+/g," ")),t.trim&&(n=n.trim()),n},e.baseOptions=te,e.compilerOptions=ie,e.composeLayout=async function(e,t,n={}){const{data:i={},options:r}=n,s=new mt({...r,autoEscape:!1}),o=await s.render(t,i);return s.render(e,{...i,content:o})},e.composeTemplates=jt,e.composeTemplatesWithData=async function(e,t={}){let n="";const{options:i}=t,r=new mt(i);for(const t of e){const e={...t.data,_content:n};n=await r.render(t.template,e)}return n},e.composeWithSlots=async function(e,t,n={}){const{data:i={},options:r}=n,s=new mt({...r,autoEscape:!1}),o={};for(const[e,n]of Object.entries(t))o[e]=await s.render(n,i);return s.render(e,{...i,slots:o})},e.createErrorRecovery=function(e={}){return new en(e)},e.createFileLoader=function(e,{extensions:t=[".janja",".html"]}={}){return async n=>{const{readFile:i}=await(import("node:fs/promises")),r=await(import("node:path")),s=r.resolve(e),o=r.extname(n)?[n]:[...t.map(e=>`${n}${e}`),n];for(const e of o){const t=r.resolve(s,e);if(!t.startsWith(s+r.sep))break;try{return await i(t,"utf-8")}catch{}}throw new Error(`Template "${n}" not found in ${e}`)}},e.createMixin=function(e,t,n){return{name:e,template:t,data:n}},e.deepEscape=h,e.defaultErrorHandler=function(e,t){console.error("[Janja Error]",e.message),t.expression&&console.error(" Expression:",t.expression),t.filter&&console.error(" Filter:",t.filter)},e.defaultWhitespaceOptions=$t,e.defineFilters=function(e){return e},e.definePlugin=function(e){return e},e.expTokenTypes=T,e.extendTemplateWithMixin=async function(e,t,n={},i=It){const r=await Nt(t,n,i);return new mt({...n.options,autoEscape:!1}).render(e,{_mixin:r})},e.filters=ee,e.formatTemplate=function(t,n={}){const i={...ne,...n},r=new K(i).tokenize(t),s=[0];for(let e=0;e<t.length;e++)"\n"===t[e]&&s.push(e+1);const o=({line:e,column:t})=>s[e-1]+t-1,a=new M,l=new Rt,c=(e,t)=>{try{const n=a.parse(e,t),i=l.format(n);return Zt(a.parse(i,t))!==Zt(n)?null:i.replace(/[{}]/g,"\\$&")}catch{return null}},u=r.map(n=>{const r=t.slice(o(n.loc.start),o(n.loc.end));return n.type===e.TokenType.TEXT||n.type===e.TokenType.COMMENT&&n.val.includes("\n")?r:(t=>{const n=t.strip.before?"-":"",r=t.strip.after?"-":"";if(t.type===e.TokenType.COMMENT)return`${i.commentOpen}${n} ${t.val.trim()} ${r}${i.commentClose}`;if(t.type===e.TokenType.OUTPUT){const e=c(t.val,t.loc);return e&&`${i.outputOpen}${n} ${e} ${r}${i.outputClose}`}const{name:s,expression:o}=t;if(!s)return null;const a=o?c(o.val,o.loc):"";return null!==a&&`${i.directiveOpen}${n} ${s}${a&&` ${a}`} ${r}${i.directiveClose}`})(n)||r}).join("");return!1===n.html?u:Kt(u,{tabWidth:n.tabWidth,commentOpen:i.commentOpen,commentClose:i.commentClose,directiveOpen:i.directiveOpen,directiveClose:i.directiveClose,outputOpen:i.outputOpen,outputClose:i.outputClose})},e.generateDeclarations=vt,e.generateSourceMap=Ot,e.getWhitespaceCompilerOptions=function(e){const t=kt(e);return{trimWhitespace:t.trim,stripComments:t.stripComments}},e.getWhitespaceRendererOptions=function(e){const t=kt(e),n={};return t.trim!==$t.trim&&(n.trimWhitespace=t.trim),t.stripComments!==$t.stripComments&&(n.stripComments=t.stripComments),n},e.globalMixinRegistry=It,e.i18n=Tt,e.isForbiddenIdentifier=$,e.mergeOptions=se,e.mergeWhitespaceOptions=kt,e.optionsFingerprint=m,e.parserOptions=ne,e.precompile=Et,e.precompileTemplate=async function(e,t={}){return(await Et(e,t)).code},e.render=async function(e,t,n){return rn(n).render(e,t)},e.renderCompiled=async function(e,t={},n){return rn(n).renderCompiled(e,t)},e.renderFile=async function(e,t,n){return rn(n).renderFile(e,t)},e.renderOptions=re,e.renderStream=function(e,t={},n){return rn(n).renderStream(e,t)},e.resolveSecurityLimits=u,e.templateCacheKey=b,e.validateTemplate=async function(e,t){return new Lt(t).validate(e)}}(this.janja=this.janja||{});
1
+ !function(e){"use strict";class t{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=new Map,this.maxSize=e.maxSize??1e3,this.ttl=e.ttl??36e5,this.stats={hits:0,misses:0,evictions:0}}get(e){const t=this.cache.get(e);return t?this.ttl>0&&Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),this.stats.misses++,null):(this.cache.delete(e),this.cache.set(e,t),t.hits++,this.stats.hits++,t.value):(this.stats.misses++,null)}peek(e){const t=this.cache.get(e);return!t||this.ttl>0&&Date.now()-t.timestamp>this.ttl?null:t.value}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){const e=this.cache.keys().next().value;void 0!==e&&(this.cache.delete(e),this.stats.evictions++)}this.cache.set(e,{value:t,timestamp:Date.now(),hits:0})}has(e){const t=this.cache.get(e);return!!t&&(!(this.ttl>0&&Date.now()-t.timestamp>this.ttl)||(this.cache.delete(e),!1))}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.stats={hits:0,misses:0,evictions:0}}invalidate(e){if(e)for(const t of this.cache.keys())e(t)&&this.cache.delete(t);else this.clear()}getStats(){return{...this.stats,size:this.cache.size,hitRate:this.stats.hits+this.stats.misses>0?this.stats.hits/(this.stats.hits+this.stats.misses):0}}resetStats(){this.stats={hits:0,misses:0,evictions:0}}}function n(e,t,n){const i=[];if("ExpError"===e&&(t.includes("Unexpected end of expression")&&i.push({message:"The expression is incomplete. Make sure you have closed all parentheses, brackets, and quotes.",fix:"Check for missing closing characters: ), ], }"}),t.includes('Expected "RP" after "LP"')&&i.push({message:"Missing closing parenthesis in your expression.",fix:"Add a closing parenthesis ) to match the opening one.",example:"(foo.bar) instead of (foo.bar"}),t.includes("No left operand")&&i.push({message:"An operator is missing its left operand.",fix:"Add a value or variable before the operator.",example:"x + 1 instead of + 1"}),t.includes("No right operand")&&i.push({message:"An operator is missing its right operand.",fix:"Add a value or variable after the operator.",example:"x + 1 instead of x +"}),t.includes('Expected "ID" after "PIPE"')&&i.push({message:"The pipe operator | must be followed by a filter name.",fix:"Add a filter name after the pipe.",example:"value|upper instead of value|"}),t.includes('Expected "ID" after "DOT"')&&i.push({message:"The dot operator . must be followed by a property name.",fix:"Add a property name after the dot.",example:"object.property instead of object."}),t.includes("Left operand of assignment must be an identifier")&&i.push({message:"Assignment targets must be valid identifiers.",fix:"Use a simple variable name or sequence of variable names.",example:"x = 1 or (a, b) = [1, 2]"}),t.includes("Expected test expression")&&i.push({message:"The conditional expression is missing its test condition.",fix:"Add a condition after the if keyword.",example:"if x > 0 then y else z"}),t.includes("Expected alternative expression")&&i.push({message:"The conditional expression is missing its else clause.",fix:"Add an alternative expression after then.",example:"if x > 0 then y else z"}),t.startsWith("Unexpect")&&i.push({message:"An unexpected character was found in the expression.",fix:"Check for typos or invalid characters in your expression."})),"CompileError"===e){if(t.includes("Unclosed")){const e=t.match(/Unclosed "([^"]+)"/),n=e?e[1]:"marker";i.push({message:`The ${n} marker is not closed properly.`,fix:`Add the closing marker for ${n}.`,example:"{%"===n?"{% ... %}":"{#"===n?"{# ... #}":"{{ ... }}"})}t.includes("Unexpected")&&i.push({message:"An unexpected token was found in the template.",fix:"Check your template syntax and ensure all markers are properly formatted."})}return n&&i.push({message:"Context information:",fix:n}),i}class i extends SyntaxError{constructor(e,t,n,r){super(e),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:r}),this.name="CompileError",i.captureStackTrace?.(this,this.constructor)}get details(){const e=this.loc?function(e,t,{start:{line:n,column:i},end:{line:r,column:s}}){const o=[],a=new Set,l=e=>{a.add(e-2),a.add(e-1),a.add(e),a.add(e+1),a.add(e+2)},c=t.split("\n"),u=String(c.length).length+2;let p=0;c.forEach((e,t)=>{if(e){if(o.push(`${`${t+1}│ `.padStart(u," ")}${e}`),n===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(i-1)}^${n===r&&s>i+1?`${" ".repeat(s-i-2)}^`:""}`;/\S/.test(e)&&o.push(e),l(++p+t)}if(n!==r&&r===t+1){const e=`${" ".repeat(u-2)}│ ${" ".repeat(s-1)}${"^".repeat(1)}`;/\S/.test(e)&&o.push(e),l(++p+t)}}});const h=`${" ".repeat(u)}...`;return`${e}\n\n${o.map((e,t)=>a.has(t)?e:h).reduce((e,t)=>t===h&&e.at(-1)===t?e:[...e,t],[]).join("\n")}\n`}(this.message,this.src,this.loc):this.message;return function(e,t,i,r){const s=n(e,t,r);return 0===s.length?i:`${i}\n\nSuggestions:\n${s.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n")}`}(this.name,this.message,e,this.context)}get suggestions(){return n(this.name,this.message,this.context)}}const r=/[&<>"']/,s=/[&<>"']/g,o={"&":"&amp;",'"':"&#34;","'":"&#39;","<":"&lt;",">":"&gt;"},a=e=>o[e];function l(e){const t="string"==typeof e?e:`${e}`;return r.test(t)?t.replace(s,a):t}class c extends String{constructor(e){super(`${e}`)}}function u(e={}){return{maxIncludeDepth:e.maxIncludeDepth??100,maxLoopIterations:e.maxLoopIterations,maxCallDepth:e.maxCallDepth,timeoutMs:e.timeoutMs}}class p{constructor(e={}){Object.defineProperty(this,"allowedGlobals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cspNonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.allowedGlobals=new Set(e.allowedGlobals||[]),this.cspNonce=e.cspNonce}sanitizeGlobals(e){const t={};for(const[n,i]of Object.entries(e))this.allowedGlobals.has(n)&&(t[n]=i);return t}validateExpression(e){const t=[/\bprocess\b/,/\brequire\b/,/\bimport\b/,/\bexport\b/,/\beval\b/,/\bFunction\b/,/\b__proto__\b/,/\bconstructor\b/];for(const n of t)if(n.test(e))return!1;return!0}createSecureContext(e){return{...this.sanitizeGlobals(e),Math:Math,Date:Date,JSON:JSON}}getCSPNonce(){return this.cspNonce}generateCSPHeaders(){const e={};return this.cspNonce&&(e["Content-Security-Policy"]=`script-src 'nonce-${this.cspNonce}'`),e}}function h(e,t=new WeakSet){if(null==e)return"";if(e instanceof c)return`${e}`;if("object"==typeof e){if(t.has(e))return"";t.add(e);return(Array.isArray(e)?e:Object.values(e)).map(e=>h(e,t)).join("")}return l(e)}class f{auditTemplate(e){const t=[],n=[{pattern:/\beval\s*\(/,type:"dangerous-eval",message:"Use of eval() is dangerous and should be avoided",severity:"critical"},{pattern:/\bFunction\s*\(/,type:"dangerous-function",message:"Use of Function constructor is dangerous",severity:"critical"},{pattern:/\brequire\s*\(/,type:"require-usage",message:"Direct require() usage in templates is unsafe",severity:"high"},{pattern:/\bimport\s*\(/,type:"dynamic-import",message:"Dynamic import() usage in templates may be unsafe",severity:"high"}];for(const{pattern:i,type:r,message:s,severity:o}of n){const n=e.match(i);n&&t.push({type:r,message:s,location:`at index ${n.index}`,severity:o})}return{issues:t,severity:this.calculateOverallSeverity(t)}}calculateOverallSeverity(e){if(0===e.length)return"low";const t={critical:4,high:3,medium:2,low:1},n=Math.max(...e.map(e=>t[e.severity]));return Object.entries(t).find(([,e])=>e===n)[0]}}const d=new WeakMap;function b(e,t=!1){return t?`\0stream:${e}`:e}function m(e){let t=d.get(e);if(void 0===t){const{trimWhitespace:n,stripComments:i,commentOpen:r,commentClose:s,directiveOpen:o,directiveClose:a,outputOpen:l,outputClose:c,preloadIncludes:p}=e,{maxIncludeDepth:h,maxLoopIterations:f,maxCallDepth:b}=u(e.security);t=JSON.stringify([n,i,r,s,o,a,l,c,h,f??null,b??null,p]),d.set(e,t)}return t}const y="c",g="f",w="r_";class v{constructor(){Object.defineProperty(this,"mappings",{enumerable:!0,configurable:!0,writable:!0,value:[]})}addMapping(e,t){this.mappings.push({source:e,target:t})}getSourceLoc({line:e,column:t}){return this.mappings.filter(({target:{start:n,end:i}})=>n.line<=e&&i.line>=e&&(n.line<e||n.column<=t)&&(i.line>e||i.column>=t)).map(({source:e})=>e)}}class x extends v{constructor(){super(...arguments),Object.defineProperty(this,"codeParts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"codeLength",{enumerable:!0,configurable:!0,writable:!0,value:0})}get code(){return this.codeParts.join("")}set code(e){this.codeParts=[e],this.codeLength=e.length}get script(){return new Function(y,"e",g,"w",this.code)}checkpoint(){return[this.codeParts.length,this.mappings.length,this.codeLength]}rollback(e){const[t,n,i]=e;this.codeParts.length=t,this.mappings.length=n,this.codeLength=i}start(e=!0){this.pushRaw(null,"return(async()=>{",`let s="",${w};`),e&&this.pushRaw(null,"const u_=(n)=>{throw new Error('Unknown filter \"'+n+'\"')};")}end(){this.pushRaw(null,"return s;","})();")}pushRaw(e,...t){const n=this.codeLength;for(const e of t)this.codeParts.push(e),this.codeLength+=e.length;e&&this.addMapping(e,{start:{line:1,column:n},end:{line:1,column:this.codeLength}})}pushStr(e,t){t&&this.pushRaw(e,`s+=${JSON.stringify(t)};`)}pushFlush(){this.pushRaw(null,'if(s.length>1024){await w(s);s="";}')}pushVar(e,t){this.pushRaw(e,`s+=e(${t});`)}}class O extends x{constructor(){super(...arguments),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:y}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:[y]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0})}checkpoint(){return[super.checkpoint(),this.context,[...this.stack]]}rollback(e){const[t,n,i]=e;super.rollback(t),this.context=n,this.stack=i}in(){return this.context=`${this.context}_${this.index++}`,this.stack.push(this.context),this.context}out(){this.context!==y&&(this.stack.pop(),this.context=this.stack.at(-1))}}class E extends SyntaxError{constructor(e,t,n){super(e),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="ExpError",E.captureStackTrace?.(this,this.constructor)}get suggestions(){return n(this.name,this.message,this.context)}get details(){const{suggestions:e}=this;if(0===e.length)return this.message;const t=e.map((e,t)=>{let n=` ${t+1}. ${e.message}`;return e.fix&&(n+=`\n Fix: ${e.fix}`),e.example&&(n+=`\n Example: ${e.example}`),n}).join("\n");return`${this.message}\n\nSuggestions:\n${t}`}}function P(e,t){const n=(e.match(/\n/g)||[]).length;if(n>0){t.line+=n;const i=e.lastIndexOf("\n");t.column=e.length-i}else t.column+=e.length;return{line:t.line,column:t.column}}const j={and:"AND",or:"OR",not:"NOT",is:"IS",eq:"EQ",ne:"NE",gt:"GT",lt:"LT",ge:"GE",le:"LE",in:"IN",ni:"NI",of:"OF",with:"WITH","+":"ADD","-":"SUB","*":"MUL","/":"DIV","%":"MOD",if:"IF",else:"ELSE",true:"LIT",false:"LIT",null:"LIT",undefined:"LIT","|":"PIPE","=":"ASSIGN","(":"LP",")":"RP",",":"COMMA",".":"DOT"},T=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(e){return"string"==typeof e&&T.has(e)}const k={n:"\n",t:"\t",r:"\r","\\":"\\",'"':'"',"'":"'","`":"`"};function S(e){switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return;default:return e}}class I{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}tokenize(e,t){for(this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=[];this.index<this.val.length;){const e=this.val[this.index];if(N(e))"\n"===e?(this.line++,this.column=1):this.column++,this.index++;else if("'"!==e&&'"'!==e&&"`"!==e)if(L(e)||"-"===e&&L(this.val[this.index+1]??"")&&!this.afterOperand())this.readNumber(e);else if(R(e))this.readIdentifier(e);else{if(!C(e))throw new E(`Unexpected "${e}"`,{start:{line:this.line,column:this.column},end:{line:this.line,column:this.column+1}});this.readSymbol(e)}else this.readString(e)}return this.tokens}afterOperand(){const e=this.tokens.at(-1)?.type;return"ID"===e||"LIT"===e||"RP"===e}readString(e){let t="",n="",i=!1;const r={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const r=this.val[this.index];if(i)t+=k[r]??`\\${r}`,n+=r,i=!1;else if("\\"===r)n+=r,i=!0;else{if(r===e)break;t+=r,n+=r}this.index++}this.index++,this.tokens.push({type:"LIT",value:t,loc:{start:r,end:P(`${e}${n}${e}`,this)},raw:`${e}${n}${e}`})}readNumber(e){let t=e,n=!1;const i={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(L(e))t+=e;else{if("."!==e||n)break;t+=e,n=!0}this.index++}this.tokens.push({type:"LIT",value:Number.parseFloat(t),loc:{start:i,end:P(t,this)},raw:t})}readIdentifier(e){let t=e;const n={line:this.line,column:this.column};for(this.index++;this.index<this.val.length;){const e=this.val[this.index];if(!D(e))break;t+=e,this.index++}if($(t))throw new E(`"${t}" is not allowed in expressions`,{start:n,end:{line:this.line,column:this.column+t.length}});const i=Object.prototype.hasOwnProperty.call(j,t)?j[t]:"ID";this.tokens.push({type:i,value:"LIT"===i?S(t):t,loc:{start:n,end:P(t,this)},raw:t})}readSymbol(e){const t={line:this.line,column:this.column};this.index++,this.tokens.push({type:j[e],value:e,loc:{start:t,end:P(e,this)},raw:e})}}function N(e){return/\s/.test(e)}function C(e){return/[+\-*/%|=(),.]/.test(e)}function L(e){return/\d/.test(e)}function R(e){return/[a-z_$]/i.test(e)}function D(e){return/[\w$]/.test(e)}const A={COMMA:5,IF:10,ELSE:10,ASSIGN:15,LP:20,RP:20,OR:25,AND:30,IS:40,EQ:40,NE:40,GT:40,LT:40,GE:40,LE:40,IN:40,NI:40,OF:40,WITH:40,ADD:50,SUB:50,MUL:60,DIV:60,MOD:60,NOT:70,PIPE:80,DOT:90,ID:90,LIT:90};class M{constructor(){Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1})}parse(e,t){return this.val=e,this.index=0,this.line=t.start.line,this.column=t.start.column,this.tokens=(new I).tokenize(e,t),this.val?this.parseExp():null}parseExp(e){let t=null;for(;;){const n=this.next();if(!n)break;const i=e?.(n);if("BACK"===i){this.back();break}if("BREAK"===i)break;if(t&&F(n),"LP"===n.type){if(!this.peek())throw new E("Unexpected end of expression",n.loc);const e=this.parseSequence(),i=this.consume("RP");if(!i)throw new E('Expected "RP" after "LP"',n.loc);t={...n,type:"SEQ",elements:e,loc:{start:n.loc.start,end:i.loc.end}};continue}if("NOT"!==n.type){if("ID"===n.type){t={...n,type:"ID",value:n.value},this.match("DOT")&&(t.path=this.parsePath());const e=this.consume("LP");if(e){if(t.args=this.parseSequence(),!this.consume("RP"))throw new E('Expected "RP" after "LP"',e.loc);continue}continue}if("LIT"!==n.type){if("IF"===n.type){const e=this.parseExp(e=>"ELSE"===e.type||X(n,e)?"BACK":void 0);if(!e)throw new E("Expected test expression",n.loc);if(t={...n,type:"IF",test:e,consequent:t},this.consume("ELSE")){const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E("Expected alternative expression",n.loc);t.alternative=e}continue}if(_(n.type)){if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);"ASSIGN"===n.type&&W(t,n);const e=this.parseExp(e=>X(n,e)?"BACK":void 0);if(!e)throw new E(`No right operand for "${n.type}"`,n.loc);t={...n,type:n.type,left:t,right:e};continue}if("PIPE"!==n.type){this.back();break}if(!t)throw new E(`No left operand for "${n.type}"`,n.loc);if(!this.match("ID"))throw new E('Expected "ID" after "PIPE"',n.loc);t={...n,type:"PIPE",left:t,right:this.parsePipe()}}else t={...n,type:"LIT"}}else{if(!this.peek())throw new E("Unexpected end of expression",n.loc);t={...n,type:"NOT",argument:this.parseExp(e=>X(n,e)?"BACK":void 0)}}}return t}parsePath(){const e=[];for(;;){const t=this.consume("DOT");if(!t)break;const n=this.next();if(!n)throw new E('Expected "ID" after "DOT"',t.loc);if("ID"!==n.type)throw new E('Expected "ID" after "DOT"',t.loc);e.push({...n,type:"ID",value:n.value})}return e}parseSequence(){const e=[];for(;!this.match("RP");){const t=this.parseExp(e=>"COMMA"===e.type?"BREAK":void 0);if(!t)break;e.push(t)}return e}parsePipe(){const e=this.next(),t={...e,type:"ID",value:e.value},n=this.consume("LP");if(n&&(t.args=this.parseSequence(),!this.consume("RP")))throw new E('Expected "RP" after "LP"',n.loc);return t}next(){return this.tokens[this.index++]??null}back(){return this.tokens[this.index--]}peek(){return this.tokens.at(this.index)??null}match(e){return this.peek()?.type===e}consume(e){if(this.match(e))return this.next()}}const U=new Set(["AND","OR","IS","EQ","NE","GT","LT","GE","LE","IN","NI","OF","WITH","ADD","SUB","MUL","DIV","MOD","ASSIGN"]);function _(e){return U.has(e)}function F(e){if("ID"===e.type||"LIT"===e.type||"LP"===e.type)throw new E(`Unexpected "${e.raw??e.value}"`,e.loc)}function W(e,t){if("SEQ"===e.type){if(e.elements.some(e=>"ID"!==e.type||e.path||e.args))throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}else if("ID"!==e.type||e.path||e.args)throw new E("Left operand of assignment must be an identifier or a sequence of identifiers",t.loc)}function X(e,t){return"LP"!==t.type&&A[e.type]>A[t.type]}class G{constructor(){Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}traverse(e){this.body?.forEach(e)}}class z extends G{constructor(e,t){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEMPLATE"})}}var B;function q(e){return e.replace(/\\([{}])/g,"$1")}e.TokenType=void 0,(B=e.TokenType||(e.TokenType={})).TEXT="TEXT",B.OUTPUT="OUTPUT",B.DIRECTIVE="DIRECTIVE",B.COMMENT="COMMENT";class K{constructor(t){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenPatterns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"markerIndices",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"line",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"column",{enumerable:!0,configurable:!0,writable:!0,value:1});const{commentOpen:n,commentClose:i,directiveOpen:r,directiveClose:s,outputOpen:o,outputClose:a}=this.options;this.tokenPatterns=[[e.TokenType.COMMENT,n,i],[e.TokenType.DIRECTIVE,r,s],[e.TokenType.OUTPUT,o,a]].sort(([,e],[,t])=>e.length>t.length?-1:1),this.markerIndices=new Map;for(const[,e]of this.tokenPatterns)e.length>0&&this.markerIndices.set(e[0],this.markerIndices.get(e[0])||0)}tokenize(e){for(this.template=e,this.length=e.length,this.index=0,this.line=1,this.column=1,this.tokens=[];this.index<this.length;)this.consumeSpecialTokens()||this.consumeTextToken();return this.tokens}consumeSpecialTokens(){return this.tokenPatterns.some(([t,n,r])=>{if(!this.lookahead(n))return!1;const s={line:this.line,column:this.column},o=this.template.indexOf(r,this.index+n.length);if(-1===o)throw new i(`Unclosed "${n}"`,this.template,{start:s,end:P(n,{...s})});const a=this.lookahead("-",n.length),l="-"===this.template[o-1],c=this.template.slice(this.index+n.length+ +a,o-+l),u=P(this.template.slice(this.index,this.index=o+r.length),this),p={type:t,val:q(c),strip:{before:a,after:l},loc:{start:s,end:u}};if(t===e.TokenType.DIRECTIVE){let e=0,t="";for(;e<c.length;){const n=c[e];if(/\S/.test(n))t+=n;else if(t)break;e++}Object.assign(p,{name:t,expression:e===c.length||/^\s*$/m.test(c.slice(e+1))?null:{val:c.slice(e+1),loc:{start:P(c.slice(0,e+1),P(`${n}${a?"-":""}`,{...s})),end:{line:this.line,column:this.column-r.length-+l}}}})}return this.tokens.push(p),!0})}consumeTextToken(){const t=this.findNextSpecialIndex(),n={line:this.line,column:this.column},i=this.template.slice(this.index,t);this.tokens.push({type:e.TokenType.TEXT,val:q(i),loc:{start:n,end:P(i,this)},strip:{}}),this.index=t}lookahead(e,t=0){return this.template.startsWith(e,this.index+t)}findNextSpecialIndex(){const{outputOpen:e,directiveOpen:t,commentOpen:n}=this.options;let i=this.length;for(let r=this.index;r<this.length;r++){if(this.template.startsWith(n,r)){i=r;break}if(this.template.startsWith(t,r)){i=r;break}if(this.template.startsWith(e,r)){i=r;break}}return i}}class H extends K{constructor(){super(...arguments),Object.defineProperty(this,"expParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}parse(t){this.tokenize(t),this.tokens.forEach((t,n)=>{t.type===e.TokenType.TEXT&&(this.tokens[n-1]?.strip?.after&&(t.strip.start=!0),this.tokens[n+1]?.strip?.before&&(t.strip.end=!0))});const n=this.tokens[0]?.loc.start??{line:1,column:1},i=this.tokens.at(-1)?.loc.end??{line:1,column:1};return this.expParser=new M,this.cursor=0,new z(this.parseUntil(),{start:n,end:i})}parseUntil(t){const n=[];let i=null;for(;;){const r=this.peek();if(!r||r.type===e.TokenType.DIRECTIVE&&t&&this.match(t,r))break;i?.strip?.after&&r.type===e.TokenType.TEXT&&(r.strip.start=!0),r.strip?.before&&i?.type===e.TokenType.TEXT&&(i.strip.end=!0);let s=this.options.parsers[r.name?.toLowerCase()??r.type?.toLowerCase()];"string"==typeof s&&(s=this.options.parsers[s]),s||(s=this.options.parsers.unknown);const{cursor:o}=this,a=s?.(r,this);if(a)for(;;){const{value:e,done:t}=a.next();if(t)break;"NEXT"===e?this.advance():e&&n.push(e)}this.cursor===o&&this.advance(),i=r}return n}parseExp({val:e,loc:t}){try{return this.expParser.parse(e,t)}catch(e){this.options.debug(e.loc?new i(e.message,this.template,e.loc):e)}}peek(){return this.tokens.at(this.cursor)??null}advance(){this.cursor++}match(e,t=this.peek()){return e.includes(t?.name?.toLowerCase())}emitExpErr({name:e,loc:t},n=!0){this.options.debug(new i(n?`"${e}" requires expression`:`"${e}" should not have expression`,this.template,t))}}function J(e){return"LIT"===e.type&&"string"==typeof e.value}class V extends G{constructor(e,t,n,i=null,r=null){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"withExp",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"modifier",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"INCLUDE"})}}const Q={start:{line:1,column:1},end:{line:1,column:1}},Y=new Set(["IF","FOR"]);class Z extends O{constructor(e,t,n=!0,i=!1){super(),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"revalidate",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isRoot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rootNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partials",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheets",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stylesheetKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sources",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hasDynamicInclude",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"flushable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.cache=t}async compile(e,t=!0,n=new Map,i=new Map,r=new Map,s=new Map,o="\0root"){this.template=e,this.isRoot=t,this.partials=n,this.blocks=i,this.stylesheets=s,this.stylesheetKey=o,this.sources=r,this.hasDynamicInclude=!1;const a=this.generateCacheKey(e);if(this.cache&&t){const e=this.cache.get(a);if(e){if(e.fingerprint===this.fingerprint()&&await this.isFresh(e))return this.code=e.code,this.mappings=e.mappings,this.compiled=e,this;this.cache.delete(a)}}if(this.rootNode=new H(this.options).parse(e),this.state={},this.start(this.isRoot),this.isRoot&&(this.pushResourceLimitCounters(),this.pushRaw(null,"let ss_u=0;")),await this.parseTemplates(),this.isRoot){if(this.partials.size||this.hasDynamicInclude){const{maxIncludeDepth:e}=u(this.options.security);this.pushRaw(null,`const tc_=${y};`,"let d_=0;","const inc_={};","const p={");for(const[t,n]of this.partials)this.pushRaw(null,`${JSON.stringify(t)}:async(c)=>{`,`if(d_>=${e})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(t)} are nested too deeply`)});`,"d_++;","try{return await(async()=>{",n,"})();}finally{d_--;}","},");this.pushRaw(null,"};")}if(this.blocks.size){this.pushRaw(null,"const b={");for(const[e,t]of this.blocks){this.pushRaw(null,`${JSON.stringify(e)}:{`,"u:0,","s:["),this.state.block=e;for(const e of t)this.pushRaw(null,"async()=>{",'let s="";'),await this.compileNodes(e.body),this.pushRaw(null,"return s;","},");this.state.block=void 0,this.pushRaw(null,"],","},")}this.pushRaw(null,"};")}this.pushRaw(null,"const ss_=[");for(const[,e]of this.stylesheets){this.pushRaw(null,"async()=>{",'let s="";');for(const t of e)await this.compileNodes(t.body);this.pushRaw(null,"return s;","},")}this.pushRaw(null,"];")}return this.flushable=this.isRoot&&this.stream,await this.compileNode(this.rootNode),this.flushable=!1,this.end(),this.cache&&t&&(this.compiled={code:this.code,mappings:this.mappings,sources:this.sources,fingerprint:this.fingerprint()},this.cache.set(a,this.compiled)),this}get script(){var e;return this.compiled?(e=this.compiled).script??(e.script=super.script):super.script}generateCacheKey(e){return b(e,this.stream)}fingerprint(){return m(this.options)}pushResourceLimitCounters(){const{maxLoopIterations:e,maxCallDepth:t}=u(this.options.security);null!=e&&this.pushRaw(null,"let li_=0;"),null!=t&&this.pushRaw(null,"let cd_=0;")}async isFresh({sources:e}){if(!this.revalidate)return!0;try{for(const[t,n]of e)if(await this.options.loader(t)!==n)return!1}catch{return!1}return!0}async parseTemplates(){const{partials:e,blocks:t,stylesheets:n}=this.collectPartialsAndBlocks();if(this.isRoot)for(const t of this.options.preloadIncludes)e.has(t)||e.set(t,new V({type:"LIT",value:t,loc:Q},Q,{before:!1,after:!1}));for(const[t,n]of e)if(!this.partials.has(t)){let e;try{e=await this.options.loader(t)}catch{throw new i(`Failed to load template from "${t}"`,this.template,n.loc)}this.sources.set(t,e??""),this.partials.set(t,""),e&&await this.compilePartial(t,n,e)}for(const e of t){const{val:{value:t}}=e;this.blocks.has(t)||this.blocks.set(t,[]),this.blocks.get(t).push(e)}n.length&&!this.stylesheets.has(this.stylesheetKey)&&this.stylesheets.set(this.stylesheetKey,n)}collectPartialsAndBlocks(){const e=new Map,t=[],n=[],i=new Map,r=s=>{if("INCLUDE"===s.type){const t=s;if(J(t.val)){if(e.has(t.val.value)||e.set(t.val.value,t),"last"===t.modifier){const e=i.get(t.val.value);e?e.total+=1:i.set(t.val.value,{total:1,emitted:0})}}else this.hasDynamicInclude=!0}"BLOCK"===s.type&&t.push(s),"STYLESHEET"===s.type&&n.push(s),s.traverse(r)};return r(this.rootNode),this.state.includeLast=i,{partials:e,blocks:t,stylesheets:n}}async compileNode(e){if("TEMPLATE"===e.type){for(const t of e.body)await this.compileNode(t),this.flushable&&"TEXT"!==t.type&&this.pushFlush();return}let t=this.options.compilers[e.type];"string"==typeof t&&(t=this.options.compilers[t]),t||(t=this.options.compilers.UNKNOWN);const n=this.checkpoint(),{flushable:r}=this;Y.has(e.type)||(this.flushable=!1);try{await(t?.(e,this))}catch(t){if(this.flushable=r,"CompileError"===t?.name)throw t;this.rollback(n),this.options.debug(new i(`Invalid "${e.type.toLowerCase()}" directive`,this.template,e.loc))}this.flushable=r}async compileNodes(e){for(const t of e)await this.compileNode(t)}async compilePartial(e,t,n){try{const{code:t}=await new Z(this.options).compile(n,!1,this.partials,this.blocks,this.sources,this.stylesheets,e);this.partials.set(e,t)}catch{this.options.debug(new i("Failed to compile template",this.template,t.loc))}}}var ee=Object.freeze({__proto__:null,abs:function(e=0){return Math.abs(e)},add:function(e=0,t=0){return e+t},capitalize:function(e=""){return e.replace(/\b\w/g,e=>e.toUpperCase())},ceil:function(e=0){return Math.ceil(e)},chunk:function(e,t){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},compact:function(e=[]){return e.filter(e=>null!=e)},currency:function(e,t="USD",n="en-US"){return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(e)},date:function(e,t="ISO"){const n=e instanceof Date?e:new Date(e);if(isNaN(n.getTime()))return"";switch(t){case"ISO":default:return n.toISOString();case"date":return n.toISOString().split("T")[0];case"time":return n.toTimeString().split(" ")[0];case"locale":return n.toLocaleDateString();case"locale-time":return n.toLocaleTimeString();case"locale-datetime":return n.toLocaleString()}},defaults:function(e,t){return{...t,...e}},delay:async function(e,t){return await new Promise(e=>setTimeout(e,t)),e},div:function(e=0,t=1){return e/t},entries:function(e={}){return Object.entries(e)},escape:l,even:function(e=0){return+e%2==0},fallback:function(e,t,n=!1){return n?e||t:e??t},fetchUrl:async function(e,t={}){return(await fetch(e,t)).text()},first:function(e=[]){return[...e][0]},fixed:function(e,t=2){return Number(e).toFixed(t)},get:function(e,...t){return t.reduce((e,t)=>e&&"object"==typeof e&&!$(t)&&t in e?e[t]:void 0,e)},groupby:function(e=[],t){return e.reduce((e,n)=>{const i=n[t];return{...e,[i]:[...e[i]||[],n]}},{})},invert:function(e){return Object.entries(e).reduce((e,[t,n])=>({...e,[String(n)]:t}),{})},join:function(e=[],t=""){return[...e].join(t)},json:function(e=null,t=0){return new c(JSON.stringify(e,null,t))},keys:function(e={}){return Object.keys(e)},last:function(e=[]){return[...e].reverse()[0]},length:function(e=""){return e.length},lower:function(e=""){return e.toLowerCase()},map:function(e=[],t,n){return e.map(e=>$(t)?n:e[t]??n)},max:function(e=0,...t){return Math.max(e,...t)},merge:function(e,...t){return Object.assign({},e,...t)},min:function(e=0,...t){return Math.min(e,...t)},mul:function(e=0,t=1){return e*t},odd:function(e=0){return+e%2==1},omit:function(e={},...t){return Object.entries(e).reduce((e,[n,i])=>t.includes(n)?e:{...e,[n]:i},{})},percent:function(e,t=0){return`${(100*e).toFixed(t)}%`},pick:function(e={},...t){return t.reduce((t,n)=>$(n)?t:{...t,[n]:e[n]},{})},pluck:function(e,t){return e.map(e=>e[t])},repeat:function(e="",t=0){return e.repeat(t)},replace:function(e="",t,n){return e.replace(new RegExp(t,"g"),n)},reverse:function(e=[]){return Array.isArray(e)?[...e].reverse():[...e].reverse().join("")},round:function(e,t=0){return Number(`${Math.round(Number(`${e}e${t}`))}e-${t}`)},safe:function(e=""){return new c(e)},shuffle:function(e){const t=[...e];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t},slice:function(e="",t=0,n){return e.slice(t,n)},slugify:function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")},sort:function(e=[]){return Array.isArray(e)?[...e].sort():[...e].sort().join("")},split:function(e="",t=""){return e.split(t)},stripTags:function(e){return e.replace(/<[^>]*>/g,"")},sub:function(e=0,t=0){return e-t},sum:function(e=[]){return e.reduce((e,t)=>e+t,0)},timeAgo:function(e){const t=e instanceof Date?e:new Date(e),n=new Date,i=Math.floor((n.getTime()-t.getTime())/1e3),r=[{label:"year",seconds:31536e3},{label:"month",seconds:2592e3},{label:"day",seconds:86400},{label:"hour",seconds:3600},{label:"minute",seconds:60}];for(const e of r){const t=Math.floor(i/e.seconds);if(t>=1)return`${t} ${e.label}${t>1?"s":""} ago`}return"just now"},trim:function(e=""){return e.trim()},truncate:function(e="",t=0,n="..."){return e.slice(0,t)+(e.length>t?n:"")},unique:function(e=""){return Array.isArray(e)?Array.from(new Set(e)):Array.from(new Set(e)).join("")},upper:function(e=""){return e.toUpperCase()},urldecode:function(e=""){return decodeURIComponent(e)},urlencode:function(e=""){return encodeURIComponent(e)},values:function(e={}){return Object.values(e)},wordCount:function(e){return e.trim().split(/\s+/).filter(Boolean).length}});const te={filters:{},parsers:{},compilers:{},plugins:[],debug:e=>{throw e}},ne={...te,commentOpen:"{{#",commentClose:"#}}",directiveOpen:"{{",directiveClose:"}}",outputOpen:"{{=",outputClose:"}}"},ie={...ne,trimWhitespace:!1,stripComments:!1,loader:async()=>"",preloadIncludes:[]},re={...ie,globals:{},autoEscape:!0,cache:{enabled:!0,maxSize:1e3,ttl:36e5,revalidate:!0},security:{}},se=(e,...t)=>{const n={...e},i=e=>{n.filters={...n.filters,...e.filters},n.parsers={...n.parsers,...e.parsers},n.compilers={...n.compilers,...e.compilers}};return e.plugins?.forEach(i),t.forEach(({plugins:e,filters:t,parsers:r,compilers:s,...o})=>{for(const[e,t]of Object.entries(o))void 0!==t&&(n[e]=t);i({filters:t,parsers:r,compilers:s}),e?.forEach(i)}),n};const oe={BLOCK:async function({val:{value:e},loc:t},n){const i=JSON.stringify(e);n.pushRaw(t,`if(b[${i}]&&!(b[${i}].u++)){`,`s+=await b[${i}].s?.pop()?.()??"";`,"}")},SUPER:async function({loc:e},t){t.state.block?t.pushRaw(e,`s+=await b[${JSON.stringify(t.state.block)}]?.s?.pop()?.()??"";`):t.options.debug?.(new i('"super" should be used inside a block',t.template,e))}};class ae extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BLOCK"})}}class le extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SUPER"})}}const ce={compilers:oe,parsers:{block:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endblock"]);t.match(["endblock"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ae(t.parseExp(e.expression),n,e.loc,e.strip)},super:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new le(e.val,e.loc,e.strip))},endblock:"unexpected"}},ue={AND:"&&",OR:"||",IS:"",NOT:"!",EQ:"===",NE:"!==",GT:">",LT:"<",GE:">=",LE:"<=",IN:" in ",NI:" in ",OF:" of ",WITH:" with ",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",ID:"",LIT:"",IF:"",ELSE:""},pe=new Set(Object.getOwnPropertyNames(Object.prototype));class he{constructor(){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}compile(e,t=y,n=g){return this.context=t,this.filters=n,e?this.compileExp(e):'""'}compileExp(e){switch(e.type){case"NOT":return this.compileNot(e);case"ID":return this.compileId(e);case"LIT":return this.compileLit(e);case"PIPE":return this.compilePipe(e);case"ASSIGN":return this.compileAssign(e);case"IS":return this.compileIs(e);case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.compileBinary(e);case"IF":return this.compileTernary(e);case"SEQ":return this.compileSeq(e);default:return""}}compileNot({argument:e}){return`!${this.compileExp(e)}`}compileId({value:e,path:t,args:n}){let i=pe.has(e)?`(Object.hasOwn(${this.context},"${e}")?${this.context}.${e}:undefined)`:`${this.context}.${e}`;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=`(${this.compileArgs(n).join(",")})`),i}compileArgs(e){const t=[],n=[];for(const i of e)if("ASSIGN"===i.type){const{left:e,right:t}=i;n.push(`${e.value}:${this.compileExp(t)}`)}else t.push(this.compileExp(i));return n.length&&t.push(`{${n.join(",")}}`),t}compileLit({value:e}){return void 0===e?"undefined":"number"==typeof e&&e<0?`(${e})`:JSON.stringify(e)}compileSeq({elements:e}){return`(${e.map(e=>this.compileExp(e)).join(",")})`}compilePipe({left:e,right:t}){const{value:n,args:i=[]}=t,r=`(${this.filters}.${n}||u_("${n}")).call(${[this.context,this.compileExp(e),...this.compileArgs(i)].join(",")})`;return`(${w}=${r},${w} instanceof Promise?await ${w}:${w})`}compileAssign({left:e,right:t}){return"ID"===e.type?`Object.assign(${this.context},{${e.value}:${this.compileExp(t)}});`:`Object.assign(${this.context},${this.filters}.pick.call(${this.context},${this.compileExp(t)},${e.elements.map(({value:e})=>`"${e}"`).join(",")}));`}compileIs({left:e,right:t}){return`typeof ${this.compileExp(e)}===${this.compileExp(t)}`}compileBinary({type:e,left:t,right:n}){const i=`${this.compileExp(t)}${ue[e]}${this.compileExp(n)}`;return"NI"===e?`!(${i})`:i}compileTernary({test:e,consequent:t,alternative:n}){return`${this.compileExp(e)}?${this.compileExp(t)}:${n?this.compileExp(n):'""'}`}}const fe={CALL:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`s+=await ${(new he).compile(e,i.context)}(async()=>{`,'let s="";'),await i.compileNodes(t),i.pushRaw(null,"return s;",'})??"";')}};class de extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALL"})}}const be={compilers:fe,parsers:{call:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcall"]);t.match(["endcall"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new de(t.parseExp(e.expression),n,e.loc,e.strip)},endcall:"unexpected"}};const me={CAPTURE:async function({val:e,body:t,loc:n},i){i.pushRaw(n,`${i.context}.${e.value}=${g}.safe.call(${i.context},await(async(s)=>{`),await i.compileNodes(t),i.pushRaw(null,'return s;})(""));')}};class ye extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CAPTURE"})}}const ge={compilers:me,parsers:{capture:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endcapture"]);t.match(["endcapture"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ye(t.parseExp(e.expression),n,e.loc,e.strip)},endcapture:"unexpected"}};const we={COMMENT:async function({val:e,loc:t},n){n.options.stripComments||n.pushStr(t,`\x3c!--${e}--\x3e`)}};class ve extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"COMMENT"})}}const xe={compilers:we,parsers:{comment:function*({val:e,loc:t,strip:n}){yield"NEXT",yield new ve(e,t,n)}}},Oe="loop:{first:i_===0,index:i_++,last:i_===n_}";function Ee(e,t=new Set){return!(!e||"object"!=typeof e||t.has(e))&&(t.add(e),"ASSIGN"===e.type||Object.entries(e).some(([e,n])=>"args"===e&&Array.isArray(n)?n.some(e=>Ee("ASSIGN"===e.type?e.right:e,t)):Ee(n,t)))}function Pe(e){return e.every(e=>{switch(e.type){case"TEXT":case"COMMENT":case"BREAK":case"CONTINUE":return!0;case"OUTPUT":return!Ee(e.val);case"IF":return!Ee(e.test)&&Pe(e.body)&&e.alternatives.every(e=>!Ee(e.test)&&Pe(e.body));case"FOR":return!Ee(e.loop.right)&&Pe(e.alternative?.body??[]);default:return!1}})}const je={FOR:async function({loop:{left:e,right:t,loc:n},body:i,alternative:r},s){const{context:o}=s,a=new he;s.pushRaw(n,"{",`const t_=${a.compile(t,o)},`,"a_=Array.isArray(t_)?t_:Array.from(t_??[]),n_=a_.length;"),r&&(s.pushRaw(n,"if(!n_){"),await s.compileNodes(r.body),s.pushRaw(n,"}else{"));const l="SEQ"===e.type?e.elements.map(e=>"ASSIGN"===e.type?[e.left.value,`v_.${e.left.value}===undefined?${a.compile(e.right,o)}:v_.${e.left.value}`]:[e.value,`v_.${e.value}`]):[[e.value,"v_"]],c=s.in();s.pushRaw(n,"let i_=0;");const{maxLoopIterations:p}=u(s.options.security),h=null==p?[]:[`if(++li_>${p})throw new Error(${JSON.stringify(`Loop iteration limit of ${p} exceeded`)});`];Pe(i)?s.pushRaw(n,`const ${c}={...${o}};`,"for(const v_ of a_){",...h,`${c}.loop={${Oe.slice(6)};`,...l.map(([e,t])=>`${c}.${e}=${t};`)):s.pushRaw(n,"for(const v_ of a_){",...h,`const ${c}={`,`...${o},`,`${Oe},`,...l.map(([e,t])=>`${e}:${t},`),"};"),await s.compileNodes(i),s.out(),s.flushable&&s.pushFlush(),s.pushRaw(null,r?"}}}":"}}")},BREAK:function({loc:e},t){t.pushRaw(e,"break;")},CONTINUE:function({loc:e},t){t.pushRaw(e,"continue;")}};class Te extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternative",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"FOR"})}traverse(e){this.body.forEach(e),this.alternative?.body.forEach(e)}}let $e=class extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}};class ke extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"BREAK"})}}class Se extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CONTINUE"})}}const Ie=new WeakMap;const Ne={for:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Ie.set(t,!0),yield"NEXT";const n=t.parseUntil(["else","endfor"]);Ie.set(t,!1);let r=null;if(t.match(["else"])){const e=function*(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endfor"]);yield"NEXT",yield new $e(t.parseUntil(["endfor"]),e.loc,e.strip)}(t.peek(),t);for(;;){const{value:t,done:n}=e.next();if(n)break;if(t){if("NEXT"===t){yield"NEXT";continue}r=t}}}t.match(["endfor"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const s=t.parseExp(e.expression);"OF"===s?.type?yield new Te(s,n,r,e.loc,e.strip):s&&t.options.debug?.(new i(`"${e.name}" expects "item of items"`,t.template,e.loc))},break:function*(e,t){e.expression?t.emitExpErr(e,!1):Ie.get(t)?(yield"NEXT",yield new ke(e.val,e.loc,e.strip)):t.options.debug?.(new i('"break" directive used outside of a loop',t.template,e.loc))},continue:function*(e,t){e.expression?t.emitExpErr(e,!1):Ie.get(t)?(yield"NEXT",yield new Se(e.val,e.loc,e.strip)):t.options.debug?.(new i('"continue" directive used outside of a loop',t.template,e.loc))},endfor:"unexpected"},Ce={compilers:je,parsers:Ne};const Le={IF:async function({test:e,body:t,alternatives:n},i){i.pushRaw(e.loc,`if(${(new he).compile(e,i.context)}){`),await i.compileNodes(t),i.pushRaw(null,"}");for(const e of n)"ELSE_IF"===e.type?i.pushRaw(e.test.loc,`else if(${(new he).compile(e.test,i.context)}){`):i.pushRaw(null,"else{"),await i.compileNodes(e.body),i.pushRaw(null,"}")}};class Re extends G{constructor(e,t,n,i,r){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"alternatives",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"IF"})}traverse(e){this.body?.forEach(e),this.alternatives?.forEach(t=>t.body?.forEach(e))}}class De extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"test",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE_IF"})}}class Ae extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"ELSE"})}}function*Me(e,t){if(!e.expression)return t.emitExpErr(e),yield"NEXT",void t.parseUntil(["else","elseif","elsif","elif","endif"]);yield"NEXT",yield new De(t.parseExp(e.expression),t.parseUntil(["else","elseif","elsif","elif","endif"]),e.loc,e.strip)}function*Ue(e,t){if(e.expression)return t.emitExpErr(e,!1),yield"NEXT",void t.parseUntil(["endif"]);yield"NEXT",yield new Ae(t.parseUntil(["endif"]),e.loc,e.strip)}const _e={compilers:Le,parsers:{if:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["else","elseif","elsif","elif","endif"]),r=[];for(;t.match(["else","elseif","elsif","elif"]);){const e=t.peek();if("else"===e.name.toLowerCase()){const n=Ue(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}else{const n=Me(e,t);for(;;){const{value:e,done:t}=n.next();if(t)break;if(e){if("NEXT"===e){yield"NEXT";continue}r.push(e)}}}}t.match(["endif"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new Re(t.parseExp(e.expression),n,r,e.loc,e.strip)},elseif:"unexpected",elsif:"unexpected",elif:"unexpected",endif:"unexpected"}};const Fe=/\s+(once|last)\s*$/;const We={compilers:{INCLUDE:async function({val:e,loc:t,withExp:n,modifier:i},r){const s=new he,o=J(e)?JSON.stringify(e.value):s.compile(e,r.context),a=n?`s+=await p[${o}]?.({...${r.context},...${s.compile(n,r.context)}})??"";`:`s+=await p[${o}]?.(tc_)??"";`;if("once"!==i){if("last"===i&&J(e)){const t=r.state.includeLast,n=t?.get(e.value);if(n&&(n.emitted+=1,n.emitted<n.total))return}r.pushRaw(t,a)}else r.pushRaw(t,`if(!inc_[${o}]){inc_[${o}]=1;${a}}`)}},parsers:{include:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";let n=e.expression.val,i=null;const r=Fe.exec(n);r&&(i=r[1],n=n.slice(0,r.index));const s=t.parseExp({val:n,loc:e.expression.loc});if(s){if("WITH"===s.type){const{left:t,right:n}=s;return void(yield new V(t,e.loc,e.strip,n,i))}yield new V(s,e.loc,e.strip,null,i)}}}};const Xe={MACRO:async function({val:{value:e,args:t},loc:n,body:i},r){const{context:s}=r,o=new he,{maxCallDepth:a}=u(r.options.security);r.pushRaw(n,`${s}.${e}=(...a_)=>async(_c)=>{`,...null==a?[]:[`if(cd_>=${a})throw new Error(${JSON.stringify(`Macro call depth limit of ${a} exceeded`)});`,"cd_++;","try{"],'let s="";',`const ${r.in()}={`,`...${s},`,...(t??[]).map((e,t)=>"ASSIGN"===e.type?`${e.left.value}:a_[${t}]===undefined?${o.compile(e.right)}:a_[${t}],`:`${e.value}:a_[${t}],`),"};"),await r.compileNodes(i),r.out(),r.pushRaw(null,"return s;",...null==a?[]:["}finally{cd_--;}"],"};")},CALLER:function({loc:e},t){t.pushRaw(e,'s+=await _c?.()??"";')}};class Ge extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"MACRO"})}}class ze extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"CALLER"})}}const Be=new WeakMap;const qe={compilers:Xe,parsers:{macro:function*(e,t){if(!e.expression)return void t.emitExpErr(e);Be.set(t,!0),yield"NEXT";const n=t.parseUntil(["endmacro"]);Be.set(t,!1),t.match(["endmacro"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc));const r=t.parseExp(e.expression);if("ID"===r.type){if(r.args?.length)for(const n of r.args)if("ASSIGN"===n.type){if("ID"!==n.left.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc))}else if("ID"!==n.type)return void t.options.debug?.(new i("Invalid macro parameter definition",t.template,e.loc));yield new Ge(r,n,e.loc,e.strip)}else t.options.debug?.(new i("Invalid macro definition",t.template,e.loc))},caller:function*(e,t){e.expression?t.emitExpErr(e,!1):Be.get(t)?(yield"NEXT",yield new ze(e.val,e.loc,e.strip)):t.options.debug?.(new i('"caller" directive used outside of a macro',t.template,e.loc))},endmacro:"unexpected"}};const Ke={OUTPUT:async function({val:e},t){t.pushVar(e.loc,(new he).compile(e,t.context))}};class He extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"OUTPUT"})}}const Je={compilers:Ke,parsers:{output:function*(e,t){yield"NEXT";const n=P(`${t.options.outputOpen}${e.strip.before?"-":""}`,{...e.loc.start});yield new He(t.parseExp({val:e.val,loc:{start:n,end:e.loc.end}}),e.loc,e.strip)}}};const Ve={SET:async function({val:e,loc:t},n){n.pushRaw(t,(new he).compile(e,n.context))}};class Qe extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"SET"})}}const Ye={compilers:Ve,parsers:{set:function*(e,t){e.expression?(yield"NEXT",yield new Qe(t.parseExp(e.expression),e.loc,e.strip)):t.emitExpErr(e)}}};const Ze={STYLESHEET:async function(){},STYLESHEETS:async function({loc:e},t){t.pushRaw(e,"if(!ss_u++){","for(const f_ of ss_)s+=await f_();","}")}};class et extends G{constructor(e,t,n){super(),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEET"})}}class tt extends G{constructor(e,t){super(),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"STYLESHEETS"})}}const nt={compilers:Ze,parsers:{stylesheet:function*(e,t){if(e.expression)return void t.emitExpErr(e,!1);yield"NEXT";const n=t.parseUntil(["endstylesheet"]);t.match(["endstylesheet"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new et(n,e.loc,e.strip)},endstylesheet:"unexpected",stylesheets:function*(e,t){e.expression?t.emitExpErr(e,!1):(yield"NEXT",yield new tt(e.loc,e.strip))}}};const it={TEXT:async function({val:e,loc:t,strip:{start:n,end:i}},r){(n||r.options.trimWhitespace)&&(e=e.replace(/^\s+/,"")),(i||r.options.trimWhitespace)&&(e=e.replace(/\s+$/,"")),r.pushStr(t,e)}};class rt extends G{constructor(e,t,n){super(),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"TEXT"})}}const st={compilers:it,parsers:{text:function*(e){yield"NEXT",yield new rt(e.val,e.loc,e.strip)}}};const ot={UNEXPECTED:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unexpected "${e}"--\x3e`)}};class at extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNEXPECTED"})}}const lt={compilers:ot,parsers:{unexpected:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unexpected "${n}"`,t.template,e.loc)),yield"NEXT",yield new at(n,e.val,e.loc,e.strip)}}};const ct={UNKNOWN:async function({name:e,loc:t},n){n.pushStr(t,`\x3c!--Unknown "${e}"--\x3e`)}};class ut extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"val",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"UNKNOWN"})}}const pt={compilers:ct,parsers:{unknown:function*(e,t){const n=e.name??e.type;t.options.debug?.(new i(`Unknown "${n}"`,t.template,e.loc)),yield"NEXT",yield new ut(n,e.val,e.loc,e.strip)}}};const ht={WITH:async function(e,t){const{context:n}=t,i=new he;t.pushRaw(e.loc,`const ${t.in()}={...${i.compile(e.expression,n)}};`),await t.compileNodes(e.body),t.out()}};class ft extends G{constructor(e,t,n,i){super(),Object.defineProperty(this,"expression",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"loc",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"strip",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:"WITH"})}traverse(e){this.body?.forEach(e)}}const dt=[ce,be,xe,ge,Ce,_e,We,qe,Ye,nt,st,Je,lt,pt,{parsers:{with:function*(e,t){if(!e.expression)return void t.emitExpErr(e);yield"NEXT";const n=t.parseUntil(["endwith"]);t.match(["endwith"])?yield"NEXT":t.options.debug?.(new i(`Unclosed "${e.name}"`,t.template,e.loc)),yield new ft(t.parseExp(e.expression),n,e.loc,e.strip)},endwith:"unexpected"},compilers:ht}];class bt extends i{constructor(e,t,n,i){super(e,t,void 0,i),Object.defineProperty(this,"src",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"getLoc",{enumerable:!0,configurable:!0,writable:!0,value:n}),this.name="RenderError",bt.captureStackTrace?.(this,this.constructor)}get details(){return this.loc=this.getLoc(),super.details}}const mt=new Error("Stream cancelled");class yt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sandbox",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"escape",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiling",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.options=se(re,{filters:ee,plugins:dt},e),this.filters=Object.assign(Object.create(null),this.options.filters);const n=this.options.security?.deepEscape?h:l,{autoEscape:i}=this.options;this.escape=e=>"string"==typeof e?i?l(e):e:null==e?"":e instanceof c?`${e}`:i?n(e):e,!1!==this.options.cache?.enabled&&(this.cache=new t(this.options.cache)),this.options.security?.sandbox&&(this.sandbox=new p(this.options.security))}async render(e,t){const n=this.cache?.peek(b(e));if(n?.script&&0===n.sources.size&&n.fingerprint===m(this.options)){this.cache.get(b(e));try{return await this.run(n.script,t)}catch(t){const i=new v;return i.mappings=n.mappings,this.options.debug(this.wrapError(t,e,i)),""}}let i;try{return i=await this.compile(e),await this.run(i.script,t)}catch(t){this.options.debug(this.wrapError(t,e,i??new v))}return""}template(e){return t=>this.render(e,t)}async renderCompiled(e,t={}){try{return await this.run(e,t)}catch(e){this.options.debug(e)}return""}renderStream(e,t={}){let n,i=!1;return new ReadableStream({start:r=>{const s=e=>{if(i)throw mt;if(r.enqueue(e),(r.desiredSize??1)<=0)return new Promise(e=>{n=e})};let o;(async()=>{try{o=await this.compile(e,!0);const n=await this.run(o.script,t,s);n&&!i&&r.enqueue(n),r.close()}catch(t){if(t===mt)return;try{this.options.debug(this.wrapError(t,e,o??new v)),r.close()}catch(e){r.error(e)}}})()},pull:()=>{n?.(),n=void 0},cancel:()=>{i=!0,n?.()}})}compile(e,t=!1){const n=b(e,t);let i=this.compiling.get(n);return i||(i=new Z(this.options,this.cache,this.options.cache?.revalidate??!0,t).compile(e).finally(()=>this.compiling.delete(n)),this.compiling.set(n,i)),i}wrapError(e,t,n){return"CompileError"===e?.name?e:new bt(`${e?.message??e}`,t,()=>{const t=e?.stack?.match(/<anonymous>:(\d+):(\d+)\)/);if(!t)return e?.stack??"";const[i]=n.getSourceLoc({line:+t[1]-2,column:+t[2]});return i})}run(e,t,n){const i=e(this.sandbox?{...this.sandbox.createSecureContext(this.options.globals),...t}:{...this.options.globals,...t},this.escape,this.filters,n),{timeoutMs:r}=this.options.security??{};if(null==r)return i;let s;return Promise.race([Promise.resolve(i).finally(()=>{clearTimeout(s)}),new Promise((e,t)=>{s=setTimeout(()=>{t(new Error(`Render timed out after ${r}ms`))},r)})])}async renderFile(e,t){return this.render(await this.options.loader(e),t)}clearCache(){this.cache?.clear()}invalidateCache(e){this.cache?.invalidate(e)}getCacheStats(){return this.cache?this.cache.getStats():null}resetCacheStats(){this.cache?.resetStats()}auditTemplate(e){return(new f).auditTemplate(e)}getCSPHeaders(){return new p(this.options.security).generateCSPHeaders()}}class gt{constructor(e){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"variables",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"includes",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"blocks",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"macros",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}async analyze(e,t=new Set){const n=new H(this.options).parse(e);await this.nodes(n.body,t)}async nodes(e=[],t){for(const n of e)await this.node(n,t)}async node(e,t){switch(e.type){case"OUTPUT":this.exp(e.val,t);break;case"IF":this.exp(e.test,t),await this.nodes(e.body,t);for(const n of e.alternatives)this.exp(n.test,t),await this.nodes(n.body,t);break;case"FOR":{this.exp(e.loop.right,t),await this.nodes(e.alternative?.body,t);const n=new Set(t).add("loop");this.bind(e.loop.left,n,t),await this.nodes(e.body,n);break}case"SET":this.exp(e.val.right,t),this.bind(e.val.left,t,t);break;case"CAPTURE":await this.nodes(e.body,t),t.add(e.val.value);break;case"MACRO":{const n=new Set(t);for(const i of e.val.args??[])this.bind(i,n,t);t.add(e.val.value),this.macros.add(e.val.value),await this.nodes(e.body,n);break}case"CALL":this.exp(e.val,t),await this.nodes(e.body,t);break;case"WITH":this.exp(e.expression,t),await this.nodes(e.body,wt);break;case"BLOCK":this.blocks.add(e.val.value),await this.nodes(e.body,t);break;case"STYLESHEET":default:await this.nodes(e.body,t);break;case"INCLUDE":this.exp(e.val,t),e.withExp&&this.exp(e.withExp,t),"LIT"===e.val.type&&"string"==typeof e.val.value&&await this.include(e.val.value,t)}}async include(e,t){if(this.includes.has(e))return;let n;this.includes.add(e);try{n=await this.options.loader(e)}catch{}n&&await this.analyze(n,new Set(t))}bind(e,t,n){"ID"===e.type?t.add(e.value):"SEQ"===e.type?e.elements.forEach(e=>this.bind(e,t,n)):"ASSIGN"===e.type&&(this.exp(e.right,n),this.bind(e.left,t,n))}exp(e,t){if(e)switch(e.type){case"ID":t===wt||t.has(e.value)||this.variables.add(e.value),e.args?.forEach(e=>this.exp(e,t));break;case"LIT":break;case"NOT":this.exp(e.argument,t);break;case"IF":this.exp(e.test,t),this.exp(e.consequent,t),this.exp(e.alternative,t);break;case"SEQ":e.elements.forEach(e=>this.exp(e,t));break;case"PIPE":{const{left:n,right:i}=e;this.exp(n,t),this.filters.add(i.value);for(const e of i.args??[])this.exp("ASSIGN"===e.type?e.right:e,t);break}default:this.exp(e.left,t),this.exp(e.right,t)}}}const wt=new Set;async function vt(e,t={}){const n=new gt(se(ie,{filters:ee,plugins:dt},t));await n.analyze(e);const i=e=>[...e].sort();return{variables:i(n.variables),filters:i(n.filters),includes:i(n.includes),blocks:i(n.blocks),macros:i(n.macros)}}function xt({variables:e},{includeRuntime:t=!1}={}){const n=e.map(e=>` ${e}?: unknown;`).join("\n");return`// Generated by the Janja precompiler. Do not edit.\nimport type { ${t?"RendererOptions, ":""}Script } from 'janja';\n\n/** The data this template reads. */\nexport interface TemplateData {${n?`\n${n}\n`:""}}\n\nexport declare const script: Script;\n\n${t?"export default function render(\n data?: TemplateData,\n options?: RendererOptions,\n): Promise<string>;":"export default script;"}\n`}function Ot(e){let t=e<0?-e<<1|1:e<<1,n="";do{let e=31&t;t>>>=5,t>0&&(e|=32),n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]}while(t>0);return n}function Et(e,{file:t,source:n,sourceContent:i,line:r}){const s=new Map;for(const t of e)s.set(t.target.start.column,t.source.start);let o=0,a=0,l=0;const c=[...s.entries()].sort(([e],[t])=>e-t).map(([e,t])=>{const n=t.line-1,i=t.column-1,r=Ot(e-o)+Ot(0)+Ot(n-a)+Ot(i-l);return o=e,a=n,l=i,r}).join(",");return{version:3,...t?{file:t}:{},sources:[n],sourcesContent:[i],names:[],mappings:`${";".repeat(r)}${c}`}}async function Pt(e,{includeRuntime:t,sourceMap:n,filename:i,dts:r,...s}={}){const o=new Z(se(ie,{filters:ee,plugins:dt},s));await o.compile(e);const a=`// Generated by the Janja precompiler. Do not edit.${t?"\nimport { renderCompiled } from 'janja';\n":""}\nexport function script(${y}, e, ${g}, w) {\n`,l=t?"\n}\n\nexport default function render(globals = {}, options) {\n return renderCompiled(script, globals, options);\n}\n":"\n}\n\nexport default script;\n";return{code:`${a}${o.code}${l}`,map:n?Et(o.mappings,{source:i??"template.janja",sourceContent:e,line:a.split("\n").length-1}):void 0,dts:r?xt(await vt(e,s),{includeRuntime:t}):void 0}}class jt{constructor(e={}){Object.defineProperty(this,"defaultLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentLocale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"translations",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pluralRules",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.locale||this.defaultLocale,this.translations=e.translations||{},this.pluralRules=e.pluralRules||this.getDefaultPluralRules()}setLocale(e){this.currentLocale=e}getLocale(){return this.currentLocale}addTranslations(e,t){this.translations[e]||(this.translations[e]={}),this.translations[e]=this.mergeDeep(this.translations[e],t)}translate(e,t={}){const n=this.getTranslation(e);return n?this.interpolate(n,t):e}t(e,t={}){return this.translate(e,t)}pluralize(e,t,n={}){const i=`${e}.${this.getPluralForm(t)}`,r=this.getTranslation(i);if(r)return this.interpolate(r,{...n,count:t});const s=this.getTranslation(e);return s?this.interpolate(s,{...n,count:t}):e}formatDate(e,t){const n="string"==typeof e?new Date(e):e;return new Intl.DateTimeFormat(this.currentLocale,t).format(n)}formatNumber(e,t){return new Intl.NumberFormat(this.currentLocale,t).format(e)}formatCurrency(e,t,n){return new Intl.NumberFormat(this.currentLocale,{...n,style:"currency",currency:t}).format(e)}getTranslation(e){const t=e.split(".");let n=this.translations[this.currentLocale];for(const e of t){if(!n||"object"!=typeof n||!(e in n))return null;n=n[e]}return"string"==typeof n?n:null}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>void 0!==t[n]?String(t[n]):n)}getPluralForm(e){const t=this.pluralRules[this.currentLocale];return t?t(e):this.pluralRules[this.defaultLocale](e)}getDefaultPluralRules(){return{en:e=>1===e?"one":"other",es:e=>1===e?"one":"other",fr:e=>0===e||1===e?"one":"other",de:e=>1===e?"one":"other",ru:e=>{const t=e%10,n=e%100;return 1===t&&11!==n?"one":t>=2&&t<=4&&!(n>=12&&n<=14)?"few":0===t||t>=5&&t<=9?"many":"other"},ja:()=>"other",zh:()=>"other",ar:e=>0===e?"zero":1===e?"one":2===e?"two":e%100>=3&&e%100<=10?"few":e%100>=11&&e%100<=99?"many":"other"}}mergeDeep(e,t){const n={...e};return this.isObject(e)&&this.isObject(t)&&Object.keys(t).forEach(i=>{this.isObject(t[i])?i in e?n[i]=this.mergeDeep(e[i],t[i]):Object.assign(n,{[i]:t[i]}):Object.assign(n,{[i]:t[i]})}),n}isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}}const Tt=new jt;async function $t(e,t={}){let n="";const{data:i={},options:r}=t,s=new yt(r);for(const t of e)n=await s.render(t,{...i,_content:n});return n}const kt={trim:!1,stripComments:!1,collapseWhitespace:!1,preserveNewlines:!0};function St(e){return{...kt,...e}}class It{constructor(){Object.defineProperty(this,"mixins",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}register(e){this.mixins.set(e.name,e)}registerMultiple(e){for(const t of e)this.register(t)}get(e){return this.mixins.get(e)}has(e){return this.mixins.has(e)}delete(e){return this.mixins.delete(e)}clear(){this.mixins.clear()}list(){return Array.from(this.mixins.keys())}}const Nt=new It;async function Ct(e,t={},n=Nt){const i=n.get(e);if(!i)throw new Error(`Mixin "${e}" not found in registry`);const{data:r={},options:s}=t,o={...i.data,...r};return new yt(s).render(i.template,o)}class Lt{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:e})}async validate(e){const t=[],n=[],i=e=>{const[n]=e?.suggestions??[];t.push({type:"error",message:`${e?.message??e}`,line:e?.loc?.start.line,column:e?.loc?.start.column,suggestion:n?.fix??n?.message})},r=se(ie,{filters:ee,plugins:dt},this.options,{debug:i});try{const t=new H(r).parse(e);this.checkFilters(t,r.filters,n)}catch(e){i(e)}return{valid:0===t.length,errors:t,warnings:n}}checkFilters(e,t,n,i=new Set){if(e&&"object"==typeof e&&!i.has(e)){i.add(e),"PIPE"!==e.type||"ID"!==e.right?.type||Object.prototype.hasOwnProperty.call(t,e.right.value)||n.push({type:"warning",message:`Unknown filter "${e.right.value}"`,line:e.right.loc?.start.line,column:e.right.loc?.start.column});for(const r of Object.values(e))this.checkFilters(r,t,n,i)}}}const Rt={AND:"and",OR:"or",IS:"is",NOT:"not",EQ:"eq",NE:"ne",GT:"gt",LT:"lt",GE:"ge",LE:"le",IN:"in",NI:"ni",OF:"of",WITH:"with",ADD:"+",SUB:"-",MUL:"*",DIV:"/",MOD:"%",PIPE:"|",ASSIGN:"=",LP:"(",RP:")",COMMA:",",DOT:".",IF:"if",ELSE:"else"};class Dt{format(e){return e?this.formatExp(e):'""'}formatExp(e){switch(e.type){case"NOT":return this.formatNot(e);case"ID":return this.formatId(e);case"LIT":return this.formatLit(e);case"PIPE":case"IS":case"ASSIGN":case"AND":case"OR":case"EQ":case"NE":case"GT":case"LT":case"GE":case"LE":case"IN":case"NI":case"OF":case"WITH":case"ADD":case"SUB":case"MUL":case"DIV":case"MOD":return this.formatBinary(e);case"IF":return this.formatTernary(e);case"SEQ":return this.formatSeq(e);default:return""}}formatNot({argument:e}){return`${Rt.NOT} ${this.formatExp(e)}`}formatId({value:e,path:t,args:n}){let i=e;return t&&(i+=t.map(e=>`.${e.value}`).join("")),n&&(i+=this.formatSeq({elements:n})),i}formatLit({value:e}){return void 0===e?"undefined":JSON.stringify(e)}formatSeq({elements:e}){return`(${e.map(e=>this.formatExp(e)).join(", ")})`}formatBinary({type:e,left:t,right:n}){return`${this.formatExp(t)} ${Rt[e]} ${this.formatExp(n)}`}formatTernary({test:e,consequent:t,alternative:n}){return`${this.formatExp(t)} ${Rt.IF} ${this.formatExp(e)}${n?` ${Rt.ELSE} ${this.formatExp(n)}`:""}`}}function At(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=Mt(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function Mt(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if('"'!==s&&"'"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1}return{opens:t,closes:n}}function Ut(e,t){const n=" ".repeat(Math.max(0,t)),i=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/);let s=0;const o=[];for(const e of r){const t=e.trim();if(0===t.length){o.push("");continue}const{opens:i,closes:r}=_t(t),a=r>i?Math.max(0,s-(r-i)):s;o.push(n.repeat(a)+t),s=Math.max(0,s+i-r)}return o.join(i)}function _t(e){let t=0,n=0,i=null,r=0;for(;r<e.length;){const s=e[r];if(i){if("\\"===s){r+=2;continue}s===i&&(i=null),r+=1}else if("{"!==s||"{"!==e[r+1])if('"'!==s&&"'"!==s&&"`"!==s){if("/"===s&&"*"===e[r+1]){const t=e.indexOf("*/",r+2);r=-1===t?e.length:t+2;continue}if("/"===s&&"/"===e[r+1])break;"{"===s?t+=1:"}"===s&&(n+=1),r+=1}else i=s,r+=1;else r=Ft(e,r)}return{opens:t,closes:n}}function Ft(e,t){if(e.startsWith("{{#",t)){const n=e.indexOf("#}}",t+3);return-1===n?e.length:n+3}const n=e.indexOf("}}",t+2);return-1===n?e.length:n+2}const Wt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Xt=new Set(["pre","textarea","script","style"]),Gt=new Set(["script","style"]),zt=new Set(["if","for","macro","block","call","capture","with","stylesheet"]),Bt=new Set(["stylesheet"]),qt=new Set(["else","elif","elseif","elsif"]),Kt=new Set(["endif","endfor","endmacro","endblock","endcall","endcapture","endwith","endstylesheet"]);function Ht(e,t){const n=t.tabWidth??2,i=" ".repeat(Math.max(0,n)),r=e.includes("\r\n")?"\r\n":"\n",s=e.split(/\r?\n/);let o=0,a=null,l=null;const c=[],u={inComment:!1};for(const e of s){const s=e.match(/^[ \t]*/)?.[0].length??0,h=e.slice(s),{pieces:f,prefixClosers:d}=Jt(h,t,u),b=a,m=null!==b&&f.some(e=>"close"===e.kind&&e.sensitive===b),y="stylesheet"===b||null!==b&&Gt.has(b);if(y&&!m){(l??(l=[])).push(e);continue}if(l&&m&&y){const e="stylesheet"===b?Math.max(0,o-1):o,s=l.join(r),a="stylesheet"===b?Ht(s,t):"style"===b?At(s,n):Ut(s,n);for(const t of a.split(/\r?\n/))c.push(0===t.length?"":i.repeat(e)+t);l=null}else if(a&&!m){c.push(e),p(f);continue}const g=Math.max(0,o-d);c.push(0===h.length?"":i.repeat(g)+h),p(f)}return c.join(r);function p(e){for(const t of e)"open"===t.kind?(o+=1,t.sensitive&&!a&&({sensitive:a}=t)):"close"===t.kind?(o=Math.max(0,o-1),t.sensitive&&a===t.sensitive&&(a=null)):t.kind}}function Jt(e,t,n){const i=[];let r=0,s=!0,o=0;if(n.inComment){const s=e.indexOf(t.commentClose);if(-1===s)return{pieces:i,prefixClosers:r};n.inComment=!1,o=s+t.commentClose.length}for(;o<e.length;){if(/\s/.test(e[o])){o+=1;continue}if(e.startsWith(t.commentOpen,o)){const a=e.indexOf(t.commentClose,o+t.commentOpen.length);if(-1===a)return n.inComment=!0,{pieces:i,prefixClosers:r};s=!1,o=a+t.commentClose.length;continue}const a=Vt(e,o,t);a?(a.piece?(i.push(a.piece),!s||"close"!==a.piece.kind&&"mid"!==a.piece.kind?s=!1:r+=1):s=!1,o=a.end):(s=!1,o+=1)}return{pieces:i,prefixClosers:r}}function Vt(e,t,n){const{directiveOpen:i,outputOpen:r}=n;if(e.startsWith(r,t))return{end:Zt(e,t+r.length,n.outputClose)};if(e.startsWith(i,t))return function(e,t,n){const{directiveOpen:i,directiveClose:r}=n,s=Zt(e,t+i.length,r),o=e.slice(t+i.length,s-r.length),a=o.replace(/^\s*-?\s*/,"").match(/^([A-Za-z_]\w*)/)?.[1]?.toLowerCase();if(!a)return{end:s};if(Kt.has(a)){const e=a.startsWith("end")?a.slice(3):a;return{end:s,piece:{kind:"close",sensitive:Bt.has(e)?e:void 0}}}if(qt.has(a))return{end:s,piece:{kind:"mid"}};if(zt.has(a))return{end:s,piece:{kind:"open",sensitive:Bt.has(a)?a:void 0}};return{end:s}}(e,t,n);if(e.startsWith("\x3c!--",t)){const n=e.indexOf("--\x3e",t+4);return{end:-1===n?e.length:n+3}}return"<"===e[t]?function(e,t,n){if(e.startsWith("</",t)){let i=t+2;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=Qt(e,i,n);return!s||Wt.has(s)?{end:o}:{end:o,piece:{kind:"close",sensitive:Xt.has(s)?s:void 0}}}if(e.startsWith("<!",t)||e.startsWith("<?",t))return{end:Qt(e,t+2,n)};let i=t+1;for(;i<e.length&&/\s/.test(e[i]);)i+=1;const r=i;for(;i<e.length&&/[A-Za-z0-9:-]/.test(e[i]);)i+=1;const s=e.slice(r,i).toLowerCase(),o=Qt(e,i,n),a=e.slice(t,o),l=/\/\s*>$/.test(a)||Wt.has(s);if(!s||l)return{end:o};return{end:o,piece:{kind:"open",sensitive:Xt.has(s)?s:void 0}}}(e,t,n):null}function Qt(e,t,n){let i=t,r=null;for(;i<e.length;){const t=e[i];if(r){if(t===r)r=null;else{const t=Yt(e,i,n);if(null!==t){i=t;continue}}i+=1;continue}const s=Yt(e,i,n);if(null===s)if('"'!==t&&"'"!==t){if(">"===t)return i+1;i+=1}else r=t,i+=1;else i=s}return e.length}function Yt(e,t,n){const{commentOpen:i,commentClose:r,outputOpen:s,outputClose:o,directiveOpen:a,directiveClose:l}=n;return e.startsWith(i,t)?Zt(e,t+i.length,r):e.startsWith(s,t)?Zt(e,t+s.length,o):e.startsWith(a,t)?Zt(e,t+a.length,l):null}function Zt(e,t,n){const i=e.indexOf(n,t);return-1===i?e.length:i+n.length}const en=e=>JSON.stringify(e,(e,t)=>"loc"===e||"raw"===e?void 0:t??null);class tn{constructor(e={}){Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options={continueOnError:!1,undefinedFallback:"",ignoreMissingFilters:!1,onError:()=>{},...e}}safeEvaluate(e,t,n={}){try{const n=this.evaluateExpression(e,t);return void 0===n&&void 0!==this.options.undefinedFallback?this.options.undefinedFallback:n}catch(i){const r={template:n.template||"",data:t,expression:e},s=this.options.onError(i,r);if(this.options.continueOnError)return s;throw i}}safeApplyFilter(e,t,n,i=[],r={}){try{if(!n){if(this.options.ignoreMissingFilters)return e;throw new Error(`Filter "${t}" is not defined`)}return n(e,...i)}catch(e){const n={template:r.template||"",data:r.data||{},filter:t},i=this.options.onError(e,n);if(this.options.continueOnError)return i;throw e}}wrapRender(e,t={}){return(...n)=>{try{return e(...n)}catch(e){const i={template:t.template||"",data:n[1]||{}},r=this.options.onError(e,i);if(this.options.continueOnError)return r;throw e}}}evaluateExpression(e,t){try{const n=e.split(".");let i=t;for(const e of n){if(null==i)return;i=i[e]}return i}catch{return}}createSafeAccessor(e){return t=>{try{const n=t.split(".");let i=e;for(const e of n){if(null==i)return this.options.undefinedFallback;i=i[e]}return void 0===i?this.options.undefinedFallback:i}catch{return this.options.undefinedFallback}}}}let nn;const rn=new WeakMap;function sn(e){if(!e)return nn??(nn=new yt);let t=rn.get(e);return t||(t=new yt(e),rn.set(e,t)),t}e.CompileError=i,e.Compiler=Z,e.ErrorRecovery=tn,e.ExpCompiler=he,e.ExpError=E,e.ExpParser=M,e.ExpTokenizer=I,e.I18n=jt,e.MAX_INCLUDE_DEPTH=100,e.MixinRegistry=It,e.Parser=H,e.RenderError=bt,e.Renderer=yt,e.RootNode=z,e.Safe=c,e.SecurityAuditor=f,e.SecuritySandbox=p,e.TemplatePipeline=class{constructor(e){Object.defineProperty(this,"templates",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options=e}addTemplate(e){return this.templates.push(e),this}setData(e){return this.data={...this.data,...e},this}setOptions(e){return this.options={...this.options,...e},this}async execute(){return $t(this.templates,{data:this.data,options:this.options})}},e.TemplateValidator=Lt,e.Tokenizer=K,e.Traversal=G,e.analyzeTemplate=vt,e.applyMixin=Ct,e.applyMixins=async function(e,t={},n=Nt){const i=[];for(const r of e){const e=await Ct(r,t,n);i.push(e)}return i},e.applyWhitespaceControl=function(e,t){let n=e;return t.stripComments&&(n=n.replace(/<!--[\s\S]*?-->/g,"")),t.collapseWhitespace&&(n=t.preserveNewlines?n.replace(/[ \t]+/g," "):n.replace(/\s+/g," ")),t.trim&&(n=n.trim()),n},e.baseOptions=te,e.compilerOptions=ie,e.composeLayout=async function(e,t,n={}){const{data:i={},options:r}=n,s=new yt({...r,autoEscape:!1}),o=await s.render(t,i);return s.render(e,{...i,content:o})},e.composeTemplates=$t,e.composeTemplatesWithData=async function(e,t={}){let n="";const{options:i}=t,r=new yt(i);for(const t of e){const e={...t.data,_content:n};n=await r.render(t.template,e)}return n},e.composeWithSlots=async function(e,t,n={}){const{data:i={},options:r}=n,s=new yt({...r,autoEscape:!1}),o={};for(const[e,n]of Object.entries(t))o[e]=await s.render(n,i);return s.render(e,{...i,slots:o})},e.createErrorRecovery=function(e={}){return new tn(e)},e.createFileLoader=function(e,{extensions:t=[".janja",".html"]}={}){return async n=>{const{readFile:i}=await(import("node:fs/promises")),r=await(import("node:path")),s=r.resolve(e),o=r.extname(n)?[n]:[...t.map(e=>`${n}${e}`),n];for(const e of o){const t=r.resolve(s,e);if(!t.startsWith(s+r.sep))break;try{return await i(t,"utf-8")}catch{}}throw new Error(`Template "${n}" not found in ${e}`)}},e.createMixin=function(e,t,n){return{name:e,template:t,data:n}},e.deepEscape=h,e.defaultErrorHandler=function(e,t){console.error("[Janja Error]",e.message),t.expression&&console.error(" Expression:",t.expression),t.filter&&console.error(" Filter:",t.filter)},e.defaultWhitespaceOptions=kt,e.defineFilters=function(e){return e},e.definePlugin=function(e){return e},e.expTokenTypes=j,e.extendTemplateWithMixin=async function(e,t,n={},i=Nt){const r=await Ct(t,n,i);return new yt({...n.options,autoEscape:!1}).render(e,{_mixin:r})},e.filters=ee,e.formatTemplate=function(t,n={}){const i={...ne,...n},r=new K(i).tokenize(t),s=[0];for(let e=0;e<t.length;e++)"\n"===t[e]&&s.push(e+1);const o=({line:e,column:t})=>s[e-1]+t-1,a=new M,l=new Dt,c=(e,t)=>{try{const n=a.parse(e,t),i=l.format(n);return en(a.parse(i,t))!==en(n)?null:i.replace(/[{}]/g,"\\$&")}catch{return null}},u=r.map(n=>{const r=t.slice(o(n.loc.start),o(n.loc.end));return n.type===e.TokenType.TEXT||n.type===e.TokenType.COMMENT&&n.val.includes("\n")?r:(t=>{const n=t.strip.before?"-":"",r=t.strip.after?"-":"";if(t.type===e.TokenType.COMMENT)return`${i.commentOpen}${n} ${t.val.trim()} ${r}${i.commentClose}`;if(t.type===e.TokenType.OUTPUT){const e=c(t.val,t.loc);return e&&`${i.outputOpen}${n} ${e} ${r}${i.outputClose}`}const{name:s,expression:o}=t;if(!s)return null;const a=o?c(o.val,o.loc):"";return null!==a&&`${i.directiveOpen}${n} ${s}${a&&` ${a}`} ${r}${i.directiveClose}`})(n)||r}).join("");return!1===n.html?u:Ht(u,{tabWidth:n.tabWidth,commentOpen:i.commentOpen,commentClose:i.commentClose,directiveOpen:i.directiveOpen,directiveClose:i.directiveClose,outputOpen:i.outputOpen,outputClose:i.outputClose})},e.generateDeclarations=xt,e.generateSourceMap=Et,e.getWhitespaceCompilerOptions=function(e){const t=St(e);return{trimWhitespace:t.trim,stripComments:t.stripComments}},e.getWhitespaceRendererOptions=function(e){const t=St(e),n={};return t.trim!==kt.trim&&(n.trimWhitespace=t.trim),t.stripComments!==kt.stripComments&&(n.stripComments=t.stripComments),n},e.globalMixinRegistry=Nt,e.i18n=Tt,e.isForbiddenIdentifier=$,e.mergeOptions=se,e.mergeWhitespaceOptions=St,e.optionsFingerprint=m,e.parserOptions=ne,e.precompile=Pt,e.precompileTemplate=async function(e,t={}){return(await Pt(e,t)).code},e.render=async function(e,t,n){return sn(n).render(e,t)},e.renderCompiled=async function(e,t={},n){return sn(n).renderCompiled(e,t)},e.renderFile=async function(e,t,n){return sn(n).renderFile(e,t)},e.renderOptions=re,e.renderStream=function(e,t={},n){return sn(n).renderStream(e,t)},e.resolveSecurityLimits=u,e.templateCacheKey=b,e.validateTemplate=async function(e,t){return new Lt(t).validate(e)}}(this.janja=this.janja||{});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "janja",
3
- "version": "4.4.0",
3
+ "version": "4.5.0",
4
4
  "description": "A simple, fast, lightweight, and extensible template engine for Node.js and browsers.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -58,7 +58,7 @@
58
58
  "rollup": "^4.64.7",
59
59
  "rollup-plugin-dts": "^6.5.1",
60
60
  "typescript": "^6.0.3",
61
- "vite": "^8.3.4",
61
+ "vite": "^8.3.6",
62
62
  "vitest": "^5.0.5"
63
63
  },
64
64
  "scripts": {