elit 1.1.0 → 2.0.0

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 (50) hide show
  1. package/README.md +267 -101
  2. package/dist/build.d.mts +11 -0
  3. package/dist/build.d.ts +11 -0
  4. package/dist/build.js +1 -0
  5. package/dist/build.mjs +1 -0
  6. package/dist/cli.js +2307 -0
  7. package/dist/client.d.mts +9 -0
  8. package/dist/client.d.ts +9 -0
  9. package/dist/client.js +1 -0
  10. package/dist/client.mjs +1 -0
  11. package/dist/dom.d.mts +80 -0
  12. package/dist/dom.d.ts +80 -0
  13. package/dist/dom.js +1 -0
  14. package/dist/dom.mjs +1 -0
  15. package/dist/el.d.mts +227 -0
  16. package/dist/el.d.ts +227 -0
  17. package/dist/el.js +1 -0
  18. package/dist/el.mjs +1 -0
  19. package/dist/hmr.d.mts +38 -0
  20. package/dist/hmr.d.ts +38 -0
  21. package/dist/hmr.js +1 -0
  22. package/dist/hmr.mjs +1 -0
  23. package/dist/index.d.mts +38 -619
  24. package/dist/index.d.ts +38 -619
  25. package/dist/index.js +1 -35
  26. package/dist/index.mjs +1 -35
  27. package/dist/router.d.mts +45 -0
  28. package/dist/router.d.ts +45 -0
  29. package/dist/router.js +1 -0
  30. package/dist/router.mjs +1 -0
  31. package/dist/server.d.mts +3 -0
  32. package/dist/server.d.ts +3 -0
  33. package/dist/server.js +1 -0
  34. package/dist/server.mjs +1 -0
  35. package/dist/state.d.mts +109 -0
  36. package/dist/state.d.ts +109 -0
  37. package/dist/state.js +1 -0
  38. package/dist/state.mjs +1 -0
  39. package/dist/style.d.mts +113 -0
  40. package/dist/style.d.ts +113 -0
  41. package/dist/style.js +1 -0
  42. package/dist/style.mjs +1 -0
  43. package/dist/types-DOAdFFJB.d.mts +330 -0
  44. package/dist/types-DOAdFFJB.d.ts +330 -0
  45. package/dist/types.d.mts +3 -0
  46. package/dist/types.d.ts +3 -0
  47. package/dist/types.js +1 -0
  48. package/dist/types.mjs +0 -0
  49. package/package.json +65 -2
  50. package/dist/index.global.js +0 -35
