elit 3.1.5 → 3.1.7

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.
@@ -0,0 +1,1197 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/runtime.ts
34
+ var runtime, isNode, isBun, isDeno;
35
+ var init_runtime = __esm({
36
+ "src/runtime.ts"() {
37
+ "use strict";
38
+ runtime = (() => {
39
+ if (typeof Deno !== "undefined") return "deno";
40
+ if (typeof Bun !== "undefined") return "bun";
41
+ return "node";
42
+ })();
43
+ isNode = runtime === "node";
44
+ isBun = runtime === "bun";
45
+ isDeno = runtime === "deno";
46
+ }
47
+ });
48
+
49
+ // src/http.ts
50
+ var import_node_events, http, https;
51
+ var init_http = __esm({
52
+ "src/http.ts"() {
53
+ "use strict";
54
+ import_node_events = require("events");
55
+ init_runtime();
56
+ if (isNode && typeof process !== "undefined") {
57
+ try {
58
+ http = require("http");
59
+ https = require("https");
60
+ } catch (e) {
61
+ http = require("http");
62
+ https = require("https");
63
+ }
64
+ }
65
+ }
66
+ });
67
+
68
+ // src/fs.ts
69
+ var fs, fsPromises;
70
+ var init_fs = __esm({
71
+ "src/fs.ts"() {
72
+ "use strict";
73
+ init_runtime();
74
+ if (isNode) {
75
+ fs = require("fs");
76
+ fsPromises = require("fs/promises");
77
+ }
78
+ }
79
+ });
80
+
81
+ // src/database.ts
82
+ var database_exports = {};
83
+ __export(database_exports, {
84
+ Database: () => Database,
85
+ database: () => database2,
86
+ default: () => database_default
87
+ });
88
+ module.exports = __toCommonJS(database_exports);
89
+ var import_node_vm = __toESM(require("vm"));
90
+
91
+ // src/path.ts
92
+ init_runtime();
93
+ function getSeparator(isWin) {
94
+ return isWin ? "\\" : "/";
95
+ }
96
+ function getCwd() {
97
+ if (isNode || isBun) {
98
+ return process.cwd();
99
+ } else if (isDeno) {
100
+ return Deno.cwd();
101
+ }
102
+ return "/";
103
+ }
104
+ function findLastSeparator(path2) {
105
+ return Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\"));
106
+ }
107
+ function createPathOps(isWin) {
108
+ return {
109
+ sep: getSeparator(isWin),
110
+ delimiter: isWin ? ";" : ":",
111
+ normalize: (path2) => normalizePath(path2, isWin),
112
+ join: (...paths) => joinPaths(paths, isWin),
113
+ resolve: (...paths) => resolvePaths(paths, isWin),
114
+ isAbsolute: (path2) => isWin ? isAbsoluteWin(path2) : isAbsolutePosix(path2),
115
+ relative: (from, to) => relativePath(from, to, isWin),
116
+ dirname: (path2) => getDirname(path2, isWin),
117
+ basename: (path2, ext) => getBasename(path2, ext, isWin),
118
+ extname: (path2) => getExtname(path2),
119
+ parse: (path2) => parsePath(path2, isWin),
120
+ format: (pathObject) => formatPath(pathObject, isWin)
121
+ };
122
+ }
123
+ function isAbsolutePosix(path2) {
124
+ return path2.length > 0 && path2[0] === "/";
125
+ }
126
+ function isAbsoluteWin(path2) {
127
+ const len = path2.length;
128
+ if (len === 0) return false;
129
+ const code = path2.charCodeAt(0);
130
+ if (code === 47 || code === 92) {
131
+ return true;
132
+ }
133
+ if (code >= 65 && code <= 90 || code >= 97 && code <= 122) {
134
+ if (len > 2 && path2.charCodeAt(1) === 58) {
135
+ const code2 = path2.charCodeAt(2);
136
+ if (code2 === 47 || code2 === 92) {
137
+ return true;
138
+ }
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ var isWindows = (() => {
144
+ if (isNode) {
145
+ return process.platform === "win32";
146
+ } else if (isDeno) {
147
+ return Deno.build.os === "windows";
148
+ }
149
+ return typeof process !== "undefined" && process.platform === "win32";
150
+ })();
151
+ var posix = createPathOps(false);
152
+ var win32 = createPathOps(true);
153
+ function normalizePath(path2, isWin) {
154
+ if (path2.length === 0) return ".";
155
+ const separator = getSeparator(isWin);
156
+ const isAbsolute = isWin ? isAbsoluteWin(path2) : isAbsolutePosix(path2);
157
+ const trailingSeparator = path2[path2.length - 1] === separator || isWin && path2[path2.length - 1] === "/";
158
+ let normalized = path2.replace(isWin ? /[\/\\]+/g : /\/+/g, separator);
159
+ const parts = normalized.split(separator);
160
+ const result = [];
161
+ for (let i = 0; i < parts.length; i++) {
162
+ const part = parts[i];
163
+ if (part === "" || part === ".") {
164
+ if (i === 0 && isAbsolute) result.push("");
165
+ continue;
166
+ }
167
+ if (part === "..") {
168
+ if (result.length > 0 && result[result.length - 1] !== "..") {
169
+ if (!(result.length === 1 && result[0] === "")) {
170
+ result.pop();
171
+ }
172
+ } else if (!isAbsolute) {
173
+ result.push("..");
174
+ }
175
+ } else {
176
+ result.push(part);
177
+ }
178
+ }
179
+ let final = result.join(separator);
180
+ if (final.length === 0) {
181
+ return isAbsolute ? separator : ".";
182
+ }
183
+ if (trailingSeparator && final[final.length - 1] !== separator) {
184
+ final += separator;
185
+ }
186
+ return final;
187
+ }
188
+ function joinPaths(paths, isWin) {
189
+ if (paths.length === 0) return ".";
190
+ const separator = getSeparator(isWin);
191
+ let joined = "";
192
+ for (let i = 0; i < paths.length; i++) {
193
+ const path2 = paths[i];
194
+ if (path2 && path2.length > 0) {
195
+ if (joined.length === 0) {
196
+ joined = path2;
197
+ } else {
198
+ joined += separator + path2;
199
+ }
200
+ }
201
+ }
202
+ if (joined.length === 0) return ".";
203
+ return normalizePath(joined, isWin);
204
+ }
205
+ function resolvePaths(paths, isWin) {
206
+ const separator = getSeparator(isWin);
207
+ let resolved = "";
208
+ let isAbsolute = false;
209
+ for (let i = paths.length - 1; i >= 0 && !isAbsolute; i--) {
210
+ const path2 = paths[i];
211
+ if (path2 && path2.length > 0) {
212
+ resolved = path2 + (resolved.length > 0 ? separator + resolved : "");
213
+ isAbsolute = isWin ? isAbsoluteWin(resolved) : isAbsolutePosix(resolved);
214
+ }
215
+ }
216
+ if (!isAbsolute) {
217
+ const cwd = getCwd();
218
+ resolved = cwd + (resolved.length > 0 ? separator + resolved : "");
219
+ }
220
+ return normalizePath(resolved, isWin);
221
+ }
222
+ function relativePath(from, to, isWin) {
223
+ from = resolvePaths([from], isWin);
224
+ to = resolvePaths([to], isWin);
225
+ if (from === to) return "";
226
+ const separator = getSeparator(isWin);
227
+ const fromParts = from.split(separator).filter((p) => p.length > 0);
228
+ const toParts = to.split(separator).filter((p) => p.length > 0);
229
+ let commonLength = 0;
230
+ const minLength = Math.min(fromParts.length, toParts.length);
231
+ for (let i = 0; i < minLength; i++) {
232
+ if (fromParts[i] === toParts[i]) {
233
+ commonLength++;
234
+ } else {
235
+ break;
236
+ }
237
+ }
238
+ const upCount = fromParts.length - commonLength;
239
+ const result = [];
240
+ for (let i = 0; i < upCount; i++) {
241
+ result.push("..");
242
+ }
243
+ for (let i = commonLength; i < toParts.length; i++) {
244
+ result.push(toParts[i]);
245
+ }
246
+ return result.join(separator) || ".";
247
+ }
248
+ function getDirname(path2, isWin) {
249
+ if (path2.length === 0) return ".";
250
+ const separator = getSeparator(isWin);
251
+ const normalized = normalizePath(path2, isWin);
252
+ const lastSepIndex = normalized.lastIndexOf(separator);
253
+ if (lastSepIndex === -1) return ".";
254
+ if (lastSepIndex === 0) return separator;
255
+ return normalized.slice(0, lastSepIndex);
256
+ }
257
+ function getBasename(path2, ext, isWin) {
258
+ if (path2.length === 0) return "";
259
+ const lastSepIndex = isWin ? findLastSeparator(path2) : path2.lastIndexOf("/");
260
+ let base = lastSepIndex === -1 ? path2 : path2.slice(lastSepIndex + 1);
261
+ if (ext && base.endsWith(ext)) {
262
+ base = base.slice(0, base.length - ext.length);
263
+ }
264
+ return base;
265
+ }
266
+ function getExtname(path2) {
267
+ const lastDotIndex = path2.lastIndexOf(".");
268
+ const lastSepIndex = findLastSeparator(path2);
269
+ if (lastDotIndex === -1 || lastDotIndex < lastSepIndex || lastDotIndex === path2.length - 1) {
270
+ return "";
271
+ }
272
+ return path2.slice(lastDotIndex);
273
+ }
274
+ function parsePath(path2, isWin) {
275
+ let root = "";
276
+ if (isWin) {
277
+ if (path2.length >= 2 && path2[1] === ":") {
278
+ root = path2.slice(0, 2);
279
+ if (path2.length > 2 && (path2[2] === "\\" || path2[2] === "/")) {
280
+ root += "\\";
281
+ }
282
+ } else if (path2[0] === "\\" || path2[0] === "/") {
283
+ root = "\\";
284
+ }
285
+ } else {
286
+ if (path2[0] === "/") {
287
+ root = "/";
288
+ }
289
+ }
290
+ const dir = getDirname(path2, isWin);
291
+ const base = getBasename(path2, void 0, isWin);
292
+ const ext = getExtname(path2);
293
+ const name = ext ? base.slice(0, base.length - ext.length) : base;
294
+ return { root, dir, base, ext, name };
295
+ }
296
+ function formatPath(pathObject, isWin) {
297
+ const separator = getSeparator(isWin);
298
+ const dir = pathObject.dir || pathObject.root || "";
299
+ const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
300
+ if (!dir) return base;
301
+ if (dir === pathObject.root) return dir + base;
302
+ return dir + separator + base;
303
+ }
304
+ function resolve(...paths) {
305
+ return resolvePaths(paths, isWindows);
306
+ }
307
+
308
+ // src/database.ts
309
+ var import_node_path = __toESM(require("path"));
310
+ var import_node_fs = __toESM(require("fs"));
311
+
312
+ // src/server.ts
313
+ init_http();
314
+
315
+ // src/https.ts
316
+ var import_events = require("events");
317
+ init_runtime();
318
+
319
+ // src/ws.ts
320
+ var import_events2 = require("events");
321
+ init_runtime();
322
+
323
+ // src/chokidar.ts
324
+ var import_events3 = require("events");
325
+ init_runtime();
326
+
327
+ // src/server.ts
328
+ init_fs();
329
+
330
+ // src/mime-types.ts
331
+ init_runtime();
332
+ var MIME_TYPES = {
333
+ // Text
334
+ "txt": "text/plain",
335
+ "html": "text/html",
336
+ "htm": "text/html",
337
+ "css": "text/css",
338
+ "js": "text/javascript",
339
+ "mjs": "text/javascript",
340
+ "json": "application/json",
341
+ "xml": "application/xml",
342
+ "csv": "text/csv",
343
+ "md": "text/markdown",
344
+ "markdown": "text/x-markdown",
345
+ // Images
346
+ "png": "image/png",
347
+ "jpg": "image/jpeg",
348
+ "jpeg": "image/jpeg",
349
+ "gif": "image/gif",
350
+ "svg": "image/svg+xml",
351
+ "webp": "image/webp",
352
+ "ico": "image/x-icon",
353
+ "bmp": "image/bmp",
354
+ "tiff": "image/tiff",
355
+ "tif": "image/tiff",
356
+ // Audio
357
+ "mp3": "audio/mpeg",
358
+ "wav": "audio/wav",
359
+ "ogg": "audio/ogg",
360
+ "aac": "audio/aac",
361
+ "m4a": "audio/mp4",
362
+ "flac": "audio/flac",
363
+ // Video
364
+ "mp4": "video/mp4",
365
+ "webm": "video/webm",
366
+ "avi": "video/x-msvideo",
367
+ "mov": "video/quicktime",
368
+ "mkv": "video/x-matroska",
369
+ "flv": "video/x-flv",
370
+ // Application
371
+ "pdf": "application/pdf",
372
+ "zip": "application/zip",
373
+ "gz": "application/gzip",
374
+ "tar": "application/x-tar",
375
+ "rar": "application/x-rar-compressed",
376
+ "7z": "application/x-7z-compressed",
377
+ // Documents
378
+ "doc": "application/msword",
379
+ "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
380
+ "xls": "application/vnd.ms-excel",
381
+ "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
382
+ "ppt": "application/vnd.ms-powerpoint",
383
+ "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
384
+ // Fonts
385
+ "woff": "font/woff",
386
+ "woff2": "font/woff2",
387
+ "ttf": "font/ttf",
388
+ "otf": "font/otf",
389
+ "eot": "application/vnd.ms-fontobject",
390
+ // Web
391
+ "wasm": "application/wasm",
392
+ "manifest": "application/manifest+json",
393
+ // Binary
394
+ "bin": "application/octet-stream",
395
+ "exe": "application/x-msdownload",
396
+ "dll": "application/x-msdownload",
397
+ // TypeScript/Modern JS
398
+ "ts": "text/typescript",
399
+ "tsx": "text/tsx",
400
+ "jsx": "text/jsx"
401
+ };
402
+ var TYPE_TO_EXTENSIONS = {};
403
+ for (const ext in MIME_TYPES) {
404
+ const type = MIME_TYPES[ext];
405
+ if (!TYPE_TO_EXTENSIONS[type]) {
406
+ TYPE_TO_EXTENSIONS[type] = [];
407
+ }
408
+ TYPE_TO_EXTENSIONS[type].push(ext);
409
+ }
410
+
411
+ // src/server.ts
412
+ init_runtime();
413
+
414
+ // src/dom.ts
415
+ function resolveElement(rootElement) {
416
+ return typeof rootElement === "string" ? document.getElementById(rootElement.replace("#", "")) : rootElement;
417
+ }
418
+ function ensureElement(el, rootElement) {
419
+ if (!el) {
420
+ throw new Error(`Element not found: ${rootElement}`);
421
+ }
422
+ return el;
423
+ }
424
+ function shouldSkipChild(child) {
425
+ return child == null || child === false;
426
+ }
427
+ function isPrimitiveJson(json) {
428
+ return json == null || typeof json === "boolean" || typeof json === "string" || typeof json === "number";
429
+ }
430
+ var DomNode = class {
431
+ constructor() {
432
+ this.elementCache = /* @__PURE__ */ new WeakMap();
433
+ this.reactiveNodes = /* @__PURE__ */ new Map();
434
+ }
435
+ createElement(tagName, props = {}, children = []) {
436
+ return { tagName, props, children };
437
+ }
438
+ renderToDOM(vNode, parent) {
439
+ if (vNode == null || vNode === false) return;
440
+ if (typeof vNode !== "object") {
441
+ parent.appendChild(document.createTextNode(String(vNode)));
442
+ return;
443
+ }
444
+ const { tagName, props, children } = vNode;
445
+ const isSVG = tagName === "svg" || tagName[0] === "s" && tagName[1] === "v" && tagName[2] === "g" || parent.namespaceURI === "http://www.w3.org/2000/svg";
446
+ const el = isSVG ? document.createElementNS("http://www.w3.org/2000/svg", tagName.replace("svg", "").toLowerCase() || tagName) : document.createElement(tagName);
447
+ for (const key in props) {
448
+ const value = props[key];
449
+ if (value == null || value === false) continue;
450
+ const c = key.charCodeAt(0);
451
+ if (c === 99 && (key.length < 6 || key[5] === "N")) {
452
+ const classValue = Array.isArray(value) ? value.join(" ") : value;
453
+ isSVG ? el.setAttribute("class", classValue) : el.className = classValue;
454
+ } else if (c === 115 && key.length === 5) {
455
+ if (typeof value === "string") {
456
+ el.style.cssText = value;
457
+ } else {
458
+ const s = el.style;
459
+ for (const k in value) s[k] = value[k];
460
+ }
461
+ } else if (c === 111 && key.charCodeAt(1) === 110) {
462
+ el[key.toLowerCase()] = value;
463
+ } else if (c === 100 && key.length > 20) {
464
+ el.innerHTML = value.__html;
465
+ } else if (c === 114 && key.length === 3) {
466
+ setTimeout(() => {
467
+ typeof value === "function" ? value(el) : value.current = el;
468
+ }, 0);
469
+ } else {
470
+ el.setAttribute(key, value === true ? "" : String(value));
471
+ }
472
+ }
473
+ const len = children.length;
474
+ if (!len) {
475
+ parent.appendChild(el);
476
+ return;
477
+ }
478
+ const renderChildren = (target) => {
479
+ for (let i = 0; i < len; i++) {
480
+ const child = children[i];
481
+ if (shouldSkipChild(child)) continue;
482
+ if (Array.isArray(child)) {
483
+ for (let j = 0, cLen = child.length; j < cLen; j++) {
484
+ const c = child[j];
485
+ !shouldSkipChild(c) && this.renderToDOM(c, target);
486
+ }
487
+ } else {
488
+ this.renderToDOM(child, target);
489
+ }
490
+ }
491
+ };
492
+ if (len > 30) {
493
+ const fragment = document.createDocumentFragment();
494
+ renderChildren(fragment);
495
+ el.appendChild(fragment);
496
+ } else {
497
+ renderChildren(el);
498
+ }
499
+ parent.appendChild(el);
500
+ }
501
+ render(rootElement, vNode) {
502
+ const el = ensureElement(resolveElement(rootElement), rootElement);
503
+ el.innerHTML = "";
504
+ if (vNode.children && vNode.children.length > 500) {
505
+ const fragment = document.createDocumentFragment();
506
+ this.renderToDOM(vNode, fragment);
507
+ el.appendChild(fragment);
508
+ } else {
509
+ this.renderToDOM(vNode, el);
510
+ }
511
+ return el;
512
+ }
513
+ batchRender(rootElement, vNodes) {
514
+ const el = ensureElement(resolveElement(rootElement), rootElement);
515
+ const len = vNodes.length;
516
+ if (len > 3e3) {
517
+ const fragment = document.createDocumentFragment();
518
+ let processed = 0;
519
+ const chunkSize = 1500;
520
+ const processChunk = () => {
521
+ const end = Math.min(processed + chunkSize, len);
522
+ for (let i = processed; i < end; i++) {
523
+ this.renderToDOM(vNodes[i], fragment);
524
+ }
525
+ processed = end;
526
+ if (processed >= len) {
527
+ el.appendChild(fragment);
528
+ } else {
529
+ requestAnimationFrame(processChunk);
530
+ }
531
+ };
532
+ processChunk();
533
+ } else {
534
+ const fragment = document.createDocumentFragment();
535
+ for (let i = 0; i < len; i++) {
536
+ this.renderToDOM(vNodes[i], fragment);
537
+ }
538
+ el.appendChild(fragment);
539
+ }
540
+ return el;
541
+ }
542
+ renderChunked(rootElement, vNodes, chunkSize = 5e3, onProgress) {
543
+ const el = ensureElement(resolveElement(rootElement), rootElement);
544
+ const len = vNodes.length;
545
+ let index = 0;
546
+ const renderChunk = () => {
547
+ const end = Math.min(index + chunkSize, len);
548
+ const fragment = document.createDocumentFragment();
549
+ for (let i = index; i < end; i++) {
550
+ this.renderToDOM(vNodes[i], fragment);
551
+ }
552
+ el.appendChild(fragment);
553
+ index = end;
554
+ if (onProgress) onProgress(index, len);
555
+ if (index < len) {
556
+ requestAnimationFrame(renderChunk);
557
+ }
558
+ };
559
+ requestAnimationFrame(renderChunk);
560
+ return el;
561
+ }
562
+ renderToHead(...vNodes) {
563
+ const head = document.head;
564
+ if (head) {
565
+ for (const vNode of vNodes.flat()) {
566
+ vNode && this.renderToDOM(vNode, head);
567
+ }
568
+ }
569
+ return head;
570
+ }
571
+ addStyle(cssText) {
572
+ const el = document.createElement("style");
573
+ el.textContent = cssText;
574
+ return document.head.appendChild(el);
575
+ }
576
+ addMeta(attrs) {
577
+ const el = document.createElement("meta");
578
+ for (const k in attrs) el.setAttribute(k, attrs[k]);
579
+ return document.head.appendChild(el);
580
+ }
581
+ addLink(attrs) {
582
+ const el = document.createElement("link");
583
+ for (const k in attrs) el.setAttribute(k, attrs[k]);
584
+ return document.head.appendChild(el);
585
+ }
586
+ setTitle(text) {
587
+ return document.title = text;
588
+ }
589
+ // Reactive State Management
590
+ createState(initialValue, options = {}) {
591
+ let value = initialValue;
592
+ const listeners = /* @__PURE__ */ new Set();
593
+ let updateTimer = null;
594
+ const { throttle = 0, deep = false } = options;
595
+ const notify = () => listeners.forEach((fn) => fn(value));
596
+ const scheduleUpdate = () => {
597
+ if (throttle > 0) {
598
+ if (!updateTimer) {
599
+ updateTimer = setTimeout(() => {
600
+ updateTimer = null;
601
+ notify();
602
+ }, throttle);
603
+ }
604
+ } else {
605
+ notify();
606
+ }
607
+ };
608
+ return {
609
+ get value() {
610
+ return value;
611
+ },
612
+ set value(newValue) {
613
+ const changed = deep ? JSON.stringify(value) !== JSON.stringify(newValue) : value !== newValue;
614
+ if (changed) {
615
+ value = newValue;
616
+ scheduleUpdate();
617
+ }
618
+ },
619
+ subscribe(fn) {
620
+ listeners.add(fn);
621
+ return () => listeners.delete(fn);
622
+ },
623
+ destroy() {
624
+ listeners.clear();
625
+ updateTimer && clearTimeout(updateTimer);
626
+ }
627
+ };
628
+ }
629
+ computed(states, computeFn) {
630
+ const values = states.map((s) => s.value);
631
+ const result = this.createState(computeFn(...values));
632
+ states.forEach((state, index) => {
633
+ state.subscribe((newValue) => {
634
+ values[index] = newValue;
635
+ result.value = computeFn(...values);
636
+ });
637
+ });
638
+ return result;
639
+ }
640
+ effect(stateFn) {
641
+ stateFn();
642
+ }
643
+ // Virtual scrolling helper for large lists
644
+ createVirtualList(container, items, renderItem, itemHeight = 50, bufferSize = 5) {
645
+ const viewportHeight = container.clientHeight;
646
+ const totalHeight = items.length * itemHeight;
647
+ let scrollTop = 0;
648
+ const getVisibleRange = () => {
649
+ const start = Math.max(0, Math.floor(scrollTop / itemHeight) - bufferSize);
650
+ const end = Math.min(items.length, Math.ceil((scrollTop + viewportHeight) / itemHeight) + bufferSize);
651
+ return { start, end };
652
+ };
653
+ const render2 = () => {
654
+ const { start, end } = getVisibleRange();
655
+ const wrapper = document.createElement("div");
656
+ wrapper.style.cssText = `height:${totalHeight}px;position:relative`;
657
+ for (let i = start; i < end; i++) {
658
+ const itemEl = document.createElement("div");
659
+ itemEl.style.cssText = `position:absolute;top:${i * itemHeight}px;height:${itemHeight}px;width:100%`;
660
+ this.renderToDOM(renderItem(items[i], i), itemEl);
661
+ wrapper.appendChild(itemEl);
662
+ }
663
+ container.innerHTML = "";
664
+ container.appendChild(wrapper);
665
+ };
666
+ const scrollHandler = () => {
667
+ scrollTop = container.scrollTop;
668
+ requestAnimationFrame(render2);
669
+ };
670
+ container.addEventListener("scroll", scrollHandler);
671
+ render2();
672
+ return {
673
+ render: render2,
674
+ destroy: () => {
675
+ container.removeEventListener("scroll", scrollHandler);
676
+ container.innerHTML = "";
677
+ }
678
+ };
679
+ }
680
+ // Lazy load components
681
+ lazy(loadFn) {
682
+ let component = null;
683
+ let loading = false;
684
+ return async (...args) => {
685
+ if (!component && !loading) {
686
+ loading = true;
687
+ component = await loadFn();
688
+ loading = false;
689
+ }
690
+ return component ? component(...args) : { tagName: "div", props: { class: "loading" }, children: ["Loading..."] };
691
+ };
692
+ }
693
+ // Memory management - cleanup unused elements
694
+ cleanupUnusedElements(root) {
695
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
696
+ const toRemove = [];
697
+ while (walker.nextNode()) {
698
+ const node = walker.currentNode;
699
+ if (node.id && node.id.startsWith("r") && !this.elementCache.has(node)) {
700
+ toRemove.push(node);
701
+ }
702
+ }
703
+ toRemove.forEach((el) => el.remove());
704
+ return toRemove.length;
705
+ }
706
+ // Server-Side Rendering - convert VNode to HTML string
707
+ renderToString(vNode, options = {}) {
708
+ const { pretty = false, indent = 0 } = options;
709
+ const indentStr = pretty ? " ".repeat(indent) : "";
710
+ const newLine = pretty ? "\n" : "";
711
+ let resolvedVNode = this.resolveStateValue(vNode);
712
+ resolvedVNode = this.unwrapReactive(resolvedVNode);
713
+ if (Array.isArray(resolvedVNode)) {
714
+ return resolvedVNode.map((child) => this.renderToString(child, options)).join("");
715
+ }
716
+ if (typeof resolvedVNode !== "object" || resolvedVNode === null) {
717
+ if (resolvedVNode === null || resolvedVNode === void 0 || resolvedVNode === false) {
718
+ return "";
719
+ }
720
+ return this.escapeHtml(String(resolvedVNode));
721
+ }
722
+ const { tagName, props, children } = resolvedVNode;
723
+ const isSelfClosing = this.isSelfClosingTag(tagName);
724
+ let html = `${indentStr}<${tagName}`;
725
+ const attrs = this.propsToAttributes(props);
726
+ if (attrs) {
727
+ html += ` ${attrs}`;
728
+ }
729
+ if (isSelfClosing) {
730
+ html += ` />${newLine}`;
731
+ return html;
732
+ }
733
+ html += ">";
734
+ if (props.dangerouslySetInnerHTML) {
735
+ html += props.dangerouslySetInnerHTML.__html;
736
+ html += `</${tagName}>${newLine}`;
737
+ return html;
738
+ }
739
+ if (children && children.length > 0) {
740
+ const resolvedChildren = children.map((c) => {
741
+ const resolved = this.resolveStateValue(c);
742
+ return this.unwrapReactive(resolved);
743
+ });
744
+ const hasComplexChildren = resolvedChildren.some(
745
+ (c) => typeof c === "object" && c !== null && !Array.isArray(c) && "tagName" in c
746
+ );
747
+ if (pretty && hasComplexChildren) {
748
+ html += newLine;
749
+ for (const child of resolvedChildren) {
750
+ if (shouldSkipChild(child)) continue;
751
+ if (Array.isArray(child)) {
752
+ for (const c of child) {
753
+ if (!shouldSkipChild(c)) {
754
+ html += this.renderToString(c, { pretty, indent: indent + 1 });
755
+ }
756
+ }
757
+ } else {
758
+ html += this.renderToString(child, { pretty, indent: indent + 1 });
759
+ }
760
+ }
761
+ html += indentStr;
762
+ } else {
763
+ for (const child of resolvedChildren) {
764
+ if (shouldSkipChild(child)) continue;
765
+ if (Array.isArray(child)) {
766
+ for (const c of child) {
767
+ if (!shouldSkipChild(c)) {
768
+ html += this.renderToString(c, { pretty: false, indent: 0 });
769
+ }
770
+ }
771
+ } else {
772
+ html += this.renderToString(child, { pretty: false, indent: 0 });
773
+ }
774
+ }
775
+ }
776
+ }
777
+ html += `</${tagName}>${newLine}`;
778
+ return html;
779
+ }
780
+ resolveStateValue(value) {
781
+ if (value && typeof value === "object" && "value" in value && "subscribe" in value) {
782
+ return value.value;
783
+ }
784
+ return value;
785
+ }
786
+ isReactiveWrapper(vNode) {
787
+ if (!vNode || typeof vNode !== "object" || !vNode.tagName) {
788
+ return false;
789
+ }
790
+ return vNode.tagName === "span" && vNode.props?.id && typeof vNode.props.id === "string" && vNode.props.id.match(/^r[a-z0-9]{9}$/);
791
+ }
792
+ unwrapReactive(vNode) {
793
+ if (!this.isReactiveWrapper(vNode)) {
794
+ return vNode;
795
+ }
796
+ const children = vNode.children;
797
+ if (!children || children.length === 0) {
798
+ return "";
799
+ }
800
+ if (children.length === 1) {
801
+ const child = children[0];
802
+ if (child && typeof child === "object" && child.tagName === "span") {
803
+ const props = child.props;
804
+ const hasNoProps = !props || Object.keys(props).length === 0;
805
+ const hasSingleStringChild = child.children && child.children.length === 1 && typeof child.children[0] === "string";
806
+ if (hasNoProps && hasSingleStringChild) {
807
+ return child.children[0];
808
+ }
809
+ }
810
+ return this.unwrapReactive(child);
811
+ }
812
+ return children.map((c) => this.unwrapReactive(c));
813
+ }
814
+ escapeHtml(text) {
815
+ const htmlEscapes = {
816
+ "&": "&amp;",
817
+ "<": "&lt;",
818
+ ">": "&gt;",
819
+ '"': "&quot;",
820
+ "'": "&#x27;"
821
+ };
822
+ return text.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
823
+ }
824
+ isSelfClosingTag(tagName) {
825
+ const selfClosingTags = /* @__PURE__ */ new Set([
826
+ "area",
827
+ "base",
828
+ "br",
829
+ "col",
830
+ "embed",
831
+ "hr",
832
+ "img",
833
+ "input",
834
+ "link",
835
+ "meta",
836
+ "param",
837
+ "source",
838
+ "track",
839
+ "wbr"
840
+ ]);
841
+ return selfClosingTags.has(tagName.toLowerCase());
842
+ }
843
+ propsToAttributes(props) {
844
+ const attrs = [];
845
+ for (const key in props) {
846
+ if (key === "children" || key === "dangerouslySetInnerHTML" || key === "ref") {
847
+ continue;
848
+ }
849
+ let value = props[key];
850
+ value = this.resolveStateValue(value);
851
+ if (value == null || value === false) continue;
852
+ if (key.startsWith("on") && typeof value === "function") {
853
+ continue;
854
+ }
855
+ if (key === "className" || key === "class") {
856
+ const className = Array.isArray(value) ? value.join(" ") : value;
857
+ if (className) {
858
+ attrs.push(`class="${this.escapeHtml(String(className))}"`);
859
+ }
860
+ continue;
861
+ }
862
+ if (key === "style") {
863
+ const styleStr = this.styleToString(value);
864
+ if (styleStr) {
865
+ attrs.push(`style="${this.escapeHtml(styleStr)}"`);
866
+ }
867
+ continue;
868
+ }
869
+ if (value === true) {
870
+ attrs.push(key);
871
+ continue;
872
+ }
873
+ attrs.push(`${key}="${this.escapeHtml(String(value))}"`);
874
+ }
875
+ return attrs.join(" ");
876
+ }
877
+ styleToString(style) {
878
+ if (typeof style === "string") {
879
+ return style;
880
+ }
881
+ if (typeof style === "object" && style !== null) {
882
+ const styles = [];
883
+ for (const key in style) {
884
+ const cssKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
885
+ styles.push(`${cssKey}:${style[key]}`);
886
+ }
887
+ return styles.join(";");
888
+ }
889
+ return "";
890
+ }
891
+ isState(value) {
892
+ return value && typeof value === "object" && "value" in value && "subscribe" in value && typeof value.subscribe === "function";
893
+ }
894
+ createReactiveChild(state, renderFn) {
895
+ const currentValue = renderFn(state.value);
896
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
897
+ const entry = { node: null, renderFn };
898
+ this.reactiveNodes.set(state, entry);
899
+ state.subscribe(() => {
900
+ if (entry.node && entry.node.parentNode) {
901
+ const newValue = renderFn(state.value);
902
+ entry.node.textContent = String(newValue ?? "");
903
+ }
904
+ });
905
+ }
906
+ return currentValue;
907
+ }
908
+ jsonToVNode(json) {
909
+ if (this.isState(json)) {
910
+ return this.createReactiveChild(json, (v) => v);
911
+ }
912
+ if (isPrimitiveJson(json)) {
913
+ return json;
914
+ }
915
+ const { tag, attributes = {}, children } = json;
916
+ const props = {};
917
+ for (const key in attributes) {
918
+ const value = attributes[key];
919
+ if (key === "class") {
920
+ props.className = this.isState(value) ? value.value : value;
921
+ } else {
922
+ props[key] = this.isState(value) ? value.value : value;
923
+ }
924
+ }
925
+ const childrenArray = [];
926
+ if (children != null) {
927
+ if (Array.isArray(children)) {
928
+ for (const child of children) {
929
+ if (this.isState(child)) {
930
+ childrenArray.push(this.createReactiveChild(child, (v) => v));
931
+ } else {
932
+ const converted = this.jsonToVNode(child);
933
+ if (converted != null && converted !== false) {
934
+ childrenArray.push(converted);
935
+ }
936
+ }
937
+ }
938
+ } else if (this.isState(children)) {
939
+ childrenArray.push(this.createReactiveChild(children, (v) => v));
940
+ } else if (typeof children === "object" && "tag" in children) {
941
+ const converted = this.jsonToVNode(children);
942
+ if (converted != null && converted !== false) {
943
+ childrenArray.push(converted);
944
+ }
945
+ } else {
946
+ childrenArray.push(children);
947
+ }
948
+ }
949
+ return { tagName: tag, props, children: childrenArray };
950
+ }
951
+ vNodeJsonToVNode(json) {
952
+ if (this.isState(json)) {
953
+ return this.createReactiveChild(json, (v) => v);
954
+ }
955
+ if (isPrimitiveJson(json)) {
956
+ return json;
957
+ }
958
+ const { tagName, props = {}, children = [] } = json;
959
+ const resolvedProps = {};
960
+ for (const key in props) {
961
+ const value = props[key];
962
+ resolvedProps[key] = this.isState(value) ? value.value : value;
963
+ }
964
+ const childrenArray = [];
965
+ for (const child of children) {
966
+ if (this.isState(child)) {
967
+ childrenArray.push(this.createReactiveChild(child, (v) => v));
968
+ } else {
969
+ const converted = this.vNodeJsonToVNode(child);
970
+ if (converted != null && converted !== false) {
971
+ childrenArray.push(converted);
972
+ }
973
+ }
974
+ }
975
+ return { tagName, props: resolvedProps, children: childrenArray };
976
+ }
977
+ renderJson(rootElement, json) {
978
+ const vNode = this.jsonToVNode(json);
979
+ if (!vNode || typeof vNode !== "object" || !("tagName" in vNode)) {
980
+ throw new Error("Invalid JSON structure");
981
+ }
982
+ return this.render(rootElement, vNode);
983
+ }
984
+ renderVNode(rootElement, json) {
985
+ const vNode = this.vNodeJsonToVNode(json);
986
+ if (!vNode || typeof vNode !== "object" || !("tagName" in vNode)) {
987
+ throw new Error("Invalid VNode JSON structure");
988
+ }
989
+ return this.render(rootElement, vNode);
990
+ }
991
+ renderJsonToString(json, options = {}) {
992
+ const vNode = this.jsonToVNode(json);
993
+ return this.renderToString(vNode, options);
994
+ }
995
+ renderVNodeToString(json, options = {}) {
996
+ const vNode = this.vNodeJsonToVNode(json);
997
+ return this.renderToString(vNode, options);
998
+ }
999
+ // Generate complete HTML document as string (for SSR)
1000
+ renderToHTMLDocument(vNode, options = {}) {
1001
+ const { title = "", meta = [], links = [], scripts = [], styles = [], lang = "en", head = "", bodyAttrs = {}, pretty = false } = options;
1002
+ const nl = pretty ? "\n" : "";
1003
+ const indent = pretty ? " " : "";
1004
+ const indent2 = pretty ? " " : "";
1005
+ let html = `<!DOCTYPE html>${nl}<html lang="${lang}">${nl}${indent}<head>${nl}${indent2}<meta charset="UTF-8">${nl}${indent2}<meta name="viewport" content="width=device-width, initial-scale=1.0">${nl}`;
1006
+ if (title) html += `${indent2}<title>${this.escapeHtml(title)}</title>${nl}`;
1007
+ for (const m of meta) {
1008
+ html += `${indent2}<meta`;
1009
+ for (const k in m) html += ` ${k}="${this.escapeHtml(m[k])}"`;
1010
+ html += `>${nl}`;
1011
+ }
1012
+ for (const l of links) {
1013
+ html += `${indent2}<link`;
1014
+ for (const k in l) html += ` ${k}="${this.escapeHtml(l[k])}"`;
1015
+ html += `>${nl}`;
1016
+ }
1017
+ for (const s of styles) {
1018
+ if (s.href) {
1019
+ html += `${indent2}<link rel="stylesheet" href="${this.escapeHtml(s.href)}">${nl}`;
1020
+ } else if (s.content) {
1021
+ html += `${indent2}<style>${s.content}</style>${nl}`;
1022
+ }
1023
+ }
1024
+ if (head) html += head + nl;
1025
+ html += `${indent}</head>${nl}${indent}<body`;
1026
+ for (const k in bodyAttrs) html += ` ${k}="${this.escapeHtml(bodyAttrs[k])}"`;
1027
+ html += `>${nl}`;
1028
+ html += this.renderToString(vNode, { pretty, indent: 2 });
1029
+ for (const script of scripts) {
1030
+ html += `${indent2}<script`;
1031
+ if (script.type) html += ` type="${this.escapeHtml(script.type)}"`;
1032
+ if (script.async) html += ` async`;
1033
+ if (script.defer) html += ` defer`;
1034
+ if (script.src) {
1035
+ html += ` src="${this.escapeHtml(script.src)}"></script>${nl}`;
1036
+ } else if (script.content) {
1037
+ html += `>${script.content}</script>${nl}`;
1038
+ } else {
1039
+ html += `></script>${nl}`;
1040
+ }
1041
+ }
1042
+ html += `${indent}</body>${nl}</html>`;
1043
+ return html;
1044
+ }
1045
+ // Expose elementCache for reactive updates
1046
+ getElementCache() {
1047
+ return this.elementCache;
1048
+ }
1049
+ };
1050
+ var dom = new DomNode();
1051
+ var render = dom.render.bind(dom);
1052
+ var renderToString = dom.renderToString.bind(dom);
1053
+
1054
+ // src/server.ts
1055
+ var ServerDatabase = class {
1056
+ constructor() {
1057
+ this._db = null;
1058
+ }
1059
+ async initialize(config) {
1060
+ this._db = new Database(config);
1061
+ }
1062
+ database() {
1063
+ return this._db;
1064
+ }
1065
+ };
1066
+ var serverDatabase = new ServerDatabase();
1067
+ var database = serverDatabase.database;
1068
+
1069
+ // src/database.ts
1070
+ var esbuild = __toESM(require("esbuild"));
1071
+ var Database = class {
1072
+ constructor(config) {
1073
+ this._config = {
1074
+ dir: resolve(process.cwd(), "databases")
1075
+ };
1076
+ this._config = { ...this._config, ...config };
1077
+ this._registerModules = config.registerModules || {};
1078
+ this._ctx = import_node_vm.default.createContext(this._registerModules);
1079
+ }
1080
+ set config(config) {
1081
+ this._config = { ...this._config, ...config };
1082
+ }
1083
+ register(context) {
1084
+ this._registerModules = { ...this._registerModules, ...context };
1085
+ this._ctx = import_node_vm.default.createContext(this._registerModules);
1086
+ }
1087
+ plugin(moduleName, moduleContent) {
1088
+ this.register({ [moduleName]: moduleContent });
1089
+ }
1090
+ resolvePath(fileList, query) {
1091
+ const aliases = { "@db": this._config.dir || resolve(process.cwd(), "databases") };
1092
+ let resolvedPath = query;
1093
+ for (const [alias, target] of Object.entries(aliases)) {
1094
+ if (resolvedPath.startsWith(alias + "/")) {
1095
+ resolvedPath = resolvedPath.replace(alias, target);
1096
+ break;
1097
+ }
1098
+ }
1099
+ resolvedPath = import_node_path.default.normalize(resolvedPath);
1100
+ return fileList.find((file) => {
1101
+ const normalizedFile = import_node_path.default.normalize(file);
1102
+ const fileWithoutExt = normalizedFile.replace(/\.[^/.]+$/, "");
1103
+ return normalizedFile === resolvedPath || fileWithoutExt === resolvedPath || normalizedFile === resolvedPath + ".ts" || normalizedFile === resolvedPath + ".js";
1104
+ });
1105
+ }
1106
+ async moduleLinker(specifier, referencingModule) {
1107
+ const dbFiles = import_node_fs.default.readdirSync(this._config.dir || resolve(process.cwd(), "databases")).filter((f) => f.endsWith(".ts")).map((f) => import_node_path.default.join(this._config.dir || resolve(process.cwd(), "databases"), f));
1108
+ const dbResult = this.resolvePath(dbFiles, specifier);
1109
+ if (dbResult) {
1110
+ try {
1111
+ const actualModule = await import(dbResult);
1112
+ const exportNames = Object.keys(actualModule);
1113
+ return new import_node_vm.default.SyntheticModule(
1114
+ exportNames,
1115
+ function() {
1116
+ exportNames.forEach((key) => {
1117
+ this.setExport(key, actualModule[key]);
1118
+ });
1119
+ },
1120
+ { identifier: specifier, context: referencingModule.context }
1121
+ );
1122
+ } catch (err) {
1123
+ console.error(`Failed to load database module ${specifier}:`, err);
1124
+ throw err;
1125
+ }
1126
+ }
1127
+ throw new Error(`Module ${specifier} is not allowed or not found.`);
1128
+ }
1129
+ async vmRun(code, _options) {
1130
+ const logs = [];
1131
+ const customConsole = ["log", "error", "warn", "info", "debug", "trace"].reduce((acc, type) => {
1132
+ acc[type] = (...args) => logs.push({ type, args });
1133
+ return acc;
1134
+ }, {});
1135
+ this.register({
1136
+ console: customConsole
1137
+ });
1138
+ let stringCode;
1139
+ if (typeof code === "function") {
1140
+ const funcStr = code.toString();
1141
+ const arrowMatch = funcStr.match(/^[\s]*\(?\s*\)?\s*=>\s*{?/);
1142
+ const functionMatch = funcStr.match(/^[\s]*function\s*\(?[\w\s]*\)?\s*{/);
1143
+ const match = arrowMatch || functionMatch;
1144
+ const start = match ? match[0].length : 0;
1145
+ const end = funcStr.lastIndexOf("}");
1146
+ stringCode = funcStr.substring(start, end);
1147
+ stringCode = stringCode.replace(/^[\s\r\n]+/, "").replace(/[\s\r\n]+$/, "");
1148
+ stringCode = stringCode.replace(
1149
+ /import\s*\(\s*([^)]+?)\s*\)\s*\.from\s*\(\s*(['"])([^'"]+)\2\s*\)/g,
1150
+ (_, importArg, quote, modulePath) => {
1151
+ const trimmed = importArg.trim();
1152
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
1153
+ const inner = trimmed.slice(1, -1).trim();
1154
+ return `import { ${inner} } from ${quote}${modulePath}${quote}`;
1155
+ } else {
1156
+ return `import ${trimmed} from ${quote}${modulePath}${quote}`;
1157
+ }
1158
+ }
1159
+ );
1160
+ stringCode = stringCode.split("\n").map((line) => line.trim()).join("\n").trim();
1161
+ } else {
1162
+ stringCode = code;
1163
+ }
1164
+ const result = await esbuild.build({
1165
+ stdin: {
1166
+ contents: stringCode,
1167
+ loader: this._config.language || "ts"
1168
+ },
1169
+ format: "esm",
1170
+ target: "es2020",
1171
+ write: false,
1172
+ bundle: false,
1173
+ sourcemap: false
1174
+ });
1175
+ const js = result.outputFiles[0].text;
1176
+ const mod = new import_node_vm.default.SourceTextModule(js, { context: this._ctx, identifier: import_node_path.default.join(this._config.dir || resolve(process.cwd(), "databases"), "virtual-entry.js") });
1177
+ await mod.link(this.moduleLinker.bind(this));
1178
+ await mod.evaluate();
1179
+ return {
1180
+ namespace: mod.namespace,
1181
+ logs
1182
+ };
1183
+ }
1184
+ /**
1185
+ * Execute database code and return results
1186
+ */
1187
+ async execute(code, options) {
1188
+ return await this.vmRun(code, options);
1189
+ }
1190
+ };
1191
+ var database2 = serverDatabase.database;
1192
+ var database_default = database2;
1193
+ // Annotate the CommonJS export names for ESM import in node:
1194
+ 0 && (module.exports = {
1195
+ Database,
1196
+ database
1197
+ });