elit 2.0.1 → 3.0.1

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.
Files changed (82) hide show
  1. package/README.md +275 -128
  2. package/dist/build.d.mts +10 -1
  3. package/dist/build.d.ts +10 -1
  4. package/dist/build.js +670 -1
  5. package/dist/build.mjs +641 -1
  6. package/dist/chokidar.d.mts +134 -0
  7. package/dist/chokidar.d.ts +134 -0
  8. package/dist/chokidar.js +240 -0
  9. package/dist/chokidar.mjs +221 -0
  10. package/dist/cli.js +2792 -495
  11. package/dist/dom.d.mts +10 -3
  12. package/dist/dom.d.ts +10 -3
  13. package/dist/dom.js +676 -1
  14. package/dist/dom.mjs +647 -1
  15. package/dist/el.d.mts +16 -36
  16. package/dist/el.d.ts +16 -36
  17. package/dist/el.js +789 -1
  18. package/dist/el.mjs +583 -1
  19. package/dist/fs.d.mts +255 -0
  20. package/dist/fs.d.ts +255 -0
  21. package/dist/fs.js +513 -0
  22. package/dist/fs.mjs +469 -0
  23. package/dist/hmr.js +112 -1
  24. package/dist/hmr.mjs +91 -1
  25. package/dist/http.d.mts +163 -0
  26. package/dist/http.d.ts +163 -0
  27. package/dist/http.js +632 -0
  28. package/dist/http.mjs +605 -0
  29. package/dist/https.d.mts +108 -0
  30. package/dist/https.d.ts +108 -0
  31. package/dist/https.js +907 -0
  32. package/dist/https.mjs +901 -0
  33. package/dist/index.d.mts +613 -33
  34. package/dist/index.d.ts +613 -33
  35. package/dist/index.js +2589 -1
  36. package/dist/index.mjs +2312 -1
  37. package/dist/mime-types.d.mts +48 -0
  38. package/dist/mime-types.d.ts +48 -0
  39. package/dist/mime-types.js +197 -0
  40. package/dist/mime-types.mjs +166 -0
  41. package/dist/path.d.mts +163 -0
  42. package/dist/path.d.ts +163 -0
  43. package/dist/path.js +350 -0
  44. package/dist/path.mjs +310 -0
  45. package/dist/router.d.mts +3 -1
  46. package/dist/router.d.ts +3 -1
  47. package/dist/router.js +830 -1
  48. package/dist/router.mjs +801 -1
  49. package/dist/runtime.d.mts +97 -0
  50. package/dist/runtime.d.ts +97 -0
  51. package/dist/runtime.js +43 -0
  52. package/dist/runtime.mjs +15 -0
  53. package/dist/server.d.mts +5 -1
  54. package/dist/server.d.ts +5 -1
  55. package/dist/server.js +3267 -1
  56. package/dist/server.mjs +3241 -1
  57. package/dist/state.d.mts +3 -1
  58. package/dist/state.d.ts +3 -1
  59. package/dist/state.js +1036 -1
  60. package/dist/state.mjs +992 -1
  61. package/dist/style.d.mts +47 -1
  62. package/dist/style.d.ts +47 -1
  63. package/dist/style.js +551 -1
  64. package/dist/style.mjs +483 -1
  65. package/dist/{types-DOAdFFJB.d.ts → types-C0nGi6MX.d.mts} +29 -13
  66. package/dist/{types-DOAdFFJB.d.mts → types-Du6kfwTm.d.ts} +29 -13
  67. package/dist/types.d.mts +452 -3
  68. package/dist/types.d.ts +452 -3
  69. package/dist/types.js +18 -1
  70. package/dist/ws.d.mts +195 -0
  71. package/dist/ws.d.ts +195 -0
  72. package/dist/ws.js +380 -0
  73. package/dist/ws.mjs +358 -0
  74. package/dist/wss.d.mts +108 -0
  75. package/dist/wss.d.ts +108 -0
  76. package/dist/wss.js +1306 -0
  77. package/dist/wss.mjs +1300 -0
  78. package/package.json +53 -6
  79. package/dist/client.d.mts +0 -9
  80. package/dist/client.d.ts +0 -9
  81. package/dist/client.js +0 -1
  82. package/dist/client.mjs +0 -1
