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