// @bun
var{defineProperty:u,getOwnPropertyNames:Sq,getOwnPropertyDescriptor:Cq}=Object,yq=Object.prototype.hasOwnProperty;function vq(q){return this[q]}var eJ=(q)=>{var Q=(Qq??=new WeakMap).get(q),J;if(Q)return Q;if(Q=u({},"__esModule",{value:!0}),q&&typeof q==="object"||typeof q==="function"){for(var W of Sq(q))if(!yq.call(Q,W))u(Q,W,{get:vq.bind(q,W),enumerable:!(J=Cq(q,W))||J.enumerable})}return Qq.set(q,Q),Q},Qq;var hq=(q)=>q;function gq(q,Q){this[q]=hq.bind(null,Q)}var xq=(q,Q)=>{for(var J in Q)u(q,J,{get:Q[J],enumerable:!0,configurable:!0,set:gq.bind(Q,J)})};var K=(q,Q)=>()=>(q&&(Q=q(q=0)),Q);var I=import.meta.require;function JQ(q){T={...T,...q}}function QQ(){T={...Zq}}function WQ(){return{...T}}function mq(q){let Q="",J=null,W=!1;for(let Z=0;Z<q.length;Z++){let $=q[Z];if(W){W=!1;continue}if($==="\\"&&J){W=!0;continue}if(J){if(J==="`"&&$==="$"&&Z+1<q.length&&q[Z+1]==="{"){let X=1;Z+=2;while(Z<q.length&&X>0){if(q[Z]==="{")X++;else if(q[Z]==="}")X--;if(X>0)Q+=q[Z],Z++}continue}if($===J)J=null;continue}if($==='"'||$==="'"||$==="`"){J=$;continue}Q+=$}return Q}function dq(q,Q){let J=/[$A-Z_a-z][$\w]*/g,W;while((W=J.exec(q))!==null){let Z=W[0],$=q[W.index-1];if(fq.has(Z))throw Error(`Potentially unsafe expression (matched /\\b${Z}\\b/; identifier ${Z}): ${Q}`);if($==="."&&$q.has(Z))throw Error(`Potentially unsafe expression (matched /.${Z}/; property ${Z}): ${Q}`)}}function cq(q){let Q=/\[\s*(['"])(.*?)\1\s*\]/g,J;while((J=Q.exec(q))!==null){let W=J[2];if(!$q.has(W))continue;let Z=q.slice(0,J.index).match(/\S(?=\s*$)/)?.[0],$=q.slice(J.index+J[0].length).match(/^\s*(\S)/)?.[1];if(!((Z==="{"||Z===",")&&$===":"))throw Error(`Potentially unsafe expression (bracket key ${J[2]}): ${q}`)}}function c(q){let Q=q.trim(),J=mq(Q);dq(J,Q),cq(Q);for(let W of d)if(W.test(J))throw Error(`Potentially unsafe expression (matched /${W.source}/): ${Q}`);if(!T.allowBracketNotation&&uq.test(Q))throw Error(`Bracket notation with strings not allowed: ${Q}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);return Q}function Xq(q){let Q={};Q.Math=Math,Q.JSON=JSON,Q.Date=Date,Q.String=String,Q.Number=Number,Q.Boolean=Boolean,Q.Array=Array,Q.parseInt=Number.parseInt,Q.parseFloat=Number.parseFloat,Q.isNaN=Number.isNaN,Q.isFinite=Number.isFinite,Q.encodeURIComponent=encodeURIComponent,Q.decodeURIComponent=decodeURIComponent;for(let[J,W]of Object.entries(q)){if(J.startsWith("__")||d.some((Z)=>Z.test(J)))continue;if(W&&typeof W==="object"&&!Array.isArray(W))Q[J]=m(W);else Q[J]=W}return Q}function m(q,Q=0){if(Q>=T.maxSanitizeDepth)return"[Object too deep]";if(q===null||typeof q!=="object")return q;if(Array.isArray(q))return q.map((W)=>m(W,Q+1));if(q instanceof Date||q instanceof RegExp||q instanceof Map||q instanceof Set||q instanceof Error)return q;let J={};for(let[W,Z]of Object.entries(q)){if(W.startsWith("__")||W==="constructor"||W==="prototype")continue;if(Z&&typeof Z==="object")J[W]=m(Z,Q+1);else J[W]=Z}return J}function p(q,Q){try{let J=Xq(Q),W=Object.keys(J),Z=Object.values(J);return lq(q,W)(...Z)}catch{return}}function ZQ(q){try{return c(q),!0}catch{return!1}}function $Q(q){try{return c(q),null}catch(Q){return Q instanceof Error?Q.message:String(Q)}}function XQ(q,Q){try{let J=p(q,Q);return Boolean(J)}catch{return!1}}function YQ(q,Q){try{let J=p(q,Q);if(Array.isArray(J))return J;if(J&&typeof J==="object"&&"length"in J){let W=J.length;if(typeof W==="number"&&Number.isFinite(W)&&W>=0&&Number.isInteger(W))return Array.from(J)}return[]}catch{return[]}}function l(q,Q){try{let J=p(q,Q);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return{}}catch{return{}}}function lq(q,Q){let J=c(q),W=/^[A-Za-z_$][\w$]*$/,Z=[],$=[];for(let Y=0;Y<Q.length;Y++){let G=Q[Y];if(!W.test(G))continue;if(pq.has(G))continue;Z.push(Y),$.push(G)}let X=Function(...$,`
    'use strict';
    try {
      return ${J};
    }
catch (e) {
      if (e instanceof ReferenceError || e instanceof TypeError) {
        return undefined;
      }
      throw e;
    }
  `);if($.length===Q.length)return X;return(...Y)=>{let G=Array(Z.length);for(let H=0;H<Z.length;H++)G[H]=Y[Z[H]];return X(...G)}}function GQ(q,Q){try{if(typeof q!=="string")return;if(q.length>Wq)throw Error(`safeEvaluateCode: input exceeds ${Wq} chars`);for(let X of d)if(X.test(q))throw Error("Potentially unsafe code detected");let J=Xq(Q),W=Object.keys(J),Z=Object.values(J);return Function(...W,`
      'use strict';
      ${q}
    `)(...Z)}catch{return}}function iq(q){let Q=q.trim(),J=[/\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 W of J)if(W.test(Q))return!1;return!0}function BQ(q,Q,J,W,Z=1000){if(!iq(Q))throw Error(`Unsafe expression in @${q}: ${Q}`);let $=J.replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\{\{([^}]+)\}\}/g,(X,Y)=>{return`\${${Y}}`});if(q==="for")return Function(...W,`
      'use strict';
      let result = '';
      for (${Q}) {
        result += \`${$}\`;
      }
      return result;
    // eslint-disable-next-line pickier/no-unused-vars
    `);else return Function(...W,`
      'use strict';
      let result = '';
      let __safeCounter = 0;
      const __maxIterations = ${Z};
      while (${Q} && __safeCounter < __maxIterations) {
        __safeCounter++;
        result += \`${$}\`;
      }
      // 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 Zq,T,d,fq,$q,uq,pq,Wq=65536;var Yq=K(()=>{Zq={maxSanitizeDepth:10,allowBracketNotation:!1},T={...Zq};d=[/\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/],fq=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"]),$q=new Set(["__proto__","constructor","prototype"]),uq=/[\w)\]]\s*\[\s*['"]/;pq=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 rq(q){Gq=q}function nq(){return Gq}function oq(q){L={...L,...q}}function tq(){L={}}function Bq(q,Q={}){let J=L[q]||sq[q]||{message:`Unknown error (code: ${q})`},W=J.message,Z=J.help;for(let[$,X]of Object.entries(Q)){let Y=`{{${$}}}`;if(W=W.replace(new RegExp(Y,"g"),X),Z)Z=Z.replace(new RegExp(Y,"g"),X)}return{message:W,help:Z}}function aq(q,Q={}){let{message:J,help:W}=Bq(q,Q);return W?`${J}
  Help: ${W}`:J}function i(q){for(let[Q,J]of Object.entries(N))if(J===q)return Q;return}var sq,L,Gq="en",N;var S=K(()=>{sq={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"}},L={};N={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 qJ(){return!1}function b(){return!qJ()||process.env.STX_DEBUG==="true"}function VQ(){return!1}import JJ from"path";function QJ(q){E={...E,...q}}function C(){return{...E}}function WJ(){E={...Hq}}function y(q){if(!E.showRelativePaths||!q)return q;let Q=E.baseDir||process.cwd();try{let J=JJ.relative(Q,q);return J.startsWith("..")?q:J}catch{return q}}var Hq,E,j,Fq,Vq,Mq,_q,Rq;var v=K(()=>{S();Hq={showRelativePaths:!1,enableAutoRecovery:b(),logRecoveryWarnings:!0},E={...Hq};j=class j extends Error{code;filePath;line;column;context;numericCode;constructor(q,Q,J,W,Z,$,X){super(q);this.code=Q;this.filePath=J;this.line=W;this.column=Z;this.context=$;if(this.name="StxError",this.numericCode=X||N.EVALUATION_ERROR,this.filePath)this.filePath=y(this.filePath)}};Fq=class Fq extends j{constructor(q,Q,J,W,Z,$){super(q,"stx_SYNTAX_ERROR",Q,J,W,Z,$||N.INVALID_DIRECTIVE_SYNTAX);this.name="StxSyntaxError"}};Vq=class Vq extends j{constructor(q,Q,J,W,Z,$){super(q,"stx_RUNTIME_ERROR",Q,J,W,Z,$||N.EVALUATION_ERROR);this.name="StxRuntimeError"}};Mq=class Mq extends j{constructor(q,Q,J,W,Z,$){super(q,"stx_SECURITY_ERROR",Q,J,W,Z,$||N.UNSAFE_EXPRESSION);this.name="StxSecurityError"}};_q=class _q extends j{constructor(q,Q,J,W,Z,$){super(q,"stx_FILE_ERROR",Q,J,W,Z,$||N.FILE_NOT_FOUND);this.name="StxFileError"}};Rq=class Rq extends j{isFatal=!0;constructor(q,Q,J,W,Z,$){super(q,"stx_VALIDATION_ERROR",Q,J,W,Z,$||N.DOM_API_VIOLATION);this.name="StxValidationError"}}});function s(q){let{type:Q,message:J,code:W,filePath:Z,line:$,column:X,template:Y,offset:G,snippet:H,suggestion:B,format:F="text"}=q,V=$,A=X;if(!V&&Y&&G!==void 0){let z=Nq(Y,G);V=z.line,A=z.column}let R=Z?y(Z):void 0,M=W?i(W):void 0,D={type:Q,code:W,codeName:M,message:J,filePath:R,line:V,column:A,snippet:H,suggestion:B,timestamp:new Date().toISOString()},U;switch(F){case"html":U=$J(D);break;case"json":U=JSON.stringify(D,null,2);break;case"console":U=XJ(D,Y,G);break;case"text":default:U=ZJ(D,Y,G);break}return{formatted:U,data:D}}function ZJ(q,Q,J){let W=[],Z=q.code?` [${q.codeName||q.code}]`:"";if(W.push(`[${q.type} Error${Z}]`),q.filePath){let $=q.filePath;if(q.line){if($+=`:${q.line}`,q.column)$+=`:${q.column}`}W.push(`at ${$}`)}if(W.push(`
${q.message}`),Q&&q.line){let $=YJ(Q,q.line,2);if($)W.push(`
${$}`)}if(q.snippet)W.push(`
Snippet: ${q.snippet}`);if(q.suggestion)W.push(`
Suggestion: ${q.suggestion}`);return W.join(" ")}function $J(q){let Q=q.code?` [${q.code}]`:"",J=q.filePath?` in ${q.filePath}${q.line?`:${q.line}`:""}`:"",W=`<!-- [${q.type} Error${Q}]${J}: ${Uq(q.message)}`;if(q.suggestion)W+=` | Suggestion: ${Uq(q.suggestion)}`;return W+=" -->",W}function XJ(q,Q,J){let H=[],B=q.code?` [${q.codeName||q.code}]`:"";if(H.push(`\x1B[1m${"\x1B[31m"}\u2501\u2501\u2501 ${q.type} Error${B} \u2501\u2501\u2501${"\x1B[0m"}`),q.filePath){let F=`\x1B[36m${q.filePath}\x1B[0m`;if(q.line){if(F+=`\x1B[90m:${q.line}\x1B[0m`,q.column)F+=`\x1B[90m:${q.column}\x1B[0m`}H.push(`
\x1B[90mat\x1B[0m ${F}`)}if(H.push(`

${q.message}`),Q&&q.line){let F=GJ(Q,q.line,2);if(F)H.push(`

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

\x1B[33mSuggestion:\x1B[0m ${q.suggestion}`);return H.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"}`),H.join("")}function YJ(q,Q,J){let W=q.split(`
`),Z=Math.max(0,Q-J-1),$=Math.min(W.length-1,Q+J-1),X=[];for(let Y=Z;Y<=$;Y++){let G=(Y+1).toString().padStart(4),H=Y===Q-1?">":" ";X.push(`${H}${G} | ${W[Y]}`)}return X.join(`
`)}function GJ(q,Q,J){let W=q.split(`
`),Z=Math.max(0,Q-J-1),$=Math.min(W.length-1,Q+J-1),X="\x1B[90m",Y="\x1B[31m",G="\x1B[0m",H=[];for(let B=Z;B<=$;B++){let F=(B+1).toString().padStart(4),V=B===Q-1,A=V?"\x1B[31m>\x1B[0m":" ",R=V?`\x1B[31m${W[B]}\x1B[0m`:`\x1B[90m${W[B]}\x1B[0m`;H.push(`${A}\x1B[90m${F}\x1B[0m | ${R}`)}return H.join(`
`)}function Uq(q){return q.replace(/--/g,"- -").replace(/>/g,"&gt;")}function Nq(q,Q){let W=q.substring(0,Q).split(`
`);return{line:W.length,column:W[W.length-1].length}}function h(q,Q,J){return s({type:q,message:Q,code:J,format:"html"}).formatted}function BJ(q,Q,J,W,Z){return s({type:q,message:Q,code:Z,filePath:J,line:W,format:"console"}).formatted}function HJ(q,Q,J){let W=J.template.split(`
`),Z=Nq(J.template,J.offset),$=`[${q} Error at line ${Z.line} in ${J.filePath}]: ${Q}

`,X=Math.max(0,Z.line-3),Y=Math.min(W.length-1,Z.line+2);$+=`Context:
`;for(let G=X;G<=Y;G++){let H=G+1,B=W[G]||"",F=G===Z.line-1?">":" ";$+=`${F} ${H.toString().padStart(3)}: ${B}
`}if(Z.line-1<W.length){let G=" ".repeat(Z.column+5);$+=`${G}^
`}return $}function FJ(q,Q,J){try{return q()}catch(W){if(J&&W instanceof Error)J(W);return Q}}async function VJ(q,Q,J){try{return await q()}catch(W){if(J&&W instanceof Error)J(W);return Q}}var wq=K(()=>{S();v()});class r{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,Q,J="error"){let W={timestamp:new Date,error:q,context:Q,level:J};if(this.errors.push(W),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors);if(this.enableFileLogging&&this.shouldLog(J))this.writeToFile(W)}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 Q=[`[${q.timestamp.toISOString()}] [${(q.level||"error").toUpperCase()}] ${q.error.constructor.name}: ${q.error.message}`];if(q.error.stack)Q.push(`  Stack: ${q.error.stack.split(`
`).slice(1).join(`
  `)}`);if(q.context)Q.push(`  Context: ${JSON.stringify(q.context)}`);return Q.join(`
`)}writeToFile(q){this.writeQueue=this.writeQueue.then(async()=>{try{let Q=await import("fs"),W=(await import("path")).dirname(this.logFilePath);if(!Q.existsSync(W))Q.mkdirSync(W,{recursive:!0});await this.rotateIfNeeded(Q);let Z=`${this.formatEntry(q)}
`;Q.appendFileSync(this.logFilePath,Z,"utf-8")}catch(Q){if(process.env.STX_DEBUG==="true")console.error("Failed to write to error log:",Q)}})}async rotateIfNeeded(q){try{if(!q.existsSync(this.logFilePath))return;if(q.statSync(this.logFilePath).size<this.maxFileSize)return;for(let J=this.maxLogFiles-1;J>=1;J--){let W=`${this.logFilePath}.${J}`,Z=`${this.logFilePath}.${J+1}`;if(q.existsSync(W))if(J>=this.maxLogFiles-1)q.unlinkSync(W);else q.renameSync(W,Z)}if(this.maxLogFiles<=1)q.writeFileSync(this.logFilePath,"");else q.renameSync(this.logFilePath,`${this.logFilePath}.1`)}catch(Q){if(process.env.STX_DEBUG==="true")console.error("Failed to rotate error logs:",Q)}}getRecentErrors(q=10){return this.errors.slice(-q)}getErrorsByType(q){return this.errors.filter((Q)=>Q.error.constructor.name===q)}getErrorsByLevel(q){return this.errors.filter((Q)=>Q.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={},Q={error:0,warning:0,info:0};for(let J of this.errors){let W=J.error.constructor.name;q[W]=(q[W]||0)+1;let Z=J.level||"error";Q[Z]=(Q[Z]||0)+1}return{total:this.errors.length,byType:q,byLevel:Q}}async exportToFile(q,Q="json"){let J=await import("fs"),Z=(await import("path")).dirname(q);if(!J.existsSync(Z))J.mkdirSync(Z,{recursive:!0});if(Q==="json"){let $=this.errors.map((X)=>({timestamp:X.timestamp.toISOString(),level:X.level||"error",type:X.error.constructor.name,message:X.error.message,stack:X.error.stack,context:X.context}));J.writeFileSync(q,JSON.stringify($,null,2),"utf-8")}else{let $=this.errors.map((X)=>this.formatEntry(X));J.writeFileSync(q,$.join(`

`),"utf-8")}}async flush(){await this.writeQueue}}var MJ,_J,RJ;var Dq=K(()=>{v();MJ={isEnabled(){return C().enableAutoRecovery},fixCommonSyntaxErrors(q){let Q=C();if(!Q.enableAutoRecovery)return{fixed:q,fixes:[]};let J=q,W=[],Z=(J.match(/\{\{/g)||[]).length,$=(J.match(/\}\}/g)||[]).length;if(Z>$){let Y=Z-$;J+="}}".repeat(Y),W.push(`Added ${Y} missing closing braces '}}'`)}let X=["if","foreach","for","switch","section"];for(let Y of X){let G=(J.match(new RegExp(`@${Y}\\b`,"g"))||[]).length,H=(J.match(new RegExp(`@end${Y}\\b`,"g"))||[]).length;if(G>H){let B=G-H;for(let F=0;F<B;F++)J+=`
@end${Y}`;W.push(`Added ${B} missing @end${Y}`)}}if(W.length>0&&Q.logRecoveryWarnings)console.warn("[stx] Auto-recovery applied fixes:"),W.forEach((Y)=>console.warn(`  - ${Y}`)),console.warn("  Consider fixing these issues in your template.");return{fixed:J,fixes:W}},createFallbackContent(q,Q){if(b())return`<!-- ${q} failed: ${Q.message} -->`;return"<!-- stx rendering error -->"}};_J=new r,RJ={isDevelopment(){return b()},logDetailedError(q,Q){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",q.message),console.error("Stack:",q.stack),Q)console.error("Context:",Q);console.error("========================")},createErrorReport(q,Q){let J=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${q.message}`,`Type: ${q.constructor.name}`,`Stack: ${q.stack}`];if(Q)J.push(`Context: ${JSON.stringify(Q,null,2)}`);return J.push("========================"),J.join(`
`)}}});import n from"path";function UJ(q){let Q={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return q.replace(/[&<>"']/g,(J)=>Q[J]||J)}function g(q,Q={}){let{allowHtml:J=!1,maxLength:W=1e4,allowSpecialChars:Z=!0,customSanitizer:$}=Q,X=[],Y=q,G=!1;if($){let B=$(Y);if(B!==Y)Y=B,G=!0}if(Y.includes("\x00"))Y=Y.replace(/\0/g,""),G=!0,X.push("Null bytes removed from parameter");if(Y.length>W)Y=Y.substring(0,W),G=!0,X.push(`Parameter truncated to ${W} characters`);if(!J&&/<[^>]+>/.test(Y))Y=UJ(Y),G=!0,X.push("HTML content was escaped");let H=[{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:B,replacement:F,name:V}of H)if(B.test(Y))Y=Y.replace(B,F),G=!0,X.push(`Removed ${V} from parameter`);if(!Z){let B=Y;if(Y=Y.split("").filter((F)=>{let V=F.charCodeAt(0);return V>=32&&V!==127}).join(""),Y!==B)G=!0,X.push("Control characters removed")}return{value:Y,modified:G,warnings:X}}function NJ(q,Q){let J=q.replace(/\0/g,"");J=J.replace(/\\/g,"/"),J=J.replace(/^[a-z][a-z0-9+.-]*:/i,"");while(J.includes("../")||J.includes("./"))J=J.replace(/\.\.\//g,"").replace(/\.\//g,"");if(!o.isValidFilePath(J,Q))return null;return J}function wJ(q){let Q=[],J=q.trim(),W=J!==q,Z=[{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:$,name:X}of Z)if($.test(J))Q.push(`Potentially dangerous pattern detected: ${X}`);if(J.includes("\x00"))J=J.replace(/\0/g,""),W=!0,Q.push("Null bytes removed from expression");return{value:J,modified:W,warnings:Q}}function DJ(q,Q={}){return q.map((J)=>g(J,Q))}function Kq(q){let Q={};for(let[J,W]of Object.entries(q)){if(!o.isValidVariableName(J))continue;if(typeof W==="string"){let Z=g(W);Q[J]=Z.value}else if(Array.isArray(W))Q[J]=W.map((Z)=>typeof Z==="string"?g(Z).value:Z);else if(typeof W==="object"&&W!==null)Q[J]=Kq(W);else Q[J]=W}return Q}var o;var Oq=K(()=>{o={isValidFilePath(q,Q){let J=q.replace(/\\/g,"/");if(J.includes("\x00"))return!1;if(J.includes("../")||J.includes("..\\")||J===".."||J.startsWith("../")||J.endsWith("/..")||J.includes("/..\\")||J.includes("\\../"))return!1;if(/^[a-z][a-z0-9+.-]*:/i.test(J))return!1;if(J.startsWith("/")){if(["/etc/","/root/","/var/","/usr/","/bin/","/sbin/","/proc/","/sys/","/dev/","/boot/","/home/","/private/","/Library/","/System/"].some(($)=>J===$.slice(0,-1)||J.startsWith($)))return!1}if(/^[a-z]:/i.test(J)){if(["Windows/","Windows\\","System32/","System32\\","Program Files/","Program Files\\"].some(($)=>J.includes($)))return!1}if(Q){let Z=n.resolve(Q,q),$=n.resolve(Q);if(!Z.startsWith($+n.sep)&&Z!==$)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((J)=>J.test(q))}}});var Aq=K(()=>{S();wq();Dq();Oq();v()});var Iq=K(()=>{Aq()});var tJ={};xq(tJ,{waitForLocale:()=>kJ,processTranslateDirective:()=>nJ,preloadTranslationsBackground:()=>EJ,preloadTranslations:()=>Tq,loadTranslationLazy:()=>P,loadTranslation:()=>bq,isLoading:()=>zJ,isLoaded:()=>TJ,isICUFormat:()=>Lq,getTranslationSync:()=>Eq,getTranslationCacheStats:()=>AJ,getTranslationAsync:()=>bJ,getTranslation:()=>x,getLoadingState:()=>jJ,getLoadingLocales:()=>PJ,formatICU:()=>kq,defaultI18nConfig:()=>f,createTranslateFilter:()=>oJ,clearTranslationCache:()=>OJ,cancelPendingLoads:()=>LJ});import a from"path";async function KJ(){if(k!==void 0)return k;try{k=(await import("@stacksjs/ts-i18n")).loadLocale??null}catch{k=null}return k}function OJ(q){if(q)delete _[q];else for(let Q of Object.keys(_))delete _[Q]}function AJ(){let q=Object.entries(_).map(([Q,J])=>({locale:Q,loadedAt:new Date(J.loadedAt),keyCount:zq(J.translations)}));return{size:Object.keys(_).length,locales:Object.keys(_),entries:q}}function zq(q,Q=0){for(let J of Object.values(q))if(Q++,J&&typeof J==="object"&&!Array.isArray(J))Q=zq(J,Q);return Q}function IJ(q,Q=0){if(Q<=0)return!1;return Date.now()-q.loadedAt>Q}function jJ(q){if(_[q])return"loaded";return O[q]||"idle"}function zJ(q){return O[q]==="loading"}function TJ(q){return!!_[q]}async function Tq(q,Q){let{locales:J,parallel:W=!0,priority:Z={},onLocaleLoaded:$,onComplete:X,onError:Y}=q,G=W?J:[...J].sort((H,B)=>(Z[B]||0)-(Z[H]||0));if(W){let H=G.map(async(B)=>{try{await P(B,Q),$?.(B)}catch(F){Y?.(B,F instanceof Error?F:Error(String(F)))}});await Promise.all(H)}else for(let H of G)try{await P(H,Q),$?.(H)}catch(B){Y?.(H,B instanceof Error?B:Error(String(B)))}X?.()}function EJ(q,Q){queueMicrotask(()=>{Tq(q,Q).catch((J)=>{if(Q.debug)console.error("Background preload error:",J)})})}async function P(q,Q){if({...f,...Q.i18n}.cache&&_[q]){let Z=_[q],$=Q.i18n?.cacheMaxAge??0;if(!IJ(Z,$))return Z.translations}if(w[q]?.state==="loading")return w[q].promise;O[q]="loading";let W=e(q,Q).then((Z)=>{return O[q]="loaded",delete w[q],Z}).catch((Z)=>{throw O[q]="error",w[q]={promise:W,state:"error",error:Z instanceof Error?Z:Error(String(Z))},Z});return w[q]={promise:W,state:"loading"},W}function Eq(q){return _[q]?.translations}async function bJ(q,Q){let J=Eq(q);if(J)return J;return P(q,Q)}async function kJ(q,Q){if(_[q])return _[q].translations;if(w[q]){if(Q)return Promise.race([w[q].promise,new Promise((J,W)=>setTimeout(()=>W(Error(`Timeout waiting for locale: ${q}`)),Q))]);return w[q].promise}throw Error(`Locale "${q}" is not loading. Call loadTranslationLazy first.`)}function PJ(){return Object.entries(O).filter(([q,Q])=>Q==="loading").map(([q])=>q)}function LJ(q){if(q)delete w[q],delete O[q];else{for(let Q of Object.keys(w))delete w[Q];for(let Q of Object.keys(O))delete O[Q]}}async function e(q,Q){let J={...f,...Q.i18n},W=a.isAbsolute(J.translationsDir)?J.translationsDir:a.resolve(Q.root||process.cwd(),J.translationsDir);try{let Z=await KJ(),$=Z?await Z(q,{translationsDir:W,defaultLocale:J.defaultLocale,sources:hJ(J.format)}):await SJ(q,J,W);if($===void 0){if(q!==J.defaultLocale)return e(J.defaultLocale,Q);return{}}let X=$;if(J.cache)_[q]={translations:X,loadedAt:Date.now(),locale:q};return X}catch(Z){if(Q.debug)console.error(`Error loading translation file for locale "${q}":`,Z);if(q!==J.defaultLocale)return e(J.defaultLocale,Q);return{}}}async function SJ(q,Q,J){let W=a.join(J,`${q}${CJ(Q.format)}`);try{let Z=await import(W);return Z.default||Z}catch(Z){try{let $=await Bun.file(W).text();if(Q.format==="yaml"||Q.format==="yml")return yJ($);if(Q.format==="json")return JSON.parse($);throw Z}catch{return}}}function CJ(q){switch(q){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"ts":return".ts";case"json":default:return".json"}}function yJ(q){let Q={},J=q.split(`
`),W=[{obj:Q,indent:-1}];for(let Z of J){let $=Z.replace(/#.*$/,"").trimEnd();if(!$.trim())continue;let X=$.search(/\S/);if(X===-1)continue;while(W.length>1&&W[W.length-1].indent>=X)W.pop();let Y=W[W.length-1].obj,G=$.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(G){let[,,H,B]=G,F=H.trim(),V=B.trim();if(V==="")Y[F]={},W.push({obj:Y[F],indent:X});else Y[F]=vJ(V)}}return Q}function vJ(q){if(q.startsWith("'")&&q.endsWith("'")||q.startsWith('"')&&q.endsWith('"'))return q.slice(1,-1);let Q=q.toLowerCase();if(Q==="true"||Q==="yes")return!0;if(Q==="false"||Q==="no")return!1;if(Q==="null"||Q==="~")return null;let J=Number(q);if(!Number.isNaN(J)&&q!=="")return J;return q}function hJ(q){switch(q){case"yaml":case"yml":return["yaml"];case"js":case"ts":return["ts"];case"json":default:return["json"]}}async function bq(q,Q){return P(q,Q)}function gJ(q,Q){for(let J of q){let W=J.trim(),Z=W.match(/^\{(\d+)\}\s*(.*)$/);if(Z){let X=Number.parseInt(Z[1],10);if(Q===X)return Z[2];continue}let $=W.match(/^\[(\d+),(\d+|\*)\]\s*(.*)$/);if($){let X=Number.parseInt($[1],10),Y=$[2]==="*"?Number.POSITIVE_INFINITY:Number.parseInt($[2],10);if(Q>=X&&Q<=Y)return $[3];continue}}if(q.length===2)return Q===1?q[0].trim():q[1].trim();if(Q<q.length)return q[Q].trim();return q[q.length-1].trim()}function kq(q,Q={}){return Pq(q,Q)}function Pq(q,Q){let J="",W=0;while(W<q.length)if(q[W]==="{"){let Z=xJ(q,W);if(Z===-1){J+=q[W],W++;continue}let $=q.slice(W+1,Z);J+=fJ($,Q),W=Z+1}else if(q[W]==="'"&&W+1<q.length)if(q[W+1]==="'")J+="'",W+=2;else if(q[W+1]==="{"||q[W+1]==="}")J+=q[W+1],W+=2;else J+=q[W],W++;else J+=q[W],W++;return J}function xJ(q,Q){let J=0;for(let W=Q;W<q.length;W++)if(q[W]==="{")J++;else if(q[W]==="}"){if(J--,J===0)return W}return-1}function fJ(q,Q){let J=uJ(q);if(J.length===0)return`{${q}}`;let W=J[0].trim(),Z=Q[W];if(J.length===1)return Z!==void 0?String(Z):`{${W}}`;switch(J[1].trim().toLowerCase()){case"plural":return mJ(Z,J.slice(2).join(","),Q);case"select":return cJ(Z,J.slice(2).join(","));case"selectordinal":return pJ(Z,J.slice(2).join(","));case"number":return iJ(Z,J[2]?.trim());case"date":return sJ(Z,J[2]?.trim());case"time":return rJ(Z,J[2]?.trim());default:return Z!==void 0?String(Z):`{${q}}`}}function uJ(q){let Q=[],J="",W=0;for(let Z=0;Z<q.length;Z++){let $=q[Z];if($==="{")W++,J+=$;else if($==="}")W--,J+=$;else if($===","&&W===0)Q.push(J),J="";else J+=$}if(J)Q.push(J);return Q}function mJ(q,Q,J){let W=Number(q)||0,Z=qq(Q),$=`=${W}`;if(Z[$])return t(Z[$],W,J);let X=dJ(W);if(Z[X])return t(Z[X],W,J);if(Z.other)return t(Z.other,W,J);return String(W)}function t(q,Q,J){let W=q.replace(/#/g,String(Q));return Pq(W,J)}function dJ(q){let Q=Math.abs(q),J=Math.floor(Q),W=String(q).includes(".")?String(q).split(".")[1].length:0;if(J===1&&W===0)return"one";return"other"}function cJ(q,Q){let J=String(q||""),W=qq(Q);if(W[J])return W[J];return W.other||String(q)}function pJ(q,Q){let J=Number(q)||0,W=qq(Q),Z=lJ(J);if(W[Z])return W[Z].replace(/#/g,String(J));if(W.other)return W.other.replace(/#/g,String(J));return String(J)}function lJ(q){let Q=Math.abs(q),J=Q%10,W=Q%100;if(J===1&&W!==11)return"one";if(J===2&&W!==12)return"two";if(J===3&&W!==13)return"few";return"other"}function qq(q){let Q={},J=/(\w+|=\d+)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,W=J.exec(q);while(W!==null)Q[W[1]]=W[2],W=J.exec(q);return Q}function iJ(q,Q){let J=Number(q);if(Number.isNaN(J))return String(q);switch(Q){case"integer":return Math.floor(J).toLocaleString();case"percent":return`${(J*100).toFixed(0)}%`;case"currency":return J.toLocaleString(void 0,{style:"currency",currency:"USD"});default:return J.toLocaleString()}}function sJ(q,Q){let J=q instanceof Date?q:new Date(String(q));if(Number.isNaN(J.getTime()))return String(q);let W={};switch(Q){case"short":W.dateStyle="short";break;case"medium":W.dateStyle="medium";break;case"long":W.dateStyle="long";break;case"full":W.dateStyle="full";break;default:W.dateStyle="medium"}return J.toLocaleDateString(void 0,W)}function rJ(q,Q){let J=q instanceof Date?q:new Date(String(q));if(Number.isNaN(J.getTime()))return String(q);let W={};switch(Q){case"short":W.timeStyle="short";break;case"medium":W.timeStyle="medium";break;case"long":W.timeStyle="long";break;case"full":W.timeStyle="full";break;default:W.timeStyle="short"}return J.toLocaleTimeString(void 0,W)}function Lq(q){return/\{[^}]+,\s*(?:plural|select|selectordinal|number|date|time)\s*,/.test(q)}function x(q,Q,J=!0,W={}){let Z=q.split("."),$=Q;for(let Y of Z){if($===void 0||$===null)break;$=$[Y]}if($===void 0||$===null)return J?q:"";let X=String($);if(Lq(X))return kq(X,W);if(X.includes("|")&&"count"in W){let Y=Number(W.count),G=X.split("|");X=gJ(G,Y)}for(let[Y,G]of Object.entries(W)){let H=Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");X=X.replace(new RegExp(`:${H}`,"g"),String(G))}return X}async function nJ(q,Q,J,W){let Z=q,$=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)([\s\S]*?)@endtranslate/g,X={...f,...W.i18n},Y=await bq(X.locale,W);Q.__translations=Y,Q.__locale=X.locale,Q.__i18nConfig=X,Z=await jq(Z,$,async(B,F,V,A,R)=>{try{let M={};if(V)try{let U=[()=>JSON.parse(V),()=>{let z=`{"data":${V}}`,Jq=JSON.parse(z);return typeof Jq.data==="object"?Jq.data:{}},()=>{return l(V,Q)}];for(let z of U)try{if(M=z(),Object.keys(M).length>0)break}catch{}}catch(U){if(W.debug)console.error("Error parsing parameters for @translate directive:",U)}return x(F,Y,X.fallbackToKey,M)||A.trim()}catch(M){if(W.debug)console.error("Error processing @translate directive:",M);return h("Translate",`Error in @translate('${F}'): ${M instanceof Error?M.message:String(M)}`,N.EVALUATION_ERROR)}});let G=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]+\})\s*)?\)/g;if(W.debug){console.warn(`Processing translations in template. Sections: ${Z.includes("<h2>Translation with Parameters</h2>")?"Parameters section found":"Parameters section missing"}`);let B=[...Z.matchAll(G)];console.warn(`Found ${B.length} @translate matches`),B.forEach((F,V)=>console.warn(`Match ${V}: ${F[0]}, Key: ${F[1]}, Params: ${F[2]||"none"}`))}return Z=await jq(Z,/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)/g,async(B,F,V,A)=>{try{let R={};if(V)try{let M=[()=>JSON.parse(V),()=>{let D=`{"data":${V}}`,U=JSON.parse(D);return typeof U.data==="object"?U.data:{}},()=>{return l(V,Q)}];for(let D of M)try{if(R=D(),Object.keys(R).length>0)break}catch{}}catch(M){if(W.debug)console.error("Error parsing parameters for @translate directive:",M)}return x(F,Y,X.fallbackToKey,R)}catch(R){if(W.debug)console.error("Error processing @translate directive:",R);return h("Translate",`Error in @translate('${F}'): ${R instanceof Error?R.message:String(R)}`,N.EVALUATION_ERROR)}}),Z}async function jq(q,Q,J){let W=[];return q.replace(Q,($,...X)=>{let Y=J($,...X).then((G)=>({match:$,replacement:G}));return W.push(Y),$}),(await Promise.all(W)).reduce(($,{match:X,replacement:Y})=>$.replace(X,Y),q)}function oJ(q,Q=!0){return(J,W={})=>{return x(J,q,Q,W)}}var k,f,_,w,O;var aJ=K(()=>{Iq();Yq();f={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},_={},w={},O={}});aJ();export{kJ as waitForLocale,nJ as processTranslateDirective,EJ as preloadTranslationsBackground,Tq as preloadTranslations,P as loadTranslationLazy,bq as loadTranslation,zJ as isLoading,TJ as isLoaded,Lq as isICUFormat,Eq as getTranslationSync,AJ as getTranslationCacheStats,bJ as getTranslationAsync,x as getTranslation,jJ as getLoadingState,PJ as getLoadingLocales,kq as formatICU,f as defaultI18nConfig,oJ as createTranslateFilter,OJ as clearTranslationCache,LJ as cancelPendingLoads};
