elit 3.2.0 → 3.2.2

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.
package/dist/server.js CHANGED
@@ -732,205 +732,205 @@ async function processDenoEntriesAsync(iterator, withFileTypes) {
732
732
  }
733
733
  return entries;
734
734
  }
735
- async function readFile(path2, options) {
735
+ async function readFile(path, options) {
736
736
  const opts = parseOptions(options, {});
737
737
  if (isNode) {
738
- return fsPromises.readFile(path2, opts);
738
+ return fsPromises.readFile(path, opts);
739
739
  } else if (isBun) {
740
- const file = Bun.file(path2);
740
+ const file = Bun.file(path);
741
741
  const content = await file.arrayBuffer();
742
742
  return decodeContent(content, opts.encoding);
743
743
  } else if (isDeno) {
744
- const content = await Deno.readFile(path2);
744
+ const content = await Deno.readFile(path);
745
745
  return decodeContent(content, opts.encoding);
746
746
  }
747
747
  throw new Error("Unsupported runtime");
748
748
  }
749
- function readFileSync(path2, options) {
749
+ function readFileSync(path, options) {
750
750
  const opts = parseOptions(options, {});
751
751
  if (isNode) {
752
- return fs.readFileSync(path2, opts);
752
+ return fs.readFileSync(path, opts);
753
753
  } else if (isBun) {
754
- const file = Bun.file(path2);
754
+ const file = Bun.file(path);
755
755
  const content = file.arrayBuffer();
756
756
  return decodeContent(content, opts.encoding);
757
757
  } else if (isDeno) {
758
- const content = Deno.readFileSync(path2);
758
+ const content = Deno.readFileSync(path);
759
759
  return decodeContent(content, opts.encoding);
760
760
  }
761
761
  throw new Error("Unsupported runtime");
762
762
  }
763
- async function writeFile(path2, data, options) {
763
+ async function writeFile(path, data, options) {
764
764
  const opts = parseOptions(options, {});
765
765
  if (isNode) {
766
- return fsPromises.writeFile(path2, data, opts);
766
+ return fsPromises.writeFile(path, data, opts);
767
767
  } else if (isBun) {
768
- await Bun.write(path2, data);
768
+ await Bun.write(path, data);
769
769
  } else if (isDeno) {
770
- await Deno.writeFile(path2, dataToUint8Array(data));
770
+ await Deno.writeFile(path, dataToUint8Array(data));
771
771
  }
772
772
  }
773
- function writeFileSync(path2, data, options) {
773
+ function writeFileSync(path, data, options) {
774
774
  const opts = parseOptions(options, {});
775
775
  if (isNode) {
776
- fs.writeFileSync(path2, data, opts);
776
+ fs.writeFileSync(path, data, opts);
777
777
  } else if (isBun) {
778
- Bun.write(path2, data);
778
+ Bun.write(path, data);
779
779
  } else if (isDeno) {
780
- Deno.writeFileSync(path2, dataToUint8Array(data));
780
+ Deno.writeFileSync(path, dataToUint8Array(data));
781
781
  }
782
782
  }
783
- async function appendFile(path2, data, options) {
783
+ async function appendFile(path, data, options) {
784
784
  const opts = parseOptions(options, {});
785
785
  if (isNode) {
786
- return fsPromises.appendFile(path2, data, opts);
786
+ return fsPromises.appendFile(path, data, opts);
787
787
  } else {
788
- if (await exists(path2)) {
789
- const existing = await readFile(path2);
788
+ if (await exists(path)) {
789
+ const existing = await readFile(path);
790
790
  const combined = Buffer.isBuffer(existing) ? Buffer.concat([existing, Buffer.isBuffer(data) ? data : Buffer.from(data)]) : existing + (Buffer.isBuffer(data) ? data.toString() : data);
791
- await writeFile(path2, combined, opts);
791
+ await writeFile(path, combined, opts);
792
792
  } else {
793
- await writeFile(path2, data, opts);
793
+ await writeFile(path, data, opts);
794
794
  }
795
795
  }
796
796
  }
797
- function appendFileSync(path2, data, options) {
797
+ function appendFileSync(path, data, options) {
798
798
  const opts = parseOptions(options, {});
799
799
  if (isNode) {
800
- fs.appendFileSync(path2, data, opts);
800
+ fs.appendFileSync(path, data, opts);
801
801
  } else {
802
- if (existsSync(path2)) {
803
- const existing = readFileSync(path2);
802
+ if (existsSync(path)) {
803
+ const existing = readFileSync(path);
804
804
  const combined = Buffer.isBuffer(existing) ? Buffer.concat([existing, Buffer.isBuffer(data) ? data : Buffer.from(data)]) : existing + (Buffer.isBuffer(data) ? data.toString() : data);
805
- writeFileSync(path2, combined, opts);
805
+ writeFileSync(path, combined, opts);
806
806
  } else {
807
- writeFileSync(path2, data, opts);
807
+ writeFileSync(path, data, opts);
808
808
  }
809
809
  }
810
810
  }
811
- async function exists(path2) {
811
+ async function exists(path) {
812
812
  try {
813
- await stat(path2);
813
+ await stat(path);
814
814
  return true;
815
815
  } catch {
816
816
  return false;
817
817
  }
818
818
  }
819
- function existsSync(path2) {
819
+ function existsSync(path) {
820
820
  try {
821
- statSync(path2);
821
+ statSync(path);
822
822
  return true;
823
823
  } catch {
824
824
  return false;
825
825
  }
826
826
  }
827
- async function stat(path2) {
827
+ async function stat(path) {
828
828
  if (isNode) {
829
- return fsPromises.stat(path2);
829
+ return fsPromises.stat(path);
830
830
  } else if (isBun) {
831
- const file = Bun.file(path2);
831
+ const file = Bun.file(path);
832
832
  const size = file.size;
833
833
  const exists2 = await file.exists();
834
834
  if (!exists2) {
835
- throw new Error(`ENOENT: no such file or directory, stat '${path2}'`);
835
+ throw new Error(`ENOENT: no such file or directory, stat '${path}'`);
836
836
  }
837
- return createStatsObject(path2, size, false);
837
+ return createStatsObject(path, size, false);
838
838
  } else if (isDeno) {
839
- const info = await Deno.stat(path2);
839
+ const info = await Deno.stat(path);
840
840
  return createStatsFromDenoFileInfo(info);
841
841
  }
842
842
  throw new Error("Unsupported runtime");
843
843
  }
844
- function statSync(path2) {
844
+ function statSync(path) {
845
845
  if (isNode) {
846
- return fs.statSync(path2);
846
+ return fs.statSync(path);
847
847
  } else if (isBun) {
848
- const file = Bun.file(path2);
848
+ const file = Bun.file(path);
849
849
  const size = file.size;
850
850
  try {
851
851
  file.arrayBuffer();
852
852
  } catch {
853
- throw new Error(`ENOENT: no such file or directory, stat '${path2}'`);
853
+ throw new Error(`ENOENT: no such file or directory, stat '${path}'`);
854
854
  }
855
- return createStatsObject(path2, size, false);
855
+ return createStatsObject(path, size, false);
856
856
  } else if (isDeno) {
857
- const info = Deno.statSync(path2);
857
+ const info = Deno.statSync(path);
858
858
  return createStatsFromDenoFileInfo(info);
859
859
  }
860
860
  throw new Error("Unsupported runtime");
861
861
  }
862
- async function mkdir(path2, options) {
862
+ async function mkdir(path, options) {
863
863
  const opts = typeof options === "number" ? { mode: options } : options || {};
864
864
  if (isNode) {
865
- await fsPromises.mkdir(path2, opts);
865
+ await fsPromises.mkdir(path, opts);
866
866
  } else if (isBun) {
867
- await Deno.mkdir(path2, { recursive: opts.recursive });
867
+ await Deno.mkdir(path, { recursive: opts.recursive });
868
868
  } else if (isDeno) {
869
- await Deno.mkdir(path2, { recursive: opts.recursive });
869
+ await Deno.mkdir(path, { recursive: opts.recursive });
870
870
  }
871
871
  }
872
- function mkdirSync(path2, options) {
872
+ function mkdirSync(path, options) {
873
873
  const opts = typeof options === "number" ? { mode: options } : options || {};
874
874
  if (isNode) {
875
- fs.mkdirSync(path2, opts);
875
+ fs.mkdirSync(path, opts);
876
876
  } else if (isBun) {
877
- Deno.mkdirSync(path2, { recursive: opts.recursive });
877
+ Deno.mkdirSync(path, { recursive: opts.recursive });
878
878
  } else if (isDeno) {
879
- Deno.mkdirSync(path2, { recursive: opts.recursive });
879
+ Deno.mkdirSync(path, { recursive: opts.recursive });
880
880
  }
881
881
  }
882
- async function readdir(path2, options) {
882
+ async function readdir(path, options) {
883
883
  const opts = parseOptions(options, {});
884
884
  if (isNode) {
885
- return fsPromises.readdir(path2, opts);
885
+ return fsPromises.readdir(path, opts);
886
886
  } else if (isBunOrDeno) {
887
- return processDenoEntriesAsync(Deno.readDir(path2), opts.withFileTypes);
887
+ return processDenoEntriesAsync(Deno.readDir(path), opts.withFileTypes);
888
888
  }
889
889
  throw new Error("Unsupported runtime");
890
890
  }
891
- function readdirSync(path2, options) {
891
+ function readdirSync(path, options) {
892
892
  const opts = parseOptions(options, {});
893
893
  if (isNode) {
894
- return fs.readdirSync(path2, opts);
894
+ return fs.readdirSync(path, opts);
895
895
  } else if (isBunOrDeno) {
896
- return processDenoEntries(Deno.readDirSync(path2), opts.withFileTypes);
896
+ return processDenoEntries(Deno.readDirSync(path), opts.withFileTypes);
897
897
  }
898
898
  throw new Error("Unsupported runtime");
899
899
  }
900
- async function unlink(path2) {
900
+ async function unlink(path) {
901
901
  if (isNode) {
902
- return fsPromises.unlink(path2);
902
+ return fsPromises.unlink(path);
903
903
  } else if (isBun) {
904
- await Deno.remove(path2);
904
+ await Deno.remove(path);
905
905
  } else if (isDeno) {
906
- await Deno.remove(path2);
906
+ await Deno.remove(path);
907
907
  }
908
908
  }
909
- function unlinkSync(path2) {
909
+ function unlinkSync(path) {
910
910
  if (isNode) {
911
- fs.unlinkSync(path2);
911
+ fs.unlinkSync(path);
912
912
  } else if (isBun) {
913
- Deno.removeSync(path2);
913
+ Deno.removeSync(path);
914
914
  } else if (isDeno) {
915
- Deno.removeSync(path2);
915
+ Deno.removeSync(path);
916
916
  }
917
917
  }
918
- async function rmdir(path2, options) {
918
+ async function rmdir(path, options) {
919
919
  if (isNode) {
920
- return fsPromises.rmdir(path2, options);
920
+ return fsPromises.rmdir(path, options);
921
921
  } else if (isBun) {
922
- await Deno.remove(path2, { recursive: options?.recursive });
922
+ await Deno.remove(path, { recursive: options?.recursive });
923
923
  } else if (isDeno) {
924
- await Deno.remove(path2, { recursive: options?.recursive });
924
+ await Deno.remove(path, { recursive: options?.recursive });
925
925
  }
926
926
  }
927
- function rmdirSync(path2, options) {
927
+ function rmdirSync(path, options) {
928
928
  if (isNode) {
929
- fs.rmdirSync(path2, options);
929
+ fs.rmdirSync(path, options);
930
930
  } else if (isBun) {
931
- Deno.removeSync(path2, { recursive: options?.recursive });
931
+ Deno.removeSync(path, { recursive: options?.recursive });
932
932
  } else if (isDeno) {
933
- Deno.removeSync(path2, { recursive: options?.recursive });
933
+ Deno.removeSync(path, { recursive: options?.recursive });
934
934
  }
935
935
  }
936
936
  async function rename(oldPath, newPath) {
@@ -969,27 +969,27 @@ function copyFileSync(src, dest, flags) {
969
969
  Deno.copyFileSync(src, dest);
970
970
  }
971
971
  }
972
- async function realpath(path2, options) {
972
+ async function realpath(path, options) {
973
973
  if (isNode) {
974
- return fsPromises.realpath(path2, options);
974
+ return fsPromises.realpath(path, options);
975
975
  } else if (isBun) {
976
- const fs3 = require("fs/promises");
977
- return fs3.realpath(path2, options);
976
+ const fs2 = require("fs/promises");
977
+ return fs2.realpath(path, options);
978
978
  } else if (isDeno) {
979
- return await Deno.realPath(path2);
979
+ return await Deno.realPath(path);
980
980
  }
981
- return path2;
981
+ return path;
982
982
  }
983
- function realpathSync(path2, options) {
983
+ function realpathSync(path, options) {
984
984
  if (isNode) {
985
- return fs.realpathSync(path2, options);
985
+ return fs.realpathSync(path, options);
986
986
  } else if (isBun) {
987
- const fs3 = require("fs");
988
- return fs3.realpathSync(path2, options);
987
+ const fs2 = require("fs");
988
+ return fs2.realpathSync(path, options);
989
989
  } else if (isDeno) {
990
- return Deno.realPathSync(path2);
990
+ return Deno.realPathSync(path);
991
991
  }
992
- return path2;
992
+ return path;
993
993
  }
994
994
  function createStatsObject(_path, size, isDir) {
995
995
  const now = Date.now();
@@ -1132,14 +1132,12 @@ __export(server_exports, {
1132
1132
  cors: () => cors,
1133
1133
  createDevServer: () => createDevServer,
1134
1134
  createProxyHandler: () => createProxyHandler,
1135
- database: () => database,
1136
1135
  errorHandler: () => errorHandler,
1137
1136
  html: () => html,
1138
1137
  json: () => json,
1139
1138
  logger: () => logger,
1140
1139
  rateLimit: () => rateLimit,
1141
1140
  security: () => security,
1142
- serverDatabase: () => serverDatabase,
1143
1141
  status: () => status,
1144
1142
  text: () => text
1145
1143
  });
@@ -1528,32 +1526,32 @@ var WebSocketServer = class extends import_events2.EventEmitter {
1528
1526
  // src/chokidar.ts
1529
1527
  var import_events3 = require("events");
1530
1528
  init_runtime();
1531
- function normalizePath(path2) {
1532
- return path2.replace(/\\/g, "/");
1529
+ function normalizePath(path) {
1530
+ return path.replace(/\\/g, "/");
1533
1531
  }
1534
- function emitEvent(watcher, eventType, path2) {
1535
- watcher.emit(eventType, path2);
1536
- watcher.emit("all", eventType, path2);
1532
+ function emitEvent(watcher, eventType, path) {
1533
+ watcher.emit(eventType, path);
1534
+ watcher.emit("all", eventType, path);
1537
1535
  }
1538
- function matchesAnyPattern(path2, patterns) {
1539
- return patterns.some((pattern) => matchesPattern(path2, pattern));
1536
+ function matchesAnyPattern(path, patterns) {
1537
+ return patterns.some((pattern) => matchesPattern(path, pattern));
1540
1538
  }
1541
- function handleRenameEvent(watcher, fullPath, fs3) {
1539
+ function handleRenameEvent(watcher, fullPath, fs2) {
1542
1540
  try {
1543
- fs3.statSync(fullPath);
1541
+ fs2.statSync(fullPath);
1544
1542
  emitEvent(watcher, "add", fullPath);
1545
1543
  } catch {
1546
1544
  emitEvent(watcher, "unlink", fullPath);
1547
1545
  }
1548
1546
  }
1549
- function setupFsWatch(watcher, baseDir, patterns, fs3) {
1547
+ function setupFsWatch(watcher, baseDir, patterns, fs2) {
1550
1548
  try {
1551
- const nativeWatcher = fs3.watch(baseDir, { recursive: true }, (eventType, filename) => {
1549
+ const nativeWatcher = fs2.watch(baseDir, { recursive: true }, (eventType, filename) => {
1552
1550
  if (!filename) return;
1553
1551
  const fullPath = normalizePath(`${baseDir}/${filename}`);
1554
1552
  if (!matchesAnyPattern(fullPath, patterns)) return;
1555
1553
  if (eventType === "rename") {
1556
- handleRenameEvent(watcher, fullPath, fs3);
1554
+ handleRenameEvent(watcher, fullPath, fs2);
1557
1555
  } else if (eventType === "change") {
1558
1556
  emitEvent(watcher, "change", fullPath);
1559
1557
  }
@@ -1585,7 +1583,7 @@ var FSWatcher = class extends import_events3.EventEmitter {
1585
1583
  this._watcher.add(pathArray);
1586
1584
  }
1587
1585
  } else {
1588
- pathArray.forEach((path2) => this._watched.add(path2));
1586
+ pathArray.forEach((path) => this._watched.add(path));
1589
1587
  }
1590
1588
  return this;
1591
1589
  }
@@ -1602,7 +1600,7 @@ var FSWatcher = class extends import_events3.EventEmitter {
1602
1600
  this._watcher.unwatch(pathArray);
1603
1601
  }
1604
1602
  } else {
1605
- pathArray.forEach((path2) => this._watched.delete(path2));
1603
+ pathArray.forEach((path) => this._watched.delete(path));
1606
1604
  }
1607
1605
  return this;
1608
1606
  }
@@ -1629,9 +1627,9 @@ var FSWatcher = class extends import_events3.EventEmitter {
1629
1627
  return this._watcher.getWatched();
1630
1628
  }
1631
1629
  const result = {};
1632
- this._watched.forEach((path2) => {
1633
- const dir = path2.substring(0, path2.lastIndexOf("/")) || ".";
1634
- const file = path2.substring(path2.lastIndexOf("/") + 1);
1630
+ this._watched.forEach((path) => {
1631
+ const dir = path.substring(0, path.lastIndexOf("/")) || ".";
1632
+ const file = path.substring(path.lastIndexOf("/") + 1);
1635
1633
  if (!result[dir]) {
1636
1634
  result[dir] = [];
1637
1635
  }
@@ -1668,19 +1666,19 @@ function watch(paths, options) {
1668
1666
  const watcher = new FSWatcher(options);
1669
1667
  const pathArray = Array.isArray(paths) ? paths : [paths];
1670
1668
  const watchMap = /* @__PURE__ */ new Map();
1671
- pathArray.forEach((path2) => {
1672
- const baseDir = getBaseDirectory(path2);
1669
+ pathArray.forEach((path) => {
1670
+ const baseDir = getBaseDirectory(path);
1673
1671
  if (!watchMap.has(baseDir)) {
1674
1672
  watchMap.set(baseDir, []);
1675
1673
  }
1676
- watchMap.get(baseDir).push(path2);
1674
+ watchMap.get(baseDir).push(path);
1677
1675
  });
1678
1676
  if (runtime === "node") {
1679
- const fs3 = require("fs");
1680
- watchMap.forEach((patterns, baseDir) => setupFsWatch(watcher, baseDir, patterns, fs3));
1677
+ const fs2 = require("fs");
1678
+ watchMap.forEach((patterns, baseDir) => setupFsWatch(watcher, baseDir, patterns, fs2));
1681
1679
  } else if (runtime === "bun") {
1682
- const fs3 = require("fs");
1683
- watchMap.forEach((patterns, baseDir) => setupFsWatch(watcher, baseDir, patterns, fs3));
1680
+ const fs2 = require("fs");
1681
+ watchMap.forEach((patterns, baseDir) => setupFsWatch(watcher, baseDir, patterns, fs2));
1684
1682
  } else if (runtime === "deno") {
1685
1683
  const baseDirs = Array.from(watchMap.keys());
1686
1684
  const allPatterns = Array.from(watchMap.values()).flat();
@@ -1689,18 +1687,18 @@ function watch(paths, options) {
1689
1687
  const denoWatcher = Deno.watchFs(baseDirs);
1690
1688
  for await (const event of denoWatcher) {
1691
1689
  if (watcher["_closed"]) break;
1692
- for (const path2 of event.paths) {
1693
- const normalizedPath = normalizePath(path2);
1690
+ for (const path of event.paths) {
1691
+ const normalizedPath = normalizePath(path);
1694
1692
  if (!matchesAnyPattern(normalizedPath, allPatterns)) continue;
1695
1693
  switch (event.kind) {
1696
1694
  case "create":
1697
- emitEvent(watcher, "add", path2);
1695
+ emitEvent(watcher, "add", path);
1698
1696
  break;
1699
1697
  case "modify":
1700
- emitEvent(watcher, "change", path2);
1698
+ emitEvent(watcher, "change", path);
1701
1699
  break;
1702
1700
  case "remove":
1703
- emitEvent(watcher, "unlink", path2);
1701
+ emitEvent(watcher, "unlink", path);
1704
1702
  break;
1705
1703
  }
1706
1704
  }
@@ -1711,7 +1709,7 @@ function watch(paths, options) {
1711
1709
  }
1712
1710
  }
1713
1711
  })();
1714
- pathArray.forEach((path2) => watcher.add(path2));
1712
+ pathArray.forEach((path) => watcher.add(path));
1715
1713
  queueMicrotask(() => watcher.emit("ready"));
1716
1714
  }
1717
1715
  return watcher;
@@ -1733,38 +1731,38 @@ function getCwd() {
1733
1731
  }
1734
1732
  return "/";
1735
1733
  }
1736
- function findLastSeparator(path2) {
1737
- return Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\"));
1734
+ function findLastSeparator(path) {
1735
+ return Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
1738
1736
  }
1739
1737
  function createPathOps(isWin) {
1740
1738
  return {
1741
1739
  sep: getSeparator(isWin),
1742
1740
  delimiter: isWin ? ";" : ":",
1743
- normalize: (path2) => normalizePath2(path2, isWin),
1741
+ normalize: (path) => normalizePath2(path, isWin),
1744
1742
  join: (...paths) => joinPaths(paths, isWin),
1745
1743
  resolve: (...paths) => resolvePaths(paths, isWin),
1746
- isAbsolute: (path2) => isWin ? isAbsoluteWin(path2) : isAbsolutePosix(path2),
1744
+ isAbsolute: (path) => isWin ? isAbsoluteWin(path) : isAbsolutePosix(path),
1747
1745
  relative: (from, to) => relativePath(from, to, isWin),
1748
- dirname: (path2) => getDirname(path2, isWin),
1749
- basename: (path2, ext) => getBasename(path2, ext, isWin),
1750
- extname: (path2) => getExtname(path2),
1751
- parse: (path2) => parsePath(path2, isWin),
1746
+ dirname: (path) => getDirname(path, isWin),
1747
+ basename: (path, ext) => getBasename(path, ext, isWin),
1748
+ extname: (path) => getExtname(path),
1749
+ parse: (path) => parsePath(path, isWin),
1752
1750
  format: (pathObject) => formatPath(pathObject, isWin)
1753
1751
  };
1754
1752
  }
1755
- function isAbsolutePosix(path2) {
1756
- return path2.length > 0 && path2[0] === "/";
1753
+ function isAbsolutePosix(path) {
1754
+ return path.length > 0 && path[0] === "/";
1757
1755
  }
1758
- function isAbsoluteWin(path2) {
1759
- const len = path2.length;
1756
+ function isAbsoluteWin(path) {
1757
+ const len = path.length;
1760
1758
  if (len === 0) return false;
1761
- const code = path2.charCodeAt(0);
1759
+ const code = path.charCodeAt(0);
1762
1760
  if (code === 47 || code === 92) {
1763
1761
  return true;
1764
1762
  }
1765
1763
  if (code >= 65 && code <= 90 || code >= 97 && code <= 122) {
1766
- if (len > 2 && path2.charCodeAt(1) === 58) {
1767
- const code2 = path2.charCodeAt(2);
1764
+ if (len > 2 && path.charCodeAt(1) === 58) {
1765
+ const code2 = path.charCodeAt(2);
1768
1766
  if (code2 === 47 || code2 === 92) {
1769
1767
  return true;
1770
1768
  }
@@ -1783,12 +1781,12 @@ var isWindows = (() => {
1783
1781
  var sep = isWindows ? "\\" : "/";
1784
1782
  var posix = createPathOps(false);
1785
1783
  var win32 = createPathOps(true);
1786
- function normalizePath2(path2, isWin) {
1787
- if (path2.length === 0) return ".";
1784
+ function normalizePath2(path, isWin) {
1785
+ if (path.length === 0) return ".";
1788
1786
  const separator = getSeparator(isWin);
1789
- const isAbsolute = isWin ? isAbsoluteWin(path2) : isAbsolutePosix(path2);
1790
- const trailingSeparator = path2[path2.length - 1] === separator || isWin && path2[path2.length - 1] === "/";
1791
- let normalized = path2.replace(isWin ? /[\/\\]+/g : /\/+/g, separator);
1787
+ const isAbsolute = isWin ? isAbsoluteWin(path) : isAbsolutePosix(path);
1788
+ const trailingSeparator = path[path.length - 1] === separator || isWin && path[path.length - 1] === "/";
1789
+ let normalized = path.replace(isWin ? /[\/\\]+/g : /\/+/g, separator);
1792
1790
  const parts = normalized.split(separator);
1793
1791
  const result = [];
1794
1792
  for (let i = 0; i < parts.length; i++) {
@@ -1823,12 +1821,12 @@ function joinPaths(paths, isWin) {
1823
1821
  const separator = getSeparator(isWin);
1824
1822
  let joined = "";
1825
1823
  for (let i = 0; i < paths.length; i++) {
1826
- const path2 = paths[i];
1827
- if (path2 && path2.length > 0) {
1824
+ const path = paths[i];
1825
+ if (path && path.length > 0) {
1828
1826
  if (joined.length === 0) {
1829
- joined = path2;
1827
+ joined = path;
1830
1828
  } else {
1831
- joined += separator + path2;
1829
+ joined += separator + path;
1832
1830
  }
1833
1831
  }
1834
1832
  }
@@ -1840,9 +1838,9 @@ function resolvePaths(paths, isWin) {
1840
1838
  let resolved = "";
1841
1839
  let isAbsolute = false;
1842
1840
  for (let i = paths.length - 1; i >= 0 && !isAbsolute; i--) {
1843
- const path2 = paths[i];
1844
- if (path2 && path2.length > 0) {
1845
- resolved = path2 + (resolved.length > 0 ? separator + resolved : "");
1841
+ const path = paths[i];
1842
+ if (path && path.length > 0) {
1843
+ resolved = path + (resolved.length > 0 ? separator + resolved : "");
1846
1844
  isAbsolute = isWin ? isAbsoluteWin(resolved) : isAbsolutePosix(resolved);
1847
1845
  }
1848
1846
  }
@@ -1878,51 +1876,51 @@ function relativePath(from, to, isWin) {
1878
1876
  }
1879
1877
  return result.join(separator) || ".";
1880
1878
  }
1881
- function getDirname(path2, isWin) {
1882
- if (path2.length === 0) return ".";
1879
+ function getDirname(path, isWin) {
1880
+ if (path.length === 0) return ".";
1883
1881
  const separator = getSeparator(isWin);
1884
- const normalized = normalizePath2(path2, isWin);
1882
+ const normalized = normalizePath2(path, isWin);
1885
1883
  const lastSepIndex = normalized.lastIndexOf(separator);
1886
1884
  if (lastSepIndex === -1) return ".";
1887
1885
  if (lastSepIndex === 0) return separator;
1888
1886
  return normalized.slice(0, lastSepIndex);
1889
1887
  }
1890
- function getBasename(path2, ext, isWin) {
1891
- if (path2.length === 0) return "";
1892
- const lastSepIndex = isWin ? findLastSeparator(path2) : path2.lastIndexOf("/");
1893
- let base = lastSepIndex === -1 ? path2 : path2.slice(lastSepIndex + 1);
1888
+ function getBasename(path, ext, isWin) {
1889
+ if (path.length === 0) return "";
1890
+ const lastSepIndex = isWin ? findLastSeparator(path) : path.lastIndexOf("/");
1891
+ let base = lastSepIndex === -1 ? path : path.slice(lastSepIndex + 1);
1894
1892
  if (ext && base.endsWith(ext)) {
1895
1893
  base = base.slice(0, base.length - ext.length);
1896
1894
  }
1897
1895
  return base;
1898
1896
  }
1899
- function getExtname(path2) {
1900
- const lastDotIndex = path2.lastIndexOf(".");
1901
- const lastSepIndex = findLastSeparator(path2);
1902
- if (lastDotIndex === -1 || lastDotIndex < lastSepIndex || lastDotIndex === path2.length - 1) {
1897
+ function getExtname(path) {
1898
+ const lastDotIndex = path.lastIndexOf(".");
1899
+ const lastSepIndex = findLastSeparator(path);
1900
+ if (lastDotIndex === -1 || lastDotIndex < lastSepIndex || lastDotIndex === path.length - 1) {
1903
1901
  return "";
1904
1902
  }
1905
- return path2.slice(lastDotIndex);
1903
+ return path.slice(lastDotIndex);
1906
1904
  }
1907
- function parsePath(path2, isWin) {
1905
+ function parsePath(path, isWin) {
1908
1906
  let root = "";
1909
1907
  if (isWin) {
1910
- if (path2.length >= 2 && path2[1] === ":") {
1911
- root = path2.slice(0, 2);
1912
- if (path2.length > 2 && (path2[2] === "\\" || path2[2] === "/")) {
1908
+ if (path.length >= 2 && path[1] === ":") {
1909
+ root = path.slice(0, 2);
1910
+ if (path.length > 2 && (path[2] === "\\" || path[2] === "/")) {
1913
1911
  root += "\\";
1914
1912
  }
1915
- } else if (path2[0] === "\\" || path2[0] === "/") {
1913
+ } else if (path[0] === "\\" || path[0] === "/") {
1916
1914
  root = "\\";
1917
1915
  }
1918
1916
  } else {
1919
- if (path2[0] === "/") {
1917
+ if (path[0] === "/") {
1920
1918
  root = "/";
1921
1919
  }
1922
1920
  }
1923
- const dir = getDirname(path2, isWin);
1924
- const base = getBasename(path2, void 0, isWin);
1925
- const ext = getExtname(path2);
1921
+ const dir = getDirname(path, isWin);
1922
+ const base = getBasename(path, void 0, isWin);
1923
+ const ext = getExtname(path);
1926
1924
  const name = ext ? base.slice(0, base.length - ext.length) : base;
1927
1925
  return { root, dir, base, ext, name };
1928
1926
  }
@@ -1934,8 +1932,8 @@ function formatPath(pathObject, isWin) {
1934
1932
  if (dir === pathObject.root) return dir + base;
1935
1933
  return dir + separator + base;
1936
1934
  }
1937
- function normalize(path2) {
1938
- return normalizePath2(path2, isWindows);
1935
+ function normalize(path) {
1936
+ return normalizePath2(path, isWindows);
1939
1937
  }
1940
1938
  function join(...paths) {
1941
1939
  return joinPaths(paths, isWindows);
@@ -1946,8 +1944,8 @@ function resolve(...paths) {
1946
1944
  function relative(from, to) {
1947
1945
  return relativePath(from, to, isWindows);
1948
1946
  }
1949
- function extname(path2) {
1950
- return getExtname(path2);
1947
+ function extname(path) {
1948
+ return getExtname(path);
1951
1949
  }
1952
1950
 
1953
1951
  // src/mime-types.ts
@@ -2030,12 +2028,12 @@ for (const ext in MIME_TYPES) {
2030
2028
  }
2031
2029
  TYPE_TO_EXTENSIONS[type].push(ext);
2032
2030
  }
2033
- function getExtension(path2) {
2034
- const match = /\.([^./\\]+)$/.exec(path2);
2031
+ function getExtension(path) {
2032
+ const match = /\.([^./\\]+)$/.exec(path);
2035
2033
  return match ? match[1].toLowerCase() : "";
2036
2034
  }
2037
- function lookup(path2) {
2038
- const ext = getExtension(path2) || path2.toLowerCase();
2035
+ function lookup(path) {
2036
+ const ext = getExtension(path) || path.toLowerCase();
2039
2037
  return MIME_TYPES[ext] || false;
2040
2038
  }
2041
2039
 
@@ -2682,497 +2680,29 @@ var dom = new DomNode();
2682
2680
  var render = dom.render.bind(dom);
2683
2681
  var renderToString = dom.renderToString.bind(dom);
2684
2682
 
2685
- // src/database.ts
2686
- var import_node_vm = __toESM(require("vm"));
2687
- var import_node_path = __toESM(require("path"));
2688
- var import_node_fs = __toESM(require("fs"));
2689
- var esbuild = __toESM(require("esbuild"));
2690
- var Database = class {
2691
- constructor(config) {
2692
- this._config = {
2693
- dir: resolve(process.cwd(), "databases")
2694
- };
2695
- this._config = { ...this._config, ...config };
2696
- this._registerModules = config.registerModules || {};
2697
- this._ctx = import_node_vm.default.createContext(this._registerModules);
2698
- }
2699
- set config(config) {
2700
- this._config = { ...this._config, ...config };
2701
- }
2702
- register(context) {
2703
- this._registerModules = { ...this._registerModules, ...context };
2704
- this._ctx = import_node_vm.default.createContext(this._registerModules);
2705
- }
2706
- plugin(moduleName, moduleContent) {
2707
- this.register({ [moduleName]: moduleContent });
2708
- }
2709
- resolvePath(fileList, query) {
2710
- const aliases = { "@db": this._config.dir || resolve(process.cwd(), "databases") };
2711
- let resolvedPath = query;
2712
- for (const [alias, target] of Object.entries(aliases)) {
2713
- if (resolvedPath.startsWith(alias + "/")) {
2714
- resolvedPath = resolvedPath.replace(alias, target);
2715
- break;
2716
- }
2717
- }
2718
- resolvedPath = import_node_path.default.normalize(resolvedPath);
2719
- return fileList.find((file) => {
2720
- const normalizedFile = import_node_path.default.normalize(file);
2721
- const fileWithoutExt = normalizedFile.replace(/\.[^/.]+$/, "");
2722
- return normalizedFile === resolvedPath || fileWithoutExt === resolvedPath || normalizedFile === resolvedPath + ".ts" || normalizedFile === resolvedPath + ".js";
2723
- });
2724
- }
2725
- async moduleLinker(specifier, referencingModule) {
2726
- 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));
2727
- const dbResult = this.resolvePath(dbFiles, specifier);
2728
- if (dbResult) {
2729
- try {
2730
- const actualModule = await import(dbResult);
2731
- const exportNames = Object.keys(actualModule);
2732
- return new import_node_vm.default.SyntheticModule(
2733
- exportNames,
2734
- function() {
2735
- exportNames.forEach((key) => {
2736
- this.setExport(key, actualModule[key]);
2737
- });
2738
- },
2739
- { identifier: specifier, context: referencingModule.context }
2740
- );
2741
- } catch (err) {
2742
- console.error(`Failed to load database module ${specifier}:`, err);
2743
- throw err;
2744
- }
2745
- }
2746
- throw new Error(`Module ${specifier} is not allowed or not found.`);
2747
- }
2748
- async vmRun(code, _options) {
2749
- const logs = [];
2750
- const customConsole = ["log", "error", "warn", "info", "debug", "trace"].reduce((acc, type) => {
2751
- acc[type] = (...args) => logs.push({ type, args });
2752
- return acc;
2753
- }, {});
2754
- const systemBase = {
2755
- update,
2756
- remove,
2757
- rename: rename2,
2758
- read,
2759
- create,
2760
- save
2761
- };
2762
- this.register({
2763
- dbConsole: { ...customConsole, ...systemBase }
2764
- });
2765
- let stringCode;
2766
- if (typeof code === "function") {
2767
- const funcStr = code.toString();
2768
- if (funcStr.includes("=>")) {
2769
- const arrowIndex = funcStr.indexOf("=>");
2770
- let start = arrowIndex + 2;
2771
- while (start < funcStr.length && funcStr[start] === " ") start++;
2772
- if (funcStr[start] === "{") start++;
2773
- let end = funcStr.lastIndexOf("}");
2774
- if (start < end) {
2775
- stringCode = funcStr.substring(start, end);
2776
- } else {
2777
- stringCode = funcStr.substring(start);
2778
- }
2779
- } else if (funcStr.includes("function")) {
2780
- const funcIndex = funcStr.indexOf("function");
2781
- let start = funcIndex + 8;
2782
- while (start < funcStr.length && funcStr[start] === " ") start++;
2783
- if (funcStr[start] === "(") start++;
2784
- if (start < funcStr.length && funcStr[start] !== "(") {
2785
- while (start < funcStr.length && funcStr[start] !== " " && funcStr[start] !== "(") start++;
2786
- }
2787
- if (funcStr[start] === "(") start++;
2788
- while (start < funcStr.length && funcStr[start] === " ") start++;
2789
- if (funcStr[start] === "{") start++;
2790
- const end = funcStr.lastIndexOf("}");
2791
- if (start < end) {
2792
- stringCode = funcStr.substring(start, end);
2793
- } else {
2794
- stringCode = funcStr.substring(start);
2795
- }
2796
- } else {
2797
- stringCode = funcStr;
2798
- }
2799
- stringCode = stringCode.trim();
2800
- let importPos = 0;
2801
- while ((importPos = stringCode.indexOf("import(", importPos)) !== -1) {
2802
- const fromPos = stringCode.indexOf(".from(", importPos);
2803
- if (fromPos === -1) break;
2804
- const quoteStart = stringCode.indexOf("(", fromPos + 7) + 1;
2805
- if (quoteStart === -1) break;
2806
- const quoteChar = stringCode[quoteStart];
2807
- if (quoteChar !== '"' && quoteChar !== "'") break;
2808
- const quoteEnd = stringCode.indexOf(quoteChar, quoteStart + 1);
2809
- if (quoteEnd === -1) break;
2810
- const modulePath = stringCode.substring(quoteStart + 1, quoteEnd);
2811
- const importArgEnd = fromPos - 1;
2812
- const importArgStart = importPos + 7;
2813
- const trimmed = stringCode.substring(importArgStart, importArgEnd).trim();
2814
- let replacement;
2815
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
2816
- const inner = trimmed.slice(1, -1).trim();
2817
- replacement = `import { ${inner} } from "${modulePath}"`;
2818
- } else {
2819
- replacement = `import ${trimmed} from "${modulePath}"`;
2820
- }
2821
- const before = stringCode.substring(0, importPos);
2822
- const after = stringCode.substring(quoteEnd + 2);
2823
- stringCode = before + replacement + after;
2824
- }
2825
- const lines = stringCode.split("\n");
2826
- const trimmedLines = lines.map((line) => line.trim());
2827
- stringCode = trimmedLines.join("\n").trim();
2828
- } else {
2829
- stringCode = code;
2830
- }
2831
- const result = await esbuild.build({
2832
- stdin: {
2833
- contents: stringCode,
2834
- loader: this._config.language || "ts"
2835
- },
2836
- format: "esm",
2837
- target: "es2020",
2838
- write: false,
2839
- bundle: false,
2840
- sourcemap: false
2841
- });
2842
- const js = result.outputFiles[0].text;
2843
- 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") });
2844
- await mod.link(this.moduleLinker.bind(this));
2845
- await mod.evaluate();
2846
- return {
2847
- namespace: mod.namespace,
2848
- logs
2849
- };
2850
- }
2851
- /**
2852
- * Execute database code and return results
2853
- */
2854
- async execute(code, options) {
2855
- return await this.vmRun(code, options);
2856
- }
2857
- };
2858
- function create(dbName, code) {
2859
- const DIR = "databases";
2860
- const basePath = process.cwd();
2861
- const baseDir = import_node_path.default.resolve(basePath, DIR);
2862
- const dbPath = import_node_path.default.join(baseDir, `${dbName}.ts`);
2863
- import_node_fs.default.appendFileSync(dbPath, code.toString(), "utf8");
2864
- }
2865
- function read(dbName) {
2866
- const DIR = "databases";
2867
- const basePath = process.cwd();
2868
- const baseDir = import_node_path.default.resolve(basePath, DIR);
2869
- const dbPath = import_node_path.default.join(baseDir, `${dbName}.ts`);
2870
- if (!import_node_fs.default.existsSync(dbPath)) {
2871
- throw new Error(`Database '${dbName}' not found`);
2872
- }
2873
- return import_node_fs.default.readFileSync(dbPath, "utf8");
2874
- }
2875
- function remove(dbName, fnName) {
2876
- const DIR = "databases";
2877
- const basePath = process.cwd();
2878
- const baseDir = import_node_path.default.resolve(basePath, DIR);
2879
- const dbPath = import_node_path.default.join(baseDir, `${dbName}.ts`);
2880
- if (!import_node_fs.default.existsSync(dbPath)) return false;
2881
- if (!fnName) {
2882
- const bak2 = `${dbPath}.bak`;
2883
- try {
2884
- import_node_fs.default.copyFileSync(dbPath, bak2);
2885
- } catch (e) {
2886
- }
2887
- try {
2888
- import_node_fs.default.unlinkSync(dbPath);
2889
- return "Removed successfully";
2890
- } catch (e) {
2891
- return "Removed failed";
2892
- }
2893
- }
2894
- const bak = `${dbPath}.bak`;
2895
- try {
2896
- import_node_fs.default.copyFileSync(dbPath, bak);
2897
- } catch (e) {
2898
- }
2899
- let src = import_node_fs.default.readFileSync(dbPath, "utf8");
2900
- const escaped = fnName.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
2901
- const startRe = new RegExp(
2902
- `function\\s+${escaped}\\s*\\(|\\bclass\\s+${escaped}\\b|\\b(?:const|let|var)\\s+${escaped}\\s*=\\s*(?:function\\b|class\\b|\\(|\\{|\\[)`,
2903
- "m"
2904
- );
2905
- const startMatch = src.match(startRe);
2906
- if (startMatch) {
2907
- const startIdx = startMatch.index;
2908
- const len = src.length;
2909
- const idxCurly = src.indexOf("{", startIdx);
2910
- const idxBracket = src.indexOf("[", startIdx);
2911
- let braceOpen = -1;
2912
- if (idxCurly === -1) braceOpen = idxBracket;
2913
- else if (idxBracket === -1) braceOpen = idxCurly;
2914
- else braceOpen = Math.min(idxCurly, idxBracket);
2915
- if (braceOpen !== -1) {
2916
- const openingChar = src[braceOpen];
2917
- const closingChar = openingChar === "[" ? "]" : "}";
2918
- let i = braceOpen + 1;
2919
- let depth = 1;
2920
- while (i < len && depth > 0) {
2921
- const ch = src[i];
2922
- if (ch === openingChar) depth++;
2923
- else if (ch === closingChar) depth--;
2924
- i++;
2925
- }
2926
- let braceClose = i;
2927
- let endIdx = braceClose;
2928
- if (src.slice(braceClose, braceClose + 1) === ";")
2929
- endIdx = braceClose + 1;
2930
- const before = src.slice(0, startIdx);
2931
- const after = src.slice(endIdx);
2932
- src = before + after;
2933
- } else {
2934
- const semi = src.indexOf(";", startIdx);
2935
- let endIdx = semi !== -1 ? semi + 1 : src.indexOf("\n\n", startIdx);
2936
- if (endIdx === -1) endIdx = len;
2937
- src = src.slice(0, startIdx) + src.slice(endIdx);
2938
- }
2939
- }
2940
- const exportRe = new RegExp(
2941
- `export\\s+const\\s+${escaped}\\s*:\\s*any\\s*=\\s*${escaped}\\s*;?`,
2942
- "g"
2943
- );
2944
- src = src.replace(exportRe, "");
2945
- src = src.replace(/\n{3,}/g, "\n\n");
2946
- import_node_fs.default.writeFileSync(dbPath, src, "utf8");
2947
- return `Removed ${fnName} from database ${dbName}.`;
2948
- }
2949
- function rename2(oldName, newName) {
2950
- const DIR = "databases";
2951
- const basePath = process.cwd();
2952
- const baseDir = import_node_path.default.resolve(basePath, DIR);
2953
- const oldPath = import_node_path.default.join(baseDir, `${oldName}.ts`);
2954
- const newPath = import_node_path.default.join(baseDir, `${newName}.ts`);
2955
- if (!import_node_fs.default.existsSync(oldPath)) {
2956
- return `Error: File '${oldName}.ts' does not exist in the database`;
2957
- }
2958
- if (import_node_fs.default.existsSync(newPath)) {
2959
- return `Error: File '${newName}.ts' already exists in the database`;
2960
- }
2961
- try {
2962
- import_node_fs.default.renameSync(oldPath, newPath);
2963
- return `Successfully renamed '${oldName}.ts' to '${newName}.ts'`;
2964
- } catch (error) {
2965
- return `Error renaming file: ${error instanceof Error ? error.message : String(error)}`;
2966
- }
2967
- }
2968
- function save(dbName, code) {
2969
- const DIR = "databases";
2970
- const basePath = process.cwd();
2971
- const baseDir = import_node_path.default.resolve(basePath, DIR);
2972
- const dbPath = import_node_path.default.join(baseDir, `${dbName}.ts`);
2973
- let fileContent = typeof code === "function" ? code.toString() : code;
2974
- import_node_fs.default.writeFileSync(dbPath, fileContent, "utf8");
2975
- }
2976
- function update(dbName, fnName, code) {
2977
- const DIR = "databases";
2978
- const basePath = process.cwd();
2979
- const baseDir = import_node_path.default.resolve(basePath, DIR);
2980
- const dbPath = import_node_path.default.join(baseDir, `${dbName}.ts`);
2981
- let src;
2982
- if (!import_node_fs.default.existsSync(dbPath)) {
2983
- try {
2984
- import_node_fs.default.writeFileSync(dbPath, "", "utf8");
2985
- return `Created new database file: ${dbPath}`;
2986
- } catch (e) {
2987
- return `Failed to create dbPath file: ${dbPath}`;
2988
- }
2989
- }
2990
- src = import_node_fs.default.readFileSync(dbPath, "utf8");
2991
- const originalSrc = src;
2992
- const escaped = fnName.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
2993
- const startRe = new RegExp(
2994
- `function\\s+${escaped}\\s*\\(|\\bclass\\s+${escaped}\\b|\\b(?:const|let|var)\\s+${escaped}\\s*=\\s*(?:function\\b|class\\b|\\(|\\{|\\[)`,
2995
- "m"
2996
- );
2997
- const startMatch = src.match(startRe);
2998
- let declKind = null;
2999
- if (startMatch) {
3000
- let startIdx = startMatch.index;
3001
- const snippet = src.slice(startIdx, startIdx + 80);
3002
- if (/^function\b/.test(snippet)) declKind = "functionDecl";
3003
- else if (/^class\b/.test(snippet)) declKind = "classDecl";
3004
- else if (/^\b(?:const|let|var)\b/.test(snippet)) declKind = "varAssign";
3005
- }
3006
- let newCode;
3007
- if (typeof code === "function") {
3008
- const fnStr = code.toString();
3009
- if (declKind === "functionDecl") {
3010
- if (/^function\s+\w+/.test(fnStr)) newCode = fnStr;
3011
- else
3012
- newCode = `function ${fnName}${fnStr.replace(
3013
- /^function\s*\(/,
3014
- "("
3015
- )}`;
3016
- } else if (declKind === "classDecl") {
3017
- if (/^class\s+\w+/.test(fnStr)) newCode = fnStr;
3018
- else if (/^class\s*\{/.test(fnStr))
3019
- newCode = fnStr.replace(/^class\s*\{/, `class ${fnName} {`);
3020
- else newCode = `const ${fnName} = ${fnStr};`;
3021
- } else {
3022
- newCode = `const ${fnName} = ${fnStr};`;
3023
- }
3024
- } else {
3025
- newCode = `const ${fnName} = ${valueToCode(code, 0)};`;
3026
- }
3027
- if (startMatch) {
3028
- const startIdx = startMatch.index;
3029
- const idxCurly = src.indexOf("{", startIdx);
3030
- const idxBracket = src.indexOf("[", startIdx);
3031
- let braceOpen = -1;
3032
- if (idxCurly === -1) braceOpen = idxBracket;
3033
- else if (idxBracket === -1) braceOpen = idxCurly;
3034
- else braceOpen = Math.min(idxCurly, idxBracket);
3035
- if (braceOpen === -1) {
3036
- const exportRe = new RegExp(
3037
- `export\\s+const\\s+${escaped}\\s*:\\s*any\\s*=\\s*${escaped}\\s*;?`,
3038
- "m"
3039
- );
3040
- if (exportRe.test(src)) {
3041
- src = src.replace(
3042
- exportRe,
3043
- `${newCode}
3044
-
3045
- export const ${fnName}: any = ${fnName};`
3046
- );
3047
- } else {
3048
- src = src + `
3049
-
3050
- ${newCode}
3051
-
3052
- export const ${fnName}: any = ${fnName};`;
3053
- }
3054
- } else {
3055
- const openingChar = src[braceOpen];
3056
- const closingChar = openingChar === "[" ? "]" : "}";
3057
- let i = braceOpen + 1;
3058
- let depth = 1;
3059
- const len = src.length;
3060
- while (i < len && depth > 0) {
3061
- const ch = src[i];
3062
- if (ch === openingChar) depth++;
3063
- else if (ch === closingChar) depth--;
3064
- i++;
3065
- }
3066
- let braceClose = i;
3067
- let endIdx = braceClose;
3068
- if (src.slice(braceClose, braceClose + 1) === ";")
3069
- endIdx = braceClose + 1;
3070
- const before = src.slice(0, startIdx);
3071
- const after = src.slice(endIdx);
3072
- src = before + newCode + after;
3073
- }
3074
- } else {
3075
- const exportRe = new RegExp(
3076
- `export\\s+const\\s+${escaped}\\s*:\\s*any\\s*=\\s*${escaped}\\s*;?`,
3077
- "m"
3078
- );
3079
- if (exportRe.test(src)) {
3080
- src = src.replace(
3081
- exportRe,
3082
- `${newCode}
3083
-
3084
- export const ${fnName}: any = ${fnName};`
3085
- );
3086
- } else {
3087
- src = src + `
3088
-
3089
- ${newCode}
3090
-
3091
- export const ${fnName}: any = ${fnName};`;
3092
- }
3093
- }
3094
- import_node_fs.default.writeFileSync(dbPath, src, "utf8");
3095
- if (src === originalSrc) {
3096
- return `Saved ${fnName} to database ${dbName}.`;
3097
- } else {
3098
- return `Updated ${dbName} with ${fnName}.`;
3099
- }
3100
- }
3101
- function valueToCode(val, depth = 0) {
3102
- const indentUnit = " ";
3103
- const indent = indentUnit.repeat(depth);
3104
- const indentInner = indentUnit.repeat(depth + 1);
3105
- if (val === null) return "null";
3106
- const t = typeof val;
3107
- if (t === "string") return JSON.stringify(val);
3108
- if (t === "number" || t === "boolean") return String(val);
3109
- if (t === "function") return val.toString();
3110
- if (Array.isArray(val)) {
3111
- if (val.length === 0) return "[]";
3112
- const items = val.map((v) => valueToCode(v, depth + 1));
3113
- return "[\n" + items.map((it) => indentInner + it).join(",\n") + "\n" + indent + "]";
3114
- }
3115
- if (t === "object") {
3116
- const keys = Object.keys(val);
3117
- if (keys.length === 0) return "{}";
3118
- const entries = keys.map((k) => {
3119
- const keyPart = isIdentifier(k) ? k : JSON.stringify(k);
3120
- const v = valueToCode(val[k], depth + 1);
3121
- return indentInner + keyPart + ": " + v;
3122
- });
3123
- return "{\n" + entries.join(",\n") + "\n" + indent + "}";
3124
- }
3125
- return String(val);
3126
- }
3127
- function isIdentifier(key) {
3128
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);
3129
- }
3130
- var dbConsole = {
3131
- create,
3132
- read,
3133
- remove,
3134
- rename: rename2,
3135
- save,
3136
- update,
3137
- ...console
3138
- };
3139
-
3140
2683
  // src/server.ts
3141
- var ServerDatabase = class {
3142
- constructor() {
3143
- this._db = null;
3144
- }
3145
- async initialize(config) {
3146
- this._db = new Database(config);
3147
- }
3148
- database() {
3149
- return this._db;
3150
- }
3151
- };
3152
- var serverDatabase = new ServerDatabase();
3153
- var database = serverDatabase.database;
3154
2684
  var ServerRouter = class {
3155
2685
  constructor() {
3156
2686
  this.routes = [];
3157
2687
  this.middlewares = [];
3158
2688
  // Express-like .all() method - matches all HTTP methods
3159
- this.all = (path2, ...handlers) => this.addRoute("ALL", path2, handlers);
2689
+ this.all = (path, ...handlers) => this.addRoute("ALL", path, handlers);
3160
2690
  // Support per-route middleware: accept middleware(s) before the final handler
3161
- this.get = (path2, ...handlers) => this.addRoute("GET", path2, handlers);
3162
- this.post = (path2, ...handlers) => this.addRoute("POST", path2, handlers);
3163
- this.put = (path2, ...handlers) => this.addRoute("PUT", path2, handlers);
3164
- this.delete = (path2, ...handlers) => this.addRoute("DELETE", path2, handlers);
3165
- this.patch = (path2, ...handlers) => this.addRoute("PATCH", path2, handlers);
3166
- this.options = (path2, ...handlers) => this.addRoute("OPTIONS", path2, handlers);
3167
- this.head = (path2, ...handlers) => this.addRoute("HEAD", path2, handlers);
2691
+ this.get = (path, ...handlers) => this.addRoute("GET", path, handlers);
2692
+ this.post = (path, ...handlers) => this.addRoute("POST", path, handlers);
2693
+ this.put = (path, ...handlers) => this.addRoute("PUT", path, handlers);
2694
+ this.delete = (path, ...handlers) => this.addRoute("DELETE", path, handlers);
2695
+ this.patch = (path, ...handlers) => this.addRoute("PATCH", path, handlers);
2696
+ this.options = (path, ...handlers) => this.addRoute("OPTIONS", path, handlers);
2697
+ this.head = (path, ...handlers) => this.addRoute("HEAD", path, handlers);
3168
2698
  }
3169
2699
  // Accept both internal Middleware and Express-style `(req, res, next?)` functions
3170
2700
  // Also support path-based middleware like Express: use(path, middleware)
3171
2701
  use(...args) {
3172
2702
  if (typeof args[0] === "string") {
3173
- const path2 = args[0];
2703
+ const path = args[0];
3174
2704
  const middlewares = args.slice(1);
3175
- return this.addRoute("ALL", path2, middlewares);
2705
+ return this.addRoute("ALL", path, middlewares);
3176
2706
  }
3177
2707
  const mw = args[0];
3178
2708
  this.middlewares.push(this.toMiddleware(mw));
@@ -3203,8 +2733,8 @@ var ServerRouter = class {
3203
2733
  await next();
3204
2734
  };
3205
2735
  }
3206
- addRoute(method, path2, handlers) {
3207
- const { pattern, paramNames } = this.pathToRegex(path2);
2736
+ addRoute(method, path, handlers) {
2737
+ const { pattern, paramNames } = this.pathToRegex(path);
3208
2738
  if (!handlers || handlers.length === 0) throw new Error("Route must include a handler");
3209
2739
  const rawMiddlewares = handlers.slice(0, handlers.length - 1);
3210
2740
  const rawLast = handlers[handlers.length - 1];
@@ -3233,9 +2763,9 @@ var ServerRouter = class {
3233
2763
  this.routes.push({ method, pattern, paramNames, handler: last, middlewares });
3234
2764
  return this;
3235
2765
  }
3236
- pathToRegex(path2) {
2766
+ pathToRegex(path) {
3237
2767
  const paramNames = [];
3238
- const pattern = path2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\//g, "\\/").replace(/:(\w+)/g, (_, name) => (paramNames.push(name), "([^\\/]+)"));
2768
+ const pattern = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\//g, "\\/").replace(/:(\w+)/g, (_, name) => (paramNames.push(name), "([^\\/]+)"));
3239
2769
  return { pattern: new RegExp(`^${pattern}$`), paramNames };
3240
2770
  }
3241
2771
  parseQuery(url) {
@@ -3293,11 +2823,11 @@ var ServerRouter = class {
3293
2823
  });
3294
2824
  }
3295
2825
  async handle(req, res) {
3296
- const method = req.method, url = req.url || "/", path2 = url.split("?")[0];
2826
+ const method = req.method, url = req.url || "/", path = url.split("?")[0];
3297
2827
  for (const route of this.routes) {
3298
2828
  if (route.method !== "ALL" && route.method !== method) continue;
3299
- if (!route.pattern.test(path2)) continue;
3300
- const match = path2.match(route.pattern);
2829
+ if (!route.pattern.test(path)) continue;
2830
+ const match = path.match(route.pattern);
3301
2831
  const params = Object.fromEntries(route.paramNames.map((name, i2) => [name, match[i2 + 1]]));
3302
2832
  let body = {};
3303
2833
  if (["POST", "PUT", "PATCH"].includes(method)) {
@@ -3732,21 +3262,21 @@ function security() {
3732
3262
  await next();
3733
3263
  };
3734
3264
  }
3735
- function rewritePath(path2, pathRewrite) {
3736
- if (!pathRewrite) return path2;
3265
+ function rewritePath(path, pathRewrite) {
3266
+ if (!pathRewrite) return path;
3737
3267
  for (const [from, to] of Object.entries(pathRewrite)) {
3738
3268
  const regex = new RegExp(from);
3739
- if (regex.test(path2)) {
3740
- return path2.replace(regex, to);
3269
+ if (regex.test(path)) {
3270
+ return path.replace(regex, to);
3741
3271
  }
3742
3272
  }
3743
- return path2;
3273
+ return path;
3744
3274
  }
3745
3275
  function createProxyHandler(proxyConfigs) {
3746
3276
  return async (req, res) => {
3747
3277
  const url = req.url || "/";
3748
- const path2 = url.split("?")[0];
3749
- const proxy = proxyConfigs.find((p) => path2.startsWith(p.context));
3278
+ const path = url.split("?")[0];
3279
+ const proxy = proxyConfigs.find((p) => path.startsWith(p.context));
3750
3280
  if (!proxy) return false;
3751
3281
  const { target, changeOrigin, pathRewrite, headers } = proxy;
3752
3282
  try {
@@ -3798,7 +3328,7 @@ function createProxyHandler(proxyConfigs) {
3798
3328
  req.on("end", () => proxyReq.end());
3799
3329
  return true;
3800
3330
  } catch (error) {
3801
- console.error("[Proxy] Invalid proxy configuration for %s:", path2, error);
3331
+ console.error("[Proxy] Invalid proxy configuration for %s:", path, error);
3802
3332
  return false;
3803
3333
  }
3804
3334
  };
@@ -3919,9 +3449,6 @@ function createDevServer(options) {
3919
3449
  if (config.mode === "dev") {
3920
3450
  clearImportMapCache();
3921
3451
  }
3922
- serverDatabase.initialize(config.database ? config.database : {
3923
- dir: resolve(process.cwd(), "databases")
3924
- });
3925
3452
  const clientsToNormalize = config.clients?.length ? config.clients : config.root ? [{ root: config.root, basePath: config.basePath || "", index: config.index, ssr: config.ssr, api: config.api, proxy: config.proxy, mode: config.mode }] : null;
3926
3453
  if (!clientsToNormalize) throw new Error('DevServerOptions must include either "clients" array or "root" directory');
3927
3454
  const normalizedClients = clientsToNormalize.map((client) => {
@@ -4213,8 +3740,8 @@ export default css;
4213
3740
  });
4214
3741
  transpiled = transpiler.transformSync(content.toString());
4215
3742
  } else {
4216
- const { build: build2 } = await import("esbuild");
4217
- const result = await build2({
3743
+ const { build } = await import("esbuild");
3744
+ const result = await build({
4218
3745
  stdin: {
4219
3746
  contents: content.toString(),
4220
3747
  loader: ext === ".tsx" ? "tsx" : "ts",
@@ -4231,19 +3758,19 @@ export default css;
4231
3758
  }
4232
3759
  transpiled = transpiled.replace(
4233
3760
  /from\s+["']([^"']+)\.ts(x?)["']/g,
4234
- (_, path2, tsx) => `from "${path2}.js${tsx}"`
3761
+ (_, path, tsx) => `from "${path}.js${tsx}"`
4235
3762
  );
4236
3763
  transpiled = transpiled.replace(
4237
3764
  /import\s+["']([^"']+)\.ts(x?)["']/g,
4238
- (_, path2, tsx) => `import "${path2}.js${tsx}"`
3765
+ (_, path, tsx) => `import "${path}.js${tsx}"`
4239
3766
  );
4240
3767
  transpiled = transpiled.replace(
4241
3768
  /import\s+["']([^"']+\.css)["']/g,
4242
- (_, path2) => `import "${path2}?inline"`
3769
+ (_, path) => `import "${path}?inline"`
4243
3770
  );
4244
3771
  transpiled = transpiled.replace(
4245
3772
  /from\s+["']([^"']+\.css)["']/g,
4246
- (_, path2) => `from "${path2}?inline"`
3773
+ (_, path) => `from "${path}?inline"`
4247
3774
  );
4248
3775
  content = Buffer.from(transpiled);
4249
3776
  mimeType = "application/javascript";
@@ -4405,17 +3932,17 @@ ${elitImportMap}` : elitImportMap;
4405
3932
  (client) => config.watch.map((pattern) => join(client.root, pattern))
4406
3933
  );
4407
3934
  const watcher = watch(watchPaths, {
4408
- ignored: (path2) => config.ignore.some((pattern) => path2.includes(pattern.replace("/**", "").replace("**/", ""))),
3935
+ ignored: (path) => config.ignore.some((pattern) => path.includes(pattern.replace("/**", "").replace("**/", ""))),
4409
3936
  ignoreInitial: true,
4410
3937
  persistent: true
4411
3938
  });
4412
- watcher.on("change", (path2) => {
4413
- if (config.logging) console.log(`[HMR] File changed: ${path2}`);
4414
- const message = JSON.stringify({ type: "update", path: path2, timestamp: Date.now() });
3939
+ watcher.on("change", (path) => {
3940
+ if (config.logging) console.log(`[HMR] File changed: ${path}`);
3941
+ const message = JSON.stringify({ type: "update", path, timestamp: Date.now() });
4415
3942
  wsClients.forEach((client) => client.readyState === 1 /* OPEN */ && client.send(message));
4416
3943
  });
4417
- watcher.on("add", (path2) => config.logging && console.log(`[HMR] File added: ${path2}`));
4418
- watcher.on("unlink", (path2) => config.logging && console.log(`[HMR] File removed: ${path2}`));
3944
+ watcher.on("add", (path) => config.logging && console.log(`[HMR] File added: ${path}`));
3945
+ watcher.on("unlink", (path) => config.logging && console.log(`[HMR] File removed: ${path}`));
4419
3946
  server.setMaxListeners(20);
4420
3947
  server.listen(config.port, config.host, () => {
4421
3948
  if (config.logging) {
@@ -4488,14 +4015,12 @@ ${elitImportMap}` : elitImportMap;
4488
4015
  cors,
4489
4016
  createDevServer,
4490
4017
  createProxyHandler,
4491
- database,
4492
4018
  errorHandler,
4493
4019
  html,
4494
4020
  json,
4495
4021
  logger,
4496
4022
  rateLimit,
4497
4023
  security,
4498
- serverDatabase,
4499
4024
  status,
4500
4025
  text
4501
4026
  });