// @bun
var{defineProperty:g,getOwnPropertyNames:Aq,getOwnPropertyDescriptor:jq}=Object,Dq=Object.prototype.hasOwnProperty;function kq(q){return this[q]}var GJ=(q)=>{var J=(i??=new WeakMap).get(q),W;if(J)return J;if(J=g({},"__esModule",{value:!0}),q&&typeof q==="object"||typeof q==="function"){for(var Z of Aq(q))if(!Dq.call(J,Z))g(J,Z,{get:kq.bind(q,Z),enumerable:!(W=jq(q,Z))||W.enumerable})}return i.set(q,J),J},i;var zq=(q)=>q;function Lq(q,J){this[q]=zq.bind(null,J)}var BJ=(q,J)=>{for(var W in J)g(q,W,{get:J[W],enumerable:!0,configurable:!0,set:Lq.bind(J,W)})};var N=(q,J)=>()=>(q&&(J=q(q=0)),J);var E=import.meta.require;function QJ(q){z={...z,...q}}function MJ(){z={...a}}function KJ(){return{...z}}function bq(q){let J="",W=null,Z=!1;for(let $=0;$<q.length;$++){let X=q[$];if(Z){Z=!1;continue}if(X==="\\"&&W){Z=!0;continue}if(W){if(W==="`"&&X==="$"&&$+1<q.length&&q[$+1]==="{"){let V=1;$+=2;while($<q.length&&V>0){if(q[$]==="{")V++;else if(q[$]==="}")V--;if(V>0)J+=q[$],$++}continue}if(X===W)W=null;continue}if(X==='"'||X==="'"||X==="`"){W=X;continue}J+=X}return J}function Pq(q,J){let W=/[$A-Z_a-z][$\w]*/g,Z;while((Z=W.exec(q))!==null){let $=Z[0],X=q[Z.index-1];if(Eq.has($))throw Error(`Potentially unsafe expression (matched /\\b${$}\\b/; identifier ${$}): ${J}`);if(X==="."&&t.has($))throw Error(`Potentially unsafe expression (matched /.${$}/; property ${$}): ${J}`)}}function Sq(q){let J=/\[\s*(['"])(.*?)\1\s*\]/g,W;while((W=J.exec(q))!==null){let Z=W[2];if(!t.has(Z))continue;let $=q.slice(0,W.index).match(/\S(?=\s*$)/)?.[0],X=q.slice(W.index+W[0].length).match(/^\s*(\S)/)?.[1];if(!(($==="{"||$===",")&&X===":"))throw Error(`Potentially unsafe expression (bracket key ${W[2]}): ${q}`)}}function u(q){let J=q.trim(),W=bq(J);Pq(W,J),Sq(J);for(let Z of f)if(Z.test(W))throw Error(`Potentially unsafe expression (matched /${Z.source}/): ${J}`);if(!z.allowBracketNotation&&Iq.test(J))throw Error(`Bracket notation with strings not allowed: ${J}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);return J}function e(q){let J={};J.Math=Math,J.JSON=JSON,J.Date=Date,J.String=String,J.Number=Number,J.Boolean=Boolean,J.Array=Array,J.parseInt=Number.parseInt,J.parseFloat=Number.parseFloat,J.isNaN=Number.isNaN,J.isFinite=Number.isFinite,J.encodeURIComponent=encodeURIComponent,J.decodeURIComponent=decodeURIComponent;for(let[W,Z]of Object.entries(q)){if(W.startsWith("__")||f.some(($)=>$.test(W)))continue;if(Z&&typeof Z==="object"&&!Array.isArray(Z))J[W]=h(Z);else J[W]=Z}return J}function h(q,J=0){if(J>=z.maxSanitizeDepth)return"[Object too deep]";if(q===null||typeof q!=="object")return q;if(Array.isArray(q))return q.map((Z)=>h(Z,J+1));if(q instanceof Date||q instanceof RegExp||q instanceof Map||q instanceof Set||q instanceof Error)return q;let W={};for(let[Z,$]of Object.entries(q)){if(Z.startsWith("__")||Z==="constructor"||Z==="prototype")continue;if($&&typeof $==="object")W[Z]=h($,J+1);else W[Z]=$}return W}function x(q,J){try{let W=e(J),Z=Object.keys(W),$=Object.values(W);return m(q,Z)(...$)}catch{return}}function qq(q){try{return u(q),!0}catch{return!1}}function _J(q){try{return u(q),null}catch(J){return J instanceof Error?J.message:String(J)}}function OJ(q,J){try{let W=x(q,J);return Boolean(W)}catch{return!1}}function wJ(q,J){try{let W=x(q,J);if(Array.isArray(W))return W;if(W&&typeof W==="object"&&"length"in W){let Z=W.length;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=0&&Number.isInteger(Z))return Array.from(W)}return[]}catch{return[]}}function RJ(q,J){try{let W=x(q,J);if(W&&typeof W==="object"&&!Array.isArray(W))return W;return{}}catch{return{}}}function m(q,J){let W=u(q),Z=/^[A-Za-z_$][\w$]*$/,$=[],X=[];for(let Y=0;Y<J.length;Y++){let F=J[Y];if(!Z.test(F))continue;if(vq.has(F))continue;$.push(Y),X.push(F)}let V=Function(...X,`
    'use strict';
    try {
      return ${W};
    }
catch (e) {
      if (e instanceof ReferenceError || e instanceof TypeError) {
        return undefined;
      }
      throw e;
    }
  `);if(X.length===J.length)return V;return(...Y)=>{let F=Array($.length);for(let G=0;G<$.length;G++)F[G]=Y[$[G]];return V(...F)}}function NJ(q,J){try{if(typeof q!=="string")return;if(q.length>n)throw Error(`safeEvaluateCode: input exceeds ${n} chars`);for(let V of f)if(V.test(q))throw Error("Potentially unsafe code detected");let W=e(J),Z=Object.keys(W),$=Object.values(W);return Function(...Z,`
      'use strict';
      ${q}
    `)(...$)}catch{return}}function Cq(q){let J=q.trim(),W=[/\beval\s*\(/i,/\bFunction\s*\(/i,/\bimport\s*\(/i,/\brequire\s*\(/i,/\bprocess\b/i,/\b__proto__\b/i,/\bconstructor\s*[.(]/i,/\bglobalThis\b/i,/\bwindow\b/i,/\bdocument\b/i,/\bfetch\s*\(/i,/\bBun\b/i,/\bDeno\b/i,/\bconsole\b/i,/\bthis\b/i,/\bReflect\b/i,/\bProxy\b/i,/\bprototype\b/i,/\.(bind|call|apply)\s*\(/i];for(let Z of W)if(Z.test(J))return!1;return!0}function TJ(q,J,W,Z,$=1000){if(!Cq(J))throw Error(`Unsafe expression in @${q}: ${J}`);let X=W.replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\{\{([^}]+)\}\}/g,(V,Y)=>{return`\${${Y}}`});if(q==="for")return Function(...Z,`
      'use strict';
      let result = '';
      for (${J}) {
        result += \`${X}\`;
      }
      return result;
    // eslint-disable-next-line pickier/no-unused-vars
    `);else return Function(...Z,`
      'use strict';
      let result = '';
      let __safeCounter = 0;
      const __maxIterations = ${$};
      while (${J} && __safeCounter < __maxIterations) {
        __safeCounter++;
        result += \`${X}\`;
      }
      // Surface the truncation both inline (for end users) and via
      // console.warn (for developers running \`stx dev\`). A silent cut-off
      // made pages render half a list with no breadcrumb.
      if (__safeCounter >= __maxIterations) {
        result += '<!-- [Loop Error]: Maximum iterations exceeded -->';
        if (typeof console !== 'undefined' && typeof console.warn === 'function') {
          console.warn('[stx] @while loop hit max iterations (' + __maxIterations + '); template output was truncated. Raise via createSafeForLoop(..., maxIterations) if intentional.');
        }
      }
      return result;
    // eslint-disable-next-line pickier/no-unused-vars
    `)}var a,z,f,Eq,t,Iq,vq,n=65536;var Jq=N(()=>{a={maxSanitizeDepth:10,allowBracketNotation:!1},z={...a};f=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/\b(Reflect|Proxy)\b/,/\bSymbol\b/,/\b(WeakMap|WeakSet|WeakRef|FinalizationRegistry)\b/,/\b(Generator|AsyncGenerator)\b/,/__\w+__/,/\.(bind|call|apply)\s*\(/,/\bnew\s+/,/\bdelete\s+/,/\bthis\b/],Eq=new Set(["eval","Function","setTimeout","setInterval","setImmediate","process","require","import","exports","module","window","document","global","globalThis","constructor","prototype","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Generator","AsyncGenerator","delete","this"]),t=new Set(["__proto__","constructor","prototype"]),Iq=/[\w)\]]\s*\[\s*['"]/;vq=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public","arguments","eval","await"])});function gq(q){Wq=q}function hq(){return Wq}function fq(q){b={...b,...q}}function uq(){b={}}function Zq(q,J={}){let W=b[q]||yq[q]||{message:`Unknown error (code: ${q})`},Z=W.message,$=W.help;for(let[X,V]of Object.entries(J)){let Y=`{{${X}}}`;if(Z=Z.replace(new RegExp(Y,"g"),V),$)$=$.replace(new RegExp(Y,"g"),V)}return{message:Z,help:$}}function xq(q,J={}){let{message:W,help:Z}=Zq(q,J);return Z?`${W}
  Help: ${Z}`:W}function c(q){for(let[J,W]of Object.entries(T))if(W===q)return J;return}var yq,b,Wq="en",T;var P=N(()=>{yq={1001:{message:"Unclosed directive: {{directive}}",help:"Make sure to close the directive with the appropriate end tag"},1002:{message:"Unclosed expression at position {{position}}",help:"Check for missing closing braces }}"},1003:{message:"Invalid directive syntax: {{directive}}",help:"Review the directive documentation for correct syntax"},1004:{message:"Malformed expression: {{expression}}",help:"Check for syntax errors in your expression"},1005:{message:"Unexpected token: {{token}}",help:"Remove or fix the unexpected token"},1101:{message:"Undefined variable: {{variable}}",help:"Make sure the variable is defined in the template context"},1102:{message:"Type error: {{details}}",help:"Check that you are using the correct types"},1103:{message:"Evaluation error: {{details}}",help:"Review the expression for errors"},1104:{message:"Infinite loop detected in {{location}}",help:"Check your loop conditions"},1105:{message:"Circular reference detected: {{path}}",help:"Remove the circular dependency"},1201:{message:"Unsafe expression blocked: {{expression}}",help:"This expression contains potentially dangerous code"},1202:{message:"Path traversal attempt blocked: {{path}}",help:"Use only relative paths within allowed directories"},1203:{message:"Potential XSS attempt blocked",help:"Sanitize user input before rendering"},1204:{message:"Code injection attempt blocked: {{code}}",help:"Avoid executing dynamic code"},1205:{message:"Prohibited DOM API usage: {{api}}",help:"Use STX.useRefs(), STX.useRef(), STX.el() and other STX helpers instead of direct DOM manipulation"},1301:{message:"File not found: {{path}}",help:"Check that the file exists and the path is correct"},1302:{message:"Error reading file: {{path}}",help:"Check file permissions and encoding"},1303:{message:"Invalid file path: {{path}}",help:"Use a valid file path"},1304:{message:"Permission denied: {{path}}",help:"Check file permissions"},1401:{message:"Invalid configuration: {{details}}",help:"Review your stx.config.ts file"},1402:{message:"Missing required configuration: {{key}}",help:"Add the required configuration option"},1403:{message:"Deprecated configuration: {{key}}",help:"Update to the new configuration format"},1501:{message:"Component not found: {{name}}",help:"Check that the component exists in your components directory"},1502:{message:"Invalid props for component {{name}}: {{details}}",help:"Check the component prop requirements"},1503:{message:"Error rendering component {{name}}: {{details}}",help:"Check the component template for errors"},1601:{message:"Filter not found: {{filter}}",help:"Register the filter or check the filter name"},1602:{message:"Invalid arguments for filter {{filter}}: {{details}}",help:"Check the filter documentation for correct arguments"},1603:{message:"Expression evaluation timed out",help:"Simplify the expression or increase the timeout"}},b={};T={UNCLOSED_DIRECTIVE:1001,UNCLOSED_EXPRESSION:1002,INVALID_DIRECTIVE_SYNTAX:1003,MALFORMED_EXPRESSION:1004,UNEXPECTED_TOKEN:1005,UNDEFINED_VARIABLE:1101,TYPE_ERROR:1102,EVALUATION_ERROR:1103,INFINITE_LOOP:1104,CIRCULAR_REFERENCE:1105,UNSAFE_EXPRESSION:1201,PATH_TRAVERSAL:1202,XSS_ATTEMPT:1203,CODE_INJECTION:1204,DOM_API_VIOLATION:1205,FILE_NOT_FOUND:1301,FILE_READ_ERROR:1302,INVALID_FILE_PATH:1303,PERMISSION_DENIED:1304,INVALID_CONFIG:1401,MISSING_REQUIRED_CONFIG:1402,DEPRECATED_CONFIG:1403,COMPONENT_NOT_FOUND:1501,INVALID_PROPS:1502,COMPONENT_RENDER_ERROR:1503,FILTER_NOT_FOUND:1601,INVALID_FILTER_ARGS:1602,EXPRESSION_TIMEOUT:1603}});function cq(){return!1}function I(){return!cq()||process.env.STX_DEBUG==="true"}function DJ(){return!1}import pq from"path";function dq(q){L={...L,...q}}function S(){return{...L}}function lq(){L={...$q}}function v(q){if(!L.showRelativePaths||!q)return q;let J=L.baseDir||process.cwd();try{let W=pq.relative(J,q);return W.startsWith("..")?q:W}catch{return q}}var $q,L,j,Xq,Yq,Vq,Fq,Uq;var C=N(()=>{P();$q={showRelativePaths:!1,enableAutoRecovery:I(),logRecoveryWarnings:!0},L={...$q};j=class j extends Error{code;filePath;line;column;context;numericCode;constructor(q,J,W,Z,$,X,V){super(q);this.code=J;this.filePath=W;this.line=Z;this.column=$;this.context=X;if(this.name="StxError",this.numericCode=V||T.EVALUATION_ERROR,this.filePath)this.filePath=v(this.filePath)}};Xq=class Xq extends j{constructor(q,J,W,Z,$,X){super(q,"stx_SYNTAX_ERROR",J,W,Z,$,X||T.INVALID_DIRECTIVE_SYNTAX);this.name="StxSyntaxError"}};Yq=class Yq extends j{constructor(q,J,W,Z,$,X){super(q,"stx_RUNTIME_ERROR",J,W,Z,$,X||T.EVALUATION_ERROR);this.name="StxRuntimeError"}};Vq=class Vq extends j{constructor(q,J,W,Z,$,X){super(q,"stx_SECURITY_ERROR",J,W,Z,$,X||T.UNSAFE_EXPRESSION);this.name="StxSecurityError"}};Fq=class Fq extends j{constructor(q,J,W,Z,$,X){super(q,"stx_FILE_ERROR",J,W,Z,$,X||T.FILE_NOT_FOUND);this.name="StxFileError"}};Uq=class Uq extends j{isFatal=!0;constructor(q,J,W,Z,$,X){super(q,"stx_VALIDATION_ERROR",J,W,Z,$,X||T.DOM_API_VIOLATION);this.name="StxValidationError"}}});function p(q){let{type:J,message:W,code:Z,filePath:$,line:X,column:V,template:Y,offset:F,snippet:G,suggestion:U,format:B="text"}=q,H=X,Q=V;if(!H&&Y&&F!==void 0){let A=Bq(Y,F);H=A.line,Q=A.column}let _=$?v($):void 0,O=Z?c(Z):void 0,w={type:J,code:Z,codeName:O,message:W,filePath:_,line:H,column:Q,snippet:G,suggestion:U,timestamp:new Date().toISOString()},R;switch(B){case"html":R=rq(w);break;case"json":R=JSON.stringify(w,null,2);break;case"console":R=oq(w,Y,F);break;case"text":default:R=sq(w,Y,F);break}return{formatted:R,data:w}}function sq(q,J,W){let Z=[],$=q.code?` [${q.codeName||q.code}]`:"";if(Z.push(`[${q.type} Error${$}]`),q.filePath){let X=q.filePath;if(q.line){if(X+=`:${q.line}`,q.column)X+=`:${q.column}`}Z.push(`at ${X}`)}if(Z.push(`
${q.message}`),J&&q.line){let X=iq(J,q.line,2);if(X)Z.push(`
${X}`)}if(q.snippet)Z.push(`
Snippet: ${q.snippet}`);if(q.suggestion)Z.push(`
Suggestion: ${q.suggestion}`);return Z.join(" ")}function rq(q){let J=q.code?` [${q.code}]`:"",W=q.filePath?` in ${q.filePath}${q.line?`:${q.line}`:""}`:"",Z=`<!-- [${q.type} Error${J}]${W}: ${Gq(q.message)}`;if(q.suggestion)Z+=` | Suggestion: ${Gq(q.suggestion)}`;return Z+=" -->",Z}function oq(q,J,W){let G=[],U=q.code?` [${q.codeName||q.code}]`:"";if(G.push(`\x1B[1m${"\x1B[31m"}\u2501\u2501\u2501 ${q.type} Error${U} \u2501\u2501\u2501${"\x1B[0m"}`),q.filePath){let B=`\x1B[36m${q.filePath}\x1B[0m`;if(q.line){if(B+=`\x1B[90m:${q.line}\x1B[0m`,q.column)B+=`\x1B[90m:${q.column}\x1B[0m`}G.push(`
\x1B[90mat\x1B[0m ${B}`)}if(G.push(`

${q.message}`),J&&q.line){let B=nq(J,q.line,2);if(B)G.push(`

\x1B[90mContext:\x1B[0m
${B}`)}if(q.suggestion)G.push(`

\x1B[33mSuggestion:\x1B[0m ${q.suggestion}`);return G.push(`
${"\x1B[31m"}\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${"\x1B[0m"}`),G.join("")}function iq(q,J,W){let Z=q.split(`
`),$=Math.max(0,J-W-1),X=Math.min(Z.length-1,J+W-1),V=[];for(let Y=$;Y<=X;Y++){let F=(Y+1).toString().padStart(4),G=Y===J-1?">":" ";V.push(`${G}${F} | ${Z[Y]}`)}return V.join(`
`)}function nq(q,J,W){let Z=q.split(`
`),$=Math.max(0,J-W-1),X=Math.min(Z.length-1,J+W-1),V="\x1B[90m",Y="\x1B[31m",F="\x1B[0m",G=[];for(let U=$;U<=X;U++){let B=(U+1).toString().padStart(4),H=U===J-1,Q=H?"\x1B[31m>\x1B[0m":" ",_=H?`\x1B[31m${Z[U]}\x1B[0m`:`\x1B[90m${Z[U]}\x1B[0m`;G.push(`${Q}\x1B[90m${B}\x1B[0m | ${_}`)}return G.join(`
`)}function Gq(q){return q.replace(/--/g,"- -").replace(/>/g,"&gt;")}function Bq(q,J){let Z=q.substring(0,J).split(`
`);return{line:Z.length,column:Z[Z.length-1].length}}function aq(q,J,W){return p({type:q,message:J,code:W,format:"html"}).formatted}function tq(q,J,W,Z,$){return p({type:q,message:J,code:$,filePath:W,line:Z,format:"console"}).formatted}function eq(q,J,W){let Z=W.template.split(`
`),$=Bq(W.template,W.offset),X=`[${q} Error at line ${$.line} in ${W.filePath}]: ${J}

`,V=Math.max(0,$.line-3),Y=Math.min(Z.length-1,$.line+2);X+=`Context:
`;for(let F=V;F<=Y;F++){let G=F+1,U=Z[F]||"",B=F===$.line-1?">":" ";X+=`${B} ${G.toString().padStart(3)}: ${U}
`}if($.line-1<Z.length){let F=" ".repeat($.column+5);X+=`${F}^
`}return X}function qJ(q,J,W){try{return q()}catch(Z){if(W&&Z instanceof Error)W(Z);return J}}async function JJ(q,J,W){try{return await q()}catch(Z){if(W&&Z instanceof Error)W(Z);return J}}var Hq=N(()=>{P();C()});class d{errors=[];maxErrors;enableFileLogging;logFilePath;logFormat;maxFileSize;maxLogFiles;minLevel;writeQueue=Promise.resolve();constructor(q={}){this.maxErrors=q.maxErrors??1000,this.enableFileLogging=q.enableFileLogging??!1,this.logFilePath=q.logFilePath??".stx/errors.log",this.logFormat=q.logFormat??"json",this.maxFileSize=q.maxFileSize??10485760,this.maxLogFiles=q.maxLogFiles??5,this.minLevel=q.minLevel??"all"}configure(q){if(q.maxErrors!==void 0)this.maxErrors=q.maxErrors;if(q.enableFileLogging!==void 0)this.enableFileLogging=q.enableFileLogging;if(q.logFilePath!==void 0)this.logFilePath=q.logFilePath;if(q.logFormat!==void 0)this.logFormat=q.logFormat;if(q.maxFileSize!==void 0)this.maxFileSize=q.maxFileSize;if(q.maxLogFiles!==void 0)this.maxLogFiles=q.maxLogFiles;if(q.minLevel!==void 0)this.minLevel=q.minLevel}log(q,J,W="error"){let Z={timestamp:new Date,error:q,context:J,level:W};if(this.errors.push(Z),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors);if(this.enableFileLogging&&this.shouldLog(W))this.writeToFile(Z)}shouldLog(q){if(this.minLevel==="all")return!0;if(this.minLevel==="warning")return q==="error"||q==="warning";if(this.minLevel==="error")return q==="error";return!0}formatEntry(q){if(this.logFormat==="json")return JSON.stringify({timestamp:q.timestamp.toISOString(),level:q.level||"error",type:q.error.constructor.name,message:q.error.message,stack:q.error.stack,context:q.context});let J=[`[${q.timestamp.toISOString()}] [${(q.level||"error").toUpperCase()}] ${q.error.constructor.name}: ${q.error.message}`];if(q.error.stack)J.push(`  Stack: ${q.error.stack.split(`
`).slice(1).join(`
  `)}`);if(q.context)J.push(`  Context: ${JSON.stringify(q.context)}`);return J.join(`
`)}writeToFile(q){this.writeQueue=this.writeQueue.then(async()=>{try{let J=await import("fs"),Z=(await import("path")).dirname(this.logFilePath);if(!J.existsSync(Z))J.mkdirSync(Z,{recursive:!0});await this.rotateIfNeeded(J);let $=`${this.formatEntry(q)}
`;J.appendFileSync(this.logFilePath,$,"utf-8")}catch(J){if(process.env.STX_DEBUG==="true")console.error("Failed to write to error log:",J)}})}async rotateIfNeeded(q){try{if(!q.existsSync(this.logFilePath))return;if(q.statSync(this.logFilePath).size<this.maxFileSize)return;for(let W=this.maxLogFiles-1;W>=1;W--){let Z=`${this.logFilePath}.${W}`,$=`${this.logFilePath}.${W+1}`;if(q.existsSync(Z))if(W>=this.maxLogFiles-1)q.unlinkSync(Z);else q.renameSync(Z,$)}if(this.maxLogFiles<=1)q.writeFileSync(this.logFilePath,"");else q.renameSync(this.logFilePath,`${this.logFilePath}.1`)}catch(J){if(process.env.STX_DEBUG==="true")console.error("Failed to rotate error logs:",J)}}getRecentErrors(q=10){return this.errors.slice(-q)}getErrorsByType(q){return this.errors.filter((J)=>J.error.constructor.name===q)}getErrorsByLevel(q){return this.errors.filter((J)=>J.level===q)}clear(){this.errors.length=0}async clearLogFile(){try{let q=await import("fs");if(q.existsSync(this.logFilePath))q.writeFileSync(this.logFilePath,"","utf-8")}catch(q){if(process.env.STX_DEBUG==="true")console.error("Failed to clear error log:",q)}}getStats(){let q={},J={error:0,warning:0,info:0};for(let W of this.errors){let Z=W.error.constructor.name;q[Z]=(q[Z]||0)+1;let $=W.level||"error";J[$]=(J[$]||0)+1}return{total:this.errors.length,byType:q,byLevel:J}}async exportToFile(q,J="json"){let W=await import("fs"),$=(await import("path")).dirname(q);if(!W.existsSync($))W.mkdirSync($,{recursive:!0});if(J==="json"){let X=this.errors.map((V)=>({timestamp:V.timestamp.toISOString(),level:V.level||"error",type:V.error.constructor.name,message:V.error.message,stack:V.error.stack,context:V.context}));W.writeFileSync(q,JSON.stringify(X,null,2),"utf-8")}else{let X=this.errors.map((V)=>this.formatEntry(V));W.writeFileSync(q,X.join(`

`),"utf-8")}}async flush(){await this.writeQueue}}var WJ,l,ZJ;var Qq=N(()=>{C();WJ={isEnabled(){return S().enableAutoRecovery},fixCommonSyntaxErrors(q){let J=S();if(!J.enableAutoRecovery)return{fixed:q,fixes:[]};let W=q,Z=[],$=(W.match(/\{\{/g)||[]).length,X=(W.match(/\}\}/g)||[]).length;if($>X){let Y=$-X;W+="}}".repeat(Y),Z.push(`Added ${Y} missing closing braces '}}'`)}let V=["if","foreach","for","switch","section"];for(let Y of V){let F=(W.match(new RegExp(`@${Y}\\b`,"g"))||[]).length,G=(W.match(new RegExp(`@end${Y}\\b`,"g"))||[]).length;if(F>G){let U=F-G;for(let B=0;B<U;B++)W+=`
@end${Y}`;Z.push(`Added ${U} missing @end${Y}`)}}if(Z.length>0&&J.logRecoveryWarnings)console.warn("[stx] Auto-recovery applied fixes:"),Z.forEach((Y)=>console.warn(`  - ${Y}`)),console.warn("  Consider fixing these issues in your template.");return{fixed:W,fixes:Z}},createFallbackContent(q,J){if(I())return`<!-- ${q} failed: ${J.message} -->`;return"<!-- stx rendering error -->"}};l=new d,ZJ={isDevelopment(){return I()},logDetailedError(q,J){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",q.message),console.error("Stack:",q.stack),J)console.error("Context:",J);console.error("========================")},createErrorReport(q,J){let W=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${q.message}`,`Type: ${q.constructor.name}`,`Stack: ${q.stack}`];if(J)W.push(`Context: ${JSON.stringify(J,null,2)}`);return W.push("========================"),W.join(`
`)}}});import s from"path";function $J(q){let J={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return q.replace(/[&<>"']/g,(W)=>J[W]||W)}function y(q,J={}){let{allowHtml:W=!1,maxLength:Z=1e4,allowSpecialChars:$=!0,customSanitizer:X}=J,V=[],Y=q,F=!1;if(X){let U=X(Y);if(U!==Y)Y=U,F=!0}if(Y.includes("\x00"))Y=Y.replace(/\0/g,""),F=!0,V.push("Null bytes removed from parameter");if(Y.length>Z)Y=Y.substring(0,Z),F=!0,V.push(`Parameter truncated to ${Z} characters`);if(!W&&/<[^>]+>/.test(Y))Y=$J(Y),F=!0,V.push("HTML content was escaped");let G=[{pattern:/javascript:/gi,replacement:"",name:"javascript: URI"},{pattern:/vbscript:/gi,replacement:"",name:"vbscript: URI"},{pattern:/data:text\/html/gi,replacement:"",name:"data:text/html URI"}];for(let{pattern:U,replacement:B,name:H}of G)if(U.test(Y))Y=Y.replace(U,B),F=!0,V.push(`Removed ${H} from parameter`);if(!$){let U=Y;if(Y=Y.split("").filter((B)=>{let H=B.charCodeAt(0);return H>=32&&H!==127}).join(""),Y!==U)F=!0,V.push("Control characters removed")}return{value:Y,modified:F,warnings:V}}function XJ(q,J){let W=q.replace(/\0/g,"");W=W.replace(/\\/g,"/"),W=W.replace(/^[a-z][a-z0-9+.-]*:/i,"");while(W.includes("../")||W.includes("./"))W=W.replace(/\.\.\//g,"").replace(/\.\//g,"");if(!r.isValidFilePath(W,J))return null;return W}function YJ(q){let J=[],W=q.trim(),Z=W!==q,$=[{pattern:/\beval\s*\(/gi,name:"eval()"},{pattern:/\bFunction\s*\(/gi,name:"Function()"},{pattern:/\bsetTimeout\s*\(/gi,name:"setTimeout()"},{pattern:/\bsetInterval\s*\(/gi,name:"setInterval()"},{pattern:/\bimport\s*\(/gi,name:"dynamic import()"},{pattern:/\brequire\s*\(/gi,name:"require()"},{pattern:/\b__proto__\b/gi,name:"__proto__"},{pattern:/\bconstructor\b/gi,name:"constructor"},{pattern:/\bprototype\b/gi,name:"prototype"}];for(let{pattern:X,name:V}of $)if(X.test(W))J.push(`Potentially dangerous pattern detected: ${V}`);if(W.includes("\x00"))W=W.replace(/\0/g,""),Z=!0,J.push("Null bytes removed from expression");return{value:W,modified:Z,warnings:J}}function VJ(q,J={}){return q.map((W)=>y(W,J))}function Mq(q){let J={};for(let[W,Z]of Object.entries(q)){if(!r.isValidVariableName(W))continue;if(typeof Z==="string"){let $=y(Z);J[W]=$.value}else if(Array.isArray(Z))J[W]=Z.map(($)=>typeof $==="string"?y($).value:$);else if(typeof Z==="object"&&Z!==null)J[W]=Mq(Z);else J[W]=Z}return J}var r;var Kq=N(()=>{r={isValidFilePath(q,J){let W=q.replace(/\\/g,"/");if(W.includes("\x00"))return!1;if(W.includes("../")||W.includes("..\\")||W===".."||W.startsWith("../")||W.endsWith("/..")||W.includes("/..\\")||W.includes("\\../"))return!1;if(/^[a-z][a-z0-9+.-]*:/i.test(W))return!1;if(W.startsWith("/")){if(["/etc/","/root/","/var/","/usr/","/bin/","/sbin/","/proc/","/sys/","/dev/","/boot/","/home/","/private/","/Library/","/System/"].some((X)=>W===X.slice(0,-1)||W.startsWith(X)))return!1}if(/^[a-z]:/i.test(W)){if(["Windows/","Windows\\","System32/","System32\\","Program Files/","Program Files\\"].some((X)=>W.includes(X)))return!1}if(J){let $=s.resolve(J,q),X=s.resolve(J);if(!$.startsWith(X+s.sep)&&$!==X)return!1}return!0},isValidVariableName(q){return/^[a-z_$]\w*$/i.test(q)},isValidDirectiveName(q){return/^[a-z][\w-]*$/i.test(q)},isSafeContent(q){return![/<script[^>]*>[\s\S]*?<\/script>/i,/javascript:/i,/data:text\/html/i,/vbscript:/i,/on\w+\s*=/i].some((W)=>W.test(q))}}});var _q=N(()=>{P();Hq();Qq();Kq();C()});var Oq=N(()=>{_q()});function oJ(q,J){let W=q,Z=/@json\s*\(/g,$;while(($=Z.exec(W))!==null){let X=$.index,V=X+$[0].length-1,Y=1,F=V+1,G=null,U=!1;while(F<W.length&&Y>0){let K=W[F];if(U){U=!1,F++;continue}if(K==="\\"&&G){U=!0,F++;continue}if(G){if(K===G)G=null;F++;continue}if(K==='"'||K==="'"||K==="`"){G=K,F++;continue}if(K==="(")Y++;else if(K===")"){if(Y--,Y===0)break}F++}if(Y!==0)break;let B=W.substring(V+1,F).trim(),H=W.substring(X,F+1),Q=-1,_=0,O=null,w=!1;for(let K=0;K<B.length;K++){let M=B[K];if(w){w=!1;continue}if(M==="\\"&&O){w=!0;continue}if(O){if(M===O)O=null;continue}if(M==='"'||M==="'"||M==="`"){O=M;continue}if(M==="("||M==="["||M==="{")_++;else if(M===")"||M==="]"||M==="}")_--;if(M===","&&_===0){Q=K;break}}let R=Q>=0?B.substring(0,Q).trim():B,A=Q>=0?B.substring(Q+1).trim():void 0;try{let K=R.trim(),M;if(qq(K))M=m(K,Object.keys(J))(...Object.values(J));else M=void 0;let D;if(A==="true")D=JSON.stringify(M,null,2);else D=JSON.stringify(M);let k=D.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");W=W.substring(0,X)+k+W.substring(F+1),Z.lastIndex=X+k.length}catch(K){l.log(K instanceof Error?K:Error(String(K)),{directive:"@json"},"error"),Z.lastIndex=X+H.length}}return W}function iJ(q){return q.replace(/@once\s*([\s\S]*?)@endonce/g,"$1")}function nJ(q){let J=q,W=/@memo\s*\(/g,Z,$=[];while((Z=W.exec(J))!==null){let X=Z.index,V=X+Z[0].length,Y=1,F=V;while(F<J.length&&Y>0){if(J[F]==="(")Y++;else if(J[F]===")")Y--;F++}if(Y!==0)continue;let G=J.slice(V,F-1).trim(),U=F,B=J.slice(U),H=B.indexOf("@endmemo");if(H===-1)continue;let Q=B.slice(0,H),_=U+H+8,O=Q.match(/^(\s*(?:(?:<!--[\s\S]*?-->|\x00STX_HTML_COMMENT_\d+\x00)\s*)*)/),w=O?O[0].length:0,R=Q.slice(w),A=Q.match(/(\s*)$/),K=A?A[0].length:0,M=R.slice(0,R.length-K),D=M.match(/^<([a-zA-Z][a-zA-Z0-9-]*)(\s[^>]*?)?(\/?)>/),k;if(D){let[o,wq,Rq="",Nq]=D,Tq=`<${wq}${Rq} data-stx-memo="${G}"${Nq}>`;k=Q.slice(0,w)+Tq+M.slice(o.length)+Q.slice(w+M.length)}else k=`${Q.slice(0,w)}<div data-stx-memo="${G}">${M}</div>${Q.slice(w+M.length)}`;$.push({start:X,end:_,replacement:k}),W.lastIndex=_}for(let X=$.length-1;X>=0;X--){let V=$[X];J=J.slice(0,V.start)+V.replacement+J.slice(V.end)}return J.replace(/@memo="([^"]*)"/g,'data-stx-memo="$1"')}function aJ(q){let J=q.replace(/@ref="([^"]+)"/g,'data-stx-ref="$1"');return J=J.replace(/(<[a-zA-Z][a-zA-Z0-9-]*\b[^>]*?)\sref="([^"]+)"/g,'$1 data-stx-ref="$2"'),J}function tJ(q){let W=new RegExp("<(div|span|p|h[1-6]|td|th|li|a|button|label|section|article|header|footer|main|nav|aside|dd|dt|figcaption|summary|caption|blockquote|pre|code|em|strong|small|sub|sup|time|mark|abbr|cite|q|s|u|b|i)\\b","gi"),Z="",$=0,X;while((X=W.exec(q))!==null){let V=X.index,Y=V+X[0].length,F=!1,G=!1,U=-1;while(Y<q.length){let O=q[Y];if(F){if(O==="'")F=!1}else if(G){if(O==='"')G=!1}else if(O==="'")F=!0;else if(O==='"')G=!0;else if(O===">"){U=Y;break}Y++}if(U===-1)continue;if(q.slice(V,U+1).includes("x-cloak"))continue;let H=q.slice(U+1),Q=H.indexOf("</"),_=Q>=0?H.slice(0,Q):H.slice(0,200);if(/\{\{[\s\S]*?\}\}/.test(_))Z+=q.slice($,U)+" x-cloak>",$=U+1}return Z+=q.slice($),Z}function eJ(q){let J=/<[a-z][\w-]*/gi,W="",Z=0,$;while(($=J.exec(q))!==null){let X=$.index,V=$[0].slice(1).toLowerCase();if(V==="script"||V==="style"){let _=`</${V}>`,O=q.toLowerCase().indexOf(_,X);if(O!==-1)J.lastIndex=O+_.length;continue}let Y=X+$[0].length,F=!1,G=!1,U=-1;while(Y<q.length){let _=q[Y];if(F){if(_==="'")F=!1}else if(G){if(_==='"')G=!1}else if(_==="'")F=!0;else if(_==='"')G=!0;else if(_===">"){U=Y;break}Y++}if(U===-1)continue;let B=q.slice(X+$[0].length,U);if(/(?:^|\s)x-cloak(?:=|\s|\/|>|$)/.test(B))continue;if(!FJ.test(B))continue;let H=q[U-1]==="/",Q=H?U-1:U;W+=`${q.slice(Z,Q)} x-cloak${H?" ":""}`,Z=Q}return W+=q.slice(Z),W}var FJ;var UJ=N(()=>{Oq();Jq();FJ=/(?:^|\s)(?::else-if|:if|:else|:show|x-else-if|x-if|x-else|x-show|@if|@show)(?:=|\s|\/|>|$)/});UJ();export{aJ as processRefAttributes,iJ as processOnceDirective,nJ as processMemoDirective,oJ as processJsonDirective,tJ as addCloakToUnresolvedExpressions,eJ as addCloakToConditionalDirectives};
