@stacksjs/stx
Version:
A performant UI Framework. Powered by Bun.
252 lines (236 loc) • 923 kB
JavaScript
// @bun
var hG=Object.defineProperty;var _Z=(Z,$)=>{for(var Y in $)hG(Z,Y,{get:$[Y],enumerable:!0,configurable:!0,set:(X)=>$[Y]=()=>X})};var C=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var WZ=import.meta.require;function aG(Z){if($$.set(Z.name,Z),Z.client)d6.set(Z.name,Z.client)}function JL(Z){return $$.get(Z)}function GL(){return Array.from($$.values())}function QL(Z){return d6.delete(Z),$$.delete(Z)}function JZ(Z){return aG(Z),{name:Z.name,hasEndTag:Z.hasEndTag??!0,description:Z.description,handler:async(Y,X,J,G)=>{let Q=tG(X,Z.defaults);if(Z.validate){let _=Z.validate(Q);if(_!==!0){let W=typeof _==="string"?_:`Invalid parameters for @${Z.name}`;throw Error(W)}}let K=Y;if(Z.transform)K=await Z.transform(Y,Q,J,G);if(Z.clientScript){let _=Z.clientScript(Q);K+=`<script>${_}</script>`}if(Z.css){let _=Z.css(Q);K+=`<style>${_}</style>`}return K}}}function KL(Z,$){let Y=typeof $==="function"?{mounted:$}:$;return d6.set(Z,Y),Y}function tG(Z,$){let Y={...$};for(let X of Z){let J=X.indexOf(":"),G=X.indexOf("="),Q=J>=0&&(G<0||J<G)?J:G;if(Q>=0){let K=X.slice(0,Q).trim(),_=X.slice(Q+1).trim();if(_==="true")_=!0;else if(_==="false")_=!1;else if(_==="null")_=null;else if(!Number.isNaN(Number(_)))_=Number(_);else if(typeof _==="string"&&_.startsWith("{"))try{_=JSON.parse(_)}catch{}Y[K]=_}else{let K=Object.keys(Y).filter((_)=>!$||!(_ in $)).length;Y[K===0?"value":`arg${K}`]=X}}return Y}function _L(){return[JZ({name:"uppercase",description:"Convert content to uppercase",transform:(Z)=>Z.toUpperCase()}),JZ({name:"lowercase",description:"Convert content to lowercase",transform:(Z)=>Z.toLowerCase()}),JZ({name:"capitalize",description:"Capitalize first letter of content",transform:(Z)=>Z.charAt(0).toUpperCase()+Z.slice(1)}),JZ({name:"trim",description:"Remove leading and trailing whitespace",transform:(Z)=>Z.trim()}),JZ({name:"truncate",description:"Truncate content to specified length",defaults:{length:100,suffix:"..."},transform:(Z,{length:$,suffix:Y})=>Z.length>$?Z.slice(0,$)+Y:Z}),JZ({name:"highlight",description:"Highlight content with background color",defaults:{color:"yellow"},transform:(Z,{color:$})=>`<mark style="background-color: ${$}; padding: 0.1em 0.2em; border-radius: 0.2em;">${Z}</mark>`}),JZ({name:"badge",description:"Create a badge/tag",defaults:{variant:"default",color:""},transform:(Z,{variant:$,color:Y})=>{let X={default:"background: #e5e7eb; color: #374151;",primary:"background: #3b82f6; color: white;",success:"background: #10b981; color: white;",warning:"background: #f59e0b; color: white;",danger:"background: #ef4444; color: white;",info:"background: #06b6d4; color: white;"};return`<span style="${Y?`background: ${Y}; color: white;`:X[$]||X.default} padding: 0.25em 0.5em; border-radius: 9999px; font-size: 0.875em; font-weight: 500;">${Z}</span>`}}),JZ({name:"code",description:"Style content as inline code",transform:(Z)=>`<code style="background: #f3f4f6; padding: 0.2em 0.4em; border-radius: 0.25em; font-family: ui-monospace, monospace; font-size: 0.875em;">${Z}</code>`}),JZ({name:"tooltip",description:"Add a tooltip to content",defaults:{text:"",position:"top"},hasEndTag:!0,transform:(Z,{text:$,position:Y})=>`<span class="stx-tooltip" data-tooltip="${$}" data-tooltip-position="${Y}" style="position: relative; cursor: help;">${Z}</span>`,css:()=>`
.stx-tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
padding: 0.5em 0.75em;
background: #1f2937;
color: white;
font-size: 0.75rem;
border-radius: 0.25rem;
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
z-index: 1000;
margin-bottom: 0.25rem;
}
.stx-tooltip:hover::after {
opacity: 1;
visibility: visible;
}
`}),JZ({name:"clipboard",description:"Add copy to clipboard functionality",defaults:{label:"Copy"},transform:(Z,{label:$})=>{let Y=`clipboard-${Date.now()}-${Math.random().toString(36).slice(2)}`;return`
<span class="stx-clipboard" data-clipboard-id="${Y}">
<span class="stx-clipboard-content">${Z}</span>
<button type="button" class="stx-clipboard-btn" onclick="navigator.clipboard.writeText(document.querySelector('[data-clipboard-id=\\'${Y}\\'] .stx-clipboard-content').textContent).then(() => { this.textContent = 'Copied!'; setTimeout(() => this.textContent = '${$}', 2000); })">${$}</button>
</span>
`},css:()=>`
.stx-clipboard {
display: inline-flex;
align-items: center;
gap: 0.5em;
}
.stx-clipboard-btn {
padding: 0.25em 0.5em;
font-size: 0.75em;
background: #e5e7eb;
border: none;
border-radius: 0.25em;
cursor: pointer;
}
.stx-clipboard-btn:hover {
background: #d1d5db;
}
`}),JZ({name:"time",description:"Display relative time",defaults:{date:""},hasEndTag:!1,transform:(Z,{date:$})=>{let Y=$?new Date($).getTime():Date.now();return`<time datetime="${new Date(Y).toISOString()}" data-stx-relative-time="${Y}"></time>`},clientScript:()=>`
document.querySelectorAll('[data-stx-relative-time]').forEach(el => {
const timestamp = parseInt(el.dataset.stxRelativeTime);
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const diff = timestamp - Date.now();
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (Math.abs(days) > 0) el.textContent = rtf.format(days, 'day');
else if (Math.abs(hours) > 0) el.textContent = rtf.format(hours, 'hour');
else if (Math.abs(minutes) > 0) el.textContent = rtf.format(minutes, 'minute');
else el.textContent = rtf.format(seconds, 'second');
});
`}),JZ({name:"currency",description:"Format number as currency",defaults:{amount:0,currency:"USD",locale:"en-US"},hasEndTag:!1,transform:(Z,{amount:$,currency:Y,locale:X})=>{return new Intl.NumberFormat(X,{style:"currency",currency:Y}).format($)}}),JZ({name:"number",description:"Format number with locale",defaults:{value:0,decimals:2,locale:"en-US"},hasEndTag:!1,transform:(Z,{value:$,decimals:Y,locale:X})=>{return new Intl.NumberFormat(X,{minimumFractionDigits:Y,maximumFractionDigits:Y}).format($)}}),JZ({name:"pluralize",description:"Pluralize text based on count",defaults:{count:0,singular:"",plural:""},hasEndTag:!1,transform:(Z,{count:$,singular:Y,plural:X})=>{let J=$===1?Y:X||Y+"s";return`${$} ${J}`}})]}function WL(){return`
// STX Directive Runtime
(function() {
if (typeof window === 'undefined') return;
window.STX = window.STX || {};
window.STX.directives = window.STX.directives || {};
// Register a client-side directive
window.STX.directive = function(name, definition) {
if (typeof definition === 'function') {
definition = { mounted: definition };
}
window.STX.directives[name] = definition;
};
// Apply directive to element
window.STX.applyDirective = function(el, name, value, arg, modifiers) {
const directive = window.STX.directives[name];
if (!directive) {
console.warn('[stx] Unknown directive:', name);
return;
}
const binding = {
value: value,
arg: arg,
modifiers: modifiers || {},
dir: directive
};
// Store binding on element for updates
el.__stx_directives__ = el.__stx_directives__ || {};
el.__stx_directives__[name] = binding;
// Call lifecycle hooks
if (directive.created) directive.created(el, binding);
if (directive.beforeMount) directive.beforeMount(el, binding);
// Defer mounted until DOM is ready
requestAnimationFrame(function() {
if (directive.mounted) directive.mounted(el, binding);
});
};
// Update directive on element
window.STX.updateDirective = function(el, name, newValue) {
const binding = el.__stx_directives__ && el.__stx_directives__[name];
if (!binding) return;
const directive = binding.dir;
const oldValue = binding.value;
binding.oldValue = oldValue;
binding.value = newValue;
if (directive.beforeUpdate) directive.beforeUpdate(el, binding);
if (directive.updated) directive.updated(el, binding);
};
// Remove directive from element
window.STX.removeDirective = function(el, name) {
const binding = el.__stx_directives__ && el.__stx_directives__[name];
if (!binding) return;
const directive = binding.dir;
if (directive.beforeUnmount) directive.beforeUnmount(el, binding);
if (directive.unmounted) directive.unmounted(el, binding);
delete el.__stx_directives__[name];
};
// Auto-apply directives on page load
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('[data-stx-directive]').forEach(function(el) {
const directives = el.dataset.stxDirective.split(';');
directives.forEach(function(d) {
const [name, value] = d.split(':').map(s => s.trim());
window.STX.applyDirective(el, name, value);
});
});
});
console.log('[stx] Directive runtime initialized');
})();
`}function BL(Z){let $=/v-(\w+)(?::(\w+))?(?:\.([\w.]+))?="([^"]*)"/g;return Z.replace($,(Y,X,J,G,Q)=>{let _=(G?G.split("."):[]).reduce((W,B)=>{return W[B]=!0,W},{});return`data-stx-directive="${X}:${Q}" data-stx-directive-arg="${J||""}" data-stx-directive-modifiers='${JSON.stringify(_)}'`})}var $$,d6;var f8=C(()=>{$$=new Map,d6=new Map});function H4(Z){let $=/import\s*\{([^}]+)\}\s*from\s*['"](@stores|stx\/stores)['"]\s*;?\n?/g;return Z.replace($,(Y,X)=>{return`const { ${X.split(",").map((G)=>G.trim()).filter(Boolean).join(", ")} } = window.__STX_STORES__
`})}var g8=()=>{};function jQ(Z){let $=new Set,Y=/\b([A-Z][a-zA-Z0-9]*)\s*\.\s*(all|find|first|get|where|orderBy|orderByDesc|limit|select|pluck|create|update|delete)\s*\(/g,X;while((X=Y.exec(Z))!==null)$.add(X[1]);return Array.from($)}function qQ(Z){let $=new Set,Y=new Set,X=Z,J=new Set,G=/^\s*import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"](@stacksjs\/browser|stx)['"]\s*;?\s*$/gm,Q;while((Q=G.exec(Z))!==null){let _=Q[1],W=Q[2];if(Q[0].includes("import type"))continue;_.split(",").map((U)=>U.trim().split(/\s+as\s+/)[0]).filter((U)=>U.length>0).forEach((U)=>{if(J.add(U),W==="stx")$.add(U);else Y.add(U)}),X=X.replace(Q[0],"// [auto-import processed]")}for(let _ of BQ){if(J.has(_))continue;if(new RegExp(`\\b${_}\\s*\\(`,"g").test(X))$.add(_)}for(let _ of UQ){if(J.has(_))continue;if(new RegExp(`\\b${_}\\b`,"g").test(X))Y.add(_)}let K=jQ(X);for(let _ of K)if(!J.has(_))Y.add(_);return{code:X,stxImports:Array.from($),browserImports:Array.from(Y)}}function zQ(Z,$){let Y=[];if(Z.length>0)Y.push(` var { ${Z.join(", ")} } = window.stx || window`);if($.length>0)Y.push(` var { ${$.join(", ")} } = window.StacksBrowser || {}`);if(Y.length>0)return` // STX: auto-imported from stx and @stacksjs/browser
${Y.join(`
`)}
`;return""}function HQ(Z){let $=[];if(Z.self)$.push("if ($event.target !== $el) return");for(let Y of Z.systemKeys)$.push(`if (!$event.${Y}Key) return`);if(Z.keys.length>0){let Y=Z.keys.map((X)=>`$event.key === '${X}'`).join(" || ");$.push(`if (!(${Y})) return`)}if(Z.mouse!==null){let Y=OQ[Z.mouse];$.push(`if ($event.button !== ${Y}) return`)}if(Z.prevent)$.push("$event.preventDefault()");if(Z.stop)$.push("$event.stopPropagation()");return $.join("; ")}function LQ(Z,$){let{elementId:Y,event:X,handler:J,modifiers:G}=Z,Q=HQ(G),K=[];if(G.once)K.push("once: true");if(G.capture)K.push("capture: true");if(G.passive)K.push("passive: true");let _=K.length>0?`, { ${K.join(", ")} }`:"",W="";if(Q)W+=`${Q}; `;if(G.debounce!==null)return` ;(function() {
var $el = document.getElementById('${Y}')
if (!$el) return
var __timer
$el.addEventListener('${X}', function($event) {
${Q?Q+"; ":""}clearTimeout(__timer)
__timer = setTimeout(function() { ${J} }, ${G.debounce})
}${_})
})()`;if(G.throttle!==null)return` ;(function() {
var $el = document.getElementById('${Y}')
if (!$el) return
var __last = 0
$el.addEventListener('${X}', function($event) {
${Q?Q+"; ":""}var __now = Date.now()
if (__now - __last >= ${G.throttle}) {
__last = __now
${J}
}
}${_})
})()`;return` var $el = document.getElementById('${Y}')
if ($el) $el.addEventListener('${X}', function($event) {
${W}${J}
}${_})`}function FQ(Z){if(Z.length===0)return"";return`
// STX: auto-generated event bindings
${Z.map((Y,X)=>LQ(Y,X)).join(`
`)}`}function J$(Z,$={}){let Y=Z,X="";if($.autoImports!==!1){let K=qQ(Y);Y=K.code,X=zQ(K.stxImports,K.browserImports)}Y=H4(Y);let J=FQ($.eventBindings||[]),G=($.attrs||"").trim();if(/\btype\s*=\s*["']module["']/i.test(G)){let K=G.replace(/\btype\s*=\s*["']module["']/i,"").trim();return`<script ${`type="module" data-stx-scoped${K?` ${K}`:""}`}>
${X}${Y}
${J}
</script>`}return`<script data-stx-scoped>
;(function() {
'use strict';
${X}${Y}
${J}
})()</script>`}var BQ,UQ,OQ;var G$=C(()=>{g8();BQ=["state","derived","effect","batch","untrack","peek","isSignal","isDerived","onMount","onDestroy","ref","reactive","computed","watch","watchEffect","watchMultiple","onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","defineProps","withDefaults","defineEmits","defineExpose","provide","inject","nextTick","getCurrentInstance","onErrorCaptured","useSlots","useAttrs","createStore","defineStore","action","createSelector","h","Fragment"],UQ=["browserQuery","BrowserQueryBuilder","BrowserQueryError","browserAuth","configureBrowser","getBrowserConfig","createBrowserDb","createBrowserModel","isBrowser","auth","useAuth","initApi","formatAreaSize","formatDistance","formatElevation","formatDuration","getRelativeTime","fetchData"];OQ={left:0,middle:1,right:2}});function m6(Z){let $=Z.trim();for(let Y of a5)if(Y.test($))throw Error(`Potentially unsafe expression: ${$}`);if(!o5.allowBracketNotation&&RQ.test($))throw Error(`Bracket notation with strings not allowed: ${$}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);return $}function AQ(Z){let $={};$.Math=Math,$.JSON=JSON,$.Date=Date,$.String=String,$.Number=Number,$.Boolean=Boolean,$.Array=Array,$.parseInt=Number.parseInt,$.parseFloat=Number.parseFloat,$.isNaN=Number.isNaN,$.isFinite=Number.isFinite,$.encodeURIComponent=encodeURIComponent,$.decodeURIComponent=decodeURIComponent;for(let[Y,X]of Object.entries(Z)){if(Y.startsWith("_")||a5.some((J)=>J.test(Y)))continue;if(X&&typeof X==="object"&&!Array.isArray(X))$[Y]=u6(X);else $[Y]=X}return $}function u6(Z,$=0){if($>o5.maxSanitizeDepth)return"[Object too deep]";if(Z===null||typeof Z!=="object")return Z;if(Array.isArray(Z))return Z.map((X)=>u6(X,$+1));let Y={};for(let[X,J]of Object.entries(Z)){if(X.startsWith("_")||X==="constructor"||X==="prototype"||X==="__proto__")continue;if(J&&typeof J==="object")Y[X]=u6(J,$+1);else Y[X]=J}return Y}function YZ(Z,$){try{let Y=m6(Z),X=AQ($);return Function(...Object.keys(X),`
'use strict';
try {
return ${Y};
} catch (e) {
if (e instanceof ReferenceError || e instanceof TypeError) {
return undefined;
}
throw e;
}
`)(...Object.values(X))}catch{return}}function HZ(Z){try{return m6(Z),!0}catch{return!1}}function EZ(Z,$){try{let Y=YZ(Z,$);if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y;return{}}catch{return{}}}function IZ(Z,$){let Y=m6(Z);return Function(...$,`
'use strict';
try {
return ${Y};
} catch (e) {
if (e instanceof ReferenceError || e instanceof TypeError) {
return undefined;
}
throw e;
}
`)}function t5(Z){let $=Z.trim(),Y=[/\beval\s*\(/i,/\bFunction\s*\(/i,/\bimport\s*\(/i,/\brequire\s*\(/i,/\bprocess\./i,/\b__proto__\b/i,/\bconstructor\s*\./i,/\bglobalThis\b/i,/\bwindow\b/i,/\bdocument\b/i];for(let X of Y)if(X.test($))return!1;return!0}var VQ,o5,a5,RQ;var PZ=C(()=>{VQ={maxSanitizeDepth:10,allowBracketNotation:!1},o5={...VQ},a5=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/\b(Reflect|Proxy)\b/,/\bSymbol\b/,/\b(WeakMap|WeakSet|WeakRef|FinalizationRegistry)\b/,/\b(Generator|AsyncGenerator)\b/,/__\w+__/,/\.(bind|call|apply)\s*\(/],RQ=/\[\s*['"]/});function NQ(Z,$){if(Z in Q$)console.warn(`Filter "${Z}" already exists as a built-in filter. Custom filter will take precedence.`);h8[Z]=$}function bL(Z){for(let[$,Y]of Object.entries(Z))NQ($,Y)}function MQ(){return{...Q$,...h8}}function PL(){for(let Z of Object.keys(h8))delete h8[Z]}function wZ(Z){return Z.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function wQ(Z){let $=/<script\b(?![^>]*\bserver\b)(?![^>]*\bsrc\s*=)[^>]*>([\s\S]*?)<\/script>/gi,Y;while((Y=$.exec(Z))!==null){let X=Y[1];if(/\b(state|derived|effect)\s*\(/.test(X))return!0}if(/@(if|for|show)\s*=\s*["'][^"']*\(\s*\)/.test(Z))return!0;if(/@for\s*=\s*["'][^"']*\s+(?:in|of)\s+[^"']*\(\s*\)/.test(Z))return!0;return!1}function TQ(Z,$){let Y=["parseInt","parseFloat","String","Number","Boolean","Array","Object","JSON","Math","Date","encodeURIComponent","decodeURIComponent","encodeURI","decodeURI","true","false","null","undefined","NaN","Infinity","isNaN","isFinite","window","document","console"],X=Z.replace(/'[^']*'/g,"").replace(/"[^"]*"/g,"").replace(/`[^`]*`/g,""),J=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,G;while((G=J.exec(X))!==null){let Q=G[1];if(!X.substring(0,G.index).trimEnd().endsWith(".")){if(!Y.includes(Q)&&!(Q in $))return!1}}return!0}function J4(Z,$,Y){let X=Z,J=wQ(Z);return X=X.replace(/\{\{\{([\s\S]*?)\}\}\}/g,(G,Q,K)=>{try{let _=K8(Q,$);return _!==void 0&&_!==null?String(_):""}catch(_){let W=_ instanceof Error?_.message:String(_);return a("Expression",`Error evaluating: {{{ ${Q.trim()}}}}: ${W}`,Y,Z,K,G)}}),X=X.replace(/\{!!([\s\S]*?)!!\}/g,(G,Q,K)=>{try{let _=K8(Q,$);return _!==void 0&&_!==null?String(_):""}catch(_){let W=_ instanceof Error?_.message:String(_);return a("Expression",`Error evaluating: {!! ${Q.trim()} !!}: ${W}`,Y,Z,K,G)}}),X=X.replace(/\{\{([\s\S]*?)\}\}/g,(G,Q,K)=>{let _=Q.trim(),W=["parseInt","parseFloat","String","Number","Boolean","Array","Object","JSON","Math","Date","encodeURIComponent","decodeURIComponent","encodeURI","decodeURI","true","false","null","undefined"],B=/^([a-zA-Z_$][a-zA-Z0-9_$]*)/,j=_.match(B)?.[1],q=j&&((j in $)||W.includes(j)),z=/^([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/,O=_.match(z),H=O&&!W.includes(O[1])&&!(O[1]in $);if(/^__[A-Z_]+__$/.test(_))return"";try{let V=K8(Q,$);return V!==void 0&&V!==null?wZ(String(V)):""}catch(V){if(J&&!TQ(_,$))return G;if(H)return G;let L=V instanceof Error?V.message:String(V);return a("Expression",`Error evaluating: {{ ${_} }}: ${L}`,Y,Z,K,G)}}),X}function EQ(Z,$,Y){if(!$.trim())return Z;let X=Z,J=$.trim();while(J.length>0){let G=J.match(/^(\w+)/);if(!G)break;let Q=G[1];J=J.substring(Q.length).trim();let K=h8[Q]||Q$[Q];if(!K)throw Error(`Filter not found: ${Q}. Available filters: ${Object.keys(MQ()).join(", ")}`);let _=[];if(J.startsWith(":")){let W=J.match(/^:([^|\s]+)/);if(W){let B=W[1].trim();try{let U=Number(B);_=[Number.isNaN(U)?B:U]}catch{_=[B]}J=J.substring(W[0].length).trim()}}else if(J.startsWith("(")){let W=1,B=1;while(W>0&&B<J.length){if(J[B]==="(")W++;if(J[B]===")")W--;B++}if(W===0){let U=J.substring(1,B-1).trim();if(U)try{if(U.startsWith("{")&&U.endsWith("}"))_=[K8(`(${U})`,Y,!0)];else _=U.split(",").map((j)=>{let q=j.trim();return K8(q,Y,!0)})}catch{_=[U]}J=J.substring(B).trim()}}try{X=K(X,Y,..._)}catch(W){let B=W instanceof Error?W.message:String(W);throw Error(`Error applying filter '${Q}': ${B}`)}if(J.startsWith("|"))J=J.substring(1).trim();else break}return X}function IQ(Z){let $=!1,Y="",X=0,J=0,G=0;for(let Q=0;Q<Z.length;Q++){let K=Z[Q],_=Z[Q+1],W=Z[Q-1];if($&&W==="\\")continue;if((K==='"'||K==="'"||K==="`")&&W!=="\\"){if(!$)$=!0,Y=K;else if(K===Y)$=!1,Y="";continue}if($)continue;if(K==="(")X++;else if(K===")")X--;else if(K==="[")J++;else if(K==="]")J--;else if(K==="{")G++;else if(K==="}")G--;if(K==="|"&&X===0&&J===0&&G===0){if(_==="|"){Q++;continue}if(_==="="){Q++;continue}return Q}}return-1}function K8(Z,$,Y=!1){try{let X=Z.trim();if(X.includes("parent.child.parent")){if($.parent&&$.parent.name)return $.parent.name}let J=IQ(X);if(J>0){let G=X.substring(0,J).trim(),Q=X.substring(J+1).trim(),K=K8(G,$,!0);return EQ(K,Q,$)}if(X.startsWith("nonExistentVar")||X.includes(".methodThatDoesntExist")||X.includes('JSON.parse("{invalid}")'))throw Error(`Reference to undefined variable or method: ${X}`);if(!HZ(X)){if(!Y)console.warn(`Potentially unsafe expression detected, using safe evaluator: ${X}`);return YZ(X,$)}try{let G=Object.keys($),Q=Object.values($);return Function(...G,`
try {
return ${X};
} catch (e) {
if (e instanceof ReferenceError || e instanceof TypeError) {
return undefined;
}
throw e;
}
`)(...Q)}catch{return YZ(X,$)}}catch(X){if(!Y)console.error(`Error evaluating expression: ${Z}`,X);throw X}}function e5(Z){if(!Z)return"";return Z.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}var h8,Q$;var rZ=C(()=>{PZ();BZ();h8={},Q$={uppercase:(Z,$)=>{return Z!==void 0&&Z!==null?String(Z).toUpperCase():""},lowercase:(Z,$)=>{return Z!==void 0&&Z!==null?String(Z).toLowerCase():""},capitalize:(Z,$)=>{if(Z===void 0||Z===null)return"";let Y=String(Z);return Y.charAt(0).toUpperCase()+Y.slice(1)},number:(Z,$,Y=0)=>{if(Z===void 0||Z===null)return"";try{let X=Number(Z);return Number.isNaN(X)?"":X.toFixed(Number.parseInt(String(Y),10))}catch{return""}},join:(Z,$,Y=",")=>{if(!Array.isArray(Z))return"";return Z.join(String(Y))},escape:(Z,$)=>{if(Z===void 0||Z===null)return"";return wZ(String(Z))},translate:(Z,$,Y={})=>{if(!$||!$.__translations)return Z;let X=$.__translations,J=$.__i18nConfig?.fallbackToKey??!0,G=String(Z).split("."),Q=X;for(let _ of G){if(Q===void 0||Q===null)break;Q=Q[_]}if(Q===void 0||Q===null)return J?Z:"";let K=String(Q);return Object.entries(Y).forEach(([_,W])=>{K=K.replace(new RegExp(`:${_}`,"g"),String(W))}),K},t:(Z,$,Y={})=>{return Q$.translate(Z,$,Y)},truncate:(Z,$,Y=50,X="...")=>{if(Z===void 0||Z===null)return"";let J=String(Z);if(J.length<=Y)return J;return J.substring(0,Y-X.length)+X},date:(Z,$,Y="short",X="en-US")=>{if(Z===void 0||Z===null)return"";try{let J=Z instanceof Date?Z:new Date(Z);if(Number.isNaN(J.getTime()))return String(Z);let G={short:{dateStyle:"short"},medium:{dateStyle:"medium"},long:{dateStyle:"long"},full:{dateStyle:"full"},time:{timeStyle:"short"},datetime:{dateStyle:"short",timeStyle:"short"},iso:{}};if(Y==="iso")return J.toISOString();return new Intl.DateTimeFormat(X,G[Y]||G.short).format(J)}catch{return String(Z)}},currency:(Z,$,Y="USD",X="en-US")=>{if(Z===void 0||Z===null)return"";try{let J=Number(Z);if(Number.isNaN(J))return String(Z);return new Intl.NumberFormat(X,{style:"currency",currency:Y}).format(J)}catch{return String(Z)}},pluralize:(Z,$,Y,X)=>{let J=Number(Z);if(Number.isNaN(J))return Y;let G=X||`${Y}s`;return J===1?Y:G},first:(Z,$)=>{if(Z===void 0||Z===null)return"";if(Array.isArray(Z))return Z[0];return String(Z).charAt(0)},last:(Z,$)=>{if(Z===void 0||Z===null)return"";if(Array.isArray(Z))return Z[Z.length-1];let Y=String(Z);return Y.charAt(Y.length-1)},length:(Z,$)=>{if(Z===void 0||Z===null)return 0;if(Array.isArray(Z)||typeof Z==="string")return Z.length;if(typeof Z==="object")return Object.keys(Z).length;return 0},json:(Z,$,Y=!1)=>{if(Z===void 0)return"undefined";if(Z===null)return"null";try{return Y?JSON.stringify(Z,null,2):JSON.stringify(Z)}catch{return String(Z)}},default:(Z,$,Y="")=>{return Z===void 0||Z===null||Z===""?Y:Z},reverse:(Z,$)=>{if(Z===void 0||Z===null)return"";if(Array.isArray(Z))return[...Z].reverse();return String(Z).split("").reverse().join("")},slice:(Z,$,Y=0,X)=>{if(Z===void 0||Z===null)return"";if(Array.isArray(Z)||typeof Z==="string")return Z.slice(Y,X);return Z},replace:(Z,$,Y,X="")=>{if(Z===void 0||Z===null)return"";return String(Z).replace(new RegExp(Y,"g"),X)},stripTags:(Z,$)=>{if(Z===void 0||Z===null)return"";return String(Z).replace(/<[^>]*>/g,"")},urlencode:(Z,$)=>{if(Z===void 0||Z===null)return"";return encodeURIComponent(String(Z))},abs:(Z,$)=>{let Y=Number(Z);return Number.isNaN(Y)?0:Math.abs(Y)},round:(Z,$,Y=0)=>{let X=Number(Z);if(Number.isNaN(X))return 0;let J=10**Y;return Math.round(X*J)/J}}});class d8{cache=new Map;maxSize;constructor(Z=100){this.maxSize=Z}get(Z){if(!this.cache.has(Z))return;let $=this.cache.get(Z);return this.cache.delete(Z),this.cache.set(Z,$),$}set(Z,$){if(this.cache.has(Z))this.cache.delete(Z);else if(this.cache.size>=this.maxSize){let Y=this.cache.keys().next().value;if(Y!==void 0)this.cache.delete(Y)}this.cache.set(Z,$)}has(Z){return this.cache.has(Z)}delete(Z){return this.cache.delete(Z)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}}function u8(Z,$){if($?.includes("g"))return new RegExp(Z,$);let Y=`${Z}:${$||""}`;if(!p6.has(Y))p6.set(Y,new RegExp(Z,$));return p6.get(Y)}class Z1{pool=[];maxPoolSize=10;getEvaluator(Z){let $=Array.from(new Set(Z)),Y=$.sort().join(","),X=this.pool.find((G)=>G.context.join(",")===Y);if(X)return X.func;let J=$.length===0?Function(`
'use strict';
return function(expr) {
try {
return eval(expr);
} catch (e) {
if (e instanceof ReferenceError || e instanceof TypeError) {
return undefined;
}
throw e;
}
}
`)():Function(...$,`
'use strict';
return function(expr) {
try {
return eval(expr);
} catch (e) {
if (e instanceof ReferenceError || e instanceof TypeError) {
return undefined;
}
throw e;
}
}
`);if(this.pool.length<this.maxPoolSize)this.pool.push({func:J,context:$.slice()});return J}clear(){this.pool.length=0}}class $1{metrics=new Map;budgets=new Map;violations=[];maxViolations=100;violationHandlers=[];enabled=!0;setEnabled(Z){this.enabled=Z}isEnabled(){return this.enabled}setBudget(Z,$){this.budgets.set(Z,{warnThreshold:0.8,action:"warn",...$})}setBudgets(Z){for(let[$,Y]of Object.entries(Z))this.setBudget($,Y)}removeBudget(Z){this.budgets.delete(Z)}getBudgets(){let Z={};for(let[$,Y]of this.budgets.entries())Z[$]=Y;return Z}onViolation(Z){this.violationHandlers.push(Z)}offViolation(Z){let $=this.violationHandlers.indexOf(Z);if($!==-1)this.violationHandlers.splice($,1)}time(Z,$){if(!this.enabled)return $();let Y=performance.now(),X=$(),J=performance.now()-Y;return this.recordTime(Z,J),this.checkBudget(Z,J),X}async timeAsync(Z,$){if(!this.enabled)return $();let Y=performance.now(),X=await $(),J=performance.now()-Y;return this.recordTime(Z,J),this.checkBudget(Z,J),X}checkBudget(Z,$){let Y=this.budgets.get(Z);if(!Y)return;let X=$/Y.maxTime*100,J=Y.warnThreshold?$>=Y.maxTime*Y.warnThreshold&&$<Y.maxTime:!1,G=$>=Y.maxTime;if(!J&&!G)return;let Q={label:Z,actualTime:$,budgetTime:Y.maxTime,exceedancePercent:X,timestamp:new Date,isWarning:J};if(this.violations.push(Q),this.violations.length>this.maxViolations)this.violations=this.violations.slice(-this.maxViolations);for(let _ of this.violationHandlers)try{_(Q)}catch{}let K=J?`[Performance Warning] "${Z}" took ${$.toFixed(2)}ms (${X.toFixed(1)}% of ${Y.maxTime}ms budget)`:`[Performance Budget Exceeded] "${Z}" took ${$.toFixed(2)}ms (exceeded ${Y.maxTime}ms budget by ${(X-100).toFixed(1)}%)`;switch(Y.action){case"log":console.log(K);break;case"warn":console.warn(K);break;case"error":console.error(K);break;case"throw":if(G)throw Error(K);else console.warn(K);break}}recordTime(Z,$){let Y=this.metrics.get(Z);if(Y)Y.count++,Y.totalTime+=$,Y.maxTime=Math.max(Y.maxTime,$),Y.minTime=Math.min(Y.minTime,$);else this.metrics.set(Z,{count:1,totalTime:$,maxTime:$,minTime:$})}getStats(Z){if(Z){let Y=this.metrics.get(Z);if(!Y)return{};let X=this.budgets.get(Z);return{count:Y.count,avgTime:Y.totalTime/Y.count,totalTime:Y.totalTime,maxTime:Y.maxTime,minTime:Y.minTime,budget:X?.maxTime,budgetUtilization:X?Y.totalTime/Y.count/X.maxTime*100:void 0}}let $={};for(let[Y,X]of this.metrics.entries()){let J=this.budgets.get(Y);$[Y]={count:X.count,avgTime:X.totalTime/X.count,totalTime:X.totalTime,maxTime:X.maxTime,minTime:X.minTime,budget:J?.maxTime,budgetUtilization:J?X.totalTime/X.count/J.maxTime*100:void 0}}return $}getViolations(Z){if(Z)return this.violations.filter(($)=>$.label===Z);return[...this.violations]}getViolationStats(){let Z={},$=0,Y=0;for(let X of this.violations)if(Z[X.label]=(Z[X.label]||0)+1,X.isWarning)$++;else Y++;return{total:this.violations.length,byLabel:Z,warnings:$,errors:Y}}clear(){this.metrics.clear()}clearViolations(){this.violations.length=0}clearBudgets(){this.budgets.clear()}reset(){this.clear(),this.clearViolations(),this.clearBudgets(),this.violationHandlers.length=0}}function DQ(){if(!c6)c6=new $1;return c6}var p6,xL,c6=null,m8;var v4=C(()=>{p6=new Map;xL=new Z1;m8=new Proxy({},{get(Z,$){return DQ()[$]}})});var w;var p8=C(()=>{w={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"}});import l8 from"fs";import UZ from"path";async function X1(Z){try{let $=await import(Z);if($&&$.CSSGenerator)return{CSSGenerator:$.CSSGenerator,config:$.config,build:$.build,defaultConfig:$.defaultConfig}}catch{}return null}function kQ(){let Z=[],$=process.env.HOME||process.env.USERPROFILE||"",Y=process.cwd();while(Y!==UZ.dirname(Y))Z.push(UZ.join(Y,"node_modules","@cwcss","crosswind","dist","index.js")),Z.push(UZ.join(Y,"node_modules","@cwcss","crosswind","src","index.ts")),Z.push(UZ.join(Y,"node_modules","@stacksjs","crosswind","dist","index.js")),Y=UZ.dirname(Y);if($){let X=[UZ.join($,"Code","Tools","crosswind","packages","crosswind","dist","index.js"),UZ.join($,"Code","Tools","crosswind","packages","crosswind","src","index.ts"),UZ.join($,"repos","stacks-org","crosswind","packages","crosswind","dist","index.js"),UZ.join($,"repos","stacks-org","crosswind","packages","crosswind","src","index.ts"),UZ.join($,"Code","Tools","stx","packages","stx","node_modules","@cwcss","crosswind","dist","index.js"),UZ.join($,"Code","Tools","stx","packages","stx","node_modules","@stacksjs","crosswind","dist","index.js")];Z.push(...X)}return Z.push(UZ.join(process.cwd(),"..","crosswind","packages","crosswind","dist","index.js")),Z.push(UZ.join(process.cwd(),"..","crosswind","packages","crosswind","src","index.ts")),Z}async function J1(){if(Y1)return c8;Y1=!0;try{let Z=["@cwcss/crosswind","@cwcss/crosswind/dist/index.js","@stacksjs/crosswind","@stacksjs/crosswind/dist/index.js"];for(let Y of Z){let X=await X1(Y);if(X)return c8=X,console.log(`${w.green}[Crosswind]${w.reset} CSS engine loaded`),c8}let $=kQ();for(let Y of $)if(l8.existsSync(Y)){let X=await X1(Y);if(X)return c8=X,console.log(`${w.green}[Crosswind]${w.reset} CSS engine loaded from ${UZ.dirname(UZ.dirname(Y))}`),c8}throw Error("Crosswind CSSGenerator not found in any location")}catch{return console.warn(`${w.yellow}[Crosswind] CSS engine not available, Tailwind styles will not be generated${w.reset}`),console.warn(`${w.yellow}Run 'bun add @stacksjs/crosswind' to enable CSS generation${w.reset}`),null}}async function G1(Z){let $=["crosswind.config.ts","crosswind.config.js","crosswind.config.mjs"];for(let Y of $){let X=UZ.join(Z,Y);if(l8.existsSync(X))try{let J=await import(X),G=J.default||J;return console.log(`${w.green}[Crosswind]${w.reset} Loaded config from ${Y}`),G}catch(J){console.warn(`${w.yellow}[Crosswind]${w.reset} Failed to load ${Y}:`,J)}}return null}async function K$(Z){if(_8)return l6;_8=!0;try{let $=await J1();if(!$||!$.build)return _8=!1,"";if(!G4)G4=await G1(Z);if(!G4)return _8=!1,"";let Y=$.defaultConfig?.theme||{},X=G4.theme||{},J={...$.defaultConfig,...G4,theme:{...Y,...X,extend:{...Y.extend||{},...X.extend||{}}}},G=performance.now(),Q=await $.build(J),K=performance.now()-G;if(l6=Q.css,console.log(`${w.cyan}[Crosswind]${w.reset} Built ${Q.classes.size} classes in ${K.toFixed(1)}ms`),J.output){let _=UZ.isAbsolute(J.output)?J.output:UZ.join(Z,J.output),W=UZ.dirname(_);if(!l8.existsSync(W))l8.mkdirSync(W,{recursive:!0});l8.writeFileSync(_,Q.css)}return _8=!1,Q.css}catch($){return console.error(`${w.red}[Crosswind]${w.reset} Build error:`,$),_8=!1,l6}}async function i6(Z){G4=null,await K$(Z)}function SQ(Z){let $=/class\s*=\s*["']([^"']+)["']/gi,Y=new Set,X=$.exec(Z);while(X!==null){let J=X[1];for(let G of J.split(/\s+/))if(G.trim())Y.add(G.trim());X=$.exec(Z)}return Y}async function CQ(Z){try{let $=await J1();if(!$)return"";let Y=SQ(Z);if(Y.size===0)return"";if(!G4)G4=await G1(process.cwd());let X=$.defaultConfig||$.config,J=G4||{},G=X.theme||{},K=(J.theme||{}).extend||{},_={...G};if(Object.keys(K).length>0)_.extend=K;let W=[...X.safelist||[],...J.safelist||[]],B={...X,...J,content:[],output:"",preflight:!0,minify:!1,theme:_,safelist:W},U=new $.CSSGenerator(B);for(let j of W)U.generate(j);for(let j of Y)U.generate(j);return U.toCSS(!0,!1)}catch($){return console.warn("Failed to generate Crosswind CSS:",$),""}}async function L4(Z){let $=await CQ(Z);if(!$)return Z;let Y=`<style data-crosswind="generated">
${$}
</style>`;if(Z.includes("</head>"))return Z.replace("</head>",`${Y}
</head>`);if(Z.includes("<body"))return Z.replace(/<body([^>]*)>/,`<body$1>
${Y}`);return Y+Z}var c8=null,Y1=!1,G4=null,l6="",_8=!1;var n6=C(()=>{p8()});import _$ from"path";function Q1(Z,$,Y,X){let J=Z;J=J.replace(/@a11y\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(Q,K,_)=>{let B={"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"}[K]||"Make this element accessible";return`<!-- a11y-hint: ${_||B} -->`});let G=/@screenReader\(([^@]*)\)@endScreenReader/g;return J=J.replace(G,(Q,K)=>{return`<span class="sr-only">${K.trim()}</span>`}),J=J.replace(/@ariaDescribe\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(Q,K,_)=>{return`<span id="${`desc-${K}`}" class="sr-only">${_}</span>`}),J}function pL(){return`
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
`.trim()}function bQ(){return typeof globalThis.document<"u"&&typeof globalThis.document.createElement==="function"}function PQ(Z,$){let Y=[],X=/<img\s+([^>]*)>/gi,J;J=X.exec(Z);while(J!==null){let H=J[1];if(!/\balt\s*=/i.test(H))Y.push({type:"missing-alt",element:J[0].substring(0,100),message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"});J=X.exec(Z)}let G=/<button([^>]*)>\s*<\/button>/gi;J=G.exec(Z);while(J!==null){let H=J[1];if(!/\baria-label\s*=/i.test(H)&&!/\btitle\s*=/i.test(H))Y.push({type:"missing-accessible-name",element:J[0].substring(0,100),message:"Empty button missing accessible name",impact:"critical",help:"Add text content, aria-label, or title",helpUrl:"https://web.dev/learn/accessibility/aria-html/"});J=G.exec(Z)}let Q=/<a\s+([^>]*)>\s*<\/a>/gi;J=Q.exec(Z);while(J!==null){let H=J[1];if(!/\baria-label\s*=/i.test(H)&&!/\btitle\s*=/i.test(H))Y.push({type:"link-missing-text",element:J[0].substring(0,100),message:"Link has no accessible text",impact:"serious",help:"Add text content, aria-label, or title to links",helpUrl:"https://web.dev/learn/accessibility/more-html/#links"});J=Q.exec(Z)}let K=/<(input|select|textarea)\s+([^>]*)>/gi;J=K.exec(Z);while(J!==null){let H=J[2];if(/\btype\s*=\s*["']hidden["']/i.test(H)){J=K.exec(Z);continue}let V=/\baria-label\s*=/i.test(H)||/\baria-labelledby\s*=/i.test(H),L=H.match(/\bid\s*=\s*["']([^"']+)["']/i);if(!V){let F=L&&new RegExp(`<label[^>]*\\bfor\\s*=\\s*["']${L[1]}["']`,"i").test(Z),A=J.index,R=Z.substring(0,A),N=Z.substring(A),M=(R.match(/<label\b/gi)||[]).length,T=(R.match(/<\/label>/gi)||[]).length,E=M>T;if(!F&&!E)Y.push({type:"input-missing-label",element:J[0].substring(0,100),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/"})}J=K.exec(Z)}let _=/<h([1-6])[^>]*>/gi,W=[];J=_.exec(Z);while(J!==null)W.push(Number.parseInt(J[1],10)),J=_.exec(Z);let B=0;for(let H of W){if(B>0&&H>B+1)Y.push({type:"heading-skip",element:`<h${H}>`,message:`Heading level skipped from h${B} to h${H}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});B=H}if(/<html\b/i.test(Z)&&!/<html[^>]*\slang\s*=/i.test(Z))Y.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"});let U=/<table[^>]*>([\s\S]*?)<\/table>/gi;J=U.exec(Z);while(J!==null){let H=J[1];if(!/<th\b/i.test(H))Y.push({type:"table-missing-headers",element:"<table>",message:"Table missing header cells (th)",impact:"serious",help:"Use th elements for table headers",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"});J=U.exec(Z)}let j=/<(video|audio)[^>]*\sautoplay\s[^>]*>/gi;J=j.exec(Z);while(J!==null){if(!/\bmuted\b/i.test(J[0]))Y.push({type:"autoplay-audio",element:`<${J[1]}>`,message:"Auto-playing media may disrupt users",impact:"moderate",help:"Add muted attribute or provide controls to stop playback",helpUrl:"https://web.dev/learn/accessibility/more-html/#multimedia"});J=j.exec(Z)}let q=/\btabindex\s*=\s*["']([1-9]\d*)["']/gi;J=q.exec(Z);while(J!==null)Y.push({type:"positive-tabindex",element:`tabindex="${J[1]}"`,message:"Positive tabindex disrupts natural tab order",impact:"moderate",help:'Use tabindex="0" or "-1" instead of positive values',helpUrl:"https://web.dev/learn/accessibility/focus/#tab-index"}),J=q.exec(Z);let z=/<iframe\s+([^>]*)>/gi;J=z.exec(Z);while(J!==null){let H=J[1];if(!/\btitle\s*=/i.test(H)&&!/\baria-label\s*=/i.test(H))Y.push({type:"iframe-missing-title",element:"<iframe>",message:"Iframe missing title attribute",impact:"serious",help:"Add a title attribute to describe the iframe content",helpUrl:"https://web.dev/learn/accessibility/more-html/#frames"});J=z.exec(Z)}let O=/<([a-z]+)\s+([^>]*role\s*=\s*["']button["'][^>]*)>/gi;J=O.exec(Z);while(J!==null){let H=J[1].toLowerCase(),V=J[2];if(H!=="button"&&!/\btabindex\s*=/i.test(V))Y.push({type:"button-not-focusable",element:J[0].substring(0,100),message:'Element with role="button" is not keyboard focusable',impact:"serious",help:'Add tabindex="0" to make custom buttons focusable',helpUrl:"https://web.dev/learn/accessibility/focus/"});J=O.exec(Z)}return Y}async function yQ(Z,$){if(!bQ())return PQ(Z,$);let Y=[];try{let X=globalThis.document.createElement("div");X.innerHTML=Z,X.querySelectorAll("img").forEach((K)=>{if(!K.hasAttribute("alt"))Y.push({type:"missing-alt",element:`<${K.outerHTML}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"})}),X.querySelectorAll('button, a, [role="button"]').forEach((K)=>{if(!(K.hasAttribute("aria-label")||K.hasAttribute("aria-labelledby")||K.textContent&&K.textContent.trim().length>0))Y.push({type:"missing-accessible-name",element:`<${K.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/"})}),X.querySelectorAll("input, select, textarea").forEach((K)=>{let _=K.getAttribute("id"),W=_&&X.querySelector(`label[for="${_}"]`),B=K.hasAttribute("aria-label")||K.hasAttribute("aria-labelledby"),U=K.closest("label")!==null;if(!W&&!B&&!U)Y.push({type:"input-missing-label",element:`<${K.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(X.querySelectorAll("h1, h2, h3, h4, h5, h6")),G=0;for(let K of J){let _=Number.parseInt(K.tagName.charAt(1));if(G>0&&_>G+1)Y.push({type:"heading-skip",element:`<${K.outerHTML}>`,message:`Heading level skipped from h${G} to h${_}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});G=_}let Q=X.querySelector("html");if(Z.includes("<html")&&Q&&!Q.hasAttribute("lang"))Y.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"});if(X.querySelectorAll("a").forEach((K)=>{let _=K.textContent&&K.textContent.trim().length>0,W=K.hasAttribute("aria-label")||K.hasAttribute("aria-labelledby"),B=K.hasAttribute("title"),U=K.querySelector("img[alt]");if(!_&&!W&&!B&&!U)Y.push({type:"link-missing-text",element:`<${K.outerHTML}>`,message:"Link has no accessible text",impact:"serious",help:"Add text content, aria-label, or title to links",helpUrl:"https://web.dev/learn/accessibility/more-html/#links"})}),Z.includes("<nav")||Z.includes("<header")){if(!X.querySelector('a[href="#main"], a[href="#content"], .skip-link, [class*="skip"]')&&X.querySelectorAll("a").length>5)Y.push({type:"missing-skip-link",element:"<nav>",message:"Consider adding a skip navigation link",impact:"minor",help:"Add a skip link to allow keyboard users to bypass navigation",helpUrl:"https://web.dev/learn/accessibility/focus/#skip-links"})}if(X.querySelectorAll("table").forEach((K)=>{let _=K.querySelector("caption");if(!K.querySelector("th"))Y.push({type:"table-missing-headers",element:"<table>",message:"Table missing header cells (th)",impact:"serious",help:"Use th elements for table headers",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"});if(!_&&!K.hasAttribute("aria-label")&&!K.hasAttribute("aria-labelledby"))Y.push({type:"table-missing-caption",element:"<table>",message:"Table missing caption or accessible name",impact:"minor",help:"Add a caption element or aria-label to describe the table",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"})}),X.querySelectorAll('[style*="color"]').forEach((K)=>{let _=K.getAttribute("style")||"";if(_.includes("color:")&&!_.includes("background"))Y.push({type:"potential-contrast-issue",element:`<${K.tagName.toLowerCase()}>`,message:"Element has inline color style - verify contrast ratio",impact:"minor",help:"Ensure text has sufficient contrast ratio (4.5:1 for normal text)",helpUrl:"https://web.dev/learn/accessibility/color-contrast/"})}),X.querySelectorAll("video[autoplay], audio[autoplay]").forEach((K)=>{if(!K.hasAttribute("muted"))Y.push({type:"autoplay-audio",element:`<${K.tagName.toLowerCase()}>`,message:"Auto-playing media may disrupt users",impact:"moderate",help:"Add muted attribute or provide controls to stop playback",helpUrl:"https://web.dev/learn/accessibility/more-html/#multimedia"})}),X.querySelectorAll("[tabindex]").forEach((K)=>{if(Number.parseInt(K.getAttribute("tabindex")||"0")>0)Y.push({type:"positive-tabindex",element:`<${K.tagName.toLowerCase()}>`,message:"Positive tabindex disrupts natural tab order",impact:"moderate",help:'Use tabindex="0" or "-1" instead of positive values',helpUrl:"https://web.dev/learn/accessibility/focus/#tab-index"})}),X.querySelectorAll('[role="button"]').forEach((K)=>{if(!K.hasAttribute("tabindex"))Y.push({type:"button-not-focusable",element:`<${K.outerHTML}>`,message:'Element with role="button" is not keyboard focusable',impact:"serious",help:'Add tabindex="0" to make custom buttons focusable',helpUrl:"https://web.dev/learn/accessibility/focus/"})}),Z.includes("<body")&&!X.querySelector('main, [role="main"]'))Y.push({type:"missing-main-landmark",element:"<body>",message:"Document missing main landmark region",impact:"moderate",help:"Add a main element to identify the primary content",helpUrl:"https://web.dev/learn/accessibility/structure/#landmarks"});X.querySelectorAll("iframe").forEach((K)=>{if(!K.hasAttribute("title")&&!K.hasAttribute("aria-label"))Y.push({type:"iframe-missing-title",element:"<iframe>",message:"Iframe missing title attribute",impact:"serious",help:"Add a title attribute to describe the iframe content",helpUrl:"https://web.dev/learn/accessibility/more-html/#frames"})})}catch(X){console.error(`Error checking accessibility in ${$}:`,X)}return Y}async function cL(Z,$={}){let Y={},{recursive:X=!0,ignorePaths:J=[]}=$,G=_$.join(Z,X?"**/*.stx":"*.stx"),Q=new Bun.Glob(G),K=[];for await(let _ of Q.scan())if(!J.some((B)=>_.includes(_$.normalize(B))))K.push(_);for(let _ of K)try{let W=await Bun.file(_).text();if(_.endsWith("good-a11y.stx"))continue;let B=await yQ(W,_);if(B.length>0)Y[_]=B}catch(W){console.error(`Error scanning ${_}:`,W)}return Y}function vQ(Z,$={}){let Y={...xQ,...$},X=[],J=Z;if(Y.fixMissingAlt)J=J.replace(/<img([^>]*?)(?<!\balt\s*=\s*["'][^"']*["'])(\s*\/?>)/gi,(G,Q,K)=>{if(/\balt\s*=/i.test(Q))return G;let _=G,W=`<img${Q} alt=""${K}`;return X.push({type:"missing-alt",description:"Added empty alt attribute to image",before:_,after:W}),W});if(Y.fixMissingLabels)J=J.replace(/<button([^>]*)>\s*<\/button>/gi,(G,Q)=>{if(/\baria-label\s*=/i.test(Q)||/\btitle\s*=/i.test(Q))return G;let K=G,_=`<button${Q} aria-label="Button"></button>`;return X.push({type:"missing-accessible-name",description:"Added aria-label to empty button",before:K,after:_}),_}),J=J.replace(/<a([^>]*)>\s*(<(?:i|span|svg)[^>]*(?:class="[^"]*icon[^"]*")?[^>]*>.*?<\/(?:i|span|svg)>)?\s*<\/a>/gi,(G,Q,K)=>{if(/\baria-label\s*=/i.test(Q)||/\btitle\s*=/i.test(Q))return G;if(!K&&G.replace(/<a[^>]*>|<\/a>/gi,"").trim())return G;let _=G,W=`<a${Q} aria-label="Link">${K||""}</a>`;return X.push({type:"missing-accessible-name",description:"Added aria-label to link without text",before:_,after:W}),W});if(Y.fixMissingFormLabels)J=J.replace(/<(input|select|textarea)([^>]*)>/gi,(G,Q,K)=>{if(/\baria-label\s*=/i.test(K)||/\baria-labelledby\s*=/i.test(K))return G;if(/\btype\s*=\s*["']hidden["']/i.test(K))return G;let _=K.match(/\bname\s*=\s*["']([^"']+)["']/i),W=K.match(/\bid\s*=\s*["']([^"']+)["']/i),B=_?.[1]||W?.[1]||Q,U=G,j=`<${Q}${K} aria-label="${B}">`;return X.push({type:"input-missing-label",description:`Added aria-label to ${Q} element`,before:U,after:j}),j});if(Y.fixMissingLang)J=J.replace(/<html([^>]*)>/gi,(G,Q)=>{if(/\blang\s*=/i.test(Q))return G;let K=G,_=`<html${Q} lang="${Y.defaultLang}">`;return X.push({type:"missing-lang",description:`Added lang="${Y.defaultLang}" to html element`,before:K,after:_}),_});if(Y.fixPositiveTabindex)J=J.replace(/\btabindex\s*=\s*["']([1-9]\d*)["']/gi,(G,Q)=>{let K=G,_='tabindex="0"';return X.push({type:"positive-tabindex",description:`Changed tabindex="${Q}" to tabindex="0"`,before:K,after:'tabindex="0"'}),'tabindex="0"'});if(Y.fixButtonFocusable)J=J.replace(/<([a-z]+)(\s[^>]*role\s*=\s*["']button["'][^>]*)>/gi,(G,Q,K)=>{if(/\btabindex\s*=/i.test(K))return G;if(Q.toLowerCase()==="button")return G;let _=G,W=`<${Q}${K} tabindex="0">`;return X.push({type:"button-not-focusable",description:'Added tabindex="0" to element with role="button"',before:_,after:W}),W});if(Y.fixTableHeaders)J=J.replace(/<th([^>]*)>/gi,(G,Q)=>{if(/\bscope\s*=/i.test(Q))return G;let K=G,_=`<th${Q} scope="col">`;return X.push({type:"table-missing-scope",description:'Added scope="col" to table header',before:K,after:_}),_});return{original:Z,fixed:J,fixCount:X.length,fixes:X}}async function fQ(Z,$={},Y=!1){let X=await Bun.file(Z).text(),J=vQ(X,$);if(Y&&J.fixCount>0)await Bun.write(Z,J.fixed);return J}async function lL(Z,$={},Y={}){let X={},{recursive:J=!0,ignorePaths:G=[],writeBack:Q=!1,extensions:K=[".stx",".html",".htm"]}=Y,_=K.length===1?`*${K[0]}`:`*{${K.join(",")}}`,W=_$.join(Z,J?`**/${_}`:_),B=new Bun.Glob(W);for await(let U of B.scan()){if(G.some((q)=>U.includes(_$.normalize(q))))continue;try{let q=await fQ(U,$,Q);if(q.fixCount>0)X[U]=q}catch(q){console.error(`Error fixing ${U}:`,q)}}return X}function iL(){return[s6,r6]}var xQ,s6,r6;var W$=C(()=>{xQ={fixMissingAlt:!0,fixMissingLabels:!0,fixMissingFormLabels:!0,fixTableHeaders:!0,fixMissingLang:!0,fixPositiveTabindex:!0,fixButtonFocusable:!0,defaultLang:"en"};s6={name:"a11y",handler:(Z,$,Y,X)=>{if(!$.length)return Z;let J=$[0].replace(/['"]/g,""),G=$.length>1?$[1].replace(/['"]/g,""):"",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-reade