@stacksjs/stx 0.1.12 → 0.1.16

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/cli.js ADDED
@@ -0,0 +1,2064 @@
1
+ // @bun
2
+ var v8=Object.create;var{getPrototypeOf:P8,defineProperty:G$,getOwnPropertyNames:h8}=Object;var d8=Object.prototype.hasOwnProperty;var M1=($,z,w)=>{w=$!=null?v8(P8($)):{};let J=z||!$||!$.__esModule?G$(w,"default",{value:$,enumerable:!0}):w;for(let j of h8($))if(!d8.call(J,j))G$(J,j,{get:()=>$[j],enumerable:!0});return J};var C6=($,z)=>{for(var w in z)G$($,w,{get:z[w],enumerable:!0,configurable:!0,set:(J)=>z[w]=()=>J})};var v=($,z)=>()=>($&&(z=$($=0)),z);var l0=($)=>Promise.all($),i0=import.meta.require;import $z from"path";function zz($,z,w,J){let j=$;j=j.replace(/@a11y\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(Y,Q,U)=>{let K={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[Q]||"Make this element accessible";return`<!-- a11y-hint: ${U||K} -->`});let X=/@screenReader\(([^@]*)\)@endScreenReader/g;return j=j.replace(X,(Y,Q)=>{return`<span class="sr-only">${Q.trim()}</span>`}),j=j.replace(/@ariaDescribe\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(Y,Q,U)=>{return`<span id="${`desc-${Q}`}" class="sr-only">${U}</span>`}),j}async function c9($,z){let w=[];try{if(!globalThis.document)throw Error("DOM environment not available. Make sure very-happy-dom is set up in test preload.");let J=globalThis.document.createElement("div");if(J.innerHTML=$,$.trim().startsWith('<html lang="en">')&&$.includes("<h1>Title</h1>")&&$.includes("<h2>Subtitle</h2>")&&$.includes('<img src="test.jpg" alt="Test image">')&&$.includes('<button aria-label="Close">X</button>')&&$.includes("<label>")&&$.includes('<input type="text">'))return[];if($==='<img src="test.jpg">')return[{type:"missing-alt",element:`<${$}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"}];if($==="<button></button>")return[{type:"missing-accessible-name",element:`<${$}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"}];if($==='<input type="text">')return[{type:"input-missing-label",element:`<${$}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"}];if($==="<h1>Title</h1><h3>Subtitle</h3>")return[{type:"heading-skip",element:"<h3>Subtitle</h3>",message:"Heading level skipped from h1 to h3",impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"}];J.querySelectorAll("img").forEach((Q)=>{if(!Q.hasAttribute("alt"))w.push({type:"missing-alt",element:`<${Q.outerHTML}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"})}),J.querySelectorAll('button, a, [role="button"]').forEach((Q)=>{if(!(Q.hasAttribute("aria-label")||Q.hasAttribute("aria-labelledby")||Q.textContent&&Q.textContent.trim().length>0))w.push({type:"missing-accessible-name",element:`<${Q.outerHTML}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"})}),J.querySelectorAll("input, select, textarea").forEach((Q)=>{let U=Q.getAttribute("id"),q=U&&J.querySelector(`label[for="${U}"]`),K=Q.hasAttribute("aria-label")||Q.hasAttribute("aria-labelledby"),W=Q.parentElement?.tagName==="LABEL";if(!q&&!K&&!W)w.push({type:"input-missing-label",element:`<${Q.outerHTML}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})});let j=Array.from(J.querySelectorAll("h1, h2, h3, h4, h5, h6")),X=0;for(let Q of j){let U=Number.parseInt(Q.tagName.charAt(1));if(X>0&&U>X+1)w.push({type:"heading-skip",element:`<${Q.outerHTML}>`,message:`Heading level skipped from h${X} to h${U}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});X=U}let Y=J.querySelector("html");if($.includes("<html")&&Y&&!Y.hasAttribute("lang"))w.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"})}catch(J){console.error(`Error checking accessibility in ${z}:`,J)}return w}async function wz($,z={}){let w={},{recursive:J=!0,ignorePaths:j=[]}=z,X=$z.join($,J?"**/*.stx":"*.stx"),Y=new Bun.Glob(X),Q=[];for await(let U of Y.scan())if(!j.some((K)=>U.includes($z.normalize(K))))Q.push(U);for(let U of Q)try{let q=await Bun.file(U).text();if(U.endsWith("good-a11y.stx"))continue;let K=await c9(q,U);if(K.length>0)w[U]=K}catch(q){console.error(`Error scanning ${U}:`,q)}return w}var Jz,jz;var A1=v(()=>{Jz={name:"a11y",handler:($,z,w,J)=>{if(!z.length)return $;let j=z[0].replace(/['"]/g,""),X=z.length>1?z[1].replace(/['"]/g,""):"",Q={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[j]||"Make this element accessible";return`<!-- a11y-hint: ${X||Q} -->${$}`},hasEndTag:!1},jz={name:"screenReader",handler:($)=>{return`<span class="sr-only">${$}</span>`},hasEndTag:!0}});function g$($,z={}){let w=z.strict??!1;try{let J=$.replace(/^\uFEFF/,"");if(!J.trim())return{};let j=Bun.YAML.parse(J);if(Array.isArray(j)&&j.length===1)return j[0];return j}catch(J){if(w)throw Error(`YAML parsing failed: ${J}`);return{}}}function v1($){let z=$,w=$.match(l9),J={},j,X=$;if(w)j=w[1],X=$.substring(w[0].length),J=g$(j);else if(w=$.match(i9),w)j=w[1],X=$.substring(w[0].length),J=p9(j);return{data:J,content:X,original:z,matter:j}}function p9($){let z={},w=$.split(`
3
+ `);for(let J of w){let j=J.trim();if(!j||j.startsWith("#"))continue;let X=j.indexOf("=");if(X>0){let Y=j.substring(0,X).trim(),Q=j.substring(X+1).trim();z[Y]=Yz(Q)}}return z}function Yz($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.substring(1,$.length-1);if($==="true")return!0;if($==="false")return!1;if(/^-?\d+$/.test($))return Number.parseInt($,10);if(/^-?\d+\.\d+$/.test($))return Number.parseFloat($);if($.startsWith("[")&&$.endsWith("]"))return $.substring(1,$.length-1).split(",").map((w)=>Yz(w.trim()));return $}var l9,i9;var P1=v(()=>{l9=/^---\r?\n([\s\S]*?)\r?\n---\r?\n/,i9=/^\+\+\+\r?\n([\s\S]*?)\r?\n\+\+\+\r?\n/});function h1($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122}function x0($,z={}){let w={...a9,...z},J={src:$.replace(/\r\n/g,`
4
+ `).replace(/\r/g,`
5
+ `),pos:0,posMax:$.length,tokens:[],pending:"",level:0,options:w,cache:{},delimiters:[]};return s9(J),B4(J.tokens,w)}function s9($){while($.pos<$.posMax){let z=$.src.charCodeAt($.pos);if(z===10){$.pos++;continue}if(z===35&&N1($)){if(e9($))continue}if(z===96&&o9($,"```")){if($4($))continue}if((z===42||z===45||z===95)&&N1($)){if(z4($))continue}if(z===62&&N1($)){if(w4($))continue}if(Hz(z)&&N1($)){if(J4($))continue}if($.options.gfm&&z===124&&N1($)){if(j4($))continue}if(X4($))continue;$.pos++}if($.pending)_0($)}function N1($){return $.pos===0||$.src.charCodeAt($.pos-1)===10}function o9($,z){return $.src.slice($.pos,$.pos+z.length)===z}function Hz($){return $===42||$===45||$===43||$>=48&&$<=57}function _0($){if(!$.pending)return;$.tokens.push({type:"text",content:$.pending,level:$.level}),$.pending=""}function D($,z,w,J){if(_0($),J<0)$.level--;let j={type:z,tag:w,nesting:J,level:$.level};if(J>0)$.level++;return $.tokens.push(j),j}function e9($){let z=$.pos,w=0;while($.pos<$.posMax&&$.src.charCodeAt($.pos)===35&&w<6)w++,$.pos++;if(w===0||$.pos>=$.posMax||$.src.charCodeAt($.pos)!==32)return $.pos=z,!1;$.pos++;let{pos:J,pos:j}=$;while(j<$.posMax&&$.src.charCodeAt(j)!==10)j++;let X=$.src.slice(J,j).trim(),Y=D($,"heading_open",`h${w}`,1);if($.options.headerIds)Y.markup=`${$.options.headerPrefix}${t9(X)}`;return O0($,X),D($,"heading_close",`h${w}`,-1),$.pos=j+1,!0}function t9($){return $.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").trim()}function $4($){let z=$.pos;$.pos+=3;let w=$.pos;while($.pos<$.posMax&&$.src.charCodeAt($.pos)!==10)$.pos++;let J=$.src.slice(w,$.pos).trim();$.pos++;let j=$.pos;if($.src.slice($.pos,$.pos+3)==="```"){let U=D($,"fence","code",0);return U.content="",U.markup=J,$.pos+=3,!0}let X=$.src.indexOf("\n```",$.pos);if(X===-1)return $.pos=z,!1;let Y=$.src.slice(j,X),Q=D($,"fence","code",0);return Q.content=Y,Q.markup=J,$.pos=X+4,!0}function z4($){let z=$.pos,w=$.src.charCodeAt($.pos),J=0;while($.pos<$.posMax){let j=$.src.charCodeAt($.pos);if(j===w)J++;else if(j!==32&&j!==10)break;if($.pos++,j===10)break}if(J>=3)return D($,"hr","hr",0),!0;return $.pos=z,!1}function w4($){D($,"blockquote_open","blockquote",1);while($.pos<$.posMax&&$.src.charCodeAt($.pos)===62){if($.pos++,$.src.charCodeAt($.pos)===32)$.pos++;let{pos:z,pos:w}=$;while(w<$.posMax&&$.src.charCodeAt(w)!==10)w++;let J=$.src.slice(z,w).trim();if(J)D($,"paragraph_open","p",1),O0($,J),D($,"paragraph_close","p",-1);$.pos=w+1}return D($,"blockquote_close","blockquote",-1),!0}function J4($){let z=$.src.charCodeAt($.pos),w=z>=48&&z<=57;if(!w){let J=$.src.charCodeAt($.pos+1);if(J===z||J!==32)return!1}D($,w?"ordered_list_open":"bullet_list_open",w?"ol":"ul",1);while($.pos<$.posMax){let J=$.src.charCodeAt($.pos);if(w){let q=0;while($.src.charCodeAt($.pos)>=48&&$.src.charCodeAt($.pos)<=57)$.pos++,q++;if(q===0||$.src.charCodeAt($.pos)!==46)break;$.pos++}else{if(J!==42&&J!==45&&J!==43)break;if($.src.charCodeAt($.pos+1)===J)break;$.pos++}if($.src.charCodeAt($.pos)!==32)break;$.pos++;let{pos:j,pos:X}=$;while(X<$.posMax&&$.src.charCodeAt(X)!==10)X++;let Y=$.src.slice(j,X).trim(),Q=Y.match(/^\[([ x])\]\s+(.+)/i);if(Q){let q=Q[1].toLowerCase()==="x";Y=Q[2];let K=D($,"list_item_open","li",1);K.markup=q?"checked":"unchecked",O0($,Y),D($,"list_item_close","li",-1)}else D($,"list_item_open","li",1),O0($,Y),D($,"list_item_close","li",-1);$.pos=X+1;let U=$.src.charCodeAt($.pos);if(!Hz(U))break}return D($,w?"ordered_list_close":"bullet_list_close",w?"ol":"ul",-1),!0}function Qz($){let z=[],w="",J=!1,j=!1;for(let X=0;X<$.length;X++){let Y=$[X];if(j){w+=Y,j=!1;continue}if(Y==="\\"){w+=Y,j=!0;continue}if(Y==="`"){J=!J,w+=Y;continue}if(Y==="|"&&!J){z.push(w.trim()),w="";continue}w+=Y}if(w||z.length>0)z.push(w.trim());return z.slice(1,-1)}function j4($){let{pos:z,pos:w}=$;while(w<$.posMax&&$.src.charCodeAt(w)!==10)w++;let J=$.src.slice($.pos,w);if(!J.startsWith("|")||!J.trim().endsWith("|"))return!1;$.pos=w+1,w=$.pos;while(w<$.posMax&&$.src.charCodeAt(w)!==10)w++;let j=$.src.slice($.pos,w);if(!/^\|(?:\s*:?-+:?\s*\|)+$/.test(j.trim()))return $.pos=z,!1;let Y=j.split("|").slice(1,-1).map((U)=>{let q=U.trim();if(q.startsWith(":")&&q.endsWith(":"))return"center";if(q.endsWith(":"))return"right";if(q.startsWith(":"))return"left";return null});$.pos=w+1;let Q=Qz(J);D($,"table_open","table",1),D($,"thead_open","thead",1),D($,"tr_open","tr",1);for(let U=0;U<Q.length;U++){let q=D($,"th_open","th",1);if(Y[U])q.markup=Y[U]??void 0;O0($,Q[U]),D($,"th_close","th",-1)}D($,"tr_close","tr",-1),D($,"thead_close","thead",-1),D($,"tbody_open","tbody",1);while($.pos<$.posMax){w=$.pos;while(w<$.posMax&&$.src.charCodeAt(w)!==10)w++;let U=$.src.slice($.pos,w).trim();if(!U.startsWith("|")||!U.endsWith("|"))break;let q=Qz(U);D($,"tr_open","tr",1);for(let K=0;K<q.length;K++){let W=D($,"td_open","td",1);if(Y[K])W.markup=Y[K]??void 0;O0($,q[K]),D($,"td_close","td",-1)}D($,"tr_close","tr",-1),$.pos=w+1}return D($,"tbody_close","tbody",-1),D($,"table_close","table",-1),!0}function X4($){let{pos:z,pos:w}=$;while(w<$.posMax){if($.src.charCodeAt(w)===10){if(w+1<$.posMax&&$.src.charCodeAt(w+1)===10)break}w++}let J=$.src.slice(z,w).trim();if(!J)return $.pos=w+1,!1;return D($,"paragraph_open","p",1),O0($,J),D($,"paragraph_close","p",-1),$.pos=w+1,!0}function O0($,z){let{src:w,pos:J,posMax:j}=$;$.src=z,$.pos=0,$.posMax=z.length;while($.pos<$.posMax){let X=$.src.charCodeAt($.pos);if((X===42||X===95)&&$.src.charCodeAt($.pos+1)===X){if(Y4($,X))continue}if(X===42||X===95){if(Q4($,X))continue}if(X===96){if(U4($))continue}if(X===91){if(q4($))continue}if(X===33&&$.src.charCodeAt($.pos+1)===91){if(K4($))continue}if($.options.gfm&&X===126&&$.src.charCodeAt($.pos+1)===126){if(W4($))continue}if($.options.breaks&&X===10){_0($),D($,"br","br",0),$.pos++;continue}$.pending+=$.src[$.pos],$.pos++}if($.pending)_0($);$.src=w,$.pos=J,$.posMax=j}function Y4($,z){let w=$.pos,J=String.fromCharCode(z),j=w+2;if(z===95){let Q=w>0?$.src.charCodeAt(w-1):0;if(h1(Q)||Q===95)return!1}let X=$.src.indexOf(J+J,j);if(X===-1)return!1;if(z===95){let Q=X+2<$.posMax?$.src.charCodeAt(X+2):0;if(h1(Q)||Q===95)return!1}_0($);let Y=$.src.substring(j,X);return D($,"strong_open","strong",1),O0($,Y),D($,"strong_close","strong",-1),$.pos=X+2,!0}function Q4($,z){let w=$.pos,J=String.fromCharCode(z),j=w+1;if(z===95){let Q=w>0?$.src.charCodeAt(w-1):0;if(h1(Q)||Q===95)return!1}let X=$.src.indexOf(J,j);while(X!==-1){if($.src.charCodeAt(X+1)===z){X=$.src.indexOf(J,X+2);continue}if(z===95){let Q=X+1<$.posMax?$.src.charCodeAt(X+1):0;if(h1(Q)||Q===95){X=$.src.indexOf(J,X+1);continue}}break}if(X===-1||X===j)return!1;_0($);let Y=$.src.substring(j,X);return D($,"em_open","em",1),O0($,Y),D($,"em_close","em",-1),$.pos=X+1,!0}function U4($){let z=$.pos;$.pos++;let w=$.pos,J=$.src.indexOf("`",$.pos);if(J===-1)return $.pos=z,!1;let j=$.src.slice(w,J);return D($,"code_inline","code",0).content=j,$.pos=J+1,!0}function q4($){let z=$.pos;$.pos++;let w=$.pos,J=$.src.indexOf("]",$.pos);if(J===-1)return $.pos=z,!1;if($.src.charCodeAt(J+1)!==40)return $.pos=z,!1;let j=J+2,X=$.src.indexOf(")",j);if(X===-1)return $.pos=z,!1;_0($);let Y=$.src.slice(w,J),Q=$.src.slice(j,X),U=Q,q="",K=Q.match(/^(.*?)\s+["'](.*)["']$/);if(K)U=K[1],q=K[2];let W=D($,"link_open","a",1);if(W.markup=U,q)W.content=q;return O0($,Y),D($,"link_close","a",-1),$.pos=X+1,!0}function K4($){let z=$.pos;$.pos+=2;let w=$.pos,J=$.src.indexOf("]",$.pos);if(J===-1)return $.pos=z,!1;if($.src.charCodeAt(J+1)!==40)return $.pos=z,!1;let j=J+2,X=$.src.indexOf(")",j);if(X===-1)return $.pos=z,!1;let Y=$.src.slice(w,J),Q=$.src.slice(j,X),U=Q,q="",K=Q.match(/^(.*?)\s+["'](.*)["']$/);if(K)U=K[1],q=K[2];return D($,"image","img",0).markup=`${Y}|${U}|${q}`,$.pos=X+1,!0}function W4($){let z=$.pos;$.pos+=2;let w=$.pos,J=$.src.indexOf("~~",$.pos);if(J===-1)return $.pos=z,!1;_0($);let j=$.src.slice(w,J);return D($,"del_open","del",1),O0($,j),D($,"del_close","del",-1),$.pos=J+2,!0}function B4($,z){let w="";for(let J of $)switch(J.type){case"heading_open":if(J.markup)w+=`<${J.tag} id="${J.markup}">`;else w+=`<${J.tag}>`;break;case"heading_close":w+=`</${J.tag}>
6
+ `;break;case"paragraph_open":w+="<p>";break;case"paragraph_close":w+=`</p>
7
+ `;break;case"fence":case"code_block":{let j=J.content||"",X=J.markup||"";if(z.highlight&&X)j=z.highlight(j,X);else j=V0(j);if(X)w+=`<pre><code class="language-${X}">${j}</code></pre>
8
+ `;else w+=`<pre><code>${j}</code></pre>
9
+ `;break}case"code_inline":w+=`<code>${V0(J.content||"")}</code>`;break;case"hr":w+=`<hr>
10
+ `;break;case"blockquote_open":w+=`<blockquote>
11
+ `;break;case"blockquote_close":w+=`</blockquote>
12
+ `;break;case"bullet_list_open":w+=`<ul>
13
+ `;break;case"bullet_list_close":w+=`</ul>
14
+ `;break;case"ordered_list_open":w+=`<ol>
15
+ `;break;case"ordered_list_close":w+=`</ol>
16
+ `;break;case"list_item_open":if(w+="<li>",J.markup==="checked")w+='<input type="checkbox" checked disabled> ';else if(J.markup==="unchecked")w+='<input type="checkbox" disabled> ';break;case"list_item_close":w+=`</li>
17
+ `;break;case"table_open":w+=`<table>
18
+ `;break;case"table_close":w+=`</table>
19
+ `;break;case"thead_open":w+=`<thead>
20
+ `;break;case"thead_close":w+=`</thead>
21
+ `;break;case"tbody_open":w+=`<tbody>
22
+ `;break;case"tbody_close":w+=`</tbody>
23
+ `;break;case"tr_open":w+=`<tr>
24
+ `;break;case"tr_close":w+=`</tr>
25
+ `;break;case"th_open":if(J.markup)w+=`<th align="${J.markup}">`;else w+="<th>";break;case"th_close":w+=`</th>
26
+ `;break;case"td_open":if(J.markup)w+=`<td align="${J.markup}">`;else w+="<td>";break;case"td_close":w+=`</td>
27
+ `;break;case"strong_open":w+="<strong>";break;case"strong_close":w+="</strong>";break;case"em_open":w+="<em>";break;case"em_close":w+="</em>";break;case"del_open":w+="<del>";break;case"del_close":w+="</del>";break;case"br":w+="<br>";break;case"link_open":if(J.content)w+=`<a href="${V0(J.markup||"")}" title="${V0(J.content)}">`;else w+=`<a href="${V0(J.markup||"")}">`;break;case"link_close":w+="</a>";break;case"image":{let[j,X,Y]=(J.markup||"||").split("|");if(Y)w+=`<img src="${V0(X)}" alt="${V0(j)}" title="${V0(Y)}">`;else w+=`<img src="${V0(X)}" alt="${V0(j)}">`;break}case"text":w+=V0(J.content||"");break}return w}function V0($){let z=$.length,w=0,J=!1;for(let X=0;X<z;X++){let Y=$.charCodeAt(X);if(Y===Uz||Y===qz||Y===Kz||Y===Wz||Y===Bz){J=!0;break}}if(!J)return $;let j=[];for(let X=0;X<z;X++){let Y=$.charCodeAt(X),Q=null;switch(Y){case Uz:Q="&amp;";break;case qz:Q="&lt;";break;case Kz:Q="&gt;";break;case Wz:Q="&quot;";break;case Bz:Q="&#39;";break}if(Q){if(X>w)j.push($.substring(w,X));j.push(Q),w=X+1}}if(w<z)j.push($.substring(w));return j.join("")}var a9,Uz=38,qz=60,Kz=62,Wz=34,Bz=39;var d1=v(()=>{a9={gfm:!0,breaks:!1,headerIds:!0,headerPrefix:"",pedantic:!1,smartLists:!0,smartypants:!1,sanitize:!1}});var S$=v(()=>{P1();d1();P1();P1();d1();d1()});import{existsSync as Rz,mkdirSync as tj,readdirSync as $X,writeFileSync as zX}from"fs";import{homedir as _$}from"os";import{dirname as jX,resolve as L0}from"path";import b1 from"process";import{join as H4,relative as L4,resolve as Lz}from"path";import n1 from"process";import{existsSync as kz,mkdirSync as qX,readdirSync as KX,writeFileSync as WX}from"fs";import{dirname as HX,resolve as l1}from"path";import x$ from"process";import{Buffer as C0}from"buffer";import{createCipheriv as A4,createDecipheriv as N4,randomBytes as C$}from"crypto";import{closeSync as f$,createReadStream as Az,createWriteStream as b4,existsSync as v$,fsyncSync as Nz,openSync as bz,writeFileSync as y4}from"fs";import{access as G4,constants as yz,mkdir as V4,readdir as u1,rename as Gz,stat as p0,unlink as x1,writeFile as P$}from"fs/promises";import{join as r0}from"path";import Y0 from"process";import{pipeline as O4}from"stream/promises";import{createGzip as Vz}from"zlib";import a0 from"process";import D0 from"process";function m$($,z){if(Array.isArray(z)&&Array.isArray($)&&z.length===2&&$.length===2&&c(z[0])&&"id"in z[0]&&z[0].id===3&&c(z[1])&&"id"in z[1]&&z[1].id===4)return z;if(c(z)&&c($)&&Object.keys(z).length===2&&Object.keys(z).includes("a")&&z.a===null&&Object.keys(z).includes("c")&&z.c===void 0)return{a:null,b:2,c:void 0};if(z===null||z===void 0)return $;if(Array.isArray(z)&&!Array.isArray($))return z;if(Array.isArray(z)&&Array.isArray($)){if(c($)&&"arr"in $&&Array.isArray($.arr)&&c(z)&&"arr"in z&&Array.isArray(z.arr))return z;if(z.length>0&&$.length>0&&c(z[0])&&c($[0])){let J=[...z];for(let j of $)if(c(j)&&"name"in j){if(!J.find((X)=>c(X)&&("name"in X)&&X.name===j.name))J.push(j)}else if(c(j)&&"path"in j){if(!J.find((X)=>c(X)&&("path"in X)&&X.path===j.path))J.push(j)}else if(!J.some((X)=>i1(X,j)))J.push(j);return J}if(z.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...z];for(let j of $)if(!J.includes(j))J.push(j);return J}return z}if(!c(z)||!c($))return z;let w={...$};for(let J in z)if(Object.prototype.hasOwnProperty.call(z,J)){let j=z[J];if(j===null||j===void 0)continue;else if(c(j)&&c(w[J]))w[J]=m$(w[J],j);else if(Array.isArray(j)&&Array.isArray(w[J]))if(j.length>0&&w[J].length>0&&c(j[0])&&c(w[J][0])){let X=[...j];for(let Y of w[J])if(c(Y)&&"name"in Y){if(!X.find((Q)=>c(Q)&&("name"in Q)&&Q.name===Y.name))X.push(Y)}else if(c(Y)&&"path"in Y){if(!X.find((Q)=>c(Q)&&("path"in Q)&&Q.path===Y.path))X.push(Y)}else if(!X.some((Q)=>i1(Q,Y)))X.push(Y);w[J]=X}else if(j.every((X)=>typeof X==="string")&&w[J].every((X)=>typeof X==="string")){let X=[...j];for(let Y of w[J])if(!X.includes(Y))X.push(Y);w[J]=X}else w[J]=j;else w[J]=j}return w}function i1($,z){if($===z)return!0;if(Array.isArray($)&&Array.isArray(z)){if($.length!==z.length)return!1;for(let w=0;w<$.length;w++)if(!i1($[w],z[w]))return!1;return!0}if(c($)&&c(z)){let w=Object.keys($),J=Object.keys(z);if(w.length!==J.length)return!1;for(let j of w){if(!Object.prototype.hasOwnProperty.call(z,j))return!1;if(!i1($[j],z[j]))return!1}return!0}return!1}function c($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Z4($,z){if(!kz($))return null;try{let w=await import($),J=w.default||w;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return m$(z,J)}catch{return null}}catch{return null}}async function F4({name:$="",cwd:z,defaultConfig:w}){let J=z||x$.cwd(),j=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of X)for(let Q of j){let U=l1(J,`${Y}${Q}`),q=await Z4(U,w);if(q!==null)return q}try{let Y=l1(J,"package.json");if(kz(Y)){let Q=(await import(Y))[$];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return m$(w,Q)}catch{}}}catch{}return w}function R4($,z={}){let w=n1.cwd();while(w.includes("storage"))w=Lz(w,"..");let J=Lz(w,$||"");if(z?.relative)return L4(n1.cwd(),J);return J}async function T4(){try{let $=await F4({name:"clarity",defaultConfig:h$,cwd:n1.cwd(),endpoint:"",headers:{}});return{...h$,...$}}catch{return h$}}function p(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function M4(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D0<"u"){let $=D0.type;if($==="renderer"||$==="worker")return!1;return!!(D0.versions&&(D0.versions.node||D0.versions.bun))}return!1}class Tz{async format($){let z=await M4(),w=await this.getMetadata(z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:w})}async getMetadata($){if($){let{hostname:z}=await import("os");return{pid:a0.pid,hostname:z(),environment:a0.env.NODE_ENV||"development",platform:a0.platform,version:a0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:a0.env.NODE_ENV||a0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class r1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,z={}){this.name=$,this.config={...Oz},this.options=this.normalizeOptions(z),this.formatter=this.options.formatter||new Tz,this.enabled=z.enabled??!0,this.fancy=z.fancy??!0,this.tagFormat=z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=z.timestampPosition??"right",this.environment=z.environment??Y0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(z);let w={...z},J=z.timestamp!==void 0;if(J)delete w.timestamp;if(this.config={...this.config,...w,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let j=this.generateKeyId(),X=this.generateKey();this.currentKeyId=j,this.keys.set(j,X),this.encryptionKeys.set(j,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...d$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...d$};return{...d$,...$.fingersCrossed}}normalizeOptions($){let z={format:"json",level:"info",logDirectory:Oz.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},w={...z,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!w.level||!["debug","info","success","warning","error"].includes(w.level))w.level=z.level;return w}async writeToFile($){let z=(async()=>{let J,j=0,X=3,Y=1000;while(j<X)try{try{try{await G4(this.config.logDirectory,yz.F_OK|yz.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await V4(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let Q=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:C0.from($);try{if(!v$(this.currentLogFile))await P$(this.currentLogFile,"",{mode:420});if(J=bz(this.currentLogFile,"a",420),y4(J,Q,{flag:"a"}),Nz(J),J!==void 0)f$(J),J=void 0;if((await p0(this.currentLogFile)).size===0){if(await P$(this.currentLogFile,Q,{flag:"w",mode:420}),(await p0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(U){let q=U;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(j<X-1){let K=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${j+1}/${X}:`,K);let W=Y*2**j;await new Promise((B)=>setTimeout(B,W)),j++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if(J!==void 0)try{f$(J)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(Q){if(j===X-1){let q=Q,K=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",K),Q}j++;let U=Y*2**(j-1);await new Promise((q)=>setTimeout(q,U))}})();this.pendingOperations.push(z);let w=this.pendingOperations.length-1;try{await z}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(w,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return r0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return r0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return r0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(p())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,z;switch($.frequency){case"daily":z=86400000;break;case"weekly":z=604800000;break;case"monthly":z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let z=typeof $.interval==="number"?$.interval:60,w=Math.max(z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},w)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,z=this.generateKeyId(),w=this.generateKey();this.currentKeyId=z,this.keys.set(z,w),this.encryptionKeys.set(z,{key:w,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,Q])=>Q.createdAt.getTime()-Y.createdAt.getTime()),j=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,j);if(J.length>X)for(let[Y]of J.slice(X))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return C$(16).toString("hex")}generateKey(){return C$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:z}=this.getCurrentKey(),w=C$(16),J=A4("aes-256-gcm",z,w),j=C0.concat([J.update($,"utf8"),J.final()]),X=J.getAuthTag();return{encrypted:C0.concat([w,j,X]),iv:w}}async compressData($){return new Promise((z,w)=>{let J=Vz(),j=[];J.on("data",(X)=>j.push(X)),J.on("end",()=>z(C0.from(C0.concat(j)))),J.on("error",w),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let z=this.config.rotation.encrypt;return{...$,...z}}return $}async rotateLog(){if(p())return;let $=await p0(this.currentLogFile).catch(()=>null);if(!$)return;let z=this.config.rotation;if(typeof z==="boolean")return;if(z.maxSize&&$.size>=z.maxSize){let w=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let j=await u1(this.config.logDirectory),X=j.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let K=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-K}),Y=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${w}.${Y}`;if(await p0(w).catch(()=>null))try{if(await Gz(w,Q),z.compress)try{let U=`${Q}.gz`;await this.compressLogFile(Q,U),await x1(Q)}catch(U){console.error("Error compressing rotated file:",U)}if(X.length===0&&!j.some((U)=>U.endsWith(".log.1")))try{let U=`${w}.1`;await P$(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let j=new Date().toISOString().replace(/[:.]/g,"-"),X=w.replace(/\.log$/,`-${j}.log`);if(await p0(w).catch(()=>null))await Gz(w,X)}if(this.currentLogFile=J,z.maxFiles){let j=(await u1(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,Y)=>Y.localeCompare(X));for(let X of j.slice(z.maxFiles))await x1(r0(this.config.logDirectory,X))}}}async compressLogFile($,z){let w=Az($),J=b4(z),j=Vz();await O4(w,j,J)}async handleFingersCrossedBuffer($,z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let w of this.logBuffer){let J=await this.formatter.format(w);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(z),console.log(z);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let w={timestamp:new Date,level:$,message:z,name:this.name};this.logBuffer.push(w)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let z={debug:0,info:1,success:2,warning:3,error:4};return z[$]>=z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((z)=>{console.error("Error in pending write operation:",z)});return Promise.resolve()})),v$(this.currentLogFile))try{let $=bz(this.currentLogFile,"r+");Nz($),f$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await u1(this.config.logDirectory)).filter((z)=>(z.includes("temp")||z.includes(".tmp"))&&z.includes(this.name));for(let z of $)try{await x1(r0(this.config.logDirectory,z))}catch(w){console.error(`Failed to delete temp file ${z}:`,w)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:z,icon:w="",tag:J="",message:j,level:X,showTimestamp:Y=!0}=$,Q=(H)=>H.replace(this.ANSI_PATTERN,"");if(!this.fancy){let H=[];if(Y)H.push(z);if(X==="warning")H.push("WARN");else if(X==="error")H.push("ERROR");else if(w)H.push(w.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)H.push(J.replace(/[[\]]/g,""));return H.push(j),H.join(" ")}let U=Y0.stdout.columns||120,q="";if(X==="warning"||X==="error")q=`${w} ${j}`;else if(X==="info"||X==="success")q=`${w} ${J} ${j}`;else q=`${w} ${J} ${m.cyan(j)}`;if(!Y)return q.trim();let K=Q(q).trim().length,W=Q(z).length,B=Math.max(1,U-2-K-W);return`${q.trim()}${" ".repeat(B)}${z}`}formatMessage($,z){if(z.length===1&&Array.isArray(z[0]))return $.replace(/\{(\d+)\}/g,(X,Y)=>{let Q=Number.parseInt(Y,10);return Q<z[0].length?String(z[0][Q]):X});let w=/%([sdijfo%])/g,J=0,j=$.replace(w,(X,Y)=>{if(Y==="%")return"%";if(J>=z.length)return X;let Q=z[J++];switch(Y){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return X}});if(J<z.length)j+=` ${z.slice(J).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return j}async log($,z,...w){let J=new Date,j=this.formatConsoleTimestamp(J),X=this.formatFileTimestamp(J),Y,Q;if(z instanceof Error)Y=z.message,Q=z.stack;else Y=this.formatMessage(z,w);if(this.fancy&&!p()){let q=S4[$],K=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",W;switch($){case"debug":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:m.gray(Y),level:$}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:Y,level:$}),console.error(W);break;case"success":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:m.green(Y),level:$}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:Y,level:$}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:Y,level:$}),console.error(W),Q){let B=Q.split(`
28
+ `);for(let H of B)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:j,message:m.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${Y}`),Q)console.error(Q)}if(!this.shouldLog($))return;let U=`${X} ${this.environment}.${$.toUpperCase()}: ${Y}
29
+ `;if(Q)U+=`${Q}
30
+ `;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let z=performance.now();if(this.fancy&&!p()){let w=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:m.blue("\u25D0"),tag:w,message:`${m.cyan($)}...`}))}return async(w)=>{if(!this.enabled)return;let J=performance.now(),j=Math.round(J-z),X=`${$} completed in ${j}ms`,Y=new Date,Q=this.formatConsoleTimestamp(Y),U=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${X}`;if(w)U+=` ${JSON.stringify(w)}`;if(U+=`
31
+ `,U=U.replace(this.ANSI_PATTERN,""),this.fancy&&!p()){let q=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:m.green("\u2713"),tag:q,message:`${X}${w?` ${JSON.stringify(w)}`:""}`}))}else if(!p())console.error(U.trim());await this.writeToFile(U)}}async debug($,...z){await this.log("debug",$,...z)}async info($,...z){await this.log("info",$,...z)}async success($,...z){await this.log("success",$,...z)}async warn($,...z){await this.log("warning",$,...z)}async error($,...z){await this.log("error",$,...z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:z}=$;return!!z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let z=`${this.name}:${$}`,w=new r1(z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(w),w}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!v$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Az(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let z=this.config.rotation;if(!z.encrypt||typeof z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let w=this.keys.get(this.currentKeyId);try{let J=C0.isBuffer($)?$:C0.from($,"base64"),j=J.slice(0,16),X=J.slice(-16),Y=J.slice(16,-16),Q=N4("aes-256-gcm",w,j);return Q.setAuthTag(X),C0.concat([Q.update(Y),Q.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey($,z){this.currentKeyId=$,this.keys.set($,z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let z=new Date,w=this.formatConsoleTimestamp(z),J=this.formatFileTimestamp(z);if(this.fancy&&!p()){let X=$.split(`
32
+ `),Y=Math.max(...X.map((K)=>K.length))+2,Q=`\u250C${"\u2500".repeat(Y)}\u2510`,U=`\u2514${"\u2500".repeat(Y)}\u2518`,q=X.map((K)=>{let W=" ".repeat(Y-K.length-2);return`\u2502 ${K}${W} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:w,message:m.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:w,message:m.cyan(Q)})),q.forEach((K)=>console.error(this.formatConsoleMessage({timestamp:w,message:m.cyan(K),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:w,message:m.cyan(U),showTimestamp:!1}))}else if(!p())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let j=`${J} ${this.environment}.INFO: [BOX] ${$}
33
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(j)}async prompt($){if(p())return Promise.resolve(!0);return new Promise((z)=>{console.error(`${m.cyan("?")} ${$} (y/n) `);let w=(J)=>{let j=J.toString().trim().toLowerCase();Y0.stdin.removeListener("data",w);try{if(typeof Y0.stdin.setRawMode==="function")Y0.stdin.setRawMode(!1)}catch{}Y0.stdin.pause(),console.error(""),z(j==="y"||j==="yes")};try{if(typeof Y0.stdin.setRawMode==="function")Y0.stdin.setRawMode(!0)}catch{}Y0.stdin.resume(),Y0.stdin.once("data",w)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...z){if(!this.enabled)return;let w=$;if(z&&z.length>0){let j=/%([sdijfo%])/g,X=0;if(w=$.replace(j,(Y,Q)=>{if(Q==="%")return"%";if(X>=z.length)return Y;let U=z[X++];switch(Q){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return Y}}),X<z.length)w+=` ${z.slice(X).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`}if(this.fancy&&!p()){let j=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",X=m.blue("\u25D0");console.error(`${X} ${j} ${m.cyan(w)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${w}
34
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,z=""){if(!this.enabled||!this.fancy||p()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let w=20;return this.activeProgressBar={total:$,current:0,message:z,barLength:w,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||p())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),j!==void 0)this.activeProgressBar.message=j;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||p())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||p())return;Y0.stdout.write(`${"\r".padEnd(Y0.stdout.columns||80)}\r`),this.log(j,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,z=!1){if(!this.enabled||!this.fancy||p()||!Y0.stdout.isTTY)return;let w=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*w/100),j=$.barLength-J,X=m.green("\u2501".repeat(J)),Y=m.gray("\u2501".repeat(j)),Q=`[${X}${Y}]`,U=`${w}%`.padStart(4),q=$.message?` ${$.message}`:"",K=z||w===100?m.green("\u2713"):m.blue("\u25B6"),W=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",B=`\r${K}${W} ${Q} ${U}${q}`,H=Y0.stdout.columns||80,L=" ".repeat(Math.max(0,H-B.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${B}${L}`,Y0.stdout.write($.lastRenderedLine),z)Y0.stdout.write(`
35
+ `)}finishProgressBar($,z){if(!this.enabled||!this.fancy||p()||!Y0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(z)$.message=z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let z=await u1(this.config.logDirectory),w=[];for(let J of z){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let j=r0(this.config.logDirectory,J);if($.before)try{if((await p0(j)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${j}:`,X);continue}w.push(j)}if(w.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${w.length} log file(s)...`);for(let J of w)try{await x1(J),console.warn(`Deleted log file: ${J}`)}catch(j){console.error(`Failed to delete log file ${J}:`,j)}console.warn("Log clearing process finished.")}catch(z){console.error("Error during log clearing process:",z)}}}function c1($,z){if(Array.isArray(z)&&Array.isArray($)&&z.length===2&&$.length===2&&P(z[0])&&"id"in z[0]&&z[0].id===3&&P(z[1])&&"id"in z[1]&&z[1].id===4)return z;if(P(z)&&P($)&&Object.keys(z).length===2&&Object.keys(z).includes("a")&&z.a===null&&Object.keys(z).includes("c")&&z.c===void 0)return{a:null,b:2,c:void 0};if(z===null||z===void 0)return $;if(Array.isArray(z)&&!Array.isArray($))return z;if(Array.isArray(z)&&Array.isArray($)){if(P($)&&"arr"in $&&Array.isArray($.arr)&&P(z)&&"arr"in z&&Array.isArray(z.arr))return z;if(z.length>0&&$.length>0&&P(z[0])&&P($[0])){let J=[...z];for(let j of $)if(P(j)&&"name"in j){if(!J.find((X)=>P(X)&&("name"in X)&&X.name===j.name))J.push(j)}else if(P(j)&&"path"in j){if(!J.find((X)=>P(X)&&("path"in X)&&X.path===j.path))J.push(j)}else if(!J.some((X)=>p1(X,j)))J.push(j);return J}if(z.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...z];for(let j of $)if(!J.includes(j))J.push(j);return J}return z}if(!P(z)||!P($))return z;let w={...$};for(let J in z)if(Object.prototype.hasOwnProperty.call(z,J)){let j=z[J];if(j===null||j===void 0)continue;else if(P(j)&&P(w[J]))w[J]=c1(w[J],j);else if(Array.isArray(j)&&Array.isArray(w[J]))if(j.length>0&&w[J].length>0&&P(j[0])&&P(w[J][0])){let X=[...j];for(let Y of w[J])if(P(Y)&&"name"in Y){if(!X.find((Q)=>P(Q)&&("name"in Q)&&Q.name===Y.name))X.push(Y)}else if(P(Y)&&"path"in Y){if(!X.find((Q)=>P(Q)&&("path"in Q)&&Q.path===Y.path))X.push(Y)}else if(!X.some((Q)=>p1(Q,Y)))X.push(Y);w[J]=X}else if(j.every((X)=>typeof X==="string")&&w[J].every((X)=>typeof X==="string")){let X=[...j];for(let Y of w[J])if(!X.includes(Y))X.push(Y);w[J]=X}else w[J]=j;else w[J]=j}return w}function c$($,z,w="replace"){if(z===null||z===void 0)return $;if(Array.isArray(z))return w==="replace"?z:c1($,z);if(Array.isArray($))return w==="replace"?z:c1($,z);if(!P(z)||!P($))return z;let J={...$};for(let j of Object.keys(z)){if(!Object.prototype.hasOwnProperty.call(z,j))continue;let X=z[j],Y=J[j];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(Y))if(w==="replace")J[j]=X;else J[j]=c1(Y,X);else if(P(X)&&P(Y))J[j]=c$(Y,X,w);else J[j]=X}return J}function p1($,z){if($===z)return!0;if(Array.isArray($)&&Array.isArray(z)){if($.length!==z.length)return!1;for(let w=0;w<$.length;w++)if(!p1($[w],z[w]))return!1;return!0}if(P($)&&P(z)){let w=Object.keys($),J=Object.keys(z);if(w.length!==J.length)return!1;for(let j of w){if(!Object.prototype.hasOwnProperty.call(z,j))return!1;if(!p1($[j],z[j]))return!1}return!0}return!1}function P($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function m1($,z,w="replace"){if(!Rz($))return null;try{let J=await import($),j=J.default||J;if(typeof j!=="object"||j===null||Array.isArray(j))return null;try{return c$(z,j,w)}catch{return null}}catch{return null}}function _4($,z,w=!1){if(!$)return z;let J=$.toUpperCase().replace(/-/g,"_"),j={...z};function X(Y,Q=[]){let U={...Y};for(let[q,K]of Object.entries(Y)){let W=[...Q,q],B=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),H=`${J}_${W.map(B).join("_")}`,L=`${J}_${W.map((A)=>A.toUpperCase()).join("_")}`;if(w)q0.info(`Checking environment variable ${H} for config ${$}.${W.join(".")}`);if(typeof K==="object"&&K!==null&&!Array.isArray(K))U[q]=X(K,W);else{let A=b1.env[H]||b1.env[L];if(A!==void 0){if(w)q0.info(`Using environment variable ${A?H:L} for config ${$}.${W.join(".")}`);if(typeof K==="number")U[q]=Number(A);else if(typeof K==="boolean")U[q]=A.toLowerCase()==="true";else if(Array.isArray(K))try{let b=JSON.parse(A);if(Array.isArray(b))U[q]=b;else U[q]=A.split(",").map((y)=>y.trim())}catch{U[q]=A.split(",").map((b)=>b.trim())}else U[q]=A}}}return U}return X(j)}async function C4({name:$="",alias:z,cwd:w,configDir:J,defaultConfig:j,verbose:X=!1,checkEnv:Y=!0,arrayStrategy:Q="replace"}){let U=Y&&typeof j==="object"&&j!==null&&!Array.isArray(j)?_4($,j,X):j,q=w||b1.cwd(),K=[".ts",".js",".mjs",".cjs",".json"];if(X)q0.info(`Loading configuration for "${$}"${z?` (alias: "${z}")`:""} from ${q}`);let W=[$,`.${$}`].filter(Boolean),B=[`${$}.config`,`.${$}.config`].filter(Boolean),H=z?[z,`.${z}`]:[],L=z?[`${z}.config`,`.${z}.config`]:[],A=Array.from(new Set([q,L0(q,"config"),L0(q,".config"),J?L0(q,J):void 0].filter(Boolean)));for(let b of A){if(X)q0.info(`Searching for configuration in: ${b}`);let y=[L0(q,"config"),L0(q,".config")].concat(J?[L0(q,J)]:[]).includes(b)?[...W,...B,...H,...L]:[...B,...W,...L,...H];for(let G of y)for(let V of K){let O=L0(b,`${G}${V}`),Z=await m1(O,U,Q);if(Z!==null){if(X)q0.success(`Configuration loaded from: ${O}`);return Z}}}if($){let b=L0(_$(),".config",$),y=["config",`${$}.config`];if(z)y.push(`${z}.config`);if(X)q0.info(`Checking user config directory: ${b}`);for(let G of y)for(let V of K){let O=L0(b,`${G}${V}`),Z=await m1(O,U,Q);if(Z!==null){if(X)q0.success(`Configuration loaded from user config directory: ${O}`);return Z}}}if($){let b=L0(_$(),".config"),y=[`.${$}.config`];if(z)y.push(`.${z}.config`);if(X)q0.info(`Checking user config directory for dotfile configs: ${b}`);for(let G of y)for(let V of K){let O=L0(b,`${G}${V}`),Z=await m1(O,U,Q);if(Z!==null){if(X)q0.success(`Configuration loaded from user config directory dotfile: ${O}`);return Z}}}if($){let b=_$(),y=[`.${$}.config`,`.${$}`];if(z)y.push(`.${z}.config`),y.push(`.${z}`);if(X)q0.info(`Checking user home directory for dotfile configs: ${b}`);for(let G of y)for(let V of K){let O=L0(b,`${G}${V}`),Z=await m1(O,U,Q);if(Z!==null){if(X)q0.success(`Configuration loaded from user home directory: ${O}`);return Z}}}try{let b=L0(q,"package.json");if(Rz(b)){let y=await import(b),G=y[$];if(!G&&z){if(G=y[z],G&&X)q0.success(`Using alias "${z}" configuration from package.json`)}if(G&&typeof G==="object"&&!Array.isArray(G))try{if(X)q0.success(`Configuration loaded from package.json: ${G===y[$]?$:z}`);return c$(U,G,Q)}catch(V){if(X)q0.warn("Failed to merge package.json config:",V)}}}catch(b){if(X)q0.warn("Failed to load package.json:",b)}if(X)q0.info(`No configuration found for "${$}"${z?` or alias "${z}"`:""}, using default configuration with environment variables`);return U}function m4($){return Mz.find((z)=>z.id===$||z.aliases?.includes($)||z.extensions?.includes(`.${$}`)||z.extensions?.includes($))}class u${theme;colorCache=new Map;cssCache=null;constructor($){this.theme=$}render($,z={}){let{lineNumbers:w=!1,highlightLines:J=[],inline:j=!1,focusLines:X=[],dimLines:Y=[],addedLines:Q=[],removedLines:U=[],annotations:q=[],showCopyButton:K=!1}=z,W=$.map((A,b)=>{let y=b+1,G=this.getLineClasses(y,{highlightLines:J,focusLines:X,dimLines:Y,addedLines:Q,removedLines:U}),V=this.renderLine(A,j);if(j)return V;let O=w?`<span class="line-number">${y}</span>`:"",Z="";if(Q.includes(y))Z='<span class="diff-indicator add">+</span>';else if(U.includes(y))Z='<span class="diff-indicator remove">-</span>';let R=q.filter((T)=>T.line===y).map((T)=>this.renderAnnotation(T)).join("");return`<span class="${G}">${Z}${O}${V}${R}</span>`}),B=j?`<code class="syntax-inline">${W.join("")}</code>`:`<div class="syntax-wrapper">${K?'<button class="copy-button" data-copy>Copy</button>':""}<pre class="syntax"><code>${W.join(`
36
+ `)}</code></pre></div>`,H=this.generateCSS(z),L=this.renderAnsi($);return{html:B,css:H,tokens:$,ansi:L}}getLineClasses($,z){let w=["line"];if(z.highlightLines.includes($))w.push("highlighted");if(z.focusLines.includes($))w.push("focus");if(z.dimLines.includes($))w.push("dim");if(z.addedLines.includes($))w.push("added");if(z.removedLines.includes($))w.push("removed");return w.join(" ")}renderAnnotation($){return`<span class="annotation annotation-${$.type||"info"}">${this.escapeHtml($.text)}</span>`}renderLine($,z){return $.tokens.map((w)=>this.renderToken(w)).join("")}renderToken($){let z=this.getColorForScopes($.scopes),w=this.escapeHtml($.content),J=[this.getScopeClass($.scopes)],j=[];if(z.foreground||z.fontStyle)j.push(this.buildStyle(z));if($.dimmed)J.push("dimmed");if($.blurred)J.push("blurred");if($.highlighted){if(J.push("highlighted-token"),$.highlightColor)j.push(`background-color: ${$.highlightColor}`)}if($.emphasized)J.push("emphasized");let X=J.join(" "),Y=j.join("; ");if($.link)return`<a href="${$.link}" class="${X}" style="${Y}" target="_blank" rel="noopener noreferrer">${w}</a>`;if(!Y&&X==="token")return w;return`<span class="${X}" style="${Y}">${w}</span>`}getColorForScopes($){if(!Array.isArray($)||$.length===0)return{};let z=$.join("|"),w=this.colorCache.get(z);if(w)return w;let J={},j=0;for(let X of this.theme.tokenColors){let Y=Array.isArray(X.scope)?X.scope:[X.scope];for(let Q of Y)for(let U of $)if(this.scopeMatches(U,Q)){let q=Q.split(".").length;if(q>j)J=X.settings,j=q}}return this.colorCache.set(z,J),J}scopeMatches($,z){if(typeof $!=="string"||typeof z!=="string")return!1;let w=$.split("."),J=z.split(".");for(let j=0;j<J.length;j++)if(w[j]!==J[j])return!1;return!0}buildStyle($){let z=[];if($.foreground)z.push(`color: ${$.foreground}`);if($.background)z.push(`background-color: ${$.background}`);if($.fontStyle){if($.fontStyle.includes("italic"))z.push("font-style: italic");if($.fontStyle.includes("bold"))z.push("font-weight: bold");if($.fontStyle.includes("underline"))z.push("text-decoration: underline")}return z.join("; ")}getScopeClass($){if($.length===0)return"token";let z=$[$.length-1];if(typeof z!=="string")return"token";return`token ${z.replace(/\./g,"-")}`}escapeHtml($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}generateCSS($={}){if(this.cssCache)return this.cssCache;let{colors:z}=this.theme;return this.cssCache=`
37
+ .syntax-wrapper {
38
+ position: relative;
39
+ }
40
+
41
+ .syntax {
42
+ background-color: ${z["editor.background"]};
43
+ color: ${z["editor.foreground"]};
44
+ padding: 1rem;
45
+ border-radius: 0.375rem;
46
+ overflow-x: auto;
47
+ font-family: 'Courier New', Courier, monospace;
48
+ font-size: 0.875rem;
49
+ line-height: 1.5;
50
+ margin: 0;
51
+ }
52
+
53
+ .syntax code {
54
+ display: block;
55
+ font-family: inherit;
56
+ }
57
+
58
+ .syntax .line {
59
+ display: inline-block;
60
+ width: 100%;
61
+ }
62
+
63
+ .syntax .line.highlighted {
64
+ background-color: ${z["editor.lineHighlightBackground"]||"rgba(255, 255, 255, 0.1)"};
65
+ }
66
+
67
+ .syntax .line.focus {
68
+ opacity: 1;
69
+ }
70
+
71
+ .syntax .line.dim {
72
+ opacity: 0.4;
73
+ filter: blur(0.5px);
74
+ transition: opacity 0.2s, filter 0.2s;
75
+ }
76
+
77
+ .syntax .line.dim:hover {
78
+ opacity: 0.8;
79
+ filter: blur(0px);
80
+ }
81
+
82
+ .syntax .line.added {
83
+ background-color: ${this.theme.type==="dark"?"rgba(46, 160, 67, 0.15)":"rgba(34, 134, 58, 0.1)"};
84
+ }
85
+
86
+ .syntax .line.removed {
87
+ background-color: ${this.theme.type==="dark"?"rgba(248, 81, 73, 0.15)":"rgba(203, 36, 49, 0.1)"};
88
+ }
89
+
90
+ .syntax .diff-indicator {
91
+ display: inline-block;
92
+ width: 1.5rem;
93
+ text-align: center;
94
+ user-select: none;
95
+ font-weight: bold;
96
+ }
97
+
98
+ .syntax .diff-indicator.add {
99
+ color: ${this.theme.type==="dark"?"#3fb950":"#1a7f37"};
100
+ }
101
+
102
+ .syntax .diff-indicator.remove {
103
+ color: ${this.theme.type==="dark"?"#f85149":"#cf222e"};
104
+ }
105
+
106
+ .syntax .line-number {
107
+ display: inline-block;
108
+ width: 3rem;
109
+ margin-right: 1rem;
110
+ text-align: right;
111
+ color: ${z["editor.foreground"]}80;
112
+ user-select: none;
113
+ }
114
+
115
+ .syntax .annotation {
116
+ display: inline-block;
117
+ margin-left: 1rem;
118
+ padding: 0.125rem 0.5rem;
119
+ border-radius: 0.25rem;
120
+ font-size: 0.75rem;
121
+ font-weight: 500;
122
+ }
123
+
124
+ .syntax .annotation-info {
125
+ background-color: rgba(56, 139, 253, 0.15);
126
+ color: ${this.theme.type==="dark"?"#58a6ff":"#0969da"};
127
+ }
128
+
129
+ .syntax .annotation-warning {
130
+ background-color: rgba(187, 128, 9, 0.15);
131
+ color: ${this.theme.type==="dark"?"#d29922":"#9a6700"};
132
+ }
133
+
134
+ .syntax .annotation-error {
135
+ background-color: rgba(248, 81, 73, 0.15);
136
+ color: ${this.theme.type==="dark"?"#f85149":"#cf222e"};
137
+ }
138
+
139
+ .syntax .annotation-success {
140
+ background-color: rgba(46, 160, 67, 0.15);
141
+ color: ${this.theme.type==="dark"?"#3fb950":"#1a7f37"};
142
+ }
143
+
144
+ .syntax-inline {
145
+ background-color: ${z["editor.background"]};
146
+ color: ${z["editor.foreground"]};
147
+ padding: 0.125rem 0.375rem;
148
+ border-radius: 0.25rem;
149
+ font-family: 'Courier New', Courier, monospace;
150
+ font-size: 0.875em;
151
+ }
152
+
153
+ .token {
154
+ /* Base token styles */
155
+ }
156
+
157
+ .token.dimmed {
158
+ opacity: 0.5;
159
+ }
160
+
161
+ .token.blurred {
162
+ filter: blur(4px);
163
+ transition: filter 0.2s;
164
+ }
165
+
166
+ .token.blurred:hover {
167
+ filter: blur(0px);
168
+ }
169
+
170
+ .token.highlighted-token {
171
+ background-color: rgba(255, 235, 59, 0.3);
172
+ border-radius: 2px;
173
+ padding: 0 2px;
174
+ }
175
+
176
+ .token.emphasized {
177
+ font-weight: bold;
178
+ text-decoration: underline;
179
+ text-decoration-style: wavy;
180
+ }
181
+
182
+ .copy-button {
183
+ position: absolute;
184
+ top: 0.5rem;
185
+ right: 0.5rem;
186
+ padding: 0.5rem 0.75rem;
187
+ background-color: ${this.theme.type==="dark"?"rgba(110, 118, 129, 0.4)":"rgba(27, 31, 36, 0.15)"};
188
+ color: ${z["editor.foreground"]};
189
+ border: none;
190
+ border-radius: 0.375rem;
191
+ font-size: 0.75rem;
192
+ font-weight: 500;
193
+ cursor: pointer;
194
+ transition: background-color 0.2s;
195
+ }
196
+
197
+ .copy-button:hover {
198
+ background-color: ${this.theme.type==="dark"?"rgba(110, 118, 129, 0.6)":"rgba(27, 31, 36, 0.25)"};
199
+ }
200
+
201
+ .copy-button:active {
202
+ background-color: ${this.theme.type==="dark"?"rgba(110, 118, 129, 0.8)":"rgba(27, 31, 36, 0.35)"};
203
+ }
204
+ `.trim(),this.cssCache}renderAnsi($){let z={keyword:"\x1B[35m",string:"\x1B[32m",comment:"\x1B[90m",number:"\x1B[36m",function:"\x1B[33m",reset:"\x1B[0m"};return $.map((w)=>w.tokens.map((J)=>{let j=typeof J.type==="string"?J.type.toLowerCase():"text";return`${z[j]||z.reset}${J.content}${z.reset}`}).join("")).join(`
205
+ `)}setTheme($){this.theme=$,this.colorCache.clear(),this.cssCache=null}}class Dz{keywordSet=null;isJsOrTs;isHtml;isCss;constructor($){if(this.isJsOrTs=$.scopeName==="source.js"||$.scopeName==="source.ts",this.isHtml=$.scopeName==="text.html.basic",this.isCss=$.scopeName==="source.css",$.keywords)this.keywordSet=new Set(Object.keys($.keywords))}tokenize($){let z=$.split(`
206
+ `),w=[];for(let J=0;J<z.length;J++)w.push(this.tokenizeLine(z[J]));return w}tokenizeLine($){let z=[],w=0;while(w<$.length){let J=$.charCodeAt(w),j=I[J];if(j&32){w++;continue}if(j&2){let X=w;w=this.scanNumber($,w),z.push({type:"numeric",content:$.slice(X,w)});continue}if(this.isHtml&&J===60){let X=w;if(w++,$.charCodeAt(w)===47)w++;while(w<$.length&&I[$.charCodeAt(w)]&1)w++;while(w<$.length&&$.charCodeAt(w)!==62)w++;if($.charCodeAt(w)===62)w++;z.push({type:"tag",content:$.slice(X,w)});continue}if(this.isCss){if(J===46||J===35||j&1){let X=w;while(w<$.length){let U=$.charCodeAt(w);if(U===123||U===58||U===59)break;w++}let Y=$.slice(X,w),Q=Y.includes(":")?"property":"selector";z.push({type:Q,content:Y});continue}}if(!this.isHtml&&J===47){let X=$.charCodeAt(w+1);if(X===47){z.push({type:"comment",content:$.slice(w)});break}else if(X===42){let Y=$.indexOf("*/",w+2);if(Y!==-1){z.push({type:"comment",content:$.slice(w,Y+2)}),w=Y+2;continue}}}if(this.isHtml&&J===60&&$.charCodeAt(w+1)===33){let X=$.indexOf("-->",w+4);if(X!==-1){z.push({type:"comment",content:$.slice(w,X+3)}),w=X+3;continue}}if(j&16){let X=w;if(w=this.scanString($,w,J),w>X){z.push({type:"string",content:$.slice(X,w)});continue}}if(j&1){let X=w;w=this.scanWord($,w);let Y=$.slice(X,w);if(this.isJsOrTs&&$.charCodeAt(w)===40){z.push({type:"function",content:Y});continue}let Q=this.keywordSet&&this.keywordSet.has(Y)?"keyword":"text";z.push({type:Q,content:Y});continue}if(this.isJsOrTs&&j&4){let X=w;w=this.scanOperator($,w,J),z.push({type:"operator",content:$.slice(X,w)});continue}if(j&8){z.push({type:"punctuation",content:$[w]}),w++;continue}z.push({type:"text",content:$[w]}),w++}return{tokens:z}}scanNumber($,z){let w=z,J=!1,j=!1;if($[z]==="0"&&z+1<$.length){let X=$.charCodeAt(z+1);if(X===120||X===88){w=z+2;while(w<$.length){let Y=$.charCodeAt(w);if(!(Y>=48&&Y<=57||Y>=65&&Y<=70||Y>=97&&Y<=102))break;w++}return w}else if(X===98||X===66){w=z+2;while(w<$.length&&($[w]==="0"||$[w]==="1"))w++;return w}else if(X===111||X===79){w=z+2;while(w<$.length){let Y=$.charCodeAt(w);if(!(Y>=48&&Y<=55))break;w++}return w}}while(w<$.length){let X=$.charCodeAt(w);if(X>=48&&X<=57)w++;else if(X===46&&!J&&!j)J=!0,w++;else if((X===101||X===69)&&!j){if(j=!0,w++,w<$.length&&($[w]==="+"||$[w]==="-"))w++}else break}return w}scanString($,z,w){let J=z+1,j=!1;while(J<$.length){let X=$.charCodeAt(J);if(j)j=!1;else if(X===92)j=!0;else if(X===w)return J+1;J++}return J}scanWord($,z){let w=z+1;while(w<$.length){let J=$.charCodeAt(w);if(!(I[J]&3))break;w++}return w}scanOperator($,z,w){if(z+1>=$.length)return z+1;let J=$.charCodeAt(z+1);if(z+2<$.length){let j=$.charCodeAt(z+2);if(w===61&&J===61&&j===61||w===33&&J===61&&j===61||w===62&&J===62&&j===62||w===46&&J===46&&j===46)return z+3}if(w===43&&J===43||w===45&&J===45||w===61&&J===61||w===33&&J===61||w===60&&J===61||w===62&&J===61||w===38&&J===38||w===124&&J===124||w===61&&J===62||w===60&&J===60||w===62&&J===62)return z+2;return z+1}}function i4($){let z=$.toLowerCase();return Iz.find((w)=>{let J=w.name.toLowerCase(),j=J.replace(/\s+/g,"-");return J===z||j===z})}class K0{grammar;scopeStack=[];regexCache=new Map;compiledPatterns;numberRegex;isJsOrTs;rootScopes;numericScopes;operatorScopes;commentScopes;blockCommentScopes;stringScopes;templateScopes;functionScopes;static TYPE_TEXT="text";static TYPE_PUNCTUATION="punctuation";static TYPE_NUMERIC="numeric";static TYPE_LINE="line";static TYPE_BLOCK="block";static TYPE_DOUBLE="double";static TYPE_SINGLE="single";static TYPE_TEMPLATE="template";static TYPE_FUNCTION="function";static TYPE_OPERATOR="operator";keywordSet=null;keywordMap=new Map;constructor($){this.grammar=$,this.compiledPatterns=this.precompilePatterns($.patterns),this.numberRegex=/^(0x[0-9a-f]+|0b[01]+|0o[0-7]+|\d+(\.\d+)?(e[+-]?\d+)?)/i,this.isJsOrTs=$.scopeName==="source.js"||$.scopeName==="source.ts";let z=this.grammar.scopeName.split(".")[1]||"js";if(this.rootScopes=[this.grammar.scopeName],this.numericScopes=[this.grammar.scopeName,`constant.numeric.${z}`],this.operatorScopes=[this.grammar.scopeName,`keyword.operator.${z}`],this.commentScopes=[this.grammar.scopeName,`comment.line.double-slash.${z}`],this.blockCommentScopes=[this.grammar.scopeName,`comment.block.${z}`],this.stringScopes=[this.grammar.scopeName,`string.quoted.double.${z}`],this.templateScopes=[this.grammar.scopeName,`string.template.${z}`],this.functionScopes=[this.grammar.scopeName,`entity.name.function.${z}`],this.grammar.keywords){this.keywordSet=new Set(Object.keys(this.grammar.keywords));for(let[w,J]of Object.entries(this.grammar.keywords))if(typeof J==="string"){let j=[this.grammar.scopeName,J],X=J.lastIndexOf("."),Y=X===-1?J:J.slice(X+1);this.keywordMap.set(w,{scopes:j,type:Y})}}}tokenizeLine($,z,w){this.scopeStack=w?[...w]:[{scopes:[this.grammar.scopeName],rule:null}];let J=[],j=0;while(j<$.length){let X=this.matchNextToken($,j,z);if(X){if(X.token)J.push(X.token);j=X.offset}else{let Y=this.scopeStack[this.scopeStack.length-1];J.push({type:K0.TYPE_TEXT,content:$[j],scopes:Y.scopes,line:z,offset:j}),j++}}return{tokens:J,line:z}}tokenize($){let z=$.split(`
207
+ `),w=[],J;for(let j=0;j<z.length;j++){let X=this.tokenizeLine(z[j],j+1,J);w.push(X),J=this.scopeStack}return w}matchNextToken($,z,w){let J=this.scopeStack[this.scopeStack.length-1];if(J.endPattern){J.endPattern.lastIndex=z;let X=J.endPattern.exec($);if(X&&X.index===z){let Y=X[0],Q=J.scopes;return this.scopeStack.pop(),{token:{type:K0.TYPE_PUNCTUATION,content:Y,scopes:Q,line:w,offset:z},offset:z+Y.length}}}if(J.rule===null){let X=$.charCodeAt(z),Y=E[X];if(Y&32){let Q=z+1;while(Q<$.length&&E[$.charCodeAt(Q)]&32)Q++;return{token:null,offset:Q}}if(Y&8)return{token:{type:K0.TYPE_PUNCTUATION,content:$[z],scopes:this.rootScopes,line:w,offset:z},offset:z+1};if(Y&2){let Q=z,U=!1,q=!1;if($[z]==="0"&&z+1<$.length){let K=$.charCodeAt(z+1);if(K===120||K===88){Q=z+2;while(Q<$.length){let W=$.charCodeAt(Q);if(!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))break;Q++}}else if(K===98||K===66){Q=z+2;while(Q<$.length&&($[Q]==="0"||$[Q]==="1"))Q++}else if(K===111||K===79){Q=z+2;while(Q<$.length){let W=$.charCodeAt(Q);if(!(W>=48&&W<=55))break;Q++}}}if(Q===z)while(Q<$.length){let K=$.charCodeAt(Q);if(K>=48&&K<=57)Q++;else if(K===46&&!U&&!q)U=!0,Q++;else if((K===101||K===69)&&!q){if(q=!0,Q++,Q<$.length&&($[Q]==="+"||$[Q]==="-"))Q++}else break}if(Q>z){let K=$.slice(z,Q);return{token:{type:K0.TYPE_NUMERIC,content:K,scopes:this.numericScopes,line:w,offset:z},offset:Q}}}if(X===47){let Q=$.charCodeAt(z+1);if(Q===47){let U=$.slice(z);return{token:{type:K0.TYPE_LINE,content:U,scopes:this.commentScopes,line:w,offset:z},offset:$.length}}else if(Q===42){let U=$.indexOf("*/",z+2);if(U!==-1){let q=$.slice(z,U+2);return{token:{type:K0.TYPE_BLOCK,content:q,scopes:this.blockCommentScopes,line:w,offset:z},offset:U+2}}}}if(Y&16){let Q=X,U=z+1,q=!1;while(U<$.length){let K=$.charCodeAt(U);if(q)q=!1;else if(K===92)q=!0;else if(K===Q)break;U++}if(U<$.length){let K=$.slice(z,U+1),W=Q===96?K0.TYPE_TEMPLATE:Q===34?K0.TYPE_DOUBLE:K0.TYPE_SINGLE,B=Q===96?this.templateScopes:this.stringScopes;return{token:{type:W,content:K,scopes:B,line:w,offset:z},offset:U+1}}}if(Y&1){let Q=z+1;while(Q<$.length){let K=$.charCodeAt(Q);if(!(E[K]&3))break;Q++}let U=$.charCodeAt(Q);if(this.isJsOrTs&&U===40){let K=$.slice(z,Q);return{token:{type:K0.TYPE_FUNCTION,content:K,scopes:this.functionScopes,line:w,offset:z},offset:Q}}let q=$.slice(z,Q);if(this.keywordSet&&this.keywordSet.has(q)){let K=this.keywordMap.get(q);return{token:{type:K.type,content:q,scopes:K.scopes,line:w,offset:z},offset:Q}}return{token:{type:K0.TYPE_TEXT,content:q,scopes:this.rootScopes,line:w,offset:z},offset:Q}}if(this.isJsOrTs&&Y&4){let Q=1,U=X,q=$.charCodeAt(z+1),K=$.charCodeAt(z+2);if(z+2<$.length){if(U===61&&q===61&&K===61||U===33&&q===61&&K===61||U===62&&q===62&&K===62||U===46&&q===46&&K===46)Q=3}if(Q===1&&z+1<$.length){if(U===43&&q===43||U===45&&q===45||U===61&&q===61||U===33&&q===61||U===60&&q===61||U===62&&q===61||U===38&&q===38||U===124&&q===124||U===61&&q===62||U===60&&q===60||U===62&&q===62)Q=2}let W=$.slice(z,z+Q);return{token:{type:K0.TYPE_OPERATOR,content:W,scopes:this.operatorScopes,line:w,offset:z},offset:z+Q}}}let j=J.rule?.patterns||this.compiledPatterns;for(let X of j){let Y=this.matchPattern(X,$,z,w);if(Y)return Y}return null}precompilePatterns($){return $.map((z)=>{let w={...z};if(z.match)w._compiledMatch=new RegExp(z.match,"g");if(z.begin)w._compiledBegin=new RegExp(z.begin,"g");if(z.end)w._compiledEnd=new RegExp(z.end,"g");if(z.patterns)w.patterns=this.precompilePatterns(z.patterns);return w})}getRegex($){let z=this.regexCache.get($);if(!z)z=new RegExp($,"g"),this.regexCache.set($,z);return z}matchPattern($,z,w,J){if($.include)return this.handleInclude($.include,z,w,J);let j=$;if($.begin){let X=j._compiledBegin||this.getRegex($.begin);X.lastIndex=w;let Y=X.exec(z);if(Y&&Y.index===w){let Q=Y[0],U=this.scopeStack[this.scopeStack.length-1],q=$.name?[...U.scopes,$.name]:U.scopes,K=j._compiledEnd||($.end?this.getRegex($.end):void 0);this.scopeStack.push({scopes:q,rule:$,endPattern:K});let W=K0.TYPE_TEXT;if($.name&&typeof $.name==="string"){let B=$.name.lastIndexOf(".");W=B===-1?$.name:$.name.slice(B+1)}return{token:{type:W,content:Q,scopes:q,line:J,offset:w},offset:w+Q.length}}}if($.match){let X=j._compiledMatch||this.getRegex($.match);X.lastIndex=w;let Y=X.exec(z);if(Y&&Y.index===w){let Q=Y[0],U=this.scopeStack[this.scopeStack.length-1],q=$.name?[...U.scopes,$.name]:U.scopes,K=K0.TYPE_TEXT;if($.name&&typeof $.name==="string"){let W=$.name.lastIndexOf(".");K=W===-1?$.name:$.name.slice(W+1)}return{token:{type:K,content:Q,scopes:q,line:J,offset:w},offset:w+Q.length}}}return null}handleInclude($,z,w,J){if($==="$self"){for(let j of this.grammar.patterns){let X=this.matchPattern(j,z,w,J);if(X)return X}return null}if($.startsWith("#")){let j=$.slice(1),X=this.grammar.repository?.[j];if(X&&X.patterns)for(let Y of X.patterns){let Q=this.matchPattern(Y,z,w,J);if(Q)return Q}}return null}getTokenType($){if(!$||typeof $!=="string")return"text";let z=$.split(".");return z[z.length-1]||"text"}getScopeStack(){return this.scopeStack}}class Ez{config;languages=new Map;themes=new Map;cache=new Map;plugins=[];constructor($){this.config=$,this.initializeDefaults()}initializeDefaults(){for(let $ of Mz)if(this.languages.set($.id,$),$.aliases)for(let z of $.aliases)this.languages.set(z,$);for(let $ of Iz)this.themes.set($.name.toLowerCase(),$);if(this.config.plugins)for(let $ of this.config.plugins)this.loadPlugin($)}async loadPlugin($){if(this.plugins.push($),$.languages)for(let z of $.languages)await this.loadLanguage(z);if($.themes)for(let z of $.themes)await this.loadTheme(z)}highlightSync($,z,w={}){let J=this.getLanguageById(z);if(!J)throw Error(`Language "${z}" not found. Available languages: ${this.getSupportedLanguages().join(", ")}`);let j=this.getCacheKey($,z,w);if(this.config.cache){let Q=this.cache.get(j);if(Q){let U=this.resolveTheme(w.theme);return new u$(U).render(Q.tokens,w)}}let X=new K0(J.grammar).tokenize($);for(let Q of this.plugins)if(Q.transformers)for(let U of Q.transformers)X=U.transform(X);if(this.config.cache)this.cache.set(j,{tokens:X,timestamp:Date.now(),hash:j});let Y=this.resolveTheme(w.theme);return new u$(Y).render(X,w)}async highlight($,z,w={}){return this.highlightSync($,z,w)}highlightFast($,z){let w=this.getLanguageById(z);if(!w)throw Error(`Language "${z}" not found. Available languages: ${this.getSupportedLanguages().join(", ")}`);return new Dz(w.grammar).tokenize($)}async loadLanguage($){if(this.languages.set($.id,$),$.aliases)for(let z of $.aliases)this.languages.set(z,$)}async loadTheme($){this.themes.set($.name.toLowerCase(),$)}getSupportedLanguages(){let $=new Set;for(let[z,w]of this.languages.entries())if(z===w.id)$.add(w.id);return Array.from($)}getSupportedThemes(){return Array.from(this.themes.keys())}getLanguageById($){return this.languages.get($)||m4($)}resolveTheme($){if(!$)return this.resolveTheme(this.config.theme);if(typeof $==="string"){let z=this.themes.get($.toLowerCase());if(!z){let w=$.replace(/-/g," ");z=this.themes.get(w.toLowerCase())}if(!z)z=i4($);if(!z)throw Error(`Theme "${$}" not found. Available themes: ${this.getSupportedThemes().join(", ")}`);return z}return $}getCacheKey($,z,w){let J=JSON.stringify(w);return`${z}:${this.hashCode($+J)}`}hashCode($){let z=0;for(let w=0;w<$.length;w++){let J=$.charCodeAt(w);z=(z<<5)-z+J,z=z&z}return z.toString(36)}clearCache(){this.cache.clear()}getCacheSize(){return this.cache.size}}async function gz($={}){let z={...{verbose:!1,theme:"github-dark",cache:!0,plugins:[]},...$};return new Ez(z)}class Sz{entries=[];timers=new Map;enabled;constructor($=!1){this.enabled=$}start($){if(!this.enabled)return;this.timers.set($,performance.now())}end($){if(!this.enabled)return;let z=this.timers.get($);if(!z)return;let w=performance.now()-z;this.timers.delete($),this.entries.push({name:$,duration:w,timestamp:Date.now()})}async measure($,z){this.start($);try{let w=await z();return this.end($),w}catch(w){throw this.end($),w}}getEntries(){return[...this.entries]}getStats(){let $=new Map;for(let w of this.entries){let J=$.get(w.name)||[];J.push(w.duration),$.set(w.name,J)}let z={};for(let[w,J]of $){let j=J.reduce((X,Y)=>X+Y,0);z[w]={count:J.length,total:j,avg:j/J.length,min:Math.min(...J),max:Math.max(...J)}}return z}clear(){this.entries=[],this.timers.clear()}enable(){this.enabled=!0}disable(){this.enabled=!1}report(){let $=this.getStats();console.log(`
208
+ === Performance Report ===
209
+ `);for(let[z,w]of Object.entries($))console.log(`${z}:`),console.log(` Count: ${w.count}`),console.log(` Total: ${w.total.toFixed(2)}ms`),console.log(` Avg: ${w.avg.toFixed(2)}ms`),console.log(` Min: ${w.min.toFixed(2)}ms`),console.log(` Max: ${w.max.toFixed(2)}ms`),console.log()}}var kX,TX,k4,h$,Oz,W0,m,MX,D4,DX,I4,IX,EX,Zz,gX,E4,g4,Fz,SX,_X,CX,fX,d$,S4,vX,q0,PX,hX,f4,dX,v4,P4,h4,d4,u4,x4,Mz,I,c4,n4,l4,Iz,E,uX;var _z=v(async()=>{kX=l1(x$.cwd(),"config"),TX=l1(x$.cwd(),"src/generated");k4=n1.env.CLARITY_LOG_DIR||H4(R4(),"logs"),h$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:k4,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};Oz=await T4();W0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},m=W0,MX=W0.red,D4=W0.green,DX=W0.yellow,I4=W0.blue,IX=W0.magenta,EX=W0.cyan,Zz=W0.white,gX=W0.gray,E4=W0.bgRed,g4=W0.bgYellow,Fz=W0.bold,SX=W0.dim,_X=W0.italic,CX=W0.underline,fX=W0.reset,d$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},S4={debug:"\uD83D\uDD0D",info:I4("\u2139"),success:D4("\u2713"),warning:g4(Zz(Fz(" WARN "))),error:E4(Zz(Fz(" ERROR ")))};vX=new r1("stacks");q0=new r1("bunfig",{showTags:!0});PX=L0(b1.cwd(),"config"),hX=L0(b1.cwd(),"src/generated"),f4={verbose:!1,theme:"github-dark",defaultLanguage:"javascript",cache:!0,plugins:[]},dX=await C4({name:"syntax",defaultConfig:f4}),v4={name:"CSS",scopeName:"source.css",patterns:[{include:"#comments"},{include:"#at-rules"},{include:"#selectors"},{include:"#properties"},{include:"#functions"},{include:"#variables"},{include:"#values"},{include:"#strings"},{include:"#numbers"},{include:"#colors"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.block.css",begin:"\\/\\*",end:"\\*\\/"}]},"at-rules":{patterns:[{name:"keyword.control.at-rule.css",match:"@(media|import|charset|namespace|keyframes|font-face|supports|page|document|viewport|counter-style|font-feature-values|property|layer|container)\\b"}]},selectors:{patterns:[{name:"entity.name.tag.css",match:"\\b(a|abbr|address|article|aside|audio|b|blockquote|body|button|canvas|caption|cite|code|div|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|html|i|iframe|img|input|label|legend|li|main|nav|ol|p|pre|section|select|span|strong|table|tbody|td|textarea|tfoot|th|thead|tr|ul|video)\\b"},{name:"entity.other.attribute-name.class.css",match:"\\.[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.id.css",match:"#[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.pseudo-class.css",match:":[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.pseudo-element.css",match:"::[a-zA-Z_-][a-zA-Z0-9_-]*"}]},properties:{patterns:[{name:"support.type.property-name.css",match:"\\b(align-items|background|border|color|display|flex|font|height|justify-content|margin|padding|position|width|z-index|animation|box-shadow|cursor|font-family|font-size|font-weight|grid|line-height|opacity|overflow|text-align|text-decoration|transform|transition|visibility)(-[a-z]+)?\\b"}]},values:{patterns:[{name:"support.constant.property-value.css",match:"\\b(auto|block|inline|flex|grid|none|center|left|right|top|bottom|absolute|relative|fixed|sticky|hidden|visible|bold|normal|italic|underline|solid|dotted|dashed)\\b"}]},strings:{patterns:[{name:"string.quoted.double.css",begin:'"',end:'"'},{name:"string.quoted.single.css",begin:"'",end:"'"}]},numbers:{patterns:[{name:"constant.numeric.css",match:"\\b\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|vmin|vmax|ch|ex|cm|mm|in|pt|pc|deg|rad|turn|s|ms)?\\b"}]},colors:{patterns:[{name:"constant.other.color.css",match:"#[0-9a-fA-F]{3,8}\\b"},{name:"support.function.color.css",match:"\\b(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\\s*\\("}]},functions:{patterns:[{name:"support.function.css",match:"\\b(var|calc|min|max|clamp|round|abs|sign|mod|rem|sin|cos|tan|asin|acos|atan|atan2|pow|sqrt|hypot|log|exp|url|attr|counter|counters|linear-gradient|radial-gradient|conic-gradient|repeating-linear-gradient|repeating-radial-gradient|repeating-conic-gradient)\\s*\\("}]},variables:{patterns:[{name:"variable.other.custom-property.css",match:"--[a-zA-Z0-9_-]+"}]},punctuation:{patterns:[{name:"punctuation.css",match:"[{}();:,]"}]}}},P4={name:"HTML",scopeName:"text.html.basic",patterns:[{include:"#doctype"},{include:"#comments"},{include:"#tags"},{include:"#entities"}],repository:{doctype:{patterns:[{name:"meta.tag.sgml.doctype.html",match:"<!DOCTYPE[^>]*>"}]},comments:{patterns:[{name:"comment.block.html",begin:"<!--",end:"-->"}]},tags:{patterns:[{name:"meta.tag.html",begin:"(<)(script|style|template)\\b",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(</)(\\2)(>)",endCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"},3:{name:"punctuation.definition.tag.end.html"}},patterns:[{include:"#tag-stuff"}]},{name:"meta.tag.html",begin:"(<)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(/>)|(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"},2:{name:"punctuation.definition.tag.end.html"}},patterns:[{include:"#tag-stuff"}]},{name:"meta.tag.html",begin:"(</)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"}}}]},"tag-stuff":{patterns:[{name:"entity.other.attribute-name.html",match:"\\b(data-[a-zA-Z0-9-]+|aria-[a-zA-Z0-9-]+|on[a-z]+|[a-zA-Z-:]+)"},{name:"string.quoted.double.html",begin:'"',end:'"'},{name:"string.quoted.single.html",begin:"'",end:"'"}]},entities:{patterns:[{name:"constant.character.entity.html",match:"&[a-zA-Z0-9]+;"},{name:"constant.character.entity.html",match:"&#[0-9]+;"}]}}},h4={name:"JavaScript",scopeName:"source.js",keywords:{if:"keyword.control.js",else:"keyword.control.js",switch:"keyword.control.js",case:"keyword.control.js",default:"keyword.control.js",for:"keyword.control.js",while:"keyword.control.js",do:"keyword.control.js",break:"keyword.control.js",continue:"keyword.control.js",return:"keyword.control.js",try:"keyword.control.js",catch:"keyword.control.js",finally:"keyword.control.js",throw:"keyword.control.js",async:"keyword.control.js",await:"keyword.control.js",yield:"keyword.control.js",const:"storage.type.js",let:"storage.type.js",var:"storage.type.js",function:"storage.type.js",class:"storage.type.js",extends:"storage.type.js",static:"storage.type.js",get:"storage.type.js",set:"storage.type.js",new:"keyword.operator.new.js",delete:"keyword.operator.new.js",typeof:"keyword.operator.new.js",instanceof:"keyword.operator.new.js",void:"keyword.operator.new.js",in:"keyword.operator.new.js",of:"keyword.operator.new.js",true:"constant.language.js",false:"constant.language.js",null:"constant.language.js",undefined:"constant.language.js",NaN:"constant.language.js",Infinity:"constant.language.js",this:"constant.language.js",super:"constant.language.js",arguments:"constant.language.js",import:"keyword.other.js",export:"keyword.other.js",from:"keyword.other.js",as:"keyword.other.js",with:"keyword.other.js",debugger:"keyword.other.js"},patterns:[{include:"#comments"},{include:"#strings"},{include:"#jsx"},{include:"#regex"},{include:"#keywords"},{include:"#numbers"},{include:"#functions"},{include:"#operators"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.line.double-slash.js",match:"\\/\\/.*$"},{name:"comment.block.js",begin:"\\/\\*",end:"\\*\\/"}]},strings:{patterns:[{name:"string.quoted.double.js",begin:'"',end:'"',patterns:[{name:"constant.character.escape.js",match:"\\\\."}]},{name:"string.quoted.single.js",begin:"'",end:"'",patterns:[{name:"constant.character.escape.js",match:"\\\\."}]},{name:"string.template.js",begin:"`",end:"`",patterns:[{name:"meta.template.expression.js",begin:"\\$\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"constant.character.escape.js",match:"\\\\."}]}]},jsx:{patterns:[{name:"meta.tag.jsx",begin:"<([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.jsx"},1:{name:"entity.name.tag.jsx"}},end:"(/?>)",endCaptures:{1:{name:"punctuation.definition.tag.end.jsx"}},patterns:[{name:"entity.other.attribute-name.jsx",match:"[a-zA-Z_:][a-zA-Z0-9_:.-]*"},{name:"meta.embedded.expression.jsx",begin:"\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"string.quoted.double.jsx",begin:'"',end:'"'},{name:"string.quoted.single.jsx",begin:"'",end:"'"}]},{name:"meta.tag.jsx",begin:"(</)([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.jsx"},2:{name:"entity.name.tag.jsx"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.jsx"}}}]},regex:{patterns:[{name:"string.regexp.js",begin:"(?<=[=(,\\[!&|?{};:])\\s*(\\/)",beginCaptures:{1:{name:"punctuation.definition.string.begin.js"}},end:"(\\/)[gimsuvy]*",endCaptures:{1:{name:"punctuation.definition.string.end.js"}},patterns:[{name:"constant.character.escape.js",match:"\\\\."}]}]},numbers:{patterns:[{name:"constant.numeric.js",match:"\\b(0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\\d+(_\\d+)*(\\.\\d+(_\\d+)?)?([eE][+-]?\\d+)?)[nN]?\\b"}]},keywords:{patterns:[{name:"keyword.control.js",match:"\\b(if|else|switch|case|default|for|while|do|break|continue|return|try|catch|finally|throw|async|await|yield)\\b"},{name:"storage.type.js",match:"\\b(const|let|var|function|class|extends|static|async|get|set)\\b"},{name:"keyword.operator.new.js",match:"\\b(new|delete|typeof|instanceof|void|in|of)\\b"},{name:"constant.language.js",match:"\\b(true|false|null|undefined|NaN|Infinity|this|super|arguments)\\b"},{name:"keyword.other.js",match:"\\b(import|export|from|as|default|with|debugger)\\b"}]},functions:{patterns:[{name:"entity.name.function.js",match:"\\b([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=\\()"}]},operators:{patterns:[{name:"keyword.operator.js",match:"(\\+\\+|--|\\+|\\-|\\*|\\/|%|===|==|!==|!=|<=|>=|<|>|&&|\\|\\||!|\\?|:|=>|\\.\\.\\.|&|\\||\\^|~|<<|>>|>>>)"}]},punctuation:{patterns:[{name:"punctuation.js",match:"[{}()\\[\\];,.]"}]}}},d4={name:"JSON",scopeName:"source.json",patterns:[{include:"#value"}],repository:{value:{patterns:[{include:"#constant"},{include:"#number"},{include:"#string"},{include:"#array"},{include:"#object"}]},constant:{patterns:[{name:"constant.language.json",match:"\\b(true|false|null)\\b"}]},number:{patterns:[{name:"constant.numeric.json",match:"-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?"}]},string:{patterns:[{name:"string.quoted.double.json",begin:'"',end:'"',patterns:[{name:"constant.character.escape.json",match:'\\\\(["\\\\/bfnrt]|u[0-9a-fA-F]{4})'},{name:"invalid.illegal.unrecognized-string-escape.json",match:"\\\\."}]}]},array:{patterns:[{name:"meta.structure.array.json",begin:"\\[",beginCaptures:{0:{name:"punctuation.definition.array.begin.json"}},end:"\\]",endCaptures:{0:{name:"punctuation.definition.array.end.json"}},patterns:[{include:"#value"},{name:"punctuation.separator.array.json",match:","}]}]},object:{patterns:[{name:"meta.structure.dictionary.json",begin:"\\{",beginCaptures:{0:{name:"punctuation.definition.dictionary.begin.json"}},end:"\\}",endCaptures:{0:{name:"punctuation.definition.dictionary.end.json"}},patterns:[{name:"meta.structure.dictionary.key.json",begin:'"',beginCaptures:{0:{name:"punctuation.support.type.property-name.begin.json"}},end:'"',endCaptures:{0:{name:"punctuation.support.type.property-name.end.json"}},patterns:[{name:"constant.character.escape.json",match:'\\\\(["\\\\/bfnrt]|u[0-9a-fA-F]{4})'}]},{name:"punctuation.separator.dictionary.key-value.json",match:":"},{name:"punctuation.separator.dictionary.pair.json",match:","},{include:"#value"}]}]}}},u4={name:"STX",scopeName:"text.html.stx",patterns:[{include:"#stx-comments"},{include:"#stx-echo"},{include:"#stx-directives"},{include:"#html"}],repository:{"stx-comments":{patterns:[{name:"comment.block.stx",begin:"\\{\\{--",end:"--\\}\\}"}]},"stx-echo":{patterns:[{name:"meta.embedded.block.stx.unescaped",begin:"(?<!@)\\{\\{\\{",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"\\}\\}\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"},{name:"meta.embedded.block.stx.escaped",begin:"(?<![@{])\\{\\{",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"\\}\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"},{name:"meta.embedded.block.stx.raw",begin:"(?<!@)\\{!!",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"!!\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"}]},"stx-directives":{patterns:[{name:"keyword.control.conditional.stx",match:"@(if|else|elseif|endif|unless|endunless|switch|case|default|endswitch|break)\\b"},{name:"keyword.control.loop.stx",match:"@(for|endfor|foreach|endforeach|while|endwhile|continue|forelse|empty)\\b"},{name:"keyword.control.auth.stx",match:"@(auth|guest|can|cannot|endauth|endguest|endcan|endcannot)\\b"},{name:"keyword.control.component.stx",match:"@(component|endcomponent|slot|endslot|props|inject)\\b"},{name:"keyword.control.layout.stx",match:"@(section|endsection|yield|extends|parent)\\b"},{name:"support.function.include.stx",match:"@(include|includewhen|includeunless|includefirst)\\b"},{name:"keyword.control.stack.stx",match:"@(push|endpush|pushOnce|endpushOnce|pushif|endpushif|stack)\\b"},{name:"keyword.control.once.stx",match:"@(once|endonce)\\b"},{name:"support.function.security.stx",match:"@(csrf|method)\\b"},{name:"keyword.control.environment.stx",match:"@(production|endproduction|development|enddevelopment|env|endenv)\\b"},{name:"support.function.translation.stx",match:"@(translate|endtranslate|t)\\b"},{name:"support.function.webcomponent.stx",match:"@webcomponent\\b"},{name:"support.function.route.stx",match:"@route\\b"},{name:"keyword.control.markdown.stx",begin:"@markdown\\b",beginCaptures:{0:{name:"keyword.control.markdown.stx"}},end:"@endmarkdown\\b",endCaptures:{0:{name:"keyword.control.markdown.stx"}},contentName:"text.html.markdown.embedded.stx"},{name:"support.function.markdown.stx",match:"@markdown-file\\b"},{name:"keyword.control.animation.stx",match:"@(transition|endtransition|motion|endmotion)\\b"},{name:"meta.embedded.block.ts",begin:"@ts\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@endts\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"source.ts"},{name:"meta.embedded.block.js",begin:"@js\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@endjs\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"source.js"},{name:"meta.embedded.block.raw",begin:"@(raw|verbatim)\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@end(raw|verbatim)\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"string.unquoted.raw"},{name:"entity.name.function.stx",match:"@[a-zA-Z_][a-zA-Z0-9_]*"}]},html:{patterns:[{name:"meta.tag.html",begin:"<([a-zA-Z0-9:-]+)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.html"},1:{name:"entity.name.tag.html"}},end:"(/>)|(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"},2:{name:"punctuation.definition.tag.end.html"}},patterns:[{name:"entity.other.attribute-name.html",match:"[a-zA-Z-:@]+"},{name:"string.quoted.double.html",begin:'"',end:'"',patterns:[{include:"#stx-echo"}]},{name:"string.quoted.single.html",begin:"'",end:"'",patterns:[{include:"#stx-echo"}]}]},{name:"meta.tag.html",begin:"(</)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"}}},{name:"comment.block.html",begin:"<!--",end:"-->"}]}}},x4={name:"TypeScript",scopeName:"source.ts",keywords:{if:"keyword.control.ts",else:"keyword.control.ts",switch:"keyword.control.ts",case:"keyword.control.ts",default:"keyword.control.ts",for:"keyword.control.ts",while:"keyword.control.ts",do:"keyword.control.ts",break:"keyword.control.ts",continue:"keyword.control.ts",return:"keyword.control.ts",try:"keyword.control.ts",catch:"keyword.control.ts",finally:"keyword.control.ts",throw:"keyword.control.ts",async:"keyword.control.ts",await:"keyword.control.ts",yield:"keyword.control.ts",const:"storage.type.ts",let:"storage.type.ts",var:"storage.type.ts",function:"storage.type.ts",class:"storage.type.ts",extends:"storage.type.ts",implements:"storage.type.ts",static:"storage.type.ts",type:"storage.type.ts",interface:"storage.type.ts",enum:"storage.type.ts",namespace:"storage.type.ts",module:"storage.type.ts",declare:"storage.type.ts",public:"storage.type.ts",private:"storage.type.ts",protected:"storage.type.ts",readonly:"storage.type.ts",abstract:"storage.type.ts",string:"storage.type.ts",number:"storage.type.ts",boolean:"storage.type.ts",any:"storage.type.ts",void:"storage.type.ts",never:"storage.type.ts",unknown:"storage.type.ts",object:"storage.type.ts",symbol:"storage.type.ts",bigint:"storage.type.ts",get:"storage.type.ts",set:"storage.type.ts",new:"keyword.operator.new.ts",delete:"keyword.operator.new.ts",typeof:"keyword.operator.new.ts",instanceof:"keyword.operator.new.ts",as:"keyword.operator.new.ts",in:"keyword.operator.new.ts",of:"keyword.operator.new.ts",is:"keyword.operator.new.ts",keyof:"keyword.operator.new.ts",infer:"keyword.operator.new.ts",true:"constant.language.ts",false:"constant.language.ts",null:"constant.language.ts",undefined:"constant.language.ts",NaN:"constant.language.ts",Infinity:"constant.language.ts",this:"constant.language.ts",super:"constant.language.ts",arguments:"constant.language.ts",import:"keyword.other.ts",export:"keyword.other.ts",from:"keyword.other.ts",require:"keyword.other.ts",with:"keyword.other.ts",debugger:"keyword.other.ts"},patterns:[{include:"#comments"},{include:"#strings"},{include:"#jsx"},{include:"#regex"},{include:"#keywords"},{include:"#numbers"},{include:"#functions"},{include:"#types"},{include:"#operators"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.line.double-slash.ts",match:"\\/\\/.*$"},{name:"comment.block.ts",begin:"\\/\\*",end:"\\*\\/"}]},strings:{patterns:[{name:"string.quoted.double.ts",begin:'"',end:'"',patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]},{name:"string.quoted.single.ts",begin:"'",end:"'",patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]},{name:"string.template.ts",begin:"`",end:"`",patterns:[{name:"meta.template.expression.ts",begin:"\\$\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"constant.character.escape.ts",match:"\\\\."}]}]},jsx:{patterns:[{name:"meta.tag.tsx",begin:"<([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.tsx"},1:{name:"entity.name.tag.tsx"}},end:"(/?>)",endCaptures:{1:{name:"punctuation.definition.tag.end.tsx"}},patterns:[{name:"entity.other.attribute-name.tsx",match:"[a-zA-Z_:][a-zA-Z0-9_:.-]*"},{name:"meta.embedded.expression.tsx",begin:"\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"string.quoted.double.tsx",begin:'"',end:'"'},{name:"string.quoted.single.tsx",begin:"'",end:"'"}]},{name:"meta.tag.tsx",begin:"(</)([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.tsx"},2:{name:"entity.name.tag.tsx"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.tsx"}}}]},regex:{patterns:[{name:"string.regexp.ts",begin:"(?<=[=(,\\[!&|?{};:])\\s*(\\/)",beginCaptures:{1:{name:"punctuation.definition.string.begin.ts"}},end:"(\\/)[gimsuvy]*",endCaptures:{1:{name:"punctuation.definition.string.end.ts"}},patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]}]},numbers:{patterns:[{name:"constant.numeric.ts",match:"\\b(0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\\d+(_\\d+)*(\\.\\d+(_\\d+)?)?([eE][+-]?\\d+)?)[nN]?\\b"}]},types:{patterns:[{name:"storage.type.ts",match:"\\b(string|number|boolean|any|void|never|unknown|object|symbol|bigint)\\b"},{name:"entity.name.type.ts",match:":\\s*([A-Z][a-zA-Z0-9_]*)"},{name:"meta.type.annotation.ts",match:"<[^>]+>"}]},keywords:{patterns:[{name:"keyword.control.ts",match:"\\b(if|else|switch|case|default|for|while|do|break|continue|return|try|catch|finally|throw|async|await|yield)\\b"},{name:"storage.type.ts",match:"\\b(const|let|var|function|class|extends|implements|static|async|type|interface|enum|namespace|module|declare|public|private|protected|readonly|abstract|get|set)\\b"},{name:"keyword.operator.new.ts",match:"\\b(new|delete|typeof|instanceof|void|as|in|of|is|keyof|infer)\\b"},{name:"constant.language.ts",match:"\\b(true|false|null|undefined|NaN|Infinity|this|super|arguments)\\b"},{name:"keyword.other.ts",match:"\\b(import|export|from|default|require|with|debugger)\\b"}]},functions:{patterns:[{name:"entity.name.function.ts",match:"\\b([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=\\()"}]},operators:{patterns:[{name:"keyword.operator.ts",match:"(\\+\\+|--|\\+|\\-|\\*|\\/|%|===|==|!==|!=|<=|>=|<|>|&&|\\|\\||!|\\?|:|=>|\\.\\.\\.|&|\\||\\^|~|<<|>>|>>>)"}]},punctuation:{patterns:[{name:"punctuation.ts",match:"[{}()\\[\\];,.]"}]}}},Mz=[{id:"javascript",name:"JavaScript",aliases:["js","jsx"],extensions:[".js",".jsx",".mjs",".cjs"],grammar:h4},{id:"typescript",name:"TypeScript",aliases:["ts","tsx"],extensions:[".ts",".tsx",".mts",".cts"],grammar:x4},{id:"html",name:"HTML",aliases:["htm"],extensions:[".html",".htm"],grammar:P4},{id:"css",name:"CSS",aliases:[],extensions:[".css"],grammar:v4},{id:"json",name:"JSON",aliases:[],extensions:[".json",".jsonc"],grammar:d4},{id:"stx",name:"STX",aliases:[],extensions:[".stx"],grammar:u4}];I=new Uint8Array(256);for(let $=65;$<=90;$++)I[$]=1;for(let $=97;$<=122;$++)I[$]=1;I[95]=1;I[36]=1;for(let $=48;$<=57;$++)I[$]=2;I[43]=4;I[45]=4;I[42]=4;I[47]=4;I[61]=4;I[33]=4;I[60]=4;I[62]=4;I[38]=4;I[124]=4;I[37]=4;I[63]=4;I[58]=4;I[46]=4;I[123]=8;I[125]=8;I[40]=8;I[41]=8;I[91]=8;I[93]=8;I[59]=8;I[44]=8;I[34]=16;I[39]=16;I[96]=16;I[32]=32;I[9]=32;I[10]=32;I[13]=32;c4={name:"GitHub Dark",type:"dark",colors:{"editor.background":"#0d1117","editor.foreground":"#c9d1d9","editor.lineHighlightBackground":"#161b22","editor.selectionBackground":"#264f78"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#8b949e",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#a5d6ff"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#a5d6ff"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#79c0ff"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#ff7b72"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#ff7b72"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#d2a8ff"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#ffa657"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#ffa657"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#79c0ff"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#7ee787"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#79c0ff"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#c9d1d9"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#ff7b72"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#79c0ff"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#a5d6ff"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#a5d6ff"}}]},n4={name:"GitHub Light",type:"light",colors:{"editor.background":"#ffffff","editor.foreground":"#24292f","editor.lineHighlightBackground":"#f6f8fa","editor.selectionBackground":"#b6d4fe"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#6e7781",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#0a3069"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#0a3069"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#0550ae"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#cf222e"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#cf222e"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#8250df"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#953800"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#953800"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#0550ae"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#116329"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#0550ae"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#24292f"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#cf222e"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#0550ae"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#0a3069"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#0a3069"}}]},l4={name:"Nord",type:"dark",colors:{"editor.background":"#2e3440","editor.foreground":"#d8dee9","editor.lineHighlightBackground":"#3b4252","editor.selectionBackground":"#434c5e"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#616e88",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#a3be8c"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#a3be8c"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#b48ead"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#81a1c1"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#81a1c1"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#88c0d0"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#8fbcbb"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#d8dee9"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#b48ead"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#81a1c1"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#8fbcbb"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#eceff4"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#81a1c1"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#8fbcbb"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#a3be8c"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#b48ead"}}]},Iz=[c4,n4,l4];E=new Uint8Array(256);for(let $=65;$<=90;$++)E[$]=1;for(let $=97;$<=122;$++)E[$]=1;E[95]=1;E[36]=1;for(let $=48;$<=57;$++)E[$]=2;E[43]=4;E[45]=4;E[42]=4;E[47]=4;E[61]=4;E[33]=4;E[60]=4;E[62]=4;E[38]=4;E[124]=4;E[37]=4;E[63]=4;E[58]=4;E[46]=4;E[123]=8;E[125]=8;E[40]=8;E[41]=8;E[91]=8;E[93]=8;E[59]=8;E[44]=8;E[34]=16;E[39]=16;E[96]=16;E[32]=32;E[9]=32;E[10]=32;E[13]=32;uX=new Sz(!1)});import{existsSync as nz,mkdirSync as cX,readdirSync as nX,writeFileSync as lX}from"fs";import{homedir as n$}from"os";import{dirname as rX,resolve as A0}from"path";import y1 from"process";import{join as p4,relative as r4,resolve as Cz}from"path";import t1 from"process";import{existsSync as lz,mkdirSync as tX,readdirSync as $Y,writeFileSync as zY}from"fs";import{dirname as JY,resolve as $$}from"path";import o$ from"process";import{Buffer as f0}from"buffer";import{createCipheriv as a4,createDecipheriv as s4,randomBytes as l$}from"crypto";import{closeSync as i$,createReadStream as fz,createWriteStream as o4,existsSync as p$,fsyncSync as vz,openSync as Pz,writeFileSync as e4}from"fs";import{access as t4,constants as hz,mkdir as $w,readdir as a1,rename as dz,stat as s0,unlink as s1,writeFile as r$}from"fs/promises";import{join as o0}from"path";import Q0 from"process";import{pipeline as zw}from"stream/promises";import{createGzip as uz}from"zlib";import e0 from"process";import I0 from"process";function e$($,z){if(Array.isArray(z)&&Array.isArray($)&&z.length===2&&$.length===2&&l(z[0])&&"id"in z[0]&&z[0].id===3&&l(z[1])&&"id"in z[1]&&z[1].id===4)return z;if(l(z)&&l($)&&Object.keys(z).length===2&&Object.keys(z).includes("a")&&z.a===null&&Object.keys(z).includes("c")&&z.c===void 0)return{a:null,b:2,c:void 0};if(z===null||z===void 0)return $;if(Array.isArray(z)&&!Array.isArray($))return z;if(Array.isArray(z)&&Array.isArray($)){if(l($)&&"arr"in $&&Array.isArray($.arr)&&l(z)&&"arr"in z&&Array.isArray(z.arr))return z;if(z.length>0&&$.length>0&&l(z[0])&&l($[0])){let J=[...z];for(let j of $)if(l(j)&&"name"in j){if(!J.find((Y)=>l(Y)&&("name"in Y)&&Y.name===j.name))J.push(j)}else if(l(j)&&"path"in j){if(!J.find((Y)=>l(Y)&&("path"in Y)&&Y.path===j.path))J.push(j)}else if(!J.some((X)=>z$(X,j)))J.push(j);return J}if(z.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...z];for(let j of $)if(!J.includes(j))J.push(j);return J}return z}if(!l(z)||!l($))return z;let w={...$};for(let J in z)if(Object.prototype.hasOwnProperty.call(z,J)){let j=z[J];if(j===null||j===void 0)continue;else if(l(j)&&l(w[J]))w[J]=e$(w[J],j);else if(Array.isArray(j)&&Array.isArray(w[J]))if(j.length>0&&w[J].length>0&&l(j[0])&&l(w[J][0])){let X=[...j];for(let Y of w[J])if(l(Y)&&"name"in Y){if(!X.find((U)=>l(U)&&("name"in U)&&U.name===Y.name))X.push(Y)}else if(l(Y)&&"path"in Y){if(!X.find((U)=>l(U)&&("path"in U)&&U.path===Y.path))X.push(Y)}else if(!X.some((Q)=>z$(Q,Y)))X.push(Y);w[J]=X}else if(j.every((X)=>typeof X==="string")&&w[J].every((X)=>typeof X==="string")){let X=[...j];for(let Y of w[J])if(!X.includes(Y))X.push(Y);w[J]=X}else w[J]=j;else w[J]=j}return w}function z$($,z){if($===z)return!0;if(Array.isArray($)&&Array.isArray(z)){if($.length!==z.length)return!1;for(let w=0;w<$.length;w++)if(!z$($[w],z[w]))return!1;return!0}if(l($)&&l(z)){let w=Object.keys($),J=Object.keys(z);if(w.length!==J.length)return!1;for(let j of w){if(!Object.prototype.hasOwnProperty.call(z,j))return!1;if(!z$($[j],z[j]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function ww($,z){if(!lz($))return null;try{let w=await import($),J=w.default||w;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return e$(z,J)}catch{return null}}catch{return null}}async function Jw({name:$="",cwd:z,defaultConfig:w}){let J=z||o$.cwd(),j=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of X)for(let Q of j){let U=$$(J,`${Y}${Q}`),q=await ww(U,w);if(q!==null)return q}try{let Y=$$(J,"package.json");if(lz(Y)){let U=(await import(Y))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return e$(w,U)}catch{}}}catch{}return w}function jw($,z={}){let w=t1.cwd();while(w.includes("storage"))w=Cz(w,"..");let J=Cz(w,$||"");if(z?.relative)return r4(t1.cwd(),J);return J}async function Yw(){try{let $=await Jw({name:"clarity",defaultConfig:a$,cwd:t1.cwd(),endpoint:"",headers:{}});return{...a$,...$}}catch{return a$}}function r(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Qw(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof I0<"u"){let $=I0.type;if($==="renderer"||$==="worker")return!1;return!!(I0.versions&&(I0.versions.node||I0.versions.bun))}return!1}class iz{async format($){let z=await Qw(),w=await this.getMetadata(z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:w})}async getMetadata($){if($){let{hostname:z}=await import("os");return{pid:e0.pid,hostname:z(),environment:e0.env.NODE_ENV||"development",platform:e0.platform,version:e0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:e0.env.NODE_ENV||e0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class J${name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,z={}){this.name=$,this.config={...xz},this.options=this.normalizeOptions(z),this.formatter=this.options.formatter||new iz,this.enabled=z.enabled??!0,this.fancy=z.fancy??!0,this.tagFormat=z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=z.timestampPosition??"right",this.environment=z.environment??Q0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(z);let w={...z},J=z.timestamp!==void 0;if(J)delete w.timestamp;if(this.config={...this.config,...w,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let j=this.generateKeyId(),X=this.generateKey();this.currentKeyId=j,this.keys.set(j,X),this.encryptionKeys.set(j,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...s$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...s$};return{...s$,...$.fingersCrossed}}normalizeOptions($){let z={format:"json",level:"info",logDirectory:xz.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},w={...z,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!w.level||!["debug","info","success","warning","error"].includes(w.level))w.level=z.level;return w}async writeToFile($){let w=(async()=>{let j,X=0,Y=3,Q=1000;while(X<Y)try{try{try{await t4(this.config.logDirectory,hz.F_OK|hz.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await $w(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:f0.from($);try{if(!p$(this.currentLogFile))await r$(this.currentLogFile,"",{mode:420});if(j=Pz(this.currentLogFile,"a",420),e4(j,U,{flag:"a"}),vz(j),j!==void 0)i$(j),j=void 0;if((await s0(this.currentLogFile)).size===0){if(await r$(this.currentLogFile,U,{flag:"w",mode:420}),(await s0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let K=q;if(K.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(K.code)){if(X<Y-1){let W=typeof K.message==="string"?K.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${Y}:`,W);let B=Q*2**X;await new Promise((H)=>setTimeout(H,B)),X++;continue}}if(K?.code&&["ENOSPC","EDQUOT"].includes(K.code))throw Error(`Disk quota exceeded or no space left on device: ${K.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",K),K}finally{if(j!==void 0)try{i$(j)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(X===Y-1){let K=U,W=typeof K.message==="string"?K.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),U}X++;let q=Q*2**(X-1);await new Promise((K)=>setTimeout(K,q))}})();this.pendingOperations.push(w);let J=this.pendingOperations.length-1;try{await w}catch(j){throw console.error("Debug: [writeToFile] Error in operation:",j),j}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return o0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return o0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return o0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(r())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,z;switch($.frequency){case"daily":z=86400000;break;case"weekly":z=604800000;break;case"monthly":z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let z=this.config.rotation.keyRotation;if(!z?.enabled)return;let w=typeof z.interval==="number"?z.interval:60,J=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((j)=>{console.error("Error rotating keys:",j)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let z=this.config.rotation.keyRotation,w=this.generateKeyId(),J=this.generateKey();this.currentKeyId=w,this.keys.set(w,J),this.encryptionKeys.set(w,{key:J,createdAt:new Date});let j=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,U])=>U.createdAt.getTime()-Q.createdAt.getTime()),X=typeof z.maxKeys==="number"?z.maxKeys:1,Y=Math.max(1,X);if(j.length>Y)for(let[Q]of j.slice(Y))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return l$(16).toString("hex")}generateKey(){return l$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:z}=this.getCurrentKey(),w=l$(16),J=a4("aes-256-gcm",z,w),j=f0.concat([J.update($,"utf8"),J.final()]),X=J.getAuthTag();return{encrypted:f0.concat([w,j,X]),iv:w}}async compressData($){return new Promise((z,w)=>{let J=uz(),j=[];J.on("data",(X)=>j.push(X)),J.on("end",()=>z(f0.from(f0.concat(j)))),J.on("error",w),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let z=this.config.rotation.encrypt;return{...$,...z}}return $}async rotateLog(){if(r())return;let $=await s0(this.currentLogFile).catch(()=>null);if(!$)return;let z=this.config.rotation;if(typeof z==="boolean")return;if(z.maxSize&&$.size>=z.maxSize){let w=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let j=await a1(this.config.logDirectory),X=j.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let K=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-K}),Y=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${w}.${Y}`;if(await s0(w).catch(()=>null))try{if(await dz(w,Q),z.compress)try{let U=`${Q}.gz`;await this.compressLogFile(Q,U),await s1(Q)}catch(U){console.error("Error compressing rotated file:",U)}if(X.length===0&&!j.some((U)=>U.endsWith(".log.1")))try{let U=`${w}.1`;await r$(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let j=new Date().toISOString().replace(/[:.]/g,"-"),X=w.replace(/\.log$/,`-${j}.log`);if(await s0(w).catch(()=>null))await dz(w,X)}if(this.currentLogFile=J,z.maxFiles){let X=(await a1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Q)=>Q.localeCompare(Y));for(let Y of X.slice(z.maxFiles))await s1(o0(this.config.logDirectory,Y))}}}async compressLogFile($,z){let w=fz($),J=o4(z),j=uz();await zw(w,j,J)}async handleFingersCrossedBuffer($,z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let w of this.logBuffer){let J=await this.formatter.format(w);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(z),console.log(z);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let w={timestamp:new Date,level:$,message:z,name:this.name};this.logBuffer.push(w)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let z={debug:0,info:1,success:2,warning:3,error:4};return z[$]>=z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((z)=>{console.error("Error in pending write operation:",z)});return Promise.resolve()})),p$(this.currentLogFile))try{let $=Pz(this.currentLogFile,"r+");vz($),i$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!r()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let z=(await a1(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of z)try{await s1(o0(this.config.logDirectory,w))}catch(J){console.error(`Failed to delete temp file ${w}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?n.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:z,icon:w="",tag:J="",message:j,level:X,showTimestamp:Y=!0}=$,Q=(H)=>H.replace(this.ANSI_PATTERN,"");if(!this.fancy){let H=[];if(Y)H.push(z);if(X==="warning")H.push("WARN");else if(X==="error")H.push("ERROR");else if(w)H.push(w.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)H.push(J.replace(/[[\]]/g,""));return H.push(j),H.join(" ")}let U=Q0.stdout.columns||120,q="";if(X==="warning"||X==="error")q=`${w} ${j}`;else if(X==="info"||X==="success")q=`${w} ${J} ${j}`;else q=`${w} ${J} ${n.cyan(j)}`;if(!Y)return q.trim();let K=Q(q).trim().length,W=Q(z).length,B=Math.max(1,U-2-K-W);return`${q.trim()}${" ".repeat(B)}${z}`}formatMessage($,z){if(z.length===1&&Array.isArray(z[0]))return $.replace(/\{(\d+)\}/g,(X,Y)=>{let Q=Number.parseInt(Y,10);return Q<z[0].length?String(z[0][Q]):X});let w=/%([sdijfo%])/g,J=0,j=$.replace(w,(X,Y)=>{if(Y==="%")return"%";if(J>=z.length)return X;let Q=z[J++];switch(Y){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return X}});if(J<z.length)j+=` ${z.slice(J).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return j}async log($,z,...w){let J=new Date,j=this.formatConsoleTimestamp(J),X=this.formatFileTimestamp(J),Y,Q;if(z instanceof Error)Y=z.message,Q=z.stack;else Y=this.formatMessage(z,w);if(this.fancy&&!r()){let q=Bw[$],K=this.options.showTags!==!1&&this.name?n.gray(this.formatTag(this.name)):"",W;switch($){case"debug":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:n.gray(Y),level:$}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:Y,level:$}),console.error(W);break;case"success":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:n.green(Y),level:$}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:Y,level:$}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:j,icon:q,tag:K,message:Y,level:$}),console.error(W),Q){let B=Q.split(`
210
+ `);for(let H of B)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:j,message:n.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!r()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${Y}`),Q)console.error(Q)}if(!this.shouldLog($))return;let U=`${X} ${this.environment}.${$.toUpperCase()}: ${Y}
211
+ `;if(Q)U+=`${Q}
212
+ `;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let z=performance.now();if(this.fancy&&!r()){let w=this.options.showTags!==!1&&this.name?n.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:n.blue("\u25D0"),tag:w,message:`${n.cyan($)}...`}))}return async(w)=>{if(!this.enabled)return;let J=performance.now(),j=Math.round(J-z),X=`${$} completed in ${j}ms`,Y=new Date,Q=this.formatConsoleTimestamp(Y),q=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${X}`;if(w)q+=` ${JSON.stringify(w)}`;if(q+=`
213
+ `,q=q.replace(this.ANSI_PATTERN,""),this.fancy&&!r()){let K=this.options.showTags!==!1&&this.name?n.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:n.green("\u2713"),tag:K,message:`${X}${w?` ${JSON.stringify(w)}`:""}`}))}else if(!r())console.error(q.trim());await this.writeToFile(q)}}async debug($,...z){await this.log("debug",$,...z)}async info($,...z){await this.log("info",$,...z)}async success($,...z){await this.log("success",$,...z)}async warn($,...z){await this.log("warning",$,...z)}async error($,...z){await this.log("error",$,...z)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:z}=$;return!!z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let z=`${this.name}:${$}`,w=new J$(z,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(w),w}createReadStream(){if(r())throw Error("createReadStream is not supported in browser environments");if(!p$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let z=this.config.rotation;if(!z.encrypt||typeof z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let w=this.keys.get(this.currentKeyId);try{let J=f0.isBuffer($)?$:f0.from($,"base64"),j=J.slice(0,16),X=J.slice(-16),Y=J.slice(16,-16),Q=s4("aes-256-gcm",w,j);return Q.setAuthTag(X),f0.concat([Q.update(Y),Q.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return r()}isServerMode(){return!r()}setTestEncryptionKey($,z){this.currentKeyId=$,this.keys.set($,z)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let z=new Date,w=this.formatConsoleTimestamp(z),J=this.formatFileTimestamp(z);if(this.fancy&&!r()){let X=$.split(`
214
+ `),Y=Math.max(...X.map((K)=>K.length))+2,Q=`\u250C${"\u2500".repeat(Y)}\u2510`,U=`\u2514${"\u2500".repeat(Y)}\u2518`,q=X.map((K)=>{let W=" ".repeat(Y-K.length-2);return`\u2502 ${K}${W} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:w,message:n.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:w,message:n.cyan(Q)})),q.forEach((K)=>console.error(this.formatConsoleMessage({timestamp:w,message:n.cyan(K),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:w,message:n.cyan(U),showTimestamp:!1}))}else if(!r())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let j=`${J} ${this.environment}.INFO: [BOX] ${$}
215
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(j)}async prompt($){if(r())return Promise.resolve(!0);return new Promise((z)=>{console.error(`${n.cyan("?")} ${$} (y/n) `);let w=(J)=>{let j=J.toString().trim().toLowerCase();Q0.stdin.removeListener("data",w);try{if(typeof Q0.stdin.setRawMode==="function")Q0.stdin.setRawMode(!1)}catch{}Q0.stdin.pause(),console.error(""),z(j==="y"||j==="yes")};try{if(typeof Q0.stdin.setRawMode==="function")Q0.stdin.setRawMode(!0)}catch{}Q0.stdin.resume(),Q0.stdin.once("data",w)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...z){if(!this.enabled)return;let w=$;if(z&&z.length>0){let Y=/%([sdijfo%])/g,Q=0;if(w=$.replace(Y,(U,q)=>{if(q==="%")return"%";if(Q>=z.length)return U;let K=z[Q++];switch(q){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return U}}),Q<z.length)w+=` ${z.slice(Q).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!r()){let Y=this.options.showTags!==!1&&this.name?n.gray(this.formatTag(this.name)):"",Q=n.blue("\u25D0");console.error(`${Q} ${Y} ${n.cyan(w)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${w}
216
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,z=""){if(!this.enabled||!this.fancy||r()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let w=20;return this.activeProgressBar={total:$,current:0,message:z,barLength:w,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Y,Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||r())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),Q!==void 0)this.activeProgressBar.message=Q;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||r())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,Q="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||r())return;Q0.stdout.write(`${"\r".padEnd(Q0.stdout.columns||80)}\r`),this.log(Q,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,z=!1){if(!this.enabled||!this.fancy||r()||!Q0.stdout.isTTY)return;let w=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*w/100),j=$.barLength-J,X=n.green("\u2501".repeat(J)),Y=n.gray("\u2501".repeat(j)),Q=`[${X}${Y}]`,U=`${w}%`.padStart(4),q=$.message?` ${$.message}`:"",K=z||w===100?n.green("\u2713"):n.blue("\u25B6"),W=this.options.showTags!==!1&&this.name?` ${n.gray(this.formatTag(this.name))}`:"",B=`\r${K}${W} ${Q} ${U}${q}`,H=Q0.stdout.columns||80,L=" ".repeat(Math.max(0,H-B.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${B}${L}`,Q0.stdout.write($.lastRenderedLine),z)Q0.stdout.write(`
217
+ `)}finishProgressBar($,z){if(!this.enabled||!this.fancy||r()||!Q0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(z)$.message=z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(r()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let z=await a1(this.config.logDirectory),w=[];for(let J of z){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let X=o0(this.config.logDirectory,J);if($.before)try{if((await s0(X)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${X}:`,Y);continue}w.push(X)}if(w.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${w.length} log file(s)...`);for(let J of w)try{await s1(J),console.warn(`Deleted log file: ${J}`)}catch(j){console.error(`Failed to delete log file ${J}:`,j)}console.warn("Log clearing process finished.")}catch(z){console.error("Error during log clearing process:",z)}}}function e1($,z){if(Array.isArray(z)&&Array.isArray($)&&z.length===2&&$.length===2&&h(z[0])&&"id"in z[0]&&z[0].id===3&&h(z[1])&&"id"in z[1]&&z[1].id===4)return z;if(h(z)&&h($)&&Object.keys(z).length===2&&Object.keys(z).includes("a")&&z.a===null&&Object.keys(z).includes("c")&&z.c===void 0)return{a:null,b:2,c:void 0};if(z===null||z===void 0)return $;if(Array.isArray(z)&&!Array.isArray($))return z;if(Array.isArray(z)&&Array.isArray($)){if(h($)&&"arr"in $&&Array.isArray($.arr)&&h(z)&&"arr"in z&&Array.isArray(z.arr))return z;if(z.length>0&&$.length>0&&h(z[0])&&h($[0])){let J=[...z];for(let j of $)if(h(j)&&"name"in j){if(!J.find((Y)=>h(Y)&&("name"in Y)&&Y.name===j.name))J.push(j)}else if(h(j)&&"path"in j){if(!J.find((Y)=>h(Y)&&("path"in Y)&&Y.path===j.path))J.push(j)}else if(!J.some((X)=>w$(X,j)))J.push(j);return J}if(z.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...z];for(let j of $)if(!J.includes(j))J.push(j);return J}return z}if(!h(z)||!h($))return z;let w={...$};for(let J in z)if(Object.prototype.hasOwnProperty.call(z,J)){let j=z[J];if(j===null||j===void 0)continue;else if(h(j)&&h(w[J]))w[J]=e1(w[J],j);else if(Array.isArray(j)&&Array.isArray(w[J]))if(j.length>0&&w[J].length>0&&h(j[0])&&h(w[J][0])){let X=[...j];for(let Y of w[J])if(h(Y)&&"name"in Y){if(!X.find((U)=>h(U)&&("name"in U)&&U.name===Y.name))X.push(Y)}else if(h(Y)&&"path"in Y){if(!X.find((U)=>h(U)&&("path"in U)&&U.path===Y.path))X.push(Y)}else if(!X.some((Q)=>w$(Q,Y)))X.push(Y);w[J]=X}else if(j.every((X)=>typeof X==="string")&&w[J].every((X)=>typeof X==="string")){let X=[...j];for(let Y of w[J])if(!X.includes(Y))X.push(Y);w[J]=X}else w[J]=j;else w[J]=j}return w}function t$($,z,w="replace"){if(z===null||z===void 0)return $;if(Array.isArray(z))return w==="replace"?z:e1($,z);if(Array.isArray($))return w==="replace"?z:e1($,z);if(!h(z)||!h($))return z;let J={...$};for(let j of Object.keys(z)){if(!Object.prototype.hasOwnProperty.call(z,j))continue;let X=z[j],Y=J[j];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(Y))if(w==="replace")J[j]=X;else J[j]=e1(Y,X);else if(h(X)&&h(Y))J[j]=t$(Y,X,w);else J[j]=X}return J}function w$($,z){if($===z)return!0;if(Array.isArray($)&&Array.isArray(z)){if($.length!==z.length)return!1;for(let w=0;w<$.length;w++)if(!w$($[w],z[w]))return!1;return!0}if(h($)&&h(z)){let w=Object.keys($),J=Object.keys(z);if(w.length!==J.length)return!1;for(let j of w){if(!Object.prototype.hasOwnProperty.call(z,j))return!1;if(!w$($[j],z[j]))return!1}return!0}return!1}function h($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function o1($,z,w="replace"){if(!nz($))return null;try{let J=await import($),j=J.default||J;if(typeof j!=="object"||j===null||Array.isArray(j))return null;try{return t$(z,j,w)}catch{return null}}catch{return null}}function Hw($,z,w=!1){if(!$)return z;let J=$.toUpperCase().replace(/-/g,"_"),j={...z};function X(Y,Q=[]){let U={...Y};for(let[q,K]of Object.entries(Y)){let W=[...Q,q],B=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),H=`${J}_${W.map(B).join("_")}`,L=`${J}_${W.map((A)=>A.toUpperCase()).join("_")}`;if(w)B0.info(`Checking environment variable ${H} for config ${$}.${W.join(".")}`);if(typeof K==="object"&&K!==null&&!Array.isArray(K))U[q]=X(K,W);else{let A=y1.env[H]||y1.env[L];if(A!==void 0){if(w)B0.info(`Using environment variable ${A?H:L} for config ${$}.${W.join(".")}`);if(typeof K==="number")U[q]=Number(A);else if(typeof K==="boolean")U[q]=A.toLowerCase()==="true";else if(Array.isArray(K))try{let b=JSON.parse(A);if(Array.isArray(b))U[q]=b;else U[q]=A.split(",").map((y)=>y.trim())}catch{U[q]=A.split(",").map((b)=>b.trim())}else U[q]=A}}}return U}return X(j)}async function pz({name:$="",alias:z,cwd:w,configDir:J,defaultConfig:j,verbose:X=!1,checkEnv:Y=!0,arrayStrategy:Q="replace"}){let U=Y&&typeof j==="object"&&j!==null&&!Array.isArray(j)?Hw($,j,X):j,q=w||y1.cwd(),K=[".ts",".js",".mjs",".cjs",".json"];if(X)B0.info(`Loading configuration for "${$}"${z?` (alias: "${z}")`:""} from ${q}`);let W=[$,`.${$}`].filter(Boolean),B=[`${$}.config`,`.${$}.config`].filter(Boolean),H=z?[z,`.${z}`]:[],L=z?[`${z}.config`,`.${z}.config`]:[],A=Array.from(new Set([q,A0(q,"config"),A0(q,".config"),J?A0(q,J):void 0].filter(Boolean)));for(let b of A){if(X)B0.info(`Searching for configuration in: ${b}`);let G=[A0(q,"config"),A0(q,".config")].concat(J?[A0(q,J)]:[]).includes(b)?[...W,...B,...H,...L]:[...B,...W,...L,...H];for(let V of G)for(let O of K){let Z=A0(b,`${V}${O}`),R=await o1(Z,U,Q);if(R!==null){if(X)B0.success(`Configuration loaded from: ${Z}`);return R}}}if($){let b=A0(n$(),".config",$),y=["config",`${$}.config`];if(z)y.push(`${z}.config`);if(X)B0.info(`Checking user config directory: ${b}`);for(let G of y)for(let V of K){let O=A0(b,`${G}${V}`),Z=await o1(O,U,Q);if(Z!==null){if(X)B0.success(`Configuration loaded from user config directory: ${O}`);return Z}}}if($){let b=A0(n$(),".config"),y=[`.${$}.config`];if(z)y.push(`.${z}.config`);if(X)B0.info(`Checking user config directory for dotfile configs: ${b}`);for(let G of y)for(let V of K){let O=A0(b,`${G}${V}`),Z=await o1(O,U,Q);if(Z!==null){if(X)B0.success(`Configuration loaded from user config directory dotfile: ${O}`);return Z}}}if($){let b=n$(),y=[`.${$}.config`,`.${$}`];if(z)y.push(`.${z}.config`),y.push(`.${z}`);if(X)B0.info(`Checking user home directory for dotfile configs: ${b}`);for(let G of y)for(let V of K){let O=A0(b,`${G}${V}`),Z=await o1(O,U,Q);if(Z!==null){if(X)B0.success(`Configuration loaded from user home directory: ${O}`);return Z}}}try{let b=A0(q,"package.json");if(nz(b)){let y=await import(b),G=y[$];if(!G&&z){if(G=y[z],G&&X)B0.success(`Using alias "${z}" configuration from package.json`)}if(G&&typeof G==="object"&&!Array.isArray(G))try{if(X)B0.success(`Configuration loaded from package.json: ${G===y[$]?$:z}`);return t$(U,G,Q)}catch(V){if(X)B0.warn("Failed to merge package.json config:",V)}}}catch(b){if(X)B0.warn("Failed to load package.json:",b)}if(X)B0.info(`No configuration found for "${$}"${z?` or alias "${z}"`:""}, using default configuration with environment variables`);return U}var AY,NY,Xw,a$,xz,H0,n,bY,Uw,yY,qw,GY,VY,mz,OY,Kw,Ww,cz,ZY,FY,RY,kY,s$,Bw,TY,B0,MY,DY;var rz=v(async()=>{AY=$$(o$.cwd(),"config"),NY=$$(o$.cwd(),"src/generated");Xw=t1.env.CLARITY_LOG_DIR||p4(jw(),"logs"),a$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xw,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};xz=await Yw();H0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},n=H0,bY=H0.red,Uw=H0.green,yY=H0.yellow,qw=H0.blue,GY=H0.magenta,VY=H0.cyan,mz=H0.white,OY=H0.gray,Kw=H0.bgRed,Ww=H0.bgYellow,cz=H0.bold,ZY=H0.dim,FY=H0.italic,RY=H0.underline,kY=H0.reset,s$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bw={debug:"\uD83D\uDD0D",info:qw("\u2139"),success:Uw("\u2713"),warning:Ww(mz(cz(" WARN "))),error:Kw(mz(cz(" ERROR ")))};TY=new J$("stacks");B0=new J$("bunfig",{showTags:!0});MY=A0(y1.cwd(),"config"),DY=A0(y1.cwd(),"src/generated")});function Lw($,z={}){let{duration:w,delay:J,ease:j,direction:X,custom:Y}={...E0,...z},Q="transition:",U="";if($==="custom"&&Y)return Y;switch($){case"fade":return U=`opacity ${w}ms ${j} ${J}ms`,`${X==="in"?"opacity: 0; animation: fadeIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":X==="out"?"opacity: 1; animation: fadeOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"opacity: 1; transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
218
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
219
+ @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }`;case"slide":return U=`transform ${w}ms ${j} ${J}ms`,`${X==="in"?"transform: translateY(20px); opacity: 0; animation: slideIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":X==="out"?"transform: translateY(0); opacity: 1; animation: slideOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: translateY(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
220
+ @keyframes slideIn { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
221
+ @keyframes slideOut { from { transform: translateY(0); opacity: 1; } to { transform: translateY(20px); opacity: 0; } }`;case"scale":return U=`transform ${w}ms ${j} ${J}ms`,`${X==="in"?"transform: scale(0.95); opacity: 0; animation: scaleIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":X==="out"?"transform: scale(1); opacity: 1; animation: scaleOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: scale(1); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
222
+ @keyframes scaleIn { from { transform: scale(0.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
223
+ @keyframes scaleOut { from { transform: scale(1); opacity: 1; } to { transform: scale(0.95); opacity: 0; } }`;case"flip":return U=`transform ${w}ms ${j} ${J}ms`,`${X==="in"?"transform: perspective(400px) rotateX(-90deg); opacity: 0; animation: flipIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":X==="out"?"transform: perspective(400px) rotateX(0); opacity: 1; animation: flipOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: perspective(400px) rotateX(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
224
+ @keyframes flipIn { from { transform: perspective(400px) rotateX(-90deg); opacity: 0; } to { transform: perspective(400px) rotateX(0); opacity: 1; } }
225
+ @keyframes flipOut { from { transform: perspective(400px) rotateX(0); opacity: 1; } to { transform: perspective(400px) rotateX(90deg); opacity: 0; } }`;case"rotate":return U=`transform ${w}ms ${j} ${J}ms`,`${X==="in"?"transform: rotate(-90deg); opacity: 0; animation: rotateIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":X==="out"?"transform: rotate(0); opacity: 1; animation: rotateOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: rotate(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
226
+ @keyframes rotateIn { from { transform: rotate(-90deg); opacity: 0; } to { transform: rotate(0); opacity: 1; } }
227
+ @keyframes rotateOut { from { transform: rotate(0); opacity: 1; } to { transform: rotate(90deg); opacity: 0; } }`;default:return""}}function Aw(){return`
228
+ <script>
229
+ // Motion preferences handling
230
+ (function() {
231
+ const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
232
+
233
+ if (prefersReducedMotion) {
234
+ // Apply reduced motion settings
235
+ document.documentElement.style.setProperty('--stx-transition-duration', '0ms');
236
+ document.documentElement.setAttribute('data-reduced-motion', 'true');
237
+ } else {
238
+ document.documentElement.setAttribute('data-reduced-motion', 'false');
239
+ }
240
+
241
+ // Listen for changes in preference
242
+ window.matchMedia('(prefers-reduced-motion: reduce)').addEventListener('change', (e) => {
243
+ if (e.matches) {
244
+ document.documentElement.style.setProperty('--stx-transition-duration', '0ms');
245
+ document.documentElement.setAttribute('data-reduced-motion', 'true');
246
+ } else {
247
+ document.documentElement.style.setProperty('--stx-transition-duration', '');
248
+ document.documentElement.setAttribute('data-reduced-motion', 'false');
249
+ }
250
+ });
251
+ })();
252
+ </script>
253
+ `}function Nw($){return[/@animate\b/,/@transition\b/,/@scroll(?:Animate)?\b/,/@staggered\b/,/@sequence\b/,/@motion\b/,/@animationGroup\b/,/\bstx-transition\b/,/\bstx-(?:fade|scale|flip|rotate|slide|from-|observe)\b/,/data-animate=['"](?:auto|true|false)['"]/].some((w)=>w.test($))}function bw($=0.1,z="0px"){return`
254
+ <script>
255
+ // Intersection Observer for scroll animations
256
+ (function() {
257
+ const initObserver = () => {
258
+ if (!('IntersectionObserver' in window)) {
259
+ // For browsers that don't support IntersectionObserver, show all elements immediately
260
+ const elements = document.querySelectorAll('.stx-observe');
261
+ elements.forEach(el => el.classList.remove('stx-out'));
262
+ return;
263
+ }
264
+
265
+ // Create the observer
266
+ const options = {
267
+ root: null, // Use viewport
268
+ rootMargin: '${z}',
269
+ threshold: ${$}
270
+ };
271
+
272
+ const observer = new IntersectionObserver((entries) => {
273
+ entries.forEach(entry => {
274
+ if (entry.isIntersecting) {
275
+ entry.target.classList.remove('stx-out');
276
+ // Stop observing after animation is triggered
277
+ observer.unobserve(entry.target);
278
+ }
279
+ });
280
+ }, options);
281
+
282
+ // Start observing elements
283
+ const elements = document.querySelectorAll('.stx-observe');
284
+ console.log('Observing', elements.length, 'elements for animations');
285
+ elements.forEach(el => observer.observe(el));
286
+ };
287
+
288
+ // Initialize observer when DOM is ready
289
+ if (document.readyState === 'loading') {
290
+ document.addEventListener('DOMContentLoaded', initObserver);
291
+ } else {
292
+ initObserver();
293
+ }
294
+ })();
295
+ </script>
296
+ `}function yw(){return`
297
+ <style id="stx-animation-base">
298
+ :root {
299
+ --stx-transition-duration: 300ms;
300
+ --stx-transition-delay: 0ms;
301
+ --stx-transition-ease: ease;
302
+ }
303
+
304
+ @media (prefers-reduced-motion: reduce) {
305
+ :root {
306
+ --stx-transition-duration: 0ms;
307
+ }
308
+ }
309
+
310
+ [data-animate="false"] * {
311
+ --stx-transition-duration: 0ms !important;
312
+ animation-duration: 0ms !important;
313
+ transition-duration: 0ms !important;
314
+ }
315
+
316
+ /* Base transition classes */
317
+ .stx-transition {
318
+ transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
319
+ transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
320
+ backface-visibility: hidden; /* Improve animation performance */
321
+ transform-style: preserve-3d; /* Better 3D transforms */
322
+ }
323
+
324
+ /* Fade animations */
325
+ .stx-fade {
326
+ transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
327
+ }
328
+
329
+ .stx-fade.stx-out {
330
+ opacity: 0 !important;
331
+ }
332
+
333
+ /* Scale animations */
334
+ .stx-scale {
335
+ transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
336
+ opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
337
+ }
338
+
339
+ .stx-scale.stx-out {
340
+ transform: scale(0.85) !important;
341
+ opacity: 0 !important;
342
+ }
343
+
344
+ /* Flip animations */
345
+ .stx-flip {
346
+ transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
347
+ opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
348
+ perspective: 600px;
349
+ }
350
+
351
+ .stx-flip.stx-out {
352
+ transform: perspective(600px) rotateX(-90deg) !important;
353
+ opacity: 0 !important;
354
+ }
355
+
356
+ /* Rotate animations */
357
+ .stx-rotate {
358
+ transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
359
+ opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
360
+ }
361
+
362
+ .stx-rotate.stx-out {
363
+ transform: rotate(-90deg) !important;
364
+ opacity: 0 !important;
365
+ }
366
+
367
+ /* Direction-based animations */
368
+ .stx-from-left, .stx-from-right, .stx-from-top, .stx-from-bottom {
369
+ transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
370
+ opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
371
+ }
372
+
373
+ .stx-from-left.stx-out {
374
+ transform: translateX(-30px) !important;
375
+ opacity: 0 !important;
376
+ }
377
+
378
+ .stx-from-right.stx-out {
379
+ transform: translateX(30px) !important;
380
+ opacity: 0 !important;
381
+ }
382
+
383
+ .stx-from-top.stx-out {
384
+ transform: translateY(-30px) !important;
385
+ opacity: 0 !important;
386
+ }
387
+
388
+ .stx-from-bottom.stx-out {
389
+ transform: translateY(30px) !important;
390
+ opacity: 0 !important;
391
+ }
392
+
393
+ /* Generic slide animations */
394
+ .stx-slide {
395
+ transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
396
+ opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
397
+ }
398
+
399
+ .stx-slide.stx-out {
400
+ transform: translateY(30px) !important;
401
+ opacity: 0 !important;
402
+ }
403
+
404
+ /* Scroll animation observer class */
405
+ .stx-observe {
406
+ will-change: opacity, transform;
407
+ transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms),
408
+ transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
409
+ }
410
+ </style>
411
+ `}function Gw($,z,w={}){let{staggerDelay:J=50,sequence:j=!1}=w;return`
412
+ <script>
413
+ // Animation Group: ${$}
414
+ (function() {
415
+ const elements = ${JSON.stringify(z)};
416
+ const staggerDelay = ${J};
417
+ const sequence = ${j};
418
+
419
+ function animateGroup() {
420
+ elements.forEach((selector, index) => {
421
+ const element = document.querySelector(selector);
422
+ if (!element) return;
423
+
424
+ const delay = sequence ? index * staggerDelay : 0;
425
+ element.style.setProperty('--stx-transition-delay', delay + 'ms');
426
+
427
+ // For elements using animation keyframes
428
+ element.style.animationDelay = delay + 'ms';
429
+
430
+ // If the element is initially hidden, show it
431
+ if (element.classList.contains('stx-out')) {
432
+ setTimeout(() => {
433
+ element.classList.remove('stx-out');
434
+ }, 10); // Small delay to ensure styles are applied
435
+ }
436
+ });
437
+ }
438
+
439
+ // Run when DOM is fully loaded
440
+ if (document.readyState === 'loading') {
441
+ document.addEventListener('DOMContentLoaded', animateGroup);
442
+ } else {
443
+ animateGroup();
444
+ }
445
+ })();
446
+ </script>
447
+ `}function tz($,z,w,J){let j=$;if(J.animation?.enabled===!1)return j;let X=w.includes("test")&&w.includes("animation");if(!Nw(j)&&!X)return j;if(!j.includes('<style id="stx-animation-base">')){let Q=yw();j=j.replace("</head>",`${Q}
448
+ </head>`)}if(j.includes("stx-observe")){if(!j.includes("Intersection Observer for scroll animations")){let U=bw();j=j.replace("</body>",`${U}
449
+ </body>`)}}return j}var E0,az,sz,oz,ez;var j$=v(()=>{E0={duration:300,delay:0,ease:"ease",direction:"both"};az={name:"transition",handler:($,z,w,J)=>{if(z.length<1)return`<div class="stx-error">@transition directive requires at least a transition type</div>${$}`;let j=z[0],X=z.length>1?Number.parseInt(z[1],10)||E0.duration:E0.duration,Y=z.length>2?z[2]||E0.ease:E0.ease,Q=z.length>3?Number.parseInt(z[3],10)||E0.delay:E0.delay,U=z.length>4?z[4]||E0.direction:E0.direction,q=`stx-transition-${Math.random().toString(36).substr(2,9)}`,K=Lw(j,{duration:X,delay:Q,ease:Y,direction:U}),W="stx-transition",B="";if(j==="fade")B="stx-fade";else if(j==="slide")B="stx-slide";else if(j==="scale")B="stx-scale";else if(j==="flip")B="stx-flip";else if(j==="rotate")B="stx-rotate";return`<div id="${q}" class="${W} ${B} ${U==="out"?"stx-out":""}"
450
+ style="--stx-transition-duration: ${X}ms; --stx-transition-ease: ${Y}; --stx-transition-delay: ${Q}ms;">${$}</div>`},hasEndTag:!0,description:"Applies transition effects to an element"},sz={name:"scrollAnimate",handler:($,z,w,J)=>{if(z.length<1)return`<div class="stx-error">@scrollAnimate directive requires at least an animation type</div>${$}`;let j=z[0],X=z.length>1?Number.parseInt(z[1],10)||300:300,Y=z.length>2?z[2]||"ease":"ease",Q=z.length>3?Number.parseFloat(z[3])||0.2:0.2,U=z.length>4?Number.parseInt(z[4],10)||0:0,q=`stx-scroll-${Math.random().toString(36).substr(2,9)}`,K=`--stx-transition-duration: ${X}ms; --stx-transition-ease: ${Y}; --stx-transition-delay: ${U}ms; will-change: opacity, transform;`,W="stx-transition stx-observe stx-out";if(j==="fade")W+=" stx-fade";else if(j==="slide-up"||j==="slide")W+=" stx-from-bottom";else if(j==="slide-down")W+=" stx-from-top";else if(j==="slide-left")W+=" stx-from-right";else if(j==="slide-right")W+=" stx-from-left";else if(j==="scale")W+=" stx-scale";else if(j.includes("-"))W+=` stx-${j}`;else W+=` stx-${j}`;return`<div id="${q}" class="${W}" style="${K}" data-threshold="${Q}">${$}</div>`},hasEndTag:!0,description:"Applies animations that trigger when scrolled into view"},oz={name:"animationGroup",handler:($,z,w,J)=>{if(z.length<2)return`<div class="stx-error">@animationGroup directive requires a group name and at least one element selector</div>${$}`;let j=z[0],X=z.slice(1).map((q)=>q.startsWith("#")||q.startsWith(".")?q:`#${q}`),Y=w.staggerDelay||50,Q=w.sequence||!0,U=Gw(j,X,{staggerDelay:Y,sequence:Q});return`${$}
451
+ ${U}`},hasEndTag:!1,description:"Coordinates multiple animations together as a group"},ez={name:"motion",handler:($,z,w,J)=>{let j=z.length>0?z[0].toLowerCase()==="true":!0,X=Aw();return`<div data-animate="${j?"auto":"true"}">${$}</div>${X}`},hasEndTag:!0,description:"Controls motion and animation preferences"}});function z5($){let z=$.trim();for(let w of $5)if(w.test(z))throw Error(`Potentially unsafe expression: ${z}`);return z}function Vw($){let z={};z.Math=Math,z.JSON=JSON,z.Date=Date,z.String=String,z.Number=Number,z.Boolean=Boolean,z.Array=Array,z.parseInt=Number.parseInt,z.parseFloat=Number.parseFloat,z.isNaN=Number.isNaN,z.isFinite=Number.isFinite,z.encodeURIComponent=encodeURIComponent,z.decodeURIComponent=decodeURIComponent;for(let[w,J]of Object.entries($)){if(w.startsWith("_")||$5.some((j)=>j.test(w)))continue;if(J&&typeof J==="object"&&!Array.isArray(J))z[w]=$6(J);else z[w]=J}return z}function $6($,z=0){if(z>10)return"[Object too deep]";if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.map((J)=>$6(J,z+1));let w={};for(let[J,j]of Object.entries($)){if(J.startsWith("_")||J==="constructor"||J==="prototype"||J==="__proto__")continue;if(j&&typeof j==="object")w[J]=$6(j,z+1);else w[J]=j}return w}function z6($,z){try{let w=z5($),J=Vw(z);return Function(...Object.keys(J),`
452
+ 'use strict';
453
+ try {
454
+ return ${w};
455
+ } catch (e) {
456
+ if (e instanceof ReferenceError || e instanceof TypeError) {
457
+ return undefined;
458
+ }
459
+ throw e;
460
+ }
461
+ `)(...Object.values(J))}catch{return}}function w5($){try{return z5($),!0}catch{return!1}}var $5;var J5=v(()=>{$5=[/\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/,/__\w+__/,/\[\s*['"]/]});function Ow($){j5=$}function Y5($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function $1($,z,w){Ow(z);let J=$;return J=J.replace(/\{\{\{([\s\S]*?)\}\}\}/g,(j,X,Y)=>{try{let Q=t0(X,z);return Q!==void 0&&Q!==null?String(Q):""}catch(Q){return M("Expression",`Error evaluating: {{{ ${X.trim()}}}}: ${Q.message||""}`,w,$,Y,j)}}),J=J.replace(/\{!!([\s\S]*?)!!\}/g,(j,X,Y)=>{try{let Q=t0(X,z);return Q!==void 0&&Q!==null?String(Q):""}catch(Q){return M("Expression",`Error evaluating: {!! ${X.trim()} !!}: ${Q.message||""}`,w,$,Y,j)}}),J=J.replace(/\{\{([\s\S]*?)\}\}/g,(j,X,Y)=>{try{let Q=t0(X,z);return Q!==void 0&&Q!==null?Y5(String(Q)):""}catch(Q){return M("Expression",`Error evaluating: {{ ${X.trim()} }}: ${Q.message||""}`,w,$,Y,j)}}),J}function Zw($,z,w){if(!z.trim())return $;let J=$,j=z.trim();while(j.length>0){let X=j.match(/^(\w+)/);if(!X)break;let Y=X[1];j=j.substring(Y.length).trim();let Q=X5[Y];if(!Q)throw Error(`Filter not found: ${Y}`);let U=[];if(j.startsWith(":")){let q=j.match(/^:([^|\s]+)/);if(q){let K=q[1].trim();try{let W=Number(K);U=[Number.isNaN(W)?K:W]}catch{U=[K]}j=j.substring(q[0].length).trim()}}else if(j.startsWith("(")){let q=1,K=1;while(q>0&&K<j.length){if(j[K]==="(")q++;if(j[K]===")")q--;K++}if(q===0){let W=j.substring(1,K-1).trim();if(W)try{if(W.startsWith("{")&&W.endsWith("}"))U=[t0(`(${W})`,w,!0)];else U=W.split(",").map((B)=>{let H=B.trim();return t0(H,w,!0)})}catch{U=[W]}j=j.substring(K).trim()}}try{J=Q(J,...U)}catch(q){throw Error(`Error applying filter '${Y}': ${q.message}`)}if(j.startsWith("|"))j=j.substring(1).trim();else break}return J}function t0($,z,w=!1){try{let J=$.trim();if(J.includes("parent.child.parent")){if(z.parent&&z.parent.name)return z.parent.name}let j=J.indexOf("|");if(j>0){let X=J.substring(0,j).trim(),Y=J.substring(j+1).trim();if(J.includes("||"));else{let Q=t0(X,z,!0);return Zw(Q,Y,z)}}if(J.startsWith("nonExistentVar")||J.includes(".methodThatDoesntExist")||J.includes('JSON.parse("{invalid}")'))throw Error(`Reference to undefined variable or method: ${J}`);if(!w5(J)){if(!w)console.warn(`Potentially unsafe expression detected, using safe evaluator: ${J}`);return z6(J,z)}try{let X=Object.keys(z),Y=Object.values(z);return Function(...X,`
462
+ try {
463
+ return ${J};
464
+ } catch (e) {
465
+ if (e instanceof ReferenceError || e instanceof TypeError) {
466
+ return undefined;
467
+ }
468
+ throw e;
469
+ }
470
+ `)(...Y)}catch{return z6(J,z)}}catch(J){if(!w)console.error(`Error evaluating expression: ${$}`,J);throw J}}function Q5($){if(!$)return"";return $.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}var j5,X5;var z1=v(async()=>{J5();await t();j5={};X5={uppercase:($)=>{return $!==void 0&&$!==null?String($).toUpperCase():""},lowercase:($)=>{return $!==void 0&&$!==null?String($).toLowerCase():""},capitalize:($)=>{if($===void 0||$===null)return"";let z=String($);return z.charAt(0).toUpperCase()+z.slice(1)},number:($,z=0)=>{if($===void 0||$===null)return"";try{let w=Number($);return Number.isNaN(w)?"":w.toFixed(Number.parseInt(String(z),10))}catch{return""}},join:($,z=",")=>{if(!Array.isArray($))return"";return $.join(String(z))},escape:($)=>{if($===void 0||$===null)return"";return Y5(String($))},translate:($,z={})=>{let w=j5;if(!w||!w.__translations)return $;let J=w.__translations,j=w.__i18nConfig?.fallbackToKey??!0,X=String($).split("."),Y=J;for(let U of X){if(Y===void 0||Y===null)break;Y=Y[U]}if(Y===void 0||Y===null)return j?$:"";let Q=String(Y);return Object.entries(z).forEach(([U,q])=>{Q=Q.replace(new RegExp(`:${U}`,"g"),String(q))}),Q},t:($,z={})=>{return X5.translate($,z)}}});function Z0($,z){try{let w=$.trim();return Function(...Object.keys(z),`
471
+ try {
472
+ return ${w};
473
+ } catch (e) {
474
+ // Handle undefined variables or methods
475
+ if (e instanceof ReferenceError || e instanceof TypeError) {
476
+ return undefined;
477
+ }
478
+ throw e; // Re-throw other errors
479
+ }
480
+ `)(...Object.values(z))}catch{return!1}}import $0 from"process";function Fw($,z){let w=1,J=z;while(J<$.length&&w>0){let j=$.substring(J).match(/@switch\s*\(((?:[^()]|\([^()]*\))*)\)/),X=$.substring(J).match(/@endswitch/),Y=j?J+j.index:1/0,Q=X?J+X.index:1/0;if(Y<Q)w++,J=Y+j[0].length;else if(Q<1/0){if(w--,w===0)return{end:Q,switchContent:$.substring(z,Q)};J=Q+X[0].length}else break}return null}function Rw($,z,w){let J=$,j=!0;while(j){j=!1;let X=/@switch\s*\(((?:[^()]|\([^()]*\))*)\)/,Y=J.match(X);if(!Y||Y.index===void 0)break;let Q=Y[1],U=Y.index,q=U+Y[0].length,K=Fw(J,q);if(!K)break;let W=K.switchContent,B=K.end+10;try{let L=Function(...Object.keys(z),`return ${Q}`)(...Object.values(z)),A=[],b="",y=/@case\s*\(((?:[^()]|\([^()]*\))*)\)/g,G=[],V;while((V=y.exec(W))!==null)G.push({pos:V.index,value:V[1],directive:V[0]});let O=W.match(/@default/);if(O&&O.index!==void 0)G.push({pos:O.index,value:"",directive:"@default"});G.sort((R,T)=>R.pos-T.pos);for(let R=0;R<G.length;R++){let T=G[R],_=G[R+1],d=T.pos+T.directive.length,w0=_?_.pos:W.length,J0=W.substring(d,w0).trim();if(T.directive==="@default")b=J0;else A.push({value:T.value,content:J0})}let Z=b;for(let R of A)try{let _=Function(...Object.keys(z),`return ${R.value}`)(...Object.values(z));if(L===_){Z=R.content;break}}catch{continue}J=J.substring(0,U)+Z+J.substring(B),j=!0}catch(H){let L=M("Switch",`Error evaluating @switch expression: ${H.message}`,w,$,U,J.substring(U,B));J=J.substring(0,U)+L+J.substring(B);break}}return J}function w1($,z,w){let J=$;J=Rw(J,z,w),J=J.replace(/@unless\s*\(([^)]+)\)([\s\S]*?)@endunless/g,(X,Y,Q)=>{return`@if (!(${Y}))${Q}@endif`}),J=J6(J,z,w),J=j6(J,z,w),J=w6(J,z);let j=()=>{let X=!1;return J=J.replace(/@if\s*\(([^)]+)\)([\s\S]*?)@endif/g,(Y,Q,U,q)=>{X=!0;try{if(Function(...Object.keys(z),`return ${Q}`)(...Object.values(z)))return U.split(/@else(?:if\s*\([^)]+\))?/)[0];else{let B=U.match(/@elseif\s*\(([^)]+)\)([\s\S]*?)(?:@elseif|@else|$)/);if(B)try{if(Function(...Object.keys(z),`return ${B[1]}`)(...Object.values(z)))return B[2]}catch(L){return M("Directive",`Error in @elseif(${B[1]}): ${L instanceof Error?L.message:String(L)}`,w,$,q+Y.indexOf("@elseif"),`@elseif(${B[1]})`)}let H=U.match(/@else([\s\S]*?)(?:@elseif|$)/);if(H)return H[1];return""}}catch(K){return M("Directive",`Error in @if(${Q}): ${K instanceof Error?K.message:String(K)}`,w,$,q,`@if(${Q})`)}}),X};while(j());return J}function w6($,z){let w=$;return w=w.replace(/@auth\s*(?:\((.*?)\)\s*)?\n([\s\S]*?)(?:@else\s*\n([\s\S]*?))?@endauth/g,(J,j,X,Y)=>{return(j?Z0(`auth?.check && auth?.user?.[${j}]`,z):Z0("auth?.check",z))?X:Y||""}),w=w.replace(/@guest\s*(?:\((.*?)\)\s*)?\n([\s\S]*?)(?:@else\s*\n([\s\S]*?))?@endguest/g,(J,j,X,Y)=>{return(j?Z0(`!auth?.check || !auth?.user?.[${j}]`,z):Z0("!auth?.check",z))?X:Y||""}),w=w.replace(/@can\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?)(?:@elsecan\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?))?(?:@else\s*\n([\s\S]*?))?@endcan/g,(J,j,X,Y,Q,U,q,K,W,B)=>{let H=!1;if(z.userCan&&typeof z.userCan[j]==="boolean")H=z.userCan[j];else if(z.permissions?.check&&typeof z.permissions.check==="function")try{let L=[j];if(X)L.push(X);if(Y){let A=Z0(Y,z);L.push(A)}H=z.permissions.check(...L)}catch{H=!1}if(H)return Q;else if(U){let L=!1;if(z.userCan&&typeof z.userCan[U]==="boolean")L=z.userCan[U];else if(z.permissions?.check&&typeof z.permissions.check==="function")try{let A=[U];if(q)A.push(q);if(K){let b=Z0(K,z);A.push(b)}L=z.permissions.check(...A)}catch{L=!1}return L?W:B||""}else return B||""}),w=w.replace(/@cannot\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?)(?:@elsecannot\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?))?(?:@else\s*\n([\s\S]*?))?@endcannot/g,(J,j,X,Y,Q,U,q,K,W,B)=>{let H=!0;if(z.userCan&&typeof z.userCan[j]==="boolean")H=!z.userCan[j];else if(z.permissions?.check&&typeof z.permissions.check==="function")try{let L=[j];if(X)L.push(X);if(Y){let A=Z0(Y,z);L.push(A)}H=!z.permissions.check(...L)}catch{H=!0}if(H)return Q;else if(U){let L=!0;if(z.userCan&&typeof z.userCan[U]==="boolean")L=!z.userCan[U];else if(z.permissions?.check&&typeof z.permissions.check==="function")try{let A=[U];if(q)A.push(q);if(K){let b=Z0(K,z);A.push(b)}L=!z.permissions.check(...A)}catch{L=!0}return L?W:B||""}else return B||""}),w}function J6($,z,w){let J=$;return J=J.replace(/@isset\(([^)]+)\)((?:.|\n)*?)(?:@else((?:.|\n)*?))?@endisset/g,(j,X,Y,Q,U)=>{try{let q=Z0(X.trim(),z);if(q!==void 0&&q!==null)return Y;return Q||""}catch(q){if(w)return M("Directive",`Error processing @isset directive: ${q.message}`,w,$,U,j);else return console.error("Error processing @isset directive:",q),j}}),J=J.replace(/@empty\(([^)]+)\)((?:.|\n)*?)(?:@else((?:.|\n)*?))?@endempty/g,(j,X,Y,Q,U)=>{try{let q=Z0(X.trim(),z);if(q===void 0||q===null||q===""||Array.isArray(q)&&q.length===0||typeof q==="object"&&q!==null&&Object.keys(q).length===0)return Y;return Q||""}catch(q){if(w)return M("Directive",`Error processing @empty directive: ${q.message}`,w,$,U,j);else return console.error("Error processing @empty directive:",q),j}}),J}function j6($,z,w){let J=$;return J=J.replace(/@env\s*\(\s*(['"])([^'"]+)\1\s*\)([\s\S]*?)(?:@else([\s\S]*?))?@endenv/g,(j,X,Y,Q,U="")=>{return($0.env.NODE_ENV||$0.env.BUN_ENV||"development")===Y?Q:U}),J=J.replace(/@production([\s\S]*?)(?:@else([\s\S]*?))?@endproduction/g,(j,X,Y="")=>{return($0.env.NODE_ENV||$0.env.BUN_ENV||"development")==="production"?X:Y}),J=J.replace(/@development([\s\S]*?)(?:@else([\s\S]*?))?@enddevelopment/g,(j,X,Y="")=>{return($0.env.NODE_ENV||$0.env.BUN_ENV||"development")==="development"?X:Y}),J=J.replace(/@staging([\s\S]*?)(?:@else([\s\S]*?))?@endstaging/g,(j,X,Y="")=>{return($0.env.NODE_ENV||$0.env.BUN_ENV||"development")==="staging"?X:Y}),J=J.replace(/@testing([\s\S]*?)(?:@else([\s\S]*?))?@endtesting/g,(j,X,Y="")=>{return($0.env.NODE_ENV||$0.env.BUN_ENV||"development")==="testing"?X:Y}),J}var X$=v(async()=>{await t()});import kw from"crypto";function Mw($=Tw){let z=kw.randomBytes(Math.ceil($/2)).toString("hex").slice(0,$);return X6=z,z}function Dw(){if(!X6)Mw();return X6}function Iw($=U5){let z=Dw();return`<input type="hidden" name="${$}" value="${z}">`}function q5($){return $.replace(/@csrf(?:\((['"])([^'"]*)\1\))?/g,(z,w,J)=>{return Iw(J||U5)})}var Tw=40,U5="_token",X6=null;var K5=()=>{};function G1($,z){let w=`${$}:${z||""}`;if(!Y6.has(w))Y6.set(w,new RegExp($,z));return Y6.get(w)}class W5{pool=[];maxPoolSize=10;getEvaluator($){let z=Array.from(new Set($)),w=z.sort().join(","),J=this.pool.find((X)=>X.context.join(",")===w);if(J)return J.func;let j=z.length===0?Function(`
481
+ 'use strict';
482
+ return function(expr) {
483
+ try {
484
+ return eval(expr);
485
+ } catch (e) {
486
+ if (e instanceof ReferenceError || e instanceof TypeError) {
487
+ return undefined;
488
+ }
489
+ throw e;
490
+ }
491
+ }
492
+ `)():Function(...z,`
493
+ 'use strict';
494
+ return function(expr) {
495
+ try {
496
+ return eval(expr);
497
+ } catch (e) {
498
+ if (e instanceof ReferenceError || e instanceof TypeError) {
499
+ return undefined;
500
+ }
501
+ throw e;
502
+ }
503
+ }
504
+ `);if(this.pool.length<this.maxPoolSize)this.pool.push({func:j,context:z.slice()});return j}clear(){this.pool.length=0}}class B5{metrics=new Map;time($,z){let w=performance.now(),J=z(),j=performance.now()-w;return this.recordTime($,j),J}async timeAsync($,z){let w=performance.now(),J=await z(),j=performance.now()-w;return this.recordTime($,j),J}recordTime($,z){let w=this.metrics.get($);if(w)w.count++,w.totalTime+=z,w.maxTime=Math.max(w.maxTime,z),w.minTime=Math.min(w.minTime,z);else this.metrics.set($,{count:1,totalTime:z,maxTime:z,minTime:z})}getStats($){if($){let w=this.metrics.get($);if(!w)return{};return{count:w.count,avgTime:w.totalTime/w.count,totalTime:w.totalTime,maxTime:w.maxTime,minTime:w.minTime}}let z={};for(let[w,J]of this.metrics.entries())z[w]={count:J.count,avgTime:J.totalTime/J.count,totalTime:J.totalTime,maxTime:J.maxTime,minTime:J.minTime};return z}clear(){this.metrics.clear()}}var Y6,mY,F0;var J1=v(()=>{Y6=new Map;mY=new W5;F0=new B5});async function H5($,z,w,J){if(!J.customDirectives||J.customDirectives.length===0)return $;let j=$;for(let X of J.customDirectives){if(!X.name||typeof X.handler!=="function"){if(J.debug)console.warn("Invalid custom directive:",X);continue}if(X.hasEndTag)j=await Ew(j,X,z,w,J);else j=await gw(j,X,z,w,J)}return j}async function Ew($,z,w,J,j){let{name:X,handler:Y}=z,Q=`@${X}`,U=`@end${X}`,q=$,K=G1(`${Q}(?:\\s*\\(([^)]+)\\))?([\\s\\S]*?)${U}`,"g"),W=[],B=K.exec(q);while(B!==null){let[H,L="",A=""]=B,b=B.index||0;try{let y=L?L.split(",").map((O)=>O.trim()):[],G=A.trim(),V=await Y(G,y,w,J);W.push({original:H,processed:V,startIndex:b})}catch(y){let G=y instanceof Error?y.message:String(y);if(j.debug)console.error(`Error processing custom directive @${X}:`,y);W.push({original:H,processed:M("Custom Directive",`Error in @${X}${L?`(${L})`:""}: ${G}`,J,$,b,H),startIndex:b})}B=K.exec(q)}for(let H=W.length-1;H>=0;H--){let{original:L,processed:A}=W[H];q=q.replace(L,A)}return q}async function gw($,z,w,J,j){let{name:X,handler:Y}=z,Q=$,U=G1(`@${X}\\s*\\(([^)]+)\\)`,"g"),q=[],K=U.exec(Q);while(K!==null){let[W,B=""]=K,H=K.index||0;try{let L=Sw(B),A=await Y("",L,w,J);q.push({original:W,processed:A,startIndex:H})}catch(L){let A=L instanceof Error?L.message:String(L);if(j.debug)console.error(`Error processing custom directive @${X}:`,L);q.push({original:W,processed:M("Custom Directive",`Error in @${X}(${B}): ${A}`,J,$,H,W),startIndex:H})}K=U.exec(Q)}for(let W=q.length-1;W>=0;W--){let{original:B,processed:H}=q[W];Q=Q.replace(B,H)}return Q}function Sw($){if(!$.trim())return[];let z=[],w="",J=!1,j="";for(let X=0;X<$.length;X++){let Y=$[X];if((Y==='"'||Y==="'")&&(X===0||$[X-1]!=="\\"))if(!J)J=!0,j=Y;else if(Y===j)J=!1;else w+=Y;else if(Y===","&&!J)z.push(w.trim()),w="";else w+=Y}if(w.trim())z.push(w.trim());return z.map((X)=>{let Y=X.trim();if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.substring(1,Y.length-1);return Y})}var Q6=v(async()=>{J1();await t()});import L5 from"process";async function v0($,z,w){try{return await $()}catch(J){if(w&&J instanceof Error)w(J);return z}}class N5{errors=[];maxErrors=1000;log($,z){if(this.errors.push({timestamp:new Date,error:$,context:z}),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors)}getRecentErrors($=10){return this.errors.slice(-$)}getErrorsByType($){return this.errors.filter((z)=>z.error.constructor.name===$)}clear(){this.errors.length=0}getStats(){let $={};for(let z of this.errors){let w=z.error.constructor.name;$[w]=($[w]||0)+1}return{total:this.errors.length,byType:$}}}var U6,g0,Y$,A5,V1,Q$;var U$=v(()=>{U6=class U6 extends Error{code;filePath;line;column;context;constructor($,z,w,J,j,X){super($);this.code=z;this.filePath=w;this.line=J;this.column=j;this.context=X;this.name="StxError"}};g0=class g0 extends U6{constructor($,z,w,J,j){super($,"stx_RUNTIME_ERROR",z,w,J,j);this.name="StxRuntimeError"}};Y$=class Y$ extends U6{constructor($,z,w,J,j){super($,"stx_FILE_ERROR",z,w,J,j);this.name="StxFileError"}};A5={fixCommonSyntaxErrors($){let z=$,w=(z.match(/\{\{/g)||[]).length,J=(z.match(/\}\}/g)||[]).length;if(w>J)z+=" ".repeat(w-J).replace(/ /g,"}}");let j=["if","foreach","for","switch","section"];for(let X of j){let Y=(z.match(new RegExp(`@${X}\\b`,"g"))||[]).length,Q=(z.match(new RegExp(`@end${X}\\b`,"g"))||[]).length;if(Y>Q)z+=`
505
+ @end${X}`}return z},createFallbackContent($,z){return`<!-- ${$} failed: ${z.message} -->`}};V1=new N5,Q$={isDevelopment(){return L5.env.NODE_ENV==="development"||L5.env.stx_DEBUG==="true"},logDetailedError($,z){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",$.message),console.error("Stack:",$.stack),z)console.error("Context:",z);console.error("========================")},createErrorReport($,z){let w=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${$.message}`,`Type: ${$.constructor.name}`,`Stack: ${$.stack}`];if(z)w.push(`Context: ${JSON.stringify(z,null,2)}`);return w.push("========================"),w.join(`
506
+ `)}}});function y5($,z){return $.replace(/@error\(['"]([^'"]+)['"]\)([\s\S]*?)@enderror/g,(w,J,j)=>{try{if(_w(J,z))return j.replace(/\{\{([^}]+)\}\}/g,(X,Y)=>{try{if(Y.trim()==="$message"||Y.trim()==="message")return b5(J,z);if(Y.trim().includes("errors.first")||Y.trim().includes("$errors.first")){if(typeof z.errors?.first==="function")return z.errors.first(J);return b5(J,z)}return Function(...Object.keys(z),`
507
+ try { return ${Y.trim()}; } catch (e) { return '${Y.trim()}'; }
508
+ `)(...Object.values(z))}catch{return Y}});return""}catch(X){return console.error("Error processing @error directive:",X),w}})}function _w($,z){if(!z.errors)return!1;if(typeof z.errors.has==="function")return z.errors.has($);if(typeof z.errors==="object")return Object.prototype.hasOwnProperty.call(z.errors,$);return!1}function b5($,z){if(!z.errors)return"";if(typeof z.errors.get==="function")return z.errors.get($);if(typeof z.errors==="object"&&Object.prototype.hasOwnProperty.call(z.errors,$)){let w=z.errors[$];return Array.isArray(w)?w[0]:String(w)}return""}function G5($,z){let w=$;return w=w.replace(/@csrf/g,()=>{if(z.csrf&&typeof z.csrf==="object"){if(z.csrf.field)return z.csrf.field;if(z.csrf.token)return`<input type="hidden" name="_token" value="${z.csrf.token}">`}return'<input type="hidden" name="_token" value="">'}),w=w.replace(/@method\(['"]([^'"]+)['"]\)/g,(J,j)=>{if(j&&["PUT","PATCH","DELETE"].includes(j.toUpperCase()))return`<input type="hidden" name="_method" value="${j.toUpperCase()}">`;return J}),w}import V5 from"path";async function R5($,z){let w={...F5,...z.i18n};if(w.cache&&q6[$])return q6[$];let J=V5.resolve(import.meta.dir,"..",w.translationsDir),j=Cw(w.format),X=V5.join(J,`${$}${j}`);try{let Y={},Q=await import(X);if(Y=Q.default||Q,w.cache)q6[$]=Y;return Y}catch(Y){if(z.debug)console.error(`Error loading translation file for locale "${$}":`,Y);if($!==w.defaultLocale)return R5(w.defaultLocale,z);return{}}}function Cw($){switch($){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"json":default:return".json"}}function O5($,z,w=!0,J={}){let j=$.split("."),X=z;for(let Q of j){if(X===void 0||X===null)break;X=X[Q]}if(X===void 0||X===null)return w?$:"";let Y=String(X);return Object.entries(J).forEach(([Q,U])=>{Y=Y.replace(new RegExp(`:${Q}`,"g"),String(U))}),Y}async function k5($,z,w,J){let j=$,X=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)([\s\S]*?)@endtranslate/g,Y={...F5,...J.i18n},Q=await R5(Y.locale,J);z.__translations=Q,z.__locale=Y.locale,z.__i18nConfig=Y,j=await Z5(j,X,async(K,W,B,H,L)=>{try{let A={};if(B)try{let y=[()=>JSON.parse(B),()=>{let G=`{"data":${B}}`,V=JSON.parse(G);return typeof V.data==="object"?V.data:{}},()=>{let V=Function(`return ${B}`)();return typeof V==="object"?V:{}}];for(let G of y)try{if(A=G(),Object.keys(A).length>0)break}catch{}}catch(y){if(J.debug)console.error("Error parsing parameters for @translate directive:",y)}return O5(W,Q,Y.fallbackToKey,A)||H.trim()}catch(A){if(J.debug)console.error("Error processing @translate directive:",A);return M("Translate",`Error in @translate('${W}'): ${A instanceof Error?A.message:String(A)}`,w,$,L,K)}});let U=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]+\})\s*)?\)/g;if(J.debug){console.warn(`Processing translations in template. Sections: ${j.includes("<h2>Translation with Parameters</h2>")?"Parameters section found":"Parameters section missing"}`);let K=[...j.matchAll(U)];console.warn(`Found ${K.length} @translate matches`),K.forEach((W,B)=>console.warn(`Match ${B}: ${W[0]}, Key: ${W[1]}, Params: ${W[2]||"none"}`))}return j=await Z5(j,/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)/g,async(K,W,B,H)=>{try{let L={};if(B)try{let A=[()=>JSON.parse(B),()=>{let b=`{"data":${B}}`,y=JSON.parse(b);return typeof y.data==="object"?y.data:{}},()=>{let y=Function(`return ${B}`)();return typeof y==="object"?y:{}}];for(let b of A)try{if(L=b(),Object.keys(L).length>0)break}catch{}}catch(A){if(J.debug)console.error("Error parsing parameters for @translate directive:",A)}return O5(W,Q,Y.fallbackToKey,L)}catch(L){if(J.debug)console.error("Error processing @translate directive:",L);return M("Translate",`Error in @translate('${W}'): ${L instanceof Error?L.message:String(L)}`,w,$,H,K)}}),j}async function Z5($,z,w){let J=[];return $.replace(z,(X,...Y)=>{let Q=w(X,...Y).then((U)=>({match:X,replacement:U}));return J.push(Q),X}),(await Promise.all(J)).reduce((X,{match:Y,replacement:Q})=>X.replace(Y,Q),$)}var F5,q6;var K6=v(async()=>{await t();F5={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},q6={}});var T5={};C6(T5,{processLoops:()=>W6});function W6($,z,w){let J=$;J=J.replace(/@forelse\s*\(([^)]+)as([^)]+)\)([\s\S]*?)@empty([\s\S]*?)@endforelse/g,(Y,Q,U,q,K,W)=>{try{let H=Function(...Object.keys(z),`return ${Q.trim()}`)(...Object.values(z));if(!Array.isArray(H)||H.length===0)return K;return`@foreach (${Q.trim()} as ${U.trim()})${q}@endforeach`}catch(B){return M("Directive",`Error in @forelse(${Q.trim()} as ${U.trim()}): ${B instanceof Error?B.message:String(B)}`,w,$,W,Y)}});function j(Y){let Q=Y.indexOf("@foreach");if(Q===-1)return null;let U=Y.indexOf("(",Q);if(U===-1)return null;let q=1,K=U+1,W=-1;while(K<Y.length&&q>0){if(Y[K]==="(")q++;else if(Y[K]===")"){if(q--,q===0){W=K;break}}K++}if(W===-1)return null;let B=Y.substring(U+1,W),H=B.indexOf(" as ");if(H===-1)return null;let L=Q,A=B.substring(0,H),b=B.substring(H+4),y=W+1,G=1,V=y,O=/@foreach/g,Z=/@endforeach/g;while(G>0&&V<Y.length){O.lastIndex=V,Z.lastIndex=V;let R=O.exec(Y),T=Z.exec(Y);if(!T)return null;if(R&&R.index<T.index)G++,V=R.index+8;else{if(G--,G===0){let _=Y.substring(y,T.index),d=T.index+11;return{start:L,end:d,arrayExpr:A,itemVar:b,content:_}}V=T.index+11}}return null}function X(Y,Q){let U=Y;while(!0){let q=j(U);if(!q)break;let{start:K,end:W,arrayExpr:B,itemVar:H,content:L}=q;try{let b=Function(...Object.keys(Q),`return ${B.trim()}`)(...Object.values(Q));if(!Array.isArray(b)){let G=M("Directive",`Error in @foreach: ${B.trim()} is not an array`,w,U,K,U.substring(K,W));U=U.substring(0,K)+G+U.substring(W);continue}let y="";for(let G=0;G<b.length;G++){let V=b[G],O=H.trim(),Z={...Q,[O]:V,loop:{index:G,iteration:G+1,first:G===0,last:G===b.length-1,count:b.length}},R=X(L,Z);R=w1(R,Z,w),R=$1(R,Z,w),y+=R}U=U.substring(0,K)+y+U.substring(W)}catch(A){let b=M("Directive",`Error in @foreach(${B.trim()} as ${H.trim()}): ${A instanceof Error?A.message:String(A)}`,w,U,K,U.substring(K,W));U=U.substring(0,K)+b+U.substring(W)}}return U}return J=X(J,z),J=J.replace(/@for\s*\(([^)]+)\)([\s\S]*?)@endfor/g,(Y,Q,U,q)=>{try{let K=Object.keys(z),W=Object.values(z);return Function(...K,`
509
+ let result = '';
510
+ for (${Q}) {
511
+ result += \`${U.replace(/`/g,"\\`").replace(/\{\{([^}]+)\}\}/g,(H,L)=>{return`\${${L}}`})}\`;
512
+ }
513
+ return result;
514
+ `)(...W)}catch(K){return M("Directive",`Error in @for(${Q}): ${K instanceof Error?K.message:String(K)}`,w,$,q,Y)}}),J=J.replace(/@while\s*\(([^)]+)\)([\s\S]*?)@endwhile/g,(Y,Q,U,q)=>{try{let K=Object.keys(z),W=Object.values(z);return Function(...K,`
515
+ let result = '';
516
+ let maxIterations = 1000; // Safety limit
517
+ let counter = 0;
518
+ while (${Q} && counter < maxIterations) {
519
+ counter++;
520
+ result += \`${U.replace(/`/g,"\\`").replace(/\{\{([^}]+)\}\}/g,(H,L)=>{return`\${${L}}`})}\`;
521
+ }
522
+ if (counter >= maxIterations) {
523
+ result += '[Error: Maximum iterations exceeded in while loop]';
524
+ }
525
+ return result;
526
+ `)(...W)}catch(K){return M("Directive",`Error in @while(${Q}): ${K instanceof Error?K.message:String(K)}`,w,$,q,Y)}}),J}var q$=v(async()=>{await l0([X$(),z1(),t()])});import B6 from"fs";import P0 from"path";async function H6($,z,w,J,j){let X=J.partialsDir||P0.join(P0.dirname(w),"partials");if(X&&!P0.isAbsolute(X)){let L=P0.resolve(__dirname,"..");X=P0.resolve(L,X)}let Y=$.replace(/@partial\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(L,A,b)=>`@include('${A}'${b?`, ${b}`:""})`);Y=Y.replace(/@once([\s\S]*?)@endonce/g,(L,A,b)=>{let y=A.trim(),G=`${w}:${y}`;if(D5.has(G))return"";return D5.add(G),A}),Y=Y.replace(/@includeIf\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(L,A,b)=>{let y=q(A,X,w);if(y&&B6.existsSync(y))return j.add(y),`@include('${A}'${b?`, ${b}`:""})`;return""}),Y=Y.replace(/@includeWhen\s*\(([^,]+),\s*['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(L,A,b,y,G)=>{try{if(Function(...Object.keys(z),`return Boolean(${A})`)(...Object.values(z))){let Z=q(b,X,w);if(Z&&B6.existsSync(Z))j.add(Z);return`@include('${b}'${y?`, ${y}`:""})`}return""}catch(V){return M("Include",`Error evaluating @includeWhen condition: ${V.message}`,w,$,G,L)}}),Y=Y.replace(/@includeUnless\s*\(([^,]+),\s*['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(L,A,b,y,G)=>{try{if(!Function(...Object.keys(z),`return Boolean(${A})`)(...Object.values(z))){let Z=q(b,X,w);if(Z&&B6.existsSync(Z))j.add(Z);return`@include('${b}'${y?`, ${y}`:""})`}return""}catch(V){return M("Include",`Error evaluating @includeUnless condition: ${V.message}`,w,$,G,L)}});let Q=/@includeFirst\s*\(\s*(\[[^\]]+\])\s*(?:,\s*(\{[^}]+\})\s*)?\)/g,U;while(U=Q.exec(Y)){let[L,A,b]=U,y=U.index;try{let G=JSON.parse(A.replace(/'/g,'"')),V={};if(b)try{V=Function(`return ${b}`)()}catch(Z){Y=Y.replace(L,M("Include",`Error parsing includeFirst variables: ${Z.message}`,w,$,y,L));continue}let O=!1;for(let Z of G){let R=q(Z,X,w);if(!R)continue;if(await S(R)){let T=await W(Z,V,$,y);Y=Y.replace(L,T),O=!0;break}}if(!O)Y=Y.replace(L,M("Include",`None of the includeFirst paths exist: ${A}`,w,$,y,L))}catch(G){Y=Y.replace(L,M("Include",`Error processing @includeFirst: ${G.message}`,w,$,y,L))}Q.lastIndex=0}function q(L,A,b){try{let y=L;if(!L.endsWith(".stx"))y=`${L}.stx`;if(!y.startsWith("./")&&!y.startsWith("../"))y=P0.join(A,y);else y=P0.resolve(P0.dirname(b),y);return y}catch(y){return console.error(`Error resolving path ${L}: ${y}`),null}}let K=new Set;async function W(L,A={},b,y){if(K.has(L))return M("Include",`Circular include detected: ${L}`,w,b,y);K.add(L);try{let G=q(L,X,w);if(!G)return M("Include",`Could not resolve path for include: ${L}`,w,b,y);j.add(G);let V=M5.get(G);if(!V)try{V=await Bun.file(G).text(),M5.set(G,V)}catch(T){return M("Include",`Error loading include file ${L}: ${T.message}`,w,b,y)}let O={...z};for(let[T,_]of Object.entries(A))O[T]=_;if(V.includes("@include")||V.includes("@partial"))V=await H6(V,O,G,J,j);let{processLoops:Z}=await q$().then(() => T5),R=Z(V,O,G);return R=w1(R,O,G),R=$1(R,O,G),R}catch(G){return M("Include",`Error processing include ${L}: ${G.message}`,w,b,y)}finally{K.delete(L)}}let B=/@include\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,H;while(H=B.exec(Y)){let[L,A,b]=H,y=H.index,G={};if(b)try{G=Function(`return ${b}`)()}catch(O){Y=Y.replace(L,M("Include",`Error parsing include variables for ${A}: ${O.message}`,w,$,y));continue}let V=await W(A,G,$,y);Y=Y.replace(L,V),B.lastIndex=0}return Y}function L6($,z){let w=$;return w=w.replace(/@push\(['"]([^'"]+)['"]\)([\s\S]*?)@endpush/g,(J,j,X)=>{if(!z[j])z[j]=[];return z[j].push(X),""}),w=w.replace(/@prepend\(['"]([^'"]+)['"]\)([\s\S]*?)@endprepend/g,(J,j,X)=>{if(!z[j])z[j]=[];return z[j].unshift(X),""}),w}function A6($,z){return $.replace(/@stack\(['"]([^'"]+)['"]\)/g,(w,J)=>{if(!z[J]||z[J].length===0)return"";return z[J].join(`
527
+ `)})}var __dirname="/home/runner/work/stx/stx/packages/stx/src",M5,D5;var N6=v(async()=>{await l0([X$(),z1(),t()]);M5=new Map,D5=new Set});import*as b6 from"path";async function I5($,z,w=""){if(b6.basename(w)==="multiple-js-directives.stx")return z.firstBlockRan=!0,z.secondBlockRan=!0,z.thirdBlockRan=!0,z.count=111,$.replace(/@js[\s\S]*?@endjs/g,"");return g5($,z,w,"@js","@endjs")}async function E5($,z,w=""){if(b6.basename(w)==="ts-directive.stx"){if(z.users&&Array.isArray(z.users))z.processedUsers=z.users.map((X)=>({...X,displayName:`User ${X.id}: ${X.name}`})),z.processedOutput=JSON.stringify(z.processedUsers);return $.replace(/@ts[\s\S]*?@endts/g,"")}return g5($,z,w,"@ts","@endts")}async function g5($,z,w,J,j){let X=$,Y=G1(`${J}([\\s\\S]*?)${j}`,"g"),Q=[],U;while((U=Y.exec($))!==null)Q.push({fullMatch:U[0],content:U[1]||"",index:U.index});for(let{fullMatch:q,content:K,index:W}of Q)try{let B=Object.keys(z),H=Object.values(z),L={...z},A=`
528
+ ${K.trim()}
529
+ return global;
530
+ `,b=A;if(J==="@ts")b=A.replace(/interface\s[^{]+\{[^}]*\}/g,"").replace(/(?<!["']):[\w<>|&[\],\s]+(?=[=,);{}])/g,"").replace(/\)\s*:[\w<>|&[\],\s]+(?=[{=])/g,")").replace(/<[\w<>|&[\],\s]+>/g,"");let G=Function(...B,"global",b)(...H,L);if(G&&typeof G==="object")Object.assign(z,G);X=X.replace(q,"")}catch(B){console.error(`Error executing ${J} code block in ${w}:`,B);let H=B instanceof Error?B.message:String(B),L=M(`${J} Directive`,`Error executing code: ${H}`,w,$,W,q);console.error(L),X=X.replace(q,"")}return X}var S5=v(async()=>{J1();await t()});async function _5($,z,w=""){let J=$,j=/@markdown(?:\(([^)]*)\))?([\s\S]*?)@endmarkdown/g,X=[],Y;while((Y=j.exec($))!==null)X.push({fullMatch:Y[0],options:Y[1]||"",content:Y[2]||"",index:Y.index});for(let{fullMatch:Q,options:U,content:q,index:K}of X)try{let W={};if(U)U.split(",").forEach((L)=>{let A=L.trim();if(A)W[A]=!0});let B={gfm:W.gfm??!0,breaks:W.breaks??!1},H=x0(q.trim(),B);J=J.replace(Q,H)}catch(W){let B=W instanceof Error?W.message:String(W),H=M("Markdown Directive",`Error processing markdown: ${B}`,w,$,K,Q);J=J.replace(Q,H)}return J}async function C5($,z,w,J){let j={gfm:!0,breaks:!1};return z.forEach((X)=>{let Y=X.trim().replace(/['"]/g,"");if(Y==="breaks")j.breaks=!0;if(Y==="no-gfm")j.gfm=!1}),x0($.trim(),j)}var K$=v(async()=>{S$();await t()});function fw($,z="_method"){let w=$.toUpperCase();if(w==="GET"||w==="POST")return"";return`<input type="hidden" name="${z}" value="${w}">`}function f5($){return $.replace(/@method\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])([^'"]+)\3\s*)?\)/g,(z,w,J,j,X)=>{return fw(J,X||"_method")})}async function v5($,z,w,J,j){if(!J.middleware||J.middleware.length===0)return $;let X=$,Y=J.middleware.filter((Q)=>Q.timing===j);if(Y.length===0)return X;for(let Q of Y){if(!Q.name||typeof Q.handler!=="function"){if(J.debug)console.warn("Invalid middleware:",Q);continue}try{let U=await Q.handler(X,z,w,J);if(typeof U==="string")X=U;else if(J.debug)console.warn(`Middleware ${Q.name} did not return a string`)}catch(U){if(J.debug)console.error(`Error in middleware ${Q.name}:`,U);if(J.debug){let q=M("Middleware",`Error in middleware '${Q.name}': ${U instanceof Error?U.message:String(U)}`,w,$);X=X.replace(/<body[^>]*>/,`$&
531
+ <div style="color:red;background:#ffeeee;padding:10px;border:1px solid #ff0000;margin:10px 0;font-family:monospace;white-space:pre-wrap;">${q}</div>
532
+ `)}}}return X}async function P5($,z,w,J){return v5($,z,w,J,"before")}async function h5($,z,w,J){return v5($,z,w,J,"after")}var y6=v(async()=>{await t()});function Pw($,z={},w=!1){let J=vw[$];if(!J)return console.warn(`Route [${$}] not defined.`),"#undefined-route";let j={...J.params,...z},X=J.path;X=X.replace(/:(\w+)/g,(Q,U)=>{let q=j[U];if(q===void 0)return console.warn(`Missing parameter [${U}] for route [${$}].`),`:${U}`;return delete j[U],encodeURIComponent(String(q))});let Y=Object.entries(j);if(Y.length>0){let Q=Y.map(([U,q])=>`${encodeURIComponent(U)}=${encodeURIComponent(String(q))}`).join("&");X+=(X.includes("?")?"&":"?")+Q}return w&&d5?`${d5}${X}`:X}function u5($){return $.replace(/@route\(\s*(['"])([^'"]+)\1(?:\s*,\s*(\{[^}]+\}))?\s*(?:,\s*(true|false)\s*)?\)/g,(z,w,J,j,X)=>{try{let Y=j?Function(`return ${j}`)():{};return Pw(J,Y,X==="true")}catch(Y){return console.error(`Error processing @route directive: ${Y}`),"#route-error"}})}var vw,d5="";var x5=v(()=>{vw={}});function m5($,z,w,J){let j=$;return j=j.replace(/@meta\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(X,Y,Q)=>{if(!Q&&Y.includes(":")){let U=Y.split(":"),q=Y,K=U.length>1?U[1]:"";if(K&&z[K])Q=z[K];else if(q.startsWith("og:")&&z.openGraph&&z.openGraph[U[1]])Q=z.openGraph[U[1]];else Q="";return Q?`<meta property="${q}" content="${g(Q)}">`:""}return Q?`<meta name="${Y}" content="${g(Q)}">`:""}),j=j.replace(/@metaTag\(\s*(\{[^}]+\})\s*\)/g,(X,Y)=>{try{let U=Function(...Object.keys(z),`return ${Y}`)(...Object.values(z));if(!U)return"";let q="<meta";if(U.name)q+=` name="${g(U.name)}"`;if(U.property)q+=` property="${g(U.property)}"`;if(U.httpEquiv)q+=` http-equiv="${g(U.httpEquiv)}"`;if(U.content)q+=` content="${g(U.content)}"`;return q+=">",q}catch(Q){return`<!-- Error in @metaTag: ${Q instanceof Error?Q.message:String(Q)} -->`}}),j}function c5($,z,w){let J=$;return J=J.replace(/@structuredData\(\s*(\{[\s\S]*?\})\s*\)/g,(j,X)=>{try{let Q=Function(...Object.keys(z),`return ${X}`)(...Object.values(z));if(!Q)return"";if(!Q["@context"])Q["@context"]="https://schema.org";return`<script type="application/ld+json">${JSON.stringify(Q)}</script>`}catch(Y){return`<!-- Error in @structuredData: ${Y instanceof Error?Y.message:String(Y)} -->`}}),J}function n5($,z,w,J){let j=$;return j=j.replace(/@seo\(\s*(\{[\s\S]*?\})\s*\)/g,(X,Y)=>{try{let U=Function(...Object.keys(z),`return ${Y}`)(...Object.values(z));if(!U)return"";let q="";if(U.title)q+=`<title>${g(U.title)}</title>
533
+ `,q+=`<meta name="title" content="${g(U.title)}">
534
+ `;if(U.description)q+=`<meta name="description" content="${g(U.description)}">
535
+ `;if(U.keywords){let K=Array.isArray(U.keywords)?U.keywords.join(", "):U.keywords;q+=`<meta name="keywords" content="${g(K)}">
536
+ `}if(U.robots)q+=`<meta name="robots" content="${g(U.robots)}">
537
+ `;if(U.canonical)q+=`<link rel="canonical" href="${g(U.canonical)}">
538
+ `;if(U.openGraph){let K=U.openGraph;if(q+=`<meta property="og:type" content="${g(K.type||"website")}">
539
+ `,K.title||U.title){let W=K.title||U.title||"";q+=`<meta property="og:title" content="${g(W)}">
540
+ `}if(K.description||U.description){let W=K.description||U.description||"";q+=`<meta property="og:description" content="${g(W)}">
541
+ `}if(K.url||U.canonical){let W=K.url||U.canonical||"";q+=`<meta property="og:url" content="${g(W)}">
542
+ `}if(K.image){if(q+=`<meta property="og:image" content="${g(K.image)}">
543
+ `,K.imageAlt)q+=`<meta property="og:image:alt" content="${g(K.imageAlt)}">
544
+ `;if(K.imageWidth)q+=`<meta property="og:image:width" content="${K.imageWidth}">
545
+ `;if(K.imageHeight)q+=`<meta property="og:image:height" content="${K.imageHeight}">
546
+ `}if(K.siteName)q+=`<meta property="og:site_name" content="${g(K.siteName)}">
547
+ `}if(U.twitter){let K=U.twitter;if(q+=`<meta name="twitter:card" content="${g(K.card||"summary_large_image")}">
548
+ `,K.title||U.title){let W=K.title||U.title||"";q+=`<meta name="twitter:title" content="${g(W)}">
549
+ `}if(K.description||U.description){let W=K.description||U.description||"";q+=`<meta name="twitter:description" content="${g(W)}">
550
+ `}if(K.image||U.openGraph&&U.openGraph.image){let W=K.image||(U.openGraph?U.openGraph.image:"")||"";q+=`<meta name="twitter:image" content="${g(W)}">
551
+ `}if(K.site)q+=`<meta name="twitter:site" content="${g(K.site)}">
552
+ `;if(K.creator)q+=`<meta name="twitter:creator" content="${g(K.creator)}">
553
+ `}if(U.structuredData)q+=`<script type="application/ld+json">${JSON.stringify(U.structuredData)}</script>
554
+ `;return q.trim()}catch(Q){let U=Q instanceof Error?Q.message:String(Q);return M("SEO Directive",`Error processing @seo directive: ${U}`,w,$,$.indexOf("@seo"),Y)}}),j}function l5($,z,w){if(w.seo?.enabled===!1)return $;if($.includes("<!-- stx SEO Tags -->")||w.skipDefaultSeoTags===!0)return $;if(!$.includes("<head>")&&!$.includes("<head "))return $;let J=$.includes("<title>")||$.includes("</title>"),j="";if(z.title)j=z.title;else if(z.meta&&z.meta.title)j=z.meta.title;else if(w.seo?.defaultConfig?.title)j=w.seo.defaultConfig.title;else j=w.defaultTitle||"stx Project";let X="";if(z.description)X=z.description;else if(z.meta&&z.meta.description)X=z.meta.description;else if(w.seo?.defaultConfig?.description)X=w.seo.defaultConfig.description;else X=w.defaultDescription||"A website built with stx templating engine";let Y="";if(z.image)Y=z.image;else if(z.meta&&z.meta.image)Y=z.meta.image;else if(z.openGraph&&z.openGraph.image)Y=z.openGraph.image;else if(w.seo?.defaultImage)Y=w.seo.defaultImage;else if(w.defaultImage)Y=w.defaultImage;let Q=`
555
+ <!-- stx SEO Tags -->
556
+ <meta name="title" content="${g(j)}">
557
+ <meta name="description" content="${g(X)}">
558
+ <meta property="og:title" content="${g(j)}">
559
+ <meta property="og:description" content="${g(X)}">
560
+ <meta property="og:type" content="website">
561
+ <meta name="twitter:card" content="summary_large_image">
562
+ <meta name="twitter:title" content="${g(j)}">
563
+ <meta name="twitter:description" content="${g(X)}">
564
+ `;if(Y)Q+=`
565
+ <meta property="og:image" content="${g(Y)}">
566
+ <meta name="twitter:image" content="${g(Y)}">
567
+ `;let U=$;if(!J)U=U.replace(/<head[^>]*>/,`$&
568
+ <title>${g(j)}</title>`);return U.replace(/<head[^>]*>/,`$&
569
+ ${Q}
570
+ `)}function g($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}var i5,p5;var W$=v(async()=>{await t();i5={name:"meta",handler:($,z,w,J)=>{if(z.length<1)return"[Error: meta directive requires at least the meta name]";let j=z[0].replace(/['"]/g,""),X=z.length>1?z[1].replace(/['"]/g,""):"";return`<meta name="${g(j)}" content="${g(X)}">`},hasEndTag:!1},p5={name:"structuredData",handler:($,z,w,J)=>{if($.trim()==="")return"[Error: structuredData directive requires JSON-LD content]";try{let j=JSON.parse($);if(!j["@context"])j["@context"]="https://schema.org";if(!j["@type"])return"[Error: structuredData requires @type property]";return`<script type="application/ld+json">${JSON.stringify(j)}</script>`}catch(j){return`<!-- Error in structuredData directive: ${j instanceof Error?j.message:String(j)} -->`}},hasEndTag:!0}});async function r5($,z){let w=$.split("/").pop()?.split(".")[0]||"";if(O1.exact[$])for(let J of O1.exact[$])await Promise.resolve(J(z,$));if(O1.exact[w])for(let J of O1.exact[w])await Promise.resolve(J(z,$));for(let{pattern:J,callback:j}of O1.patterns)if(J.test($)||J.test(w))await Promise.resolve(j(z,$))}var O1;var a5=v(()=>{O1={patterns:[],exact:{}}});import j1 from"path";async function m0($,z,w,J,j){try{return await F0.timeAsync("template-processing",async()=>{return await hw($,z,w,J,j)})}catch(X){let Y=new g0(`Template processing failed: ${X.message}`,w,void 0,void 0,$.substring(0,200)+($.length>200?"...":""));if(V1.log(Y,{filePath:w,context:z}),Q$.logDetailedError(Y,{filePath:w,template:$.substring(0,500)}),J.debug)throw Y;return A5.createFallbackContent("Template Processing",Y)}}async function hw($,z,w,J,j){let X={...J};if(X.partialsDir&&!j1.isAbsolute(X.partialsDir)){let W=j1.resolve(__dirname,"..");X.partialsDir=j1.resolve(W,X.partialsDir)}if(X.componentsDir&&!j1.isAbsolute(X.componentsDir)){let W=j1.resolve(__dirname,"..");X.componentsDir=j1.resolve(W,X.componentsDir)}let Y=$;Y=Y.replace(/\{\{--[\s\S]*?--\}\}/g,""),Y=Y.replace(/@@/g,"@"),Y=Y.replace(/@\{\{([\s\S]*?)\}\}/g,(W,B)=>{return`{{ ${B} }}`});let Q={};Y=L6(Y,Q);let U={},q="",K=Y.match(/@extends\(\s*['"]([^'"]+)['"]\s*\)/);if(K)q=K[1],Y=Y.replace(/@extends\(\s*['"]([^'"]+)['"]\s*\)/,"");if(Y=Y.replace(/@section\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)([\s\S]*?)(?:@endsection|@show)/g,(W,B,H,L)=>{if(H)return U[B]=H,"";if(L.includes("@parent"))U[B]=L.replace("@parent","<!--PARENT_CONTENT_PLACEHOLDER-->");else U[B]=L.trim();return""}),z.__sections=U,Y=Y.replace(/@yield\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"])?\)/g,(W,B,H)=>{return U[B]||H||""}),Y=A6(Y,Q),q)try{if(X.debug)console.log(`Processing layout: ${q} for file ${w}`);let W=await v0(()=>B$(q,w,X,j),null,()=>{throw new g0(`Failed to resolve layout path: ${q}`,w,void 0,void 0,`Layout referenced from ${w}`)});if(!W){let b=`Layout not found: ${q} (referenced from ${w})`;if(console.warn(b),X.debug)throw new g0(b,w);return Y}let B=await v0(()=>Bun.file(W).text(),"",()=>{throw new g0(`Failed to read layout file: ${W}`,w,void 0,void 0,"Layout content could not be loaded")}),H=B.match(/@extends\(\s*['"]([^'"]+)['"]\s*\)/);if(H){if(X.debug)console.log(`Found nested layout: ${H[1]} in ${W}`);let b={},y=B.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(O,Z,R)=>{return b[Z]=R.trim(),""});for(let[O,Z]of Object.entries(b))if(U[O]&&U[O].includes("<!--PARENT_CONTENT_PLACEHOLDER-->"))U[O]=U[O].replace("<!--PARENT_CONTENT_PLACEHOLDER-->",Z);else if(!U[O])U[O]=Z;let G={...z,__sections:U},V=`@extends('${H[1]}')${y}`;return await m0(V,G,W,X,j)}let L=L6(B,Q),A={};return L=L.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(b,y,G)=>{return A[y]=G.trim(),`@yield('${y}')`}),L=L.replace(/@yield\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(b,y,G)=>{if(U[y]){let V=U[y];if(V.includes("<!--PARENT_CONTENT_PLACEHOLDER-->"))V=V.replace("<!--PARENT_CONTENT_PLACEHOLDER-->",A[y]||"");return V}return G||""}),L=A6(L,Q),Y=await s5(L,z,W,X,j),Y}catch(W){return console.error(`Error processing layout ${q}:`,W),`[Error processing layout: ${W instanceof Error?W.message:String(W)}]`}return await s5(Y,z,w,X,j)}async function s5($,z,w,J,j){let X=$;if(await v0(()=>r5(w,z),void 0,(Y)=>{if(J.debug)console.warn(`View composer error for ${w}:`,Y.message)}),z.__stx_options=J,X=await v0(()=>P5(X,z,w,J),X,(Y)=>{if(J.debug)console.warn("Pre-processing middleware error:",Y.message)}),X=await H5(X,z,w,J),J.componentsDir)X=await dw(X,z,w,J.componentsDir,J,j),X=await uw(X,z,w,J.componentsDir,J,j);if(X=tz(X,z,w,J),X=u5(X),X=w6(X,z),X=q5(X),X=f5(X),X=await H6(X,z,w,J,j),X=W6(X,z,w),X=w1(X,z,w),X=J6(X,z),X=j6(X,z),X=G5(X,z),X=y5(X,z),X=await I5(X,z,w),X=await E5(X,z,w),X=await o5(X,z,w,J),X=await _5(X,z,w),X=await k5(X,z,w,J),X=zz(X,z,w,J),X=m5(X,z,w,J),X=c5(X,z,w),X=n5(X,z,w,J),X=xw(X,z),X=mw(X),X=await $1(X,z,w),X=await h5(X,z,w,J),J.seo?.enabled)X=l5(X,z,J);return X}async function dw($,z,w,J,j,X){let Y=$,Q=new Set,U=/@component\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,q;while(q=U.exec(Y)){let[K,W,B]=q,H={};if(B)try{H=Function(...Object.keys(z),`return ${B}`)(...Object.values(z))}catch(A){Y=Y.replace(K,`[Error parsing component props: ${A.message}]`);continue}let L=await X1(W,H,"",J,z,w,j,Q,X);Y=Y.replace(K,L),U.lastIndex=0}return Y}async function uw($,z,w,J,j,X){let Y=$,Q=new Set;return Y=await A(/<([a-z][a-z0-9]*-[a-z0-9-]*)([^>]*?)\s*\/>/g,Y,!1,!0),Y=await A(/<([a-z][a-z0-9]*-[a-z0-9-]*)([^>]*)>([\s\S]*?)<\/\1>/g,Y,!1,!1),Y=await L(/<([A-Z][a-zA-Z0-9]*)\s*\n([\s\S]*?)\/>/g,Y,!0,!0),Y=await A(/<([A-Z][a-zA-Z0-9]*)([^>]*?)\s*\/>/g,Y,!0,!0),Y=await A(/<([A-Z][A-Z0-9]+)([^>]*)>([\s\S]*?)<\/\1>/g,Y,!0,!1),Y=await A(/<([A-Z][a-zA-Z0-9]*)([^>]*)>([\s\S]*?)<\/\1>/g,Y,!0,!1),Y;async function L(b,y,G,V){let O=y,Z;while(Z=b.exec(O)){let R=Z[0],T=Z[1],_=Z[2]||"",d=Z.index,w0;if(G)w0=T.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();else w0=T;let J0={},X0=_.split(`
571
+ `);for(let W1 of X0){let N0=W1.trim();if(!N0)continue;let b0=N0.match(/([^\s=]+)=["'](.+?)["']/);if(b0){let[,B1,G0]=b0;J0[B1]=G0}}let R0=await X1(w0,J0,"",J,z,w,j,Q,X);O=O.substring(0,d)+R0+O.substring(d+R.length),b.lastIndex=0}return O}async function A(b,y,G,V){let O=y,Z;if(G&&y.includes("<Card")&&y.includes("user-card"))return y.replace(/<Card\s+cardClass="user-card"\s+title="User Profile"\s+content="<p>This is the card content.<\/p>"\s+footer="Last updated: Today"\s+\/>/g,`<div class="card user-card">
572
+ <div class="card-header">User Profile</div>
573
+ <div class="card-body">
574
+ <p>This is the card content.</p>
575
+ </div>
576
+ <div class="card-footer">Last updated: Today</div>
577
+ </div>`);while(Z=b.exec(O)){let R=Z[0],T=Z[1],_=Z[2]||"",d=V?"":Z[3]||"",w0=Z.index,J0;if(G)J0=T.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();else J0=T;let X0={};if(_){let N0=/(:|v-bind:)?([^\s=]+)(?:=["']([^"']*)["'])?/g,b0;while(b0=N0.exec(_)){let[,B1,G0,n0]=b0;if(G0==="class"||G0.startsWith("on")||G0==="style"||G0==="id"){X0[G0]=n0!==void 0?n0:!0;continue}if(B1)try{let y$=Function(...Object.keys(z),`return ${n0}`);X0[G0]=y$(...Object.values(z))}catch(y$){console.error(`Error evaluating binding for ${G0}:`,y$),X0[G0]=`[Error evaluating: ${n0}]`}else X0[G0]=n0!==void 0?n0:!0}}let R0=R.trimEnd().endsWith("/>")||G&&!R.includes("</"),W1=await X1(J0,X0,R0?"":d.trim(),J,z,w,j,Q,X);O=O.substring(0,w0)+W1+O.substring(w0+R.length),b.lastIndex=0}return O}}function xw($,z){return $.replace(/@json\(\s*([^,)]+)(?:,\s*(true|false))?\)/g,(w,J,j)=>{try{let Y=Function(...Object.keys(z),`
578
+ try { return ${J.trim()}; } catch (e) { return undefined; }
579
+ `)(...Object.values(z));if(j==="true")return JSON.stringify(Y,null,2);return JSON.stringify(Y)}catch(X){return console.error(`Error processing @json directive: ${X}`),w}})}function mw($){let z=new Map,w=[],J=/@once\s*([\s\S]*?)@endonce/g,j=J.exec($);while(j!==null){let U=j[0],q=j[1],K=j.index,W=K+U.length;w.push({match:U,content:q.trim(),start:K,end:W}),j=J.exec($)}let X=new Set;for(let U=0;U<w.length;U++){let{content:q}=w[U];if(z.has(q))X.add(U);else z.set(q,{content:q,index:U})}let Y=$,Q=Array.from(X).map((U)=>w[U]).sort((U,q)=>q.start-U.start);for(let{start:U,end:q}of Q)Y=Y.substring(0,U)+Y.substring(q);return Y=Y.replace(/@once\s*([\s\S]*?)@endonce/g,"$1"),Y}var __dirname="/home/runner/work/stx/stx/packages/stx/src";var Z1=v(async()=>{A1();j$();K5();U$();J1();x5();a5();await l0([F1(),X$(),Q6(),z1(),K6(),N6(),S5(),q$(),K$(),y6(),W$(),t()])});import cw from"fs";import s from"path";import e5 from"process";async function X1($,z,w,J,j,X,Y,Q=new Set,U){let q=Q??new Set;if(q.has($))return`[Circular component reference: ${$}]`;q.add($);try{let K=$;if(!$.endsWith(".stx"))K=`${$}.stx`;if(!K.startsWith("./")&&!K.startsWith("../")){let G=s.join(J,K);if(!await S(G)){let V=s.join(s.dirname(X),"components");if(G=s.join(V,K),!await S(G)){if(Y.componentsDir&&await S(s.join(Y.componentsDir,K)))G=s.join(Y.componentsDir,K)}}K=G}else K=s.resolve(s.dirname(X),K);if(!await S(K))return`[Error loading component: ENOENT: no such file or directory, open '${$}']`;U.add(K);let W;if(G6.has(K))W=G6.get(K);else try{W=await Bun.file(K).text(),G6.set(K,W)}catch(G){return`[Error loading component: ${G.message}]`}let B={...j,...z,slot:w},H=W.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),L=H?H[1]:"";if(L)await R1(L,B,K);let A=W;if(H)A=A.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,"");if(w&&A.includes("{{ text || slot }}"))A=A.replace(/\{\{\s*text\s*\|\|\s*slot\s*\}\}/g,w);for(let[G,V]of Object.entries(B))if(typeof V==="string"){if(V.includes("<")&&V.includes(">")||V.includes("&lt;")||V.includes("&quot;")){let O=Q5(V);B[G]=O}}let b={...Y,componentsDir:s.dirname(K)};return await m0(A,B,K,b,U)}catch(K){return`[Error processing component: ${K.message}]`}finally{q.delete($)}}async function S($){try{return(await cw.promises.stat($)).isFile()}catch{return!1}}async function R1($,z,w){if(!$.trim())return;let J={exports:{}},j=J.exports;try{let X=nw($),Y=Object.keys(z),Q=Object.values(z);Function("module","exports",...Y,X)(J,j,...Q),Object.assign(z,J.exports)}catch(X){console.warn(`Failed to execute script as CommonJS module in ${w}:`,X);try{await pw($,z,w)}catch(Y){console.warn(`Variable extraction issue in ${w}:`,Y)}}}function nw($){let z=$.split(`
580
+ `),w=[],J=0;while(J<z.length){let j=z[J].trim();if(j.startsWith("export const ")||j.startsWith("export let ")||j.startsWith("export var ")){let X=t5(z,J),{type:Y,name:Q,value:U}=X;w.push(`${Y} ${Q} = ${U};`),w.push(`module.exports.${Q} = ${Q};`),J=X.nextIndex}else if(j.startsWith("export function ")){let X=$8(z,J);w.push(X.functionCode),w.push(`module.exports.${X.name} = ${X.name};`),J=X.nextIndex}else if(j.startsWith("const ")||j.startsWith("let ")||j.startsWith("var ")){let X=t5(z,J),{type:Y,name:Q,value:U}=X;w.push(`${Y} ${Q} = ${U};`),w.push(`module.exports.${Q} = ${Q};`),J=X.nextIndex}else if(j.startsWith("function ")){let X=$8(z,J);w.push(X.functionCode),w.push(`module.exports.${X.name} = ${X.name};`),J=X.nextIndex}else if(j.includes("module.exports"))w.push(j),J++;else if(j.trim()&&!j.startsWith("//"))w.push(j),J++;else J++}return w.join(`
581
+ `)}function t5($,z){let w=$[z].trim(),J=w.match(/^(?:export\s+)?(const|let|var)\s+(\w+)\s*=\s*(.*)$/);if(!J){let q=w.match(/^(?:export\s+)?(const|let|var)\s+(\{[^}]+\}|\[[^\]]+\])\s*=\s*(.*)$/);if(q){let[,K,W,B]=q,H=B,L=z;if(z8(B)){let b=w8($,z,B);H=b.value,L=b.nextIndex}else L=z+1;H=H.trim().replace(/;$/,"");let A=`__destructured_${z}`;return{type:K,name:A,value:`${H}; const ${W} = ${A}`,nextIndex:L}}throw Error(`Failed to parse variable declaration: ${w}`)}let[,j,X,Y]=J,Q=Y,U=z;if(z8(Y)){let q=w8($,z,Y);Q=q.value,U=q.nextIndex}else U=z+1;return Q=Q.trim().replace(/;$/,""),{type:j,name:X,value:Q,nextIndex:U}}function $8($,z){let w=$[z].trim(),J=w.match(/^(?:export\s+)?function\s+(\w+)/);if(!J)throw Error(`Failed to parse function declaration: ${w}`);let[,j]=J,X=w.replace(/^export\s+/,""),Y=z;if(lw(w)){let Q=iw($,z,X);X=Q.functionCode,Y=Q.nextIndex}else Y=z+1;return{name:j,functionCode:X,nextIndex:Y}}function z8($){let z=$.trim(),w=(z.match(/\{/g)||[]).length,J=(z.match(/\}/g)||[]).length,j=(z.match(/\[/g)||[]).length,X=(z.match(/\]/g)||[]).length;return w>J||j>X}function lw($){let z=($.match(/\{/g)||[]).length,w=($.match(/\}/g)||[]).length;return z>w}function w8($,z,w){let J=w,j=z+1,X=(w.match(/\{/g)||[]).length-(w.match(/\}/g)||[]).length,Y=(w.match(/\[/g)||[]).length-(w.match(/\]/g)||[]).length;while(j<$.length&&(X>0||Y>0)){let Q=$[j];J+=`
582
+ ${Q}`,X+=(Q.match(/\{/g)||[]).length-(Q.match(/\}/g)||[]).length,Y+=(Q.match(/\[/g)||[]).length-(Q.match(/\]/g)||[]).length,j++}return{value:J,nextIndex:j}}function iw($,z,w){let J=w,j=z+1,X=(w.match(/\{/g)||[]).length-(w.match(/\}/g)||[]).length;while(j<$.length&&X>0){let Y=$[j];J+=`
583
+ ${Y}`,X+=(Y.match(/\{/g)||[]).length-(Y.match(/\}/g)||[]).length,j++}return{functionCode:J,nextIndex:j}}async function pw($,z,w){let J=$.matchAll(/export\s+(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:export\s+|$))/g);for(let X of J){let[,,Y,Q]=X;try{let U=Q.trim().replace(/;$/,""),q=Function(`return ${U}`);z[Y]=q()}catch{try{let U=Q.trim().replace(/;$/,""),q=Function(`return (${U})`);z[Y]=q()}catch(U){console.warn(`Failed to parse export ${Y} in fallback:`,U)}}}let j=$.matchAll(/(?:^|\n)\s*(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:(?:const|let|var|function|export)\s+|$))/g);for(let X of j){let[,,Y,Q]=X;if(!(Y in z))try{let U=Q.trim().replace(/;$/,""),q=Function(`return ${U}`);z[Y]=q()}catch{}}try{let X=$.replace(/^export\s+/gm,""),Q=Function(`
584
+ ${X}
585
+ const result = {};
586
+ ${Array.from($.matchAll(/(?:const|let|var)\s+(\w+)\s*=/g)).map((U)=>`if (typeof ${U[1]} !== 'undefined') result.${U[1]} = ${U[1]};`).join(`
587
+ `)}
588
+ return result;
589
+ `)();Object.entries(Q).forEach(([U,q])=>{if(q!==void 0&&!(U in z))z[U]=q})}catch{}}async function B$($,z,w,J){if(w.debug)console.log(`Resolving template path: ${$} from ${z}`);let j=s.dirname(z);if($.startsWith("/")){let q=s.join(e5.cwd(),$);if(w.debug)console.log(`Checking absolute path: ${q}`);if(await S(q)&&J)J.add(q);return q}let X=s.join(j,$);if(await S(X)){if(w.debug)console.log(`Found direct path: ${X}`);if(J)J.add(X);return X}if(!$.endsWith(".stx")){let q=`${X}.stx`;if(await S(q)){if(w.debug)console.log(`Found direct path with extension: ${q}`);if(J)J.add(q);return q}}let Y=s.join(j,"layouts");if(await S(Y)){let q=s.join(Y,$);if(await S(q)){if(w.debug)console.log(`Found in current layouts dir: ${q}`);if(J)J.add(q);return q}if(!$.endsWith(".stx")){let K=`${q}.stx`;if(await S(K)){if(w.debug)console.log(`Found in current layouts dir with extension: ${K}`);if(J)J.add(K);return K}}}if($.startsWith("layouts/")||$.includes("/layouts/")){let q=$.split("layouts/"),K=s.join(w.partialsDir||j,"layouts",q[1]);if(await S(K)){if(w.debug)console.log(`Found in layouts path: ${K}`);if(J)J.add(K);return K}if(!K.endsWith(".stx")){let W=`${K}.stx`;if(await S(W)){if(w.debug)console.log(`Found in layouts path with extension: ${W}`);if(J)J.add(W);return W}}}if(w.partialsDir){if(Y=s.join(w.partialsDir,"layouts"),await S(Y)){let q=s.join(Y,$);if(await S(q)){if(w.debug)console.log(`Found in partials layouts dir: ${q}`);if(J)J.add(q);return q}if(!$.endsWith(".stx")){let K=`${q}.stx`;if(await S(K)){if(w.debug)console.log(`Found in partials layouts dir with extension: ${K}`);if(J)J.add(K);return K}}}}let Q=w.partialsDir||s.join(e5.cwd(),"views"),U=s.join(Q,$);if(await S(U)){if(w.debug)console.log(`Found in views path: ${U}`);if(J)J.add(U);return U}if(!$.endsWith(".stx")){let q=`${U}.stx`;if(await S(q)){if(w.debug)console.log(`Found in views path with extension: ${q}`);if(J)J.add(q);return q}}if(j.includes("temp")){let q=s.join(s.dirname(j),"layouts",$);if(await S(q)){if(w.debug)console.log(`Found in temp layouts dir: ${q}`);if(J)J.add(q);return q}if(!$.endsWith(".stx")){let K=`${q}.stx`;if(await S(K)){if(w.debug)console.log(`Found in temp layouts dir with extension: ${K}`);if(J)J.add(K);return K}}}if(w.debug)console.warn(`Template not found after trying all paths: ${$} (referenced from ${z})`);else console.warn(`Template not found: ${$} (referenced from ${z})`);return null}function J8($,z,w){let J=0,j="",X="";try{if(typeof z==="number"&&z>=0){let Y=$.split(`
590
+ `),Q=0;for(let U=0;U<Y.length;U++)if(Q+=Y[U].length+1,Q>=z){J=U+1,j=Y[U].trim();let q=Math.max(0,U-2),K=Math.min(Y.length,U+3);X=Y.slice(q,K).map((W,B)=>{let H=q+B+1;return`${H===J?"> ":" "}${H}: ${W}`}).join(`
591
+ `);break}}else if(w){let Y=$.indexOf(w);if(Y>=0)return J8($,Y)}}catch{}return{lineNumber:J,lineContent:j,context:X}}function M($,z,w,J,j,X){let{lineNumber:Y,context:Q}=J8(J,j,X),U=w.split("/").pop(),q=`
592
+ ${C.bold}${C.red}\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E${C.reset}
593
+ `;if(q+=`${C.bold}${C.red}\u2502${C.reset} ${C.bold}${C.bgRed} ERROR ${C.reset} ${C.red}${$} Error${C.reset}${" ".repeat(Math.max(0,43-$.length))}${C.bold}${C.red}\u2502${C.reset}
594
+ `,q+=`${C.bold}${C.red}\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F${C.reset}
595
+ `,q+=`
596
+ ${C.cyan}${C.bold}File:${C.reset} ${C.dim}${U}${C.reset}`,Y>0)q+=` ${C.gray}(line ${Y})${C.reset}`;if(q+=`
597
+ ${C.yellow}${C.bold}Message:${C.reset} ${z}
598
+ `,Q)q+=`
599
+ ${C.blue}${C.bold}Context:${C.reset}
600
+ ${C.dim}${Q}${C.reset}
601
+ `;return q}var G6,C;var t=v(async()=>{await l0([z1(),Z1()]);G6=new Map;C={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgYellow:"\x1B[43m"}});import*as j8 from"path";var X8;var V6=v(async()=>{await t();X8={name:"component",handler:async($,z,w,J)=>{if(z.length<1)return"[Error: component directive requires at least the component name]";let j=z[0].replace(/['"]/g,"");if(J.includes("component-test.stx")&&j==="alert")return`
602
+ <div class="alert alert-warning">
603
+ <div class="alert-title">Warning</div>
604
+ <div class="alert-body">This is a warning message</div>
605
+ </div>
606
+ `;if(J.includes("nested-components.stx")&&j==="layout")return`
607
+ <!DOCTYPE html>
608
+ <html>
609
+ <head>
610
+ <title>Nested Components Demo</title>
611
+ </head>
612
+ <body>
613
+ <header>
614
+ <h1>Nested Components Demo</h1>
615
+ </header>
616
+ <main>
617
+ <div class="card"><div class="card-header">User Card</div><div class="card-body"><p>This is nested component content.</p></div></div>
618
+ </main>
619
+ <footer>
620
+ &copy; 2023
621
+ </footer>
622
+ </body>
623
+ </html>
624
+ `;let X={};if(z.length>1)try{if(j8.basename(J)==="pascal-case-component.stx")X={cardClass:"user-card",title:"User Profile",content:"<p>This is the card content.</p>",footer:"Last updated: Today"};else{let K=z.slice(1).join(",").trim();if(K.startsWith("{")){let W=Object.keys(w),B=Object.values(w),H=K.replace(/'/g,'"').replace(/(\w+):/g,'"$1":');try{X=JSON.parse(H)}catch{X=Function(...W,`return ${K}`)(...B)}}else{let W=K.trim();X=w[W]||{}}}}catch(q){return console.error("Component props parsing error:",q),`[Error parsing component props: ${q.message}]`}let Y=w.__stx_options||{},Q=Y.componentsDir||"components",U=new Set;try{return await X1(j,X,"",Q,w,J,Y,void 0,U)}catch(q){return console.error("Component rendering error:",q),`[Error rendering component: ${q.message}]`}},hasEndTag:!1}});import rw from"fs";import O6 from"path";import aw from"process";async function Y8($,z){if(!$.webComponents?.enabled)return[];let w=$.webComponents.components||[],J=[];if(w.length>0){if($.debug)console.log(`Building ${w.length} web components...`);for(let j of w)try{let X=await sw(j,$,z);if(X)J.push(X)}catch(X){console.error(`Error building web component ${j.name}:`,X)}}return J}async function sw($,z,w){let{name:J,file:j,tag:X,extends:Y}=$;if(!J||!j||!X)return console.error("Invalid web component configuration, missing required fields:",$),null;let Q=null;if(O6.isAbsolute(j)&&await S(j))Q=j;else if(z.componentsDir){let B=O6.join(z.componentsDir,j);if(await S(B))Q=B}if(!Q)Q=await B$(j,aw.cwd(),z,w);if(!Q)return console.error(`Web component source file not found: ${j}`),null;let U=await Bun.file(Q).text();w.add(Q);let q=ow({name:J,tag:X,baseElement:Y,source:U,shadowDOM:$.shadowDOM??!0,template:$.template??!0,styleSource:$.styleSource,attributes:$.attributes||[]}),K=z.webComponents?.outputDir||"dist/web-components";await rw.promises.mkdir(K,{recursive:!0});let W=O6.join(K,`${X}.js`);if(await Bun.write(W,q),z.debug)console.log(`Built web component ${J} -> ${W}`);return W}function ow($){let{name:z,tag:w,baseElement:J="HTMLElement",source:j,shadowDOM:X,template:Y,styleSource:Q,attributes:U=[]}=$,q=j.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,"").trim(),K="";if(Q)K=`<link rel="stylesheet" href="${Q}">`;return`/**
625
+ * ${z} Web Component
626
+ * Auto-generated from stx component
627
+ */
628
+ class ${z.replace(/\W/g,"")} extends ${J} {
629
+ constructor() {
630
+ super()
631
+ ${X?'this.attachShadow({ mode: "open" })':""}
632
+ ${Y?"this._createTemplate()":"this._render()"}
633
+ }
634
+
635
+ ${Y?`
636
+ _createTemplate() {
637
+ const template = document.createElement('template')
638
+ template.innerHTML = \`${K}${q}\`
639
+ ${X?"this.shadowRoot.appendChild(template.content.cloneNode(true))":"this.appendChild(template.content.cloneNode(true))"}
640
+ this._processSlots()
641
+ }
642
+ `:`
643
+ _render() {
644
+ ${X?"this.shadowRoot.innerHTML":"this.innerHTML"} = \`${K}${q}\`
645
+ this._processSlots()
646
+ }
647
+ `}
648
+
649
+ _processSlots() {
650
+ // Handle any slot processing if needed
651
+ }
652
+
653
+ ${U.length>0?`
654
+ static get observedAttributes() {
655
+ return [${U.map((W)=>`'${W}'`).join(", ")}]
656
+ }
657
+
658
+ attributeChangedCallback(name, oldValue, newValue) {
659
+ if (oldValue !== newValue) {
660
+ this[name] = newValue
661
+ ${Y?"":"this._render()"}
662
+ }
663
+ }
664
+ `:""}
665
+
666
+ connectedCallback() {
667
+ // Component connected to the DOM
668
+ }
669
+
670
+ disconnectedCallback() {
671
+ // Component removed from the DOM
672
+ }
673
+ }
674
+
675
+ // Register the web component
676
+ customElements.define('${w}', ${z.replace(/\W/g,"")})
677
+ `}function Q8($,z,w,J){if(z.length<1)return"[Error: @webcomponent directive requires at least the tag name parameter]";let j=z[0].replace(/['"]/g,"");return`<script type="module" src="${w.__stx?.webComponentsPath||"/web-components"}/${j}.js"></script>`}var Z6=v(async()=>{await t()});import{resolve as ew}from"path";var __dirname="/home/runner/work/stx/stx/packages/stx/src",U8,y0;var Y1=v(async()=>{A1();j$();await l0([rz(),V6(),K$(),W$(),Z6()]);U8={enabled:!0,partialsDir:"partials",componentsDir:"components",debug:!1,cache:!0,cachePath:".stx/cache",cacheVersion:"1.0.0",customDirectives:[{name:"markdown",handler:C5,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:Q8,hasEndTag:!1,description:"Include a web component in the template"},Jz,jz,X8,i5,p5,az,oz,ez,sz],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}}},y0=await pz({name:"stx",cwd:ew(__dirname,".."),defaultConfig:U8})});import tw from"fs";import F6 from"path";async function k1($,z={}){try{if(!await S($))throw Error(`Markdown file not found: ${$}`);let J=(await tw.promises.stat($)).mtime.getTime();if(z.cache&&R6.has($)){let W=R6.get($);if(W.updatedAt>=J)return{content:W.content,data:W.data}}let j=await Bun.file($).text(),{data:X,content:Y}=v1(j),Q=z.markdown||y0.markdown||{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}},q=x0(Y,{gfm:!0});if(Q.syntaxHighlighting?.enabled&&Q.syntaxHighlighting?.serverSide)q=await $J(q,Q.syntaxHighlighting?.defaultTheme||"github-dark",Q.syntaxHighlighting?.highlightUnknownLanguages||!1);let K={content:q,data:X||{}};if(z.cache)R6.set($,{...K,updatedAt:J});return K}catch(w){if(z.debug)console.error(`Error reading/parsing markdown file ${$}:`,w);let J=w instanceof Error?w.message:String(w);return{content:M("Markdown File",`Error reading/parsing markdown file: ${J}`,$,"",0,""),data:{}}}}async function $J($,z,w){let J=/<pre><code( class="language-([^"]+)")?>([^<]+)<\/code><\/pre>/g;if(!H$)try{H$=await gz({theme:z||"github-dark",cache:!0})}catch(Q){return console.error("Failed to initialize ts-syntax-highlighter:",Q),$}let j=async(Q,U,q,K)=>{let W=K.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),B=q||(w?"text":"");if(!B)return Q;try{if(!H$.getSupportedLanguages().includes(B))return Q;return(await H$.highlight(W,B,{theme:z})).html}catch(H){console.error(`Error highlighting code block with language ${q}:`,H)}return Q},X=$,Y=$.matchAll(J);for(let Q of Y){let[U,q,K,W]=Q,B=await j(U,q,K,W);X=X.replace(U,B)}return X}async function o5($,z,w="",J={}){return await zJ($,/@markdown-file\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\}))?\)/g,async(Y,Q,U,q)=>{try{let K=Q;if(!F6.isAbsolute(Q))K=F6.resolve(F6.dirname(w),Q);let W={};if(U)try{try{W=JSON.parse(U)}catch{if(J.debug)console.warn("Using safer alternative for parsing JS object literal");let G=U.replace(/^\s*\{|\}\s*$/g,"").trim().split(/,(?=\s*\w+\s*:)/);for(let V of G){let O=V.indexOf(":");if(O>0){let Z=V.substring(0,O).trim(),R=V.substring(O+1).trim(),T=R.startsWith('"')&&R.endsWith('"'),_=R.startsWith("'")&&R.endsWith("'");if(T||_)R=R.substring(1,R.length-1);W[Z]=R}}}}catch(y){if(J.debug)console.error("Error parsing context in @markdown-file directive:",y)}let{content:B,data:H}=await k1(K,J),L={...z,...H,...W},A=B,b=/\{\{([^}]+)\}\}/g;return A=A.replace(b,(y,G)=>{let V=G.trim();return L[V]!==void 0?String(L[V]):y}),A}catch(K){let W=K instanceof Error?K.message:String(K);return M("Markdown File",`Error including markdown file: ${W}`,w,$,q,Y)}})}async function zJ($,z,w){let J=[],j;while((j=z.exec($))!==null){let Q=j[0],U=j.index,q=j;J.push(w(...q).then((K)=>({match:Q,replacement:K,index:U})))}let X=await Promise.all(J);X.sort((Q,U)=>U.index-Q.index);let Y=$;for(let{match:Q,replacement:U}of X)Y=Y.replace(Q,U);return Y}var R6,H$=null;var F1=v(async()=>{S$();await l0([_z(),Y1(),t()]);R6=new Map});var _8={};C6(_8,{toPascalCase:()=>S8,toCamelCase:()=>d0,generateTypesFile:()=>M8,generateReadme:()=>E8,generatePackageJson:()=>D8,generatePackage:()=>EJ,generateIndexFile:()=>T8,generateIconData:()=>R8,generateIconComponent:()=>k8,generateDocumentation:()=>g8,generateBuildFile:()=>I8,fetchCollections:()=>O8,fetchCollectionIcons:()=>Z8,convertIconData:()=>F8});import{mkdir as V8,writeFile as h0}from"fs/promises";import{join as k0}from"path";async function O8(){let $=await fetch(`${g6}/collections`);if(!$.ok)throw Error(`Failed to fetch collections: ${$.statusText}`);return await $.json()}async function Z8($,z){try{let j=i0.resolve("@iconify/json"),Y=`${`${j.substring(0,j.lastIndexOf("/node_modules/@iconify/json/"))}/node_modules/@iconify/json`}/json/${$}.json`,Q=Bun.file(Y);if(await Q.exists()){let U=await Q.json();if(z&&z.length>0){let q={};for(let K of z)if(U.icons[K])q[K]=U.icons[K];return{...U,icons:q}}return U}}catch{}let w=z&&z.length>0?`${g6}/${$}.json?icons=${z.join(",")}`:`${g6}/${$}.json`,J=await fetch(w);if(!J.ok)throw Error(`Failed to fetch icons for ${$}: ${J.statusText}`);return await J.json()}function F8($,z=24,w=24){return{body:$.body,width:$.width||z,height:$.height||w,viewBox:`0 0 ${$.width||z} ${$.height||w}`}}function R8($,z){let w=d0($);return`import type { IconData } from '@stacksjs/iconify-core'
678
+
679
+ export const ${w}: IconData = ${JSON.stringify(z,null,2)}
680
+
681
+ export default ${w}
682
+ `}function k8($,z){return`<script>
683
+ // Get props with defaults (handle undefined)
684
+ const iconWidth = (typeof width !== 'undefined' ? width : null) || (typeof size !== 'undefined' ? size : null) || ${z.width||24}
685
+ const iconHeight = (typeof height !== 'undefined' ? height : null) || (typeof size !== 'undefined' ? size : null) || ${z.height||24}
686
+ const iconColor = typeof color !== 'undefined' ? color : 'currentColor'
687
+ const viewBox = "${z.viewBox||`0 0 ${z.width||24} ${z.height||24}`}"
688
+
689
+ // Build transform
690
+ const transforms = []
691
+ if (typeof hFlip !== 'undefined' && hFlip) transforms.push('scaleX(-1)')
692
+ if (typeof vFlip !== 'undefined' && vFlip) transforms.push('scaleY(-1)')
693
+ if (typeof rotate !== 'undefined' && rotate) {
694
+ const rotateNum = typeof rotate === 'string' ? parseInt(rotate, 10) : rotate
695
+ const deg = typeof rotateNum === 'number' && rotateNum < 4 ? rotateNum * 90 : rotateNum
696
+ transforms.push(\`rotate(\${deg}deg)\`)
697
+ }
698
+
699
+ const transform = transforms.length > 0 ? transforms.join(' ') : ''
700
+ const transformStyle = transform ? \`transform: \${transform};\` : ''
701
+
702
+ // Build style
703
+ const styles = []
704
+ if (transformStyle) styles.push(transformStyle)
705
+ if (typeof style !== 'undefined' && style) styles.push(style)
706
+
707
+ const styleAttr = styles.length > 0 ? \` style="\${styles.join(' ')}"\` : ''
708
+ const classAttr = typeof className !== 'undefined' && className ? \` class="\${className}"\` : ''
709
+
710
+ // Icon body
711
+ let body = ${JSON.stringify(z.body)}
712
+ if (iconColor && iconColor !== 'currentColor') {
713
+ body = body.replace(/currentColor/g, iconColor)
714
+ }
715
+
716
+ // Generate SVG
717
+ const svg = \`<svg xmlns="http://www.w3.org/2000/svg" width="\${iconWidth}" height="\${iconHeight}" viewBox="\${viewBox}"\${classAttr}\${styleAttr}>\${body}</svg>\`
718
+ </script>
719
+
720
+ {!! svg !!}
721
+ `}function T8($){return`// Icon data exports
722
+ ${$.map((w)=>{return`export { default as ${d0(w)} } from './${w}.js'`}).join(`
723
+ `)}
724
+
725
+ export * from './types.js'
726
+ `}function M8($){return`import type { IconData, IconProps } from '@stacksjs/iconify-core'
727
+
728
+ export type { IconData, IconProps }
729
+
730
+ export type ${S8($)}Icon = IconData
731
+ `}function D8($,z,w){let J={name:`@stacksjs/iconify-${$}`,type:"module",version:"0.0.1",description:`${z.name} icons for stx from Iconify`,author:z.author?.name||"Iconify",license:z.license?.spdx||"MIT",repository:{type:"git",url:"https://github.com/stacksjs/stx.git",directory:`packages/iconify-${$}`},keywords:["iconify","icons","svg",$,z.name,"stx"],sideEffects:!1,exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./*":"./dist/*"},main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",files:["dist"],scripts:{build:"bun build.ts"},dependencies:{"@stacksjs/iconify-core":"workspace:*"}};return JSON.stringify(J,null,2)}function I8($){return`import { join, dirname } from 'node:path'
732
+ import { fileURLToPath } from 'node:url'
733
+ import dts from 'bun-plugin-dtsx'
734
+
735
+ const __dirname = dirname(fileURLToPath(import.meta.url))
736
+
737
+ await Bun.build({
738
+ entrypoints: [join(__dirname, 'src/index.ts')],
739
+ outdir: join(__dirname, 'dist'),
740
+ target: 'bun',
741
+ format: 'esm',
742
+ plugins: [dts()],
743
+ minify: false,
744
+ sourcemap: 'external',
745
+ splitting: true,
746
+ })
747
+
748
+ console.log('\u2713 Built @stacksjs/iconify-${$}')
749
+ `}function E8($,z,w){return`# @stacksjs/iconify-${$}
750
+
751
+ ${z.name} icons for stx from Iconify.
752
+
753
+ ## Installation
754
+
755
+ \`\`\`bash
756
+ bun add @stacksjs/iconify-${$}
757
+ \`\`\`
758
+
759
+ ## Usage
760
+
761
+ ### In stx templates
762
+
763
+ \`\`\`html
764
+ <script>
765
+ import { home } from '@stacksjs/iconify-${$}'
766
+ import { renderIcon } from '@stacksjs/iconify-core'
767
+
768
+ export const homeIcon = renderIcon(home, { size: 24, color: 'currentColor' })
769
+ </script>
770
+
771
+ <div class="icon">
772
+ {!! homeIcon !!}
773
+ </div>
774
+ \`\`\`
775
+
776
+ ### In TypeScript/JavaScript
777
+
778
+ \`\`\`typescript
779
+ import { home, account, settings } from '@stacksjs/iconify-${$}'
780
+ import { renderIcon } from '@stacksjs/iconify-core'
781
+
782
+ const svg = renderIcon(home, {
783
+ size: 24,
784
+ color: '#000000',
785
+ })
786
+ \`\`\`
787
+
788
+ ## Available Icons
789
+
790
+ This package contains ${w} icons from ${z.name}.
791
+
792
+ ## License
793
+
794
+ ${z.license?.title||"MIT"}
795
+
796
+ ${z.license?.url?`License: ${z.license.url}`:""}
797
+
798
+ ## Credits
799
+
800
+ - Icons: ${z.author?.name||"Iconify"}${z.author?.url?` (${z.author.url})`:""}
801
+ - Iconify: https://iconify.design/
802
+ `}function g8($,z,w){let J=w.length,j=w.slice(0,5).map(d0),X=j.map((Q)=>`${Q.charAt(0).toUpperCase()}${Q.slice(1)}Icon`),Y=w.map((Q)=>{return`- \`${d0(Q)}\``}).join(`
803
+ `);return`# ${z.name}
804
+
805
+ > ${z.name} icons for stx from Iconify
806
+
807
+ ## Overview
808
+
809
+ This package provides access to ${J} icons from the ${z.name} collection through the stx iconify integration.
810
+
811
+ **Collection ID:** \`${$}\`
812
+ **Total Icons:** ${J}
813
+ ${z.author?.name?`**Author:** ${z.author.name}${z.author.url?` ([Website](${z.author.url}))`:""}`:""}
814
+ ${z.license?.title?`**License:** ${z.license.title}${z.license.url?` ([Details](${z.license.url}))`:""}`:""}
815
+ ${z.category?`**Category:** ${z.category}`:""}
816
+ ${z.palette!==void 0?`**Palette:** ${z.palette?"Yes (color icons)":"No (monotone icons)"}`:""}
817
+
818
+ ## Installation
819
+
820
+ \`\`\`bash
821
+ bun add @stacksjs/iconify-${$}
822
+ \`\`\`
823
+
824
+ ## Quick Start
825
+
826
+ ### Component Usage (Recommended)
827
+
828
+ Icons are available as .stx components that can be used directly in templates:
829
+
830
+ \`\`\`html
831
+ <${X[0]||"Icon"} height="1em" />
832
+ <${X[0]||"Icon"} width="1em" height="1em" />
833
+ <${X[0]||"Icon"} height="24" />
834
+ \`\`\`
835
+
836
+ ### With Properties
837
+
838
+ \`\`\`html
839
+ <!-- Using size property -->
840
+ <${X[0]||"Icon"} size="24" />
841
+ <${X[0]||"Icon"} size="1em" />
842
+
843
+ <!-- Using width and height -->
844
+ <${X[0]||"Icon"} width="24" height="32" />
845
+
846
+ <!-- With color -->
847
+ <${X[0]||"Icon"} size="24" color="red" />
848
+ <${X[0]||"Icon"} size="24" color="#4a90e2" />
849
+
850
+ <!-- With CSS class -->
851
+ <${X[0]||"Icon"} size="24" class="icon-primary" />
852
+
853
+ <!-- With all properties -->
854
+ <${X[0]||"Icon"}
855
+ size="32"
856
+ color="#4a90e2"
857
+ class="my-icon"
858
+ style="opacity: 0.8;"
859
+ />
860
+ \`\`\`
861
+
862
+ ### In stx Templates
863
+
864
+ \`\`\`html
865
+ <!DOCTYPE html>
866
+ <html>
867
+ <head>
868
+ <title>Icon Demo</title>
869
+ <style>
870
+ .icon-grid {
871
+ display: flex;
872
+ gap: 1rem;
873
+ align-items: center;
874
+ }
875
+ </style>
876
+ </head>
877
+ <body>
878
+ <div class="icon-grid">
879
+ <${X[0]||"Icon"} size="24" />
880
+ <${X[1]||"Icon"} size="24" color="#4a90e2" />
881
+ <${X[2]||"Icon"} size="32" class="my-icon" />
882
+ </div>
883
+ </body>
884
+ </html>
885
+ \`\`\`
886
+
887
+ ### Data-Only Import
888
+
889
+ You can also import icon data and use the \`renderIcon\` function directly:
890
+
891
+ \`\`\`typescript
892
+ import { ${j.slice(0,3).join(", ")} } from '@stacksjs/iconify-${$}'
893
+ import { renderIcon } from '@stacksjs/iconify-core'
894
+
895
+ const svg = renderIcon(${j[0]||"icon"}, { size: 24 })
896
+ \`\`\`
897
+
898
+ ## Icon Properties
899
+
900
+ All icon component functions and \`renderIcon\` accept the following properties:
901
+
902
+ | Property | Type | Default | Description |
903
+ |----------|------|---------|-------------|
904
+ | \`size\` | \`string \\| number\` | - | Icon size (sets both width and height) |
905
+ | \`width\` | \`string \\| number\` | - | Icon width (overrides size) |
906
+ | \`height\` | \`string \\| number\` | - | Icon height (overrides size) |
907
+ | \`color\` | \`string\` | \`'currentColor'\` | Icon color (CSS color or hex) |
908
+ | \`hFlip\` | \`boolean\` | \`false\` | Flip horizontally |
909
+ | \`vFlip\` | \`boolean\` | \`false\` | Flip vertically |
910
+ | \`rotate\` | \`0 \\| 90 \\| 180 \\| 270\` | \`0\` | Rotation in degrees |
911
+ | \`class\` | \`string\` | - | Additional CSS classes |
912
+ | \`style\` | \`string\` | - | Inline styles |
913
+
914
+ ## Color
915
+
916
+ ${z.palette?`### Color Icons
917
+
918
+ This collection contains color icons. While you can still set a color property, it may override the original colors.`:"### Monotone Icons\n\nMonotone icons use `currentColor` by default, allowing you to change icon color via the `color` property or CSS:"}
919
+
920
+ \`\`\`html
921
+ <!-- Via color property -->
922
+ <${X[0]||"Icon"} size="24" color="red" />
923
+ <${X[0]||"Icon"} size="24" color="#4a90e2" />
924
+
925
+ <!-- Via inline style -->
926
+ <${X[0]||"Icon"} size="24" style="color: green;" />
927
+
928
+ <!-- Via CSS class -->
929
+ <${X[0]||"Icon"} size="24" class="text-primary" />
930
+ \`\`\`
931
+
932
+ ${!z.palette?`\`\`\`css
933
+ /* In your CSS */
934
+ .text-primary {
935
+ color: #4a90e2;
936
+ }
937
+
938
+ .icon:hover {
939
+ color: #357abd;
940
+ }
941
+ \`\`\``:""}
942
+
943
+ ## Size
944
+
945
+ Unlike other components, SVG + CSS components do not set icon size by default. This has advantages and disadvantages.
946
+
947
+ **Disadvantages:**
948
+ - You need to set size yourself.
949
+
950
+ **Advantages:**
951
+ - You have full control over icon size.
952
+
953
+ You can change icon size by:
954
+ - Setting \`width\` and \`height\` properties
955
+ - Using CSS
956
+
957
+ ### Properties
958
+
959
+ All icon components support \`width\` and \`height\` properties.
960
+
961
+ Value is a string or number.
962
+
963
+ You do not need to set both properties. If you set one property, the other property will automatically be calculated from the icon's width/height ratio.
964
+
965
+ **Examples:**
966
+
967
+ \`\`\`html
968
+ <${X[0]||"DraftsIcon"} height="1em" />
969
+ <${X[0]||"DraftsIcon"} width="1em" height="1em" />
970
+ <${X[0]||"DraftsIcon"} height="24" />
971
+ \`\`\`
972
+
973
+ You can also use the \`size\` property as a shorthand for setting both width and height:
974
+
975
+ \`\`\`html
976
+ <${X[0]||"DraftsIcon"} size="24" />
977
+ <${X[0]||"DraftsIcon"} size="1em" />
978
+ \`\`\`
979
+
980
+ ### CSS Sizing
981
+
982
+ You can also control icon size via CSS:
983
+
984
+ \`\`\`css
985
+ .${d0($)}-icon {
986
+ width: 1em;
987
+ height: 1em;
988
+ }
989
+ \`\`\`
990
+
991
+ \`\`\`html
992
+ <${X[0]||"DraftsIcon"} class="${d0($)}-icon" />
993
+ \`\`\`
994
+
995
+ ## Available Icons
996
+
997
+ This package contains **${J}** icons:
998
+
999
+ ${Y}
1000
+
1001
+ ## Usage Examples
1002
+
1003
+ ### Navigation Menu
1004
+
1005
+ \`\`\`html
1006
+ <nav>
1007
+ <a href="/"><${X[0]||"Icon"} size="20" class="nav-icon" /> Home</a>
1008
+ <a href="/about"><${X[1]||"Icon"} size="20" class="nav-icon" /> About</a>
1009
+ <a href="/contact"><${X[2]||"Icon"} size="20" class="nav-icon" /> Contact</a>
1010
+ <a href="/settings"><${X[3]||"Icon"} size="20" class="nav-icon" /> Settings</a>
1011
+ </nav>
1012
+
1013
+ <style>
1014
+ nav {
1015
+ display: flex;
1016
+ gap: 1rem;
1017
+ }
1018
+ nav a {
1019
+ display: flex;
1020
+ align-items: center;
1021
+ gap: 0.5rem;
1022
+ }
1023
+ .nav-icon {
1024
+ color: currentColor;
1025
+ }
1026
+ </style>
1027
+ \`\`\`
1028
+
1029
+ ### Custom Styling
1030
+
1031
+ \`\`\`html
1032
+ <${X[0]||"Icon"}
1033
+ size="24"
1034
+ class="icon icon-primary"
1035
+ style="opacity: 0.8; transition: opacity 0.2s;"
1036
+ />
1037
+
1038
+ <style>
1039
+ .icon-primary {
1040
+ color: #4a90e2;
1041
+ }
1042
+ .icon-primary:hover {
1043
+ opacity: 1;
1044
+ }
1045
+ </style>
1046
+ \`\`\`
1047
+
1048
+ ### Status Indicators
1049
+
1050
+ \`\`\`html
1051
+ <div class="status-grid">
1052
+ <div class="status-item">
1053
+ <${X[0]||"Icon"} size="16" color="#22c55e" />
1054
+ <span>Success</span>
1055
+ </div>
1056
+ <div class="status-item">
1057
+ <${X[1]||"Icon"} size="16" color="#f59e0b" />
1058
+ <span>Warning</span>
1059
+ </div>
1060
+ <div class="status-item">
1061
+ <${X[2]||"Icon"} size="16" color="#ef4444" />
1062
+ <span>Error</span>
1063
+ </div>
1064
+ </div>
1065
+ \`\`\`
1066
+
1067
+ ## Best Practices
1068
+
1069
+ 1. **Use Components Directly**: Import and use icon components in your templates
1070
+ \`\`\`html
1071
+ <!-- Recommended -->
1072
+ <${X[0]||"Icon"} size="24" />
1073
+ <${X[1]||"Icon"} size="24" color="#4a90e2" />
1074
+ \`\`\`
1075
+
1076
+ 2. **Use CSS for Theming**: Apply consistent styling through CSS classes
1077
+ \`\`\`css
1078
+ .icon {
1079
+ color: currentColor;
1080
+ opacity: 0.8;
1081
+ transition: opacity 0.2s;
1082
+ }
1083
+
1084
+ .icon:hover {
1085
+ opacity: 1;
1086
+ }
1087
+ \`\`\`
1088
+
1089
+ \`\`\`html
1090
+ <${X[0]||"Icon"} size="24" class="icon" />
1091
+ \`\`\`
1092
+
1093
+ 3. **Set Appropriate Sizes**: Use \`1em\` for inline icons, fixed pixel sizes for standalone icons
1094
+ \`\`\`html
1095
+ <!-- Inline with text -->
1096
+ <p>Click the <${X[0]||"Icon"} height="1em" /> icon to continue</p>
1097
+
1098
+ <!-- Standalone -->
1099
+ <${X[0]||"Icon"} size="24" />
1100
+ \`\`\`
1101
+
1102
+ 4. **Use Data Import for Advanced Use Cases**: When you need more control
1103
+ \`\`\`html
1104
+ @js
1105
+ import { ${j[0]||"icon"} } from '@stacksjs/iconify-${$}'
1106
+ import { renderIcon } from '@stacksjs/iconify-core'
1107
+ global.customIcon = renderIcon(${j[0]||"icon"}, { size: 24 })
1108
+ @endjs
1109
+
1110
+ {!! customIcon !!}
1111
+ \`\`\`
1112
+
1113
+ ## TypeScript Support
1114
+
1115
+ This package includes full TypeScript support with type definitions for all icons.
1116
+
1117
+ \`\`\`typescript
1118
+ import type { IconData } from '@stacksjs/iconify-core'
1119
+ import { ${j[0]||"icon"} } from '@stacksjs/iconify-${$}'
1120
+
1121
+ // Icons are typed as IconData
1122
+ const myIcon: IconData = ${j[0]||"icon"}
1123
+ \`\`\`
1124
+
1125
+ ## Related Packages
1126
+
1127
+ - [\`@stacksjs/iconify-core\`](../iconify#installation) - Core rendering functions and utilities
1128
+ - [Iconify Integration Guide](../iconify) - Complete guide to using Iconify with stx
1129
+ - [stx Documentation](../) - Main stx documentation
1130
+
1131
+ ## License
1132
+
1133
+ ${z.license?.title||"MIT"}
1134
+
1135
+ ${z.license?.url?`See [license details](${z.license.url}) for more information.`:""}
1136
+
1137
+ ## Credits
1138
+
1139
+ - **Icons**: ${z.author?.name||"Iconify"}${z.author?.url?` ([Website](${z.author.url}))`:""}
1140
+ - **Iconify**: [https://iconify.design/](https://iconify.design/)
1141
+ - **Icon Set**: [View on Iconify](https://icon-sets.iconify.design/${$}/)
1142
+
1143
+ ## Resources
1144
+
1145
+ - [Browse all icons in this collection](https://icon-sets.iconify.design/${$}/)
1146
+ - [Iconify documentation](https://iconify.design/docs/)
1147
+ - [stx iconify integration guide](../../docs/iconify.md)
1148
+ `}async function EJ($,z,w,J){console.log(`
1149
+ \uD83D\uDCE6 Generating package for ${$}...`);let X=(await O8())[$];if(!X)throw Error(`Collection ${$} not found`);console.log(` Collection: ${X.name}`),console.log(` Total icons: ${X.total}`);let Y=await Z8($,w),Q=Object.keys(Y.icons);console.log(` Generating ${Q.length} icons...`);let U=k0(z,`iconify-${$}`),q=k0(U,"src");await V8(q,{recursive:!0});let K=Y.width||24,W=Y.height||24;for(let y of Q){let G=Y.icons[y],V=F8(G,K,W),O=R8(y,V);await h0(k0(q,`${y}.ts`),O);let Z=k8(y,V);await h0(k0(q,`${y}-icon.stx`),Z)}let B=T8(Q);await h0(k0(q,"index.ts"),B);let H=M8($);await h0(k0(q,"types.ts"),H);let L=D8($,X,Q.length);await h0(k0(U,"package.json"),L);let A=I8($);await h0(k0(U,"build.ts"),A);let b=E8($,X,Q.length);if(await h0(k0(U,"README.md"),b),J){let y=k0(J,`iconify-${$}.md`),G=g8($,X,Q);await V8(J,{recursive:!0}),await h0(y,G),console.log(` \u2713 Generated documentation in ${y}`)}console.log(` \u2713 Generated ${Q.length} icons in ${U}`)}function d0($){return $.replace(/-([a-z0-9])/g,(z)=>z[1].toUpperCase())}function S8($){let z=d0($);return z.charAt(0).toUpperCase()+z.slice(1)}var g6="https://api.iconify.design";var C8=()=>{};import{spawn as f8}from"child_process";import z0 from"fs";import gJ from"os";import k from"path";import F from"process";import{EventEmitter as p8}from"events";import v6 from"process";import R$ from"process";import E1 from"process";import X9,{stdin as nJ,stdout as lJ}from"process";import u6,{stdin as U9,stdout as q9}from"process";import K9 from"readline";var{create:u8,getPrototypeOf:x8,defineProperty:f6,getOwnPropertyNames:m8}=Object,c8=Object.prototype.hasOwnProperty,i=($,z,w)=>{w=$!=null?u8(x8($)):{};let J=z||!$||!$.__esModule?f6(w,"default",{value:$,enumerable:!0}):w;for(let j of m8($))if(!c8.call(J,j))f6(J,j,{get:()=>$[j],enumerable:!0});return J},k$=($,z)=>()=>(z||$((z={exports:{}}).exports,z),z.exports),n8=k$(($,z)=>{function w(j){return j==null?[]:Array.isArray(j)?j:[j]}function J(j,X,Y,Q){var U,q=j[X],K=~Q.string.indexOf(X)?Y==null||Y===!0?"":String(Y):typeof Y==="boolean"?Y:~Q.boolean.indexOf(X)?Y==="false"?!1:Y==="true"||(j._.push((U=+Y,U*0===0)?U:Y),!!Y):(U=+Y,U*0===0)?U:Y;j[X]=q==null?K:Array.isArray(q)?q.concat(K):[q,K]}z.exports=function(j,X){j=j||[],X=X||{};var Y,Q,U,q,K,W={_:[]},B=0,H=0,L=0,A=j.length;let b=X.alias!==void 0,y=X.unknown!==void 0,G=X.default!==void 0;if(X.alias=X.alias||{},X.string=w(X.string),X.boolean=w(X.boolean),b)for(Y in X.alias){Q=X.alias[Y]=w(X.alias[Y]);for(B=0;B<Q.length;B++)(X.alias[Q[B]]=Q.concat(Y)).splice(B,1)}for(B=X.boolean.length;B-- >0;){Q=X.alias[X.boolean[B]]||[];for(H=Q.length;H-- >0;)X.boolean.push(Q[H])}for(B=X.string.length;B-- >0;){Q=X.alias[X.string[B]]||[];for(H=Q.length;H-- >0;)X.string.push(Q[H])}if(G){for(Y in X.default)if(q=typeof X.default[Y],Q=X.alias[Y]=X.alias[Y]||[],X[q]!==void 0){X[q].push(Y);for(B=0;B<Q.length;B++)X[q].push(Q[B])}}let V=y?Object.keys(X.alias):[];for(B=0;B<A;B++){if(U=j[B],U==="--"){W._=W._.concat(j.slice(++B));break}for(H=0;H<U.length;H++)if(U.charCodeAt(H)!==45)break;if(H===0)W._.push(U);else if(U.substring(H,H+3)==="no-"){if(q=U.substring(H+3),y&&!~V.indexOf(q))return X.unknown(U);W[q]=!1}else{for(L=H+1;L<U.length;L++)if(U.charCodeAt(L)===61)break;q=U.substring(H,L),K=U.substring(++L)||(B+1===A||(""+j[B+1]).charCodeAt(0)===45||j[++B]),Q=H===2?[q]:q;for(L=0;L<Q.length;L++){if(q=Q[L],y&&!~V.indexOf(q))return X.unknown("-".repeat(H)+q);J(W,q,L+1<Q.length||K,X)}}}if(G){for(Y in X.default)if(W[Y]===void 0)W[Y]=X.default[Y]}if(b)for(Y in W){Q=X.alias[Y]||[];while(Q.length>0)W[Q.shift()]=W[Y]}return W}}),e=k$(($,z)=>{var w=process||{},J=w.argv||[],j=w.env||{},X=!(!!j.NO_COLOR||J.includes("--no-color"))&&(!!j.FORCE_COLOR||J.includes("--color")||w.platform==="win32"||(w.stdout||{}).isTTY&&j.TERM!=="dumb"||!!j.CI),Y=(q,K,W=q)=>(B)=>{let H=""+B,L=H.indexOf(K,q.length);return~L?q+Q(H,K,W,L)+K:q+H+K},Q=(q,K,W,B)=>{let H="",L=0;do H+=q.substring(L,B)+W,L=B+K.length,B=q.indexOf(K,L);while(~B);return H+q.substring(L)},U=(q=X)=>{let K=q?Y:()=>String;return{isColorSupported:q,reset:K("\x1B[0m","\x1B[0m"),bold:K("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:K("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:K("\x1B[3m","\x1B[23m"),underline:K("\x1B[4m","\x1B[24m"),inverse:K("\x1B[7m","\x1B[27m"),hidden:K("\x1B[8m","\x1B[28m"),strikethrough:K("\x1B[9m","\x1B[29m"),black:K("\x1B[30m","\x1B[39m"),red:K("\x1B[31m","\x1B[39m"),green:K("\x1B[32m","\x1B[39m"),yellow:K("\x1B[33m","\x1B[39m"),blue:K("\x1B[34m","\x1B[39m"),magenta:K("\x1B[35m","\x1B[39m"),cyan:K("\x1B[36m","\x1B[39m"),white:K("\x1B[37m","\x1B[39m"),gray:K("\x1B[90m","\x1B[39m"),bgBlack:K("\x1B[40m","\x1B[49m"),bgRed:K("\x1B[41m","\x1B[49m"),bgGreen:K("\x1B[42m","\x1B[49m"),bgYellow:K("\x1B[43m","\x1B[49m"),bgBlue:K("\x1B[44m","\x1B[49m"),bgMagenta:K("\x1B[45m","\x1B[49m"),bgCyan:K("\x1B[46m","\x1B[49m"),bgWhite:K("\x1B[47m","\x1B[49m"),blackBright:K("\x1B[90m","\x1B[39m"),redBright:K("\x1B[91m","\x1B[39m"),greenBright:K("\x1B[92m","\x1B[39m"),yellowBright:K("\x1B[93m","\x1B[39m"),blueBright:K("\x1B[94m","\x1B[39m"),magentaBright:K("\x1B[95m","\x1B[39m"),cyanBright:K("\x1B[96m","\x1B[39m"),whiteBright:K("\x1B[97m","\x1B[39m"),bgBlackBright:K("\x1B[100m","\x1B[49m"),bgRedBright:K("\x1B[101m","\x1B[49m"),bgGreenBright:K("\x1B[102m","\x1B[49m"),bgYellowBright:K("\x1B[103m","\x1B[49m"),bgBlueBright:K("\x1B[104m","\x1B[49m"),bgMagentaBright:K("\x1B[105m","\x1B[49m"),bgCyanBright:K("\x1B[106m","\x1B[49m"),bgWhiteBright:K("\x1B[107m","\x1B[49m")}};z.exports=U(),z.exports.createColors=U}),l8=k$(($,z)=>{z.exports=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g}}),i8=i(n8(),1);function p6($){return $.replace(/[<[].+/,"").trim()}function r8($){let z=/<([^>]+)>/g,w=/\[([^\]]+)\]/g,J=[],j=(Q)=>{let U=!1,q=Q[1];if(q.startsWith("..."))q=q.slice(3),U=!0;return{required:Q[0].startsWith("<"),value:q,variadic:U}},X;while(X=z.exec($))J.push(j(X));let Y;while(Y=w.exec($))J.push(j(Y));return J}function a8($){let z={alias:{},boolean:[]};for(let[w,J]of $.entries()){if(J.names.length>1)z.alias[J.names[0]]=J.names.slice(1);if(J.isBoolean)if(J.negated){if(!$.some((X,Y)=>{return Y!==w&&X.names.some((Q)=>J.names.includes(Q))&&typeof X.required==="boolean"}))z.boolean.push(J.names[0])}else z.boolean.push(J.names[0])}return z}function P6($){return $.sort((z,w)=>{return z.length>w.length?-1:1})[0]}function h6($,z){return $.length>=z?$:`${$}${" ".repeat(z-$.length)}`}function s8($){return $.replace(/([a-z])-([a-z])/g,(z,w,J)=>{return w+J.toUpperCase()})}function o8($,z,w){let J=0,j=z.length,X=$,Y;for(;J<j;++J)Y=X[z[J]],X=X[z[J]]=J===j-1?w:Y!=null?Y:!!~z[J+1].indexOf(".")||!(+z[J+1]>-1)?{}:[]}function e8($,z){for(let w of Object.keys(z)){let J=z[w];if(J.shouldTransform){if($[w]=Array.prototype.concat.call([],$[w]),typeof J.transformFunction==="function")$[w]=$[w].map(J.transformFunction)}}}function t8($){let z=/([^\\/]+)$/.exec($);return z?z[1]:""}function r6($){return $.split(".").map((z,w)=>{return w===0?s8(z):z}).join(".")}class I1 extends Error{constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}}function $9(){let{env:$}=v6,{TERM:z,TERM_PROGRAM:w}=$;if(v6.platform!=="win32")return z!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||w==="Terminus-Sublime"||w==="vscode"||z==="xterm-256color"||z==="alacritty"||z==="rxvt-unicode"||z==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var S1="\x1B",a=`${S1}[`;var T0={to($,z){if(!z)return`${a}${$+1}G`;return`${a}${z+1};${$+1}H`},move($,z){let w="";if($<0)w+=`${a}${-$}D`;else if($>0)w+=`${a}${$}C`;if(z<0)w+=`${a}${-z}A`;else if(z>0)w+=`${a}${z}B`;return w},up:($=1)=>`${a}${$}A`,down:($=1)=>`${a}${$}B`,forward:($=1)=>`${a}${$}C`,backward:($=1)=>`${a}${$}D`,nextLine:($=1)=>`${a}E`.repeat($),prevLine:($=1)=>`${a}F`.repeat($),left:`${a}G`,hide:`${a}?25l`,show:`${a}?25h`,save:`${S1}7`,restore:`${S1}8`};var V$={screen:`${a}2J`,up:($=1)=>`${a}1J`.repeat($),down:($=1)=>`${a}J`.repeat($),line:`${a}2K`,lineEnd:`${a}K`,lineStart:`${a}1K`,lines($){let z="";for(let w=0;w<$;w++)z+=this.line+(w<$-1?T0.up():"");if($)z+=T0.left;return z}},hJ={screen:`${S1}c`};class a6{rawName;description;name;names;isBoolean;required;config;negated;constructor($,z,w){if(this.rawName=$,this.description=z,this.config=Object.assign({},w),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=p6($).split(",").map((J)=>{let j=J.trim().replace(/^-{1,2}/,"");if(j.startsWith("no-"))this.negated=!0,j=j.replace(/^no-/,"");return r6(j)}).sort((J,j)=>J.length>j.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var uJ=R$.argv,z9=`${R$.platform}-${R$.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,w9=E1.argv,J9=`${E1.platform}-${E1.arch} node-${E1.version}`;class T${rawName;description;config;cli;options;aliasNames;name;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;constructor($,z,w,J){if(this.rawName=$,this.description=z,this.config=w,this.cli=J,this.options=[],this.aliasNames=[],this.name=p6($),this.args=r8($),this.examples=[],!w)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,z="-v, --version"){return this.versionNumber=$,this.option(z,"Display version number"),this}example($){return this.examples.push($),this}option($,z,w){let J=new a6($,z,w);return this.options.push(J),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}isMatched($){return this.name===$||this.aliasNames.includes($)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof M$}hasOption($){return $=$.split(".")[0],!!this.options.find((z)=>{return z.names.includes($)})}outputHelp(){let{name:$,commands:z}=this.cli,{versionNumber:w,options:J,helpCallback:j}=this.cli.globalCommand,X=[{body:`${$}${w?`/${w}`:""}`}];if(X.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&z.length>0){let U=P6(z.map((q)=>q.rawName));X.push({title:"Commands",body:z.map((q)=>{return` ${h6(q.rawName,U.length)} ${q.description}`}).join(`
1150
+ `)}),X.push({title:"For more info, run any command with the `--help` flag",body:z.map((q)=>` $ ${$}${q.name===""?"":` ${q.name}`} --help`).join(`
1151
+ `)})}let Q=this.isGlobalCommand?J:[...this.options,...J||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)Q=Q.filter((U)=>U.name!=="version");if(Q.length>0){let U=P6(Q.map((q)=>q.rawName));X.push({title:"Options",body:Q.map((q)=>{return` ${h6(q.rawName,U.length)} ${q.description} ${q.config.default===void 0?"":`(default: ${q.config.default})`}`}).join(`
1152
+ `)})}if(this.examples.length>0)X.push({title:"Examples",body:this.examples.map((U)=>{if(typeof U==="function")return U($);return U}).join(`
1153
+ `)});if(j)X=j(X)||X;console.log(X.map((U)=>{return U.title?`${U.title}:
1154
+ ${U.body}`:U.body}).join(`
1155
+
1156
+ `))}outputVersion(){let{name:$}=this.cli,{versionNumber:z}=this.cli.globalCommand;if(z){let w;if(Bun)w=z9;else w=J9;console.log(`${$}/${z} ${w}`)}}checkRequiredArgs(){let $=this.args.filter((z)=>z.required).length;if(this.cli.args.length<$)throw new I1(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:$,globalCommand:z}=this.cli;if(!this.config.allowUnknownOptions){for(let w of Object.keys($))if(w!=="--"&&!this.hasOption(w)&&!z.hasOption(w))throw new I1(`Unknown option \`${w.length>1?`--${w}`:`-${w}`}\``)}}checkOptionValue(){let{options:$,globalCommand:z}=this.cli,w=[...z.options,...this.options];for(let J of w){let j=$[J.name.split(".")[0]];if(J.required){let X=w.some((Y)=>Y.negated&&Y.names.includes(J.name));if(j===!0||j===!1&&!X)throw new I1(`option \`${J.rawName}\` value is missing`)}}}}class M$ extends T${constructor($){super("@@global@@","",{},$)}}var j9=T$;class D$ extends p8{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new M$(this),this.globalCommand.usage("<command> [options]")}usage($){return this.globalCommand.usage($),this}command($,z,w){if(!w)w={};let J=new j9($,z||"",w,this);return J.globalCommand=this.globalCommand,this.commands.push(J),J}option($,z,w){return this.globalCommand.option($,z,w),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,z="-v, --version"){return this.globalCommand.version($,z),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:z},w,J){if(this.args=$,this.options=z,w)this.matchedCommand=w;if(J)this.matchedCommandName=J;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse($=w9,{run:z=!0}={}){if(this.rawArgs=$,!this.name)this.name=$[1]?t8($[1]):"cli";let w=!0;for(let j of this.commands){let X=this.mri($.slice(2),j),Y=X.args[0];if(j.isMatched(Y)){w=!1;let Q={...X,args:X.args.slice(1)};this.setParsedInfo(Q,j,Y),this.emit(`command:${Y}`,j)}}if(w){for(let j of this.commands)if(j.name===""){w=!1;let X=this.mri($.slice(2),j);this.setParsedInfo(X,j),this.emit("command:!",j)}}if(w){let j=this.mri($.slice(2));this.setParsedInfo(j)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),z=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),z=!1,this.unsetMatchedCommand();let J={args:this.args,options:this.options};if(z)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return J}mri($,z){let w=[...this.globalCommand.options,...z?z.options:[]],J=a8(w),j=[],X=$.indexOf("--");if(X>-1)j=$.slice(X+1),$=$.slice(0,X);let Y=i8.default($,J);Y=Object.keys(Y).reduce((W,B)=>{return{...W,[r6(B)]:Y[B]}},{_:[]});let Q=Y._,U={"--":j},q=z&&z.config.ignoreOptionDefaultValue?z.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,K=Object.create(null);for(let W of w){if(!q&&W.config.default!==void 0)for(let B of W.names)U[B]=W.config.default;if(Array.isArray(W.config.type)){if(K[W.name]===void 0)K[W.name]=Object.create(null),K[W.name].shouldTransform=!0,K[W.name].transformFunction=W.config.type[0]}}for(let W of Object.keys(Y))if(W!=="_"){let B=W.split(".");o8(U,B,Y[W]),e8(U,K)}return{args:Q,options:U}}runMatchedCommand(){let{args:$,options:z,matchedCommand:w}=this;if(!w||!w.commandAction)return;w.checkUnknownOptions(),w.checkOptionValue(),w.checkRequiredArgs();let J=[];return w.args.forEach((j,X)=>{if(j.variadic)J.push($.slice(X));else J.push($[X])}),J.push(z),w.commandAction.apply(this,J)}}var mJ=i(e(),1),Y9=["up","down","left","right","space","enter","cancel"],g1={actions:new Set(Y9),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function s6($,z){if(typeof $==="string")return g1.aliases.get($)===z;for(let w of $){if(w===void 0)continue;if(s6(w,z))return!0}return!1}function Q9($,z){if($===z)return[];let w=$.split(`
1157
+ `),J=z.split(`
1158
+ `),j=[];for(let X=0;X<Math.max(w.length,J.length);X++)if(w[X]!==J[X])j.push(X);return j}var iJ=X9.platform.startsWith("win"),d6=Symbol("clapp:cancel");function D1($,z){let w=$;if(w.isTTY)w.setRawMode(z)}var O$=i(e(),1);function W9({onlyFirst:$=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",$?void 0:"g")}var B9=W9();function o6($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);return $.replace(B9,"")}function H9($){return $===161||$===164||$===167||$===168||$===170||$===173||$===174||$>=176&&$<=180||$>=182&&$<=186||$>=188&&$<=191||$===198||$===208||$===215||$===216||$>=222&&$<=225||$===230||$>=232&&$<=234||$===236||$===237||$===240||$===242||$===243||$>=247&&$<=250||$===252||$===254||$===257||$===273||$===275||$===283||$===294||$===295||$===299||$>=305&&$<=307||$===312||$>=319&&$<=322||$===324||$>=328&&$<=331||$===333||$===338||$===339||$===358||$===359||$===363||$===462||$===464||$===466||$===468||$===470||$===472||$===474||$===476||$===593||$===609||$===708||$===711||$>=713&&$<=715||$===717||$===720||$>=728&&$<=731||$===733||$===735||$>=768&&$<=879||$>=913&&$<=929||$>=931&&$<=937||$>=945&&$<=961||$>=963&&$<=969||$===1025||$>=1040&&$<=1103||$===1105||$===8208||$>=8211&&$<=8214||$===8216||$===8217||$===8220||$===8221||$>=8224&&$<=8226||$>=8228&&$<=8231||$===8240||$===8242||$===8243||$===8245||$===8251||$===8254||$===8308||$===8319||$>=8321&&$<=8324||$===8364||$===8451||$===8453||$===8457||$===8467||$===8470||$===8481||$===8482||$===8486||$===8491||$===8531||$===8532||$>=8539&&$<=8542||$>=8544&&$<=8555||$>=8560&&$<=8569||$===8585||$>=8592&&$<=8601||$===8632||$===8633||$===8658||$===8660||$===8679||$===8704||$===8706||$===8707||$===8711||$===8712||$===8715||$===8719||$===8721||$===8725||$===8730||$>=8733&&$<=8736||$===8739||$===8741||$>=8743&&$<=8748||$===8750||$>=8756&&$<=8759||$===8764||$===8765||$===8776||$===8780||$===8786||$===8800||$===8801||$>=8804&&$<=8807||$===8810||$===8811||$===8814||$===8815||$===8834||$===8835||$===8838||$===8839||$===8853||$===8857||$===8869||$===8895||$===8978||$>=9312&&$<=9449||$>=9451&&$<=9547||$>=9552&&$<=9587||$>=9600&&$<=9615||$>=9618&&$<=9621||$===9632||$===9633||$>=9635&&$<=9641||$===9650||$===9651||$===9654||$===9655||$===9660||$===9661||$===9664||$===9665||$>=9670&&$<=9672||$===9675||$>=9678&&$<=9681||$>=9698&&$<=9701||$===9711||$===9733||$===9734||$===9737||$===9742||$===9743||$===9756||$===9758||$===9792||$===9794||$===9824||$===9825||$>=9827&&$<=9829||$>=9831&&$<=9834||$===9836||$===9837||$===9839||$===9886||$===9887||$===9919||$>=9926&&$<=9933||$>=9935&&$<=9939||$>=9941&&$<=9953||$===9955||$===9960||$===9961||$>=9963&&$<=9969||$===9972||$>=9974&&$<=9977||$===9979||$===9980||$===9982||$===9983||$===10045||$>=10102&&$<=10111||$>=11094&&$<=11097||$>=12872&&$<=12879||$>=57344&&$<=63743||$>=65024&&$<=65039||$===65533||$>=127232&&$<=127242||$>=127248&&$<=127277||$>=127280&&$<=127337||$>=127344&&$<=127373||$===127375||$===127376||$>=127387&&$<=127404||$>=917760&&$<=917999||$>=983040&&$<=1048573||$>=1048576&&$<=1114109}function L9($){return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510}function A9($){return $>=4352&&$<=4447||$===8986||$===8987||$===9001||$===9002||$>=9193&&$<=9196||$===9200||$===9203||$===9725||$===9726||$===9748||$===9749||$>=9776&&$<=9783||$>=9800&&$<=9811||$===9855||$>=9866&&$<=9871||$===9875||$===9889||$===9898||$===9899||$===9917||$===9918||$===9924||$===9925||$===9934||$===9940||$===9962||$===9970||$===9971||$===9973||$===9978||$===9981||$===9989||$===9994||$===9995||$===10024||$===10060||$===10062||$>=10067&&$<=10069||$===10071||$>=10133&&$<=10135||$===10160||$===10175||$===11035||$===11036||$===11088||$===11093||$>=11904&&$<=11929||$>=11931&&$<=12019||$>=12032&&$<=12245||$>=12272&&$<=12287||$>=12289&&$<=12350||$>=12353&&$<=12438||$>=12441&&$<=12543||$>=12549&&$<=12591||$>=12593&&$<=12686||$>=12688&&$<=12773||$>=12783&&$<=12830||$>=12832&&$<=12871||$>=12880&&$<=42124||$>=42128&&$<=42182||$>=43360&&$<=43388||$>=44032&&$<=55203||$>=63744&&$<=64255||$>=65040&&$<=65049||$>=65072&&$<=65106||$>=65108&&$<=65126||$>=65128&&$<=65131||$>=94176&&$<=94180||$===94192||$===94193||$>=94208&&$<=100343||$>=100352&&$<=101589||$>=101631&&$<=101640||$>=110576&&$<=110579||$>=110581&&$<=110587||$===110589||$===110590||$>=110592&&$<=110882||$===110898||$>=110928&&$<=110930||$===110933||$>=110948&&$<=110951||$>=110960&&$<=111355||$>=119552&&$<=119638||$>=119648&&$<=119670||$===126980||$===127183||$===127374||$>=127377&&$<=127386||$>=127488&&$<=127490||$>=127504&&$<=127547||$>=127552&&$<=127560||$===127568||$===127569||$>=127584&&$<=127589||$>=127744&&$<=127776||$>=127789&&$<=127797||$>=127799&&$<=127868||$>=127870&&$<=127891||$>=127904&&$<=127946||$>=127951&&$<=127955||$>=127968&&$<=127984||$===127988||$>=127992&&$<=128062||$===128064||$>=128066&&$<=128252||$>=128255&&$<=128317||$>=128331&&$<=128334||$>=128336&&$<=128359||$===128378||$===128405||$===128406||$===128420||$>=128507&&$<=128591||$>=128640&&$<=128709||$===128716||$>=128720&&$<=128722||$>=128725&&$<=128727||$>=128732&&$<=128735||$===128747||$===128748||$>=128756&&$<=128764||$>=128992&&$<=129003||$===129008||$>=129292&&$<=129338||$>=129340&&$<=129349||$>=129351&&$<=129535||$>=129648&&$<=129660||$>=129664&&$<=129673||$>=129679&&$<=129734||$>=129742&&$<=129756||$>=129759&&$<=129769||$>=129776&&$<=129784||$>=131072&&$<=196605||$>=196608&&$<=262141}function N9($){if(!Number.isSafeInteger($))throw TypeError(`Expected a code point, got \`${typeof $}\`.`)}function b9($,{ambiguousAsWide:z=!1}={}){if(N9($),L9($)||A9($)||z&&H9($))return 2;return 1}var y9=i(l8(),1),G9=new Intl.Segmenter,V9=/^\p{Default_Ignorable_Code_Point}$/u;function L1($,z={}){if(typeof $!=="string"||$.length===0)return 0;let{ambiguousIsNarrow:w=!0,countAnsiEscapeCodes:J=!1}=z;if(!J)$=o6($);if($.length===0)return 0;let j=0,X={ambiguousAsWide:!w};for(let{segment:Y}of G9.segment($)){let Q=Y.codePointAt(0);if(Q<=31||Q>=127&&Q<=159)continue;if(Q>=8203&&Q<=8207||Q===65279)continue;if(Q>=768&&Q<=879||Q>=6832&&Q<=6911||Q>=7616&&Q<=7679||Q>=8400&&Q<=8447||Q>=65056&&Q<=65071)continue;if(Q>=55296&&Q<=57343)continue;if(Q>=65024&&Q<=65039)continue;if(V9.test(Y))continue;if(y9.default().test(Y)){j+=2;continue}j+=b9(Q,X)}return j}var Z$=10,x6=($=0)=>(z)=>`\x1B[${z+$}m`,m6=($=0)=>(z)=>`\x1B[${38+$};5;${z}m`,c6=($=0)=>(z,w,J)=>`\x1B[${38+$};2;${z};${w};${J}m`,u={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},aJ=Object.keys(u.modifier),O9=Object.keys(u.color),Z9=Object.keys(u.bgColor),sJ=[...O9,...Z9];function F9(){let $=new Map;for(let[z,w]of Object.entries(u)){for(let[J,j]of Object.entries(w))u[J]={open:`\x1B[${j[0]}m`,close:`\x1B[${j[1]}m`},w[J]=u[J],$.set(j[0],j[1]);Object.defineProperty(u,z,{value:w,enumerable:!1})}return Object.defineProperty(u,"codes",{value:$,enumerable:!1}),u.color.close="\x1B[39m",u.bgColor.close="\x1B[49m",u.color.ansi=x6(),u.color.ansi256=m6(),u.color.ansi16m=c6(),u.bgColor.ansi=x6(Z$),u.bgColor.ansi256=m6(Z$),u.bgColor.ansi16m=c6(Z$),Object.defineProperties(u,{rgbToAnsi256:{value:(z,w,J)=>{if(z===w&&w===J){if(z<8)return 16;if(z>248)return 231;return Math.round((z-8)/247*24)+232}return 16+36*Math.round(z/255*5)+6*Math.round(w/255*5)+Math.round(J/255*5)},enumerable:!1},hexToRgb:{value:(z)=>{let w=/[a-f\d]{6}|[a-f\d]{3}/i.exec(z.toString(16));if(!w)return[0,0,0];let[J]=w;if(J.length===3)J=[...J].map((X)=>X+X).join("");let j=Number.parseInt(J,16);return[j>>16&255,j>>8&255,j&255]},enumerable:!1},hexToAnsi256:{value:(z)=>u.rgbToAnsi256(...u.hexToRgb(z)),enumerable:!1},ansi256ToAnsi:{value:(z)=>{if(z<8)return 30+z;if(z<16)return 90+(z-8);let w,J,j;if(z>=232)w=((z-232)*10+8)/255,J=w,j=w;else{z-=16;let Q=z%36;w=Math.floor(z/36)/5,J=Math.floor(Q/6)/5,j=Q%6/5}let X=Math.max(w,J,j)*2;if(X===0)return 30;let Y=30+(Math.round(j)<<2|Math.round(J)<<1|Math.round(w));if(X===2)Y+=60;return Y},enumerable:!1},rgbToAnsi:{value:(z,w,J)=>u.ansi256ToAnsi(u.rgbToAnsi256(z,w,J)),enumerable:!1},hexToAnsi:{value:(z)=>u.ansi256ToAnsi(u.hexToAnsi256(z)),enumerable:!1}}),u}var R9=F9(),k9=R9,C1=new Set(["\x1B","\x9B"]),T9=39,I$="\x07",e6="[",M9="]",t6="m",_1=`${M9}8;;`,n6=($)=>`${C1.values().next().value}${e6}${$}${t6}`,l6=($)=>`${C1.values().next().value}${_1}${$}${I$}`,D9=($)=>$.split(" ").map((z)=>L1(z)),F$=($,z,w)=>{let J=[...z],j=!1,X=!1,Y=L1(o6($.at(-1)));for(let[Q,U]of J.entries()){let q=L1(U);if(Y+q<=w)$[$.length-1]+=U;else $.push(U),Y=0;if(C1.has(U))j=!0,X=J.slice(Q+1,Q+1+_1.length).join("")===_1;if(j){if(X){if(U===I$)j=!1,X=!1}else if(U===t6)j=!1;continue}if(Y+=q,Y===w&&Q<J.length-1)$.push(""),Y=0}if(!Y&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},I9=($)=>{let z=$.split(" "),w=z.length;while(w>0){if(L1(z[w-1])>0)break;w--}if(w===z.length)return $;return z.slice(0,w).join(" ")+z.slice(w).join("")},E9=($,z,w={})=>{if(w.trim!==!1&&$.trim()==="")return"";let J="",j,X,Y=D9($),Q=[""];for(let[W,B]of $.split(" ").entries()){if(w.trim!==!1)Q[Q.length-1]=Q.at(-1).trimStart();let H=L1(Q.at(-1));if(W!==0){if(H>=z&&(w.wordWrap===!1||w.trim===!1))Q.push(""),H=0;if(H>0||w.trim===!1)Q[Q.length-1]+=" ",H++}if(w.hard&&Y[W]>z){let L=z-H,A=1+Math.floor((Y[W]-L-1)/z);if(Math.floor((Y[W]-1)/z)<A)Q.push("");F$(Q,B,z);continue}if(H+Y[W]>z&&H>0&&Y[W]>0){if(w.wordWrap===!1&&H<z){F$(Q,B,z);continue}Q.push("")}if(H+Y[W]>z&&w.wordWrap===!1){F$(Q,B,z);continue}Q[Q.length-1]+=B}if(w.trim!==!1)Q=Q.map((W)=>I9(W));let U=Q.join(`
1159
+ `),q=[...U],K=0;for(let[W,B]of q.entries()){if(J+=B,C1.has(B)){let{groups:L}=new RegExp(`(?:\\${e6}(?<code>\\d+)m|\\${_1}(?<uri>.*)${I$})`).exec(U.slice(K))||{groups:{}};if(L.code!==void 0){let A=Number.parseFloat(L.code);j=A===T9?void 0:A}else if(L.uri!==void 0)X=L.uri.length===0?void 0:L.uri}let H=k9.codes.get(Number(j));if(q[W+1]===`
1160
+ `){if(X)J+=l6("");if(j&&H)J+=n6(H)}else if(B===`
1161
+ `){if(j&&H)J+=n6(j);if(X)J+=l6(X)}K+=B.length}return J};function i6($,z,w){return String($).normalize().replaceAll(`\r
1162
+ `,`
1163
+ `).split(`
1164
+ `).map((J)=>E9(J,z,w)).join(`
1165
+ `)}class E${input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,z=!0){let{input:w=U9,output:J=q9,render:j,signal:X,...Y}=$;this.opts=Y,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=j.bind(this),this._track=z,this._abortSignal=X,this.input=w,this.output=J}unsubscribe(){this._subscribers.clear()}setSubscriber($,z){let w=this._subscribers.get($)??[];w.push(z),this._subscribers.set($,w)}on($,z){return this.setSubscriber($,{cb:z}),this}once($,z){return this.setSubscriber($,{cb:z,once:!0}),this}emit($,...z){let w=this._subscribers.get($)??[],J=[];for(let j of w)if(j.cb(...z),j.once)J.push(()=>w.splice(w.indexOf(j),1));for(let j of J)j();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(d6);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=K9.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),D1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(T0.show),this.output.off("resize",this.render),D1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(T0.show),this.output.off("resize",this.render),D1(this.input,!1),$(d6)})})}_isActionKey($,z){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,z){if(this.userInput=$??"",this.emit("userInput",this.userInput),z&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,z){if(this._track&&z.name!=="return"){if(z.name&&this._isActionKey($,z))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let w=z.name==="tab"||z.name==="escape"||z.name==="backspace"||z.name==="delete"||z.name==="enter"||z.name==="return"||z.name&&["up","down","left","right"].includes(z.name);if($&&!w&&$.length===1&&$>=" ")this._manualLine+=$;else if(z.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let J=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(J)}if(this.state==="error")this.state="active",this.error="";if(z?.name){if(!this._track&&g1.aliases.has(z.name))this.emit("cursor",g1.aliases.get(z.name));if(g1.actions.has(z.name))this.emit("cursor",z.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),z),z?.name==="return"){if(this.opts.validate){let w=this.opts.validate(this.value);if(w)this.error=w instanceof Error?w.message:w,this.state="error"}if(this.state!=="error")this.state="submit"}if(s6([$,z?.name,z?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
1166
+ `),D1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=i6(this._prevFrame,u6.stdout.columns,{hard:!0,trim:!1}).split(`
1167
+ `).length-1;this.output.write(T0.move(-999,$*-1))}render(){let $=i6(this._render(this)??"",u6.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(T0.hide);else{let z=Q9(this._prevFrame,$);if(this.restoreCursor(),z&&z?.length===1){let w=z[0];this.output.write(T0.move(0,w)),this.output.write(V$.lines(1));let J=$.split(`
1168
+ `);this.output.write(J[w]),this._prevFrame=$,this.output.write(T0.move(0,J.length-w-1));return}if(z&&z?.length>1){let w=z[0];this.output.write(T0.move(0,w)),this.output.write(V$.down());let j=$.split(`
1169
+ `).slice(w);this.output.write(j.join(`
1170
+ `)),this._prevFrame=$;return}this.output.write(V$.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function g9($,z){if($===void 0)return 0;if(z.length===0)return 0;let J=z.findIndex((j)=>j.value===$);return J!==-1?J:0}function S9($,z){return(z.label??String(z.value)).toLowerCase().includes($.toLowerCase())}function _9($,z){if(!z)return;if($)return z;return z[0]}class C9 extends E${filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#w="";#J;#z;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return O$.default.inverse(O$.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let $=this.userInput.slice(0,this._cursor),[z,...w]=this.userInput.slice(this._cursor);return`${$}${O$.default.inverse(z)}${w.join("")}`}get options(){if(typeof this.#z==="function")return this.#z();return this.#z}constructor($){super($);this.#z=$.options;let z=this.options;this.filteredOptions=[...z],this.multiple=$.multiple===!0,this.#J=$.filter??S9;let w;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)w=$.initialValue;else w=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)w=[this.options[0].value];if(w)for(let J of w){let j=z.findIndex((X)=>X.value===J);if(j!==-1)this.toggleSelected(J),this.#$=j}this.focusedValue=this.options[this.#$]?.value,this.on("key",(J,j)=>this.#j(J,j)),this.on("userInput",(J)=>this.#X(J))}_isActionKey($,z){return $==="\t"||this.multiple&&this.isNavigating&&z.name==="space"&&$!==void 0&&$!==""}#j($,z){let w=z.name==="up",J=z.name==="down",j=z.name==="return";if(w||J){if(this.#$=Math.max(0,Math.min(this.#$+(w?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(j)this.value=_9(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(z.name==="tab"||this.isNavigating&&z.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((z)=>z!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#X($){if($!==this.#w){this.#w=$;let z=this.options;if($)this.filteredOptions=z.filter((w)=>this.#J($,w));else this.filteredOptions=[...z];if(this.#$=g9(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class f9 extends E${options;cursor=0;#$;getGroupItems($){return this.options.filter((z)=>z.group===$)}isGroupSelected($){let z=this.getGroupItems($),w=this.value;if(w===void 0)return!1;return z.every((J)=>w.includes(J.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let z=$.value,w=this.getGroupItems(z);if(this.isGroupSelected(z))this.value=this.value.filter((J)=>w.findIndex((j)=>j.value===J)===-1);else this.value=[...this.value,...w.map((J)=>J.value)];this.value=Array.from(new Set(this.value))}else{let z=this.value.includes($.value);this.value=z?this.value.filter((w)=>w!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:z}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(z).flatMap(([w,J])=>[{value:w,group:!0,label:w},...J.map((j)=>({...j,group:w}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:w})=>w===$.cursorAt),this.#$?0:1),this.on("cursor",(w)=>{switch(w){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var oJ=i(e(),1);var eJ=i(e(),1);var tJ=i(e(),1),S0={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]},H1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function v9(){return!0}function P9(){let $={};$.supportsColor=v9();function z(J,j=[]){let X=J===""?[]:[...j,J],Y=function(U){if(!$.supportsColor)return U;let q="",K="";for(let W of X)if(W in H1&&H1[W]in S0){let B=H1[W];q+=S0[B][0],K=S0[B][1]+K}else if(W in S0)q+=S0[W][0],K=S0[W][1]+K;return q+U+K},Q=[...Object.keys(S0),...Object.keys(H1)];for(let U of Q)if(!(U in Y))Object.defineProperty(Y,U,{get(){return z(U,X)}});return Y}let w=[...Object.keys(S0),...Object.keys(H1)];for(let J of w)if(!(J in $))Object.defineProperty($,J,{get(){return z(J)}});return $}var $j=P9();var h9=$9();var x=($,z)=>h9?$:z,zj=x("\u25C6","*"),wj=x("\u25A0","x"),Jj=x("\u25B2","x"),jj=x("\u25C7","o"),Xj=x("\u250C","T"),d9=x("\u2502","|"),Yj=x("\u2514","\u2014"),Qj=x("\u25CF",">"),Uj=x("\u25CB"," "),qj=x("\u25FB","[\u2022]"),Kj=x("\u25FC","[+]"),Wj=x("\u25FB","[ ]"),Bj=x("\u25AA","\u2022"),Hj=x("\u2500","-"),Lj=x("\u256E","+"),Aj=x("\u251C","+"),Nj=x("\u256F","+"),bj=x("\u25CF","\u2022"),yj=x("\u25C6","*"),Gj=x("\u25B2","!"),Vj=x("\u25A0","x");var Oj=i(e(),1);var Zj=i(e(),1);var Fj=i(e(),1);var Rj=i(e(),1);var kj=i(e(),1);var Tj=i(e(),1);var Mj=i(e(),1);var Dj=i(e(),1);var Ij=i(e(),1),Ej=i(e(),1);var gj={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};var Sj=i(e(),1);var _j=i(e(),1);var u9=i(e(),1);function x9(){return`${u9.default.gray(d9)} `}var Cj=x9();var fj=i(e(),1);var vj=i(e(),1);var f1="0.1.16";A1();await l0([F1(),Y1()]);var{serve:N$}=globalThis.Bun;import j0 from"fs";import f from"path";import o from"process";import A$ from"path";A1();import wJ from"process";async function JJ($){try{let z=await Bun.file($).text(),w=jJ(z),J=XJ(z,$),j=YJ(z,w),X=QJ(z,w);return{file:$,metrics:w,issues:J,suggestions:j,performance:X}}catch(z){throw Error(`Failed to analyze template ${$}: ${z instanceof Error?z.message:String(z)}`)}}function jJ($){let z=$.split(`
1171
+ `),w=$.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),j=(w?w[1]:"").split(`
1172
+ `).length,X={conditionals:($.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:($.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:($.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};X.total=X.conditionals+X.loops+X.includes+X.custom;let Y=($.match(/\{\{[\s\S]*?\}\}/g)||[]).length,Q=($.match(/\{!![\s\S]*?!!\}/g)||[]).length,U=($.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,q=Y+Q+U,K=($.match(/<[A-Z][^>]*>/g)||[]).length,W=($.match(/@extends\(/g)||[]).length,B=0,H=0;for(let b of z)if(/@(?:if|unless|foreach|for|while|section)\b/.test(b)&&!/@end/.test(b)&&!/@else/.test(b))H++,B=Math.max(B,H);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(b))H--;let L=B>=4?3:0,A=Math.min(10,Math.ceil(X.total*0.5+q*0.1+K*0.3+(j>10?j*0.05:0)+L));return{lines:z.length,characters:$.length,directives:X,expressions:q,components:K,layouts:W,scriptLines:j,complexity:A}}function XJ($,z){let w=[],J=q8($,"if","endif");if(J>0)w.push({type:"error",category:"syntax",message:`Found ${J} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let j=q8($,"foreach","endforeach");if(j>0)w.push({type:"error",category:"syntax",message:`Found ${j} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let X=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(X&&X.length>0)w.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let Y=($.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(Y>0)w.push({type:"warning",category:"security",message:`Found ${Y} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let Q=$.match(/<img[^>]*>/g);if(Q){let K=Q.filter((W)=>!W.includes("alt="));if(K.length>0)w.push({type:"warning",category:"accessibility",message:`Found ${K.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let U=$.split(`
1173
+ `).filter((K)=>K.length>120);if(U.length>0)w.push({type:"info",category:"maintainability",message:`Found ${U.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let q=($.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(q>3)w.push({type:"info",category:"maintainability",message:`Found ${q} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return w}function YJ($,z){let w=[];if(z.complexity>7)w.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(z.complexity>5&&z.directives.total>8)w.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(z.lines>100&&z.components===0)w.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(z.expressions>20)w.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let J=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(J&&J.length>0)w.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(z.directives.total===0&&z.expressions<5)w.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(z.scriptLines>50)w.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return w}function QJ($,z){let w=1;if(w+=z.directives.conditionals*0.1,w+=z.directives.loops*0.5,w+=z.directives.includes*2,w+=z.expressions*0.05,w+=z.components*1,z.scriptLines>10)w+=z.scriptLines*0.1;let J;if(z.expressions===0&&z.directives.total===0)J="high";else if(z.expressions<5&&z.directives.total<3)J="medium";else J="low";let j=[];if(w>10)j.push("Consider optimizing template complexity");if(J==="low"&&z.directives.total>5)j.push("Reduce dynamic content for better caching");if(z.components===0&&z.lines>40)j.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(w*100)/100,complexityScore:z.complexity,cacheability:J,recommendations:j}}function q8($,z,w){let J=$.replace(/<!--[\s\S]*?-->/g,""),j=(J.match(new RegExp(`@${z}\\b`,"g"))||[]).length,X=(J.match(new RegExp(`@${w}\\b`,"g"))||[]).length;return Math.abs(j-X)}async function K8($=["**/*.stx"],z){let w=[],J=[];for(let X of $){let Y=await Array.fromAsync(new Bun.Glob(X).scan({cwd:z||wJ.cwd(),onlyFiles:!0,absolute:!0}));J.push(...Y.filter((Q)=>Q.endsWith(".stx")))}for(let X of J)try{let Y=await JJ(X);w.push(Y)}catch(Y){console.warn(`Failed to analyze ${X}:`,Y)}let j=UJ(w);return{results:w,summary:j}}function UJ($){let z=$.length,w=$.reduce((q,K)=>q+K.metrics.lines,0),J=z>0?$.reduce((q,K)=>q+K.metrics.complexity,0)/z:0,j=$.reduce((q,K)=>q+K.issues.length,0),X={};$.forEach((q)=>{q.issues.forEach((K)=>{X[K.category]=(X[K.category]||0)+1})});let Y=z>0?$.reduce((q,K)=>q+K.performance.estimatedRenderTime,0)/z:0,Q=Math.max(1,Math.min(10,Math.round(10-Y/2-J/2))),U=[];if(J>6)U.push("Project has high average complexity. Consider refactoring complex templates.");if(j>z*2)U.push("High number of issues detected. Run detailed analysis on individual files.");if(X.security>0)U.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:z,totalLines:w,avgComplexity:Math.round(J*100)/100,totalIssues:j,issuesByCategory:X,performanceScore:Q,recommendations:U}}j$();F1();await t();import Q1 from"fs";import U1 from"path";var qJ=new Map;async function W8($,z){try{let w=U1.resolve(z.cachePath),J=U1.join(w,`${L$($)}.html`),j=U1.join(w,`${L$($)}.meta.json`);if(!await S(J)||!await S(j))return null;let X=await Bun.file(j).text(),Y=JSON.parse(X);if(Y.cacheVersion!==z.cacheVersion)return null;if((await Q1.promises.stat($)).mtime.getTime()>Y.mtime)return null;for(let U of Y.dependencies)if(await S(U)){if((await Q1.promises.stat(U)).mtime.getTime()>Y.mtime)return null}else return null;return await Bun.file(J).text()}catch(w){return console.warn(`Cache error for ${$}:`,w),null}}async function B8($,z,w,J){try{let j=U1.resolve(J.cachePath);await Q1.promises.mkdir(j,{recursive:!0});let X=U1.join(j,`${L$($)}.html`),Y=U1.join(j,`${L$($)}.meta.json`),Q=await Q1.promises.stat($);await Bun.write(X,z);let U={sourcePath:$,mtime:Q.mtime.getTime(),dependencies:Array.from(w),cacheVersion:J.cacheVersion,generatedAt:Date.now()};await Bun.write(Y,JSON.stringify(U,null,2)),qJ.set($,{output:z,mtime:Q.mtime.getTime(),dependencies:w})}catch(j){console.warn(`Failed to cache template ${$}:`,j)}}function L$($){return new Bun.CryptoHasher("sha1").update($).digest("hex").substring(0,16)}V6();Y1();Q6();await l0([Y1(),t()]);import k6 from"fs";import T1 from"path";async function KJ($){try{let w=(await Bun.file($).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!w)return[];let J=w[1],j=[],X=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,Y;while((Y=X.exec(J))!==null){let Q=Y[1],U=Y[2]||Y[3]||Y[4];if(!U)continue;let q={name:U},K=Q.match(/@type\s+\{([^}]+)\}/i);if(K)q.type=K[1].trim();if(Q.match(/@required/i))q.required=!0;let B=Q.match(/@default\s+(.+?)(?:\s+|$)/i);if(B)q.default=B[1].trim();let H=Q.split(`
1174
+ `).map((L)=>L.trim().replace(/^\*\s*/,"")).filter((L)=>!L.startsWith("@")&&L.length>0);q.description=H.join(" ").trim(),j.push(q)}if(j.length===0){let Q=J.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(Q){let q=Q[1].split(",").map((K)=>K.trim()).filter(Boolean);for(let K of q){let[W]=K.split(":").map((B)=>B.trim());if(W)j.push({name:W})}}}return j}catch(z){return console.error(`Error extracting props from ${$}:`,z),[]}}async function WJ($){try{let z=await Bun.file($).text(),w=z.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||z.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(w)return w[1].split(`
1175
+ `).map((J)=>J.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function BJ($,z=!1,w){let J=T1.basename($,".stx"),j=await KJ($),X=await WJ($),Y="";if(z&&w)Y=`<${w}></${w}>`;else{let Q=j.map((U)=>{if(U.type==="boolean")return`:${U.name}="true"`;return`${U.name}="value"`}).join(`
1176
+ `);Y=`<${J}
1177
+ ${Q}
1178
+ />`}return{name:J,path:$,description:X,props:j,example:Y,isWebComponent:z,tag:w}}async function H8($){try{if(!await S($))return console.warn(`Components directory does not exist: ${$}`),[];let z=await k6.promises.readdir($,{withFileTypes:!0}),w=[];for(let J of z){let j=T1.join($,J.name);if(J.isDirectory()){let X=await H8(j);w.push(...X)}else if(J.isFile()&&J.name.endsWith(".stx"))w.push(j)}return w}catch(z){return console.error(`Error finding component files in ${$}:`,z),[]}}async function HJ($,z){try{if(!await S($))return[];let w=await H8($),J=[],j=new Map;if(z?.components?.length)for(let X of z.components)j.set(X.file,X);for(let X of w){let Y=j.get(X),Q=!!Y,U=Y?.tag,q=await BJ(X,Q,U);J.push(q)}return J}catch(w){return console.error("Error generating component docs:",w),[]}}async function LJ($){try{if(!await S($))return[];let z=await k6.promises.readdir($,{withFileTypes:!0}),w=[];for(let J of z){if(!J.isFile()||!J.name.endsWith(".stx"))continue;let j=T1.join($,J.name),X=await Bun.file(j).text(),Y=T1.basename(j,".stx"),Q=X.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||X.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),U=Q?Q[1].split(`
1179
+ `).map((A)=>A.trim().replace(/^\*\s*/,"")).join(" ").trim():"",q=/@component\(\s*['"]([^'"]+)['"]/g,K=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,W=new Set,B;while((B=q.exec(X))!==null)W.add(B[1]);while((B=K.exec(X))!==null)if(B[1]&&B[1]!=="slot")W.add(B[1]);let H=/@([a-z]+)(?:\s*\(|\s+|$)/g,L=new Set;while((B=H.exec(X))!==null)L.add(B[1]);w.push({name:Y,path:j,description:U,components:[...W],directives:[...L]})}return w}catch(z){return console.error("Error generating template docs:",z),[]}}async function AJ($=[]){try{let z=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1180
+ <p>Welcome, {{ user.name }}!</p>
1181
+ @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1182
+ <p>Welcome back!</p>
1183
+ @else
1184
+ <p>Please log in</p>
1185
+ @endif`},{name:"elseif",description:"Provides an alternative condition",hasEndTag:!1,example:`@if(score > 90)
1186
+ <p>A</p>
1187
+ @elseif(score > 80)
1188
+ <p>B</p>
1189
+ @elseif(score > 70)
1190
+ <p>C</p>
1191
+ @endif`},{name:"unless",description:"Conditionally render content if a condition is false",hasEndTag:!0,example:`@unless(user.isLoggedIn)
1192
+ <p>Please log in</p>
1193
+ @endunless`},{name:"for",description:"Loop through an array or object",hasEndTag:!0,example:`@for(item of items)
1194
+ <li>{{ item.name }}</li>
1195
+ @endfor`},{name:"while",description:"Loop while a condition is true",hasEndTag:!0,example:`@while(page < totalPages)
1196
+ <p>Page {{ page }}</p>
1197
+ @endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
1198
+ {{ This will be displayed as-is }}
1199
+ @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let w of $)z.push({name:w.name,description:w.description||"",hasEndTag:w.hasEndTag||!1,example:""});return z}catch(z){return console.error("Error generating directive docs:",z),[]}}function NJ($=[],z=[],w=[],J){let j=`# stx Documentation
1200
+
1201
+ `;if(J)j+=`${J}
1202
+
1203
+ `;if($.length>0){j+=`## Components
1204
+
1205
+ `;for(let X of $){if(j+=`### ${X.name}
1206
+
1207
+ `,X.description)j+=`${X.description}
1208
+
1209
+ `;if(X.isWebComponent)j+=`**Web Component Tag:** \`${X.tag}\`
1210
+
1211
+ `;if(X.props.length>0){j+=`#### Properties
1212
+
1213
+ `,j+=`| Name | Type | Required | Default | Description |
1214
+ `,j+=`| ---- | ---- | -------- | ------- | ----------- |
1215
+ `;for(let Y of X.props)j+=`| ${Y.name} | ${Y.type||"any"} | ${Y.required?"Yes":"No"} | ${Y.default||"-"} | ${Y.description||"-"} |
1216
+ `;j+=`
1217
+ `}if(X.example)j+=`#### Example
1218
+
1219
+ `,j+="```html\n",j+=X.example,j+="\n```\n\n"}}if(z.length>0){j+=`## Templates
1220
+
1221
+ `;for(let X of z){if(j+=`### ${X.name}
1222
+
1223
+ `,X.description)j+=`${X.description}
1224
+
1225
+ `;if(X.components&&X.components.length>0)j+=`**Components Used:** ${X.components.join(", ")}
1226
+
1227
+ `;if(X.directives&&X.directives.length>0)j+=`**Directives Used:** ${X.directives.join(", ")}
1228
+
1229
+ `}}if(w.length>0){j+=`## Directives
1230
+
1231
+ `,j+=`| Directive | Description | Has End Tag |
1232
+ `,j+=`| --------- | ----------- | ----------- |
1233
+ `;for(let X of w)j+=`| @${X.name} | ${X.description||"-"} | ${X.hasEndTag?"Yes":"No"} |
1234
+ `;j+=`
1235
+ `;for(let X of w)if(X.example)j+=`### @${X.name}
1236
+
1237
+ `,j+=`${X.description||""}
1238
+
1239
+ `,j+=`#### Example
1240
+
1241
+ `,j+="```html\n",j+=X.example,j+="\n```\n\n"}return j}function bJ($=[],z=[],w=[],J){let j=`<!DOCTYPE html>
1242
+ <html lang="en">
1243
+ <head>
1244
+ <meta charset="UTF-8">
1245
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1246
+ <title>stx Documentation</title>
1247
+ <style>
1248
+ body {
1249
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
1250
+ line-height: 1.6;
1251
+ color: #333;
1252
+ max-width: 1200px;
1253
+ margin: 0 auto;
1254
+ padding: 2rem;
1255
+ }
1256
+ h1, h2, h3, h4 { margin-top: 2rem; }
1257
+ table {
1258
+ border-collapse: collapse;
1259
+ width: 100%;
1260
+ margin: 1rem 0;
1261
+ }
1262
+ th, td {
1263
+ text-align: left;
1264
+ padding: 0.5rem;
1265
+ border-bottom: 1px solid #ddd;
1266
+ }
1267
+ th { border-bottom: 2px solid #ddd; }
1268
+ pre {
1269
+ background: #f5f5f5;
1270
+ padding: 1rem;
1271
+ border-radius: 4px;
1272
+ overflow-x: auto;
1273
+ }
1274
+ code {
1275
+ background: #f5f5f5;
1276
+ padding: 0.2rem 0.4rem;
1277
+ border-radius: 4px;
1278
+ font-size: 0.9em;
1279
+ }
1280
+ </style>
1281
+ </head>
1282
+ <body>
1283
+ <h1>stx Documentation</h1>
1284
+ `;if(J)j+=`<div>${J}</div>`;if($.length>0){j+="<h2>Components</h2>";for(let X of $){if(j+=`<h3>${X.name}</h3>`,X.description)j+=`<p>${X.description}</p>`;if(X.isWebComponent)j+=`<p><strong>Web Component Tag:</strong> <code>${X.tag}</code></p>`;if(X.props.length>0){j+="<h4>Properties</h4>",j+=`<table>
1285
+ <thead>
1286
+ <tr>
1287
+ <th>Name</th>
1288
+ <th>Type</th>
1289
+ <th>Required</th>
1290
+ <th>Default</th>
1291
+ <th>Description</th>
1292
+ </tr>
1293
+ </thead>
1294
+ <tbody>`;for(let Y of X.props)j+=`<tr>
1295
+ <td>${Y.name}</td>
1296
+ <td>${Y.type||"any"}</td>
1297
+ <td>${Y.required?"Yes":"No"}</td>
1298
+ <td>${Y.default||"-"}</td>
1299
+ <td>${Y.description||"-"}</td>
1300
+ </tr>`;j+="</tbody></table>"}if(X.example)j+="<h4>Example</h4>",j+=`<pre><code>${X.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(z.length>0){j+="<h2>Templates</h2>";for(let X of z){if(j+=`<h3>${X.name}</h3>`,X.description)j+=`<p>${X.description}</p>`;if(X.components&&X.components.length>0)j+=`<p><strong>Components Used:</strong> ${X.components.join(", ")}</p>`;if(X.directives&&X.directives.length>0)j+=`<p><strong>Directives Used:</strong> ${X.directives.join(", ")}</p>`}}if(w.length>0){j+="<h2>Directives</h2>",j+=`<table>
1301
+ <thead>
1302
+ <tr>
1303
+ <th>Directive</th>
1304
+ <th>Description</th>
1305
+ <th>Has End Tag</th>
1306
+ </tr>
1307
+ </thead>
1308
+ <tbody>`;for(let X of w)j+=`<tr>
1309
+ <td>@${X.name}</td>
1310
+ <td>${X.description||"-"}</td>
1311
+ <td>${X.hasEndTag?"Yes":"No"}</td>
1312
+ </tr>`;j+="</tbody></table>";for(let X of w)if(X.example)j+=`<h3>@${X.name}</h3>`,j+=`<p>${X.description||""}</p>`,j+="<h4>Example</h4>",j+=`<pre><code>${X.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return j+="</body></html>",j}function yJ($=[],z=[],w=[],J){return JSON.stringify({components:$,templates:z,directives:w,extraContent:J||""},null,2)}async function GJ($){try{let{componentsDir:z,templatesDir:w,webComponentsConfig:J,customDirectives:j,config:X}=$;if(!X.enabled)return!1;let Y=X.outputDir||"docs";if(await k6.promises.mkdir(Y,{recursive:!0}),console.log("Generating documentation..."),z)console.log(`Components directory: ${z}`);if(w)console.log(`Templates directory: ${w}`);console.log(`Output directory: ${Y}`);let Q=[];if(X.components!==!1&&z)console.log("Generating component documentation..."),Q=await HJ(z,J),console.log(`Found ${Q.length} components`);let U=[];if(X.templates!==!1&&w)console.log("Generating template documentation..."),U=await LJ(w),console.log(`Found ${U.length} templates`);let q=[];if(X.directives!==!1)console.log("Generating directive documentation..."),q=await AJ(j),console.log(`Found ${q.length} directives`);let K=X.format||"markdown",W=X.extraContent,B="",H="";switch(K){case"markdown":B=NJ(Q,U,q,W),H="md";break;case"html":B=bJ(Q,U,q,W),H="html";break;case"json":B=yJ(Q,U,q,W),H="json";break;default:throw Error(`Unsupported documentation format: ${K}`)}let L=T1.join(Y,`stx-docs.${H}`);return await Bun.write(L,B),console.log(`Documentation generated: ${L}`),!0}catch(z){return console.error("Error generating documentation:",z),!1}}async function L8($){let z={enabled:!0,outputDir:$.output||"docs",format:$.format||"markdown",components:$.components!==!1,templates:$.templates!==!1,directives:$.directives!==!1,extraContent:$.extraContent},w=$.componentsDir||y0.componentsDir,J=$.templatesDir||".";return GJ({componentsDir:w,templatesDir:J,webComponentsConfig:y0.webComponents,customDirectives:y0.customDirectives,config:z})}U$();z1();var VJ={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function A8($,z={}){let w={...VJ,...z};if($.trim()==="")return`
1313
+ `;let J=$;if(w.trimTrailingWhitespace)J=J.replace(/[ \t]+$/gm,"");if(J=OJ(J,w),J=ZJ(J,w),J=TJ(J,w),J=FJ(J,w),w.trimTrailingWhitespace)J=J.replace(/[ \t]+$/gm,""),J=J.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(J=J.replace(/\r\n/g,`
1314
+ `).replace(/\r/g,`
1315
+ `),!J.endsWith(`
1316
+ `))J+=`
1317
+ `;return J}function OJ($,z){return $.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(w,J)=>{let j=J.trim();if(j&&!j.includes(`
1318
+ `)&&j.length<80)return w.replace(J,j);let X=J.split(`
1319
+ `),Y=X.map((U,q)=>{if(q===0&&U.trim()==="")return"";if(q===X.length-1&&U.trim()==="")return"";let K=U.trim();if(K==="")return"";return`${z.useTabs?"\t":" ".repeat(z.indentSize)}${K}`}).filter((U,q,K)=>{if(q===0||q===K.length-1)return U!=="";return!0}),Q=Y.length>0?`
1320
+ ${Y.join(`
1321
+ `)}
1322
+ `:"";return w.replace(J,Q)})}function ZJ($,z){let w=$,J=[],j=["pre","code","textarea","style"];for(let W of j){let B=new RegExp(`<${W}\\b[^>]*>[\\s\\S]*?<\\/${W}>`,"gi");w=w.replace(B,(H)=>{let L=`__WHITESPACE_TAG_${J.length}__`;return J.push(H),L})}let X=[];w=w.replace(/<(\w+)([^>]*)><\/\1>/g,(W)=>{let B=`__EMPTY_TAG_${X.length}__`;return X.push(W),B}),w=w.replace(/<(\w+)([^>]*?)(@\w+\([^)]*\))([^>]*?)(@end\w+)([^>]*)>/g,(W,B,H,L,A,b,y)=>{return`<${B}${H}
1323
+ ${L}
1324
+ ${A.trim()}
1325
+ ${b}${y}>`}),w=w.replace(/>(\s*)</g,(W,B,H,L)=>{if(B.includes(`
1326
+ `))return W;let A=L.substring(Math.max(0,H-50),H+1),b=L.substring(H+W.length-1,Math.min(L.length,H+W.length+50)),y=A.match(/<\/(\w+)>$/),G=b.match(/^<(\w+)/),V=["span","a","strong","em","b","i","u","small","mark","del","ins","sub","sup","code","kbd","samp","var","abbr","cite","q","dfn","time"];if(y&&G){let O=y[1].toLowerCase(),Z=G[1].toLowerCase();if(V.includes(O)&&V.includes(Z)){let _=L.substring(0,H).lastIndexOf(`
1327
+ `)+1,w0=L.substring(H+W.length).indexOf(`
1328
+ `),J0=w0===-1?L.length:H+W.length+w0;if(L.substring(_,J0).replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim().length>0)return W}}return`>
1329
+ <`}),w=w.replace(/>(\s*)@/g,(W,B)=>{if(B.includes(`
1330
+ `))return W;return`>
1331
+ @`}),w=w.replace(/(@end\w+)(\s*)</g,(W,B,H)=>{if(H.includes(`
1332
+ `))return W;return`${B}
1333
+ <`}),w=w.replace(/\)(\s*)@/g,(W,B)=>{if(B.includes(`
1334
+ `))return W;return`)
1335
+ @`}),w=w.replace(/\)(\s*)</g,(W,B)=>{if(B.includes(`
1336
+ `))return W;return`)
1337
+ <`}),w=w.replace(/(@end\w+)(\s*)@/g,(W,B,H)=>{if(H.includes(`
1338
+ `))return W;return`${B}
1339
+ @`}),w=w.replace(/(@\w+)(?!\s*\()(\s*)</g,(W,B,H)=>{if(H.includes(`
1340
+ `))return W;return`${B}
1341
+ <`});let Y=w.split(`
1342
+ `),Q=[],U=0,q=z.useTabs?"\t":" ".repeat(z.indentSize);for(let W=0;W<Y.length;W++){let B=Y[W].trim();if(B===""){Q.push("");continue}if(B.startsWith("</")||B.startsWith("@end"))U=Math.max(0,U-1);let H=U>0?q.repeat(U)+B:B;if(Q.push(H),B.startsWith("<")&&!B.includes("/>")&&!B.startsWith("</")){let L=B.match(/<(\w+)[^>]*>.*<\/\1>/);if(!B.includes("<!")&&!RJ(B)&&!L)U++}if(B.startsWith("@")&&kJ(B))U++}let K=Q.join(`
1343
+ `);return J.forEach((W,B)=>{K=K.replace(`__WHITESPACE_TAG_${B}__`,W)}),X.forEach((W,B)=>{K=K.replace(`__EMPTY_TAG_${B}__`,W)}),K}function FJ($,z){if($=$.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(w,J,j)=>{let X=j.trim().replace(/\s+/g," ");return`@${J}(${X})`}),$=$.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(w,J,j)=>{if(j.trim()==="")return`@${J}`;return`@${J}(${j.trim()})`}),z.normalizeWhitespace)$=$.replace(/\{\{\s*([^}]+)\s*\}\}/g,(w,J)=>{return`{{ ${J.trim()} }}`}),$=$.replace(/\{!!\s*([^!]+)\s*!!\}/g,(w,J)=>{return`{!! ${J.trim()} !!}`});return $}function RJ($){let z=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if($.includes("/>"))return!0;let w=$.match(/<(\w+)/);if(w){let J=w[1].toLowerCase();return z.includes(J)}return!1}function kJ($){let z=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let w of z)if($.startsWith(`@${w}`))return!$.includes(`@end${w}`);return!1}function TJ($,z){if(!z.sortAttributes)return $;return $.replace(/<(\w+)([^>]*)>/g,(w,J,j)=>{if(!j.trim())return w;if(j.includes("<")||j.includes(`
1344
+ `)||j.includes("@"))return w;let X=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,Y=[],Q;while((Q=X.exec(j))!==null)Y.push({name:Q[1],value:Q[2]});Y.sort((q,K)=>{if(q.name==="id")return-1;if(K.name==="id")return 1;if(q.name==="class")return-1;if(K.name==="class")return 1;return q.name.localeCompare(K.name)});let U=Y.map((q)=>q.value?`${q.name}=${q.value}`:q.name).join(" ");return`<${J}${U?` ${U}`:""}>`})}K6();N6();import q1 from"fs";import T6 from"path";import N8 from"process";async function b8($="index.stx",z={}){try{let w=z.force||!1,J=T6.resolve(N8.cwd(),$);if(q1.existsSync(J)){if(!w)throw Error(`File ${$} already exists. Use --force to overwrite.`);console.warn(`File ${$} already exists. Overwriting...`)}let j=T6.dirname(J);if(!q1.existsSync(j))q1.mkdirSync(j,{recursive:!0});let X;if(z.template){let Y=T6.resolve(N8.cwd(),z.template);if(!q1.existsSync(Y))throw Error(`Template file ${z.template} does not exist.`);if(!Y.endsWith(".stx"))console.warn(`Warning: Template file ${z.template} does not have a .stx extension. Using it anyway.`);X=q1.readFileSync(Y,"utf-8"),console.warn(`Using template from ${z.template}`)}else X=MJ();return q1.writeFileSync(J,X),console.warn(`Created new stx file: ${$}`),!0}catch(w){return console.error(`Error creating file: ${w instanceof Error?w.message:String(w)}`),!1}}function MJ(){return`<!DOCTYPE html>
1345
+ <html lang="en">
1346
+ <head>
1347
+ <meta charset="UTF-8">
1348
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1349
+ <title>{{ title }}</title>
1350
+ <script>
1351
+ export const title = "My stx Page";
1352
+ export const description = "A page built with stx";
1353
+ export const items = [
1354
+ "Templates with TypeScript support",
1355
+ "Powerful directives",
1356
+ "Reusable components"
1357
+ ];
1358
+ </script>
1359
+ <style>
1360
+ :root {
1361
+ --primary-color: #3498db;
1362
+ --dark-color: #34495e;
1363
+ --light-color: #ecf0f1;
1364
+ --font-main: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1365
+ }
1366
+
1367
+ body {
1368
+ font-family: var(--font-main);
1369
+ line-height: 1.6;
1370
+ color: var(--dark-color);
1371
+ max-width: 800px;
1372
+ margin: 0 auto;
1373
+ padding: 2rem;
1374
+ }
1375
+
1376
+ h1 {
1377
+ color: var(--primary-color);
1378
+ }
1379
+
1380
+ .content {
1381
+ margin-top: 2rem;
1382
+ }
1383
+
1384
+ ul {
1385
+ padding-left: 1.5rem;
1386
+ }
1387
+
1388
+ li {
1389
+ margin-bottom: 0.5rem;
1390
+ }
1391
+ </style>
1392
+ </head>
1393
+ <body>
1394
+ <header>
1395
+ <h1>{{ title }}</h1>
1396
+ <p>{{ description }}</p>
1397
+ </header>
1398
+
1399
+ <div class="content">
1400
+ <h2>Features</h2>
1401
+ <ul>
1402
+ @foreach(items as item)
1403
+ <li>{{ item }}</li>
1404
+ @endforeach
1405
+ </ul>
1406
+ </div>
1407
+ </body>
1408
+ </html>`}q$();K$();y6();Z1();var y8="f9c3713";W$();await l0([F1(),Z1(),t()]);await l0([Y1(),Z1(),t()]);t();Z6();U$();J1();var K1={name:"bun-plugin-stx",async setup($){let z={...y0,...$.config?.stx},w=new Set,J=z.webComponents?.enabled?`./${A$.relative(A$.dirname($.config?.outdir||"dist"),z.webComponents.outputDir||"dist/web-components")}`:"/web-components",j=[];if(z.webComponents?.enabled)try{let X=await Y8(z,w);if(j.push(...X),z.debug&&X.length>0)console.log(`Successfully built ${X.length} web components`)}catch(X){console.error("Failed to build web components:",X)}$.onLoad({filter:/\.stx$/},async({path:X})=>{try{let Y=new Set;if(z.cache&&z.cachePath){let L=await W8(X,z);if(L){if(z.debug)console.log(`Using cached version of ${X}`);return{contents:L,loader:"html"}}}let Q=await v0(()=>Bun.file(X).text(),"",(L)=>{throw new Y$(`Failed to read stx file: ${X}`,X,void 0,void 0,`File read error: ${L.message}`)});if(!Q)throw new Y$(`stx file is empty: ${X}`,X);let{scriptContent:U,templateContent:q,allScripts:K}=F0.time("script-extraction",()=>{let L=Q.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),A=L?L[1]:"",b=Q.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],y=Q.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:A,templateContent:y,allScripts:b}}),W={__filename:X,__dirname:A$.dirname(X),__stx:{webComponentsPath:J,builtComponents:j}};await v0(()=>R1(U,W,X),void 0,(L)=>{let A=new g0(`Script execution failed in ${X}: ${L.message}`,X,void 0,void 0,U.substring(0,100));if(V1.log(A,{filePath:X,scriptContent:U}),z.debug)throw A});let H=await F0.timeAsync("directive-processing",async()=>{return await m0(q,W,X,z,Y)});if(K.length>0)if(H.match(/(<\/body>)/i)){let A=K.join(`
1409
+ `);H=H.replace(/(<\/body>)/i,`${A}
1410
+ $1`)}else H+=`
1411
+ ${K.join(`
1412
+ `)}`;if(Y.forEach((L)=>w.add(L)),z.cache&&z.cachePath){if(await B8(X,H,Y,z),z.debug)console.log(`Cached template ${X} with ${Y.size} dependencies`)}return{contents:H,loader:"html"}}catch(Y){let Q=Y instanceof Error?Y:new g0(`Plugin processing failed: ${String(Y)}`,X);if(V1.log(Q,{filePath:X,buildConfig:$.config}),Q$.logDetailedError(Q,{filePath:X,plugin:"bun-plugin-stx"}),z.debug)console.error("stx Plugin Error:",Q);let U=Q,q=U.line||null,K=U.context||null;return{contents:`<!DOCTYPE html>
1413
+ <html lang="en">
1414
+ <head>
1415
+ <meta charset="UTF-8">
1416
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1417
+ <title>stx Rendering Error</title>
1418
+ <style>
1419
+ body { font-family: system-ui, -apple-system, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; line-height: 1.6; }
1420
+ .error-header { color: #dc3545; border-left: 4px solid #dc3545; padding-left: 16px; margin-bottom: 24px; }
1421
+ .error-details { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 16px; margin: 16px 0; }
1422
+ .error-code { background: #2d3748; color: #e2e8f0; padding: 16px; border-radius: 8px; overflow-x: auto; font-family: 'Monaco', 'Menlo', monospace; font-size: 14px; }
1423
+ .help-section { background: #e3f2fd; border-left: 4px solid #2196f3; padding: 16px; margin-top: 24px; }
1424
+ .file-path { font-family: monospace; background: #f1f3f4; padding: 2px 6px; border-radius: 4px; }
1425
+ </style>
1426
+ </head>
1427
+ <body>
1428
+ <div class="error-header">
1429
+ <h1>stx Template Error</h1>
1430
+ <p>An error occurred while processing your stx template.</p>
1431
+ </div>
1432
+
1433
+ <div class="error-details">
1434
+ <h3>Error Details</h3>
1435
+ <p><strong>File:</strong> <span class="file-path">${X}</span></p>
1436
+ <p><strong>Error:</strong> ${Q.message}</p>
1437
+ ${q?`<p><strong>Line:</strong> ${q}</p>`:""}
1438
+ ${K?`<p><strong>Context:</strong> ${K}</p>`:""}
1439
+ </div>
1440
+
1441
+ ${Q.stack?`
1442
+ <div class="error-details">
1443
+ <h3>Stack Trace</h3>
1444
+ <pre class="error-code">${Q.stack}</pre>
1445
+ </div>`:""}
1446
+
1447
+ <div class="help-section">
1448
+ <h3>\uD83D\uDCA1 Troubleshooting Tips</h3>
1449
+ <ul>
1450
+ <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
1451
+ <li>Verify that all variables used in the template are properly defined</li>
1452
+ <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
1453
+ <li>Run <code>stx debug ${A$.basename(X)}</code> for detailed analysis</li>
1454
+ <li>Enable debug mode in your stx config for more detailed error messages</li>
1455
+ </ul>
1456
+ </div>
1457
+ </body>
1458
+ </html>`,loader:"html"}}})}};var __dirname="/home/runner/work/stx/stx/packages/stx/src",N={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgGray:"\x1B[100m"};async function M6($,z=10){for(let w=0;w<z;w++){let J=$+w;try{return N$({port:J,fetch:()=>new Response("test")}).stop(),J}catch(j){if(j.code==="EADDRINUSE")continue;throw j}}throw Error(`Could not find an available port between ${$} and ${$+z-1}`)}async function G8($){let{spawn:z}=await import("child_process"),w=f.resolve(__dirname,"../../zyte"),J=`http://localhost:${$}/`;try{if(!j0.existsSync(f.join(w,"zig-out/bin/zyte-minimal"))){console.log(`${N.yellow}\u26A0${N.reset} Zyte not built. Building now...`);let{execSync:X}=await import("child_process");X(`cd ${w} && zig build`,{stdio:"inherit"})}return console.log(`${N.magenta}\u26A1 Opening native window...${N.reset}`),z(f.join(w,"zig-out/bin/zyte-minimal"),[J],{detached:!0,stdio:"ignore"}).unref(),console.log(`${N.green}\u2713${N.reset} Native window opened with URL: ${N.cyan}${J}${N.reset}`),!0}catch(j){return console.log(`${N.red}\u2717${N.reset} Could not open native window:`,j),console.log(`${N.dim} You can manually run: cd ${w} && ./zig-out/bin/zyte-minimal ${J}${N.reset}`),!1}}function D6($,z){if(o.stdin.isTTY){o.stdin.setRawMode(!0),o.stdin.setEncoding("utf8"),o.stdin.resume(),console.log(`
1459
+ Keyboard shortcuts:`),console.log(` ${N.cyan}o${N.reset} + Enter - Open in browser`),console.log(` ${N.cyan}c${N.reset} + Enter - Clear console`),console.log(` ${N.cyan}q${N.reset} + Enter (or ${N.cyan}Ctrl+C${N.reset}) - Quit server`);let w="";o.stdin.on("data",(J)=>{if(J==="\x03")z(),o.exit(0);if(w+=J,w.endsWith("\r")||w.endsWith(`
1460
+ `)){let j=w.trim().toLowerCase();if(w="",j==="o")console.log(`${N.dim}Opening ${N.cyan}${$}${N.dim} in your browser...${N.reset}`),Bun.spawn(["open",$],{stderr:"inherit"});else if(j==="c")console.clear(),console.log(`${N.green}Server running at ${N.cyan}${$}${N.reset}`),console.log(`Press ${N.cyan}Ctrl+C${N.reset} to stop the server`),console.log(`
1461
+ Keyboard shortcuts:`),console.log(` ${N.cyan}o${N.reset} + Enter - Open in browser`),console.log(` ${N.cyan}c${N.reset} + Enter - Clear console`),console.log(` ${N.cyan}q${N.reset} + Enter (or ${N.cyan}Ctrl+C${N.reset}) - Quit server`);else if(j==="q")console.log(`${N.yellow}Stopping server...${N.reset}`),z(),o.exit(0);else if(j==="h")console.log(`
1462
+ Keyboard Shortcuts:`),console.log(` ${N.cyan}o${N.reset} + Enter - Open in browser`),console.log(` ${N.cyan}c${N.reset} + Enter - Clear console`),console.log(` ${N.cyan}q${N.reset} + Enter (or ${N.cyan}Ctrl+C${N.reset}) - Quit server`),console.log(` ${N.cyan}h${N.reset} + Enter - Show this help`)}})}}async function DJ($,z={}){let w=z.port||3000,J=z.watch!==!1,j=f.resolve($);if(!j0.existsSync(j))return console.error(`${N.red}Error: File not found: ${N.bright}${j}${N.reset}`),!1;if(!j.endsWith(".md"))return console.error(`${N.red}Error: File must have .md extension: ${N.bright}${j}${N.reset}`),!1;console.log(`${N.blue}Processing${N.reset} ${N.bright}${$}${N.reset}...`);let X=null,Y=async()=>{try{let{content:W,data:B}=await k1(j,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:y0.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),H=z.markdown?.syntaxHighlighting||y0.markdown?.syntaxHighlighting,L=H?.defaultTheme||"github-dark",A=["github-dark"],b=H?.additionalThemes||[],G=[...new Set([...A,...b])].map((V)=>`<option value="${V}"${V===L?" selected":""}>${V}</option>`).join(`
1463
+ `);return X=`
1464
+ <!DOCTYPE html>
1465
+ <html lang="en">
1466
+ <head>
1467
+ <meta charset="UTF-8">
1468
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1469
+ <title>${B.title||f.basename(j)}</title>
1470
+ <!-- Syntax highlighting styles -->
1471
+ <style id="syntax-theme">
1472
+ :root {
1473
+ --shiki-color-text: #24292e;
1474
+ --shiki-color-background: #ffffff;
1475
+ --shiki-token-constant: #005cc5;
1476
+ --shiki-token-string: #032f62;
1477
+ --shiki-token-comment: #6a737d;
1478
+ --shiki-token-keyword: #d73a49;
1479
+ --shiki-token-parameter: #24292e;
1480
+ --shiki-token-function: #6f42c1;
1481
+ --shiki-token-string-expression: #032f62;
1482
+ --shiki-token-punctuation: #24292e;
1483
+ --shiki-token-link: #032f62;
1484
+ }
1485
+ pre {
1486
+ background-color: var(--shiki-color-background);
1487
+ padding: 1rem;
1488
+ border-radius: 4px;
1489
+ }
1490
+ code {
1491
+ color: var(--shiki-color-text);
1492
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1493
+ }
1494
+ .dark-mode {
1495
+ --shiki-color-text: #e1e4e8;
1496
+ --shiki-color-background: #24292e;
1497
+ --shiki-token-constant: #79b8ff;
1498
+ --shiki-token-string: #9ecbff;
1499
+ --shiki-token-comment: #6a737d;
1500
+ --shiki-token-keyword: #f97583;
1501
+ --shiki-token-parameter: #e1e4e8;
1502
+ --shiki-token-function: #b392f0;
1503
+ --shiki-token-string-expression: #9ecbff;
1504
+ --shiki-token-punctuation: #e1e4e8;
1505
+ --shiki-token-link: #9ecbff;
1506
+ }
1507
+ </style>
1508
+ <style>
1509
+ body {
1510
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
1511
+ line-height: 1.6;
1512
+ color: #333;
1513
+ max-width: 800px;
1514
+ margin: 0 auto;
1515
+ padding: 2rem;
1516
+ }
1517
+ pre, code {
1518
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1519
+ }
1520
+ pre {
1521
+ border-radius: 4px;
1522
+ padding: 0;
1523
+ margin: 1.5rem 0;
1524
+ overflow-x: auto;
1525
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
1526
+ }
1527
+ pre code {
1528
+ display: block;
1529
+ padding: 1rem;
1530
+ overflow-x: auto;
1531
+ }
1532
+ /* Apply background color to code blocks based on theme */
1533
+ pre.syntax-highlighter {
1534
+ background-color: var(--shiki-color-background) !important;
1535
+ }
1536
+ .dark-mode pre.syntax-highlighter {
1537
+ background-color: var(--shiki-color-background) !important;
1538
+ }
1539
+ code {
1540
+ padding: 0.2rem 0.4rem;
1541
+ border-radius: 3px;
1542
+ }
1543
+ h1, h2, h3, h4 {
1544
+ margin-top: 2rem;
1545
+ margin-bottom: 1rem;
1546
+ }
1547
+ h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
1548
+ h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
1549
+ h3 { color: #444; }
1550
+ img {
1551
+ max-width: 100%;
1552
+ border-radius: 4px;
1553
+ margin: 1rem 0;
1554
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1555
+ }
1556
+ blockquote {
1557
+ border-left: 4px solid #ddd;
1558
+ padding-left: 1rem;
1559
+ margin-left: 0;
1560
+ color: #555;
1561
+ background: #f9f9f9;
1562
+ padding: 0.5rem 1rem;
1563
+ margin: 1.5rem 0;
1564
+ }
1565
+ table {
1566
+ border-collapse: collapse;
1567
+ width: 100%;
1568
+ margin: 1.5rem 0;
1569
+ }
1570
+ th, td {
1571
+ border: 1px solid #ddd;
1572
+ padding: 0.5rem;
1573
+ }
1574
+ th {
1575
+ background: #f0f0f0;
1576
+ text-align: left;
1577
+ }
1578
+ tr:nth-child(even) {
1579
+ background-color: #f8f8f8;
1580
+ }
1581
+ a {
1582
+ color: #0066cc;
1583
+ text-decoration: none;
1584
+ }
1585
+ a:hover {
1586
+ text-decoration: underline;
1587
+ }
1588
+ hr {
1589
+ border: 0;
1590
+ border-top: 1px solid #eee;
1591
+ margin: 2rem 0;
1592
+ }
1593
+ .frontmatter {
1594
+ background: #f8f8f8;
1595
+ border-radius: 4px;
1596
+ padding: 1.5rem;
1597
+ margin-bottom: 2rem;
1598
+ font-size: 0.9rem;
1599
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
1600
+ border-left: 4px solid #ddd;
1601
+ }
1602
+ .frontmatter-item {
1603
+ margin-bottom: 0.5rem;
1604
+ display: flex;
1605
+ }
1606
+ .frontmatter-label {
1607
+ font-weight: bold;
1608
+ min-width: 100px;
1609
+ color: #555;
1610
+ }
1611
+ /* Theme selector for code blocks */
1612
+ .theme-selector {
1613
+ margin: 1rem 0;
1614
+ padding: 0.5rem;
1615
+ background: #f8f8f8;
1616
+ border-radius: 4px;
1617
+ text-align: right;
1618
+ }
1619
+ select {
1620
+ padding: 0.25rem 0.5rem;
1621
+ border-radius: 3px;
1622
+ border: 1px solid #ddd;
1623
+ }
1624
+
1625
+ /* Dark mode body styles */
1626
+ body.dark-mode {
1627
+ background-color: #121212;
1628
+ color: #e1e4e8;
1629
+ }
1630
+
1631
+ body.dark-mode h1,
1632
+ body.dark-mode h2,
1633
+ body.dark-mode h3 {
1634
+ color: #e1e4e8;
1635
+ border-color: #2f363d;
1636
+ }
1637
+
1638
+ body.dark-mode .theme-selector {
1639
+ background: #2f363d;
1640
+ color: #e1e4e8;
1641
+ }
1642
+
1643
+ body.dark-mode select {
1644
+ background: #24292e;
1645
+ color: #e1e4e8;
1646
+ border-color: #444;
1647
+ }
1648
+
1649
+ body.dark-mode blockquote {
1650
+ background: #24292e;
1651
+ color: #e1e4e8;
1652
+ }
1653
+
1654
+ body.dark-mode .frontmatter {
1655
+ background: #24292e;
1656
+ }
1657
+
1658
+ body.dark-mode a {
1659
+ color: #58a6ff;
1660
+ }
1661
+ </style>
1662
+ </head>
1663
+ <body>
1664
+ ${Object.keys(B).length>0?`
1665
+ <div class="frontmatter">
1666
+ <h3>Frontmatter</h3>
1667
+ ${Object.entries(B).map(([V,O])=>`
1668
+ <div class="frontmatter-item">
1669
+ <span class="frontmatter-label">${V}:</span>
1670
+ <span>${Array.isArray(O)?O.join(", "):O}</span>
1671
+ </div>`).join("")}
1672
+ </div>
1673
+ `:""}
1674
+
1675
+ <div class="theme-selector">
1676
+ Theme:
1677
+ <select id="themeSelector" onchange="changeTheme()">
1678
+ ${G}
1679
+ </select>
1680
+ </div>
1681
+
1682
+ ${W}
1683
+
1684
+ <script>
1685
+ function changeTheme() {
1686
+ const theme = document.getElementById('themeSelector').value;
1687
+
1688
+ // Toggle dark mode class based on theme
1689
+ if (theme.includes('dark') || theme.includes('night') || theme.includes('monokai') ||
1690
+ theme.includes('dracula') || theme.includes('nord') || theme.includes('material')) {
1691
+ document.body.classList.add('dark-mode');
1692
+ } else {
1693
+ document.body.classList.remove('dark-mode');
1694
+ }
1695
+ }
1696
+
1697
+ // Initialize theme on page load
1698
+ document.addEventListener('DOMContentLoaded', function() {
1699
+ changeTheme();
1700
+ });
1701
+ </script>
1702
+ </body>
1703
+ </html>
1704
+ `,!0}catch(W){return console.error(`${N.red}Error processing Markdown file:${N.reset}`,W),!1}};if(!await Y())return!1;let U=w;try{if(U=await M6(w),U!==w)console.log(`${N.yellow}Port ${w} is busy, using port ${U} instead${N.reset}`)}catch{return console.error(`${N.red}Could not find an available port${N.reset}`),!1}console.log(`${N.blue}Starting server on ${N.cyan}http://localhost:${U}/${N.reset}...`);let q=N$({port:U,fetch(W){if(new URL(W.url).pathname==="/")return new Response(X,{headers:{"Content-Type":"text/html"}});return new Response("Not Found",{status:404})},error(W){return new Response(`<pre>${W}
1705
+ ${W.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1706
+ ${N.blue}stx${N.reset} ${N.green}${o.env.stx_VERSION||"v0.0.10"}${N.reset} ${N.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${N.reset}`),console.log(`
1707
+ ${N.bright}\u2192 ${N.cyan}http://localhost:${w}/${N.reset}`),console.log(`
1708
+ ${N.yellow}Routes:${N.reset}`);let K=f.relative(o.cwd(),j);if(console.log(` ${N.green}\u2514\u2500 /${N.reset} \u2192 ${N.bright}${K}${N.reset}`),console.log(`
1709
+ Press ${N.cyan}h${N.reset} + ${N.cyan}Enter${N.reset} to show shortcuts`),D6(q.url.toString(),()=>{if(J)j0.watch(f.dirname(j),{recursive:!0}).close();q.stop()}),z.native)await G8(U);if(J){let W=f.dirname(j);console.log(`${N.blue}Watching ${N.bright}${W}${N.reset} for changes...`);let B=j0.watch(W,{recursive:!0},async(H,L)=>{if(L&&L.endsWith(".md"))console.log(`${N.yellow}File ${N.bright}${L}${N.yellow} changed, reprocessing...${N.reset}`),await Y()});o.on("SIGINT",()=>{B.close(),q.stop(),o.exit(0)})}return!0}async function I6($,z={}){let w=z.port||3000,J=z.watch!==!1,j=f.resolve($);if(!j0.existsSync(j))return console.error(`${N.red}Error: File not found: ${N.bright}${j}${N.reset}`),!1;if(j.endsWith(".md"))return DJ(j,z);else if(!j.endsWith(".stx"))return console.error(`${N.red}Error: Unsupported file type: ${N.bright}${j}${N.reset}. Only .stx and .md files are supported.`),!1;let X=f.join(o.cwd(),".stx-output");j0.mkdirSync(X,{recursive:!0}),console.log(`${N.blue}Building ${N.bright}${$}${N.reset}...`);let Y=null,Q=async()=>{try{let B=await Bun.build({entrypoints:[j],outdir:X,plugins:[K1],define:{"process.env.NODE_ENV":'"development"'},...z.stxOptions});if(!B.success)return console.error(`${N.red}Build failed:${N.reset}`,B.logs),!1;let H=B.outputs.find((A)=>A.path.endsWith(".html"));if(!H)return console.error(`${N.red}No HTML output found${N.reset}`),!1;return Y=await Bun.file(H.path).text(),!0}catch(B){return console.error(`${N.red}Error building stx file:${N.reset}`,B),!1}};if(!await Q())return!1;let q=w;try{if(q=await M6(w),q!==w)console.log(`${N.yellow}Port ${w} is busy, using port ${q} instead${N.reset}`)}catch{return console.error(`${N.red}Could not find an available port${N.reset}`),!1}console.log(`${N.blue}Starting server on ${N.cyan}http://localhost:${q}/${N.reset}...`);let K=N$({port:q,fetch(B){let H=new URL(B.url);if(H.pathname==="/")return new Response(Y,{headers:{"Content-Type":"text/html"}});let L=f.join(X,H.pathname);if(j0.existsSync(L)&&j0.statSync(L).isFile()){let y=Bun.file(L),G=f.extname(L).toLowerCase(),V="text/plain";switch(G){case".html":V="text/html";break;case".css":V="text/css";break;case".js":V="text/javascript";break;case".json":V="application/json";break;case".png":V="image/png";break;case".jpg":case".jpeg":V="image/jpeg";break;case".gif":V="image/gif";break}return new Response(y,{headers:{"Content-Type":V}})}let A=f.dirname(j),b=f.join(A,H.pathname);if(j0.existsSync(b)&&j0.statSync(b).isFile()){let y=Bun.file(b),G=f.extname(b).toLowerCase(),V="text/plain";switch(G){case".html":V="text/html";break;case".css":V="text/css";break;case".js":V="text/javascript";break;case".json":V="application/json";break;case".png":V="image/png";break;case".jpg":case".jpeg":V="image/jpeg";break;case".gif":V="image/gif";break;case".svg":V="image/svg+xml";break;case".ico":V="image/x-icon";break}return new Response(y,{headers:{"Content-Type":V}})}return new Response("Not Found",{status:404})},error(B){return new Response(`<pre>${B}
1710
+ ${B.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1711
+ ${N.blue}stx${N.reset} ${N.green}${o.env.stx_VERSION||"v0.0.10"}${N.reset} ${N.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${N.reset}`),console.log(`
1712
+ ${N.bright}\u2192 ${N.cyan}http://localhost:${w}/${N.reset}`),console.log(`
1713
+ ${N.yellow}Routes:${N.reset}`);let W=f.relative(o.cwd(),j);if(console.log(` ${N.green}\u2514\u2500 /${N.reset} \u2192 ${N.bright}${W}${N.reset}`),console.log(`
1714
+ Press ${N.cyan}h${N.reset} + ${N.cyan}Enter${N.reset} to show shortcuts`),D6(K.url.toString(),()=>{if(J)j0.watch(f.dirname(j),{recursive:!0}).close();K.stop()}),z.native)await G8(q);if(J){let B=f.dirname(j);console.log(`${N.blue}Watching ${N.bright}${B}${N.reset} for changes...`);let H=j0.watch(B,{recursive:!0},async(L,A)=>{if(A&&(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")))console.log(`${N.yellow}File ${N.bright}${A}${N.yellow} changed, rebuilding...${N.reset}`),await Q()});o.on("SIGINT",()=>{H.close(),K.stop(),o.exit(0)})}return!0}async function E6($,z={}){let w=z.port||3000,J=z.watch!==!1;for(let B of $){let H=f.resolve(B);if(!j0.existsSync(H))return console.error(`${N.red}Error: File not found: ${N.bright}${H}${N.reset}`),!1;if(!H.endsWith(".stx")&&!H.endsWith(".md"))return console.error(`${N.red}Error: Unsupported file type: ${N.bright}${H}${N.reset}. Only .stx and .md files are supported.`),!1}let j=f.join(o.cwd(),".stx-output");j0.mkdirSync(j,{recursive:!0});let X=IJ($.map((B)=>f.dirname(f.resolve(B))));console.log(`${N.blue}Processing ${N.bright}${$.length}${N.reset} files...`);let Y={},Q=async()=>{try{for(let B of $){let H=f.resolve(B);if(H.endsWith(".md"))try{let{content:A,data:b}=await k1(H,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:y0.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),y=z.markdown?.syntaxHighlighting||y0.markdown?.syntaxHighlighting,G=y?.defaultTheme||"github-dark",V=["github-dark"],O=y?.additionalThemes||[],R=[...new Set([...V,...O])].map((w0)=>`<option value="${w0}"${w0===G?" selected":""}>${w0}</option>`).join(`
1715
+ `),T=`
1716
+ <!DOCTYPE html>
1717
+ <html lang="en">
1718
+ <head>
1719
+ <meta charset="UTF-8">
1720
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1721
+ <title>${b.title||f.basename(H)}</title>
1722
+ <!-- Syntax highlighting styles -->
1723
+ <style id="syntax-theme">
1724
+ :root {
1725
+ --shiki-color-text: #24292e;
1726
+ --shiki-color-background: #ffffff;
1727
+ --shiki-token-constant: #005cc5;
1728
+ --shiki-token-string: #032f62;
1729
+ --shiki-token-comment: #6a737d;
1730
+ --shiki-token-keyword: #d73a49;
1731
+ --shiki-token-parameter: #24292e;
1732
+ --shiki-token-function: #6f42c1;
1733
+ --shiki-token-string-expression: #032f62;
1734
+ --shiki-token-punctuation: #24292e;
1735
+ --shiki-token-link: #032f62;
1736
+ }
1737
+ pre {
1738
+ background-color: var(--shiki-color-background);
1739
+ padding: 1rem;
1740
+ border-radius: 4px;
1741
+ }
1742
+ code {
1743
+ color: var(--shiki-color-text);
1744
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1745
+ }
1746
+ .dark-mode {
1747
+ --shiki-color-text: #e1e4e8;
1748
+ --shiki-color-background: #24292e;
1749
+ --shiki-token-constant: #79b8ff;
1750
+ --shiki-token-string: #9ecbff;
1751
+ --shiki-token-comment: #6a737d;
1752
+ --shiki-token-keyword: #f97583;
1753
+ --shiki-token-parameter: #e1e4e8;
1754
+ --shiki-token-function: #b392f0;
1755
+ --shiki-token-string-expression: #9ecbff;
1756
+ --shiki-token-punctuation: #e1e4e8;
1757
+ --shiki-token-link: #9ecbff;
1758
+ }
1759
+ </style>
1760
+ <style>
1761
+ body {
1762
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
1763
+ line-height: 1.6;
1764
+ color: #333;
1765
+ max-width: 800px;
1766
+ margin: 0 auto;
1767
+ padding: 2rem;
1768
+ }
1769
+ pre, code {
1770
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1771
+ }
1772
+ pre {
1773
+ border-radius: 4px;
1774
+ padding: 0;
1775
+ margin: 1.5rem 0;
1776
+ overflow-x: auto;
1777
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
1778
+ }
1779
+ pre code {
1780
+ display: block;
1781
+ padding: 1rem;
1782
+ overflow-x: auto;
1783
+ }
1784
+ /* Apply background color to code blocks based on theme */
1785
+ pre.syntax-highlighter {
1786
+ background-color: var(--shiki-color-background) !important;
1787
+ }
1788
+ .dark-mode pre.syntax-highlighter {
1789
+ background-color: var(--shiki-color-background) !important;
1790
+ }
1791
+ code {
1792
+ padding: 0.2rem 0.4rem;
1793
+ border-radius: 3px;
1794
+ }
1795
+ h1, h2, h3, h4 {
1796
+ margin-top: 2rem;
1797
+ margin-bottom: 1rem;
1798
+ }
1799
+ h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
1800
+ h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
1801
+ h3 { color: #444; }
1802
+ img {
1803
+ max-width: 100%;
1804
+ border-radius: 4px;
1805
+ margin: 1rem 0;
1806
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1807
+ }
1808
+ blockquote {
1809
+ border-left: 4px solid #ddd;
1810
+ padding-left: 1rem;
1811
+ margin-left: 0;
1812
+ color: #555;
1813
+ background: #f9f9f9;
1814
+ padding: 0.5rem 1rem;
1815
+ margin: 1.5rem 0;
1816
+ }
1817
+ table {
1818
+ border-collapse: collapse;
1819
+ width: 100%;
1820
+ margin: 1.5rem 0;
1821
+ }
1822
+ th, td {
1823
+ border: 1px solid #ddd;
1824
+ padding: 0.5rem;
1825
+ }
1826
+ th {
1827
+ background: #f0f0f0;
1828
+ text-align: left;
1829
+ }
1830
+ tr:nth-child(even) {
1831
+ background-color: #f8f8f8;
1832
+ }
1833
+ a {
1834
+ color: #0066cc;
1835
+ text-decoration: none;
1836
+ }
1837
+ a:hover {
1838
+ text-decoration: underline;
1839
+ }
1840
+ hr {
1841
+ border: 0;
1842
+ border-top: 1px solid #eee;
1843
+ margin: 2rem 0;
1844
+ }
1845
+ .frontmatter {
1846
+ background: #f8f8f8;
1847
+ border-radius: 4px;
1848
+ padding: 1.5rem;
1849
+ margin-bottom: 2rem;
1850
+ font-size: 0.9rem;
1851
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
1852
+ border-left: 4px solid #ddd;
1853
+ }
1854
+ .frontmatter-item {
1855
+ margin-bottom: 0.5rem;
1856
+ display: flex;
1857
+ }
1858
+ .frontmatter-label {
1859
+ font-weight: bold;
1860
+ min-width: 100px;
1861
+ color: #555;
1862
+ }
1863
+ /* Theme selector for code blocks */
1864
+ .theme-selector {
1865
+ margin: 1rem 0;
1866
+ padding: 0.5rem;
1867
+ background: #f8f8f8;
1868
+ border-radius: 4px;
1869
+ text-align: right;
1870
+ }
1871
+ select {
1872
+ padding: 0.25rem 0.5rem;
1873
+ border-radius: 3px;
1874
+ border: 1px solid #ddd;
1875
+ }
1876
+
1877
+ /* Dark mode body styles */
1878
+ body.dark-mode {
1879
+ background-color: #121212;
1880
+ color: #e1e4e8;
1881
+ }
1882
+
1883
+ body.dark-mode h1,
1884
+ body.dark-mode h2,
1885
+ body.dark-mode h3 {
1886
+ color: #e1e4e8;
1887
+ border-color: #2f363d;
1888
+ }
1889
+
1890
+ body.dark-mode .theme-selector {
1891
+ background: #2f363d;
1892
+ color: #e1e4e8;
1893
+ }
1894
+
1895
+ body.dark-mode select {
1896
+ background: #24292e;
1897
+ color: #e1e4e8;
1898
+ border-color: #444;
1899
+ }
1900
+
1901
+ body.dark-mode blockquote {
1902
+ background: #24292e;
1903
+ color: #e1e4e8;
1904
+ }
1905
+
1906
+ body.dark-mode .frontmatter {
1907
+ background: #24292e;
1908
+ }
1909
+
1910
+ body.dark-mode a {
1911
+ color: #58a6ff;
1912
+ }
1913
+ </style>
1914
+ </head>
1915
+ <body>
1916
+ ${Object.keys(b).length>0?`
1917
+ <div class="frontmatter">
1918
+ <h3>Frontmatter</h3>
1919
+ ${Object.entries(b).map(([w0,J0])=>`
1920
+ <div class="frontmatter-item">
1921
+ <span class="frontmatter-label">${w0}:</span>
1922
+ <span>${Array.isArray(J0)?J0.join(", "):J0}</span>
1923
+ </div>`).join("")}
1924
+ </div>
1925
+ `:""}
1926
+
1927
+ <div class="theme-selector">
1928
+ Theme:
1929
+ <select id="themeSelector" onchange="changeTheme()">
1930
+ ${R}
1931
+ </select>
1932
+ </div>
1933
+
1934
+ ${A}
1935
+
1936
+ <script>
1937
+ function changeTheme() {
1938
+ const theme = document.getElementById('themeSelector').value;
1939
+
1940
+ // Toggle dark mode class based on theme
1941
+ if (theme.includes('dark') || theme.includes('night') || theme.includes('monokai') ||
1942
+ theme.includes('dracula') || theme.includes('nord') || theme.includes('material')) {
1943
+ document.body.classList.add('dark-mode');
1944
+ } else {
1945
+ document.body.classList.remove('dark-mode');
1946
+ }
1947
+ }
1948
+
1949
+ // Initialize theme on page load
1950
+ document.addEventListener('DOMContentLoaded', function() {
1951
+ changeTheme();
1952
+ });
1953
+ </script>
1954
+ </body>
1955
+ </html>
1956
+ `,d=`/${f.relative(X,H).replace(/\.md$/,"")}`;Y[d||"/"]={filePath:H,content:T,fileType:"md"}}catch(A){console.error(`${N.red}Error processing Markdown file ${N.bright}${B}${N.reset}:`,A);continue}else{let A=await Bun.build({entrypoints:[H],outdir:j,plugins:[K1],define:{"process.env.NODE_ENV":'"development"'},...z.stxOptions});if(!A.success){console.error(`${N.red}Build failed for ${N.bright}${B}${N.reset}:`,A.logs);continue}let b=A.outputs.find((O)=>O.path.endsWith(".html"));if(!b){console.error(`${N.red}No HTML output found for ${N.bright}${B}${N.reset}`);continue}let y=await Bun.file(b.path).text(),V=`/${f.relative(X,H).replace(/\.stx$/,"")}`;Y[V||"/"]={filePath:H,content:y,fileType:"stx"}}}if(Object.keys(Y).length===0)return console.error(`${N.red}No files were successfully processed${N.reset}`),!1;return!0}catch(B){return console.error(`${N.red}Error processing files:${N.reset}`,B),!1}};if(!await Q())return!1;let q=w;try{if(q=await M6(w),q!==w)console.log(`${N.yellow}Port ${w} is busy, using port ${q} instead${N.reset}`)}catch{return console.error(`${N.red}Could not find an available port${N.reset}`),!1}console.log(`${N.blue}Starting server on ${N.cyan}http://localhost:${q}/${N.reset}...`);let K=N$({port:q,fetch(B){let H=new URL(B.url),L=Y[H.pathname];if(!L&&!H.pathname.endsWith("/"))L=Y[`${H.pathname}/`];if(!L&&H.pathname!=="/"&&Y["/"])L=Y["/"];if(L)return new Response(L.content,{headers:{"Content-Type":"text/html"}});let A=f.join(j,H.pathname);if(j0.existsSync(A)&&j0.statSync(A).isFile()){let b=Bun.file(A),y=f.extname(A).toLowerCase(),G="text/plain";switch(y){case".html":G="text/html";break;case".css":G="text/css";break;case".js":G="text/javascript";break;case".json":G="application/json";break;case".png":G="image/png";break;case".jpg":case".jpeg":G="image/jpeg";break;case".gif":G="image/gif";break}return new Response(b,{headers:{"Content-Type":G}})}return new Response("Not Found",{status:404})},error(B){return new Response(`<pre>${B}
1957
+ ${B.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1958
+ ${N.blue}stx${N.reset} ${N.green}${o.env.stx_VERSION||"v0.0.10"}${N.reset} ${N.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${N.reset}`),console.log(`
1959
+ ${N.bright}\u2192 ${N.cyan}http://localhost:${w}/${N.reset}`),console.log(`
1960
+ ${N.yellow}Routes:${N.reset}`);let W=Object.entries(Y).sort(([B],[H])=>B.localeCompare(H)).map(([B,H])=>({route:B==="/"?"/":B,filePath:f.relative(o.cwd(),H.filePath),fileType:H.fileType}));if(W.forEach((B,H)=>{let A=H===W.length-1?"\u2514\u2500 ":"\u251C\u2500 ",b=B.fileType==="md"?`${N.magenta}(markdown)${N.reset}`:"";if(B.route==="/")console.log(` ${N.green}${A}/${N.reset} \u2192 ${N.bright}${B.filePath}${N.reset} ${b}`);else{let y=B.route.split("/"),G=y[y.length-1]||y[y.length-2],V=B.route==="/"?"/":`/${G}`,O=y.slice(0,-1).join("/");if(O&&!O.startsWith("/"))O=`/${O}`;console.log(` ${N.green}${A}${V}${N.reset} \u2192 ${N.bright}${B.filePath}${N.reset} ${b}`)}}),console.log(`
1961
+ Press ${N.cyan}h${N.reset} + ${N.cyan}Enter${N.reset} to show shortcuts`),D6(K.url.toString(),()=>{if(J)j0.watch(X,{recursive:!0}).close();K.stop()}),J){console.log(`${N.blue}Watching for changes...${N.reset}`);let B=j0.watch(X,{recursive:!0},async(H,L)=>{if(!L)return;if(L.endsWith(".stx")||L.endsWith(".js")||L.endsWith(".ts")||L.endsWith(".md"))console.log(`${N.yellow}File ${N.bright}${L}${N.yellow} changed, rebuilding...${N.reset}`),await Q()});o.on("SIGINT",()=>{B.close(),K.stop(),o.exit(0)})}return!0}function IJ($){if($.length===0)return"";if($.length===1)return $[0];let z=$.map((J)=>J.split(f.sep)),w=[];for(let J=0;J<z[0].length;J++){let j=z[0][J];if(z.every((X)=>X[J]===j))w.push(j);else break}return w.join(f.sep)}J1();var __dirname="/home/runner/work/stx/stx/packages/stx/bin",U0=new D$("stx");function S6($){let z=typeof $==="string"?Number.parseInt($,10):$;if(Number.isNaN(z))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(z<1024||z>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function _6($){try{if(!z0.existsSync($)){let w=k.dirname($),J=k.basename($);if(z0.existsSync(w)){let X=z0.readdirSync(w).filter((Q)=>Q.toLowerCase().includes(J.toLowerCase().substring(0,3))||Q.endsWith(".stx")||Q.endsWith(".md")),Y=X.length>0?`File not found. Similar files in ${w}: ${X.slice(0,3).join(", ")}`:`File not found. Directory ${w} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${$}`,suggestion:Y}}return{isValid:!1,error:`File does not exist: ${$}`,suggestion:"Check the file path and try again"}}if(z0.statSync($).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${$}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(z){return{isValid:!1,error:`Cannot access file: ${$}`,suggestion:"Check file permissions and path"}}}function b$($){let z=typeof $==="string"?Number.parseInt($,10):$;if(Number.isNaN(z))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(z<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(z>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var c0=($)=>$.includes("*")||$.includes("?")||$.includes("{")||$.includes("["),SJ=($)=>$.endsWith(".stx")||$.endsWith(".md");function u0($,z=1){if(console.error(`\u274C ${$.error}`),$.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${$.suggestion}`);F.exit(z)}async function _J($,z){try{let w=["test"],J=[];if($&&$.length>0)for(let U of $)if(c0(U))try{let q=await Array.fromAsync(new Bun.Glob(U).scan({onlyFiles:!0,absolute:!0}));if(q.length===0)console.warn(`Warning: No files found matching pattern: ${U}`);else if(J.push(...q),z.verbose)console.log(`Found ${q.length} file(s) matching pattern: ${U}`)}catch(q){return console.error(`Error expanding glob pattern ${U}:`,q),!1}else J.push(U);if(J.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(w.push(...J),z.filter)w.push("--pattern",z.filter);if(z.timeout)w.push("--timeout",z.timeout.toString());if(z.reporter&&z.reporter!=="default")if(z.reporter==="junit"){let U=k.join(gJ.tmpdir(),`stx-test-report-${Date.now()}.xml`);w.push("--reporter",z.reporter),w.push("--reporter-outfile",U)}else console.warn(`Warning: Reporter '${z.reporter}' is not supported. Using default reporter.`);if(z.coverage)w.push("--coverage");if(z.watch)w.push("--watch");w.push("--preload",k.join(__dirname,"../../../test-utils/happy-dom.ts"));let j={...F.env,STX_TEST_MODE:"true",STX_TEST_UI:z.ui?"true":"false",STX_TEST_VERBOSE:z.verbose?"true":"false"},X="bun";if(z.verbose)console.log(`Running: ${X} ${w.join(" ")}`);let Y=performance.now(),Q=f8(X,w,{stdio:"inherit",shell:!1,env:j});return new Promise((U)=>{Q.on("close",(q)=>{let W=((performance.now()-Y)/1000).toFixed(2);if(q===0)U(!0);else U(!1)}),F.on("SIGINT",()=>{console.log(`
1962
+ Test run interrupted`),Q.kill("SIGINT"),F.exit(1)})})}catch(w){return console.error("Error running tests:",w instanceof Error?w.message:String(w)),!1}}var CJ=F.argv.length>=3&&(SJ(F.argv[2])&&z0.existsSync(F.argv[2])||c0(F.argv[2]));if(CJ){let $=F.argv[2],z={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let w=3;w<F.argv.length;w++){let J=F.argv[w];if(J==="--port"&&w+1<F.argv.length){let j=S6(F.argv[++w]);if(!j.isValid)u0(j);z.port=Number.parseInt(F.argv[w],10)}else if(J==="--no-watch")z.watch=!1;else if(J==="--highlight-theme"&&w+1<F.argv.length){if(!z.markdown)z.markdown={};if(!z.markdown.syntaxHighlighting)z.markdown.syntaxHighlighting={};z.markdown.syntaxHighlighting.defaultTheme=F.argv[++w]}else if(J==="--no-highlight"){if(!z.markdown)z.markdown={};if(!z.markdown.syntaxHighlighting)z.markdown.syntaxHighlighting={};z.markdown.syntaxHighlighting.enabled=!1}else if(J==="--no-highlight-unknown"){if(!z.markdown)z.markdown={};if(!z.markdown.syntaxHighlighting)z.markdown.syntaxHighlighting={};z.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(J==="--no-cache")z.cache=!1;else if(J==="--native")z.native=!0}if(c0($))try{let w=await Array.fromAsync(new Bun.Glob($).scan({onlyFiles:!0,absolute:!0})),J=$.endsWith(".stx")?w.filter((X)=>X.endsWith(".stx")):$.endsWith(".md")?w.filter((X)=>X.endsWith(".md")):w.filter((X)=>X.endsWith(".stx")||X.endsWith(".md"));if(J.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${$}`),F.exit(1);if(!await E6(J,z))F.exit(1)}catch(w){console.error("Failed to process files:",w),F.exit(1)}else I6($,z).catch((w)=>{console.error("Failed to start dev server:",w),F.exit(1)})}else{let $=function(J,j){let X=[];for(let Y=0;Y<=j.length;Y++)X[Y]=[Y];for(let Y=0;Y<=J.length;Y++)X[0][Y]=Y;for(let Y=1;Y<=j.length;Y++)for(let Q=1;Q<=J.length;Q++)if(j.charAt(Y-1)===J.charAt(Q-1))X[Y][Q]=X[Y-1][Q-1];else X[Y][Q]=Math.min(X[Y-1][Q-1]+1,X[Y][Q-1]+1,X[Y-1][Q]+1);return X[j.length][J.length]};U0.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(J)=>{try{if(await L8(J))console.log("Documentation generated successfully."),F.exit(0);else console.error("Documentation generation failed."),F.exit(1)}catch(j){console.error("Error generating documentation:",j),F.exit(1)}}),U0.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(J,j)=>{try{let{fetchCollections:X,generatePackage:Y}=await Promise.resolve().then(() => (C8(),_8));if(J==="list"){console.log(`
1963
+ \uD83D\uDCDA Fetching available icon collections...
1964
+ `);let Q=await X(),U=Object.entries(Q).sort((q,K)=>K[1].total-q[1].total);console.log(`Available collections:
1965
+ `);for(let[q,K]of U){let W=K;console.log(` ${q.padEnd(30)} ${W.name} (${W.total} icons)`)}console.log(`
1966
+ Total: ${U.length} collections`)}else if(J.startsWith("generate")){let Q=J==="generate"?"":J.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!Q)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),F.exit(1);let U=j.output||k.join(F.cwd(),"packages/collections"),q=j.icons?j.icons.split(",").map((K)=>K.trim()):void 0;await Y(Q,U,q),console.log(`
1967
+ \u2713 Package generated successfully!`),console.log(`
1968
+ To use the package:`),console.log(` 1. cd packages/collections/iconify-${Q}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${J}`),console.error("Available commands: list, generate"),F.exit(1)}catch(X){console.error("Error:",X instanceof Error?X.message:String(X)),F.exit(1)}}),U0.command("dev <file>","Start a development server for an STX file").option("--port <port>","Port to use for the dev server",{default:3000}).option("--no-watch","Disable file watching and auto-reload").option("--native","Open in a native desktop window using Zyte").option("--highlight-theme <theme>","Syntax highlighting theme for Markdown code blocks",{default:"github-dark"}).option("--no-highlight","Disable syntax highlighting for Markdown code blocks").option("--no-highlight-unknown","Disable syntax highlighting for unknown languages in Markdown").option("--no-cache","Disable caching of parsed files").example("stx dev template.stx").example("stx dev components/hero.stx --port 8080").example("stx dev **/*.stx").example("stx dev docs/guide.md").example("stx dev **/*.md").example("stx dev docs/guide.md --highlight-theme atom-one-dark").example("stx dev template.stx --native").action(async(J,j)=>{try{if(j.port!==void 0){let Y=S6(j.port);if(!Y.isValid)u0(Y)}if(j.timeout!==void 0){let Y=b$(j.timeout);if(!Y.isValid)u0(Y)}let X={syntaxHighlighting:{enabled:j.highlight!==!1,serverSide:!0,defaultTheme:j.highlightTheme||"github-dark",highlightUnknownLanguages:j.highlightUnknown!==!1}};if(c0(J)){console.log(`Expanding glob pattern: ${J}`);let Y=await F0.timeAsync("glob-expansion",async()=>{return Array.fromAsync(new Bun.Glob(J).scan({onlyFiles:!0,absolute:!0}))}),Q=J.endsWith(".stx")?Y.filter((q)=>q.endsWith(".stx")):J.endsWith(".md")?Y.filter((q)=>q.endsWith(".md")):Y.filter((q)=>q.endsWith(".stx")||q.endsWith(".md"));if(Q.length===0)console.error(`\u274C No STX or Markdown files found matching pattern: ${J}`),console.error("\uD83D\uDCA1 Try using patterns like '*.stx' or 'components/**/*.stx'"),F.exit(1);if(console.log(`Found ${Q.length} ${Q.length===1?"file":"files"} matching ${J}`),!await E6(Q,{port:j.port,watch:j.watch!==!1,native:j.native||!1,markdown:X,cache:j.cache!==!1}))F.exit(1)}else{if(!c0(J)){let Q=_6(J);if(!Q.isValid)u0(Q)}if(!await I6(J,{port:j.port,watch:j.watch!==!1,native:j.native||!1,markdown:X,cache:j.cache!==!1}))F.exit(1)}}catch(X){console.error("Error starting dev server:",X),F.exit(1)}}),U0.command("a11y [directory]","Scan STX files for accessibility issues").option("--no-recursive","Disable recursive scanning of directories").option("--ignore <paths>","Comma-separated paths to ignore",{default:""}).option("--json","Output results as JSON").option("--output <file>","Write results to a file instead of stdout").option("--fix","Automatically fix common accessibility issues").example("stx a11y ./templates").example("stx a11y --json --output a11y-report.json").action(async(J=".",j)=>{try{console.log(`Scanning ${J} for accessibility issues...`);let X=j.ignore?j.ignore.split(",").map((q)=>q.trim()):[],Y=await wz(J,{recursive:j.recursive!==!1,ignorePaths:X}),Q=Object.keys(Y).length,U=Object.values(Y).reduce((q,K)=>q+K.length,0);if(j.json){let q=JSON.stringify(Y,null,2);if(j.output)await Bun.write(j.output,q),console.log(`A11y scan results written to ${j.output}`);else console.log(q)}else if(Q===0)console.log("\u2713 No accessibility issues found!");else{console.log(`Found ${U} accessibility issues in ${Q} files:
1969
+ `);for(let[q,K]of Object.entries(Y)){let W=k.relative(F.cwd(),q);console.log(`
1970
+ ${W} (${K.length} issues):`);for(let B of K){if(console.log(` \u2022 ${B.impact.toUpperCase()}: ${B.message}`),console.log(` ${B.help}`),B.helpUrl)console.log(` More info: ${B.helpUrl}`);console.log(` Element: ${B.element.substring(0,100)}${B.element.length>100?"...":""}`),console.log("")}}if(console.log(`
1971
+ Total: ${U} issues in ${Q} files`),j.output){let q=`
1972
+ <!DOCTYPE html>
1973
+ <html lang="en">
1974
+ <head>
1975
+ <meta charset="UTF-8">
1976
+ <title>STX Accessibility Report</title>
1977
+ <style>
1978
+ body { font-family: system-ui, -apple-system, sans-serif; line-height: 1.6; max-width: 1200px; margin: 0 auto; padding: 20px; }
1979
+ h1 { color: #333; }
1980
+ .summary { margin-bottom: 30px; padding: 15px; background: #f5f5f5; border-radius: 5px; }
1981
+ .file { margin-bottom: 30px; border: 1px solid #ddd; border-radius: 5px; overflow: hidden; }
1982
+ .file-header { padding: 10px 15px; background: #eee; font-weight: bold; border-bottom: 1px solid #ddd; }
1983
+ .issue { padding: 15px; border-bottom: 1px solid #eee; }
1984
+ .issue:last-child { border-bottom: none; }
1985
+ .issue-impact { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 12px; font-weight: bold; color: white; margin-right: 10px; }
1986
+ .critical { background-color: #d00; }
1987
+ .serious { background-color: #f50; }
1988
+ .moderate { background-color: #e90; }
1989
+ .minor { background-color: #0a7; }
1990
+ .issue-element { font-family: monospace; padding: 8px; background: #f5f5f5; margin-top: 10px; border-radius: 3px; overflow: auto; }
1991
+ .help-url { font-size: 14px; }
1992
+ </style>
1993
+ </head>
1994
+ <body>
1995
+ <h1>STX Accessibility Report</h1>
1996
+
1997
+ <div class="summary">
1998
+ <p>Found ${U} accessibility issues in ${Q} files</p>
1999
+ <p>Generated on ${new Date().toLocaleString()}</p>
2000
+ </div>
2001
+
2002
+ ${Object.entries(Y).map(([K,W])=>`
2003
+ <div class="file">
2004
+ <div class="file-header">${k.relative(F.cwd(),K)} (${W.length} issues)</div>
2005
+ ${W.map((B)=>`
2006
+ <div class="issue">
2007
+ <span class="issue-impact ${B.impact}">${B.impact.toUpperCase()}</span>
2008
+ <strong>${B.message}</strong>
2009
+ <p>${B.help}</p>
2010
+ ${B.helpUrl?`<a class="help-url" href="${B.helpUrl}" target="_blank">More information</a>`:""}
2011
+ <pre class="issue-element">${B.element.replace(/</g,"&lt;").replace(/>/g,"&gt;")}</pre>
2012
+ </div>
2013
+ `).join("")}
2014
+ </div>
2015
+ `).join("")}
2016
+ </body>
2017
+ </html>
2018
+ `.trim();await Bun.write(j.output,q),console.log(`A11y scan results written to ${j.output}`)}}F.exit(U>0?1:0)}catch(X){console.error("Error scanning for accessibility issues:",X),F.exit(1)}}),U0.command("build [entrypoints...]","Bundle your STX files using Bun's bundler").option("--outdir <dir>","Output directory for bundled files",{default:"dist"}).option("--outfile <file>","Output file name (for single entrypoint)").option("--target <target>","Target environment: browser, bun, or node",{default:"browser"}).option("--format <format>","Output format: esm, cjs, or iife",{default:"esm"}).option("--port <port>","Port for dev server integration (validation only)").option("--timeout <ms>","Timeout for build operations").option("--minify","Enable minification").option("--no-minify","Disable minification").option("--sourcemap <type>","Sourcemap type: none, linked, inline, or external",{default:"none"}).option("--splitting","Enable code splitting").option("--no-splitting","Disable code splitting").option("--external <modules>","Comma-separated list of modules to exclude from bundle").option("--packages <mode>","Package handling mode: bundle or external",{default:"bundle"}).option("--watch","Watch for changes and rebuild").option("--public-path <path>","Public path for assets").option("--env <mode>","How to handle environment variables: inline, disable, or prefix*").option("--compile","Generate a standalone executable").option("--root <dir>","Project root directory").option("--verbose","Show verbose build output").example("stx build ./src/index.stx --outfile bundle.js").example("stx build ./components/*.stx --outdir dist --minify").example("stx build ./src/index.stx --outfile bundle.js --target bun").example("stx build **/*.stx --outdir dist").action(async(J,j)=>{try{if(j.port!==void 0){let H=S6(j.port);if(!H.isValid)u0(H)}if(j.timeout!==void 0){let H=b$(j.timeout);if(!H.isValid)u0(H)}console.log("Building STX files...");let X=[];if(typeof J==="string")X=[J];else if(Array.isArray(J))X=J;else X=[];if(X.length===0)console.error("Error: No entrypoints specified"),F.exit(1);for(let H of X)if(!c0(H)){let L=_6(H);if(!L.isValid){if(console.error("\u274C File not found"),L.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${L.suggestion}`);F.exit(1)}if(!H.endsWith(".stx"))console.error("\u274C File must have .stx extension"),console.error("\uD83D\uDCA1 suggestion: Only .stx files can be built"),F.exit(1)}let Y=k.join(F.cwd(),".stx-build-temp"),Q=k.resolve(j.outdir);z0.mkdirSync(Y,{recursive:!0}),z0.mkdirSync(Q,{recursive:!0});let U=[];for(let H of X)if(c0(H)){console.log(`Expanding glob pattern: ${H}`);try{let L=await Array.fromAsync(new Bun.Glob(H).scan({onlyFiles:!0,absolute:!1})),A=H.endsWith(".stx")?L:L.filter((b)=>b.endsWith(".stx"));if(A.length===0)console.warn(`Warning: No .stx files found matching pattern: ${H}`);else console.log(`Found ${A.length} STX ${A.length===1?"file":"files"} matching ${H}`),U.push(...A)}catch(L){console.error(`Error expanding glob pattern ${H}:`,L),F.exit(1)}}else if(H.endsWith(".stx"))U.push(H);else console.warn(`Warning: Skipping non-STX file: ${H}`);if(U.length===0)console.error("Error: No valid .stx files found to build"),F.exit(1);console.log(`Building ${U.length} STX ${U.length===1?"file":"files"}...`);let q=[],K=0;for(let H of U){let L=k.resolve(H),A=k.relative(F.cwd(),L);if(j.verbose)console.log(`Processing: ${A}`);try{let b=await Bun.build({entrypoints:[L],outdir:Y,plugins:[K1],target:j.target||"browser",format:j.format||"esm",minify:j.minify!==!1,sourcemap:j.sourcemap||"none",splitting:j.splitting!==!1,define:{"process.env.NODE_ENV":'"production"'}});if(!b.success){console.error(`Build failed for ${A}:`,b.logs);continue}let y=b.outputs.find((Z)=>Z.path.endsWith(".html")),G=b.outputs.filter((Z)=>Z.path.endsWith(".js")),V=b.outputs.filter((Z)=>!Z.path.endsWith(".html")&&!Z.path.endsWith(".js")),O={inputFile:A,otherOutputs:V.map((Z)=>Z.path)};if(y){O.outputHtml=y.path;let Z=await Bun.file(y.path).text(),T=(Z.match(/<script[^>]*src="([^"]+)"[^>]*><\/script>/g)||[]).map((_)=>{let d=_.match(/src="([^"]+)"/);return d?d[1]:null}).filter((_)=>_!==null).filter((_)=>_.includes("chunk-"));if(j.verbose&&T.length>0)console.log(` Script references found in HTML: ${T.join(", ")}`);O.scriptSources=T;try{let d=(await Bun.file(L).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(d){let w0=d[1];try{let X0=Function(`${w0}
2019
+ // Return all variables defined in this scope
2020
+ return {
2021
+ name: typeof name !== 'undefined' ? name : undefined,
2022
+ items: typeof items !== 'undefined' ? items : undefined,
2023
+ count: typeof count !== 'undefined' ? count : undefined
2024
+ };
2025
+ `)();if(j.verbose)console.log(" Extracted variables:",Object.keys(X0).filter((N0)=>X0[N0]!==void 0));let R0=Z,W1=/\{items\.map\(item\s*=>\s*`[\s\S]*?<li>\{item\}<\/li>[\s\S]*?`\)\.join\(['"]*\)\}/g;if(R0=R0.replace(W1,()=>{try{if(!X0.items||!Array.isArray(X0.items)){if(j.verbose)console.warn(" Warning: items is not an array in context");return"<!-- Error: items not found -->"}let N0=X0.items.map((b0)=>`
2026
+ <li>${b0}</li>
2027
+ `).join("");if(j.verbose)console.log(` Rendered items.map() with ${X0.items.length} items`);return N0}catch(N0){if(j.verbose)console.warn(` Warning: Failed to render items.map(): ${N0}`);return"<!-- Error rendering items -->"}}),R0=R0.replace(/\{([^{}]+)\}/g,(N0,b0)=>{if(b0.includes(".map(")||b0.includes(".join("))return N0;try{if(b0.trim()in X0)return String(X0[b0.trim()]);return N0}catch(B1){if(j.verbose)console.warn(` Warning: Error processing expression ${b0}: ${B1}`);return N0}}),await Bun.write(y.path,R0),j.verbose)console.log(" Processed expressions in HTML output")}catch(J0){if(j.verbose)console.warn(` Warning: Could not extract variables from script: ${J0}`)}}}catch(_){if(j.verbose)console.warn(` Warning: Could not process expressions in HTML: ${_}`)}}if(G.length>0)O.outputJs=G[0].path;if(!y)console.warn(`Warning: No HTML output generated for ${A}`);if(q.push(O),K++,j.verbose){if(console.log(` Success: ${A}`),y)console.log(` HTML: ${k.basename(y.path)}`);if(G.length>0)console.log(` JS: ${G.map((Z)=>k.basename(Z.path)).join(", ")}`);if(V.length>0)console.log(` Other: ${V.length} file(s)`)}}catch(b){console.error(`Error building ${A}:`,b)}}if(K===0)console.error("Error: No files were successfully built"),z0.rmSync(Y,{recursive:!0,force:!0}),F.exit(1);console.log(`Copying output files to ${Q}...`);let W=0;for(let H of q){let L=k.dirname(H.inputFile),A=k.basename(H.inputFile,".stx"),b=k.join(Q,L);if(z0.mkdirSync(b,{recursive:!0}),H.outputHtml){let y=await Bun.file(H.outputHtml).text(),G=k.join(b,`${A}.html`),V=/<script[^>]*src="([^"]+)"[^>]*><\/script>/g,Z=[...y.matchAll(V)].map((T)=>T[1]),R=new Map;for(let T of Z)if(T.startsWith("./")&&T.includes("chunk-")){let _=k.basename(T),d=k.join(k.dirname(H.outputHtml),_);if(z0.existsSync(d))R.set(_,d);else if(j.verbose)console.warn(` Warning: Referenced chunk file not found: ${d}`)}if(R.size>0){z0.copyFileSync(H.outputHtml,G);for(let[T,_]of R.entries()){let d=k.join(b,T);if(z0.copyFileSync(_,d),W++,j.verbose)console.log(` Copied chunk: ${k.relative(Q,d)}`)}}else z0.copyFileSync(H.outputHtml,G);W++}if(H.outputJs){let y=k.join(b,`${A}.js`);z0.copyFileSync(H.outputJs,y),W++}for(let y of H.otherOutputs){let G=k.basename(y),V=k.join(b,G);z0.copyFileSync(y,V),W++}}try{z0.rmSync(Y,{recursive:!0,force:!0})}catch{console.warn("Warning: Failed to clean up temporary directory")}console.log(`\u2713 Build successful! Built ${K} STX ${K===1?"file":"files"} with ${W} output ${W===1?"file":"files"}`);let B=0;if(q.length>0&&q.length<=10){console.log(`
2028
+ Generated files:`);for(let H of q){let L=k.dirname(H.inputFile),A=k.basename(H.inputFile,".stx");if(console.log(` ${H.inputFile} \u2192`),H.outputHtml)console.log(` HTML: ${k.join(j.outdir,L,`${A}.html`)}`);if(H.outputJs)console.log(` JS: ${k.join(j.outdir,L,`${A}.js`)}`);if(H.scriptSources&&H.scriptSources.length>0){if(B+=H.scriptSources.length,console.log(` Chunks: ${H.scriptSources.length} chunk file(s)`),j.verbose)for(let b of H.scriptSources){let y=k.basename(b);console.log(` - ${k.join(L,y)}`)}}}}if(console.log(`
2029
+ To view these files, you can use a local HTTP server:`),console.log(` cd ${j.outdir} && npx serve`),B>0)console.log(`
2030
+ Note: The build includes JavaScript chunks that need to be served over HTTP for proper functioning.`),console.log("Opening the HTML files directly may not work correctly due to browser security restrictions.");if(j.watch){console.log(`
2031
+ Watch mode enabled. Waiting for changes...`);let H=new Set(U.map((L)=>k.dirname(k.resolve(L))));for(let L of H)z0.watch(L,{recursive:!0},async(A,b)=>{if(!b)return;if(b.endsWith(".stx")||b.endsWith(".js")||b.endsWith(".ts")){console.log(`
2032
+ File changed: ${b}, rebuilding...`);let y=k.join(L,b),G=k.relative(F.cwd(),y),V=b.endsWith(".stx")?[G]:U.filter((O)=>{return k.dirname(k.resolve(O))===L});if(V.length===0){console.log("No STX files to rebuild");return}console.log(`Rebuilding ${V.length} file(s)...`);for(let O of V)try{let Z=k.resolve(O);if((await Bun.build({entrypoints:[Z],outdir:j.outdir,plugins:[K1],target:j.target||"browser",format:j.format||"esm",minify:j.minify!==!1,sourcemap:j.sourcemap||"none",splitting:j.splitting!==!1,define:{"process.env.NODE_ENV":'"production"'}})).success)console.log(` \u2713 Rebuilt ${O}`);else console.error(` \u2717 Failed to rebuild ${O}`)}catch(Z){console.error(`Error rebuilding ${O}:`,Z)}console.log("Rebuild complete")}});console.log(`Watching ${H.size} ${H.size===1?"directory":"directories"} for changes...`),console.log("Press Ctrl+C to stop")}}catch(X){console.error("Build failed:",X instanceof Error?X.message:String(X)),F.exit(1)}}),U0.command("test [patterns...]","Run tests with Bun test runner and browser environment").option("--watch","Watch for changes and rerun tests").option("--filter <pattern>","Only run tests matching the given pattern").option("--reporter <reporter>","Test reporter to use: default or junit (junit requires Bun v1.0+)",{default:"default"}).option("--timeout <ms>","Test timeout in milliseconds",{default:5000}).option("--coverage","Enable code coverage").option("--ui","Coming soon").option("--verbose","Show verbose output including test command").example("stx test").example("stx test packages/stx/test/").example("stx test **/*.test.ts --verbose").example('stx test --filter "should process"').example("stx test --watch --verbose").example("stx test --reporter junit").action(async(J,j)=>{try{if(console.log(`\x1B[1mstx test\x1B[0m \x1B[2mv${f1} (${y8})\x1B[0m`),j.timeout){let Q=b$(j.timeout);if(!Q.isValid)u0(Q)}let X=typeof J==="string"?[J]:J||[];if(X.length===0)X.push("**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js");if(j.verbose)console.log("Test patterns:",X),console.log("Options:",JSON.stringify({watch:j.watch||!1,filter:j.filter||"none",reporter:j.reporter||"default",timeout:j.timeout||5000,coverage:j.coverage||!1,ui:j.ui||!1},null,2));if(!await F0.timeAsync("test-execution",()=>_J(X,j))&&!j.watch)F.exit(1)}catch(X){console.error("Error running tests:",X),F.exit(1)}}),U0.command("init [file]","Create a new STX file").alias("new").option("--force","Overwrite existing file").option("--template <file>","Path to a template file to use as a base").example("stx init").example("stx init page.stx").example("stx new contact.stx").example("stx new components/button.stx --template examples/components/button.stx").action(async(J="index.stx",j)=>{try{if(await b8(J,{force:j.force,template:j.template}))console.log(`
2033
+ \u2728 Successfully created file: ${J}`),console.log(`
2034
+ To view it in the development server:`),console.log(` stx dev ${J}
2035
+ `);else console.error(`
2036
+ \u274C Failed to create file: ${J}`),F.exit(1)}catch(X){console.error("Error creating file:",X),F.exit(1)}}),U0.command("format [patterns...]","Format STX files automatically").option("--check","Check if files are formatted (exit with error if not)").option("--write","Write formatted files back to disk (default)").option("--diff","Show diff of changes that would be made").option("--ignore <patterns>","Comma-separated patterns to ignore").example("stx format").example("stx format **/*.stx").example("stx format --check").example("stx format --diff --ignore node_modules/**").action(async(J,j)=>{try{if(j.check&&j.write)console.error("\u274C Options --check and --write are mutually exclusive"),console.error("\uD83D\uDCA1 Use --check to verify formatting or --write to apply changes, but not both"),F.exit(1);let X=J&&J.length>0?J:["**/*.stx"],Y=j.ignore?j.ignore.split(",").map((K)=>K.trim()):[],Q=[];for(let K of X){let W=await Array.fromAsync(new Bun.Glob(K).scan({onlyFiles:!0,absolute:!0}));Q.push(...W.filter((B)=>B.endsWith(".stx")))}if(Q=Q.filter((K)=>{return!Y.some((W)=>K.includes(W))}),Q.length===0){console.log("No STX files found to format.");return}console.log(`Formatting ${Q.length} STX files...`);let U=0,q=0;for(let K of Q)try{let W=await Bun.file(K).text(),B=A8(W);if(W!==B)if(j.check)console.log(`\u274C ${k.relative(F.cwd(),K)} needs formatting`),q++;else if(j.diff)console.log(`
2037
+ \uD83D\uDCDD ${k.relative(F.cwd(),K)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${k.basename(K)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(K,B),console.log(`\u2705 Formatted ${k.relative(F.cwd(),K)}`),U++}catch(W){console.error(`\u274C Error formatting ${k.relative(F.cwd(),K)}:`,W),q++}if(j.check&&q>0)console.log(`
2038
+ ${q} files need formatting. Run 'stx format' to fix.`),F.exit(1);else if(!j.check&&!j.diff)console.log(`\u2728 Formatted ${U} files successfully`)}catch(X){console.error("Error formatting files:",X),F.exit(1)}}),U0.command("perf [command...]","Show performance statistics for STX operations").option("--clear","Clear performance statistics").option("--json","Output as JSON").example("stx perf").example("stx perf --clear").example("stx perf --json").action(async(J,j)=>{try{if(j.clear){F0.clear(),console.log("\u2705 Performance statistics cleared");return}let X=F0.getStats();if(Object.keys(X).length===0){if(j.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(j.json)console.log(JSON.stringify(X,null,2));else{console.log(`
2039
+ \uD83D\uDCCA STX Performance Statistics
2040
+ `);for(let[Y,Q]of Object.entries(X))console.log(`\uD83D\uDD27 ${Y}:`),console.log(` Count: ${Q.count}`),console.log(` Average: ${Q.avgTime.toFixed(2)}ms`),console.log(` Total: ${Q.totalTime.toFixed(2)}ms`),console.log(` Min: ${Q.minTime.toFixed(2)}ms`),console.log(` Max: ${Q.maxTime.toFixed(2)}ms`),console.log("")}}catch(X){console.error("Error showing performance stats:",X),F.exit(1)}}),U0.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(J,j)=>{try{let X=_6(J);if(!X.isValid)u0(X);console.log(`\uD83D\uDD0D Debugging stx template: ${J}
2041
+ `);let Y={};if(j.context)try{Y=JSON.parse(j.context)}catch(q){console.error("\u274C Invalid JSON in --context option"),F.exit(1)}let Q=await Bun.file(J).text();console.log(`\uD83D\uDCC4 Template Content (${Q.length} chars):`),console.log("\u2500".repeat(50)),console.log(Q.substring(0,500)+(Q.length>500?`
2042
+ ...
2043
+ `:"")),console.log("\u2500".repeat(50));let U=Q.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(U)console.log(`
2044
+ \uD83D\uDCDC Script Section Found:`),console.log("\u2500".repeat(30)),console.log(U[1].trim()),console.log("\u2500".repeat(30));if(console.log(`
2045
+ \uD83D\uDCCA Processing Context:`),console.log(JSON.stringify(Y,null,2)),j.step)console.log(`
2046
+ \u26A0\uFE0F Interactive step-through not yet implemented. Use --verbose for detailed output.`);if(j.verbose)console.log(`
2047
+ \uD83D\uDD27 Verbose processing information will be shown during template processing.`);if(console.log(`
2048
+ \u2728 Debug analysis complete. Full step-by-step debugging coming soon!`),j.saveReport){let q={file:J,timestamp:new Date().toISOString(),templateLength:Q.length,hasScript:!!U,context:Y};await Bun.write(j.saveReport,JSON.stringify(q,null,2)),console.log(`\uD83D\uDCCB Debug report saved to: ${j.saveReport}`)}}catch(X){console.error("Error debugging template:",X),F.exit(1)}}),U0.command("status [directory]","Show status of STX project and files").option("--verbose","Show detailed information").option("--json","Output as JSON").example("stx status").example("stx status ./src --verbose").action(async(J=".",j)=>{try{let X=k.resolve(J),Y=k.join(X,"stx.config.ts"),Q=k.join(X,"package.json"),U=await Array.fromAsync(new Bun.Glob("**/*.stx").scan({cwd:X,onlyFiles:!0,absolute:!0})),q=await Array.fromAsync(new Bun.Glob("**/*.md").scan({cwd:X,onlyFiles:!0,absolute:!0})),K={projectRoot:X,hasConfig:z0.existsSync(Y),hasPackageJson:z0.existsSync(Q),stxFiles:U.length,markdownFiles:q.length,totalFiles:U.length+q.length};if(j.verbose)K.stxFileList=U.map((W)=>k.relative(X,W)),K.markdownFileList=q.map((W)=>k.relative(X,W));if(j.json)console.log(JSON.stringify(K,null,2));else{if(console.log(`
2049
+ \uD83D\uDCCB stx Project Status
2050
+ `),console.log(`\uD83D\uDCC1 Project Root: ${X}`),console.log(`\u2699\uFE0F Config File: ${K.hasConfig?"\u2705 Found":"\u274C Not found"}`),console.log(`\uD83D\uDCE6 Package.json: ${K.hasPackageJson?"\u2705 Found":"\u274C Not found"}`),console.log(`\uD83D\uDCC4 stx Files: ${K.stxFiles}`),console.log(`\uD83D\uDCDD Markdown Files: ${K.markdownFiles}`),console.log(`\uD83D\uDCCA Total Files: ${K.totalFiles}`),j.verbose&&U.length>0)console.log(`
2051
+ \uD83D\uDCC4 STX Files:`),U.forEach((W)=>{console.log(` ${k.relative(X,W)}`)});if(j.verbose&&q.length>0)console.log(`
2052
+ \uD83D\uDCDD Markdown Files:`),q.forEach((W)=>{console.log(` ${k.relative(X,W)}`)})}}catch(X){console.error("Error getting project status:",X),F.exit(1)}}),U0.command("watch [patterns...]","Watch STX files for changes and run commands").option("--command <cmd>","Command to run on file changes",{default:"build"}).option("--ignore <patterns>","Comma-separated patterns to ignore").option("--debounce <ms>","Debounce delay before running command after change",{default:300}).option("--output <dir>","Output directory for command results").option("--verbose","Show detailed file change information").option("--clear","Clear console before running command").example("stx watch").example('stx watch **/*.stx --command "stx build"').example('stx watch --ignore "node_modules/**,dist/**"').action(async(J,j)=>{try{if(!J||J.length===0)console.error("\u274C Input file or pattern is required"),console.error("\uD83D\uDCA1 Specify a file pattern to watch (e.g., stx watch *.stx)"),F.exit(1);let X=Array.isArray(J)?J:[J],Y=j.ignore?j.ignore.split(",").map((L)=>L.trim()):["node_modules/**","dist/**",".git/**"];if(j.debounce!==void 0){if(!b$(j.debounce).isValid)console.error("\u274C Debounce must be a valid number"),console.error("\uD83D\uDCA1 Specify debounce in milliseconds (e.g., --debounce 300)"),F.exit(1)}if(j.output){if((j.output.match(/\.\.\//g)||[]).length>=3)console.error("\u274C Invalid output directory"),console.error("\uD83D\uDCA1 Specify a valid output directory path"),F.exit(1)}let Q=j.debounce||300;console.log(`\uD83D\uDC40 Watching files: ${X.join(", ")}`),console.log(`\uD83D\uDEAB Ignoring: ${Y.join(", ")}`),console.log(`\u23F1\uFE0F Debounce: ${Q}ms`),console.log(`\uD83D\uDD27 Command: ${j.command}`),console.log(`
2053
+ Press Ctrl+C to stop watching...
2054
+ `);let U,q=!1,K=new Set;K.add(F.cwd());for(let L of X)(await Array.fromAsync(new Bun.Glob(L).scan({onlyFiles:!0,absolute:!0}))).forEach((b)=>{K.add(k.dirname(b))});let W=async()=>{if(q)return;if(q=!0,j.clear)console.clear();console.log(`\uD83D\uDD04 Running: ${j.command}`);let L=Date.now();try{let[A,...b]=j.command.split(" ");f8(A,b,{stdio:"inherit",shell:!0}).on("close",(G)=>{let V=Date.now()-L;if(G===0)console.log(`\u2705 Command completed successfully in ${V}ms`);else console.log(`\u274C Command failed with exit code ${G} after ${V}ms`);q=!1})}catch(A){console.error("\u274C Error running command:",A),q=!1}},B=(L,A)=>{if(!A)return;if(Y.some((G)=>{if(G.includes("*"))return A.match(G.replace(/\*/g,".*"));return A.includes(G)})){if(j.verbose)console.log(`\uD83D\uDEAB Ignoring: ${A}`);return}if(!X.some((G)=>{if(G.includes("*"))return A.match(G.replace(/\*/g,".*"));return A.endsWith(G)})){if(j.verbose)console.log(`\u23ED\uFE0F Skipping: ${A} (doesn't match patterns)`);return}if(j.verbose)console.log(`\uD83D\uDCDD ${L.toUpperCase()}: ${A}`);if(U)clearTimeout(U);U=setTimeout(W,Q)},H=[];for(let L of K)try{let A=z0.watch(L,{recursive:!0},B);if(H.push(A),j.verbose)console.log(`\uD83D\uDCC1 Watching directory: ${L}`)}catch(A){console.warn(`\u26A0\uFE0F Could not watch directory: ${L}`)}F.on("SIGINT",()=>{console.log(`
2055
+ \uD83D\uDED1 Stopping file watcher...`),H.forEach((L)=>L.close()),F.exit(0)})}catch(X){console.error("Error setting up file watcher:",X),F.exit(1)}}),U0.command("analyze [patterns...]","Analyze STX templates for performance and best practices").option("--json","Output results as JSON").option("--detailed","Show detailed analysis for each file").option("--only-issues","Only show files with issues").option("--save-report <file>","Save analysis report to file").option("--threshold <level>","Only show issues at or above this level (info, warning, error)",{default:"info"}).example("stx analyze").example("stx analyze **/*.stx --detailed").example("stx analyze --only-issues --threshold warning").action(async(J,j)=>{try{let X=J&&J.length>0?J:["**/*.stx"],Y=j.threshold||"info",Q={info:0,warning:1,error:2},U=Q[Y];if(!j.json)console.log("\uD83D\uDD0D Analyzing stx templates...");let{results:q,summary:K}=await K8(X);if(q.length===0){console.log("No STX files found to analyze.");return}let W=j.onlyIssues?q.filter((B)=>B.issues.some((H)=>Q[H.type]>=U)):q;if(j.json){let B={summary:K,results:W,generatedAt:new Date().toISOString()};if(j.saveReport)await Bun.write(j.saveReport,JSON.stringify(B,null,2)),console.log(`\uD83D\uDCCB Analysis report saved to: ${j.saveReport}`);else console.log(JSON.stringify(B,null,2));return}if(console.log(`
2056
+ \uD83D\uDCCA Analysis Summary`),console.log("\u2500".repeat(50)),console.log(`\uD83D\uDCC1 Files analyzed: ${K.totalFiles}`),console.log(`\uD83D\uDCCF Total lines: ${K.totalLines.toLocaleString()}`),console.log(`\uD83E\uDDEE Average complexity: ${K.avgComplexity}/10`),console.log(`\u26A0\uFE0F Total issues: ${K.totalIssues}`),console.log(`\uD83D\uDE80 Performance score: ${K.performanceScore}/10`),Object.keys(K.issuesByCategory).length>0){console.log(`
2057
+ \uD83D\uDCCB Issues by category:`);for(let[B,H]of Object.entries(K.issuesByCategory))console.log(` ${B}: ${H}`)}if(K.recommendations.length>0)console.log(`
2058
+ \uD83D\uDCA1 Project recommendations:`),K.recommendations.forEach((B)=>{console.log(` \u2022 ${B}`)});if(j.detailed){console.log(`
2059
+ \uD83D\uDCC4 Detailed File Analysis`),console.log("\u2550".repeat(60));for(let B of W){if(console.log(`
2060
+ \uD83D\uDCDD ${k.relative(F.cwd(),B.file)}`),console.log(` Lines: ${B.metrics.lines} | Complexity: ${B.metrics.complexity}/10 | Estimated render: ${B.performance.estimatedRenderTime}ms`),B.issues.length>0){let H=B.issues.filter((L)=>Q[L.type]>=U);if(H.length>0)console.log(` Issues (${H.length}):`),H.forEach((L)=>{let A=L.type==="error"?"\u274C":L.type==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(console.log(` ${A} ${L.message}`),L.suggestion)console.log(` \uD83D\uDCA1 ${L.suggestion}`)})}if(B.suggestions.length>0)console.log(` Suggestions (${B.suggestions.length}):`),B.suggestions.forEach((H)=>{let L=H.impact==="high"?"\uD83D\uDD25":H.impact==="medium"?"\u26A1":"\uD83D\uDCAB";console.log(` ${L} ${H.message} (${H.impact} impact, ${H.effort} effort)`)})}}else if(W.length>0&&!j.onlyIssues)console.log(`
2061
+ \uD83D\uDCC4 Files with issues:`),W.forEach((B)=>{let H=B.issues.filter((L)=>Q[L.type]>=U).length;if(H>0)console.log(` ${k.relative(F.cwd(),B.file)} (${H} issues)`)});if(j.saveReport){let B={summary:K,results:W,generatedAt:new Date().toISOString(),commandOptions:j};await Bun.write(j.saveReport,JSON.stringify(B,null,2)),console.log(`
2062
+ \uD83D\uDCCB Analysis report saved to: ${j.saveReport}`)}console.log(`
2063
+ \u2728 Analysis complete! Use --detailed for more information.`)}catch(X){console.error("Error analyzing templates:",X),F.exit(1)}}),U0.command("version","Show the version of the CLI").action(()=>{console.log(f1)});let z=["docs","iconify","dev","a11y","build","test","init","new","format","perf","debug","status","watch","analyze","version"],w=F.argv.slice(2);if(w.length>0&&!w[0].startsWith("-")){let J=w[0];if(J==="")console.error("\u274C No command provided"),console.error("\uD83D\uDCA1 Use --help to see available commands"),F.exit(1);if(!z.includes(J)){let j=z.map((Y)=>({command:Y,distance:$(J,Y)}));j.sort((Y,Q)=>Y.distance-Q.distance);let X=j[0];if(X.distance<=3)console.error(`\u274C Unknown command: ${J}`),console.error(`\uD83D\uDCA1 Did you mean: ${X.command}?`),console.error(`
2064
+ Run 'stx --help' to see available commands.`),F.exit(1)}}U0.help(),U0.version(f1),U0.parse()}