package/dist/index.mjs CHANGED
@@ -1 +1,2312 @@
1
- import{createServer as e,request as t}from"http";import{request as r}from"https";import{WebSocket as s,WebSocketServer as n}from"ws";import{watch as a}from"chokidar";import{realpath as o,stat as i,readFile as l}from"fs/promises";import{normalize as c,resolve as d,join as u,sep as h,extname as p,relative as g,basename as m,dirname as f}from"path";import{lookup as y}from"mime-types";import{build as v}from"esbuild";import{mkdirSync as b,statSync as w,existsSync as $,readFileSync as S,writeFileSync as E,copyFileSync as T}from"fs";var C,N=(C=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"?new Proxy(C,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):C),M=class{constructor(){this.elementCache=new WeakMap,this.reactiveNodes=new Map}createElement(e,t={},r=[]){return{tagName:e,props:t,children:r}}renderToDOM(e,t){if(null==e||!1===e)return;if("object"!=typeof e)return void t.appendChild(document.createTextNode(String(e)));let{tagName:r,props:s,children:n}=e,a="svg"===r||"s"===r[0]&&"v"===r[1]&&"g"===r[2]||"http://www.w3.org/2000/svg"===t.namespaceURI,o=a?document.createElementNS("http://www.w3.org/2000/svg",r.replace("svg","").toLowerCase()||r):document.createElement(r);for(let e in s){let t=s[e];if(null==t||!1===t)continue;let r=e.charCodeAt(0);if(99===r&&(e.length<6||"N"===e[5])){let e=Array.isArray(t)?t.join(" "):t;a?o.setAttribute("class",e):o.className=e}else if(115===r&&5===e.length)if("string"==typeof t)o.style.cssText=t;else{let e=o.style;for(let r in t)e[r]=t[r]}else 111===r&&110===e.charCodeAt(1)?o[e.toLowerCase()]=t:100===r&&e.length>20?o.innerHTML=t.__html:114===r&&3===e.length?setTimeout(()=>{"function"==typeof t?t(o):t.current=o},0):o.setAttribute(e,!0===t?"":String(t))}let i=n.length;if(!i)return void t.appendChild(o);let l=e=>{for(let t=0;t<i;t++){let r=n[t];if(null!=r&&!1!==r)if(Array.isArray(r))for(let t=0,s=r.length;t<s;t++){let s=r[t];null!=s&&!1!==s&&this.renderToDOM(s,e)}else this.renderToDOM(r,e)}};if(i>30){let e=document.createDocumentFragment();l(e),o.appendChild(e)}else l(o);t.appendChild(o)}render(e,t){let r="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!r)throw new Error(`Element not found: ${e}`);if(t.children&&t.children.length>500){let e=document.createDocumentFragment();this.renderToDOM(t,e),r.appendChild(e)}else this.renderToDOM(t,r);return r}batchRender(e,t){let r="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!r)throw new Error(`Element not found: ${e}`);let s=t.length;if(s>3e3){let e=document.createDocumentFragment(),n=0,a=1500,o=()=>{let i=Math.min(n+a,s);for(let r=n;r<i;r++)this.renderToDOM(t[r],e);n=i,n>=s?r.appendChild(e):requestAnimationFrame(o)};o()}else{let e=document.createDocumentFragment();for(let r=0;r<s;r++)this.renderToDOM(t[r],e);r.appendChild(e)}return r}renderChunked(e,t,r=5e3,s){let n="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!n)throw new Error(`Element not found: ${e}`);let a=t.length,o=0,i=()=>{let e=Math.min(o+r,a),l=document.createDocumentFragment();for(let r=o;r<e;r++)this.renderToDOM(t[r],l);n.appendChild(l),o=e,s&&s(o,a),o<a&&requestAnimationFrame(i)};return requestAnimationFrame(i),n}renderToHead(...e){let t=document.head;if(t)for(let r of e.flat())r&&this.renderToDOM(r,t);return t}addStyle(e){let t=document.createElement("style");return t.textContent=e,document.head.appendChild(t)}addMeta(e){let t=document.createElement("meta");for(let r in e)t.setAttribute(r,e[r]);return document.head.appendChild(t)}addLink(e){let t=document.createElement("link");for(let r in e)t.setAttribute(r,e[r]);return document.head.appendChild(t)}setTitle(e){return document.title=e}createState(e,t={}){let r=e,s=new Set,n=null,{throttle:a=0,deep:o=!1}=t,i=()=>s.forEach(e=>e(r));return{get value(){return r},set value(e){(o?JSON.stringify(r)!==JSON.stringify(e):r!==e)&&(r=e,a>0?n||(n=setTimeout(()=>{n=null,i()},a)):i())},subscribe:e=>(s.add(e),()=>s.delete(e)),destroy(){s.clear(),n&&clearTimeout(n)}}}computed(e,t){let r=e.map(e=>e.value),s=this.createState(t(...r));return e.forEach((e,n)=>{e.subscribe(e=>{r[n]=e,s.value=t(...r)})}),s}effect(e){e()}createVirtualList(e,t,r,s=50,n=5){let a=e.clientHeight,o=t.length*s,i=0,l=()=>{let{start:l,end:c}={start:Math.max(0,Math.floor(i/s)-n),end:Math.min(t.length,Math.ceil((i+a)/s)+n)},d=document.createElement("div");d.style.cssText=`height:${o}px;position:relative`;for(let e=l;e<c;e++){let n=document.createElement("div");n.style.cssText=`position:absolute;top:${e*s}px;height:${s}px;width:100%`,this.renderToDOM(r(t[e],e),n),d.appendChild(n)}e.innerHTML="",e.appendChild(d)},c=()=>{i=e.scrollTop,requestAnimationFrame(l)};return e.addEventListener("scroll",c),l(),{render:l,destroy:()=>{e.removeEventListener("scroll",c),e.innerHTML=""}}}lazy(e){let t=null,r=!1;return async(...s)=>(!t&&!r&&(r=!0,t=await e(),r=!1),t?t(...s):{tagName:"div",props:{class:"loading"},children:["Loading..."]})}cleanupUnusedElements(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT),r=[];for(;t.nextNode();){let e=t.currentNode;e.id&&e.id.startsWith("r")&&!this.elementCache.has(e)&&r.push(e)}return r.forEach(e=>e.remove()),r.length}renderToString(e,t={}){let{pretty:r=!1,indent:s=0}=t,n=r?" ".repeat(s):"",a=r?"\n":"",o=this.resolveStateValue(e);if(o=this.unwrapReactive(o),Array.isArray(o))return o.map(e=>this.renderToString(e,t)).join("");if("object"!=typeof o||null===o)return null==o||!1===o?"":this.escapeHtml(String(o));let{tagName:i,props:l,children:c}=o,d=this.isSelfClosingTag(i),u=`${n}<${i}`,h=this.propsToAttributes(l);if(h&&(u+=` ${h}`),d)return u+=` />${a}`,u;if(u+=">",l.dangerouslySetInnerHTML)return u+=l.dangerouslySetInnerHTML.__html,u+=`</${i}>${a}`,u;if(c&&c.length>0){let e=c.map(e=>{let t=this.resolveStateValue(e);return this.unwrapReactive(t)}),t=e.some(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"tagName"in e);if(r&&t){u+=a;for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(u+=this.renderToString(e,{pretty:r,indent:s+1}));else u+=this.renderToString(t,{pretty:r,indent:s+1});u+=n}else for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(u+=this.renderToString(e,{pretty:!1,indent:0}));else u+=this.renderToString(t,{pretty:!1,indent:0})}return u+=`</${i}>${a}`,u}resolveStateValue(e){return e&&"object"==typeof e&&"value"in e&&"subscribe"in e?e.value:e}isReactiveWrapper(e){return!(!e||"object"!=typeof e||!e.tagName)&&("span"===e.tagName&&e.props?.id&&"string"==typeof e.props.id&&e.props.id.match(/^r[a-z0-9]{9}$/))}unwrapReactive(e){if(!this.isReactiveWrapper(e))return e;let t=e.children;if(!t||0===t.length)return"";if(1===t.length){let e=t[0];if(e&&"object"==typeof e&&"span"===e.tagName){let t=e.props,r=!t||0===Object.keys(t).length,s=e.children&&1===e.children.length&&"string"==typeof e.children[0];if(r&&s)return e.children[0]}return this.unwrapReactive(e)}return t.map(e=>this.unwrapReactive(e))}escapeHtml(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,e=>t[e])}isSelfClosingTag(e){return new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(e.toLowerCase())}propsToAttributes(e){let t=[];for(let r in e){if("children"===r||"dangerouslySetInnerHTML"===r||"ref"===r)continue;let s=e[r];if(s=this.resolveStateValue(s),null!=s&&!1!==s&&(!r.startsWith("on")||"function"!=typeof s)){if("className"===r||"class"===r){let e=Array.isArray(s)?s.join(" "):s;e&&t.push(`class="${this.escapeHtml(String(e))}"`);continue}if("style"===r){let e=this.styleToString(s);e&&t.push(`style="${this.escapeHtml(e)}"`);continue}if(!0===s){t.push(r);continue}t.push(`${r}="${this.escapeHtml(String(s))}"`)}}return t.join(" ")}styleToString(e){if("string"==typeof e)return e;if("object"==typeof e&&null!==e){let t=[];for(let r in e){let s=r.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${s}:${e[r]}`)}return t.join(";")}return""}isState(e){return e&&"object"==typeof e&&"value"in e&&"subscribe"in e&&"function"==typeof e.subscribe}createReactiveChild(e,t){let r=t(e.value);if(typeof window<"u"&&typeof document<"u"){let r={node:null,renderFn:t};this.reactiveNodes.set(e,r),e.subscribe(()=>{if(r.node&&r.node.parentNode){let s=t(e.value);r.node.textContent=String(s??"")}})}return r}jsonToVNode(e){if(this.isState(e))return this.createReactiveChild(e,e=>e);if(null==e||"boolean"==typeof e||"string"==typeof e||"number"==typeof e)return e;let{tag:t,attributes:r={},children:s}=e,n={};for(let e in r){let t=r[e];"class"===e?n.className=this.isState(t)?t.value:t:n[e]=this.isState(t)?t.value:t}let a=[];if(null!=s)if(Array.isArray(s))for(let e of s)if(this.isState(e))a.push(this.createReactiveChild(e,e=>e));else{let t=this.jsonToVNode(e);null!=t&&!1!==t&&a.push(t)}else if(this.isState(s))a.push(this.createReactiveChild(s,e=>e));else if("object"==typeof s&&"tag"in s){let e=this.jsonToVNode(s);null!=e&&!1!==e&&a.push(e)}else a.push(s);return{tagName:t,props:n,children:a}}vNodeJsonToVNode(e){if(this.isState(e))return this.createReactiveChild(e,e=>e);if(null==e||"boolean"==typeof e||"string"==typeof e||"number"==typeof e)return e;let{tagName:t,props:r={},children:s=[]}=e,n={};for(let e in r){let t=r[e];n[e]=this.isState(t)?t.value:t}let a=[];for(let e of s)if(this.isState(e))a.push(this.createReactiveChild(e,e=>e));else{let t=this.vNodeJsonToVNode(e);null!=t&&!1!==t&&a.push(t)}return{tagName:t,props:n,children:a}}renderJson(e,t){let r=this.jsonToVNode(t);if(!r||"object"!=typeof r||!("tagName"in r))throw new Error("Invalid JSON structure");return this.render(e,r)}renderVNode(e,t){let r=this.vNodeJsonToVNode(t);if(!r||"object"!=typeof r||!("tagName"in r))throw new Error("Invalid VNode JSON structure");return this.render(e,r)}renderJsonToString(e,t={}){let r=this.jsonToVNode(e);return this.renderToString(r,t)}renderVNodeToString(e,t={}){let r=this.vNodeJsonToVNode(e);return this.renderToString(r,t)}renderServer(e){if("object"!=typeof e||null===e||!("tagName"in e))throw new Error("renderServer requires a VNode with html tag");if("html"!==e.tagName)throw new Error("renderServer requires a VNode with html tag as root");let t=e,r=null,s=null;for(let e of t.children||[])"object"==typeof e&&null!==e&&"tagName"in e&&("head"===e.tagName&&(r=e),"body"===e.tagName&&(s=e));if(t.props)for(let e in t.props){let r=t.props[e];null!=r&&!1!==r&&document.documentElement.setAttribute(e,String(r))}if(r){document.head.innerHTML="";for(let e of r.children||[])this.renderToDOM(e,document.head)}if(s){if(document.body.innerHTML="",s.props)for(let e in s.props){let t=s.props[e];null!=t&&!1!==t&&document.body.setAttribute(e,String(t))}for(let e of s.children||[])this.renderToDOM(e,document.body)}}renderToHTMLDocument(e,t={}){let{title:r="",meta:s=[],links:n=[],scripts:a=[],styles:o=[],lang:i="en",head:l="",bodyAttrs:c={},pretty:d=!1}=t,u=d?"\n":"",h=d?" ":"",p=d?" ":"",g=`<!DOCTYPE html>${u}<html lang="${i}">${u}${h}<head>${u}${p}<meta charset="UTF-8">${u}${p}<meta name="viewport" content="width=device-width, initial-scale=1.0">${u}`;r&&(g+=`${p}<title>${this.escapeHtml(r)}</title>${u}`);for(let e of s){g+=`${p}<meta`;for(let t in e)g+=` ${t}="${this.escapeHtml(e[t])}"`;g+=`>${u}`}for(let e of n){g+=`${p}<link`;for(let t in e)g+=` ${t}="${this.escapeHtml(e[t])}"`;g+=`>${u}`}for(let e of o)e.href?g+=`${p}<link rel="stylesheet" href="${this.escapeHtml(e.href)}">${u}`:e.content&&(g+=`${p}<style>${e.content}</style>${u}`);l&&(g+=l+u),g+=`${h}</head>${u}${h}<body`;for(let e in c)g+=` ${e}="${this.escapeHtml(c[e])}"`;g+=`>${u}`,g+=this.renderToString(e,{pretty:d,indent:2});for(let e of a)g+=`${p}<script`,e.type&&(g+=` type="${this.escapeHtml(e.type)}"`),e.async&&(g+=" async"),e.defer&&(g+=" defer"),e.src?g+=` src="${this.escapeHtml(e.src)}"><\/script>${u}`:e.content?g+=`>${e.content}<\/script>${u}`:g+=`><\/script>${u}`;return g+=`${h}</body>${u}</html>`,g}getElementCache(){return this.elementCache}},x=new M,R=(e,t)=>x.createState(e,t),k=(e,t)=>x.computed(e,t),H=e=>x.effect(e),O=(e,t)=>x.batchRender(e,t),F=(e,t,r,s)=>x.renderChunked(e,t,r,s),j=(e,t,r,s,n)=>x.createVirtualList(e,t,r,s,n),A=e=>x.lazy(e),D=e=>x.cleanupUnusedElements(e),P=(e,t)=>{let r=null;return(...s)=>{r||(r=setTimeout(()=>{r=null,e(...s)},t))}},W=(e,t)=>{let r=null;return(...s)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...s),t)}},L=class{constructor(e,t,r){this.key=e,this.wsUrl=r,this.ws=null,this.pendingUpdates=[],this.localState=R(t),this.previousValue=t,this.connect()}get value(){return this.localState.value}set value(e){this.previousValue=this.localState.value,this.localState.value=e,this.sendToServer(e)}get state(){return this.localState}onChange(e){return this.localState.subscribe(t=>{let r=this.previousValue;this.previousValue=t,e(t,r)})}update(e){this.value=e(this.value)}connect(){if(typeof window>"u")return;let e=this.wsUrl||`ws://${location.host}`;this.ws=new WebSocket(e),this.ws.addEventListener("open",()=>{for(this.subscribe();this.pendingUpdates.length>0;){let e=this.pendingUpdates.shift();this.sendToServer(e)}}),this.ws.addEventListener("message",e=>{this.handleMessage(e.data)}),this.ws.addEventListener("close",()=>{setTimeout(()=>this.connect(),1e3)}),this.ws.addEventListener("error",e=>{console.error("[SharedState] WebSocket error:",e)})}subscribe(){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify({type:"state:subscribe",key:this.key}))}handleMessage(e){try{let t=JSON.parse(e);if(t.key!==this.key)return;("state:init"===t.type||"state:update"===t.type)&&(this.localState.value=t.value)}catch{}}sendToServer(e){if(this.ws){if(this.ws.readyState!==WebSocket.OPEN)return void this.pendingUpdates.push(e);this.ws.send(JSON.stringify({type:"state:change",key:this.key,value:e}))}}disconnect(){this.ws&&(this.ws.close(),this.ws=null)}destroy(){this.disconnect(),this.localState.destroy()}};function q(e,t,r){return new L(e,t,r)}var B=new class{constructor(){this.states=new Map}create(e,t,r){if(this.states.has(e))return this.states.get(e);let s=new L(e,t,r);return this.states.set(e,s),s}get(e){return this.states.get(e)}delete(e){let t=this.states.get(e);return!!t&&(t.destroy(),this.states.delete(e))}clear(){this.states.forEach(e=>e.destroy()),this.states.clear()}},U=(e,t)=>{let r=null,s=null,n=null,a=!0,o=t(e.value),i=o&&"object"==typeof o&&"tagName"in o,l=null==o||!1===o;e.subscribe(()=>{r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{(()=>{if(!s&&!n)return;let r=t(e.value);if(null==r||!1===r)a&&s&&(n=document.createComment("reactive"),s.parentNode?.replaceChild(n,s),a=!1);else if(!a&&n&&s&&(n.parentNode?.replaceChild(s,n),n=null,a=!0),s){let e=document.createDocumentFragment();if(i&&r&&"object"==typeof r&&"tagName"in r){let{props:t,children:n}=r;for(let e in t){let r=t[e];if("ref"!==e)if("class"===e||"className"===e)s.className=Array.isArray(r)?r.join(" "):r||"";else if("style"===e&&"object"==typeof r){let e=s.style;for(let t in r)e[t]=r[t]}else e.startsWith("on")?s[e.toLowerCase()]=r:null!=r&&!1!==r?s.setAttribute(e,String(!0===r?"":r)):s.removeAttribute(e)}for(let t of n)x.renderToDOM(t,e)}else x.renderToDOM(r,e);s.textContent="",s.appendChild(e),x.getElementCache().set(s,!0)}})(),r=null})});let c=e=>{s=e,l&&e.parentNode&&(n=document.createComment("reactive"),e.parentNode.replaceChild(n,e),a=!1)};if(i){let e=o;return{tagName:e.tagName,props:{...e.props,ref:c},children:e.children}}return{tagName:"span",props:{ref:c},children:[o]}},I=(e,t,r,s={})=>{let n=null,a=null;return t.subscribe(()=>{n&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{if(a){let e=document.createDocumentFragment(),s=r(t.value);null==s||!1===s?(a.style.display="none",a.textContent=""):(a.style.display="",x.renderToDOM(s,e),a.textContent="",a.appendChild(e)),x.getElementCache().set(a,!0)}n=null})}),{tagName:e,props:{...s,ref:e=>{a=e}},children:[r(t.value)]}},J=e=>e&&void 0!==e.value?U(e,e=>({tagName:"span",props:{},children:[String(e)]})):String(e),V=e=>({value:e.value,oninput:t=>{e.value=t.target.value}}),_=e=>({checked:e.value,onchange:t=>{e.value=t.target.checked}}),G=class{constructor(){this.variables=[],this.rules=[],this.mediaRules=[],this.keyframes=[],this.fontFaces=[],this.imports=[],this.containerRules=[],this.supportsRules=[],this.layerRules=[],this._layerOrder=[]}addVar(e,t){let r={name:e.startsWith("--")?e:`--${e}`,value:t,toString(){return`var(${this.name})`}};return this.variables.push(r),r}var(e,t){let r="string"==typeof e?e.startsWith("--")?e:`--${e}`:e.name;return t?`var(${r}, ${t})`:`var(${r})`}addTag(e,t){let r={selector:e,styles:t,type:"tag"};return this.rules.push(r),r}addClass(e,t){let r={selector:e.startsWith(".")?e:`.${e}`,styles:t,type:"class"};return this.rules.push(r),r}addId(e,t){let r={selector:e.startsWith("#")?e:`#${e}`,styles:t,type:"id"};return this.rules.push(r),r}addPseudoClass(e,t,r){let s=e.startsWith(":")?e:`:${e}`,n={selector:r?`${r}${s}`:s,styles:t,type:"pseudo-class"};return this.rules.push(n),n}addPseudoElement(e,t,r){let s=e.startsWith("::")?e:`::${e}`,n={selector:r?`${r}${s}`:s,styles:t,type:"pseudo-element"};return this.rules.push(n),n}addAttribute(e,t,r){let s=e.startsWith("[")?e:`[${e}]`,n={selector:r?`${r}${s}`:s,styles:t,type:"attribute"};return this.rules.push(n),n}attrEquals(e,t,r,s){return this.addAttribute(`${e}="${t}"`,r,s)}attrContainsWord(e,t,r,s){return this.addAttribute(`${e}~="${t}"`,r,s)}attrStartsWith(e,t,r,s){return this.addAttribute(`${e}^="${t}"`,r,s)}attrEndsWith(e,t,r,s){return this.addAttribute(`${e}$="${t}"`,r,s)}attrContains(e,t,r,s){return this.addAttribute(`${e}*="${t}"`,r,s)}descendant(e,t,r){let s={selector:`${e} ${t}`,styles:r,type:"custom"};return this.rules.push(s),s}child(e,t,r){let s={selector:`${e} > ${t}`,styles:r,type:"custom"};return this.rules.push(s),s}adjacentSibling(e,t,r){let s={selector:`${e} + ${t}`,styles:r,type:"custom"};return this.rules.push(s),s}generalSibling(e,t,r){let s={selector:`${e} ~ ${t}`,styles:r,type:"custom"};return this.rules.push(s),s}multiple(e,t){let r={selector:e.join(", "),styles:t,type:"custom"};return this.rules.push(r),r}addName(e,t){return{selector:e.startsWith("--")?`&${e}`:`&--${e}`,styles:t,type:"name"}}nesting(e,...t){return e.nested=t,e}keyframe(e,t){let r={name:e,steps:Object.entries(t).map(([e,t])=>({step:"from"===e?"from":"to"===e?"to":`${e}%`,styles:t}))};return this.keyframes.push(r),r}keyframeFromTo(e,t,r){return this.keyframe(e,{from:t,to:r})}fontFace(e){return this.fontFaces.push(e),e}import(e,t){let r=t?`@import url("${e}") ${t};`:`@import url("${e}");`;return this.imports.push(r),r}media(e,t,r){let s={type:e,condition:t,rules:Object.entries(r).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.mediaRules.push(s),s}mediaScreen(e,t){return this.media("screen",e,t)}mediaPrint(e){return this.media("print","",e)}mediaMinWidth(e,t){return this.media("screen",`min-width: ${e}`,t)}mediaMaxWidth(e,t){return this.media("screen",`max-width: ${e}`,t)}mediaDark(e){let t={type:"",condition:"prefers-color-scheme: dark",rules:Object.entries(e).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.mediaRules.push(t),t}mediaLight(e){let t={type:"",condition:"prefers-color-scheme: light",rules:Object.entries(e).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.mediaRules.push(t),t}mediaReducedMotion(e){let t={type:"",condition:"prefers-reduced-motion: reduce",rules:Object.entries(e).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.mediaRules.push(t),t}container(e,t,r){let s={name:r,condition:e,rules:Object.entries(t).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.containerRules.push(s),s}addContainer(e,t){let r={...t,containerName:e};return this.addClass(e,r)}supports(e,t){let r={condition:e,rules:Object.entries(t).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.supportsRules.push(r),r}layerOrder(...e){this._layerOrder=e}layer(e,t){let r={name:e,rules:Object.entries(t).map(([e,t])=>({selector:e,styles:t,type:"custom"}))};return this.layerRules.push(r),r}add(e){return Object.entries(e).map(([e,t])=>{let r={selector:e,styles:t,type:"custom"};return this.rules.push(r),r})}important(e){return`${e} !important`}toKebabCase(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}stylesToString(e,t=" "){return Object.entries(e).map(([e,r])=>{let s="object"==typeof r&&null!==r&&"name"in r?`var(${r.name})`:r;return`${t}${this.toKebabCase(e)}: ${s};`}).join("\n")}renderRule(e,t=""){let r=`${t}${e.selector} {\n${this.stylesToString(e.styles,t+" ")}\n`;if(e.nested&&e.nested.length>0)for(let s of e.nested){r+=`\n${t}${s.selector.startsWith("&")?s.selector.replace(/&/g,e.selector):`${e.selector} ${s.selector}`} {\n${this.stylesToString(s.styles,t+" ")}\n${t}}\n`}return r+=`${t}}`,r}renderMediaRule(e){let t=`@media ${e.type&&e.condition?`${e.type} and (${e.condition})`:e.type?e.type:`(${e.condition})`} {\n`;for(let r of e.rules)t+=this.renderRule(r," ")+"\n";return t+="}",t}renderKeyframes(e){let t=`@keyframes ${e.name} {\n`;for(let r of e.steps)t+=` ${r.step} {\n${this.stylesToString(r.styles," ")}\n }\n`;return t+="}",t}renderFontFace(e){let t="@font-face {\n";return t+=` font-family: "${e.fontFamily}";\n`,t+=` src: ${e.src};\n`,e.fontWeight&&(t+=` font-weight: ${e.fontWeight};\n`),e.fontStyle&&(t+=` font-style: ${e.fontStyle};\n`),e.fontDisplay&&(t+=` font-display: ${e.fontDisplay};\n`),e.unicodeRange&&(t+=` unicode-range: ${e.unicodeRange};\n`),t+="}",t}renderContainerRule(e){let t=`@container ${e.name?`${e.name} `:""}(${e.condition}) {\n`;for(let r of e.rules)t+=this.renderRule(r," ")+"\n";return t+="}",t}renderSupportsRule(e){let t=`@supports (${e.condition}) {\n`;for(let r of e.rules)t+=this.renderRule(r," ")+"\n";return t+="}",t}renderLayerRule(e){let t=`@layer ${e.name} {\n`;for(let r of e.rules)t+=this.renderRule(r," ")+"\n";return t+="}",t}render(...e){let t=[];if(this.imports.length>0&&t.push(this.imports.join("\n")),this._layerOrder.length>0&&t.push(`@layer ${this._layerOrder.join(", ")};`),this.variables.length>0){let e=this.variables.map(e=>` ${e.name}: ${e.value};`).join("\n");t.push(`:root {\n${e}\n}`)}for(let e of this.fontFaces)t.push(this.renderFontFace(e));for(let e of this.keyframes)t.push(this.renderKeyframes(e));let r=[...this.rules],s=[...this.mediaRules],n=[],a=[...this.containerRules],o=[...this.supportsRules],i=[...this.layerRules];for(let t of e)t&&(Array.isArray(t)?r.push(...t):!("condition"in t)||!("rules"in t)||"name"in t&&"steps"in t?"name"in t&&"steps"in t?n.push(t):"name"in t&&"rules"in t?i.push(t):r.push(t):"type"in t?s.push(t):"name"in t&&"string"==typeof t.name?a.push(t):o.push(t));for(let e of n)t.push(this.renderKeyframes(e));for(let e of i)t.push(this.renderLayerRule(e));for(let e of r)t.push(this.renderRule(e));for(let e of o)t.push(this.renderSupportsRule(e));for(let e of a)t.push(this.renderContainerRule(e));for(let e of s)t.push(this.renderMediaRule(e));return t.join("\n\n")}inject(e){let t=this.render(),r=document.createElement("style");return e&&(r.id=e),r.textContent=t,document.head.appendChild(r),r}clear(){this.variables=[],this.rules=[],this.mediaRules=[],this.keyframes=[],this.fontFaces=[],this.imports=[],this.containerRules=[],this.supportsRules=[],this.layerRules=[],this._layerOrder=[]}},z=e=>function(t,...r){if(!arguments.length)return{tagName:e,props:{},children:[]};let s=t&&"object"==typeof t&&"value"in t&&"subscribe"in t,n=t&&"object"==typeof t&&"tagName"in t,a="object"!=typeof t||Array.isArray(t)||null===t||s||n,o=a?{}:t,i=a?[t,...r]:r;if(!i.length)return{tagName:e,props:o,children:[]};let l=[];for(let e=0,t=i.length;e<t;e++){let t=i[e];if(null!=t&&!1!==t)if(Array.isArray(t))for(let e=0,r=t.length;e<r;e++){let r=t[e];null!=r&&!1!==r&&l.push(r)}else l.push(t)}return{tagName:e,props:o,children:l}},K={};["html","head","body","title","base","link","meta","style","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","main","nav","section","blockquote","dd","div","dl","dt","figcaption","figure","hr","li","ol","p","pre","ul","a","abbr","b","bdi","bdo","br","cite","code","data","dfn","em","i","kbd","mark","q","rp","rt","ruby","s","samp","small","span","strong","sub","sup","time","u","wbr","area","audio","img","map","track","video","embed","iframe","object","param","picture","portal","source","canvas","noscript","script","del","ins","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr","button","datalist","fieldset","form","input","label","legend","meter","optgroup","option","output","progress","select","textarea","details","dialog","menu","summary","slot","template"].forEach(e=>{K[e]=z(e)}),["svg","circle","rect","path","line","polyline","polygon","ellipse","g","text","tspan","defs","linearGradient","radialGradient","stop","pattern","mask","clipPath","use","symbol","marker","image","foreignObject","animate","animateTransform","animateMotion","set","filter","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence"].forEach(e=>{let t="svg"+e.charAt(0).toUpperCase()+e.slice(1);K[t]=z(e)}),["math","mi","mn","mo","ms","mtext","mrow","mfrac","msqrt","mroot","msub","msup"].forEach(e=>{let t="math"+e.charAt(0).toUpperCase()+e.slice(1);K[t]=z(e)}),K.varElement=z("var");var{head:X,body:Z,title:Y,base:Q,link:ee,meta:te,style:re,address:se,article:ne,aside:ae,footer:oe,header:ie,h1:le,h2:ce,h3:de,h4:ue,h5:he,h6:pe,main:ge,nav:me,section:fe,blockquote:ye,dd:ve,div:be,dl:we,dt:$e,figcaption:Se,figure:Ee,hr:Te,li:Ce,ol:Ne,p:Me,pre:xe,ul:Re,a:ke,abbr:He,b:Oe,bdi:Fe,bdo:je,br:Ae,cite:De,code:Pe,data:We,dfn:Le,em:qe,i:Be,kbd:Ue,mark:Ie,q:Je,rp:Ve,rt:_e,ruby:Ge,s:ze,samp:Ke,small:Xe,span:Ze,strong:Ye,sub:Qe,sup:et,time:tt,u:rt,wbr:st,area:nt,audio:at,img:ot,map:it,track:lt,video:ct,embed:dt,iframe:ut,object:ht,param:pt,picture:gt,portal:mt,source:ft,canvas:yt,noscript:vt,script:bt,del:wt,ins:$t,caption:St,col:Et,colgroup:Tt,table:Ct,tbody:Nt,td:Mt,tfoot:xt,th:Rt,thead:kt,tr:Ht,button:Ot,datalist:Ft,fieldset:jt,form:At,input:Dt,label:Pt,legend:Wt,meter:Lt,optgroup:qt,option:Bt,output:Ut,progress:It,select:Jt,textarea:Vt,details:_t,dialog:Gt,menu:zt,summary:Kt,slot:Xt,template:Zt,svgSvg:Yt,svgCircle:Qt,svgRect:er,svgPath:tr,svgLine:rr,svgPolyline:sr,svgPolygon:nr,svgEllipse:ar,svgG:or,svgText:ir,svgTspan:lr,svgDefs:cr,svgLinearGradient:dr,svgRadialGradient:ur,svgStop:hr,svgPattern:pr,svgMask:gr,svgClipPath:mr,svgUse:fr,svgSymbol:yr,svgMarker:vr,svgImage:br,svgForeignObject:wr,svgAnimate:$r,svgAnimateTransform:Sr,svgAnimateMotion:Er,svgSet:Tr,svgFilter:Cr,svgFeBlend:Nr,svgFeColorMatrix:Mr,svgFeComponentTransfer:xr,svgFeComposite:Rr,svgFeConvolveMatrix:kr,svgFeDiffuseLighting:Hr,svgFeDisplacementMap:Or,svgFeFlood:Fr,svgFeGaussianBlur:jr,svgFeMorphology:Ar,svgFeOffset:Dr,svgFeSpecularLighting:Pr,svgFeTile:Wr,svgFeTurbulence:Lr,mathMath:qr,mathMi:Br,mathMn:Ur,mathMo:Ir,mathMs:Jr,mathMtext:Vr,mathMrow:_r,mathMfrac:Gr,mathMsqrt:zr,mathMroot:Kr,mathMsub:Xr,mathMsup:Zr,varElement:Yr}=K,Qr=K,es=document,ts=es.querySelector.bind(es),rs=es.querySelectorAll.bind(es),ss=es.createElement.bind(es),ns=es.createElementNS.bind(es,"http://www.w3.org/2000/svg"),as=es.createElementNS.bind(es,"http://www.w3.org/1998/Math/MathML"),os=es.createDocumentFragment.bind(es),is=es.createTextNode.bind(es),ls=es.createComment.bind(es),cs=es.getElementById.bind(es),ds=es.getElementsByClassName.bind(es),us=es.getElementsByTagName.bind(es),hs=es.getElementsByName.bind(es);function ps(e,t){let r=e.split("/").filter(Boolean),s=t.split("/").filter(Boolean);if(e.endsWith("*")){let r=e.slice(0,-1);if(t.startsWith(r)||"/"===r||"*"===e)return{"*":t.slice(r.length)}}if(r.length!==s.length)return null;let n={};for(let e=0;e<r.length;e++){let t=r[e],a=s[e];if(t.startsWith(":"))n[t.slice(1)]=decodeURIComponent(a);else if(t!==a)return null}return n}function gs(e){let{mode:t="history",base:r="",routes:s}=e,n=[],a=e=>{let t={};return new URLSearchParams(e).forEach((e,r)=>{t[r]=e}),t},o=()=>"hash"===t?window.location.hash.slice(1)||"/":window.location.pathname.replace(r,"")||"/",i=e=>{let[t,r=""]=e.split("?"),[s,n=""]=t.split("#");return{path:s||"/",params:{},query:a(r),hash:n?"#"+n:""}},l=e=>{for(let t of s){let r=ps(t.path,e);if(null!==r)return{route:t,params:r}}return null},c=x.createState(i(o())),d=(e,s=!1)=>{let a=i(e),o=l(a.path);o&&(a.params=o.params);for(let e of n){let t=e(a,c.value);if(!1===t)return;if("string"==typeof t)return void d(t,s)}if(o?.route.beforeEnter){let e=o.route.beforeEnter(a,c.value);if(!1===e)return;if("string"==typeof e)return void d(e,s)}let u="hash"===t?"#"+e:r+e;s?window.history.replaceState({path:e},"",u):window.history.pushState({path:e},"",u),c.value=a},u=()=>{let e=o(),t=i(e),r=l(t.path);r&&(t.params=r.params),c.value=t};return typeof window<"u"&&window.addEventListener("popstate",u),{currentRoute:c,push:e=>d(e,!1),replace:e=>d(e,!0),back:()=>window.history.back(),forward:()=>window.history.forward(),go:e=>window.history.go(e),beforeEach:e=>{n.push(e)},destroy:()=>{typeof window<"u"&&window.removeEventListener("popstate",u),c.destroy()}}}function ms(e,t){let{routes:r,notFound:s}=t;return()=>{let t=e.currentRoute.value,n=r.find(e=>null!==ps(e.path,t.path));if(n){let e=ps(n.path,t.path)||{},r=n.component({...e,...t.query});return"object"==typeof r&&null!==r&&"tagName"in r?r:{tagName:"span",props:{},children:[r]}}if(s){let e=s(t.params);return"object"==typeof e&&null!==e&&"tagName"in e?e:{tagName:"span",props:{},children:[e]}}return{tagName:"div",props:{},children:["404 - Not Found"]}}}var fs=(e,t,...r)=>({tagName:"a",props:{...t,href:t.to,onclick:r=>{r.preventDefault(),e.push(t.to)}},children:r}),ys=class{constructor(){this.routes=[],this.middlewares=[]}use(e){return this.middlewares.push(e),this}get(e,t){return this.addRoute("GET",e,t)}post(e,t){return this.addRoute("POST",e,t)}put(e,t){return this.addRoute("PUT",e,t)}delete(e,t){return this.addRoute("DELETE",e,t)}patch(e,t){return this.addRoute("PATCH",e,t)}options(e,t){return this.addRoute("OPTIONS",e,t)}addRoute(e,t,r){let{pattern:s,paramNames:n}=this.pathToRegex(t);return this.routes.push({method:e,pattern:s,paramNames:n,handler:r}),this}pathToRegex(e){let t=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\//g,"\\/").replace(/:(\w+)/g,(e,r)=>(t.push(r),"([^\\/]+)"));return{pattern:new RegExp(`^${r}$`),paramNames:t}}parseQuery(e){let t={},r=e.split("?")[1];return r&&new URLSearchParams(r).forEach((e,r)=>t[r]=e),t}async parseBody(e){return new Promise((t,r)=>{let s="";e.on("data",e=>s+=e.toString()),e.on("end",()=>{try{let r=e.headers["content-type"]||"";if(r.includes("application/json"))t(s?JSON.parse(s):{});else if(r.includes("application/x-www-form-urlencoded")){let e={};new URLSearchParams(s).forEach((t,r)=>e[r]=t),t(e)}else t(s)}catch(e){r(e)}}),e.on("error",r)})}async handle(e,t){let r=e.method,s=e.url||"/",n=s.split("?")[0];for(let a of this.routes){if(a.method!==r)continue;let o=n.match(a.pattern);if(!o)continue;let i={};a.paramNames.forEach((e,t)=>{i[e]=o[t+1]});let l=this.parseQuery(s),c={};if(["POST","PUT","PATCH"].includes(r))try{c=await this.parseBody(e)}catch{return t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid request body"})),!0}let d={req:e,res:t,params:i,query:l,body:c,headers:e.headers},u=0,h=async()=>{if(u<this.middlewares.length){let e=this.middlewares[u++];await e(d,h)}};try{await h(),await a.handler(d)}catch(e){console.error("Route handler error:",e),t.headersSent||(t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal Server Error",message:e instanceof Error?e.message:"Unknown error"})))}return!0}return!1}},vs=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))},bs=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"text/plain"}),e.end(t)},ws=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"text/html"}),e.end(t)},$s=(e,t,r)=>{e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t,message:r||""}))};function Ss(e={}){let{origin:t="*",methods:r=["GET","POST","PUT","DELETE","PATCH","OPTIONS"],credentials:s=!0,maxAge:n=86400}=e;return async(e,a)=>{let o=e.req.headers.origin||"",i=Array.isArray(t)&&t.includes(o)?o:Array.isArray(t)?"":t;if(i&&e.res.setHeader("Access-Control-Allow-Origin",i),e.res.setHeader("Access-Control-Allow-Methods",r.join(", ")),e.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s&&e.res.setHeader("Access-Control-Allow-Credentials","true"),e.res.setHeader("Access-Control-Max-Age",String(n)),"OPTIONS"===e.req.method)return e.res.writeHead(204),void e.res.end();await a()}}function Es(e={}){let{format:t="simple"}=e;return async(e,r)=>{let s=Date.now(),{method:n,url:a}=e.req;await r();let o=Date.now()-s,i=e.res.statusCode;console.log("detailed"===t?`[${(new Date).toISOString()}] ${n} ${a} ${i} - ${o}ms`:`${n} ${a} - ${i} (${o}ms)`)}}function Ts(){return async(e,t)=>{try{await t()}catch(t){console.error("Error:",t),e.res.headersSent||(e.res.writeHead(500,{"Content-Type":"application/json"}),e.res.end(JSON.stringify({error:"Internal Server Error",message:t instanceof Error?t.message:"Unknown error"})))}}}function Cs(e={}){let{windowMs:t=6e4,max:r=100,message:s="Too many requests"}=e,n=new Map;return async(e,a)=>{let o=e.req.socket.remoteAddress||"unknown",i=Date.now(),l=n.get(o);if((!l||i>l.resetTime)&&(l={count:0,resetTime:i+t},n.set(o,l)),++l.count>r)return e.res.writeHead(429,{"Content-Type":"application/json"}),void e.res.end(JSON.stringify({error:s}));await a()}}function Ns(e={}){let{limit:t=1048576}=e;return async(e,r)=>{if(parseInt(e.req.headers["content-length"]||"0",10)>t)return e.res.writeHead(413,{"Content-Type":"application/json"}),void e.res.end(JSON.stringify({error:"Request body too large"}));await r()}}function Ms(e={}){let{maxAge:t=3600,public:r=!0}=e;return async(e,s)=>{e.res.setHeader("Cache-Control",`${r?"public":"private"}, max-age=${t}`),await s()}}function xs(){return async(e,t)=>{if(!(e.req.headers["accept-encoding"]||"").includes("gzip"))return void await t();let r=e.res.end.bind(e.res),s=[];e.res.write=e=>(s.push(Buffer.from(e)),!0),e.res.end=t=>{t&&s.push(Buffer.from(t));let n=Buffer.concat(s),{gzipSync:a}=N("zlib"),o=a(n);return e.res.setHeader("Content-Encoding","gzip"),e.res.setHeader("Content-Length",o.length),r(o),e.res},await t()}}function Rs(){return async(e,t)=>{e.res.setHeader("X-Content-Type-Options","nosniff"),e.res.setHeader("X-Frame-Options","DENY"),e.res.setHeader("X-XSS-Protection","1; mode=block"),e.res.setHeader("Strict-Transport-Security","max-age=31536000; includeSubDomains"),await t()}}function ks(e){return async(s,n)=>{let a=s.url||"/",o=a.split("?")[0],i=e.find(e=>o.startsWith(e.context));if(!i)return!1;let{target:l,changeOrigin:c,pathRewrite:d,headers:u}=i;try{let e=new URL(l),o="https:"===e.protocol,i=o?r:t,h=function(e,t){if(!t)return e;for(let[r,s]of Object.entries(t)){let t=new RegExp(r);if(t.test(e))return e.replace(t,s)}return e}(a,d),p={hostname:e.hostname,port:e.port||(o?443:80),path:h,method:s.method,headers:{...s.headers,...u||{}}};c&&(p.headers.host=e.host),delete p.headers.host;let g=i(p,e=>{n.writeHead(e.statusCode||200,e.headers),e.pipe(n)});return g.on("error",e=>{console.error("[Proxy] Error proxying %s to %s:",a,l,e.message),n.headersSent||(n.writeHead(502,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad Gateway",message:"Proxy error"})))}),s.pipe(g),!0}catch(e){return console.error("[Proxy] Invalid proxy configuration for %s:",o,e),!1}}}var Hs=class{constructor(e,t){this.key=e,this.listeners=new Set,this.changeHandlers=new Set,this.options=t,this._value=t.initial}get value(){return this._value}set value(e){if(this.options.validate&&!this.options.validate(e))throw new Error(`Invalid state value for "${this.key}"`);let t=this._value;this._value=e,this.changeHandlers.forEach(r=>{r(e,t)}),this.broadcast()}update(e){this.value=e(this._value)}subscribe(e){this.listeners.add(e),this.sendTo(e)}unsubscribe(e){this.listeners.delete(e)}onChange(e){return this.changeHandlers.add(e),()=>this.changeHandlers.delete(e)}broadcast(){let e=JSON.stringify({type:"state:update",key:this.key,value:this._value,timestamp:Date.now()});this.listeners.forEach(t=>t.readyState===s.OPEN&&t.send(e))}sendTo(e){e.readyState===s.OPEN&&e.send(JSON.stringify({type:"state:init",key:this.key,value:this._value,timestamp:Date.now()}))}get subscriberCount(){return this.listeners.size}clear(){this.listeners.clear(),this.changeHandlers.clear()}},Os=class{constructor(){this.states=new Map}create(e,t){if(this.states.has(e))return this.states.get(e);let r=new Hs(e,t);return this.states.set(e,r),r}get(e){return this.states.get(e)}has(e){return this.states.has(e)}delete(e){let t=this.states.get(e);return!!t&&(t.clear(),this.states.delete(e))}subscribe(e,t){this.states.get(e)?.subscribe(t)}unsubscribe(e,t){this.states.get(e)?.unsubscribe(t)}unsubscribeAll(e){this.states.forEach(t=>t.unsubscribe(e))}handleStateChange(e,t){let r=this.states.get(e);r&&(r.value=t)}keys(){return Array.from(this.states.keys())}clear(){this.states.forEach(e=>e.clear()),this.states.clear()}},Fs={port:3e3,host:"localhost",https:!1,open:!0,watch:["**/*.ts","**/*.js","**/*.html","**/*.css"],ignore:["node_modules/**","dist/**",".git/**","**/*.d.ts"],logging:!0,middleware:[],worker:[]};function js(t){let r={...Fs,...t},m=new Set,f=new Os,b=r.clients?.length?r.clients:r.root?[{root:r.root,basePath:r.basePath||"",ssr:r.ssr,proxy:r.proxy}]:null;if(!b)throw new Error('DevServerOptions must include either "clients" array or "root" directory');let w=b.map(e=>{let t=e.basePath||"";if(t){for(;t.startsWith("/");)t=t.slice(1);for(;t.endsWith("/");)t=t.slice(0,-1);t=t?"/"+t:""}return{root:e.root,basePath:t,ssr:e.ssr,proxyHandler:e.proxy?ks(e.proxy):void 0}}),$=r.proxy?ks(r.proxy):null,S=e(async(e,t)=>{let s=e.url||"/",n=w.find(e=>e.basePath&&s.startsWith(e.basePath))||w.find(e=>!e.basePath);if(!n)return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found");if(n.proxyHandler)try{if(await n.proxyHandler(e,t))return void(r.logging&&console.log(`[Proxy] ${e.method} ${s} -> proxied (client-specific)`))}catch(e){console.error("[Proxy] Error (client-specific):",e)}if($)try{if(await $(e,t))return void(r.logging&&console.log(`[Proxy] ${e.method} ${s} -> proxied (global)`))}catch(e){console.error("[Proxy] Error (global):",e)}let a=n.basePath?s.slice(n.basePath.length)||"/":s;if(r.api&&a.startsWith("/api")&&await r.api.handle(e,t))return;let l="/"===a?"/index.html":a;if(l=l.split("?")[0],r.logging&&"/src/pages"===l&&console.log("[DEBUG] Request for /src/pages received"),l.includes("\0"))return r.logging&&console.log(`[403] Rejected path with null byte: ${l}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");let p,g=l.startsWith("/dist/"),m=c(l).replace(/\\/g,"/").replace(/^\/+/,"");if(m.includes(".."))return r.logging&&console.log(`[403] Path traversal attempt: ${l}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");p=m;let f,y=await o(d(n.root)),v=g?await o(d(n.root,"..")):y;try{if(f=await o(d(u(v,p))),!f.startsWith(v.endsWith(h)?v:v+h))return r.logging&&console.log(`[403] File access outside of root: ${f}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");r.logging&&"/src/pages"===l&&console.log(`[DEBUG] Initial resolve succeeded: ${f}`)}catch{let e;if(r.logging&&!p.includes(".")&&console.log(`[DEBUG] File not found: ${p}, trying extensions...`),p.endsWith(".js")){let s=p.replace(/\.js$/,".ts");try{let n=await o(d(u(v,s)));if(!n.startsWith(v.endsWith(h)?v:v+h))return r.logging&&console.log(`[403] Fallback TS path outside of root: ${n}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");e=n}catch{}}if(!e&&!p.includes("."))try{e=await o(d(u(v,p+".ts"))),r.logging&&console.log(`[DEBUG] Found: ${p}.ts`)}catch{try{e=await o(d(u(v,p+".js"))),r.logging&&console.log(`[DEBUG] Found: ${p}.js`)}catch{try{e=await o(d(u(v,p,"index.ts"))),r.logging&&console.log(`[DEBUG] Found: ${p}/index.ts`)}catch{try{e=await o(d(u(v,p,"index.js"))),r.logging&&console.log(`[DEBUG] Found: ${p}/index.js`)}catch{r.logging&&console.log(`[DEBUG] Not found: all attempts failed for ${p}`)}}}}if(!e)return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found");f=e}try{if((await i(f)).isDirectory()){let e;r.logging&&console.log(`[DEBUG] Path is directory: ${f}, trying index files...`);try{e=await o(d(u(f,"index.ts"))),r.logging&&console.log("[DEBUG] Found index.ts in directory")}catch{try{e=await o(d(u(f,"index.js"))),r.logging&&console.log("[DEBUG] Found index.js in directory")}catch{return r.logging&&console.log("[DEBUG] No index file found in directory"),t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found")}}f=e}}catch{return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found")}let b=await o(d(n.root,"..")),S=f.startsWith(y+h)||f===y,T=g&&(f.startsWith(b+h)||f===b);if(!S&&!T)return r.logging&&console.log(`[403] Path outside allowed directories: ${l}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");try{if((await i(f)).isDirectory())try{let e=await o(d(u(f,"index.html")));return e.startsWith(y+h)||e===y?(await i(e),E(e,t,n)):(t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden"))}catch{return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found")}await E(f,t,n)}catch{r.logging&&console.log(`[404] ${l}`),t.writeHead(404,{"Content-Type":"text/plain"}),t.end("404 Not Found")}});async function E(e,t,s){try{let n,a=await o(d(s.root)),i=await o(d(s.root,".."));try{n=await o(d(e))}catch{return e.endsWith("index.html")&&s.ssr?function(e,t){try{if(!t.ssr)return e.writeHead(500,{"Content-Type":"text/plain"}),void e.end("SSR function not configured");let s,n=t.ssr();if("string"==typeof n)s=n;else if("object"==typeof n&&null!==n&&"tagName"in n){let e=n;s="html"===e.tagName?x.renderToString(e):`<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body>${x.renderToString(e)}</body></html>`}else s=String(n);let a=`<script>(function(){const ws=new WebSocket('ws://${r.host}:${r.port}${t.basePath}');ws.onopen=()=>console.log('[Elit HMR] Connected');ws.onmessage=(e)=>{const d=JSON.parse(e.data);if(d.type==='update'){console.log('[Elit HMR] File updated:',d.path);window.location.reload()}else if(d.type==='reload'){console.log('[Elit HMR] Reloading...');window.location.reload()}else if(d.type==='error')console.error('[Elit HMR] Error:',d.error)};ws.onclose=()=>{console.log('[Elit HMR] Disconnected - Retrying...');setTimeout(()=>window.location.reload(),1000)};ws.onerror=(e)=>console.error('[Elit HMR] WebSocket error:',e)})();<\/script>`;s=s.includes("</body>")?s.replace("</body>",`${a}</body>`):s+a,e.writeHead(200,{"Content-Type":"text/html","Cache-Control":"no-cache, no-store, must-revalidate"}),e.end(s),r.logging&&console.log("[200] SSR rendered")}catch(t){e.writeHead(500,{"Content-Type":"text/plain"}),e.end("500 SSR Error"),r.logging&&console.error("[500] SSR Error:",t)}}(t,s):(t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found"))}let c=n.startsWith(a+h)||n===a,u=n.startsWith(i+h+"dist"+h);if(!c&&!u)return r.logging&&console.log(`[403] Attempted to serve file outside allowed directories: ${e}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");let m=await l(n),f=p(n),b=y(n)||"application/octet-stream";if(".ts"===f||".tsx"===f)try{let e=await v({stdin:{contents:m.toString(),loader:".tsx"===f?"tsx":"ts",resolveDir:d(n,".."),sourcefile:n},format:"esm",target:"es2020",write:!1,bundle:!1,sourcemap:"inline"});m=Buffer.from(e.outputFiles[0].text),b="application/javascript"}catch(e){return t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`TypeScript compilation error:\n${e}`),void(r.logging&&console.error("[500] TypeScript compilation error:",e))}if(".html"===f){let e=`<script type="importmap">\n{\n "imports": {\n "elit": "${s.basePath?`${s.basePath}/dist/client.mjs`:"/dist/client.mjs"}"\n }\n}\n<\/script>`,t=`<script>(function(){const ws=new WebSocket('ws://${r.host}:${r.port}${s.basePath}');ws.onopen=()=>console.log('[Elit HMR] Connected');ws.onmessage=(e)=>{const d=JSON.parse(e.data);if(d.type==='update'){console.log('[Elit HMR] File updated:',d.path);window.location.reload()}else if(d.type==='reload'){console.log('[Elit HMR] Reloading...');window.location.reload()}else if(d.type==='error')console.error('[Elit HMR] Error:',d.error)};ws.onclose=()=>{console.log('[Elit HMR] Disconnected - Retrying...');setTimeout(()=>window.location.reload(),1000)};ws.onerror=(e)=>console.error('[Elit HMR] WebSocket error:',e)})();<\/script>`,n=m.toString();if(s.basePath&&"/"!==s.basePath){let e=`<base href="${s.basePath}/">`;n.includes("<base")||(n.includes('<meta name="viewport"')?n=n.replace(/<meta name="viewport"[^>]*>/,t=>`${t}\n ${e}`):n.includes("<head>")&&(n=n.replace("<head>",`<head>\n ${e}`)))}n=n.includes("</head>")?n.replace("</head>",`${e}</head>`):n,n=n.includes("</body>")?n.replace("</body>",`${t}</body>`):n+t,m=Buffer.from(n)}let w={"Content-Type":b,"Cache-Control":".html"===f||".ts"===f||".tsx"===f?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable"};if(/^(text\/|application\/(javascript|json|xml))/.test(b)&&m.length>1024){let{gzipSync:e}=N("zlib"),r=e(m);w["Content-Encoding"]="gzip",w["Content-Length"]=r.length,t.writeHead(200,w),t.end(r)}else t.writeHead(200,w),t.end(m);r.logging&&console.log(`[200] ${g(s.root,e)}`)}catch(e){t.writeHead(500,{"Content-Type":"text/plain"}),t.end("500 Internal Server Error"),r.logging&&console.error("[500] Error reading file:",e)}}let T=new n({server:S});T.on("connection",e=>{m.add(e);let t={type:"connected",timestamp:Date.now()};e.send(JSON.stringify(t)),r.logging&&console.log("[HMR] Client connected"),e.on("message",t=>{try{let s=JSON.parse(t.toString());"state:subscribe"===s.type?(f.subscribe(s.key,e),r.logging&&console.log(`[State] Client subscribed to "${s.key}"`)):"state:unsubscribe"===s.type?(f.unsubscribe(s.key,e),r.logging&&console.log(`[State] Client unsubscribed from "${s.key}"`)):"state:change"===s.type&&(f.handleStateChange(s.key,s.value),r.logging&&console.log(`[State] Client updated "${s.key}"`))}catch(e){r.logging&&console.error("[WebSocket] Message parse error:",e)}}),e.on("close",()=>{m.delete(e),f.unsubscribeAll(e),r.logging&&console.log("[HMR] Client disconnected")})});let C=w.flatMap(e=>r.watch.map(t=>u(e.root,t))),M=a(C,{ignored:r.ignore,ignoreInitial:!0,persistent:!0});M.on("change",e=>{r.logging&&console.log(`[HMR] File changed: ${e}`);let t=JSON.stringify({type:"update",path:e,timestamp:Date.now()});m.forEach(e=>e.readyState===s.OPEN&&e.send(t))}),M.on("add",e=>r.logging&&console.log(`[HMR] File added: ${e}`)),M.on("unlink",e=>r.logging&&console.log(`[HMR] File removed: ${e}`)),S.setMaxListeners(20),S.listen(r.port,r.host,()=>{if(r.logging){if(console.log("\n🚀 Elit Dev Server"),console.log(`\n ➜ Local: http://${r.host}:${r.port}`),w.length>1)console.log(" ➜ Clients:"),w.forEach(e=>{let t=`http://${r.host}:${r.port}${e.basePath}`;console.log(` - ${t} → ${e.root}`)});else{let e=w[0];console.log(` ➜ Root: ${e.root}`),e.basePath&&console.log(` ➜ Base: ${e.basePath}`)}console.log("\n[HMR] Watching for file changes...\n")}if(r.open&&w.length>0){let e=w[0],t=`http://${r.host}:${r.port}${e.basePath}`;(async()=>{let{default:e}=await import("open");await e(t)})().catch(()=>{})}});let R=!1,k=w[0],H=`http://${r.host}:${r.port}${k.basePath}`;return{server:S,wss:T,url:H,state:f,close:async()=>{if(!R)return R=!0,r.logging&&console.log("\n[Server] Shutting down..."),await M.close(),T.close(),m.forEach(e=>e.close()),m.clear(),new Promise(e=>{S.close(()=>{r.logging&&console.log("[Server] Closed"),e()})})}}}var As=new class{constructor(){this.enabled=!1,this.ws=null,this.acceptCallbacks=[],this.disposeCallbacks=[],this.declined=!1,typeof window>"u"||this.connect()}connect(){let e="https:"===window.location.protocol?"wss:":"ws:",t=window.location.hostname,r=window.location.port||"3000";this.ws=new WebSocket(`${e}//${t}:${r}`),this.ws.onopen=()=>{this.enabled=!0,console.log("[Elit HMR] Connected ✓")},this.ws.onmessage=e=>{try{let t=JSON.parse(e.data);this.handleMessage(t)}catch(e){console.error("[Elit HMR] Error parsing message:",e)}},this.ws.onclose=()=>{this.enabled=!1,console.log("[Elit HMR] Disconnected - Attempting reconnect..."),setTimeout(()=>this.reload(),1e3)},this.ws.onerror=e=>{console.error("[Elit HMR] WebSocket error:",e)}}handleMessage(e){switch(e.type){case"connected":console.log("[Elit HMR] Ready");break;case"update":if(console.log(`[Elit HMR] Update detected: ${e.path}`),this.declined)return void this.reload();this.disposeCallbacks.forEach(e=>e()),this.disposeCallbacks=[],this.acceptCallbacks.length>0?this.acceptCallbacks.forEach(e=>e()):this.reload();break;case"reload":console.log("[Elit HMR] Full reload requested"),this.reload();break;case"error":console.error("[Elit HMR] Server error:",e.error)}}reload(){window.location.reload()}accept(e){e&&this.acceptCallbacks.push(e),this.declined=!1}decline(){this.declined=!0}dispose(e){this.disposeCallbacks.push(e)}};typeof window<"u"&&(window.__ELIT_HMR__=As);var Ds=As,Ps={outDir:"dist",minify:!0,sourcemap:!1,target:"es2020",format:"esm",treeshake:!0,logging:!0,external:[]};async function Ws(e){let t={...Ps,...e},r=Date.now();if(!t.entry)throw new Error("Entry file is required");let s=d(t.entry),n=d(t.outDir),a=t.outFile;if(!a){a=m(t.entry,p(t.entry))+("cjs"===t.format?".cjs":".js")}let o=u(n,a);try{b(n,{recursive:!0})}catch{}t.logging&&(console.log("\n🔨 Building..."),console.log(` Entry: ${t.entry}`),console.log(` Output: ${o}`),console.log(` Format: ${t.format}`),console.log(` Target: ${t.target}`));let i={name:"browser-only",setup(e){e.onResolve({filter:/^(node:.*|fs|path|http|https|url|os|child_process|net|tls|crypto|stream|util|events|buffer|zlib|readline|process|assert|constants|dns|domain|punycode|querystring|repl|string_decoder|sys|timers|tty|v8|vm)$/},()=>({path:"node-builtin",external:!0,sideEffects:!1})),e.onResolve({filter:/^(chokidar|esbuild|mime-types|open|ws|fs\/promises)$/},()=>({path:"server-dep",external:!0,sideEffects:!1})),e.onLoad({filter:/[\\/](server|config|cli)\.ts$/},()=>({contents:"export {}",loader:"js"}))}};try{let e=t.platform||("cjs"===t.format?"node":"browser"),a="browser"===e?[i]:[],l={};t.env&&(Object.entries(t.env).forEach(([e,t])=>{e.startsWith("VITE_")&&(l[`import.meta.env.${e}`]=JSON.stringify(t))}),t.env.MODE&&(l["import.meta.env.MODE"]=JSON.stringify(t.env.MODE)),l["import.meta.env.DEV"]=JSON.stringify("production"!==t.env.MODE),l["import.meta.env.PROD"]=JSON.stringify("production"===t.env.MODE));let c=await v({entryPoints:[s],bundle:!0,outfile:o,format:t.format,target:t.target,minify:t.minify,sourcemap:t.sourcemap,external:t.external,treeShaking:t.treeshake,globalName:t.globalName,platform:e,plugins:a,define:l,logLevel:t.logging?"info":"silent",metafile:!0,...t.minify&&{minifyWhitespace:!0,minifyIdentifiers:!0,minifySyntax:!0,legalComments:"none",mangleProps:/^_/,keepNames:!1}}),u=Date.now()-r,h=w(o).size;if(t.logging&&(console.log("\n✅ Build successful!"),console.log(` Time: ${u}ms`),console.log(` Size: ${Ls(h)}`),c.metafile)){let e=Object.keys(c.metafile.inputs).length;console.log(` Files: ${e} input(s)`);let t=Object.keys(c.metafile.outputs);if(t.length>0){let e=c.metafile.outputs[t[0]];if(e&&e.inputs){let t=Object.entries(e.inputs).sort(([,e],[,t])=>t.bytesInOutput-e.bytesInOutput).slice(0,5);t.length>0&&(console.log("\n 📊 Top 5 largest modules:"),t.forEach(([e,t])=>{let r=e.split(/[/\\]/).pop()||e;console.log(` ${r.padEnd(30)} ${Ls(t.bytesInOutput)}`)}))}}}let p={outputPath:o,buildTime:u,size:h};if(t.copy&&t.copy.length>0){t.logging&&console.log("\n📦 Copying files...");for(let e of t.copy){let r=d(e.from),s=d(n,e.to),a=f(s);if($(a)||b(a,{recursive:!0}),$(r)){if(e.transform){let n=S(r,"utf-8"),a=e.transform(n,t);E(s,a)}else T(r,s);t.logging&&console.log(` ✓ ${e.from} → ${e.to}`)}else t.logging&&console.warn(` ⚠ File not found: ${e.from}`)}}return t.onBuildEnd&&await t.onBuildEnd(p),t.logging&&console.log(""),p}catch(e){throw t.logging&&(console.error("\n❌ Build failed:"),console.error(e)),e}}function Ls(e){if(0===e)return"0 B";let t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["B","KB","MB","GB"][t]}function qs(e){return e}var Bs=["elit.config.ts","elit.config.js","elit.config.mjs","elit.config.cjs","elit.config.json"];function Us(e="development",t=process.cwd()){let r={MODE:e},s=[`.env.${e}.local`,`.env.${e}`,".env.local",".env"];for(let e of s){let s=d(t,e);if($(s)){let e=S(s,"utf-8").split("\n");for(let t of e){let e=t.trim();if(!e||e.startsWith("#"))continue;let s=e.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(s){let[,e,t]=s,n=t.trim();(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),e in r||(r[e]=n)}}}}return r}async function Is(e=process.cwd()){for(let t of Bs){let r=d(e,t);if($(r))try{return await Js(r)}catch(e){throw console.error(`Error loading config file: ${t}`),console.error(e),e}}return null}async function Js(e){let t=e.split(".").pop();if("json"===t){let t=S(e,"utf-8");return JSON.parse(t)}if("ts"!==t){let{pathToFileURL:t}=await import("url"),r=await import(t(e).href);return r.default||r}try{let{pathToFileURL:t}=await import("url"),r=await import(t(e).href);return r.default||r}catch{throw console.error("TypeScript config files require tsx or ts-node to be installed."),console.error("Install with: npm install -D tsx"),console.error("Or use a .js or .json config file instead."),new Error("Cannot load TypeScript config without tsx/ts-node")}}function Vs(e,t){return e?{...e,...Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t))}:t}export{ys as ApiRouter,G as CreateStyle,M as DomNode,ys as ServerRouter,Hs as SharedState,Os as StateManager,ke as a,He as abbr,se as address,nt as area,ne as article,ae as aside,at as audio,Oe as b,Q as base,O as batchRender,Fe as bdi,je as bdo,_ as bindChecked,V as bindValue,ye as blockquote,Z as body,Ns as bodyLimit,Ae as br,Ws as build,Ot as button,Ms as cacheControl,yt as canvas,St as caption,De as cite,D as cleanupUnused,Pe as code,Et as col,Tt as colgroup,ls as commentNode,xs as compress,k as computed,Ss as cors,js as createDevServer,ss as createEl,z as createElementFactory,as as createMathEl,gs as createRouter,ms as createRouterView,q as createSharedState,R as createState,ns as createSvgEl,j as createVirtualList,We as data,Ft as datalist,ve as dd,W as debounce,qs as defineConfig,wt as del,_t as details,Le as dfn,Gt as dialog,be as div,we as dl,es as doc,x as dom,$e as dt,H as effect,Qr as el,K as elements,qe as em,dt as embed,Ts as errorHandler,jt as fieldset,Se as figcaption,Ee as figure,oe as footer,At as form,os as fragment,ts as getEl,ds as getElClass,cs as getElId,hs as getElName,us as getElTag,rs as getEls,le as h1,ce as h2,de as h3,ue as h4,he as h5,pe as h6,X as head,ie as header,Ds as hmr,Te as hr,ws as html,Be as i,ut as iframe,ot as img,Dt as input,$t as ins,vs as json,Ue as kbd,Pt as label,A as lazy,Wt as legend,Ce as li,ee as link,Is as loadConfig,Us as loadEnv,Es as logger,ge as main,it as map,Ie as mark,qr as mathMath,Gr as mathMfrac,Br as mathMi,Ur as mathMn,Ir as mathMo,Kr as mathMroot,_r as mathMrow,Jr as mathMs,zr as mathMsqrt,Xr as mathMsub,Zr as mathMsup,Vr as mathMtext,zt as menu,Vs as mergeConfig,te as meta,Lt as meter,me as nav,vt as noscript,ht as object,Ne as ol,qt as optgroup,Bt as option,Ut as output,Me as p,pt as param,gt as picture,mt as portal,xe as pre,It as progress,Je as q,Cs as rateLimit,U as reactive,I as reactiveAs,F as renderChunked,fs as routerLink,Ve as rp,_e as rt,Ge as ruby,ze as s,Ke as samp,bt as script,fe as section,Rs as security,Jt as select,bs as sendText,B as sharedStateManager,Xt as slot,Xe as small,ft as source,Ze as span,$s as status,Ye as strong,re as style,Qe as sub,Kt as summary,et as sup,$r as svgAnimate,Er as svgAnimateMotion,Sr as svgAnimateTransform,Qt as svgCircle,mr as svgClipPath,cr as svgDefs,ar as svgEllipse,Nr as svgFeBlend,Mr as svgFeColorMatrix,xr as svgFeComponentTransfer,Rr as svgFeComposite,kr as svgFeConvolveMatrix,Hr as svgFeDiffuseLighting,Or as svgFeDisplacementMap,Fr as svgFeFlood,jr as svgFeGaussianBlur,Ar as svgFeMorphology,Dr as svgFeOffset,Pr as svgFeSpecularLighting,Wr as svgFeTile,Lr as svgFeTurbulence,Cr as svgFilter,wr as svgForeignObject,or as svgG,br as svgImage,rr as svgLine,dr as svgLinearGradient,vr as svgMarker,gr as svgMask,tr as svgPath,pr as svgPattern,nr as svgPolygon,sr as svgPolyline,ur as svgRadialGradient,er as svgRect,Tr as svgSet,hr as svgStop,Yt as svgSvg,yr as svgSymbol,ir as svgText,lr as svgTspan,fr as svgUse,Ct as table,Nt as tbody,Mt as td,Zt as template,J as text,is as textNode,Vt as textarea,xt as tfoot,Rt as th,kt as thead,P as throttle,tt as time,Y as title,Ht as tr,lt as track,rt as u,Re as ul,Yr as varElement,ct as video,st as wbr};
1
+ import {createRequire as __createRequire} from 'module';const require = __createRequire(import.meta.url);
2
+
3
+ // src/dom.ts
4
+ function resolveElement(rootElement) {
5
+ return typeof rootElement === "string" ? document.getElementById(rootElement.replace("#", "")) : rootElement;
6
+ }
7
+ function ensureElement(el2, rootElement) {
8
+ if (!el2) {
9
+ throw new Error(`Element not found: ${rootElement}`);
10
+ }
11
+ return el2;
12
+ }
13
+ function shouldSkipChild(child) {
14
+ return child == null || child === false;
15
+ }
16
+ function isPrimitiveJson(json) {
17
+ return json == null || typeof json === "boolean" || typeof json === "string" || typeof json === "number";
18
+ }
19
+ var DomNode = class {
20
+ constructor() {
21
+ this.elementCache = /* @__PURE__ */ new WeakMap();
22
+ this.reactiveNodes = /* @__PURE__ */ new Map();
23
+ }
24
+ createElement(tagName, props = {}, children = []) {
25
+ return { tagName, props, children };
26
+ }
27
+ renderToDOM(vNode, parent) {
28
+ if (vNode == null || vNode === false) return;
29
+ if (typeof vNode !== "object") {
30
+ parent.appendChild(document.createTextNode(String(vNode)));
31
+ return;
32
+ }
33
+ const { tagName, props, children } = vNode;
34
+ const isSVG = tagName === "svg" || tagName[0] === "s" && tagName[1] === "v" && tagName[2] === "g" || parent.namespaceURI === "http://www.w3.org/2000/svg";
35
+ const el2 = isSVG ? document.createElementNS("http://www.w3.org/2000/svg", tagName.replace("svg", "").toLowerCase() || tagName) : document.createElement(tagName);
36
+ for (const key in props) {
37
+ const value = props[key];
38
+ if (value == null || value === false) continue;
39
+ const c = key.charCodeAt(0);
40
+ if (c === 99 && (key.length < 6 || key[5] === "N")) {
41
+ const classValue = Array.isArray(value) ? value.join(" ") : value;
42
+ isSVG ? el2.setAttribute("class", classValue) : el2.className = classValue;
43
+ } else if (c === 115 && key.length === 5) {
44
+ if (typeof value === "string") {
45
+ el2.style.cssText = value;
46
+ } else {
47
+ const s2 = el2.style;
48
+ for (const k in value) s2[k] = value[k];
49
+ }
50
+ } else if (c === 111 && key.charCodeAt(1) === 110) {
51
+ el2[key.toLowerCase()] = value;
52
+ } else if (c === 100 && key.length > 20) {
53
+ el2.innerHTML = value.__html;
54
+ } else if (c === 114 && key.length === 3) {
55
+ setTimeout(() => {
56
+ typeof value === "function" ? value(el2) : value.current = el2;
57
+ }, 0);
58
+ } else {
59
+ el2.setAttribute(key, value === true ? "" : String(value));
60
+ }
61
+ }
62
+ const len = children.length;
63
+ if (!len) {
64
+ parent.appendChild(el2);
65
+ return;
66
+ }
67
+ const renderChildren = (target) => {
68
+ for (let i2 = 0; i2 < len; i2++) {
69
+ const child = children[i2];
70
+ if (shouldSkipChild(child)) continue;
71
+ if (Array.isArray(child)) {
72
+ for (let j = 0, cLen = child.length; j < cLen; j++) {
73
+ const c = child[j];
74
+ !shouldSkipChild(c) && this.renderToDOM(c, target);
75
+ }
76
+ } else {
77
+ this.renderToDOM(child, target);
78
+ }
79
+ }
80
+ };
81
+ if (len > 30) {
82
+ const fragment2 = document.createDocumentFragment();
83
+ renderChildren(fragment2);
84
+ el2.appendChild(fragment2);
85
+ } else {
86
+ renderChildren(el2);
87
+ }
88
+ parent.appendChild(el2);
89
+ }
90
+ render(rootElement, vNode) {
91
+ const el2 = ensureElement(resolveElement(rootElement), rootElement);
92
+ el2.innerHTML = "";
93
+ if (vNode.children && vNode.children.length > 500) {
94
+ const fragment2 = document.createDocumentFragment();
95
+ this.renderToDOM(vNode, fragment2);
96
+ el2.appendChild(fragment2);
97
+ } else {
98
+ this.renderToDOM(vNode, el2);
99
+ }
100
+ return el2;
101
+ }
102
+ batchRender(rootElement, vNodes) {
103
+ const el2 = ensureElement(resolveElement(rootElement), rootElement);
104
+ const len = vNodes.length;
105
+ if (len > 3e3) {
106
+ const fragment2 = document.createDocumentFragment();
107
+ let processed = 0;
108
+ const chunkSize = 1500;
109
+ const processChunk = () => {
110
+ const end = Math.min(processed + chunkSize, len);
111
+ for (let i2 = processed; i2 < end; i2++) {
112
+ this.renderToDOM(vNodes[i2], fragment2);
113
+ }
114
+ processed = end;
115
+ if (processed >= len) {
116
+ el2.appendChild(fragment2);
117
+ } else {
118
+ requestAnimationFrame(processChunk);
119
+ }
120
+ };
121
+ processChunk();
122
+ } else {
123
+ const fragment2 = document.createDocumentFragment();
124
+ for (let i2 = 0; i2 < len; i2++) {
125
+ this.renderToDOM(vNodes[i2], fragment2);
126
+ }
127
+ el2.appendChild(fragment2);
128
+ }
129
+ return el2;
130
+ }
131
+ renderChunked(rootElement, vNodes, chunkSize = 5e3, onProgress) {
132
+ const el2 = ensureElement(resolveElement(rootElement), rootElement);
133
+ const len = vNodes.length;
134
+ let index = 0;
135
+ const renderChunk = () => {
136
+ const end = Math.min(index + chunkSize, len);
137
+ const fragment2 = document.createDocumentFragment();
138
+ for (let i2 = index; i2 < end; i2++) {
139
+ this.renderToDOM(vNodes[i2], fragment2);
140
+ }
141
+ el2.appendChild(fragment2);
142
+ index = end;
143
+ if (onProgress) onProgress(index, len);
144
+ if (index < len) {
145
+ requestAnimationFrame(renderChunk);
146
+ }
147
+ };
148
+ requestAnimationFrame(renderChunk);
149
+ return el2;
150
+ }
151
+ renderToHead(...vNodes) {
152
+ const head2 = document.head;
153
+ if (head2) {
154
+ for (const vNode of vNodes.flat()) {
155
+ vNode && this.renderToDOM(vNode, head2);
156
+ }
157
+ }
158
+ return head2;
159
+ }
160
+ addStyle(cssText) {
161
+ const el2 = document.createElement("style");
162
+ el2.textContent = cssText;
163
+ return document.head.appendChild(el2);
164
+ }
165
+ addMeta(attrs) {
166
+ const el2 = document.createElement("meta");
167
+ for (const k in attrs) el2.setAttribute(k, attrs[k]);
168
+ return document.head.appendChild(el2);
169
+ }
170
+ addLink(attrs) {
171
+ const el2 = document.createElement("link");
172
+ for (const k in attrs) el2.setAttribute(k, attrs[k]);
173
+ return document.head.appendChild(el2);
174
+ }
175
+ setTitle(text2) {
176
+ return document.title = text2;
177
+ }
178
+ // Reactive State Management
179
+ createState(initialValue, options = {}) {
180
+ let value = initialValue;
181
+ const listeners = /* @__PURE__ */ new Set();
182
+ let updateTimer = null;
183
+ const { throttle: throttle2 = 0, deep = false } = options;
184
+ const notify = () => listeners.forEach((fn) => fn(value));
185
+ const scheduleUpdate = () => {
186
+ if (throttle2 > 0) {
187
+ if (!updateTimer) {
188
+ updateTimer = setTimeout(() => {
189
+ updateTimer = null;
190
+ notify();
191
+ }, throttle2);
192
+ }
193
+ } else {
194
+ notify();
195
+ }
196
+ };
197
+ return {
198
+ get value() {
199
+ return value;
200
+ },
201
+ set value(newValue) {
202
+ const changed = deep ? JSON.stringify(value) !== JSON.stringify(newValue) : value !== newValue;
203
+ if (changed) {
204
+ value = newValue;
205
+ scheduleUpdate();
206
+ }
207
+ },
208
+ subscribe(fn) {
209
+ listeners.add(fn);
210
+ return () => listeners.delete(fn);
211
+ },
212
+ destroy() {
213
+ listeners.clear();
214
+ updateTimer && clearTimeout(updateTimer);
215
+ }
216
+ };
217
+ }
218
+ computed(states, computeFn) {
219
+ const values = states.map((s2) => s2.value);
220
+ const result = this.createState(computeFn(...values));
221
+ states.forEach((state, index) => {
222
+ state.subscribe((newValue) => {
223
+ values[index] = newValue;
224
+ result.value = computeFn(...values);
225
+ });
226
+ });
227
+ return result;
228
+ }
229
+ effect(stateFn) {
230
+ stateFn();
231
+ }
232
+ // Virtual scrolling helper for large lists
233
+ createVirtualList(container2, items, renderItem, itemHeight = 50, bufferSize = 5) {
234
+ const viewportHeight = container2.clientHeight;
235
+ const totalHeight = items.length * itemHeight;
236
+ let scrollTop = 0;
237
+ const getVisibleRange = () => {
238
+ const start = Math.max(0, Math.floor(scrollTop / itemHeight) - bufferSize);
239
+ const end = Math.min(items.length, Math.ceil((scrollTop + viewportHeight) / itemHeight) + bufferSize);
240
+ return { start, end };
241
+ };
242
+ const render2 = () => {
243
+ const { start, end } = getVisibleRange();
244
+ const wrapper = document.createElement("div");
245
+ wrapper.style.cssText = `height:${totalHeight}px;position:relative`;
246
+ for (let i2 = start; i2 < end; i2++) {
247
+ const itemEl = document.createElement("div");
248
+ itemEl.style.cssText = `position:absolute;top:${i2 * itemHeight}px;height:${itemHeight}px;width:100%`;
249
+ this.renderToDOM(renderItem(items[i2], i2), itemEl);
250
+ wrapper.appendChild(itemEl);
251
+ }
252
+ container2.innerHTML = "";
253
+ container2.appendChild(wrapper);
254
+ };
255
+ const scrollHandler = () => {
256
+ scrollTop = container2.scrollTop;
257
+ requestAnimationFrame(render2);
258
+ };
259
+ container2.addEventListener("scroll", scrollHandler);
260
+ render2();
261
+ return {
262
+ render: render2,
263
+ destroy: () => {
264
+ container2.removeEventListener("scroll", scrollHandler);
265
+ container2.innerHTML = "";
266
+ }
267
+ };
268
+ }
269
+ // Lazy load components
270
+ lazy(loadFn) {
271
+ let component = null;
272
+ let loading = false;
273
+ return async (...args) => {
274
+ if (!component && !loading) {
275
+ loading = true;
276
+ component = await loadFn();
277
+ loading = false;
278
+ }
279
+ return component ? component(...args) : { tagName: "div", props: { class: "loading" }, children: ["Loading..."] };
280
+ };
281
+ }
282
+ // Memory management - cleanup unused elements
283
+ cleanupUnusedElements(root) {
284
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
285
+ const toRemove = [];
286
+ while (walker.nextNode()) {
287
+ const node = walker.currentNode;
288
+ if (node.id && node.id.startsWith("r") && !this.elementCache.has(node)) {
289
+ toRemove.push(node);
290
+ }
291
+ }
292
+ toRemove.forEach((el2) => el2.remove());
293
+ return toRemove.length;
294
+ }
295
+ // Server-Side Rendering - convert VNode to HTML string
296
+ renderToString(vNode, options = {}) {
297
+ const { pretty = false, indent = 0 } = options;
298
+ const indentStr = pretty ? " ".repeat(indent) : "";
299
+ const newLine = pretty ? "\n" : "";
300
+ let resolvedVNode = this.resolveStateValue(vNode);
301
+ resolvedVNode = this.unwrapReactive(resolvedVNode);
302
+ if (Array.isArray(resolvedVNode)) {
303
+ return resolvedVNode.map((child) => this.renderToString(child, options)).join("");
304
+ }
305
+ if (typeof resolvedVNode !== "object" || resolvedVNode === null) {
306
+ if (resolvedVNode === null || resolvedVNode === void 0 || resolvedVNode === false) {
307
+ return "";
308
+ }
309
+ return this.escapeHtml(String(resolvedVNode));
310
+ }
311
+ const { tagName, props, children } = resolvedVNode;
312
+ const isSelfClosing = this.isSelfClosingTag(tagName);
313
+ let html2 = `${indentStr}<${tagName}`;
314
+ const attrs = this.propsToAttributes(props);
315
+ if (attrs) {
316
+ html2 += ` ${attrs}`;
317
+ }
318
+ if (isSelfClosing) {
319
+ html2 += ` />${newLine}`;
320
+ return html2;
321
+ }
322
+ html2 += ">";
323
+ if (props.dangerouslySetInnerHTML) {
324
+ html2 += props.dangerouslySetInnerHTML.__html;
325
+ html2 += `</${tagName}>${newLine}`;
326
+ return html2;
327
+ }
328
+ if (children && children.length > 0) {
329
+ const resolvedChildren = children.map((c) => {
330
+ const resolved = this.resolveStateValue(c);
331
+ return this.unwrapReactive(resolved);
332
+ });
333
+ const hasComplexChildren = resolvedChildren.some(
334
+ (c) => typeof c === "object" && c !== null && !Array.isArray(c) && "tagName" in c
335
+ );
336
+ if (pretty && hasComplexChildren) {
337
+ html2 += newLine;
338
+ for (const child of resolvedChildren) {
339
+ if (shouldSkipChild(child)) continue;
340
+ if (Array.isArray(child)) {
341
+ for (const c of child) {
342
+ if (!shouldSkipChild(c)) {
343
+ html2 += this.renderToString(c, { pretty, indent: indent + 1 });
344
+ }
345
+ }
346
+ } else {
347
+ html2 += this.renderToString(child, { pretty, indent: indent + 1 });
348
+ }
349
+ }
350
+ html2 += indentStr;
351
+ } else {
352
+ for (const child of resolvedChildren) {
353
+ if (shouldSkipChild(child)) continue;
354
+ if (Array.isArray(child)) {
355
+ for (const c of child) {
356
+ if (!shouldSkipChild(c)) {
357
+ html2 += this.renderToString(c, { pretty: false, indent: 0 });
358
+ }
359
+ }
360
+ } else {
361
+ html2 += this.renderToString(child, { pretty: false, indent: 0 });
362
+ }
363
+ }
364
+ }
365
+ }
366
+ html2 += `</${tagName}>${newLine}`;
367
+ return html2;
368
+ }
369
+ resolveStateValue(value) {
370
+ if (value && typeof value === "object" && "value" in value && "subscribe" in value) {
371
+ return value.value;
372
+ }
373
+ return value;
374
+ }
375
+ isReactiveWrapper(vNode) {
376
+ if (!vNode || typeof vNode !== "object" || !vNode.tagName) {
377
+ return false;
378
+ }
379
+ return vNode.tagName === "span" && vNode.props?.id && typeof vNode.props.id === "string" && vNode.props.id.match(/^r[a-z0-9]{9}$/);
380
+ }
381
+ unwrapReactive(vNode) {
382
+ if (!this.isReactiveWrapper(vNode)) {
383
+ return vNode;
384
+ }
385
+ const children = vNode.children;
386
+ if (!children || children.length === 0) {
387
+ return "";
388
+ }
389
+ if (children.length === 1) {
390
+ const child = children[0];
391
+ if (child && typeof child === "object" && child.tagName === "span") {
392
+ const props = child.props;
393
+ const hasNoProps = !props || Object.keys(props).length === 0;
394
+ const hasSingleStringChild = child.children && child.children.length === 1 && typeof child.children[0] === "string";
395
+ if (hasNoProps && hasSingleStringChild) {
396
+ return child.children[0];
397
+ }
398
+ }
399
+ return this.unwrapReactive(child);
400
+ }
401
+ return children.map((c) => this.unwrapReactive(c));
402
+ }
403
+ escapeHtml(text2) {
404
+ const htmlEscapes = {
405
+ "&": "&amp;",
406
+ "<": "&lt;",
407
+ ">": "&gt;",
408
+ '"': "&quot;",
409
+ "'": "&#x27;"
410
+ };
411
+ return text2.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
412
+ }
413
+ isSelfClosingTag(tagName) {
414
+ const selfClosingTags = /* @__PURE__ */ new Set([
415
+ "area",
416
+ "base",
417
+ "br",
418
+ "col",
419
+ "embed",
420
+ "hr",
421
+ "img",
422
+ "input",
423
+ "link",
424
+ "meta",
425
+ "param",
426
+ "source",
427
+ "track",
428
+ "wbr"
429
+ ]);
430
+ return selfClosingTags.has(tagName.toLowerCase());
431
+ }
432
+ propsToAttributes(props) {
433
+ const attrs = [];
434
+ for (const key in props) {
435
+ if (key === "children" || key === "dangerouslySetInnerHTML" || key === "ref") {
436
+ continue;
437
+ }
438
+ let value = props[key];
439
+ value = this.resolveStateValue(value);
440
+ if (value == null || value === false) continue;
441
+ if (key.startsWith("on") && typeof value === "function") {
442
+ continue;
443
+ }
444
+ if (key === "className" || key === "class") {
445
+ const className = Array.isArray(value) ? value.join(" ") : value;
446
+ if (className) {
447
+ attrs.push(`class="${this.escapeHtml(String(className))}"`);
448
+ }
449
+ continue;
450
+ }
451
+ if (key === "style") {
452
+ const styleStr = this.styleToString(value);
453
+ if (styleStr) {
454
+ attrs.push(`style="${this.escapeHtml(styleStr)}"`);
455
+ }
456
+ continue;
457
+ }
458
+ if (value === true) {
459
+ attrs.push(key);
460
+ continue;
461
+ }
462
+ attrs.push(`${key}="${this.escapeHtml(String(value))}"`);
463
+ }
464
+ return attrs.join(" ");
465
+ }
466
+ styleToString(style2) {
467
+ if (typeof style2 === "string") {
468
+ return style2;
469
+ }
470
+ if (typeof style2 === "object" && style2 !== null) {
471
+ const styles2 = [];
472
+ for (const key in style2) {
473
+ const cssKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
474
+ styles2.push(`${cssKey}:${style2[key]}`);
475
+ }
476
+ return styles2.join(";");
477
+ }
478
+ return "";
479
+ }
480
+ isState(value) {
481
+ return value && typeof value === "object" && "value" in value && "subscribe" in value && typeof value.subscribe === "function";
482
+ }
483
+ createReactiveChild(state, renderFn) {
484
+ const currentValue = renderFn(state.value);
485
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
486
+ const entry = { node: null, renderFn };
487
+ this.reactiveNodes.set(state, entry);
488
+ state.subscribe(() => {
489
+ if (entry.node && entry.node.parentNode) {
490
+ const newValue = renderFn(state.value);
491
+ entry.node.textContent = String(newValue ?? "");
492
+ }
493
+ });
494
+ }
495
+ return currentValue;
496
+ }
497
+ jsonToVNode(json) {
498
+ if (this.isState(json)) {
499
+ return this.createReactiveChild(json, (v) => v);
500
+ }
501
+ if (isPrimitiveJson(json)) {
502
+ return json;
503
+ }
504
+ const { tag, attributes = {}, children } = json;
505
+ const props = {};
506
+ for (const key in attributes) {
507
+ const value = attributes[key];
508
+ if (key === "class") {
509
+ props.className = this.isState(value) ? value.value : value;
510
+ } else {
511
+ props[key] = this.isState(value) ? value.value : value;
512
+ }
513
+ }
514
+ const childrenArray = [];
515
+ if (children != null) {
516
+ if (Array.isArray(children)) {
517
+ for (const child of children) {
518
+ if (this.isState(child)) {
519
+ childrenArray.push(this.createReactiveChild(child, (v) => v));
520
+ } else {
521
+ const converted = this.jsonToVNode(child);
522
+ if (converted != null && converted !== false) {
523
+ childrenArray.push(converted);
524
+ }
525
+ }
526
+ }
527
+ } else if (this.isState(children)) {
528
+ childrenArray.push(this.createReactiveChild(children, (v) => v));
529
+ } else if (typeof children === "object" && "tag" in children) {
530
+ const converted = this.jsonToVNode(children);
531
+ if (converted != null && converted !== false) {
532
+ childrenArray.push(converted);
533
+ }
534
+ } else {
535
+ childrenArray.push(children);
536
+ }
537
+ }
538
+ return { tagName: tag, props, children: childrenArray };
539
+ }
540
+ vNodeJsonToVNode(json) {
541
+ if (this.isState(json)) {
542
+ return this.createReactiveChild(json, (v) => v);
543
+ }
544
+ if (isPrimitiveJson(json)) {
545
+ return json;
546
+ }
547
+ const { tagName, props = {}, children = [] } = json;
548
+ const resolvedProps = {};
549
+ for (const key in props) {
550
+ const value = props[key];
551
+ resolvedProps[key] = this.isState(value) ? value.value : value;
552
+ }
553
+ const childrenArray = [];
554
+ for (const child of children) {
555
+ if (this.isState(child)) {
556
+ childrenArray.push(this.createReactiveChild(child, (v) => v));
557
+ } else {
558
+ const converted = this.vNodeJsonToVNode(child);
559
+ if (converted != null && converted !== false) {
560
+ childrenArray.push(converted);
561
+ }
562
+ }
563
+ }
564
+ return { tagName, props: resolvedProps, children: childrenArray };
565
+ }
566
+ renderJson(rootElement, json) {
567
+ const vNode = this.jsonToVNode(json);
568
+ if (!vNode || typeof vNode !== "object" || !("tagName" in vNode)) {
569
+ throw new Error("Invalid JSON structure");
570
+ }
571
+ return this.render(rootElement, vNode);
572
+ }
573
+ renderVNode(rootElement, json) {
574
+ const vNode = this.vNodeJsonToVNode(json);
575
+ if (!vNode || typeof vNode !== "object" || !("tagName" in vNode)) {
576
+ throw new Error("Invalid VNode JSON structure");
577
+ }
578
+ return this.render(rootElement, vNode);
579
+ }
580
+ renderJsonToString(json, options = {}) {
581
+ const vNode = this.jsonToVNode(json);
582
+ return this.renderToString(vNode, options);
583
+ }
584
+ renderVNodeToString(json, options = {}) {
585
+ const vNode = this.vNodeJsonToVNode(json);
586
+ return this.renderToString(vNode, options);
587
+ }
588
+ // Generate complete HTML document as string (for SSR)
589
+ renderToHTMLDocument(vNode, options = {}) {
590
+ const { title: title2 = "", meta: meta2 = [], links = [], scripts = [], styles: styles2 = [], lang = "en", head: head2 = "", bodyAttrs = {}, pretty = false } = options;
591
+ const nl = pretty ? "\n" : "";
592
+ const indent = pretty ? " " : "";
593
+ const indent2 = pretty ? " " : "";
594
+ let html2 = `<!DOCTYPE html>${nl}<html lang="${lang}">${nl}${indent}<head>${nl}${indent2}<meta charset="UTF-8">${nl}${indent2}<meta name="viewport" content="width=device-width, initial-scale=1.0">${nl}`;
595
+ if (title2) html2 += `${indent2}<title>${this.escapeHtml(title2)}</title>${nl}`;
596
+ for (const m of meta2) {
597
+ html2 += `${indent2}<meta`;
598
+ for (const k in m) html2 += ` ${k}="${this.escapeHtml(m[k])}"`;
599
+ html2 += `>${nl}`;
600
+ }
601
+ for (const l of links) {
602
+ html2 += `${indent2}<link`;
603
+ for (const k in l) html2 += ` ${k}="${this.escapeHtml(l[k])}"`;
604
+ html2 += `>${nl}`;
605
+ }
606
+ for (const s2 of styles2) {
607
+ if (s2.href) {
608
+ html2 += `${indent2}<link rel="stylesheet" href="${this.escapeHtml(s2.href)}">${nl}`;
609
+ } else if (s2.content) {
610
+ html2 += `${indent2}<style>${s2.content}</style>${nl}`;
611
+ }
612
+ }
613
+ if (head2) html2 += head2 + nl;
614
+ html2 += `${indent}</head>${nl}${indent}<body`;
615
+ for (const k in bodyAttrs) html2 += ` ${k}="${this.escapeHtml(bodyAttrs[k])}"`;
616
+ html2 += `>${nl}`;
617
+ html2 += this.renderToString(vNode, { pretty, indent: 2 });
618
+ for (const script2 of scripts) {
619
+ html2 += `${indent2}<script`;
620
+ if (script2.type) html2 += ` type="${this.escapeHtml(script2.type)}"`;
621
+ if (script2.async) html2 += ` async`;
622
+ if (script2.defer) html2 += ` defer`;
623
+ if (script2.src) {
624
+ html2 += ` src="${this.escapeHtml(script2.src)}"></script>${nl}`;
625
+ } else if (script2.content) {
626
+ html2 += `>${script2.content}</script>${nl}`;
627
+ } else {
628
+ html2 += `></script>${nl}`;
629
+ }
630
+ }
631
+ html2 += `${indent}</body>${nl}</html>`;
632
+ return html2;
633
+ }
634
+ // Expose elementCache for reactive updates
635
+ getElementCache() {
636
+ return this.elementCache;
637
+ }
638
+ };
639
+ var dom = new DomNode();
640
+ var render = dom.render.bind(dom);
641
+ var renderToString = dom.renderToString.bind(dom);
642
+ var mount = render;
643
+
644
+ // src/state.ts
645
+ var createState = (initial, options) => dom.createState(initial, options);
646
+ var computed = (states, fn) => dom.computed(states, fn);
647
+ var effect = (fn) => dom.effect(fn);
648
+ var batchRender = (container2, vNodes) => dom.batchRender(container2, vNodes);
649
+ var renderChunked = (container2, vNodes, chunkSize, onProgress) => dom.renderChunked(container2, vNodes, chunkSize, onProgress);
650
+ var createVirtualList = (container2, items, renderItem, itemHeight, bufferSize) => dom.createVirtualList(container2, items, renderItem, itemHeight, bufferSize);
651
+ var lazy = (loadFn) => dom.lazy(loadFn);
652
+ var cleanupUnused = (root) => dom.cleanupUnusedElements(root);
653
+ var throttle = (fn, delay) => {
654
+ let timer = null;
655
+ return (...args) => {
656
+ if (!timer) {
657
+ timer = setTimeout(() => {
658
+ timer = null;
659
+ fn(...args);
660
+ }, delay);
661
+ }
662
+ };
663
+ };
664
+ var debounce = (fn, delay) => {
665
+ let timer = null;
666
+ return (...args) => {
667
+ timer && clearTimeout(timer);
668
+ timer = setTimeout(() => fn(...args), delay);
669
+ };
670
+ };
671
+ var SharedState = class {
672
+ constructor(key, defaultValue, wsUrl) {
673
+ this.key = key;
674
+ this.wsUrl = wsUrl;
675
+ this.ws = null;
676
+ this.pendingUpdates = [];
677
+ this.localState = createState(defaultValue);
678
+ this.previousValue = defaultValue;
679
+ this.connect();
680
+ }
681
+ /**
682
+ * Get current value
683
+ */
684
+ get value() {
685
+ return this.localState.value;
686
+ }
687
+ /**
688
+ * Set new value and sync to server
689
+ */
690
+ set value(newValue) {
691
+ this.previousValue = this.localState.value;
692
+ this.localState.value = newValue;
693
+ this.sendToServer(newValue);
694
+ }
695
+ /**
696
+ * Get the underlying Elit State (for reactive binding)
697
+ */
698
+ get state() {
699
+ return this.localState;
700
+ }
701
+ /**
702
+ * Subscribe to changes (returns Elit State for reactive)
703
+ */
704
+ onChange(callback) {
705
+ return this.localState.subscribe((newValue) => {
706
+ const oldValue = this.previousValue;
707
+ this.previousValue = newValue;
708
+ callback(newValue, oldValue);
709
+ });
710
+ }
711
+ /**
712
+ * Update value using a function
713
+ */
714
+ update(updater) {
715
+ this.value = updater(this.value);
716
+ }
717
+ /**
718
+ * Connect to WebSocket
719
+ */
720
+ connect() {
721
+ if (typeof window === "undefined") return;
722
+ const url = this.wsUrl || `ws://${location.host}`;
723
+ this.ws = new WebSocket(url);
724
+ this.ws.addEventListener("open", () => {
725
+ this.subscribe();
726
+ while (this.pendingUpdates.length > 0) {
727
+ const value = this.pendingUpdates.shift();
728
+ this.sendToServer(value);
729
+ }
730
+ });
731
+ this.ws.addEventListener("message", (event) => {
732
+ this.handleMessage(event.data);
733
+ });
734
+ this.ws.addEventListener("close", () => {
735
+ setTimeout(() => this.connect(), 1e3);
736
+ });
737
+ this.ws.addEventListener("error", (error) => {
738
+ console.error("[SharedState] WebSocket error:", error);
739
+ });
740
+ }
741
+ /**
742
+ * Subscribe to server state
743
+ */
744
+ subscribe() {
745
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
746
+ this.ws.send(JSON.stringify({
747
+ type: "state:subscribe",
748
+ key: this.key
749
+ }));
750
+ }
751
+ /**
752
+ * Handle message from server
753
+ */
754
+ handleMessage(data2) {
755
+ try {
756
+ const msg = JSON.parse(data2);
757
+ if (msg.key !== this.key) return;
758
+ if (msg.type === "state:init" || msg.type === "state:update") {
759
+ this.localState.value = msg.value;
760
+ }
761
+ } catch (error) {
762
+ }
763
+ }
764
+ /**
765
+ * Send value to server
766
+ */
767
+ sendToServer(value) {
768
+ if (!this.ws) return;
769
+ if (this.ws.readyState !== WebSocket.OPEN) {
770
+ this.pendingUpdates.push(value);
771
+ return;
772
+ }
773
+ this.ws.send(JSON.stringify({
774
+ type: "state:change",
775
+ key: this.key,
776
+ value
777
+ }));
778
+ }
779
+ /**
780
+ * Disconnect
781
+ */
782
+ disconnect() {
783
+ if (this.ws) {
784
+ this.ws.close();
785
+ this.ws = null;
786
+ }
787
+ }
788
+ /**
789
+ * Destroy state and cleanup
790
+ */
791
+ destroy() {
792
+ this.disconnect();
793
+ this.localState.destroy();
794
+ }
795
+ };
796
+ function createSharedState(key, defaultValue, wsUrl) {
797
+ return new SharedState(key, defaultValue, wsUrl);
798
+ }
799
+ var SharedStateManager = class {
800
+ constructor() {
801
+ this.states = /* @__PURE__ */ new Map();
802
+ }
803
+ /**
804
+ * Create or get a shared state
805
+ */
806
+ create(key, defaultValue, wsUrl) {
807
+ if (this.states.has(key)) {
808
+ return this.states.get(key);
809
+ }
810
+ const state = new SharedState(key, defaultValue, wsUrl);
811
+ this.states.set(key, state);
812
+ return state;
813
+ }
814
+ /**
815
+ * Get existing state
816
+ */
817
+ get(key) {
818
+ return this.states.get(key);
819
+ }
820
+ /**
821
+ * Delete a state
822
+ */
823
+ delete(key) {
824
+ const state = this.states.get(key);
825
+ if (state) {
826
+ state.destroy();
827
+ return this.states.delete(key);
828
+ }
829
+ return false;
830
+ }
831
+ /**
832
+ * Clear all states
833
+ */
834
+ clear() {
835
+ this.states.forEach((state) => state.destroy());
836
+ this.states.clear();
837
+ }
838
+ };
839
+ var sharedStateManager = new SharedStateManager();
840
+ var scheduleRAFUpdate = (rafId, updateFn) => {
841
+ rafId && cancelAnimationFrame(rafId);
842
+ return requestAnimationFrame(() => {
843
+ updateFn();
844
+ });
845
+ };
846
+ var renderToFragment = (content, isVNode) => {
847
+ const fragment2 = document.createDocumentFragment();
848
+ if (isVNode && content && typeof content === "object" && "tagName" in content) {
849
+ const { children } = content;
850
+ for (const child of children) {
851
+ dom.renderToDOM(child, fragment2);
852
+ }
853
+ } else {
854
+ dom.renderToDOM(content, fragment2);
855
+ }
856
+ return fragment2;
857
+ };
858
+ var updateElementProps = (element, props) => {
859
+ for (const key in props) {
860
+ const value = props[key];
861
+ if (key === "ref") continue;
862
+ if (key === "class" || key === "className") {
863
+ element.className = Array.isArray(value) ? value.join(" ") : value || "";
864
+ } else if (key === "style" && typeof value === "object") {
865
+ const s2 = element.style;
866
+ for (const k in value) s2[k] = value[k];
867
+ } else if (key.startsWith("on")) {
868
+ element[key.toLowerCase()] = value;
869
+ } else if (value != null && value !== false) {
870
+ element.setAttribute(key, String(value === true ? "" : value));
871
+ } else {
872
+ element.removeAttribute(key);
873
+ }
874
+ }
875
+ };
876
+ var reactive = (state, renderFn) => {
877
+ let rafId = null;
878
+ let elementRef = null;
879
+ let placeholder = null;
880
+ let isInDOM = true;
881
+ const initialResult = renderFn(state.value);
882
+ const isVNodeResult = initialResult && typeof initialResult === "object" && "tagName" in initialResult;
883
+ const initialIsNull = initialResult == null || initialResult === false;
884
+ const updateElement = () => {
885
+ if (!elementRef && !placeholder) return;
886
+ const newResult = renderFn(state.value);
887
+ const resultIsNull = newResult == null || newResult === false;
888
+ if (resultIsNull) {
889
+ if (isInDOM && elementRef) {
890
+ placeholder = document.createComment("reactive");
891
+ elementRef.parentNode?.replaceChild(placeholder, elementRef);
892
+ isInDOM = false;
893
+ }
894
+ } else {
895
+ if (!isInDOM && placeholder && elementRef) {
896
+ placeholder.parentNode?.replaceChild(elementRef, placeholder);
897
+ placeholder = null;
898
+ isInDOM = true;
899
+ }
900
+ if (elementRef) {
901
+ const isCurrentVNode = !!(isVNodeResult && newResult && typeof newResult === "object" && "tagName" in newResult);
902
+ if (isCurrentVNode) {
903
+ const { props } = newResult;
904
+ updateElementProps(elementRef, props);
905
+ }
906
+ const fragment2 = renderToFragment(newResult, isCurrentVNode);
907
+ elementRef.textContent = "";
908
+ elementRef.appendChild(fragment2);
909
+ dom.getElementCache().set(elementRef, true);
910
+ }
911
+ }
912
+ };
913
+ state.subscribe(() => {
914
+ rafId = scheduleRAFUpdate(rafId, () => {
915
+ updateElement();
916
+ rafId = null;
917
+ });
918
+ });
919
+ const refCallback = (el2) => {
920
+ elementRef = el2;
921
+ if (initialIsNull && el2.parentNode) {
922
+ placeholder = document.createComment("reactive");
923
+ el2.parentNode.replaceChild(placeholder, el2);
924
+ isInDOM = false;
925
+ }
926
+ };
927
+ if (isVNodeResult) {
928
+ const vnode = initialResult;
929
+ return {
930
+ tagName: vnode.tagName,
931
+ props: { ...vnode.props, ref: refCallback },
932
+ children: vnode.children
933
+ };
934
+ }
935
+ return { tagName: "span", props: { ref: refCallback }, children: [initialResult] };
936
+ };
937
+ var reactiveAs = (tagName, state, renderFn, props = {}) => {
938
+ let rafId = null;
939
+ let elementRef = null;
940
+ state.subscribe(() => {
941
+ rafId = scheduleRAFUpdate(rafId, () => {
942
+ if (elementRef) {
943
+ const newResult = renderFn(state.value);
944
+ if (newResult == null || newResult === false) {
945
+ elementRef.style.display = "none";
946
+ elementRef.textContent = "";
947
+ } else {
948
+ elementRef.style.display = "";
949
+ const fragment2 = renderToFragment(newResult, false);
950
+ elementRef.textContent = "";
951
+ elementRef.appendChild(fragment2);
952
+ }
953
+ dom.getElementCache().set(elementRef, true);
954
+ }
955
+ rafId = null;
956
+ });
957
+ });
958
+ const refCallback = (el2) => {
959
+ elementRef = el2;
960
+ };
961
+ return { tagName, props: { ...props, ref: refCallback }, children: [renderFn(state.value)] };
962
+ };
963
+ var text = (state) => state && state.value !== void 0 ? reactive(state, (v) => ({ tagName: "span", props: {}, children: [String(v)] })) : String(state);
964
+ var bindValue = (state) => ({
965
+ value: state.value,
966
+ oninput: (e) => {
967
+ state.value = e.target.value;
968
+ }
969
+ });
970
+ var bindChecked = (state) => ({
971
+ checked: state.value,
972
+ onchange: (e) => {
973
+ state.value = e.target.checked;
974
+ }
975
+ });
976
+
977
+ // src/style.ts
978
+ var CreateStyle = class {
979
+ constructor() {
980
+ this.variables = [];
981
+ this.rules = [];
982
+ this.mediaRules = [];
983
+ this.keyframes = [];
984
+ this.fontFaces = [];
985
+ this.imports = [];
986
+ this.containerRules = [];
987
+ this.supportsRules = [];
988
+ this.layerRules = [];
989
+ this._layerOrder = [];
990
+ }
991
+ // CSS Variables
992
+ addVar(name, value) {
993
+ const cssVar = {
994
+ name: name.startsWith("--") ? name : `--${name}`,
995
+ value,
996
+ toString() {
997
+ return `var(${this.name})`;
998
+ }
999
+ };
1000
+ this.variables.push(cssVar);
1001
+ return cssVar;
1002
+ }
1003
+ var(variable, fallback) {
1004
+ const varName = typeof variable === "string" ? variable.startsWith("--") ? variable : `--${variable}` : variable.name;
1005
+ return fallback ? `var(${varName}, ${fallback})` : `var(${varName})`;
1006
+ }
1007
+ // Basic Selectors
1008
+ addTag(tag, styles2) {
1009
+ const rule = { selector: tag, styles: styles2, type: "tag" };
1010
+ this.rules.push(rule);
1011
+ return rule;
1012
+ }
1013
+ addClass(name, styles2) {
1014
+ const selector = name.startsWith(".") ? name : `.${name}`;
1015
+ const rule = { selector, styles: styles2, type: "class" };
1016
+ this.rules.push(rule);
1017
+ return rule;
1018
+ }
1019
+ addId(name, styles2) {
1020
+ const selector = name.startsWith("#") ? name : `#${name}`;
1021
+ const rule = { selector, styles: styles2, type: "id" };
1022
+ this.rules.push(rule);
1023
+ return rule;
1024
+ }
1025
+ // Pseudo Selectors
1026
+ addPseudoClass(pseudo, styles2, baseSelector) {
1027
+ const pseudoClass = pseudo.startsWith(":") ? pseudo : `:${pseudo}`;
1028
+ const selector = baseSelector ? `${baseSelector}${pseudoClass}` : pseudoClass;
1029
+ const rule = { selector, styles: styles2, type: "pseudo-class" };
1030
+ this.rules.push(rule);
1031
+ return rule;
1032
+ }
1033
+ addPseudoElement(pseudo, styles2, baseSelector) {
1034
+ const pseudoElement = pseudo.startsWith("::") ? pseudo : `::${pseudo}`;
1035
+ const selector = baseSelector ? `${baseSelector}${pseudoElement}` : pseudoElement;
1036
+ const rule = { selector, styles: styles2, type: "pseudo-element" };
1037
+ this.rules.push(rule);
1038
+ return rule;
1039
+ }
1040
+ // Attribute Selectors
1041
+ addAttribute(attr, styles2, baseSelector) {
1042
+ const attrSelector = attr.startsWith("[") ? attr : `[${attr}]`;
1043
+ const selector = baseSelector ? `${baseSelector}${attrSelector}` : attrSelector;
1044
+ const rule = { selector, styles: styles2, type: "attribute" };
1045
+ this.rules.push(rule);
1046
+ return rule;
1047
+ }
1048
+ attrEquals(attr, value, styles2, baseSelector) {
1049
+ return this.addAttribute(`${attr}="${value}"`, styles2, baseSelector);
1050
+ }
1051
+ attrContainsWord(attr, value, styles2, baseSelector) {
1052
+ return this.addAttribute(`${attr}~="${value}"`, styles2, baseSelector);
1053
+ }
1054
+ attrStartsWith(attr, value, styles2, baseSelector) {
1055
+ return this.addAttribute(`${attr}^="${value}"`, styles2, baseSelector);
1056
+ }
1057
+ attrEndsWith(attr, value, styles2, baseSelector) {
1058
+ return this.addAttribute(`${attr}$="${value}"`, styles2, baseSelector);
1059
+ }
1060
+ attrContains(attr, value, styles2, baseSelector) {
1061
+ return this.addAttribute(`${attr}*="${value}"`, styles2, baseSelector);
1062
+ }
1063
+ // Combinator Selectors
1064
+ descendant(ancestor, descendant2, styles2) {
1065
+ return this.createAndAddRule(`${ancestor} ${descendant2}`, styles2);
1066
+ }
1067
+ child(parent, childSel, styles2) {
1068
+ return this.createAndAddRule(`${parent} > ${childSel}`, styles2);
1069
+ }
1070
+ adjacentSibling(element, sibling, styles2) {
1071
+ return this.createAndAddRule(`${element} + ${sibling}`, styles2);
1072
+ }
1073
+ generalSibling(element, sibling, styles2) {
1074
+ return this.createAndAddRule(`${element} ~ ${sibling}`, styles2);
1075
+ }
1076
+ multiple(selectors, styles2) {
1077
+ return this.createAndAddRule(selectors.join(", "), styles2);
1078
+ }
1079
+ // Nesting (BEM-style)
1080
+ addName(name, styles2) {
1081
+ const selector = name.startsWith("--") ? `&${name}` : `&--${name}`;
1082
+ const rule = { selector, styles: styles2, type: "name" };
1083
+ return rule;
1084
+ }
1085
+ nesting(parentRule, ...childRules) {
1086
+ parentRule.nested = childRules;
1087
+ return parentRule;
1088
+ }
1089
+ // @keyframes - Animations
1090
+ keyframe(name, steps) {
1091
+ const keyframeSteps = Object.entries(steps).map(([step, styles2]) => ({
1092
+ step: step === "from" ? "from" : step === "to" ? "to" : `${step}%`,
1093
+ styles: styles2
1094
+ }));
1095
+ const kf = { name, steps: keyframeSteps };
1096
+ this.keyframes.push(kf);
1097
+ return kf;
1098
+ }
1099
+ keyframeFromTo(name, from, to) {
1100
+ return this.keyframe(name, { from, to });
1101
+ }
1102
+ // @font-face - Custom Fonts
1103
+ fontFace(options) {
1104
+ this.fontFaces.push(options);
1105
+ return options;
1106
+ }
1107
+ // @import - Import Stylesheets
1108
+ import(url, mediaQuery) {
1109
+ const importRule = mediaQuery ? `@import url("${url}") ${mediaQuery};` : `@import url("${url}");`;
1110
+ this.imports.push(importRule);
1111
+ return importRule;
1112
+ }
1113
+ // @media - Media Queries
1114
+ media(type, condition, rules) {
1115
+ const mediaRule = { type, condition, rules: this.rulesToCSSRules(rules) };
1116
+ this.mediaRules.push(mediaRule);
1117
+ return mediaRule;
1118
+ }
1119
+ mediaScreen(condition, rules) {
1120
+ return this.media("screen", condition, rules);
1121
+ }
1122
+ mediaPrint(rules) {
1123
+ return this.media("print", "", rules);
1124
+ }
1125
+ mediaMinWidth(minWidth, rules) {
1126
+ return this.media("screen", `min-width: ${minWidth}`, rules);
1127
+ }
1128
+ mediaMaxWidth(maxWidth, rules) {
1129
+ return this.media("screen", `max-width: ${maxWidth}`, rules);
1130
+ }
1131
+ mediaDark(rules) {
1132
+ const mediaRule = { type: "", condition: "prefers-color-scheme: dark", rules: this.rulesToCSSRules(rules) };
1133
+ this.mediaRules.push(mediaRule);
1134
+ return mediaRule;
1135
+ }
1136
+ mediaLight(rules) {
1137
+ const mediaRule = { type: "", condition: "prefers-color-scheme: light", rules: this.rulesToCSSRules(rules) };
1138
+ this.mediaRules.push(mediaRule);
1139
+ return mediaRule;
1140
+ }
1141
+ mediaReducedMotion(rules) {
1142
+ const mediaRule = { type: "", condition: "prefers-reduced-motion: reduce", rules: this.rulesToCSSRules(rules) };
1143
+ this.mediaRules.push(mediaRule);
1144
+ return mediaRule;
1145
+ }
1146
+ // @container - Container Queries
1147
+ container(condition, rules, name) {
1148
+ const containerRule = { name, condition, rules: this.rulesToCSSRules(rules) };
1149
+ this.containerRules.push(containerRule);
1150
+ return containerRule;
1151
+ }
1152
+ addContainer(name, styles2) {
1153
+ const containerStyles = { ...styles2, containerName: name };
1154
+ return this.addClass(name, containerStyles);
1155
+ }
1156
+ // @supports - Feature Queries
1157
+ supports(condition, rules) {
1158
+ const supportsRule = { condition, rules: this.rulesToCSSRules(rules) };
1159
+ this.supportsRules.push(supportsRule);
1160
+ return supportsRule;
1161
+ }
1162
+ // @layer - Cascade Layers
1163
+ layerOrder(...layers) {
1164
+ this._layerOrder = layers;
1165
+ }
1166
+ layer(name, rules) {
1167
+ const layerRule = { name, rules: this.rulesToCSSRules(rules) };
1168
+ this.layerRules.push(layerRule);
1169
+ return layerRule;
1170
+ }
1171
+ // Custom Rules
1172
+ add(rules) {
1173
+ const cssRules = Object.entries(rules).map(([selector, styles2]) => {
1174
+ const rule = { selector, styles: styles2, type: "custom" };
1175
+ this.rules.push(rule);
1176
+ return rule;
1177
+ });
1178
+ return cssRules;
1179
+ }
1180
+ important(value) {
1181
+ return `${value} !important`;
1182
+ }
1183
+ // Utility Methods
1184
+ toKebabCase(str) {
1185
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
1186
+ }
1187
+ // Helper: Create and add rule (eliminates duplication in combinator selectors)
1188
+ createAndAddRule(selector, styles2, type = "custom") {
1189
+ const rule = { selector, styles: styles2, type };
1190
+ this.rules.push(rule);
1191
+ return rule;
1192
+ }
1193
+ // Helper: Convert rules object to CSSRule array (eliminates duplication in media/container/supports/layer)
1194
+ rulesToCSSRules(rules) {
1195
+ return Object.entries(rules).map(([selector, styles2]) => ({
1196
+ selector,
1197
+ styles: styles2,
1198
+ type: "custom"
1199
+ }));
1200
+ }
1201
+ // Helper: Render rules with indentation (eliminates duplication in render methods)
1202
+ renderRulesWithIndent(rules, indent = " ") {
1203
+ return rules.map((rule) => this.renderRule(rule, indent)).join("\n");
1204
+ }
1205
+ stylesToString(styles2, indent = " ") {
1206
+ return Object.entries(styles2).map(([prop, value]) => {
1207
+ const cssValue = typeof value === "object" && value !== null && "name" in value ? `var(${value.name})` : value;
1208
+ return `${indent}${this.toKebabCase(prop)}: ${cssValue};`;
1209
+ }).join("\n");
1210
+ }
1211
+ renderRule(rule, indent = "") {
1212
+ let css = `${indent}${rule.selector} {
1213
+ ${this.stylesToString(rule.styles, indent + " ")}
1214
+ `;
1215
+ if (rule.nested && rule.nested.length > 0) {
1216
+ for (const nestedRule of rule.nested) {
1217
+ const nestedSelector = nestedRule.selector.startsWith("&") ? nestedRule.selector.replace(/&/g, rule.selector) : `${rule.selector} ${nestedRule.selector}`;
1218
+ css += `
1219
+ ${indent}${nestedSelector} {
1220
+ ${this.stylesToString(nestedRule.styles, indent + " ")}
1221
+ ${indent}}
1222
+ `;
1223
+ }
1224
+ }
1225
+ css += `${indent}}`;
1226
+ return css;
1227
+ }
1228
+ renderMediaRule(media) {
1229
+ const condition = media.type && media.condition ? `${media.type} and (${media.condition})` : media.type ? media.type : `(${media.condition})`;
1230
+ return `@media ${condition} {
1231
+ ${this.renderRulesWithIndent(media.rules)}
1232
+ }`;
1233
+ }
1234
+ renderKeyframes(kf) {
1235
+ let css = `@keyframes ${kf.name} {
1236
+ `;
1237
+ for (const step of kf.steps) {
1238
+ css += ` ${step.step} {
1239
+ ${this.stylesToString(step.styles, " ")}
1240
+ }
1241
+ `;
1242
+ }
1243
+ css += "}";
1244
+ return css;
1245
+ }
1246
+ renderFontFace(ff) {
1247
+ let css = "@font-face {\n";
1248
+ css += ` font-family: "${ff.fontFamily}";
1249
+ `;
1250
+ css += ` src: ${ff.src};
1251
+ `;
1252
+ if (ff.fontWeight) css += ` font-weight: ${ff.fontWeight};
1253
+ `;
1254
+ if (ff.fontStyle) css += ` font-style: ${ff.fontStyle};
1255
+ `;
1256
+ if (ff.fontDisplay) css += ` font-display: ${ff.fontDisplay};
1257
+ `;
1258
+ if (ff.unicodeRange) css += ` unicode-range: ${ff.unicodeRange};
1259
+ `;
1260
+ css += "}";
1261
+ return css;
1262
+ }
1263
+ renderContainerRule(container2) {
1264
+ const nameStr = container2.name ? `${container2.name} ` : "";
1265
+ return `@container ${nameStr}(${container2.condition}) {
1266
+ ${this.renderRulesWithIndent(container2.rules)}
1267
+ }`;
1268
+ }
1269
+ renderSupportsRule(supports) {
1270
+ return `@supports (${supports.condition}) {
1271
+ ${this.renderRulesWithIndent(supports.rules)}
1272
+ }`;
1273
+ }
1274
+ renderLayerRule(layer2) {
1275
+ return `@layer ${layer2.name} {
1276
+ ${this.renderRulesWithIndent(layer2.rules)}
1277
+ }`;
1278
+ }
1279
+ // Render Output
1280
+ render(...additionalRules) {
1281
+ const parts = [];
1282
+ if (this.imports.length > 0) {
1283
+ parts.push(this.imports.join("\n"));
1284
+ }
1285
+ if (this._layerOrder.length > 0) {
1286
+ parts.push(`@layer ${this._layerOrder.join(", ")};`);
1287
+ }
1288
+ if (this.variables.length > 0) {
1289
+ const varDeclarations = this.variables.map((v) => ` ${v.name}: ${v.value};`).join("\n");
1290
+ parts.push(`:root {
1291
+ ${varDeclarations}
1292
+ }`);
1293
+ }
1294
+ for (const ff of this.fontFaces) {
1295
+ parts.push(this.renderFontFace(ff));
1296
+ }
1297
+ for (const kf of this.keyframes) {
1298
+ parts.push(this.renderKeyframes(kf));
1299
+ }
1300
+ const allRules = [...this.rules];
1301
+ const allMediaRules = [...this.mediaRules];
1302
+ const allKeyframes = [];
1303
+ const allContainerRules = [...this.containerRules];
1304
+ const allSupportsRules = [...this.supportsRules];
1305
+ const allLayerRules = [...this.layerRules];
1306
+ for (const item of additionalRules) {
1307
+ if (!item) continue;
1308
+ if (Array.isArray(item)) {
1309
+ allRules.push(...item);
1310
+ } else if ("condition" in item && "rules" in item && !("name" in item && "steps" in item)) {
1311
+ if ("type" in item) {
1312
+ allMediaRules.push(item);
1313
+ } else if ("name" in item && typeof item.name === "string") {
1314
+ allContainerRules.push(item);
1315
+ } else {
1316
+ allSupportsRules.push(item);
1317
+ }
1318
+ } else if ("name" in item && "steps" in item) {
1319
+ allKeyframes.push(item);
1320
+ } else if ("name" in item && "rules" in item) {
1321
+ allLayerRules.push(item);
1322
+ } else {
1323
+ allRules.push(item);
1324
+ }
1325
+ }
1326
+ for (const kf of allKeyframes) {
1327
+ parts.push(this.renderKeyframes(kf));
1328
+ }
1329
+ for (const layer2 of allLayerRules) {
1330
+ parts.push(this.renderLayerRule(layer2));
1331
+ }
1332
+ for (const rule of allRules) {
1333
+ parts.push(this.renderRule(rule));
1334
+ }
1335
+ for (const supports of allSupportsRules) {
1336
+ parts.push(this.renderSupportsRule(supports));
1337
+ }
1338
+ for (const container2 of allContainerRules) {
1339
+ parts.push(this.renderContainerRule(container2));
1340
+ }
1341
+ for (const media of allMediaRules) {
1342
+ parts.push(this.renderMediaRule(media));
1343
+ }
1344
+ return parts.join("\n\n");
1345
+ }
1346
+ inject(styleId) {
1347
+ const css = this.render();
1348
+ const style2 = document.createElement("style");
1349
+ if (styleId) style2.id = styleId;
1350
+ style2.textContent = css;
1351
+ document.head.appendChild(style2);
1352
+ return style2;
1353
+ }
1354
+ clear() {
1355
+ this.variables = [];
1356
+ this.rules = [];
1357
+ this.mediaRules = [];
1358
+ this.keyframes = [];
1359
+ this.fontFaces = [];
1360
+ this.imports = [];
1361
+ this.containerRules = [];
1362
+ this.supportsRules = [];
1363
+ this.layerRules = [];
1364
+ this._layerOrder = [];
1365
+ }
1366
+ };
1367
+ var styles = new CreateStyle();
1368
+ var {
1369
+ addVar,
1370
+ var: getVar,
1371
+ addTag,
1372
+ addClass,
1373
+ addId,
1374
+ addPseudoClass,
1375
+ addPseudoElement,
1376
+ addAttribute,
1377
+ attrEquals,
1378
+ attrContainsWord,
1379
+ attrStartsWith,
1380
+ attrEndsWith,
1381
+ attrContains,
1382
+ descendant,
1383
+ child: childStyle,
1384
+ adjacentSibling,
1385
+ generalSibling,
1386
+ multiple: multipleStyle,
1387
+ addName,
1388
+ nesting,
1389
+ keyframe,
1390
+ keyframeFromTo,
1391
+ fontFace,
1392
+ import: importStyle,
1393
+ media: mediaStyle,
1394
+ mediaScreen,
1395
+ mediaPrint,
1396
+ mediaMinWidth,
1397
+ mediaMaxWidth,
1398
+ mediaDark,
1399
+ mediaLight,
1400
+ mediaReducedMotion,
1401
+ container,
1402
+ addContainer,
1403
+ supports: supportsStyle,
1404
+ layerOrder,
1405
+ layer,
1406
+ add: addStyle,
1407
+ important,
1408
+ render: renderStyle,
1409
+ inject: injectStyle,
1410
+ clear: clearStyle
1411
+ } = styles;
1412
+
1413
+ // src/el.ts
1414
+ var hasDocument = typeof document !== "undefined";
1415
+ function capitalize(str) {
1416
+ return str.charAt(0).toUpperCase() + str.slice(1);
1417
+ }
1418
+ function bindDocMethod(method) {
1419
+ return hasDocument && method ? method.bind(doc) : void 0;
1420
+ }
1421
+ function createPrefixedFactories(tags2, prefix, elements2) {
1422
+ tags2.forEach((tag) => {
1423
+ const name = prefix + capitalize(tag);
1424
+ elements2[name] = createElementFactory(tag);
1425
+ });
1426
+ }
1427
+ var createElementFactory = (tag) => {
1428
+ return function(props, ...rest) {
1429
+ if (!arguments.length) return { tagName: tag, props: {}, children: [] };
1430
+ const isState = props && typeof props === "object" && "value" in props && "subscribe" in props;
1431
+ const isVNode = props && typeof props === "object" && "tagName" in props;
1432
+ const isChild = typeof props !== "object" || Array.isArray(props) || props === null || isState || isVNode;
1433
+ const actualProps = isChild ? {} : props;
1434
+ const args = isChild ? [props, ...rest] : rest;
1435
+ if (!args.length) return { tagName: tag, props: actualProps, children: [] };
1436
+ const flatChildren = [];
1437
+ for (let i2 = 0, len = args.length; i2 < len; i2++) {
1438
+ const child = args[i2];
1439
+ if (child == null || child === false) continue;
1440
+ if (Array.isArray(child)) {
1441
+ for (let j = 0, cLen = child.length; j < cLen; j++) {
1442
+ const c = child[j];
1443
+ c != null && c !== false && flatChildren.push(c);
1444
+ }
1445
+ } else {
1446
+ flatChildren.push(child);
1447
+ }
1448
+ }
1449
+ return { tagName: tag, props: actualProps, children: flatChildren };
1450
+ };
1451
+ };
1452
+ var tags = [
1453
+ "html",
1454
+ "head",
1455
+ "body",
1456
+ "title",
1457
+ "base",
1458
+ "link",
1459
+ "meta",
1460
+ "style",
1461
+ "address",
1462
+ "article",
1463
+ "aside",
1464
+ "footer",
1465
+ "header",
1466
+ "h1",
1467
+ "h2",
1468
+ "h3",
1469
+ "h4",
1470
+ "h5",
1471
+ "h6",
1472
+ "main",
1473
+ "nav",
1474
+ "section",
1475
+ "blockquote",
1476
+ "dd",
1477
+ "div",
1478
+ "dl",
1479
+ "dt",
1480
+ "figcaption",
1481
+ "figure",
1482
+ "hr",
1483
+ "li",
1484
+ "ol",
1485
+ "p",
1486
+ "pre",
1487
+ "ul",
1488
+ "a",
1489
+ "abbr",
1490
+ "b",
1491
+ "bdi",
1492
+ "bdo",
1493
+ "br",
1494
+ "cite",
1495
+ "code",
1496
+ "data",
1497
+ "dfn",
1498
+ "em",
1499
+ "i",
1500
+ "kbd",
1501
+ "mark",
1502
+ "q",
1503
+ "rp",
1504
+ "rt",
1505
+ "ruby",
1506
+ "s",
1507
+ "samp",
1508
+ "small",
1509
+ "span",
1510
+ "strong",
1511
+ "sub",
1512
+ "sup",
1513
+ "time",
1514
+ "u",
1515
+ "wbr",
1516
+ "area",
1517
+ "audio",
1518
+ "img",
1519
+ "map",
1520
+ "track",
1521
+ "video",
1522
+ "embed",
1523
+ "iframe",
1524
+ "object",
1525
+ "param",
1526
+ "picture",
1527
+ "portal",
1528
+ "source",
1529
+ "canvas",
1530
+ "noscript",
1531
+ "script",
1532
+ "del",
1533
+ "ins",
1534
+ "caption",
1535
+ "col",
1536
+ "colgroup",
1537
+ "table",
1538
+ "tbody",
1539
+ "td",
1540
+ "tfoot",
1541
+ "th",
1542
+ "thead",
1543
+ "tr",
1544
+ "button",
1545
+ "datalist",
1546
+ "fieldset",
1547
+ "form",
1548
+ "input",
1549
+ "label",
1550
+ "legend",
1551
+ "meter",
1552
+ "optgroup",
1553
+ "option",
1554
+ "output",
1555
+ "progress",
1556
+ "select",
1557
+ "textarea",
1558
+ "details",
1559
+ "dialog",
1560
+ "menu",
1561
+ "summary",
1562
+ "slot",
1563
+ "template"
1564
+ ];
1565
+ var svgTags = [
1566
+ "svg",
1567
+ "circle",
1568
+ "rect",
1569
+ "path",
1570
+ "line",
1571
+ "polyline",
1572
+ "polygon",
1573
+ "ellipse",
1574
+ "g",
1575
+ "text",
1576
+ "tspan",
1577
+ "defs",
1578
+ "linearGradient",
1579
+ "radialGradient",
1580
+ "stop",
1581
+ "pattern",
1582
+ "mask",
1583
+ "clipPath",
1584
+ "use",
1585
+ "symbol",
1586
+ "marker",
1587
+ "image",
1588
+ "foreignObject",
1589
+ "animate",
1590
+ "animateTransform",
1591
+ "animateMotion",
1592
+ "set",
1593
+ "filter",
1594
+ "feBlend",
1595
+ "feColorMatrix",
1596
+ "feComponentTransfer",
1597
+ "feComposite",
1598
+ "feConvolveMatrix",
1599
+ "feDiffuseLighting",
1600
+ "feDisplacementMap",
1601
+ "feFlood",
1602
+ "feGaussianBlur",
1603
+ "feMorphology",
1604
+ "feOffset",
1605
+ "feSpecularLighting",
1606
+ "feTile",
1607
+ "feTurbulence"
1608
+ ];
1609
+ var mathTags = [
1610
+ "math",
1611
+ "mi",
1612
+ "mn",
1613
+ "mo",
1614
+ "ms",
1615
+ "mtext",
1616
+ "mrow",
1617
+ "mfrac",
1618
+ "msqrt",
1619
+ "mroot",
1620
+ "msub",
1621
+ "msup"
1622
+ ];
1623
+ var elements = {};
1624
+ tags.forEach((tag) => {
1625
+ elements[tag] = createElementFactory(tag);
1626
+ });
1627
+ createPrefixedFactories(svgTags, "svg", elements);
1628
+ createPrefixedFactories(mathTags, "math", elements);
1629
+ elements.varElement = createElementFactory("var");
1630
+ var {
1631
+ html,
1632
+ head,
1633
+ body,
1634
+ title,
1635
+ base,
1636
+ link,
1637
+ meta,
1638
+ style,
1639
+ address,
1640
+ article,
1641
+ aside,
1642
+ footer,
1643
+ header,
1644
+ h1,
1645
+ h2,
1646
+ h3,
1647
+ h4,
1648
+ h5,
1649
+ h6,
1650
+ main,
1651
+ nav,
1652
+ section,
1653
+ blockquote,
1654
+ dd,
1655
+ div,
1656
+ dl,
1657
+ dt,
1658
+ figcaption,
1659
+ figure,
1660
+ hr,
1661
+ li,
1662
+ ol,
1663
+ p,
1664
+ pre,
1665
+ ul,
1666
+ a,
1667
+ abbr,
1668
+ b,
1669
+ bdi,
1670
+ bdo,
1671
+ br,
1672
+ cite,
1673
+ code,
1674
+ data,
1675
+ dfn,
1676
+ em,
1677
+ i,
1678
+ kbd,
1679
+ mark,
1680
+ q,
1681
+ rp,
1682
+ rt,
1683
+ ruby,
1684
+ s,
1685
+ samp,
1686
+ small,
1687
+ span,
1688
+ strong,
1689
+ sub,
1690
+ sup,
1691
+ time,
1692
+ u,
1693
+ wbr,
1694
+ area,
1695
+ audio,
1696
+ img,
1697
+ map,
1698
+ track,
1699
+ video,
1700
+ embed,
1701
+ iframe,
1702
+ object,
1703
+ param,
1704
+ picture,
1705
+ portal,
1706
+ source,
1707
+ canvas,
1708
+ noscript,
1709
+ script,
1710
+ del,
1711
+ ins,
1712
+ caption,
1713
+ col,
1714
+ colgroup,
1715
+ table,
1716
+ tbody,
1717
+ td,
1718
+ tfoot,
1719
+ th,
1720
+ thead,
1721
+ tr,
1722
+ button,
1723
+ datalist,
1724
+ fieldset,
1725
+ form,
1726
+ input,
1727
+ label,
1728
+ legend,
1729
+ meter,
1730
+ optgroup,
1731
+ option,
1732
+ output,
1733
+ progress,
1734
+ select,
1735
+ textarea,
1736
+ details,
1737
+ dialog,
1738
+ menu,
1739
+ summary,
1740
+ slot,
1741
+ template,
1742
+ svgSvg,
1743
+ svgCircle,
1744
+ svgRect,
1745
+ svgPath,
1746
+ svgLine,
1747
+ svgPolyline,
1748
+ svgPolygon,
1749
+ svgEllipse,
1750
+ svgG,
1751
+ svgText,
1752
+ svgTspan,
1753
+ svgDefs,
1754
+ svgLinearGradient,
1755
+ svgRadialGradient,
1756
+ svgStop,
1757
+ svgPattern,
1758
+ svgMask,
1759
+ svgClipPath,
1760
+ svgUse,
1761
+ svgSymbol,
1762
+ svgMarker,
1763
+ svgImage,
1764
+ svgForeignObject,
1765
+ svgAnimate,
1766
+ svgAnimateTransform,
1767
+ svgAnimateMotion,
1768
+ svgSet,
1769
+ svgFilter,
1770
+ svgFeBlend,
1771
+ svgFeColorMatrix,
1772
+ svgFeComponentTransfer,
1773
+ svgFeComposite,
1774
+ svgFeConvolveMatrix,
1775
+ svgFeDiffuseLighting,
1776
+ svgFeDisplacementMap,
1777
+ svgFeFlood,
1778
+ svgFeGaussianBlur,
1779
+ svgFeMorphology,
1780
+ svgFeOffset,
1781
+ svgFeSpecularLighting,
1782
+ svgFeTile,
1783
+ svgFeTurbulence,
1784
+ mathMath,
1785
+ mathMi,
1786
+ mathMn,
1787
+ mathMo,
1788
+ mathMs,
1789
+ mathMtext,
1790
+ mathMrow,
1791
+ mathMfrac,
1792
+ mathMsqrt,
1793
+ mathMroot,
1794
+ mathMsub,
1795
+ mathMsup,
1796
+ varElement
1797
+ } = elements;
1798
+ var el = elements;
1799
+ var doc = hasDocument ? document : void 0;
1800
+ var getEl = bindDocMethod(doc?.querySelector);
1801
+ var getEls = bindDocMethod(doc?.querySelectorAll);
1802
+ var createEl = bindDocMethod(doc?.createElement);
1803
+ var createSvgEl = hasDocument ? doc.createElementNS.bind(doc, "http://www.w3.org/2000/svg") : void 0;
1804
+ var createMathEl = hasDocument ? doc.createElementNS.bind(doc, "http://www.w3.org/1998/Math/MathML") : void 0;
1805
+ var fragment = bindDocMethod(doc?.createDocumentFragment);
1806
+ var textNode = bindDocMethod(doc?.createTextNode);
1807
+ var commentNode = bindDocMethod(doc?.createComment);
1808
+ var getElId = bindDocMethod(doc?.getElementById);
1809
+ var getElClass = bindDocMethod(doc?.getElementsByClassName);
1810
+ var getElTag = bindDocMethod(doc?.getElementsByTagName);
1811
+ var getElName = bindDocMethod(doc?.getElementsByName);
1812
+
1813
+ // src/router.ts
1814
+ function matchRoute(pattern, path) {
1815
+ const patternParts = pattern.split("/").filter(Boolean);
1816
+ const pathParts = path.split("/").filter(Boolean);
1817
+ if (pattern.endsWith("*")) {
1818
+ const basePattern = pattern.slice(0, -1);
1819
+ if (path.startsWith(basePattern) || basePattern === "/" || pattern === "*") {
1820
+ return { "*": path.slice(basePattern.length) };
1821
+ }
1822
+ }
1823
+ if (patternParts.length !== pathParts.length) return null;
1824
+ const params = {};
1825
+ for (let i2 = 0; i2 < patternParts.length; i2++) {
1826
+ const patternPart = patternParts[i2];
1827
+ const pathPart = pathParts[i2];
1828
+ if (patternPart.startsWith(":")) {
1829
+ params[patternPart.slice(1)] = decodeURIComponent(pathPart);
1830
+ } else if (patternPart !== pathPart) {
1831
+ return null;
1832
+ }
1833
+ }
1834
+ return params;
1835
+ }
1836
+ function executeGuard(guard, to, from, navigate, replace = false) {
1837
+ const result = guard(to, from);
1838
+ if (result === false) return false;
1839
+ if (typeof result === "string") {
1840
+ navigate(result, replace);
1841
+ return false;
1842
+ }
1843
+ return true;
1844
+ }
1845
+ function wrapComponent(component) {
1846
+ if (typeof component === "object" && component !== null && "tagName" in component) {
1847
+ return component;
1848
+ }
1849
+ return { tagName: "span", props: {}, children: [component] };
1850
+ }
1851
+ function createRouter(options) {
1852
+ const { mode = "history", base: base2 = "", routes } = options;
1853
+ const globalGuards = [];
1854
+ const parseQuery = (search) => {
1855
+ const query = {};
1856
+ const params = new URLSearchParams(search);
1857
+ params.forEach((value, key) => {
1858
+ query[key] = value;
1859
+ });
1860
+ return query;
1861
+ };
1862
+ const getCurrentPath = () => {
1863
+ if (mode === "hash") {
1864
+ return window.location.hash.slice(1) || "/";
1865
+ }
1866
+ return window.location.pathname.replace(base2, "") || "/";
1867
+ };
1868
+ const parseLocation = (path) => {
1869
+ const [pathPart, queryPart = ""] = path.split("?");
1870
+ const [cleanPath, hash = ""] = pathPart.split("#");
1871
+ return {
1872
+ path: cleanPath || "/",
1873
+ params: {},
1874
+ query: parseQuery(queryPart),
1875
+ hash: hash ? "#" + hash : ""
1876
+ };
1877
+ };
1878
+ const findRoute = (path) => {
1879
+ for (const route of routes) {
1880
+ const params = matchRoute(route.path, path);
1881
+ if (params !== null) {
1882
+ return { route, params };
1883
+ }
1884
+ }
1885
+ return null;
1886
+ };
1887
+ const currentRoute = dom.createState(parseLocation(getCurrentPath()));
1888
+ const navigate = (path, replace = false) => {
1889
+ const location2 = parseLocation(path);
1890
+ const match = findRoute(location2.path);
1891
+ if (match) {
1892
+ location2.params = match.params;
1893
+ }
1894
+ for (const guard of globalGuards) {
1895
+ if (!executeGuard(guard, location2, currentRoute.value, navigate, replace)) return;
1896
+ }
1897
+ if (match?.route.beforeEnter) {
1898
+ if (!executeGuard(match.route.beforeEnter, location2, currentRoute.value, navigate, replace)) return;
1899
+ }
1900
+ const url = mode === "hash" ? "#" + path : base2 + path;
1901
+ if (replace) {
1902
+ window.history.replaceState({ path }, "", url);
1903
+ } else {
1904
+ window.history.pushState({ path }, "", url);
1905
+ }
1906
+ currentRoute.value = location2;
1907
+ };
1908
+ const handlePopState = () => {
1909
+ const path = getCurrentPath();
1910
+ const location2 = parseLocation(path);
1911
+ const match = findRoute(location2.path);
1912
+ if (match) {
1913
+ location2.params = match.params;
1914
+ }
1915
+ currentRoute.value = location2;
1916
+ };
1917
+ if (typeof window !== "undefined") {
1918
+ window.addEventListener("popstate", handlePopState);
1919
+ }
1920
+ return {
1921
+ currentRoute,
1922
+ push: (path) => navigate(path, false),
1923
+ replace: (path) => navigate(path, true),
1924
+ back: () => window.history.back(),
1925
+ forward: () => window.history.forward(),
1926
+ go: (delta) => window.history.go(delta),
1927
+ beforeEach: (guard) => {
1928
+ globalGuards.push(guard);
1929
+ },
1930
+ destroy: () => {
1931
+ if (typeof window !== "undefined") {
1932
+ window.removeEventListener("popstate", handlePopState);
1933
+ }
1934
+ currentRoute.destroy();
1935
+ }
1936
+ };
1937
+ }
1938
+ function createRouterView(router, options) {
1939
+ const { routes, notFound } = options;
1940
+ return () => {
1941
+ const location2 = router.currentRoute.value;
1942
+ const match = routes.find((r) => matchRoute(r.path, location2.path) !== null);
1943
+ if (match) {
1944
+ const params = matchRoute(match.path, location2.path) || {};
1945
+ const component = match.component({ ...params, ...location2.query });
1946
+ return wrapComponent(component);
1947
+ }
1948
+ if (notFound) {
1949
+ const component = notFound(location2.params);
1950
+ return wrapComponent(component);
1951
+ }
1952
+ return { tagName: "div", props: {}, children: ["404 - Not Found"] };
1953
+ };
1954
+ }
1955
+ var routerLink = (router, props, ...children) => {
1956
+ return {
1957
+ tagName: "a",
1958
+ props: {
1959
+ ...props,
1960
+ href: props.to,
1961
+ onclick: (e) => {
1962
+ e.preventDefault();
1963
+ router.push(props.to);
1964
+ }
1965
+ },
1966
+ children
1967
+ };
1968
+ };
1969
+
1970
+ // src/hmr.ts
1971
+ var ElitHMR = class {
1972
+ constructor() {
1973
+ this.enabled = false;
1974
+ this.ws = null;
1975
+ this.acceptCallbacks = [];
1976
+ this.disposeCallbacks = [];
1977
+ this.declined = false;
1978
+ if (typeof window === "undefined") {
1979
+ return;
1980
+ }
1981
+ this.connect();
1982
+ }
1983
+ connect() {
1984
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
1985
+ const host = window.location.hostname;
1986
+ const port = window.location.port || "3000";
1987
+ this.ws = new WebSocket(`${protocol}//${host}:${port}`);
1988
+ this.ws.onopen = () => {
1989
+ this.enabled = true;
1990
+ console.log("[Elit HMR] Connected \u2713");
1991
+ };
1992
+ this.ws.onmessage = (event) => {
1993
+ try {
1994
+ const data2 = JSON.parse(event.data);
1995
+ this.handleMessage(data2);
1996
+ } catch (error) {
1997
+ console.error("[Elit HMR] Error parsing message:", error);
1998
+ }
1999
+ };
2000
+ this.ws.onclose = () => {
2001
+ this.enabled = false;
2002
+ console.log("[Elit HMR] Disconnected - Attempting reconnect...");
2003
+ setTimeout(() => this.reload(), 1e3);
2004
+ };
2005
+ this.ws.onerror = (error) => {
2006
+ console.error("[Elit HMR] WebSocket error:", error);
2007
+ };
2008
+ }
2009
+ handleMessage(data2) {
2010
+ switch (data2.type) {
2011
+ case "connected":
2012
+ console.log("[Elit HMR] Ready");
2013
+ break;
2014
+ case "update":
2015
+ console.log(`[Elit HMR] Update detected: ${data2.path}`);
2016
+ if (this.declined) {
2017
+ this.reload();
2018
+ return;
2019
+ }
2020
+ this.disposeCallbacks.forEach((cb) => cb());
2021
+ this.disposeCallbacks = [];
2022
+ if (this.acceptCallbacks.length > 0) {
2023
+ this.acceptCallbacks.forEach((cb) => cb());
2024
+ } else {
2025
+ this.reload();
2026
+ }
2027
+ break;
2028
+ case "reload":
2029
+ console.log("[Elit HMR] Full reload requested");
2030
+ this.reload();
2031
+ break;
2032
+ case "error":
2033
+ console.error("[Elit HMR] Server error:", data2.error);
2034
+ break;
2035
+ }
2036
+ }
2037
+ reload() {
2038
+ window.location.reload();
2039
+ }
2040
+ accept(callback) {
2041
+ if (callback) {
2042
+ this.acceptCallbacks.push(callback);
2043
+ }
2044
+ this.declined = false;
2045
+ }
2046
+ decline() {
2047
+ this.declined = true;
2048
+ }
2049
+ dispose(callback) {
2050
+ this.disposeCallbacks.push(callback);
2051
+ }
2052
+ };
2053
+ var hmr = new ElitHMR();
2054
+ if (typeof window !== "undefined") {
2055
+ window.__ELIT_HMR__ = hmr;
2056
+ }
2057
+ var hmr_default = hmr;
2058
+ export {
2059
+ CreateStyle,
2060
+ DomNode,
2061
+ SharedState,
2062
+ a,
2063
+ abbr,
2064
+ addAttribute,
2065
+ addClass,
2066
+ addContainer,
2067
+ addId,
2068
+ addName,
2069
+ addPseudoClass,
2070
+ addPseudoElement,
2071
+ addStyle,
2072
+ addTag,
2073
+ addVar,
2074
+ address,
2075
+ adjacentSibling,
2076
+ area,
2077
+ article,
2078
+ aside,
2079
+ attrContains,
2080
+ attrContainsWord,
2081
+ attrEndsWith,
2082
+ attrEquals,
2083
+ attrStartsWith,
2084
+ audio,
2085
+ b,
2086
+ base,
2087
+ batchRender,
2088
+ bdi,
2089
+ bdo,
2090
+ bindChecked,
2091
+ bindValue,
2092
+ blockquote,
2093
+ body,
2094
+ br,
2095
+ button,
2096
+ canvas,
2097
+ caption,
2098
+ childStyle,
2099
+ cite,
2100
+ cleanupUnused,
2101
+ clearStyle,
2102
+ code,
2103
+ col,
2104
+ colgroup,
2105
+ commentNode,
2106
+ computed,
2107
+ container,
2108
+ createEl,
2109
+ createElementFactory,
2110
+ createMathEl,
2111
+ createRouter,
2112
+ createRouterView,
2113
+ createSharedState,
2114
+ createState,
2115
+ createSvgEl,
2116
+ createVirtualList,
2117
+ data,
2118
+ datalist,
2119
+ dd,
2120
+ debounce,
2121
+ del,
2122
+ descendant,
2123
+ details,
2124
+ dfn,
2125
+ dialog,
2126
+ div,
2127
+ dl,
2128
+ doc,
2129
+ dom,
2130
+ dt,
2131
+ effect,
2132
+ el,
2133
+ elements,
2134
+ em,
2135
+ embed,
2136
+ fieldset,
2137
+ figcaption,
2138
+ figure,
2139
+ fontFace,
2140
+ footer,
2141
+ form,
2142
+ fragment,
2143
+ generalSibling,
2144
+ getEl,
2145
+ getElClass,
2146
+ getElId,
2147
+ getElName,
2148
+ getElTag,
2149
+ getEls,
2150
+ getVar,
2151
+ h1,
2152
+ h2,
2153
+ h3,
2154
+ h4,
2155
+ h5,
2156
+ h6,
2157
+ head,
2158
+ header,
2159
+ hmr_default as hmr,
2160
+ hr,
2161
+ html,
2162
+ i,
2163
+ iframe,
2164
+ img,
2165
+ importStyle,
2166
+ important,
2167
+ injectStyle,
2168
+ input,
2169
+ ins,
2170
+ kbd,
2171
+ keyframe,
2172
+ keyframeFromTo,
2173
+ label,
2174
+ layer,
2175
+ layerOrder,
2176
+ lazy,
2177
+ legend,
2178
+ li,
2179
+ link,
2180
+ main,
2181
+ map,
2182
+ mark,
2183
+ mathMath,
2184
+ mathMfrac,
2185
+ mathMi,
2186
+ mathMn,
2187
+ mathMo,
2188
+ mathMroot,
2189
+ mathMrow,
2190
+ mathMs,
2191
+ mathMsqrt,
2192
+ mathMsub,
2193
+ mathMsup,
2194
+ mathMtext,
2195
+ mediaDark,
2196
+ mediaLight,
2197
+ mediaMaxWidth,
2198
+ mediaMinWidth,
2199
+ mediaPrint,
2200
+ mediaReducedMotion,
2201
+ mediaScreen,
2202
+ mediaStyle,
2203
+ menu,
2204
+ meta,
2205
+ meter,
2206
+ mount,
2207
+ multipleStyle,
2208
+ nav,
2209
+ nesting,
2210
+ noscript,
2211
+ object,
2212
+ ol,
2213
+ optgroup,
2214
+ option,
2215
+ output,
2216
+ p,
2217
+ param,
2218
+ picture,
2219
+ portal,
2220
+ pre,
2221
+ progress,
2222
+ q,
2223
+ reactive,
2224
+ reactiveAs,
2225
+ render,
2226
+ renderChunked,
2227
+ renderStyle,
2228
+ renderToString,
2229
+ routerLink,
2230
+ rp,
2231
+ rt,
2232
+ ruby,
2233
+ s,
2234
+ samp,
2235
+ script,
2236
+ section,
2237
+ select,
2238
+ sharedStateManager,
2239
+ slot,
2240
+ small,
2241
+ source,
2242
+ span,
2243
+ strong,
2244
+ style,
2245
+ styles,
2246
+ sub,
2247
+ summary,
2248
+ sup,
2249
+ supportsStyle,
2250
+ svgAnimate,
2251
+ svgAnimateMotion,
2252
+ svgAnimateTransform,
2253
+ svgCircle,
2254
+ svgClipPath,
2255
+ svgDefs,
2256
+ svgEllipse,
2257
+ svgFeBlend,
2258
+ svgFeColorMatrix,
2259
+ svgFeComponentTransfer,
2260
+ svgFeComposite,
2261
+ svgFeConvolveMatrix,
2262
+ svgFeDiffuseLighting,
2263
+ svgFeDisplacementMap,
2264
+ svgFeFlood,
2265
+ svgFeGaussianBlur,
2266
+ svgFeMorphology,
2267
+ svgFeOffset,
2268
+ svgFeSpecularLighting,
2269
+ svgFeTile,
2270
+ svgFeTurbulence,
2271
+ svgFilter,
2272
+ svgForeignObject,
2273
+ svgG,
2274
+ svgImage,
2275
+ svgLine,
2276
+ svgLinearGradient,
2277
+ svgMarker,
2278
+ svgMask,
2279
+ svgPath,
2280
+ svgPattern,
2281
+ svgPolygon,
2282
+ svgPolyline,
2283
+ svgRadialGradient,
2284
+ svgRect,
2285
+ svgSet,
2286
+ svgStop,
2287
+ svgSvg,
2288
+ svgSymbol,
2289
+ svgText,
2290
+ svgTspan,
2291
+ svgUse,
2292
+ table,
2293
+ tbody,
2294
+ td,
2295
+ template,
2296
+ text,
2297
+ textNode,
2298
+ textarea,
2299
+ tfoot,
2300
+ th,
2301
+ thead,
2302
+ throttle,
2303
+ time,
2304
+ title,
2305
+ tr,
2306
+ track,
2307
+ u,
2308
+ ul,
2309
+ varElement,
2310
+ video,
2311
+ wbr
2312
+ };