@@ -0,0 +1,45 @@
1
+ import { V as VNode, C as Child, w as State, P as Props } from './types-DOAdFFJB.mjs';
2
+ import 'http';
3
+ import 'ws';
4
+
5
+ /**
6
+ * Elit - Router - Client-side routing
7
+ */
8
+
9
+ interface Route {
10
+ path: string;
11
+ component: (params: RouteParams) => VNode | Child;
12
+ beforeEnter?: (to: RouteLocation, from: RouteLocation | null) => boolean | string | void;
13
+ }
14
+ interface RouteParams {
15
+ [key: string]: string;
16
+ }
17
+ interface RouteLocation {
18
+ path: string;
19
+ params: RouteParams;
20
+ query: Record<string, string>;
21
+ hash: string;
22
+ }
23
+ interface RouterOptions {
24
+ mode?: 'history' | 'hash';
25
+ base?: string;
26
+ routes: Route[];
27
+ notFound?: (params: RouteParams) => VNode | Child;
28
+ }
29
+ interface Router {
30
+ currentRoute: State<RouteLocation>;
31
+ push: (path: string) => void;
32
+ replace: (path: string) => void;
33
+ back: () => void;
34
+ forward: () => void;
35
+ go: (delta: number) => void;
36
+ beforeEach: (guard: (to: RouteLocation, from: RouteLocation | null) => boolean | string | void) => void;
37
+ destroy: () => void;
38
+ }
39
+ declare function createRouter(options: RouterOptions): Router;
40
+ declare function createRouterView(router: Router, options: RouterOptions): () => VNode;
41
+ declare const routerLink: (router: Router, props: Props & {
42
+ to: string;
43
+ }, ...children: Child[]) => VNode;
44
+
45
+ export { type Route, type RouteLocation, type RouteParams, type Router, type RouterOptions, createRouter, createRouterView, routerLink };
@@ -0,0 +1,45 @@
1
+ import { V as VNode, C as Child, w as State, P as Props } from './types-DOAdFFJB.js';
2
+ import 'http';
3
+ import 'ws';
4
+
5
+ /**
6
+ * Elit - Router - Client-side routing
7
+ */
8
+
9
+ interface Route {
10
+ path: string;
11
+ component: (params: RouteParams) => VNode | Child;
12
+ beforeEnter?: (to: RouteLocation, from: RouteLocation | null) => boolean | string | void;
13
+ }
14
+ interface RouteParams {
15
+ [key: string]: string;
16
+ }
17
+ interface RouteLocation {
18
+ path: string;
19
+ params: RouteParams;
20
+ query: Record<string, string>;
21
+ hash: string;
22
+ }
23
+ interface RouterOptions {
24
+ mode?: 'history' | 'hash';
25
+ base?: string;
26
+ routes: Route[];
27
+ notFound?: (params: RouteParams) => VNode | Child;
28
+ }
29
+ interface Router {
30
+ currentRoute: State<RouteLocation>;
31
+ push: (path: string) => void;
32
+ replace: (path: string) => void;
33
+ back: () => void;
34
+ forward: () => void;
35
+ go: (delta: number) => void;
36
+ beforeEach: (guard: (to: RouteLocation, from: RouteLocation | null) => boolean | string | void) => void;
37
+ destroy: () => void;
38
+ }
39
+ declare function createRouter(options: RouterOptions): Router;
40
+ declare function createRouterView(router: Router, options: RouterOptions): () => VNode;
41
+ declare const routerLink: (router: Router, props: Props & {
42
+ to: string;
43
+ }, ...children: Child[]) => VNode;
44
+
45
+ export { type Route, type RouteLocation, type RouteParams, type Router, type RouterOptions, createRouter, createRouterView, routerLink };
package/dist/router.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=new 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:n,children:i}=e,l="svg"===r||"s"===r[0]&&"v"===r[1]&&"g"===r[2]||"http://www.w3.org/2000/svg"===t.namespaceURI,o=l?document.createElementNS("http://www.w3.org/2000/svg",r.replace("svg","").toLowerCase()||r):document.createElement(r);for(let e in n){let t=n[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;l?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 a=i.length;if(!a)return void t.appendChild(o);let s=e=>{for(let t=0;t<a;t++){let r=i[t];if(null!=r&&!1!==r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;t++){let n=r[t];null!=n&&!1!==n&&this.renderToDOM(n,e)}else this.renderToDOM(r,e)}};if(a>30){let e=document.createDocumentFragment();s(e),o.appendChild(e)}else s(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 n=t.length;if(n>3e3){let e=document.createDocumentFragment(),i=0,l=1500,o=()=>{let a=Math.min(i+l,n);for(let r=i;r<a;r++)this.renderToDOM(t[r],e);i=a,i>=n?r.appendChild(e):requestAnimationFrame(o)};o()}else{let e=document.createDocumentFragment();for(let r=0;r<n;r++)this.renderToDOM(t[r],e);r.appendChild(e)}return r}renderChunked(e,t,r=5e3,n){let i="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!i)throw new Error(`Element not found: ${e}`);let l=t.length,o=0,a=()=>{let e=Math.min(o+r,l),s=document.createDocumentFragment();for(let r=o;r<e;r++)this.renderToDOM(t[r],s);i.appendChild(s),o=e,n&&n(o,l),o<l&&requestAnimationFrame(a)};return requestAnimationFrame(a),i}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,n=new Set,i=null,{throttle:l=0,deep:o=!1}=t,a=()=>n.forEach(e=>e(r));return{get value(){return r},set value(e){(o?JSON.stringify(r)!==JSON.stringify(e):r!==e)&&(r=e,l>0?i||(i=setTimeout(()=>{i=null,a()},l)):a())},subscribe:e=>(n.add(e),()=>n.delete(e)),destroy(){n.clear(),i&&clearTimeout(i)}}}computed(e,t){let r=e.map(e=>e.value),n=this.createState(t(...r));return e.forEach((e,i)=>{e.subscribe(e=>{r[i]=e,n.value=t(...r)})}),n}effect(e){e()}createVirtualList(e,t,r,n=50,i=5){let l=e.clientHeight,o=t.length*n,a=0,s=()=>{let{start:s,end:u}={start:Math.max(0,Math.floor(a/n)-i),end:Math.min(t.length,Math.ceil((a+l)/n)+i)},d=document.createElement("div");d.style.cssText=`height:${o}px;position:relative`;for(let e=s;e<u;e++){let i=document.createElement("div");i.style.cssText=`position:absolute;top:${e*n}px;height:${n}px;width:100%`,this.renderToDOM(r(t[e],e),i),d.appendChild(i)}e.innerHTML="",e.appendChild(d)},u=()=>{a=e.scrollTop,requestAnimationFrame(s)};return e.addEventListener("scroll",u),s(),{render:s,destroy:()=>{e.removeEventListener("scroll",u),e.innerHTML=""}}}lazy(e){let t=null,r=!1;return async(...n)=>(!t&&!r&&(r=!0,t=await e(),r=!1),t?t(...n):{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:n=0}=t,i=r?" ".repeat(n):"",l=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:a,props:s,children:u}=o,d=this.isSelfClosingTag(a),h=`${i}<${a}`,c=this.propsToAttributes(s);if(c&&(h+=` ${c}`),d)return h+=` />${l}`,h;if(h+=">",s.dangerouslySetInnerHTML)return h+=s.dangerouslySetInnerHTML.__html,h+=`</${a}>${l}`,h;if(u&&u.length>0){let e=u.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){h+=l;for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:r,indent:n+1}));else h+=this.renderToString(t,{pretty:r,indent:n+1});h+=i}else for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:!1,indent:0}));else h+=this.renderToString(t,{pretty:!1,indent:0})}return h+=`</${a}>${l}`,h}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,n=e.children&&1===e.children.length&&"string"==typeof e.children[0];if(r&&n)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 n=e[r];if(n=this.resolveStateValue(n),null!=n&&!1!==n&&(!r.startsWith("on")||"function"!=typeof n)){if("className"===r||"class"===r){let e=Array.isArray(n)?n.join(" "):n;e&&t.push(`class="${this.escapeHtml(String(e))}"`);continue}if("style"===r){let e=this.styleToString(n);e&&t.push(`style="${this.escapeHtml(e)}"`);continue}if(!0===n){t.push(r);continue}t.push(`${r}="${this.escapeHtml(String(n))}"`)}}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 n=r.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${n}:${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 n=t(e.value);r.node.textContent=String(n??"")}})}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:n}=e,i={};for(let e in r){let t=r[e];"class"===e?i.className=this.isState(t)?t.value:t:i[e]=this.isState(t)?t.value:t}let l=[];if(null!=n)if(Array.isArray(n))for(let e of n)if(this.isState(e))l.push(this.createReactiveChild(e,e=>e));else{let t=this.jsonToVNode(e);null!=t&&!1!==t&&l.push(t)}else if(this.isState(n))l.push(this.createReactiveChild(n,e=>e));else if("object"==typeof n&&"tag"in n){let e=this.jsonToVNode(n);null!=e&&!1!==e&&l.push(e)}else l.push(n);return{tagName:t,props:i,children:l}}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:n=[]}=e,i={};for(let e in r){let t=r[e];i[e]=this.isState(t)?t.value:t}let l=[];for(let e of n)if(this.isState(e))l.push(this.createReactiveChild(e,e=>e));else{let t=this.vNodeJsonToVNode(e);null!=t&&!1!==t&&l.push(t)}return{tagName:t,props:i,children:l}}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,n=null;for(let e of t.children||[])"object"==typeof e&&null!==e&&"tagName"in e&&("head"===e.tagName&&(r=e),"body"===e.tagName&&(n=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(n){if(document.body.innerHTML="",n.props)for(let e in n.props){let t=n.props[e];null!=t&&!1!==t&&document.body.setAttribute(e,String(t))}for(let e of n.children||[])this.renderToDOM(e,document.body)}}renderToHTMLDocument(e,t={}){let{title:r="",meta:n=[],links:i=[],scripts:l=[],styles:o=[],lang:a="en",head:s="",bodyAttrs:u={},pretty:d=!1}=t,h=d?"\n":"",c=d?" ":"",p=d?" ":"",f=`<!DOCTYPE html>${h}<html lang="${a}">${h}${c}<head>${h}${p}<meta charset="UTF-8">${h}${p}<meta name="viewport" content="width=device-width, initial-scale=1.0">${h}`;r&&(f+=`${p}<title>${this.escapeHtml(r)}</title>${h}`);for(let e of n){f+=`${p}<meta`;for(let t in e)f+=` ${t}="${this.escapeHtml(e[t])}"`;f+=`>${h}`}for(let e of i){f+=`${p}<link`;for(let t in e)f+=` ${t}="${this.escapeHtml(e[t])}"`;f+=`>${h}`}for(let e of o)e.href?f+=`${p}<link rel="stylesheet" href="${this.escapeHtml(e.href)}">${h}`:e.content&&(f+=`${p}<style>${e.content}</style>${h}`);s&&(f+=s+h),f+=`${c}</head>${h}${c}<body`;for(let e in u)f+=` ${e}="${this.escapeHtml(u[e])}"`;f+=`>${h}`,f+=this.renderToString(e,{pretty:d,indent:2});for(let e of l)f+=`${p}<script`,e.type&&(f+=` type="${this.escapeHtml(e.type)}"`),e.async&&(f+=" async"),e.defer&&(f+=" defer"),e.src?f+=` src="${this.escapeHtml(e.src)}"><\/script>${h}`:e.content?f+=`>${e.content}<\/script>${h}`:f+=`><\/script>${h}`;return f+=`${c}</body>${h}</html>`,f}getElementCache(){return this.elementCache}};function t(e,t){let r=e.split("/").filter(Boolean),n=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!==n.length)return null;let i={};for(let e=0;e<r.length;e++){let t=r[e],l=n[e];if(t.startsWith(":"))i[t.slice(1)]=decodeURIComponent(l);else if(t!==l)return null}return i}exports.createRouter=function(r){let{mode:n="history",base:i="",routes:l}=r,o=[],a=e=>{let t={};return new URLSearchParams(e).forEach((e,r)=>{t[r]=e}),t},s=()=>"hash"===n?window.location.hash.slice(1)||"/":window.location.pathname.replace(i,"")||"/",u=e=>{let[t,r=""]=e.split("?"),[n,i=""]=t.split("#");return{path:n||"/",params:{},query:a(r),hash:i?"#"+i:""}},d=e=>{for(let r of l){let n=t(r.path,e);if(null!==n)return{route:r,params:n}}return null},h=e.createState(u(s())),c=(e,t=!1)=>{let r=u(e),l=d(r.path);l&&(r.params=l.params);for(let e of o){let n=e(r,h.value);if(!1===n)return;if("string"==typeof n)return void c(n,t)}if(l?.route.beforeEnter){let e=l.route.beforeEnter(r,h.value);if(!1===e)return;if("string"==typeof e)return void c(e,t)}let a="hash"===n?"#"+e:i+e;t?window.history.replaceState({path:e},"",a):window.history.pushState({path:e},"",a),h.value=r},p=()=>{let e=s(),t=u(e),r=d(t.path);r&&(t.params=r.params),h.value=t};return typeof window<"u"&&window.addEventListener("popstate",p),{currentRoute:h,push:e=>c(e,!1),replace:e=>c(e,!0),back:()=>window.history.back(),forward:()=>window.history.forward(),go:e=>window.history.go(e),beforeEach:e=>{o.push(e)},destroy:()=>{typeof window<"u"&&window.removeEventListener("popstate",p),h.destroy()}}},exports.createRouterView=function(e,r){let{routes:n,notFound:i}=r;return()=>{let r=e.currentRoute.value,l=n.find(e=>null!==t(e.path,r.path));if(l){let e=t(l.path,r.path)||{},n=l.component({...e,...r.query});return"object"==typeof n&&null!==n&&"tagName"in n?n:{tagName:"span",props:{},children:[n]}}if(i){let e=i(r.params);return"object"==typeof e&&null!==e&&"tagName"in e?e:{tagName:"span",props:{},children:[e]}}return{tagName:"div",props:{},children:["404 - Not Found"]}}},exports.routerLink=(e,t,...r)=>({tagName:"a",props:{...t,href:t.to,onclick:r=>{r.preventDefault(),e.push(t.to)}},children:r});
@@ -0,0 +1 @@
1
+ var e=new 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:n,children:i}=e,l="svg"===r||"s"===r[0]&&"v"===r[1]&&"g"===r[2]||"http://www.w3.org/2000/svg"===t.namespaceURI,o=l?document.createElementNS("http://www.w3.org/2000/svg",r.replace("svg","").toLowerCase()||r):document.createElement(r);for(let e in n){let t=n[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;l?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 a=i.length;if(!a)return void t.appendChild(o);let s=e=>{for(let t=0;t<a;t++){let r=i[t];if(null!=r&&!1!==r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;t++){let n=r[t];null!=n&&!1!==n&&this.renderToDOM(n,e)}else this.renderToDOM(r,e)}};if(a>30){let e=document.createDocumentFragment();s(e),o.appendChild(e)}else s(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 n=t.length;if(n>3e3){let e=document.createDocumentFragment(),i=0,l=1500,o=()=>{let a=Math.min(i+l,n);for(let r=i;r<a;r++)this.renderToDOM(t[r],e);i=a,i>=n?r.appendChild(e):requestAnimationFrame(o)};o()}else{let e=document.createDocumentFragment();for(let r=0;r<n;r++)this.renderToDOM(t[r],e);r.appendChild(e)}return r}renderChunked(e,t,r=5e3,n){let i="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!i)throw new Error(`Element not found: ${e}`);let l=t.length,o=0,a=()=>{let e=Math.min(o+r,l),s=document.createDocumentFragment();for(let r=o;r<e;r++)this.renderToDOM(t[r],s);i.appendChild(s),o=e,n&&n(o,l),o<l&&requestAnimationFrame(a)};return requestAnimationFrame(a),i}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,n=new Set,i=null,{throttle:l=0,deep:o=!1}=t,a=()=>n.forEach(e=>e(r));return{get value(){return r},set value(e){(o?JSON.stringify(r)!==JSON.stringify(e):r!==e)&&(r=e,l>0?i||(i=setTimeout(()=>{i=null,a()},l)):a())},subscribe:e=>(n.add(e),()=>n.delete(e)),destroy(){n.clear(),i&&clearTimeout(i)}}}computed(e,t){let r=e.map(e=>e.value),n=this.createState(t(...r));return e.forEach((e,i)=>{e.subscribe(e=>{r[i]=e,n.value=t(...r)})}),n}effect(e){e()}createVirtualList(e,t,r,n=50,i=5){let l=e.clientHeight,o=t.length*n,a=0,s=()=>{let{start:s,end:u}={start:Math.max(0,Math.floor(a/n)-i),end:Math.min(t.length,Math.ceil((a+l)/n)+i)},d=document.createElement("div");d.style.cssText=`height:${o}px;position:relative`;for(let e=s;e<u;e++){let i=document.createElement("div");i.style.cssText=`position:absolute;top:${e*n}px;height:${n}px;width:100%`,this.renderToDOM(r(t[e],e),i),d.appendChild(i)}e.innerHTML="",e.appendChild(d)},u=()=>{a=e.scrollTop,requestAnimationFrame(s)};return e.addEventListener("scroll",u),s(),{render:s,destroy:()=>{e.removeEventListener("scroll",u),e.innerHTML=""}}}lazy(e){let t=null,r=!1;return async(...n)=>(!t&&!r&&(r=!0,t=await e(),r=!1),t?t(...n):{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:n=0}=t,i=r?" ".repeat(n):"",l=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:a,props:s,children:u}=o,d=this.isSelfClosingTag(a),h=`${i}<${a}`,c=this.propsToAttributes(s);if(c&&(h+=` ${c}`),d)return h+=` />${l}`,h;if(h+=">",s.dangerouslySetInnerHTML)return h+=s.dangerouslySetInnerHTML.__html,h+=`</${a}>${l}`,h;if(u&&u.length>0){let e=u.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){h+=l;for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:r,indent:n+1}));else h+=this.renderToString(t,{pretty:r,indent:n+1});h+=i}else for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:!1,indent:0}));else h+=this.renderToString(t,{pretty:!1,indent:0})}return h+=`</${a}>${l}`,h}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,n=e.children&&1===e.children.length&&"string"==typeof e.children[0];if(r&&n)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 n=e[r];if(n=this.resolveStateValue(n),null!=n&&!1!==n&&(!r.startsWith("on")||"function"!=typeof n)){if("className"===r||"class"===r){let e=Array.isArray(n)?n.join(" "):n;e&&t.push(`class="${this.escapeHtml(String(e))}"`);continue}if("style"===r){let e=this.styleToString(n);e&&t.push(`style="${this.escapeHtml(e)}"`);continue}if(!0===n){t.push(r);continue}t.push(`${r}="${this.escapeHtml(String(n))}"`)}}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 n=r.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${n}:${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 n=t(e.value);r.node.textContent=String(n??"")}})}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:n}=e,i={};for(let e in r){let t=r[e];"class"===e?i.className=this.isState(t)?t.value:t:i[e]=this.isState(t)?t.value:t}let l=[];if(null!=n)if(Array.isArray(n))for(let e of n)if(this.isState(e))l.push(this.createReactiveChild(e,e=>e));else{let t=this.jsonToVNode(e);null!=t&&!1!==t&&l.push(t)}else if(this.isState(n))l.push(this.createReactiveChild(n,e=>e));else if("object"==typeof n&&"tag"in n){let e=this.jsonToVNode(n);null!=e&&!1!==e&&l.push(e)}else l.push(n);return{tagName:t,props:i,children:l}}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:n=[]}=e,i={};for(let e in r){let t=r[e];i[e]=this.isState(t)?t.value:t}let l=[];for(let e of n)if(this.isState(e))l.push(this.createReactiveChild(e,e=>e));else{let t=this.vNodeJsonToVNode(e);null!=t&&!1!==t&&l.push(t)}return{tagName:t,props:i,children:l}}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,n=null;for(let e of t.children||[])"object"==typeof e&&null!==e&&"tagName"in e&&("head"===e.tagName&&(r=e),"body"===e.tagName&&(n=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(n){if(document.body.innerHTML="",n.props)for(let e in n.props){let t=n.props[e];null!=t&&!1!==t&&document.body.setAttribute(e,String(t))}for(let e of n.children||[])this.renderToDOM(e,document.body)}}renderToHTMLDocument(e,t={}){let{title:r="",meta:n=[],links:i=[],scripts:l=[],styles:o=[],lang:a="en",head:s="",bodyAttrs:u={},pretty:d=!1}=t,h=d?"\n":"",c=d?" ":"",p=d?" ":"",f=`<!DOCTYPE html>${h}<html lang="${a}">${h}${c}<head>${h}${p}<meta charset="UTF-8">${h}${p}<meta name="viewport" content="width=device-width, initial-scale=1.0">${h}`;r&&(f+=`${p}<title>${this.escapeHtml(r)}</title>${h}`);for(let e of n){f+=`${p}<meta`;for(let t in e)f+=` ${t}="${this.escapeHtml(e[t])}"`;f+=`>${h}`}for(let e of i){f+=`${p}<link`;for(let t in e)f+=` ${t}="${this.escapeHtml(e[t])}"`;f+=`>${h}`}for(let e of o)e.href?f+=`${p}<link rel="stylesheet" href="${this.escapeHtml(e.href)}">${h}`:e.content&&(f+=`${p}<style>${e.content}</style>${h}`);s&&(f+=s+h),f+=`${c}</head>${h}${c}<body`;for(let e in u)f+=` ${e}="${this.escapeHtml(u[e])}"`;f+=`>${h}`,f+=this.renderToString(e,{pretty:d,indent:2});for(let e of l)f+=`${p}<script`,e.type&&(f+=` type="${this.escapeHtml(e.type)}"`),e.async&&(f+=" async"),e.defer&&(f+=" defer"),e.src?f+=` src="${this.escapeHtml(e.src)}"><\/script>${h}`:e.content?f+=`>${e.content}<\/script>${h}`:f+=`><\/script>${h}`;return f+=`${c}</body>${h}</html>`,f}getElementCache(){return this.elementCache}};function t(e,t){let r=e.split("/").filter(Boolean),n=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!==n.length)return null;let i={};for(let e=0;e<r.length;e++){let t=r[e],l=n[e];if(t.startsWith(":"))i[t.slice(1)]=decodeURIComponent(l);else if(t!==l)return null}return i}function r(r){let{mode:n="history",base:i="",routes:l}=r,o=[],a=e=>{let t={};return new URLSearchParams(e).forEach((e,r)=>{t[r]=e}),t},s=()=>"hash"===n?window.location.hash.slice(1)||"/":window.location.pathname.replace(i,"")||"/",u=e=>{let[t,r=""]=e.split("?"),[n,i=""]=t.split("#");return{path:n||"/",params:{},query:a(r),hash:i?"#"+i:""}},d=e=>{for(let r of l){let n=t(r.path,e);if(null!==n)return{route:r,params:n}}return null},h=e.createState(u(s())),c=(e,t=!1)=>{let r=u(e),l=d(r.path);l&&(r.params=l.params);for(let e of o){let n=e(r,h.value);if(!1===n)return;if("string"==typeof n)return void c(n,t)}if(l?.route.beforeEnter){let e=l.route.beforeEnter(r,h.value);if(!1===e)return;if("string"==typeof e)return void c(e,t)}let a="hash"===n?"#"+e:i+e;t?window.history.replaceState({path:e},"",a):window.history.pushState({path:e},"",a),h.value=r},p=()=>{let e=s(),t=u(e),r=d(t.path);r&&(t.params=r.params),h.value=t};return typeof window<"u"&&window.addEventListener("popstate",p),{currentRoute:h,push:e=>c(e,!1),replace:e=>c(e,!0),back:()=>window.history.back(),forward:()=>window.history.forward(),go:e=>window.history.go(e),beforeEach:e=>{o.push(e)},destroy:()=>{typeof window<"u"&&window.removeEventListener("popstate",p),h.destroy()}}}function n(e,r){let{routes:n,notFound:i}=r;return()=>{let r=e.currentRoute.value,l=n.find(e=>null!==t(e.path,r.path));if(l){let e=t(l.path,r.path)||{},n=l.component({...e,...r.query});return"object"==typeof n&&null!==n&&"tagName"in n?n:{tagName:"span",props:{},children:[n]}}if(i){let e=i(r.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 i=(e,t,...r)=>({tagName:"a",props:{...t,href:t.to,onclick:r=>{r.preventDefault(),e.push(t.to)}},children:r});export{r as createRouter,n as createRouterView,i as routerLink};
@@ -0,0 +1,3 @@
1
+ import 'http';
2
+ import 'ws';
3
+ export { H as HttpMethod, M as Middleware, a as ServerRouteContext, b as ServerRouteHandler, S as ServerRouter, n as SharedState, o as SharedStateOptions, p as StateChangeHandler, m as StateManager, f as bodyLimit, g as cacheControl, i as compress, d as cors, c as createDevServer, L as createProxyHandler, e as errorHandler, h as html, j as json, l as logger, r as rateLimit, k as security, s as status, t as text } from './types-DOAdFFJB.mjs';
@@ -0,0 +1,3 @@
1
+ import 'http';
2
+ import 'ws';
3
+ export { H as HttpMethod, M as Middleware, a as ServerRouteContext, b as ServerRouteHandler, S as ServerRouter, n as SharedState, o as SharedStateOptions, p as StateChangeHandler, m as StateManager, f as bodyLimit, g as cacheControl, i as compress, d as cors, c as createDevServer, L as createProxyHandler, e as errorHandler, h as html, j as json, l as logger, r as rateLimit, k as security, s as status, t as text } from './types-DOAdFFJB.js';
package/dist/server.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e,t=require("http"),r=require("https"),n=require("ws"),o=require("chokidar"),i=require("fs/promises"),s=require("path"),a=require("mime-types"),l=require("esbuild"),d=(e=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(e,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):e),c=new 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:n,children:o}=e,i="svg"===r||"s"===r[0]&&"v"===r[1]&&"g"===r[2]||"http://www.w3.org/2000/svg"===t.namespaceURI,s=i?document.createElementNS("http://www.w3.org/2000/svg",r.replace("svg","").toLowerCase()||r):document.createElement(r);for(let e in n){let t=n[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;i?s.setAttribute("class",e):s.className=e}else if(115===r&&5===e.length)if("string"==typeof t)s.style.cssText=t;else{let e=s.style;for(let r in t)e[r]=t[r]}else 111===r&&110===e.charCodeAt(1)?s[e.toLowerCase()]=t:100===r&&e.length>20?s.innerHTML=t.__html:114===r&&3===e.length?setTimeout(()=>{"function"==typeof t?t(s):t.current=s},0):s.setAttribute(e,!0===t?"":String(t))}let a=o.length;if(!a)return void t.appendChild(s);let l=e=>{for(let t=0;t<a;t++){let r=o[t];if(null!=r&&!1!==r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;t++){let n=r[t];null!=n&&!1!==n&&this.renderToDOM(n,e)}else this.renderToDOM(r,e)}};if(a>30){let e=document.createDocumentFragment();l(e),s.appendChild(e)}else l(s);t.appendChild(s)}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 n=t.length;if(n>3e3){let e=document.createDocumentFragment(),o=0,i=1500,s=()=>{let a=Math.min(o+i,n);for(let r=o;r<a;r++)this.renderToDOM(t[r],e);o=a,o>=n?r.appendChild(e):requestAnimationFrame(s)};s()}else{let e=document.createDocumentFragment();for(let r=0;r<n;r++)this.renderToDOM(t[r],e);r.appendChild(e)}return r}renderChunked(e,t,r=5e3,n){let o="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!o)throw new Error(`Element not found: ${e}`);let i=t.length,s=0,a=()=>{let e=Math.min(s+r,i),l=document.createDocumentFragment();for(let r=s;r<e;r++)this.renderToDOM(t[r],l);o.appendChild(l),s=e,n&&n(s,i),s<i&&requestAnimationFrame(a)};return requestAnimationFrame(a),o}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,n=new Set,o=null,{throttle:i=0,deep:s=!1}=t,a=()=>n.forEach(e=>e(r));return{get value(){return r},set value(e){(s?JSON.stringify(r)!==JSON.stringify(e):r!==e)&&(r=e,i>0?o||(o=setTimeout(()=>{o=null,a()},i)):a())},subscribe:e=>(n.add(e),()=>n.delete(e)),destroy(){n.clear(),o&&clearTimeout(o)}}}computed(e,t){let r=e.map(e=>e.value),n=this.createState(t(...r));return e.forEach((e,o)=>{e.subscribe(e=>{r[o]=e,n.value=t(...r)})}),n}effect(e){e()}createVirtualList(e,t,r,n=50,o=5){let i=e.clientHeight,s=t.length*n,a=0,l=()=>{let{start:l,end:d}={start:Math.max(0,Math.floor(a/n)-o),end:Math.min(t.length,Math.ceil((a+i)/n)+o)},c=document.createElement("div");c.style.cssText=`height:${s}px;position:relative`;for(let e=l;e<d;e++){let o=document.createElement("div");o.style.cssText=`position:absolute;top:${e*n}px;height:${n}px;width:100%`,this.renderToDOM(r(t[e],e),o),c.appendChild(o)}e.innerHTML="",e.appendChild(c)},d=()=>{a=e.scrollTop,requestAnimationFrame(l)};return e.addEventListener("scroll",d),l(),{render:l,destroy:()=>{e.removeEventListener("scroll",d),e.innerHTML=""}}}lazy(e){let t=null,r=!1;return async(...n)=>(!t&&!r&&(r=!0,t=await e(),r=!1),t?t(...n):{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:n=0}=t,o=r?" ".repeat(n):"",i=r?"\n":"",s=this.resolveStateValue(e);if(s=this.unwrapReactive(s),Array.isArray(s))return s.map(e=>this.renderToString(e,t)).join("");if("object"!=typeof s||null===s)return null==s||!1===s?"":this.escapeHtml(String(s));let{tagName:a,props:l,children:d}=s,c=this.isSelfClosingTag(a),h=`${o}<${a}`,p=this.propsToAttributes(l);if(p&&(h+=` ${p}`),c)return h+=` />${i}`,h;if(h+=">",l.dangerouslySetInnerHTML)return h+=l.dangerouslySetInnerHTML.__html,h+=`</${a}>${i}`,h;if(d&&d.length>0){let e=d.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){h+=i;for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:r,indent:n+1}));else h+=this.renderToString(t,{pretty:r,indent:n+1});h+=o}else for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:!1,indent:0}));else h+=this.renderToString(t,{pretty:!1,indent:0})}return h+=`</${a}>${i}`,h}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,n=e.children&&1===e.children.length&&"string"==typeof e.children[0];if(r&&n)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 n=e[r];if(n=this.resolveStateValue(n),null!=n&&!1!==n&&(!r.startsWith("on")||"function"!=typeof n)){if("className"===r||"class"===r){let e=Array.isArray(n)?n.join(" "):n;e&&t.push(`class="${this.escapeHtml(String(e))}"`);continue}if("style"===r){let e=this.styleToString(n);e&&t.push(`style="${this.escapeHtml(e)}"`);continue}if(!0===n){t.push(r);continue}t.push(`${r}="${this.escapeHtml(String(n))}"`)}}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 n=r.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${n}:${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 n=t(e.value);r.node.textContent=String(n??"")}})}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:n}=e,o={};for(let e in r){let t=r[e];"class"===e?o.className=this.isState(t)?t.value:t:o[e]=this.isState(t)?t.value:t}let i=[];if(null!=n)if(Array.isArray(n))for(let e of n)if(this.isState(e))i.push(this.createReactiveChild(e,e=>e));else{let t=this.jsonToVNode(e);null!=t&&!1!==t&&i.push(t)}else if(this.isState(n))i.push(this.createReactiveChild(n,e=>e));else if("object"==typeof n&&"tag"in n){let e=this.jsonToVNode(n);null!=e&&!1!==e&&i.push(e)}else i.push(n);return{tagName:t,props:o,children:i}}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:n=[]}=e,o={};for(let e in r){let t=r[e];o[e]=this.isState(t)?t.value:t}let i=[];for(let e of n)if(this.isState(e))i.push(this.createReactiveChild(e,e=>e));else{let t=this.vNodeJsonToVNode(e);null!=t&&!1!==t&&i.push(t)}return{tagName:t,props:o,children:i}}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,n=null;for(let e of t.children||[])"object"==typeof e&&null!==e&&"tagName"in e&&("head"===e.tagName&&(r=e),"body"===e.tagName&&(n=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(n){if(document.body.innerHTML="",n.props)for(let e in n.props){let t=n.props[e];null!=t&&!1!==t&&document.body.setAttribute(e,String(t))}for(let e of n.children||[])this.renderToDOM(e,document.body)}}renderToHTMLDocument(e,t={}){let{title:r="",meta:n=[],links:o=[],scripts:i=[],styles:s=[],lang:a="en",head:l="",bodyAttrs:d={},pretty:c=!1}=t,h=c?"\n":"",p=c?" ":"",u=c?" ":"",g=`<!DOCTYPE html>${h}<html lang="${a}">${h}${p}<head>${h}${u}<meta charset="UTF-8">${h}${u}<meta name="viewport" content="width=device-width, initial-scale=1.0">${h}`;r&&(g+=`${u}<title>${this.escapeHtml(r)}</title>${h}`);for(let e of n){g+=`${u}<meta`;for(let t in e)g+=` ${t}="${this.escapeHtml(e[t])}"`;g+=`>${h}`}for(let e of o){g+=`${u}<link`;for(let t in e)g+=` ${t}="${this.escapeHtml(e[t])}"`;g+=`>${h}`}for(let e of s)e.href?g+=`${u}<link rel="stylesheet" href="${this.escapeHtml(e.href)}">${h}`:e.content&&(g+=`${u}<style>${e.content}</style>${h}`);l&&(g+=l+h),g+=`${p}</head>${h}${p}<body`;for(let e in d)g+=` ${e}="${this.escapeHtml(d[e])}"`;g+=`>${h}`,g+=this.renderToString(e,{pretty:c,indent:2});for(let e of i)g+=`${u}<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>${h}`:e.content?g+=`>${e.content}<\/script>${h}`:g+=`><\/script>${h}`;return g+=`${p}</body>${h}</html>`,g}getElementCache(){return this.elementCache}};function h(e){return async(n,o)=>{let i=n.url||"/",s=i.split("?")[0],a=e.find(e=>s.startsWith(e.context));if(!a)return!1;let{target:l,changeOrigin:d,pathRewrite:c,headers:h}=a;try{let e=new URL(l),s="https:"===e.protocol,a=s?r.request:t.request,p=function(e,t){if(!t)return e;for(let[r,n]of Object.entries(t)){let t=new RegExp(r);if(t.test(e))return e.replace(t,n)}return e}(i,c),u={hostname:e.hostname,port:e.port||(s?443:80),path:p,method:n.method,headers:{...n.headers,...h||{}}};d&&(u.headers.host=e.host),delete u.headers.host;let g=a(u,e=>{o.writeHead(e.statusCode||200,e.headers),e.pipe(o)});return g.on("error",e=>{console.error("[Proxy] Error proxying %s to %s:",i,l,e.message),o.headersSent||(o.writeHead(502,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Bad Gateway",message:"Proxy error"})))}),n.pipe(g),!0}catch(e){return console.error("[Proxy] Invalid proxy configuration for %s:",s,e),!1}}}var p=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===n.WebSocket.OPEN&&t.send(e))}sendTo(e){e.readyState===n.WebSocket.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()}},u=class{constructor(){this.states=new Map}create(e,t){if(this.states.has(e))return this.states.get(e);let r=new p(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()}},g={port:3e3,host:"localhost",https:!1,open:!0,watch:["**/*.ts","**/*.js","**/*.html","**/*.css"],ignore:["node_modules/**","dist/**",".git/**","**/*.d.ts"],logging:!0,middleware:[],worker:[]};exports.ServerRouter=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:n,paramNames:o}=this.pathToRegex(t);return this.routes.push({method:e,pattern:n,paramNames:o,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 n="";e.on("data",e=>n+=e.toString()),e.on("end",()=>{try{let r=e.headers["content-type"]||"";if(r.includes("application/json"))t(n?JSON.parse(n):{});else if(r.includes("application/x-www-form-urlencoded")){let e={};new URLSearchParams(n).forEach((t,r)=>e[r]=t),t(e)}else t(n)}catch(e){r(e)}}),e.on("error",r)})}async handle(e,t){let r=e.method,n=e.url||"/",o=n.split("?")[0];for(let i of this.routes){if(i.method!==r)continue;let s=o.match(i.pattern);if(!s)continue;let a={};i.paramNames.forEach((e,t)=>{a[e]=s[t+1]});let l=this.parseQuery(n),d={};if(["POST","PUT","PATCH"].includes(r))try{d=await this.parseBody(e)}catch{return t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid request body"})),!0}let c={req:e,res:t,params:a,query:l,body:d,headers:e.headers},h=0,p=async()=>{if(h<this.middlewares.length){let e=this.middlewares[h++];await e(c,p)}};try{await p(),await i.handler(c)}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}},exports.SharedState=p,exports.StateManager=u,exports.bodyLimit=function(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()}},exports.cacheControl=function(e={}){let{maxAge:t=3600,public:r=!0}=e;return async(e,n)=>{e.res.setHeader("Cache-Control",`${r?"public":"private"}, max-age=${t}`),await n()}},exports.compress=function(){return async(e,t)=>{if(!(e.req.headers["accept-encoding"]||"").includes("gzip"))return void await t();let r=e.res.end.bind(e.res),n=[];e.res.write=e=>(n.push(Buffer.from(e)),!0),e.res.end=t=>{t&&n.push(Buffer.from(t));let o=Buffer.concat(n),{gzipSync:i}=d("zlib"),s=i(o);return e.res.setHeader("Content-Encoding","gzip"),e.res.setHeader("Content-Length",s.length),r(s),e.res},await t()}},exports.cors=function(e={}){let{origin:t="*",methods:r=["GET","POST","PUT","DELETE","PATCH","OPTIONS"],credentials:n=!0,maxAge:o=86400}=e;return async(e,i)=>{let s=e.req.headers.origin||"",a=Array.isArray(t)&&t.includes(s)?s:Array.isArray(t)?"":t;if(a&&e.res.setHeader("Access-Control-Allow-Origin",a),e.res.setHeader("Access-Control-Allow-Methods",r.join(", ")),e.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n&&e.res.setHeader("Access-Control-Allow-Credentials","true"),e.res.setHeader("Access-Control-Max-Age",String(o)),"OPTIONS"===e.req.method)return e.res.writeHead(204),void e.res.end();await i()}},exports.createDevServer=function(e){let r={...g,...e},p=new Set,f=new u,y=r.clients?.length?r.clients:r.root?[{root:r.root,basePath:r.basePath||"",ssr:r.ssr,proxy:r.proxy}]:null;if(!y)throw new Error('DevServerOptions must include either "clients" array or "root" directory');let m=y.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?h(e.proxy):void 0}}),w=r.proxy?h(r.proxy):null,b=t.createServer(async(e,t)=>{let n=e.url||"/",o=m.find(e=>e.basePath&&n.startsWith(e.basePath))||m.find(e=>!e.basePath);if(!o)return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found");if(o.proxyHandler)try{if(await o.proxyHandler(e,t))return void(r.logging&&console.log(`[Proxy] ${e.method} ${n} -> proxied (client-specific)`))}catch(e){console.error("[Proxy] Error (client-specific):",e)}if(w)try{if(await w(e,t))return void(r.logging&&console.log(`[Proxy] ${e.method} ${n} -> proxied (global)`))}catch(e){console.error("[Proxy] Error (global):",e)}let a=o.basePath?n.slice(o.basePath.length)||"/":n;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 d,c=l.startsWith("/dist/"),h=s.normalize(l).replace(/\\/g,"/").replace(/^\/+/,"");if(h.includes(".."))return r.logging&&console.log(`[403] Path traversal attempt: ${l}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");d=h;let p,u=await i.realpath(s.resolve(o.root)),g=c?await i.realpath(s.resolve(o.root,"..")):u;try{if(p=await i.realpath(s.resolve(s.join(g,d))),!p.startsWith(g.endsWith(s.sep)?g:g+s.sep))return r.logging&&console.log(`[403] File access outside of root: ${p}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");r.logging&&"/src/pages"===l&&console.log(`[DEBUG] Initial resolve succeeded: ${p}`)}catch{let e;if(r.logging&&!d.includes(".")&&console.log(`[DEBUG] File not found: ${d}, trying extensions...`),d.endsWith(".js")){let n=d.replace(/\.js$/,".ts");try{let o=await i.realpath(s.resolve(s.join(g,n)));if(!o.startsWith(g.endsWith(s.sep)?g:g+s.sep))return r.logging&&console.log(`[403] Fallback TS path outside of root: ${o}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");e=o}catch{}}if(!e&&!d.includes("."))try{e=await i.realpath(s.resolve(s.join(g,d+".ts"))),r.logging&&console.log(`[DEBUG] Found: ${d}.ts`)}catch{try{e=await i.realpath(s.resolve(s.join(g,d+".js"))),r.logging&&console.log(`[DEBUG] Found: ${d}.js`)}catch{try{e=await i.realpath(s.resolve(s.join(g,d,"index.ts"))),r.logging&&console.log(`[DEBUG] Found: ${d}/index.ts`)}catch{try{e=await i.realpath(s.resolve(s.join(g,d,"index.js"))),r.logging&&console.log(`[DEBUG] Found: ${d}/index.js`)}catch{r.logging&&console.log(`[DEBUG] Not found: all attempts failed for ${d}`)}}}}if(!e)return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found");p=e}try{if((await i.stat(p)).isDirectory()){let e;r.logging&&console.log(`[DEBUG] Path is directory: ${p}, trying index files...`);try{e=await i.realpath(s.resolve(s.join(p,"index.ts"))),r.logging&&console.log("[DEBUG] Found index.ts in directory")}catch{try{e=await i.realpath(s.resolve(s.join(p,"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")}}p=e}}catch{return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found")}let f=await i.realpath(s.resolve(o.root,"..")),y=p.startsWith(u+s.sep)||p===u,b=c&&(p.startsWith(f+s.sep)||p===f);if(!y&&!b)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.stat(p)).isDirectory())try{let e=await i.realpath(s.resolve(s.join(p,"index.html")));return e.startsWith(u+s.sep)||e===u?(await i.stat(e),v(e,t,o)):(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 v(p,t,o)}catch{r.logging&&console.log(`[404] ${l}`),t.writeHead(404,{"Content-Type":"text/plain"}),t.end("404 Not Found")}});async function v(e,t,n){try{let o,h=await i.realpath(s.resolve(n.root)),p=await i.realpath(s.resolve(n.root,".."));try{o=await i.realpath(s.resolve(e))}catch{return e.endsWith("index.html")&&n.ssr?function(e,t){try{if(!t.ssr)return e.writeHead(500,{"Content-Type":"text/plain"}),void e.end("SSR function not configured");let n,o=t.ssr();if("string"==typeof o)n=o;else if("object"==typeof o&&null!==o&&"tagName"in o){let e=o;n="html"===e.tagName?c.renderToString(e):`<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body>${c.renderToString(e)}</body></html>`}else n=String(o);let i=`<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>`;n=n.includes("</body>")?n.replace("</body>",`${i}</body>`):n+i,e.writeHead(200,{"Content-Type":"text/html","Cache-Control":"no-cache, no-store, must-revalidate"}),e.end(n),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,n):(t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found"))}let u=o.startsWith(h+s.sep)||o===h,g=o.startsWith(p+s.sep+"dist"+s.sep);if(!u&&!g)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 f=await i.readFile(o),y=s.extname(o),m=a.lookup(o)||"application/octet-stream";if(".ts"===y||".tsx"===y)try{let e=await l.build({stdin:{contents:f.toString(),loader:".tsx"===y?"tsx":"ts",resolveDir:s.resolve(o,".."),sourcefile:o},format:"esm",target:"es2020",write:!1,bundle:!1,sourcemap:"inline"});f=Buffer.from(e.outputFiles[0].text),m="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"===y){let e=`<script type="importmap">\n{\n "imports": {\n "elit": "${n.basePath?`${n.basePath}/dist/client.mjs`:"/dist/client.mjs"}"\n }\n}\n<\/script>`,t=`<script>(function(){const ws=new WebSocket('ws://${r.host}:${r.port}${n.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>`,o=f.toString();if(n.basePath&&"/"!==n.basePath){let e=`<base href="${n.basePath}/">`;o.includes("<base")||(o.includes('<meta name="viewport"')?o=o.replace(/<meta name="viewport"[^>]*>/,t=>`${t}\n ${e}`):o.includes("<head>")&&(o=o.replace("<head>",`<head>\n ${e}`)))}o=o.includes("</head>")?o.replace("</head>",`${e}</head>`):o,o=o.includes("</body>")?o.replace("</body>",`${t}</body>`):o+t,f=Buffer.from(o)}let w={"Content-Type":m,"Cache-Control":".html"===y||".ts"===y||".tsx"===y?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable"};if(/^(text\/|application\/(javascript|json|xml))/.test(m)&&f.length>1024){let{gzipSync:e}=d("zlib"),r=e(f);w["Content-Encoding"]="gzip",w["Content-Length"]=r.length,t.writeHead(200,w),t.end(r)}else t.writeHead(200,w),t.end(f);r.logging&&console.log(`[200] ${s.relative(n.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 S=new n.WebSocketServer({server:b});S.on("connection",e=>{p.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 n=JSON.parse(t.toString());"state:subscribe"===n.type?(f.subscribe(n.key,e),r.logging&&console.log(`[State] Client subscribed to "${n.key}"`)):"state:unsubscribe"===n.type?(f.unsubscribe(n.key,e),r.logging&&console.log(`[State] Client unsubscribed from "${n.key}"`)):"state:change"===n.type&&(f.handleStateChange(n.key,n.value),r.logging&&console.log(`[State] Client updated "${n.key}"`))}catch(e){r.logging&&console.error("[WebSocket] Message parse error:",e)}}),e.on("close",()=>{p.delete(e),f.unsubscribeAll(e),r.logging&&console.log("[HMR] Client disconnected")})});let $=m.flatMap(e=>r.watch.map(t=>s.join(e.root,t))),T=o.watch($,{ignored:r.ignore,ignoreInitial:!0,persistent:!0});T.on("change",e=>{r.logging&&console.log(`[HMR] File changed: ${e}`);let t=JSON.stringify({type:"update",path:e,timestamp:Date.now()});p.forEach(e=>e.readyState===n.WebSocket.OPEN&&e.send(t))}),T.on("add",e=>r.logging&&console.log(`[HMR] File added: ${e}`)),T.on("unlink",e=>r.logging&&console.log(`[HMR] File removed: ${e}`)),b.setMaxListeners(20),b.listen(r.port,r.host,()=>{if(r.logging){if(console.log("\n🚀 Elit Dev Server"),console.log(`\n ➜ Local: http://${r.host}:${r.port}`),m.length>1)console.log(" ➜ Clients:"),m.forEach(e=>{let t=`http://${r.host}:${r.port}${e.basePath}`;console.log(` - ${t} → ${e.root}`)});else{let e=m[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&&m.length>0){let e=m[0],t=`http://${r.host}:${r.port}${e.basePath}`;(async()=>{let{default:e}=await import("open");await e(t)})().catch(()=>{})}});let x=!1,C=m[0],E=`http://${r.host}:${r.port}${C.basePath}`;return{server:b,wss:S,url:E,state:f,close:async()=>{if(!x)return x=!0,r.logging&&console.log("\n[Server] Shutting down..."),await T.close(),S.close(),p.forEach(e=>e.close()),p.clear(),new Promise(e=>{b.close(()=>{r.logging&&console.log("[Server] Closed"),e()})})}}},exports.createProxyHandler=h,exports.errorHandler=function(){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"})))}}},exports.html=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"text/html"}),e.end(t)},exports.json=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))},exports.logger=function(e={}){let{format:t="simple"}=e;return async(e,r)=>{let n=Date.now(),{method:o,url:i}=e.req;await r();let s=Date.now()-n,a=e.res.statusCode;console.log("detailed"===t?`[${(new Date).toISOString()}] ${o} ${i} ${a} - ${s}ms`:`${o} ${i} - ${a} (${s}ms)`)}},exports.rateLimit=function(e={}){let{windowMs:t=6e4,max:r=100,message:n="Too many requests"}=e,o=new Map;return async(e,i)=>{let s=e.req.socket.remoteAddress||"unknown",a=Date.now(),l=o.get(s);if((!l||a>l.resetTime)&&(l={count:0,resetTime:a+t},o.set(s,l)),++l.count>r)return e.res.writeHead(429,{"Content-Type":"application/json"}),void e.res.end(JSON.stringify({error:n}));await i()}},exports.security=function(){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()}},exports.status=(e,t,r)=>{e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t,message:r||""}))},exports.text=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"text/plain"}),e.end(t)};
@@ -0,0 +1 @@
1
+ import{request as e,createServer as t}from"http";import{request as r}from"https";import{WebSocket as n,WebSocketServer as o}from"ws";import{watch as i}from"chokidar";import{realpath as s,stat as a,readFile as l}from"fs/promises";import{normalize as d,resolve as c,join as h,sep as u,extname as p,relative as g}from"path";import{lookup as f}from"mime-types";import{build as m}from"esbuild";var y,w=(y=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(y,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):y),b=new 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:n,children:o}=e,i="svg"===r||"s"===r[0]&&"v"===r[1]&&"g"===r[2]||"http://www.w3.org/2000/svg"===t.namespaceURI,s=i?document.createElementNS("http://www.w3.org/2000/svg",r.replace("svg","").toLowerCase()||r):document.createElement(r);for(let e in n){let t=n[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;i?s.setAttribute("class",e):s.className=e}else if(115===r&&5===e.length)if("string"==typeof t)s.style.cssText=t;else{let e=s.style;for(let r in t)e[r]=t[r]}else 111===r&&110===e.charCodeAt(1)?s[e.toLowerCase()]=t:100===r&&e.length>20?s.innerHTML=t.__html:114===r&&3===e.length?setTimeout(()=>{"function"==typeof t?t(s):t.current=s},0):s.setAttribute(e,!0===t?"":String(t))}let a=o.length;if(!a)return void t.appendChild(s);let l=e=>{for(let t=0;t<a;t++){let r=o[t];if(null!=r&&!1!==r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;t++){let n=r[t];null!=n&&!1!==n&&this.renderToDOM(n,e)}else this.renderToDOM(r,e)}};if(a>30){let e=document.createDocumentFragment();l(e),s.appendChild(e)}else l(s);t.appendChild(s)}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 n=t.length;if(n>3e3){let e=document.createDocumentFragment(),o=0,i=1500,s=()=>{let a=Math.min(o+i,n);for(let r=o;r<a;r++)this.renderToDOM(t[r],e);o=a,o>=n?r.appendChild(e):requestAnimationFrame(s)};s()}else{let e=document.createDocumentFragment();for(let r=0;r<n;r++)this.renderToDOM(t[r],e);r.appendChild(e)}return r}renderChunked(e,t,r=5e3,n){let o="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!o)throw new Error(`Element not found: ${e}`);let i=t.length,s=0,a=()=>{let e=Math.min(s+r,i),l=document.createDocumentFragment();for(let r=s;r<e;r++)this.renderToDOM(t[r],l);o.appendChild(l),s=e,n&&n(s,i),s<i&&requestAnimationFrame(a)};return requestAnimationFrame(a),o}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,n=new Set,o=null,{throttle:i=0,deep:s=!1}=t,a=()=>n.forEach(e=>e(r));return{get value(){return r},set value(e){(s?JSON.stringify(r)!==JSON.stringify(e):r!==e)&&(r=e,i>0?o||(o=setTimeout(()=>{o=null,a()},i)):a())},subscribe:e=>(n.add(e),()=>n.delete(e)),destroy(){n.clear(),o&&clearTimeout(o)}}}computed(e,t){let r=e.map(e=>e.value),n=this.createState(t(...r));return e.forEach((e,o)=>{e.subscribe(e=>{r[o]=e,n.value=t(...r)})}),n}effect(e){e()}createVirtualList(e,t,r,n=50,o=5){let i=e.clientHeight,s=t.length*n,a=0,l=()=>{let{start:l,end:d}={start:Math.max(0,Math.floor(a/n)-o),end:Math.min(t.length,Math.ceil((a+i)/n)+o)},c=document.createElement("div");c.style.cssText=`height:${s}px;position:relative`;for(let e=l;e<d;e++){let o=document.createElement("div");o.style.cssText=`position:absolute;top:${e*n}px;height:${n}px;width:100%`,this.renderToDOM(r(t[e],e),o),c.appendChild(o)}e.innerHTML="",e.appendChild(c)},d=()=>{a=e.scrollTop,requestAnimationFrame(l)};return e.addEventListener("scroll",d),l(),{render:l,destroy:()=>{e.removeEventListener("scroll",d),e.innerHTML=""}}}lazy(e){let t=null,r=!1;return async(...n)=>(!t&&!r&&(r=!0,t=await e(),r=!1),t?t(...n):{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:n=0}=t,o=r?" ".repeat(n):"",i=r?"\n":"",s=this.resolveStateValue(e);if(s=this.unwrapReactive(s),Array.isArray(s))return s.map(e=>this.renderToString(e,t)).join("");if("object"!=typeof s||null===s)return null==s||!1===s?"":this.escapeHtml(String(s));let{tagName:a,props:l,children:d}=s,c=this.isSelfClosingTag(a),h=`${o}<${a}`,u=this.propsToAttributes(l);if(u&&(h+=` ${u}`),c)return h+=` />${i}`,h;if(h+=">",l.dangerouslySetInnerHTML)return h+=l.dangerouslySetInnerHTML.__html,h+=`</${a}>${i}`,h;if(d&&d.length>0){let e=d.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){h+=i;for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:r,indent:n+1}));else h+=this.renderToString(t,{pretty:r,indent:n+1});h+=o}else for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(h+=this.renderToString(e,{pretty:!1,indent:0}));else h+=this.renderToString(t,{pretty:!1,indent:0})}return h+=`</${a}>${i}`,h}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,n=e.children&&1===e.children.length&&"string"==typeof e.children[0];if(r&&n)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 n=e[r];if(n=this.resolveStateValue(n),null!=n&&!1!==n&&(!r.startsWith("on")||"function"!=typeof n)){if("className"===r||"class"===r){let e=Array.isArray(n)?n.join(" "):n;e&&t.push(`class="${this.escapeHtml(String(e))}"`);continue}if("style"===r){let e=this.styleToString(n);e&&t.push(`style="${this.escapeHtml(e)}"`);continue}if(!0===n){t.push(r);continue}t.push(`${r}="${this.escapeHtml(String(n))}"`)}}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 n=r.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${n}:${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 n=t(e.value);r.node.textContent=String(n??"")}})}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:n}=e,o={};for(let e in r){let t=r[e];"class"===e?o.className=this.isState(t)?t.value:t:o[e]=this.isState(t)?t.value:t}let i=[];if(null!=n)if(Array.isArray(n))for(let e of n)if(this.isState(e))i.push(this.createReactiveChild(e,e=>e));else{let t=this.jsonToVNode(e);null!=t&&!1!==t&&i.push(t)}else if(this.isState(n))i.push(this.createReactiveChild(n,e=>e));else if("object"==typeof n&&"tag"in n){let e=this.jsonToVNode(n);null!=e&&!1!==e&&i.push(e)}else i.push(n);return{tagName:t,props:o,children:i}}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:n=[]}=e,o={};for(let e in r){let t=r[e];o[e]=this.isState(t)?t.value:t}let i=[];for(let e of n)if(this.isState(e))i.push(this.createReactiveChild(e,e=>e));else{let t=this.vNodeJsonToVNode(e);null!=t&&!1!==t&&i.push(t)}return{tagName:t,props:o,children:i}}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,n=null;for(let e of t.children||[])"object"==typeof e&&null!==e&&"tagName"in e&&("head"===e.tagName&&(r=e),"body"===e.tagName&&(n=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(n){if(document.body.innerHTML="",n.props)for(let e in n.props){let t=n.props[e];null!=t&&!1!==t&&document.body.setAttribute(e,String(t))}for(let e of n.children||[])this.renderToDOM(e,document.body)}}renderToHTMLDocument(e,t={}){let{title:r="",meta:n=[],links:o=[],scripts:i=[],styles:s=[],lang:a="en",head:l="",bodyAttrs:d={},pretty:c=!1}=t,h=c?"\n":"",u=c?" ":"",p=c?" ":"",g=`<!DOCTYPE html>${h}<html lang="${a}">${h}${u}<head>${h}${p}<meta charset="UTF-8">${h}${p}<meta name="viewport" content="width=device-width, initial-scale=1.0">${h}`;r&&(g+=`${p}<title>${this.escapeHtml(r)}</title>${h}`);for(let e of n){g+=`${p}<meta`;for(let t in e)g+=` ${t}="${this.escapeHtml(e[t])}"`;g+=`>${h}`}for(let e of o){g+=`${p}<link`;for(let t in e)g+=` ${t}="${this.escapeHtml(e[t])}"`;g+=`>${h}`}for(let e of s)e.href?g+=`${p}<link rel="stylesheet" href="${this.escapeHtml(e.href)}">${h}`:e.content&&(g+=`${p}<style>${e.content}</style>${h}`);l&&(g+=l+h),g+=`${u}</head>${h}${u}<body`;for(let e in d)g+=` ${e}="${this.escapeHtml(d[e])}"`;g+=`>${h}`,g+=this.renderToString(e,{pretty:c,indent:2});for(let e of i)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>${h}`:e.content?g+=`>${e.content}<\/script>${h}`:g+=`><\/script>${h}`;return g+=`${u}</body>${h}</html>`,g}getElementCache(){return this.elementCache}},$=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:n,paramNames:o}=this.pathToRegex(t);return this.routes.push({method:e,pattern:n,paramNames:o,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 n="";e.on("data",e=>n+=e.toString()),e.on("end",()=>{try{let r=e.headers["content-type"]||"";if(r.includes("application/json"))t(n?JSON.parse(n):{});else if(r.includes("application/x-www-form-urlencoded")){let e={};new URLSearchParams(n).forEach((t,r)=>e[r]=t),t(e)}else t(n)}catch(e){r(e)}}),e.on("error",r)})}async handle(e,t){let r=e.method,n=e.url||"/",o=n.split("?")[0];for(let i of this.routes){if(i.method!==r)continue;let s=o.match(i.pattern);if(!s)continue;let a={};i.paramNames.forEach((e,t)=>{a[e]=s[t+1]});let l=this.parseQuery(n),d={};if(["POST","PUT","PATCH"].includes(r))try{d=await this.parseBody(e)}catch{return t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid request body"})),!0}let c={req:e,res:t,params:a,query:l,body:d,headers:e.headers},h=0,u=async()=>{if(h<this.middlewares.length){let e=this.middlewares[h++];await e(c,u)}};try{await u(),await i.handler(c)}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}},S=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))},v=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"text/plain"}),e.end(t)},T=(e,t,r=200)=>{e.writeHead(r,{"Content-Type":"text/html"}),e.end(t)},C=(e,t,r)=>{e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t,message:r||""}))};function E(e={}){let{origin:t="*",methods:r=["GET","POST","PUT","DELETE","PATCH","OPTIONS"],credentials:n=!0,maxAge:o=86400}=e;return async(e,i)=>{let s=e.req.headers.origin||"",a=Array.isArray(t)&&t.includes(s)?s:Array.isArray(t)?"":t;if(a&&e.res.setHeader("Access-Control-Allow-Origin",a),e.res.setHeader("Access-Control-Allow-Methods",r.join(", ")),e.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n&&e.res.setHeader("Access-Control-Allow-Credentials","true"),e.res.setHeader("Access-Control-Max-Age",String(o)),"OPTIONS"===e.req.method)return e.res.writeHead(204),void e.res.end();await i()}}function H(e={}){let{format:t="simple"}=e;return async(e,r)=>{let n=Date.now(),{method:o,url:i}=e.req;await r();let s=Date.now()-n,a=e.res.statusCode;console.log("detailed"===t?`[${(new Date).toISOString()}] ${o} ${i} ${a} - ${s}ms`:`${o} ${i} - ${a} (${s}ms)`)}}function x(){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 N(e={}){let{windowMs:t=6e4,max:r=100,message:n="Too many requests"}=e,o=new Map;return async(e,i)=>{let s=e.req.socket.remoteAddress||"unknown",a=Date.now(),l=o.get(s);if((!l||a>l.resetTime)&&(l={count:0,resetTime:a+t},o.set(s,l)),++l.count>r)return e.res.writeHead(429,{"Content-Type":"application/json"}),void e.res.end(JSON.stringify({error:n}));await i()}}function R(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 M(e={}){let{maxAge:t=3600,public:r=!0}=e;return async(e,n)=>{e.res.setHeader("Cache-Control",`${r?"public":"private"}, max-age=${t}`),await n()}}function A(){return async(e,t)=>{if(!(e.req.headers["accept-encoding"]||"").includes("gzip"))return void await t();let r=e.res.end.bind(e.res),n=[];e.res.write=e=>(n.push(Buffer.from(e)),!0),e.res.end=t=>{t&&n.push(Buffer.from(t));let o=Buffer.concat(n),{gzipSync:i}=w("zlib"),s=i(o);return e.res.setHeader("Content-Encoding","gzip"),e.res.setHeader("Content-Length",s.length),r(s),e.res},await t()}}function P(){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 O(t){return async(n,o)=>{let i=n.url||"/",s=i.split("?")[0],a=t.find(e=>s.startsWith(e.context));if(!a)return!1;let{target:l,changeOrigin:d,pathRewrite:c,headers:h}=a;try{let t=new URL(l),s="https:"===t.protocol,a=s?r:e,u=function(e,t){if(!t)return e;for(let[r,n]of Object.entries(t)){let t=new RegExp(r);if(t.test(e))return e.replace(t,n)}return e}(i,c),p={hostname:t.hostname,port:t.port||(s?443:80),path:u,method:n.method,headers:{...n.headers,...h||{}}};d&&(p.headers.host=t.host),delete p.headers.host;let g=a(p,e=>{o.writeHead(e.statusCode||200,e.headers),e.pipe(o)});return g.on("error",e=>{console.error("[Proxy] Error proxying %s to %s:",i,l,e.message),o.headersSent||(o.writeHead(502,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Bad Gateway",message:"Proxy error"})))}),n.pipe(g),!0}catch(e){return console.error("[Proxy] Invalid proxy configuration for %s:",s,e),!1}}}var D=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===n.OPEN&&t.send(e))}sendTo(e){e.readyState===n.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()}},j=class{constructor(){this.states=new Map}create(e,t){if(this.states.has(e))return this.states.get(e);let r=new D(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()}},F={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 k(e){let r={...F,...e},y=new Set,$=new j,S=r.clients?.length?r.clients:r.root?[{root:r.root,basePath:r.basePath||"",ssr:r.ssr,proxy:r.proxy}]:null;if(!S)throw new Error('DevServerOptions must include either "clients" array or "root" directory');let v=S.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?O(e.proxy):void 0}}),T=r.proxy?O(r.proxy):null,C=t(async(e,t)=>{let n=e.url||"/",o=v.find(e=>e.basePath&&n.startsWith(e.basePath))||v.find(e=>!e.basePath);if(!o)return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found");if(o.proxyHandler)try{if(await o.proxyHandler(e,t))return void(r.logging&&console.log(`[Proxy] ${e.method} ${n} -> proxied (client-specific)`))}catch(e){console.error("[Proxy] Error (client-specific):",e)}if(T)try{if(await T(e,t))return void(r.logging&&console.log(`[Proxy] ${e.method} ${n} -> proxied (global)`))}catch(e){console.error("[Proxy] Error (global):",e)}let i=o.basePath?n.slice(o.basePath.length)||"/":n;if(r.api&&i.startsWith("/api")&&await r.api.handle(e,t))return;let l="/"===i?"/index.html":i;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/"),f=d(l).replace(/\\/g,"/").replace(/^\/+/,"");if(f.includes(".."))return r.logging&&console.log(`[403] Path traversal attempt: ${l}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");p=f;let m,y=await s(c(o.root)),w=g?await s(c(o.root,"..")):y;try{if(m=await s(c(h(w,p))),!m.startsWith(w.endsWith(u)?w:w+u))return r.logging&&console.log(`[403] File access outside of root: ${m}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");r.logging&&"/src/pages"===l&&console.log(`[DEBUG] Initial resolve succeeded: ${m}`)}catch{let e;if(r.logging&&!p.includes(".")&&console.log(`[DEBUG] File not found: ${p}, trying extensions...`),p.endsWith(".js")){let n=p.replace(/\.js$/,".ts");try{let o=await s(c(h(w,n)));if(!o.startsWith(w.endsWith(u)?w:w+u))return r.logging&&console.log(`[403] Fallback TS path outside of root: ${o}`),t.writeHead(403,{"Content-Type":"text/plain"}),void t.end("403 Forbidden");e=o}catch{}}if(!e&&!p.includes("."))try{e=await s(c(h(w,p+".ts"))),r.logging&&console.log(`[DEBUG] Found: ${p}.ts`)}catch{try{e=await s(c(h(w,p+".js"))),r.logging&&console.log(`[DEBUG] Found: ${p}.js`)}catch{try{e=await s(c(h(w,p,"index.ts"))),r.logging&&console.log(`[DEBUG] Found: ${p}/index.ts`)}catch{try{e=await s(c(h(w,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");m=e}try{if((await a(m)).isDirectory()){let e;r.logging&&console.log(`[DEBUG] Path is directory: ${m}, trying index files...`);try{e=await s(c(h(m,"index.ts"))),r.logging&&console.log("[DEBUG] Found index.ts in directory")}catch{try{e=await s(c(h(m,"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")}}m=e}}catch{return t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found")}let b=await s(c(o.root,"..")),$=m.startsWith(y+u)||m===y,S=g&&(m.startsWith(b+u)||m===b);if(!$&&!S)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 a(m)).isDirectory())try{let e=await s(c(h(m,"index.html")));return e.startsWith(y+u)||e===y?(await a(e),E(e,t,o)):(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(m,t,o)}catch{r.logging&&console.log(`[404] ${l}`),t.writeHead(404,{"Content-Type":"text/plain"}),t.end("404 Not Found")}});async function E(e,t,n){try{let o,i=await s(c(n.root)),a=await s(c(n.root,".."));try{o=await s(c(e))}catch{return e.endsWith("index.html")&&n.ssr?function(e,t){try{if(!t.ssr)return e.writeHead(500,{"Content-Type":"text/plain"}),void e.end("SSR function not configured");let n,o=t.ssr();if("string"==typeof o)n=o;else if("object"==typeof o&&null!==o&&"tagName"in o){let e=o;n="html"===e.tagName?b.renderToString(e):`<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body>${b.renderToString(e)}</body></html>`}else n=String(o);let i=`<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>`;n=n.includes("</body>")?n.replace("</body>",`${i}</body>`):n+i,e.writeHead(200,{"Content-Type":"text/html","Cache-Control":"no-cache, no-store, must-revalidate"}),e.end(n),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,n):(t.writeHead(404,{"Content-Type":"text/plain"}),void t.end("404 Not Found"))}let d=o.startsWith(i+u)||o===i,h=o.startsWith(a+u+"dist"+u);if(!d&&!h)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 y=await l(o),$=p(o),S=f(o)||"application/octet-stream";if(".ts"===$||".tsx"===$)try{let e=await m({stdin:{contents:y.toString(),loader:".tsx"===$?"tsx":"ts",resolveDir:c(o,".."),sourcefile:o},format:"esm",target:"es2020",write:!1,bundle:!1,sourcemap:"inline"});y=Buffer.from(e.outputFiles[0].text),S="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"===$){let e=`<script type="importmap">\n{\n "imports": {\n "elit": "${n.basePath?`${n.basePath}/dist/client.mjs`:"/dist/client.mjs"}"\n }\n}\n<\/script>`,t=`<script>(function(){const ws=new WebSocket('ws://${r.host}:${r.port}${n.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>`,o=y.toString();if(n.basePath&&"/"!==n.basePath){let e=`<base href="${n.basePath}/">`;o.includes("<base")||(o.includes('<meta name="viewport"')?o=o.replace(/<meta name="viewport"[^>]*>/,t=>`${t}\n ${e}`):o.includes("<head>")&&(o=o.replace("<head>",`<head>\n ${e}`)))}o=o.includes("</head>")?o.replace("</head>",`${e}</head>`):o,o=o.includes("</body>")?o.replace("</body>",`${t}</body>`):o+t,y=Buffer.from(o)}let v={"Content-Type":S,"Cache-Control":".html"===$||".ts"===$||".tsx"===$?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable"};if(/^(text\/|application\/(javascript|json|xml))/.test(S)&&y.length>1024){let{gzipSync:e}=w("zlib"),r=e(y);v["Content-Encoding"]="gzip",v["Content-Length"]=r.length,t.writeHead(200,v),t.end(r)}else t.writeHead(200,v),t.end(y);r.logging&&console.log(`[200] ${g(n.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 H=new o({server:C});H.on("connection",e=>{y.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 n=JSON.parse(t.toString());"state:subscribe"===n.type?($.subscribe(n.key,e),r.logging&&console.log(`[State] Client subscribed to "${n.key}"`)):"state:unsubscribe"===n.type?($.unsubscribe(n.key,e),r.logging&&console.log(`[State] Client unsubscribed from "${n.key}"`)):"state:change"===n.type&&($.handleStateChange(n.key,n.value),r.logging&&console.log(`[State] Client updated "${n.key}"`))}catch(e){r.logging&&console.error("[WebSocket] Message parse error:",e)}}),e.on("close",()=>{y.delete(e),$.unsubscribeAll(e),r.logging&&console.log("[HMR] Client disconnected")})});let x=v.flatMap(e=>r.watch.map(t=>h(e.root,t))),N=i(x,{ignored:r.ignore,ignoreInitial:!0,persistent:!0});N.on("change",e=>{r.logging&&console.log(`[HMR] File changed: ${e}`);let t=JSON.stringify({type:"update",path:e,timestamp:Date.now()});y.forEach(e=>e.readyState===n.OPEN&&e.send(t))}),N.on("add",e=>r.logging&&console.log(`[HMR] File added: ${e}`)),N.on("unlink",e=>r.logging&&console.log(`[HMR] File removed: ${e}`)),C.setMaxListeners(20),C.listen(r.port,r.host,()=>{if(r.logging){if(console.log("\n🚀 Elit Dev Server"),console.log(`\n ➜ Local: http://${r.host}:${r.port}`),v.length>1)console.log(" ➜ Clients:"),v.forEach(e=>{let t=`http://${r.host}:${r.port}${e.basePath}`;console.log(` - ${t} → ${e.root}`)});else{let e=v[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&&v.length>0){let e=v[0],t=`http://${r.host}:${r.port}${e.basePath}`;(async()=>{let{default:e}=await import("open");await e(t)})().catch(()=>{})}});let R=!1,M=v[0],A=`http://${r.host}:${r.port}${M.basePath}`;return{server:C,wss:H,url:A,state:$,close:async()=>{if(!R)return R=!0,r.logging&&console.log("\n[Server] Shutting down..."),await N.close(),H.close(),y.forEach(e=>e.close()),y.clear(),new Promise(e=>{C.close(()=>{r.logging&&console.log("[Server] Closed"),e()})})}}}export{$ as ServerRouter,D as SharedState,j as StateManager,R as bodyLimit,M as cacheControl,A as compress,E as cors,k as createDevServer,O as createProxyHandler,x as errorHandler,T as html,S as json,H as logger,N as rateLimit,P as security,C as status,v as text};
@@ -0,0 +1,109 @@
1
+ import { x as StateOptions, w as State, V as VNode, y as VirtualListController, C as Child, P as Props } from './types-DOAdFFJB.mjs';
2
+ import 'http';
3
+ import 'ws';
4
+
5
+ /**
6
+ * Elit - State Management
7
+ */
8
+
9
+ declare const createState: <T>(initial: T, options?: StateOptions) => State<T>;
10
+ declare const computed: <T extends any[], R>(states: { [K in keyof T]: State<T[K]>; }, fn: (...values: T) => R) => State<R>;
11
+ declare const effect: (fn: () => void) => void;
12
+ declare const batchRender: (container: string | HTMLElement, vNodes: VNode[]) => HTMLElement;
13
+ declare const renderChunked: (container: string | HTMLElement, vNodes: VNode[], chunkSize?: number, onProgress?: (current: number, total: number) => void) => HTMLElement;
14
+ declare const createVirtualList: <T>(container: HTMLElement, items: T[], renderItem: (item: T, index: number) => VNode, itemHeight?: number, bufferSize?: number) => VirtualListController;
15
+ declare const lazy: <T extends any[], R>(loadFn: () => Promise<(...args: T) => R>) => (...args: T) => Promise<VNode | R>;
16
+ declare const cleanupUnused: (root: HTMLElement) => number;
17
+ declare const throttle: <T extends any[]>(fn: (...args: T) => void, delay: number) => (...args: T) => void;
18
+ declare const debounce: <T extends any[]>(fn: (...args: T) => void, delay: number) => (...args: T) => void;
19
+ type StateChangeCallback<T = any> = (value: T, oldValue: T) => void;
20
+ /**
21
+ * Shared State - syncs with elit-server
22
+ */
23
+ declare class SharedState<T = any> {
24
+ readonly key: string;
25
+ private wsUrl?;
26
+ private localState;
27
+ private ws;
28
+ private pendingUpdates;
29
+ private previousValue;
30
+ constructor(key: string, defaultValue: T, wsUrl?: string | undefined);
31
+ /**
32
+ * Get current value
33
+ */
34
+ get value(): T;
35
+ /**
36
+ * Set new value and sync to server
37
+ */
38
+ set value(newValue: T);
39
+ /**
40
+ * Get the underlying Elit State (for reactive binding)
41
+ */
42
+ get state(): State<T>;
43
+ /**
44
+ * Subscribe to changes (returns Elit State for reactive)
45
+ */
46
+ onChange(callback: StateChangeCallback<T>): () => void;
47
+ /**
48
+ * Update value using a function
49
+ */
50
+ update(updater: (current: T) => T): void;
51
+ /**
52
+ * Connect to WebSocket
53
+ */
54
+ private connect;
55
+ /**
56
+ * Subscribe to server state
57
+ */
58
+ private subscribe;
59
+ /**
60
+ * Handle message from server
61
+ */
62
+ private handleMessage;
63
+ /**
64
+ * Send value to server
65
+ */
66
+ private sendToServer;
67
+ /**
68
+ * Disconnect
69
+ */
70
+ disconnect(): void;
71
+ /**
72
+ * Destroy state and cleanup
73
+ */
74
+ destroy(): void;
75
+ }
76
+ /**
77
+ * Create a shared state that syncs with elit-server
78
+ */
79
+ declare function createSharedState<T>(key: string, defaultValue: T, wsUrl?: string): SharedState<T>;
80
+ /**
81
+ * Shared State Manager for managing multiple shared states
82
+ */
83
+ declare class SharedStateManager {
84
+ private states;
85
+ /**
86
+ * Create or get a shared state
87
+ */
88
+ create<T>(key: string, defaultValue: T, wsUrl?: string): SharedState<T>;
89
+ /**
90
+ * Get existing state
91
+ */
92
+ get<T>(key: string): SharedState<T> | undefined;
93
+ /**
94
+ * Delete a state
95
+ */
96
+ delete(key: string): boolean;
97
+ /**
98
+ * Clear all states
99
+ */
100
+ clear(): void;
101
+ }
102
+ declare const sharedStateManager: SharedStateManager;
103
+ declare const reactive: <T>(state: State<T>, renderFn: (value: T) => VNode | Child) => VNode;
104
+ declare const reactiveAs: <T>(tagName: string, state: State<T>, renderFn: (value: T) => VNode | Child, props?: Props) => VNode;
105
+ declare const text: (state: State<any> | any) => VNode | string;
106
+ declare const bindValue: <T extends string | number>(state: State<T>) => Props;
107
+ declare const bindChecked: (state: State<boolean>) => Props;
108
+
109
+ export { SharedState, batchRender, bindChecked, bindValue, cleanupUnused, computed, createSharedState, createState, createVirtualList, debounce, effect, lazy, reactive, reactiveAs, renderChunked, sharedStateManager, text, throttle };
@@ -0,0 +1,109 @@
1
+ import { x as StateOptions, w as State, V as VNode, y as VirtualListController, C as Child, P as Props } from './types-DOAdFFJB.js';
2
+ import 'http';
3
+ import 'ws';
4
+
5
+ /**
6
+ * Elit - State Management
7
+ */
8
+
9
+ declare const createState: <T>(initial: T, options?: StateOptions) => State<T>;
10
+ declare const computed: <T extends any[], R>(states: { [K in keyof T]: State<T[K]>; }, fn: (...values: T) => R) => State<R>;
11
+ declare const effect: (fn: () => void) => void;
12
+ declare const batchRender: (container: string | HTMLElement, vNodes: VNode[]) => HTMLElement;
13
+ declare const renderChunked: (container: string | HTMLElement, vNodes: VNode[], chunkSize?: number, onProgress?: (current: number, total: number) => void) => HTMLElement;
14
+ declare const createVirtualList: <T>(container: HTMLElement, items: T[], renderItem: (item: T, index: number) => VNode, itemHeight?: number, bufferSize?: number) => VirtualListController;
15
+ declare const lazy: <T extends any[], R>(loadFn: () => Promise<(...args: T) => R>) => (...args: T) => Promise<VNode | R>;
16
+ declare const cleanupUnused: (root: HTMLElement) => number;
17
+ declare const throttle: <T extends any[]>(fn: (...args: T) => void, delay: number) => (...args: T) => void;
18
+ declare const debounce: <T extends any[]>(fn: (...args: T) => void, delay: number) => (...args: T) => void;
19
+ type StateChangeCallback<T = any> = (value: T, oldValue: T) => void;
20
+ /**
21
+ * Shared State - syncs with elit-server
22
+ */
23
+ declare class SharedState<T = any> {
24
+ readonly key: string;
25
+ private wsUrl?;
26
+ private localState;
27
+ private ws;
28
+ private pendingUpdates;
29
+ private previousValue;
30
+ constructor(key: string, defaultValue: T, wsUrl?: string | undefined);
31
+ /**
32
+ * Get current value
33
+ */
34
+ get value(): T;
35
+ /**
36
+ * Set new value and sync to server
37
+ */
38
+ set value(newValue: T);
39
+ /**
40
+ * Get the underlying Elit State (for reactive binding)
41
+ */
42
+ get state(): State<T>;
43
+ /**
44
+ * Subscribe to changes (returns Elit State for reactive)
45
+ */
46
+ onChange(callback: StateChangeCallback<T>): () => void;
47
+ /**
48
+ * Update value using a function
49
+ */
50
+ update(updater: (current: T) => T): void;
51
+ /**
52
+ * Connect to WebSocket
53
+ */
54
+ private connect;
55
+ /**
56
+ * Subscribe to server state
57
+ */
58
+ private subscribe;
59
+ /**
60
+ * Handle message from server
61
+ */
62
+ private handleMessage;
63
+ /**
64
+ * Send value to server
65
+ */
66
+ private sendToServer;
67
+ /**
68
+ * Disconnect
69
+ */
70
+ disconnect(): void;
71
+ /**
72
+ * Destroy state and cleanup
73
+ */
74
+ destroy(): void;
75
+ }
76
+ /**
77
+ * Create a shared state that syncs with elit-server
78
+ */
79
+ declare function createSharedState<T>(key: string, defaultValue: T, wsUrl?: string): SharedState<T>;
80
+ /**
81
+ * Shared State Manager for managing multiple shared states
82
+ */
83
+ declare class SharedStateManager {
84
+ private states;
85
+ /**
86
+ * Create or get a shared state
87
+ */
88
+ create<T>(key: string, defaultValue: T, wsUrl?: string): SharedState<T>;
89
+ /**
90
+ * Get existing state
91
+ */
92
+ get<T>(key: string): SharedState<T> | undefined;
93
+ /**
94
+ * Delete a state
95
+ */
96
+ delete(key: string): boolean;
97
+ /**
98
+ * Clear all states
99
+ */
100
+ clear(): void;
101
+ }
102
+ declare const sharedStateManager: SharedStateManager;
103
+ declare const reactive: <T>(state: State<T>, renderFn: (value: T) => VNode | Child) => VNode;
104
+ declare const reactiveAs: <T>(tagName: string, state: State<T>, renderFn: (value: T) => VNode | Child, props?: Props) => VNode;
105
+ declare const text: (state: State<any> | any) => VNode | string;
106
+ declare const bindValue: <T extends string | number>(state: State<T>) => Props;
107
+ declare const bindChecked: (state: State<boolean>) => Props;
108
+
109
+ export { SharedState, batchRender, bindChecked, bindValue, cleanupUnused, computed, createSharedState, createState, createVirtualList, debounce, effect, lazy, reactive, reactiveAs, renderChunked, sharedStateManager, text, throttle };
package/dist/state.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=new 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:n,children:s}=e,i="svg"===r||"s"===r[0]&&"v"===r[1]&&"g"===r[2]||"http://www.w3.org/2000/svg"===t.namespaceURI,l=i?document.createElementNS("http://www.w3.org/2000/svg",r.replace("svg","").toLowerCase()||r):document.createElement(r);for(let e in n){let t=n[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;i?l.setAttribute("class",e):l.className=e}else if(115===r&&5===e.length)if("string"==typeof t)l.style.cssText=t;else{let e=l.style;for(let r in t)e[r]=t[r]}else 111===r&&110===e.charCodeAt(1)?l[e.toLowerCase()]=t:100===r&&e.length>20?l.innerHTML=t.__html:114===r&&3===e.length?setTimeout(()=>{"function"==typeof t?t(l):t.current=l},0):l.setAttribute(e,!0===t?"":String(t))}let a=s.length;if(!a)return void t.appendChild(l);let o=e=>{for(let t=0;t<a;t++){let r=s[t];if(null!=r&&!1!==r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;t++){let n=r[t];null!=n&&!1!==n&&this.renderToDOM(n,e)}else this.renderToDOM(r,e)}};if(a>30){let e=document.createDocumentFragment();o(e),l.appendChild(e)}else o(l);t.appendChild(l)}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 n=t.length;if(n>3e3){let e=document.createDocumentFragment(),s=0,i=1500,l=()=>{let a=Math.min(s+i,n);for(let r=s;r<a;r++)this.renderToDOM(t[r],e);s=a,s>=n?r.appendChild(e):requestAnimationFrame(l)};l()}else{let e=document.createDocumentFragment();for(let r=0;r<n;r++)this.renderToDOM(t[r],e);r.appendChild(e)}return r}renderChunked(e,t,r=5e3,n){let s="string"==typeof e?document.getElementById(e.replace("#","")):e;if(!s)throw new Error(`Element not found: ${e}`);let i=t.length,l=0,a=()=>{let e=Math.min(l+r,i),o=document.createDocumentFragment();for(let r=l;r<e;r++)this.renderToDOM(t[r],o);s.appendChild(o),l=e,n&&n(l,i),l<i&&requestAnimationFrame(a)};return requestAnimationFrame(a),s}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,n=new Set,s=null,{throttle:i=0,deep:l=!1}=t,a=()=>n.forEach(e=>e(r));return{get value(){return r},set value(e){(l?JSON.stringify(r)!==JSON.stringify(e):r!==e)&&(r=e,i>0?s||(s=setTimeout(()=>{s=null,a()},i)):a())},subscribe:e=>(n.add(e),()=>n.delete(e)),destroy(){n.clear(),s&&clearTimeout(s)}}}computed(e,t){let r=e.map(e=>e.value),n=this.createState(t(...r));return e.forEach((e,s)=>{e.subscribe(e=>{r[s]=e,n.value=t(...r)})}),n}effect(e){e()}createVirtualList(e,t,r,n=50,s=5){let i=e.clientHeight,l=t.length*n,a=0,o=()=>{let{start:o,end:u}={start:Math.max(0,Math.floor(a/n)-s),end:Math.min(t.length,Math.ceil((a+i)/n)+s)},d=document.createElement("div");d.style.cssText=`height:${l}px;position:relative`;for(let e=o;e<u;e++){let s=document.createElement("div");s.style.cssText=`position:absolute;top:${e*n}px;height:${n}px;width:100%`,this.renderToDOM(r(t[e],e),s),d.appendChild(s)}e.innerHTML="",e.appendChild(d)},u=()=>{a=e.scrollTop,requestAnimationFrame(o)};return e.addEventListener("scroll",u),o(),{render:o,destroy:()=>{e.removeEventListener("scroll",u),e.innerHTML=""}}}lazy(e){let t=null,r=!1;return async(...n)=>(!t&&!r&&(r=!0,t=await e(),r=!1),t?t(...n):{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:n=0}=t,s=r?" ".repeat(n):"",i=r?"\n":"",l=this.resolveStateValue(e);if(l=this.unwrapReactive(l),Array.isArray(l))return l.map(e=>this.renderToString(e,t)).join("");if("object"!=typeof l||null===l)return null==l||!1===l?"":this.escapeHtml(String(l));let{tagName:a,props:o,children:u}=l,d=this.isSelfClosingTag(a),c=`${s}<${a}`,h=this.propsToAttributes(o);if(h&&(c+=` ${h}`),d)return c+=` />${i}`,c;if(c+=">",o.dangerouslySetInnerHTML)return c+=o.dangerouslySetInnerHTML.__html,c+=`</${a}>${i}`,c;if(u&&u.length>0){let e=u.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){c+=i;for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(c+=this.renderToString(e,{pretty:r,indent:n+1}));else c+=this.renderToString(t,{pretty:r,indent:n+1});c+=s}else for(let t of e)if(null!=t&&!1!==t)if(Array.isArray(t))for(let e of t)null!=e&&!1!==e&&(c+=this.renderToString(e,{pretty:!1,indent:0}));else c+=this.renderToString(t,{pretty:!1,indent:0})}return c+=`</${a}>${i}`,c}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,n=e.children&&1===e.children.length&&"string"==typeof e.children[0];if(r&&n)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 n=e[r];if(n=this.resolveStateValue(n),null!=n&&!1!==n&&(!r.startsWith("on")||"function"!=typeof n)){if("className"===r||"class"===r){let e=Array.isArray(n)?n.join(" "):n;e&&t.push(`class="${this.escapeHtml(String(e))}"`);continue}if("style"===r){let e=this.styleToString(n);e&&t.push(`style="${this.escapeHtml(e)}"`);continue}if(!0===n){t.push(r);continue}t.push(`${r}="${this.escapeHtml(String(n))}"`)}}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 n=r.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${n}:${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 n=t(e.value);r.node.textContent=String(n??"")}})}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:n}=e,s={};for(let e in r){let t=r[e];"class"===e?s.className=this.isState(t)?t.value:t:s[e]=this.isState(t)?t.value:t}let i=[];if(null!=n)if(Array.isArray(n))for(let e of n)if(this.isState(e))i.push(this.createReactiveChild(e,e=>e));else{let t=this.jsonToVNode(e);null!=t&&!1!==t&&i.push(t)}else if(this.isState(n))i.push(this.createReactiveChild(n,e=>e));else if("object"==typeof n&&"tag"in n){let e=this.jsonToVNode(n);null!=e&&!1!==e&&i.push(e)}else i.push(n);return{tagName:t,props:s,children:i}}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:n=[]}=e,s={};for(let e in r){let t=r[e];s[e]=this.isState(t)?t.value:t}let i=[];for(let e of n)if(this.isState(e))i.push(this.createReactiveChild(e,e=>e));else{let t=this.vNodeJsonToVNode(e);null!=t&&!1!==t&&i.push(t)}return{tagName:t,props:s,children:i}}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,n=null;for(let e of t.children||[])"object"==typeof e&&null!==e&&"tagName"in e&&("head"===e.tagName&&(r=e),"body"===e.tagName&&(n=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(n){if(document.body.innerHTML="",n.props)for(let e in n.props){let t=n.props[e];null!=t&&!1!==t&&document.body.setAttribute(e,String(t))}for(let e of n.children||[])this.renderToDOM(e,document.body)}}renderToHTMLDocument(e,t={}){let{title:r="",meta:n=[],links:s=[],scripts:i=[],styles:l=[],lang:a="en",head:o="",bodyAttrs:u={},pretty:d=!1}=t,c=d?"\n":"",h=d?" ":"",p=d?" ":"",f=`<!DOCTYPE html>${c}<html lang="${a}">${c}${h}<head>${c}${p}<meta charset="UTF-8">${c}${p}<meta name="viewport" content="width=device-width, initial-scale=1.0">${c}`;r&&(f+=`${p}<title>${this.escapeHtml(r)}</title>${c}`);for(let e of n){f+=`${p}<meta`;for(let t in e)f+=` ${t}="${this.escapeHtml(e[t])}"`;f+=`>${c}`}for(let e of s){f+=`${p}<link`;for(let t in e)f+=` ${t}="${this.escapeHtml(e[t])}"`;f+=`>${c}`}for(let e of l)e.href?f+=`${p}<link rel="stylesheet" href="${this.escapeHtml(e.href)}">${c}`:e.content&&(f+=`${p}<style>${e.content}</style>${c}`);o&&(f+=o+c),f+=`${h}</head>${c}${h}<body`;for(let e in u)f+=` ${e}="${this.escapeHtml(u[e])}"`;f+=`>${c}`,f+=this.renderToString(e,{pretty:d,indent:2});for(let e of i)f+=`${p}<script`,e.type&&(f+=` type="${this.escapeHtml(e.type)}"`),e.async&&(f+=" async"),e.defer&&(f+=" defer"),e.src?f+=` src="${this.escapeHtml(e.src)}"><\/script>${c}`:e.content?f+=`>${e.content}<\/script>${c}`:f+=`><\/script>${c}`;return f+=`${h}</body>${c}</html>`,f}getElementCache(){return this.elementCache}},t=(t,r)=>e.createState(t,r),r=class{constructor(e,r,n){this.key=e,this.wsUrl=n,this.ws=null,this.pendingUpdates=[],this.localState=t(r),this.previousValue=r,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()}};var n=new class{constructor(){this.states=new Map}create(e,t,n){if(this.states.has(e))return this.states.get(e);let s=new r(e,t,n);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()}},s=(t,r)=>{let n=null,s=null,i=null,l=!0,a=r(t.value),o=a&&"object"==typeof a&&"tagName"in a,u=null==a||!1===a;t.subscribe(()=>{n&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{(()=>{if(!s&&!i)return;let n=r(t.value);if(null==n||!1===n)l&&s&&(i=document.createComment("reactive"),s.parentNode?.replaceChild(i,s),l=!1);else if(!l&&i&&s&&(i.parentNode?.replaceChild(s,i),i=null,l=!0),s){let t=document.createDocumentFragment();if(o&&n&&"object"==typeof n&&"tagName"in n){let{props:r,children:i}=n;for(let e in r){let t=r[e];if("ref"!==e)if("class"===e||"className"===e)s.className=Array.isArray(t)?t.join(" "):t||"";else if("style"===e&&"object"==typeof t){let e=s.style;for(let r in t)e[r]=t[r]}else e.startsWith("on")?s[e.toLowerCase()]=t:null!=t&&!1!==t?s.setAttribute(e,String(!0===t?"":t)):s.removeAttribute(e)}for(let r of i)e.renderToDOM(r,t)}else e.renderToDOM(n,t);s.textContent="",s.appendChild(t),e.getElementCache().set(s,!0)}})(),n=null})});let d=e=>{s=e,u&&e.parentNode&&(i=document.createComment("reactive"),e.parentNode.replaceChild(i,e),l=!1)};if(o){let e=a;return{tagName:e.tagName,props:{...e.props,ref:d},children:e.children}}return{tagName:"span",props:{ref:d},children:[a]}};exports.SharedState=r,exports.batchRender=(t,r)=>e.batchRender(t,r),exports.bindChecked=e=>({checked:e.value,onchange:t=>{e.value=t.target.checked}}),exports.bindValue=e=>({value:e.value,oninput:t=>{e.value=t.target.value}}),exports.cleanupUnused=t=>e.cleanupUnusedElements(t),exports.computed=(t,r)=>e.computed(t,r),exports.createSharedState=function(e,t,n){return new r(e,t,n)},exports.createState=t,exports.createVirtualList=(t,r,n,s,i)=>e.createVirtualList(t,r,n,s,i),exports.debounce=(e,t)=>{let r=null;return(...n)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...n),t)}},exports.effect=t=>e.effect(t),exports.lazy=t=>e.lazy(t),exports.reactive=s,exports.reactiveAs=(t,r,n,s={})=>{let i=null,l=null;return r.subscribe(()=>{i&&cancelAnimationFrame(i),i=requestAnimationFrame(()=>{if(l){let t=document.createDocumentFragment(),s=n(r.value);null==s||!1===s?(l.style.display="none",l.textContent=""):(l.style.display="",e.renderToDOM(s,t),l.textContent="",l.appendChild(t)),e.getElementCache().set(l,!0)}i=null})}),{tagName:t,props:{...s,ref:e=>{l=e}},children:[n(r.value)]}},exports.renderChunked=(t,r,n,s)=>e.renderChunked(t,r,n,s),exports.sharedStateManager=n,exports.text=e=>e&&void 0!==e.value?s(e,e=>({tagName:"span",props:{},children:[String(e)]})):String(e),exports.throttle=(e,t)=>{let r=null;return(...n)=>{r||(r=setTimeout(()=>{r=null,e(...n)},t))}};