asaihost-nodejs 0.0.1 → 0.0.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.
Files changed (79) hide show
  1. package/README.md +76 -25
  2. package/dist/InterventionLog-CRP6YJVM.cjs +30 -0
  3. package/dist/{InterventionLog-25EHE4QR.cjs.map → InterventionLog-CRP6YJVM.cjs.map} +1 -1
  4. package/dist/{InterventionLog-R6CCPU2B.es.js → InterventionLog-PZT2CCN3.es.js} +5 -5
  5. package/dist/LogStore-7MTUQA4G.cjs +54 -0
  6. package/dist/{LogStore-M2AUBNGO.cjs.map → LogStore-7MTUQA4G.cjs.map} +1 -1
  7. package/dist/{LogStore-ECXX34WC.es.js → LogStore-Q35YFNAY.es.js} +3 -3
  8. package/dist/asaihost-nodejs.cjs +1296 -1410
  9. package/dist/asaihost-nodejs.cjs.map +1 -1
  10. package/dist/asaihost-nodejs.d.cts +154 -17
  11. package/dist/asaihost-nodejs.d.ts +154 -17
  12. package/dist/asaihost-nodejs.es.js +911 -1025
  13. package/dist/asaihost-nodejs.es.js.map +1 -1
  14. package/dist/{chunk-HHPGUJ75.cjs → chunk-2BCIIKRG.cjs} +13 -6
  15. package/dist/chunk-2BCIIKRG.cjs.map +1 -0
  16. package/dist/{chunk-G4WVDUBH.cjs → chunk-4E7Z5K5U.cjs} +7 -7
  17. package/dist/{chunk-G4WVDUBH.cjs.map → chunk-4E7Z5K5U.cjs.map} +1 -1
  18. package/dist/{chunk-DROOHKB3.es.js → chunk-57UQJKSL.es.js} +2 -2
  19. package/dist/{chunk-EOGZPRML.es.js → chunk-A5CDJGJI.es.js} +224 -39
  20. package/dist/chunk-A5CDJGJI.es.js.map +1 -0
  21. package/dist/{chunk-E7V3EBDB.es.js → chunk-A6VJPLDD.es.js} +5 -3
  22. package/dist/chunk-A6VJPLDD.es.js.map +1 -0
  23. package/dist/{chunk-X7VHW2TD.cjs → chunk-H3K33HBA.cjs} +249 -64
  24. package/dist/chunk-H3K33HBA.cjs.map +1 -0
  25. package/dist/{chunk-KOFCBB3N.cjs → chunk-K2QPSQEV.cjs} +9 -9
  26. package/dist/{chunk-KOFCBB3N.cjs.map → chunk-K2QPSQEV.cjs.map} +1 -1
  27. package/dist/{chunk-LOMSUPPU.es.js → chunk-LTEP4XB2.es.js} +6 -6
  28. package/dist/{chunk-QWVR2HNT.cjs → chunk-LXJMGLKW.cjs} +21 -19
  29. package/dist/chunk-LXJMGLKW.cjs.map +1 -0
  30. package/dist/{chunk-4WJDC4M4.es.js → chunk-NLZNIGNF.es.js} +2 -2
  31. package/dist/chunk-NLZNIGNF.es.js.map +1 -0
  32. package/dist/{chunk-W7DVKGX5.cjs → chunk-OCEBEEP5.cjs} +2 -2
  33. package/dist/{chunk-W7DVKGX5.cjs.map → chunk-OCEBEEP5.cjs.map} +1 -1
  34. package/dist/{chunk-NLBFIRDB.cjs → chunk-RIRKIYET.cjs} +12 -12
  35. package/dist/{chunk-NLBFIRDB.cjs.map → chunk-RIRKIYET.cjs.map} +1 -1
  36. package/dist/{chunk-XBIN4C2V.es.js → chunk-SB23ESX2.es.js} +2 -2
  37. package/dist/{chunk-VLMM735Q.cjs → chunk-TKJAHTPO.cjs} +26 -26
  38. package/dist/{chunk-VLMM735Q.cjs.map → chunk-TKJAHTPO.cjs.map} +1 -1
  39. package/dist/{chunk-MCMADJQR.es.js → chunk-VUZO7DCA.es.js} +4 -4
  40. package/dist/chunk-VUZO7DCA.es.js.map +1 -0
  41. package/dist/{chunk-KUZQ36IJ.es.js → chunk-ZQBHJRAO.es.js} +10 -3
  42. package/dist/chunk-ZQBHJRAO.es.js.map +1 -0
  43. package/dist/intervention-hooks-KF3SNB5Q.cjs +21 -0
  44. package/dist/{intervention-hooks-LE6X4C6N.cjs.map → intervention-hooks-KF3SNB5Q.cjs.map} +1 -1
  45. package/dist/{intervention-hooks-FI4EHOL5.es.js → intervention-hooks-TCGIC4IV.es.js} +6 -6
  46. package/dist/log-formats-TUXGMCCU.cjs +31 -0
  47. package/dist/{log-formats-FKFMQKNO.cjs.map → log-formats-TUXGMCCU.cjs.map} +1 -1
  48. package/dist/{log-formats-I5E32H5F.es.js → log-formats-WW3TDUAK.es.js} +2 -2
  49. package/dist/{password-63OY27RX.es.js → password-4BABWAG4.es.js} +4 -4
  50. package/dist/password-PJHJRGPE.cjs +20 -0
  51. package/dist/{password-NZ5EGDWG.cjs.map → password-PJHJRGPE.cjs.map} +1 -1
  52. package/dist/user-store-6J2PSEIN.cjs +12 -0
  53. package/dist/{user-store-SX4N6PQ4.cjs.map → user-store-6J2PSEIN.cjs.map} +1 -1
  54. package/dist/user-store-UC5URX3C.es.js +12 -0
  55. package/package.json +2 -13
  56. package/dist/InterventionLog-25EHE4QR.cjs +0 -30
  57. package/dist/LogStore-M2AUBNGO.cjs +0 -54
  58. package/dist/chunk-4WJDC4M4.es.js.map +0 -1
  59. package/dist/chunk-E7V3EBDB.es.js.map +0 -1
  60. package/dist/chunk-EOGZPRML.es.js.map +0 -1
  61. package/dist/chunk-HHPGUJ75.cjs.map +0 -1
  62. package/dist/chunk-KUZQ36IJ.es.js.map +0 -1
  63. package/dist/chunk-MCMADJQR.es.js.map +0 -1
  64. package/dist/chunk-QWVR2HNT.cjs.map +0 -1
  65. package/dist/chunk-X7VHW2TD.cjs.map +0 -1
  66. package/dist/intervention-hooks-LE6X4C6N.cjs +0 -21
  67. package/dist/log-formats-FKFMQKNO.cjs +0 -31
  68. package/dist/password-NZ5EGDWG.cjs +0 -20
  69. package/dist/user-store-J7LWEXSW.es.js +0 -12
  70. package/dist/user-store-SX4N6PQ4.cjs +0 -12
  71. /package/dist/{InterventionLog-R6CCPU2B.es.js.map → InterventionLog-PZT2CCN3.es.js.map} +0 -0
  72. /package/dist/{LogStore-ECXX34WC.es.js.map → LogStore-Q35YFNAY.es.js.map} +0 -0
  73. /package/dist/{chunk-DROOHKB3.es.js.map → chunk-57UQJKSL.es.js.map} +0 -0
  74. /package/dist/{chunk-LOMSUPPU.es.js.map → chunk-LTEP4XB2.es.js.map} +0 -0
  75. /package/dist/{chunk-XBIN4C2V.es.js.map → chunk-SB23ESX2.es.js.map} +0 -0
  76. /package/dist/{intervention-hooks-FI4EHOL5.es.js.map → intervention-hooks-TCGIC4IV.es.js.map} +0 -0
  77. /package/dist/{log-formats-I5E32H5F.es.js.map → log-formats-WW3TDUAK.es.js.map} +0 -0
  78. /package/dist/{password-63OY27RX.es.js.map → password-4BABWAG4.es.js.map} +0 -0
  79. /package/dist/{user-store-J7LWEXSW.es.js.map → user-store-UC5URX3C.es.js.map} +0 -0
@@ -4,10 +4,10 @@
4
4
 
5
5
 
6
6
 
7
- var _chunkNLBFIRDBcjs = require('./chunk-NLBFIRDB.cjs');
7
+ var _chunkRIRKIYETcjs = require('./chunk-RIRKIYET.cjs');
8
8
 
9
9
 
10
- var _chunkG4WVDUBHcjs = require('./chunk-G4WVDUBH.cjs');
10
+ var _chunk4E7Z5K5Ucjs = require('./chunk-4E7Z5K5U.cjs');
11
11
 
12
12
 
13
13
 
@@ -28,7 +28,7 @@ var _chunkG4WVDUBHcjs = require('./chunk-G4WVDUBH.cjs');
28
28
 
29
29
 
30
30
 
31
- var _chunkVLMM735Qcjs = require('./chunk-VLMM735Q.cjs');
31
+ var _chunkTKJAHTPOcjs = require('./chunk-TKJAHTPO.cjs');
32
32
 
33
33
 
34
34
 
@@ -38,7 +38,7 @@ var _chunkVLMM735Qcjs = require('./chunk-VLMM735Q.cjs');
38
38
 
39
39
 
40
40
 
41
- var _chunkW7DVKGX5cjs = require('./chunk-W7DVKGX5.cjs');
41
+ var _chunkOCEBEEP5cjs = require('./chunk-OCEBEEP5.cjs');
42
42
 
43
43
 
44
44
  var _chunkO6LVLSNBcjs = require('./chunk-O6LVLSNB.cjs');
@@ -48,7 +48,7 @@ var _chunkO6LVLSNBcjs = require('./chunk-O6LVLSNB.cjs');
48
48
 
49
49
 
50
50
 
51
- var _chunkKOFCBB3Ncjs = require('./chunk-KOFCBB3N.cjs');
51
+ var _chunkK2QPSQEVcjs = require('./chunk-K2QPSQEV.cjs');
52
52
 
53
53
 
54
54
 
@@ -60,7 +60,7 @@ var _chunkKOFCBB3Ncjs = require('./chunk-KOFCBB3N.cjs');
60
60
 
61
61
 
62
62
 
63
- var _chunkQWVR2HNTcjs = require('./chunk-QWVR2HNT.cjs');
63
+ var _chunkLXJMGLKWcjs = require('./chunk-LXJMGLKW.cjs');
64
64
 
65
65
 
66
66
 
@@ -71,10 +71,12 @@ var _chunkQWVR2HNTcjs = require('./chunk-QWVR2HNT.cjs');
71
71
 
72
72
 
73
73
 
74
- var _chunkX7VHW2TDcjs = require('./chunk-X7VHW2TD.cjs');
75
74
 
76
75
 
77
- var _chunkHHPGUJ75cjs = require('./chunk-HHPGUJ75.cjs');
76
+ var _chunkH3K33HBAcjs = require('./chunk-H3K33HBA.cjs');
77
+
78
+
79
+ var _chunk2BCIIKRGcjs = require('./chunk-2BCIIKRG.cjs');
78
80
 
79
81
 
80
82
 
@@ -210,7 +212,7 @@ ${reason.name}: ${reason.message}`;
210
212
  if (restartTimes.length > MAX_RESTARTS) {
211
213
  try {
212
214
  $asai.$log("NO_RESTART", "Process crashed too frequently, gracefully shutdown and wait for daemon restart.");
213
- void Promise.resolve().then(() => _interopRequireWildcard(require("./intervention-hooks-LE6X4C6N.cjs"))).then(
215
+ void Promise.resolve().then(() => _interopRequireWildcard(require("./intervention-hooks-KF3SNB5Q.cjs"))).then(
214
216
  ({ logProcessGuardEvent }) => logProcessGuardEvent($asai, {
215
217
  action: "crash_loop_shutdown",
216
218
  detail: `${restartTimes.length} crashes in ${RESTART_WINDOW}ms window`,
@@ -252,7 +254,7 @@ ${reason.name}: ${reason.message}`;
252
254
  }
253
255
  _chunkSMVZ3ZDJcjs.__name.call(void 0, initProcess, "initProcess");
254
256
  function gracefulShutdown($asai) {
255
- void Promise.resolve().then(() => _interopRequireWildcard(require("./intervention-hooks-LE6X4C6N.cjs"))).then(
257
+ void Promise.resolve().then(() => _interopRequireWildcard(require("./intervention-hooks-KF3SNB5Q.cjs"))).then(
256
258
  ({ logProcessGuardEvent }) => logProcessGuardEvent($asai, {
257
259
  action: "graceful_shutdown",
258
260
  detail: "SIGTERM/SIGINT or crash guard triggered",
@@ -377,7 +379,7 @@ var LogBuffer = class _LogBuffer {
377
379
  await _promises2.default.appendFile(this.filePath, logContent, "utf8");
378
380
  const src = this.filePath.includes("/client/") || this.filePath.includes("\\client\\") ? "client" : "server";
379
381
  const kind = logContent.includes("[SEC-AUDIT]") ? "sec" : src;
380
- void _chunkVLMM735Qcjs.mirrorWebLog.call(void 0, this.$asai, {
382
+ void _chunkTKJAHTPOcjs.mirrorWebLog.call(void 0, this.$asai, {
381
383
  source: kind === "sec" ? "sec" : src,
382
384
  rawLine: logContent
383
385
  }).catch(() => void 0);
@@ -395,7 +397,7 @@ var LogBuffer = class _LogBuffer {
395
397
  }
396
398
  };
397
399
  function saveLog($asai, src, logstr) {
398
- return new Promise((resolve7, reject) => {
400
+ return new Promise((resolve6, reject) => {
399
401
  try {
400
402
  const bufferKey = `${$asai.id || "default"}_${src}`;
401
403
  let logBuffer = logBuffers.get(bufferKey);
@@ -404,7 +406,7 @@ function saveLog($asai, src, logstr) {
404
406
  logBuffers.set(bufferKey, logBuffer);
405
407
  }
406
408
  logBuffer.add(logstr);
407
- resolve7();
409
+ resolve6();
408
410
  } catch (err) {
409
411
  console.error(err);
410
412
  reject(err);
@@ -423,10 +425,10 @@ async function ensureW3CHeader($asai, filePath, dateCur) {
423
425
  }
424
426
  } catch (e9) {
425
427
  }
426
- const header = _chunkW7DVKGX5cjs.formatW3CHeader.call(void 0, {
427
- software: _optionalChain([$asai, 'access', _28 => _28.hostconfig, 'access', _29 => _29.website, 'optionalAccess', _30 => _30.title]) || "AsaiHost",
428
+ const header = _chunkOCEBEEP5cjs.formatW3CHeader.call(void 0, {
429
+ software: _optionalChain([$asai, 'access', _28 => _28.hostconfig, 'access', _29 => _29.website, 'optionalAccess', _30 => _30.title]) || "AsaiHostNodejs",
428
430
  version: _optionalChain([$asai, 'access', _31 => _31.hostconfig, 'access', _32 => _32.website, 'optionalAccess', _33 => _33.ver]) || "1.0.0.0",
429
- fields: [..._chunkW7DVKGX5cjs.W3C_SERVER_FIELDS],
431
+ fields: [..._chunkOCEBEEP5cjs.W3C_SERVER_FIELDS],
430
432
  date: dateCur
431
433
  });
432
434
  await _promises2.default.appendFile(filePath, header, "utf8");
@@ -477,8 +479,8 @@ async function appendAccessLog($asai, clfLine, w3cLine) {
477
479
  await _promises2.default.appendFile(clfPath, clfLine, "utf8");
478
480
  await ensureW3CAccessHeader($asai, w3cPath, dateCur);
479
481
  await _promises2.default.appendFile(w3cPath, w3cLine, "utf8");
480
- const clfParsed = _chunkW7DVKGX5cjs.parseCLF.call(void 0, clfLine);
481
- void _chunkVLMM735Qcjs.mirrorAccessLog.call(void 0, $asai, {
482
+ const clfParsed = _chunkOCEBEEP5cjs.parseCLF.call(void 0, clfLine);
483
+ void _chunkTKJAHTPOcjs.mirrorAccessLog.call(void 0, $asai, {
482
484
  format: "clf",
483
485
  rawLine: clfLine,
484
486
  host: _optionalChain([clfParsed, 'optionalAccess', _42 => _42.host]),
@@ -486,7 +488,7 @@ async function appendAccessLog($asai, clfLine, w3cLine) {
486
488
  url: _optionalChain([clfParsed, 'optionalAccess', _44 => _44.url]),
487
489
  status: _optionalChain([clfParsed, 'optionalAccess', _45 => _45.status])
488
490
  }).catch(() => void 0);
489
- void _chunkVLMM735Qcjs.mirrorAccessLog.call(void 0, $asai, {
491
+ void _chunkTKJAHTPOcjs.mirrorAccessLog.call(void 0, $asai, {
490
492
  format: "w3c",
491
493
  rawLine: w3cLine
492
494
  }).catch(() => void 0);
@@ -506,10 +508,10 @@ async function ensureW3CAccessHeader($asai, filePath, dateCur) {
506
508
  }
507
509
  } catch (e10) {
508
510
  }
509
- const header = _chunkW7DVKGX5cjs.formatW3CHeader.call(void 0, {
510
- software: _optionalChain([$asai, 'access', _46 => _46.hostconfig, 'access', _47 => _47.website, 'optionalAccess', _48 => _48.title]) || "AsaiHost",
511
+ const header = _chunkOCEBEEP5cjs.formatW3CHeader.call(void 0, {
512
+ software: _optionalChain([$asai, 'access', _46 => _46.hostconfig, 'access', _47 => _47.website, 'optionalAccess', _48 => _48.title]) || "AsaiHostNodejs",
511
513
  version: _optionalChain([$asai, 'access', _49 => _49.hostconfig, 'access', _50 => _50.website, 'optionalAccess', _51 => _51.ver]) || "1.0.0.0",
512
- fields: [..._chunkW7DVKGX5cjs.W3C_ACCESS_FIELDS],
514
+ fields: [..._chunkOCEBEEP5cjs.W3C_ACCESS_FIELDS],
513
515
  date: dateCur
514
516
  });
515
517
  await _promises2.default.appendFile(filePath, header, "utf8");
@@ -548,7 +550,7 @@ function initLog($asai) {
548
550
  _chunkSMVZ3ZDJcjs.__name.call(void 0, shouldSample, "shouldSample");
549
551
  function enqueueServerLog(logType, method, url, message, dateCur) {
550
552
  const filePath = `${$asai.hostconfig.logger.path.server}log-${_chunkO6LVLSNBcjs.getNowTime.call(void 0, 2, dateCur)}.txt`;
551
- const logstr = _chunkW7DVKGX5cjs.formatW3CServerRecord.call(void 0, {
553
+ const logstr = _chunkOCEBEEP5cjs.formatW3CServerRecord.call(void 0, {
552
554
  date: dateCur,
553
555
  logType,
554
556
  method,
@@ -576,7 +578,7 @@ function initLog($asai) {
576
578
  if (argType === 1) {
577
579
  if (_optionalChain([$asai, 'access', _59 => _59.hostconfig, 'access', _60 => _60.logger, 'optionalAccess', _61 => _61.path, 'optionalAccess', _62 => _62.client])) {
578
580
  const logMsg = args.slice(1).map(formatArg).join("\n");
579
- const logstr = _chunkW7DVKGX5cjs.formatW3CServerRecord.call(void 0, {
581
+ const logstr = _chunkOCEBEEP5cjs.formatW3CServerRecord.call(void 0, {
580
582
  date: dateCur,
581
583
  logType: "CLIENT",
582
584
  message: logMsg
@@ -810,8 +812,8 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, checkNtpOffset, "checkNtpOffset");
810
812
 
811
813
  // src/infra/config-integrity.ts
812
814
  var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
813
- var _fs = require('fs'); var fs3 = _interopRequireWildcard(_fs); var fs6 = _interopRequireWildcard(_fs); var fs4 = _interopRequireWildcard(_fs); var fs5 = _interopRequireWildcard(_fs); var fs8 = _interopRequireWildcard(_fs); var fs10 = _interopRequireWildcard(_fs); var fs11 = _interopRequireWildcard(_fs); var fs12 = _interopRequireWildcard(_fs);
814
- var _path = require('path'); var nodePath2 = _interopRequireWildcard(_path); var path2 = _interopRequireWildcard(_path); var nodePath = _interopRequireWildcard(_path); var nodePath3 = _interopRequireWildcard(_path); var nodePath4 = _interopRequireWildcard(_path); var path5 = _interopRequireWildcard(_path); var path6 = _interopRequireWildcard(_path); var path7 = _interopRequireWildcard(_path);
815
+ var _fs = require('fs'); var fs3 = _interopRequireWildcard(_fs); var fs6 = _interopRequireWildcard(_fs); var fs4 = _interopRequireWildcard(_fs); var fs5 = _interopRequireWildcard(_fs); var fs8 = _interopRequireWildcard(_fs); var fs10 = _interopRequireWildcard(_fs); var fs11 = _interopRequireWildcard(_fs);
816
+ var _path = require('path'); var nodePath2 = _interopRequireWildcard(_path); var path2 = _interopRequireWildcard(_path); var nodePath = _interopRequireWildcard(_path); var nodePath3 = _interopRequireWildcard(_path); var nodePath4 = _interopRequireWildcard(_path); var path5 = _interopRequireWildcard(_path); var path6 = _interopRequireWildcard(_path);
815
817
  function computeConfigHash(configPath) {
816
818
  try {
817
819
  const raw = fs3.default.readFileSync(configPath);
@@ -843,7 +845,7 @@ function verifyConfigManifest(serverRoot) {
843
845
  _chunkSMVZ3ZDJcjs.__name.call(void 0, verifyConfigManifest, "verifyConfigManifest");
844
846
 
845
847
  // src/core/init.ts
846
- function initAsaiHost($asai, _opt) {
848
+ function initAsaiHostNodejs($asai, _opt) {
847
849
  if (!_optionalChain([$asai, 'access', _93 => _93.hostconfig, 'optionalAccess', _94 => _94.ip])) {
848
850
  $asai.hostconfig.ip = getIp();
849
851
  }
@@ -865,12 +867,12 @@ function initAsaiHost($asai, _opt) {
865
867
  resAES
866
868
  };
867
869
  }
868
- if (_chunkQWVR2HNTcjs.isDevDefaultPassword.call(void 0, _optionalChain([$asai, 'access', _102 => _102.hostconfig, 'optionalAccess', _103 => _103.password]) || "")) {
870
+ if (_chunkLXJMGLKWcjs.isDevDefaultPassword.call(void 0, _optionalChain([$asai, 'access', _102 => _102.hostconfig, 'optionalAccess', _103 => _103.password]) || "")) {
869
871
  logSecurityEvent($asai, {
870
872
  type: "CONFIG_WARN",
871
873
  detail: "Using dev-only password; set ASAI_HOST_PASSWORD for production (IEC 62443-4-2 CR 1.7)"
872
874
  });
873
- void Promise.resolve().then(() => _interopRequireWildcard(require("./intervention-hooks-LE6X4C6N.cjs"))).then(
875
+ void Promise.resolve().then(() => _interopRequireWildcard(require("./intervention-hooks-KF3SNB5Q.cjs"))).then(
874
876
  ({ logSecurityConfigIntervention: logSecurityConfigIntervention2 }) => logSecurityConfigIntervention2($asai, {
875
877
  section: "password",
876
878
  detail: "dev-default-password detected at startup"
@@ -890,13 +892,13 @@ function initAsaiHost($asai, _opt) {
890
892
  if (!ntp.ok) logSecurityEvent($asai, { type: "CONFIG_WARN", detail: `NTP: ${ntp.detail}` });
891
893
  });
892
894
  }
893
- _chunkSMVZ3ZDJcjs.__name.call(void 0, initAsaiHost, "initAsaiHost");
895
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, initAsaiHostNodejs, "initAsaiHostNodejs");
894
896
  function scheduleLogComplianceCheck($asai) {
895
897
  const hours = Number(_optionalChain([$asai, 'optionalAccess', _104 => _104.hostconfig, 'optionalAccess', _105 => _105.logger, 'optionalAccess', _106 => _106.complianceIntervalHours])) || 6;
896
898
  if (hours <= 0) return;
897
899
  const ms = hours * 3600 * 1e3;
898
900
  setInterval(() => {
899
- void Promise.resolve().then(() => _interopRequireWildcard(require("./LogStore-M2AUBNGO.cjs"))).then(
901
+ void Promise.resolve().then(() => _interopRequireWildcard(require("./LogStore-7MTUQA4G.cjs"))).then(
900
902
  ({ getComplianceReport: getComplianceReport2 }) => getComplianceReport2($asai, "prod")
901
903
  ).catch(() => void 0);
902
904
  }, ms);
@@ -947,16 +949,61 @@ function getWsUserinfo(req, $asai) {
947
949
  }
948
950
  }
949
951
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getWsUserinfo, "getWsUserinfo");
952
+ function listOnlineWsUsers($asai, hostdir) {
953
+ const users = [];
954
+ const map = $asai.connectionsws || {};
955
+ const dirs = hostdir ? [hostdir] : Object.keys(map);
956
+ for (const dir of dirs) {
957
+ for (const [us, ws2] of Object.entries(map[dir] || {})) {
958
+ if (!us || us === "asai") continue;
959
+ if (isWsStillActive(ws2)) {
960
+ users.push(us);
961
+ } else if (_optionalChain([map, 'access', _111 => _111[dir], 'optionalAccess', _112 => _112[us]]) === ws2) {
962
+ delete map[dir][us];
963
+ }
964
+ }
965
+ }
966
+ return [...new Set(users)];
967
+ }
968
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, listOnlineWsUsers, "listOnlineWsUsers");
950
969
  function isUserOnlineOnWs($asai, us, hostdir) {
951
970
  if (!us || us === "asai") return false;
952
971
  const map = $asai.connectionsws || {};
953
972
  const dirs = hostdir ? [hostdir] : Object.keys(map);
954
973
  for (const dir of dirs) {
955
- if (_optionalChain([map, 'access', _111 => _111[dir], 'optionalAccess', _112 => _112[us]])) return true;
974
+ const ws2 = _optionalChain([map, 'access', _113 => _113[dir], 'optionalAccess', _114 => _114[us]]);
975
+ if (!ws2) continue;
976
+ if (isWsStillActive(ws2)) return true;
977
+ if (_optionalChain([map, 'access', _115 => _115[dir], 'optionalAccess', _116 => _116[us]]) === ws2) delete map[dir][us];
956
978
  }
957
979
  return false;
958
980
  }
959
981
  _chunkSMVZ3ZDJcjs.__name.call(void 0, isUserOnlineOnWs, "isUserOnlineOnWs");
982
+ function kickUserWs($asai, us, hostdir) {
983
+ if (!us || us === "asai") return;
984
+ const map = $asai.connectionsws || {};
985
+ const dirs = hostdir ? [hostdir] : Object.keys(map);
986
+ for (const dir of dirs) {
987
+ const ws2 = _optionalChain([map, 'access', _117 => _117[dir], 'optionalAccess', _118 => _118[us]]);
988
+ if (!ws2) continue;
989
+ try {
990
+ ws2.close();
991
+ } catch (e17) {
992
+ }
993
+ if (_optionalChain([map, 'access', _119 => _119[dir], 'optionalAccess', _120 => _120[us]]) === ws2) delete map[dir][us];
994
+ }
995
+ }
996
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, kickUserWs, "kickUserWs");
997
+ async function removeSessionOnWsClose($asai, us, token) {
998
+ try {
999
+ const store = _chunkLXJMGLKWcjs.createUserStore.call(void 0, $asai);
1000
+ const sessions = await store.getSessions();
1001
+ const match = sessions.find((s) => s.us === us && s.pub === token);
1002
+ if (match) await store.removeSession(match.id);
1003
+ } catch (e18) {
1004
+ }
1005
+ }
1006
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, removeSessionOnWsClose, "removeSessionOnWsClose");
960
1007
  function isWsStillActive(ws2) {
961
1008
  if (!ws2) return false;
962
1009
  const state = ws2.readyState;
@@ -969,13 +1016,13 @@ function rejectIncomingWs(ws2, db) {
969
1016
  ws2.send(payload, () => {
970
1017
  try {
971
1018
  ws2.close();
972
- } catch (e17) {
1019
+ } catch (e19) {
973
1020
  }
974
1021
  });
975
- } catch (e18) {
1022
+ } catch (e20) {
976
1023
  try {
977
1024
  ws2.close();
978
- } catch (e19) {
1025
+ } catch (e21) {
979
1026
  }
980
1027
  }
981
1028
  }
@@ -986,9 +1033,9 @@ function isOkWs($asai, hostdir, ws2, _req, hostcfg) {
986
1033
  ws2.close();
987
1034
  return false;
988
1035
  }
989
- if (us !== "asai" && _optionalChain([$asai, 'access', _113 => _113.connectionsws, 'access', _114 => _114[hostdir], 'optionalAccess', _115 => _115[us]])) {
1036
+ if (us !== "asai" && _optionalChain([$asai, 'access', _121 => _121.connectionsws, 'access', _122 => _122[hostdir], 'optionalAccess', _123 => _123[us]])) {
990
1037
  const existingWs = $asai.connectionsws[hostdir][us];
991
- if (_optionalChain([existingWs, 'optionalAccess', _116 => _116.Userinfo, 'optionalAccess', _117 => _117[2]]) === tk) {
1038
+ if (_optionalChain([existingWs, 'optionalAccess', _124 => _124.Userinfo, 'optionalAccess', _125 => _125[2]]) === tk) {
992
1039
  if (isWsStillActive(existingWs)) {
993
1040
  rejectIncomingWs(ws2, {
994
1041
  lang: "pageworking",
@@ -999,7 +1046,7 @@ function isOkWs($asai, hostdir, ws2, _req, hostcfg) {
999
1046
  }
1000
1047
  try {
1001
1048
  existingWs.close();
1002
- } catch (e20) {
1049
+ } catch (e22) {
1003
1050
  }
1004
1051
  delete $asai.connectionsws[hostdir][us];
1005
1052
  return true;
@@ -1014,7 +1061,7 @@ function isOkWs($asai, hostdir, ws2, _req, hostcfg) {
1014
1061
  if (us !== "asai") {
1015
1062
  const connections = $asai.connectionsws[hostdir] || {};
1016
1063
  const sameTkWs = Object.values(connections).find(
1017
- (item) => _optionalChain([item, 'access', _118 => _118.Userinfo, 'optionalAccess', _119 => _119[2]]) === tk && _optionalChain([item, 'access', _120 => _120.Userinfo, 'optionalAccess', _121 => _121[0]]) !== us
1064
+ (item) => _optionalChain([item, 'access', _126 => _126.Userinfo, 'optionalAccess', _127 => _127[2]]) === tk && _optionalChain([item, 'access', _128 => _128.Userinfo, 'optionalAccess', _129 => _129[0]]) !== us
1018
1065
  );
1019
1066
  const maxOnline = hostcfg.maxonline || 100;
1020
1067
  if (sameTkWs) {
@@ -1039,21 +1086,26 @@ function isOkWs($asai, hostdir, ws2, _req, hostcfg) {
1039
1086
  _chunkSMVZ3ZDJcjs.__name.call(void 0, isOkWs, "isOkWs");
1040
1087
  function loginWs($asai, hostdir, ws2, req, hostcfg, wsWorkHandler, logWsMessage) {
1041
1088
  const [us] = ws2.Userinfo || [];
1042
- if (hostcfg.ckws && us) {
1043
- if (!ws2.tasksws) ws2.tasksws = {};
1089
+ if (!$asai.connectionsws[hostdir]) {
1090
+ $asai.connectionsws[hostdir] = {};
1091
+ }
1092
+ if (us && us !== "asai") {
1093
+ if (hostcfg.ckws && !ws2.tasksws) ws2.tasksws = {};
1044
1094
  $asai.connectionsws[hostdir][us] = ws2;
1045
1095
  }
1046
1096
  ws2.on("message", (msg) => {
1047
1097
  if (logWsMessage) $asai.$log("WS", "message", msg.toString());
1048
- _optionalChain([wsWorkHandler, 'optionalCall', _122 => _122(msg, ws2, hostdir, req)]);
1098
+ _optionalChain([wsWorkHandler, 'optionalCall', _130 => _130(msg, ws2, hostdir, req)]);
1049
1099
  });
1050
1100
  ws2.on("close", () => {
1051
- if (hostcfg.ckws) {
1052
- if (ws2.tasksws) {
1053
- Object.values(ws2.tasksws).forEach((el) => el && clearInterval(el));
1054
- ws2.tasksws = void 0;
1055
- }
1056
- if (us && _optionalChain([$asai, 'access', _123 => _123.connectionsws, 'access', _124 => _124[hostdir], 'optionalAccess', _125 => _125[us]]) === ws2) delete $asai.connectionsws[hostdir][us];
1101
+ const token = _optionalChain([ws2, 'access', _131 => _131.Userinfo, 'optionalAccess', _132 => _132[2]]);
1102
+ if (hostcfg.ckws && ws2.tasksws) {
1103
+ Object.values(ws2.tasksws).forEach((el) => el && clearInterval(el));
1104
+ ws2.tasksws = void 0;
1105
+ }
1106
+ if (us && _optionalChain([$asai, 'access', _133 => _133.connectionsws, 'access', _134 => _134[hostdir], 'optionalAccess', _135 => _135[us]]) === ws2) delete $asai.connectionsws[hostdir][us];
1107
+ if (us && token && !isUserOnlineOnWs($asai, us, hostdir)) {
1108
+ void removeSessionOnWsClose($asai, us, String(token));
1057
1109
  }
1058
1110
  if (ws2.readyState !== _ws.WebSocket.CLOSED && ws2.readyState !== _ws.WebSocket.CLOSING) ws2.close();
1059
1111
  });
@@ -1075,7 +1127,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, clearWsServerTasks, "clearWsServerTasks");
1075
1127
  function resWsMsg(msg, $asai) {
1076
1128
  if (msg === "ping" || msg === "pong") return msg;
1077
1129
  if (typeof msg !== "object" || msg === null) return msg;
1078
- if ((_optionalChain([msg, 'optionalAccess', _126 => _126.aes]) || _optionalChain([$asai, 'access', _127 => _127.$lib, 'access', _128 => _128.aesfns, 'optionalAccess', _129 => _129.allaes])) && _optionalChain([msg, 'optionalAccess', _130 => _130.db]) && _optionalChain([$asai, 'access', _131 => _131.$lib, 'optionalAccess', _132 => _132.aesfns, 'optionalAccess', _133 => _133.resAES])) {
1130
+ if ((_optionalChain([msg, 'optionalAccess', _136 => _136.aes]) || _optionalChain([$asai, 'access', _137 => _137.$lib, 'access', _138 => _138.aesfns, 'optionalAccess', _139 => _139.allaes])) && _optionalChain([msg, 'optionalAccess', _140 => _140.db]) && _optionalChain([$asai, 'access', _141 => _141.$lib, 'optionalAccess', _142 => _142.aesfns, 'optionalAccess', _143 => _143.resAES])) {
1079
1131
  msg.db = $asai.$lib.aesfns.resAES(msg.db);
1080
1132
  }
1081
1133
  return JSON.stringify(msg);
@@ -1097,7 +1149,7 @@ function attachWssHelpers(wss, $asai) {
1097
1149
  wss.broadws = (msg) => {
1098
1150
  const data = resWsMsg(msg, $asai);
1099
1151
  wss.clients.forEach((client) => {
1100
- if (_optionalChain([client, 'optionalAccess', _134 => _134.readyState]) === _ws.WebSocket.OPEN) client.send(data);
1152
+ if (_optionalChain([client, 'optionalAccess', _144 => _144.readyState]) === _ws.WebSocket.OPEN) client.send(data);
1101
1153
  });
1102
1154
  };
1103
1155
  }
@@ -1110,7 +1162,7 @@ var apiPerIp = /* @__PURE__ */ new Map();
1110
1162
  var apiRatePerIp = /* @__PURE__ */ new Map();
1111
1163
  var wsPerIp = /* @__PURE__ */ new Map();
1112
1164
  function getQuota($asai) {
1113
- return _optionalChain([$asai, 'optionalAccess', _135 => _135.hostconfig, 'optionalAccess', _136 => _136.security, 'optionalAccess', _137 => _137.quota]) || {};
1165
+ return _optionalChain([$asai, 'optionalAccess', _145 => _145.hostconfig, 'optionalAccess', _146 => _146.security, 'optionalAccess', _147 => _147.quota]) || {};
1114
1166
  }
1115
1167
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getQuota, "getQuota");
1116
1168
  function isEnabled($asai) {
@@ -1200,7 +1252,7 @@ function getMaxWebConnections($asai, hostcfg) {
1200
1252
  const q = getQuota($asai);
1201
1253
  const fromQuota = Number(q.maxWebConnections);
1202
1254
  if (fromQuota > 0) return fromQuota;
1203
- return Number(_optionalChain([hostcfg, 'optionalAccess', _138 => _138.maxws])) > 0 ? Number(hostcfg.maxws) : 100;
1255
+ return Number(_optionalChain([hostcfg, 'optionalAccess', _148 => _148.maxws])) > 0 ? Number(hostcfg.maxws) : 100;
1204
1256
  }
1205
1257
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getMaxWebConnections, "getMaxWebConnections");
1206
1258
  function countActiveWsConnections(wss, incoming, $asai, hostdir, hostcfg, userinfo) {
@@ -1210,12 +1262,12 @@ function countActiveWsConnections(wss, incoming, $asai, hostdir, hostcfg, userin
1210
1262
  if (client === incoming) continue;
1211
1263
  if (client.readyState === _ws.WebSocket.CLOSED || client.readyState === _ws.WebSocket.CLOSING) continue;
1212
1264
  const cInfo = client.Userinfo;
1213
- const cUs = _optionalChain([cInfo, 'optionalAccess', _139 => _139[0]]);
1214
- const cTk = _optionalChain([cInfo, 'optionalAccess', _140 => _140[2]]);
1265
+ const cUs = _optionalChain([cInfo, 'optionalAccess', _149 => _149[0]]);
1266
+ const cTk = _optionalChain([cInfo, 'optionalAccess', _150 => _150[2]]);
1215
1267
  if (us && tk && cUs === us && cTk === tk) continue;
1216
- if (_optionalChain([hostcfg, 'optionalAccess', _141 => _141.ckws]) && us && tk) {
1217
- const existing = _optionalChain([$asai, 'optionalAccess', _142 => _142.connectionsws, 'optionalAccess', _143 => _143[hostdir], 'optionalAccess', _144 => _144[us]]);
1218
- if (existing === client && _optionalChain([existing, 'optionalAccess', _145 => _145.Userinfo, 'optionalAccess', _146 => _146[2]]) === tk) continue;
1268
+ if (_optionalChain([hostcfg, 'optionalAccess', _151 => _151.ckws]) && us && tk) {
1269
+ const existing = _optionalChain([$asai, 'optionalAccess', _152 => _152.connectionsws, 'optionalAccess', _153 => _153[hostdir], 'optionalAccess', _154 => _154[us]]);
1270
+ if (existing === client && _optionalChain([existing, 'optionalAccess', _155 => _155.Userinfo, 'optionalAccess', _156 => _156[2]]) === tk) continue;
1219
1271
  }
1220
1272
  count += 1;
1221
1273
  }
@@ -1227,7 +1279,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, countActiveWsConnections, "countActiveWsCo
1227
1279
  function createWSHost($asai, hostdir) {
1228
1280
  const hostcfg = getHostCFG(hostdir, $asai);
1229
1281
  const wsWorkHandler = getWorkHandler("wsWork");
1230
- const logWsMessage = !!_optionalChain([$asai, 'access', _147 => _147.hostconfig, 'access', _148 => _148.logger, 'optionalAccess', _149 => _149.lv, 'optionalAccess', _150 => _150.view]);
1282
+ const logWsMessage = !!_optionalChain([$asai, 'access', _157 => _157.hostconfig, 'access', _158 => _158.logger, 'optionalAccess', _159 => _159.lv, 'optionalAccess', _160 => _160.view]);
1231
1283
  try {
1232
1284
  if ($asai.serversws[hostdir]) return;
1233
1285
  if (hostcfg.ckws && !$asai.connectionsws[hostdir]) {
@@ -1239,14 +1291,14 @@ function createWSHost($asai, hostdir) {
1239
1291
  wss.on("error", (err) => {
1240
1292
  clearWsServerTasks($asai, hostdir);
1241
1293
  $asai.$log("WS", "WS Server error!", err);
1242
- _optionalChain([wss, 'access', _151 => _151.close, 'optionalCall', _152 => _152(() => {
1294
+ _optionalChain([wss, 'access', _161 => _161.close, 'optionalCall', _162 => _162(() => {
1243
1295
  $asai.$log("WS", "WS Server closed");
1244
1296
  delete $asai.serversws[hostdir];
1245
1297
  })]);
1246
1298
  });
1247
1299
  wss.on("close", (code, reason) => {
1248
1300
  try {
1249
- $asai.$log("WS", `WebSocket closed, server ${hostdir}, code: ${code}, reason: ${_optionalChain([reason, 'optionalAccess', _153 => _153.toString, 'call', _154 => _154()])}`);
1301
+ $asai.$log("WS", `WebSocket closed, server ${hostdir}, code: ${code}, reason: ${_optionalChain([reason, 'optionalAccess', _163 => _163.toString, 'call', _164 => _164()])}`);
1250
1302
  clearWsServerTasks($asai, hostdir);
1251
1303
  } catch (err) {
1252
1304
  $asai.$log("WS", "WS close handler error:", err);
@@ -1334,7 +1386,7 @@ var StaticPathCache = class {
1334
1386
  const stat = fs3.statSync(entry.filePath);
1335
1387
  if (!stat.isFile() || stat.mtimeMs !== entry.mtimeMs) return null;
1336
1388
  return stat;
1337
- } catch (e21) {
1389
+ } catch (e23) {
1338
1390
  return null;
1339
1391
  }
1340
1392
  }
@@ -1353,8 +1405,8 @@ function applySecurityHeaders(res, isHttps = false, hostconfig) {
1353
1405
  if (isHttps) {
1354
1406
  res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
1355
1407
  }
1356
- const sec = _optionalChain([hostconfig, 'optionalAccess', _155 => _155.security]);
1357
- if (_optionalChain([sec, 'optionalAccess', _156 => _156.csp])) {
1408
+ const sec = _optionalChain([hostconfig, 'optionalAccess', _165 => _165.security]);
1409
+ if (_optionalChain([sec, 'optionalAccess', _166 => _166.csp])) {
1358
1410
  const csp = typeof sec.cspPolicy === "string" && sec.cspPolicy.length > 0 ? sec.cspPolicy : DEFAULT_CSP;
1359
1411
  res.setHeader("Content-Security-Policy", csp);
1360
1412
  }
@@ -1362,9 +1414,9 @@ function applySecurityHeaders(res, isHttps = false, hostconfig) {
1362
1414
  _chunkSMVZ3ZDJcjs.__name.call(void 0, applySecurityHeaders, "applySecurityHeaders");
1363
1415
  function getHttpUserinfo(req, $asai) {
1364
1416
  try {
1365
- const userinfo = _optionalChain([req, 'access', _157 => _157.headers, 'optionalAccess', _158 => _158["userinfo"], 'optionalAccess', _159 => _159.split, 'call', _160 => _160("##")]);
1417
+ const userinfo = _optionalChain([req, 'access', _167 => _167.headers, 'optionalAccess', _168 => _168["userinfo"], 'optionalAccess', _169 => _169.split, 'call', _170 => _170("##")]);
1366
1418
  return deUserInfoWithAsai(userinfo, $asai);
1367
- } catch (e22) {
1419
+ } catch (e24) {
1368
1420
  return "";
1369
1421
  }
1370
1422
  }
@@ -1395,7 +1447,7 @@ function normalizeRequestPath(url) {
1395
1447
  }
1396
1448
  _chunkSMVZ3ZDJcjs.__name.call(void 0, normalizeRequestPath, "normalizeRequestPath");
1397
1449
  function createSkipChecker($asai) {
1398
- const skip = _optionalChain([$asai, 'access', _161 => _161.hostconfig, 'optionalAccess', _162 => _162.logger, 'optionalAccess', _163 => _163.skip]);
1450
+ const skip = _optionalChain([$asai, 'access', _171 => _171.hostconfig, 'optionalAccess', _172 => _172.logger, 'optionalAccess', _173 => _173.skip]);
1399
1451
  if (!Array.isArray(skip) || skip.length === 0) return () => false;
1400
1452
  const exact = /* @__PURE__ */ new Set();
1401
1453
  const prefixes = [];
@@ -1406,11 +1458,11 @@ function createSkipChecker($asai) {
1406
1458
  }
1407
1459
  if (exact.size === 0 && prefixes.length === 0) return () => false;
1408
1460
  return (url) => {
1409
- const path8 = normalizeRequestPath(url);
1410
- if (!path8) return false;
1411
- if (exact.has(path8)) return true;
1461
+ const path7 = normalizeRequestPath(url);
1462
+ if (!path7) return false;
1463
+ if (exact.has(path7)) return true;
1412
1464
  for (let i = 0; i < prefixes.length; i++) {
1413
- if (path8.startsWith(prefixes[i])) return true;
1465
+ if (path7.startsWith(prefixes[i])) return true;
1414
1466
  }
1415
1467
  return false;
1416
1468
  };
@@ -1429,9 +1481,9 @@ function attachAccessLog($asai, req, res, logType) {
1429
1481
  res.__asaiAccessLogged = true;
1430
1482
  const onFinish = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, () => {
1431
1483
  try {
1432
- const entry = _chunkW7DVKGX5cjs.buildAccessEntry.call(void 0, req, res, logType);
1433
- void $asai.appendAccessLog(_chunkW7DVKGX5cjs.formatCLF.call(void 0, entry), _chunkW7DVKGX5cjs.formatW3CAccessRecord.call(void 0, entry));
1434
- } catch (e23) {
1484
+ const entry = _chunkOCEBEEP5cjs.buildAccessEntry.call(void 0, req, res, logType);
1485
+ void $asai.appendAccessLog(_chunkOCEBEEP5cjs.formatCLF.call(void 0, entry), _chunkOCEBEEP5cjs.formatW3CAccessRecord.call(void 0, entry));
1486
+ } catch (e25) {
1435
1487
  }
1436
1488
  }, "onFinish");
1437
1489
  if (res.writableEnded || res.finished) onFinish();
@@ -1490,7 +1542,7 @@ function findExistingFileUnderRoots(requestedPath, allowedRoots) {
1490
1542
  if (stat.isFile()) {
1491
1543
  return { filePath: absTarget, stat };
1492
1544
  }
1493
- } catch (e24) {
1545
+ } catch (e26) {
1494
1546
  }
1495
1547
  }
1496
1548
  return null;
@@ -1503,13 +1555,13 @@ function getHostAllowedRoots(hostconfig) {
1503
1555
  try {
1504
1556
  const abs = path2.resolve("./" + dir.replace(/\\/g, "/"));
1505
1557
  if (fs4.existsSync(abs)) roots.add(abs);
1506
- } catch (e25) {
1558
+ } catch (e27) {
1507
1559
  }
1508
1560
  }, "push");
1509
- for (const dir of _optionalChain([hostconfig, 'optionalAccess', _164 => _164.hostdirs]) || []) push(dir);
1561
+ for (const dir of _optionalChain([hostconfig, 'optionalAccess', _174 => _174.hostdirs]) || []) push(dir);
1510
1562
  push("webdata");
1511
1563
  push("websys");
1512
- if (_optionalChain([hostconfig, 'optionalAccess', _165 => _165.weburls, 'optionalAccess', _166 => _166.webdir])) push(hostconfig.weburls.webdir);
1564
+ if (_optionalChain([hostconfig, 'optionalAccess', _175 => _175.weburls, 'optionalAccess', _176 => _176.webdir])) push(hostconfig.weburls.webdir);
1513
1565
  const result = [];
1514
1566
  roots.forEach((r) => result.push(r));
1515
1567
  return result;
@@ -1540,7 +1592,7 @@ function getStaticBaseDirs($asai) {
1540
1592
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getStaticBaseDirs, "getStaticBaseDirs");
1541
1593
  function shouldForceHostdirs($asai) {
1542
1594
  if ($asai.pkgSnapshotDir) return true;
1543
- return _optionalChain([$asai, 'access', _167 => _167.hostconfig, 'optionalAccess', _168 => _168.pkg, 'optionalAccess', _169 => _169.type]) === 1;
1595
+ return _optionalChain([$asai, 'access', _177 => _177.hostconfig, 'optionalAccess', _178 => _178.pkg, 'optionalAccess', _179 => _179.type]) === 1;
1544
1596
  }
1545
1597
  _chunkSMVZ3ZDJcjs.__name.call(void 0, shouldForceHostdirs, "shouldForceHostdirs");
1546
1598
  function buildStaticSearchDirs(hostcfg, $asai) {
@@ -1561,12 +1613,12 @@ function buildStaticSearchDirs(hostcfg, $asai) {
1561
1613
  ordered.push(dir);
1562
1614
  return;
1563
1615
  }
1564
- } catch (e26) {
1616
+ } catch (e28) {
1565
1617
  }
1566
1618
  }
1567
1619
  }, "pushDir");
1568
1620
  for (const dir of hostcfg.hostdirs || []) pushDir(dir);
1569
- if (_optionalChain([hostcfg, 'access', _170 => _170.weburls, 'optionalAccess', _171 => _171.webdir])) pushDir(hostcfg.weburls.webdir);
1621
+ if (_optionalChain([hostcfg, 'access', _180 => _180.weburls, 'optionalAccess', _181 => _181.webdir])) pushDir(hostcfg.weburls.webdir);
1570
1622
  return ordered;
1571
1623
  }
1572
1624
  _chunkSMVZ3ZDJcjs.__name.call(void 0, buildStaticSearchDirs, "buildStaticSearchDirs");
@@ -1594,7 +1646,7 @@ function parseUrlPath(requrl) {
1594
1646
  if (!requrl) return "/";
1595
1647
  const safeUrl = requrl.startsWith("http") ? requrl : encodeURI(requrl);
1596
1648
  return new URL(safeUrl, "http://localhost").pathname;
1597
- } catch (e27) {
1649
+ } catch (e29) {
1598
1650
  return requrl;
1599
1651
  }
1600
1652
  }
@@ -1686,8 +1738,8 @@ function serveStaticFile(req, res, foundPath, mimeType, stat, $asai) {
1686
1738
  _chunkSMVZ3ZDJcjs.__name.call(void 0, serveStaticFile, "serveStaticFile");
1687
1739
  function createStaticHandler(ctx) {
1688
1740
  const { hostcfg, hostdir, indexFile, $asai, staticPathCache } = ctx;
1689
- const hasRewrite = !!(_optionalChain([hostcfg, 'access', _172 => _172.weburls, 'optionalAccess', _173 => _173.rewrite]) && _optionalChain([hostcfg, 'access', _174 => _174.weburls, 'optionalAccess', _175 => _175.webdir]) && _optionalChain([hostcfg, 'access', _176 => _176.weburls, 'optionalAccess', _177 => _177.keys, 'optionalAccess', _178 => _178.length]));
1690
- const rewriteKeys = hasRewrite ? _optionalChain([hostcfg, 'access', _179 => _179.weburls, 'optionalAccess', _180 => _180.keys]) || [] : [];
1741
+ const hasRewrite = !!(_optionalChain([hostcfg, 'access', _182 => _182.weburls, 'optionalAccess', _183 => _183.rewrite]) && _optionalChain([hostcfg, 'access', _184 => _184.weburls, 'optionalAccess', _185 => _185.webdir]) && _optionalChain([hostcfg, 'access', _186 => _186.weburls, 'optionalAccess', _187 => _187.keys, 'optionalAccess', _188 => _188.length]));
1742
+ const rewriteKeys = hasRewrite ? _optionalChain([hostcfg, 'access', _189 => _189.weburls, 'optionalAccess', _190 => _190.keys]) || [] : [];
1691
1743
  const checkWebUrls = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (rurl) => {
1692
1744
  if (!hasRewrite || !rurl) return false;
1693
1745
  for (let i = 0; i < rewriteKeys.length; i++) {
@@ -1702,7 +1754,7 @@ function createStaticHandler(ctx) {
1702
1754
  const roots = rhostdirs.join("|") === primaryDirs.join("|") ? buildStaticRoots(primaryDirs, $asai) : buildStaticRoots(rhostdirs, $asai);
1703
1755
  const findValidFile = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (urlPath) => {
1704
1756
  const hit = staticPathCache.get(cacheKey);
1705
- if (_optionalChain([hit, 'optionalAccess', _181 => _181.is404])) return null;
1757
+ if (_optionalChain([hit, 'optionalAccess', _191 => _191.is404])) return null;
1706
1758
  if (hit && !hit.is404) {
1707
1759
  const verified = staticPathCache.verify(hit);
1708
1760
  if (verified) return { filePath: hit.filePath, stat: verified };
@@ -1726,7 +1778,7 @@ function createStaticHandler(ctx) {
1726
1778
  showHostDirs(req, res, [hostcfg.weburls.webdir], "/" + indexFile, primaryDirs, rtm + 1);
1727
1779
  return;
1728
1780
  }
1729
- const mimeType = _optionalChain([hostcfg, 'access', _182 => _182.mimetypes, 'optionalAccess', _183 => _183[nodePath2.extname(found.filePath)]]) || "application/octet-stream";
1781
+ const mimeType = _optionalChain([hostcfg, 'access', _192 => _192.mimetypes, 'optionalAccess', _193 => _193[nodePath2.extname(found.filePath)]]) || "application/octet-stream";
1730
1782
  serveStaticFile(req, res, found.filePath, mimeType, found.stat, $asai);
1731
1783
  }, "showHostDirs");
1732
1784
  return (req, res, url) => {
@@ -1751,7 +1803,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, createStaticHandler, "createStaticHandler"
1751
1803
  function setupHttpConnectionMonitor($asai, hostdir, server, hostcfg) {
1752
1804
  const maxHttp = hostcfg.maxhttp || 100;
1753
1805
  const monitorInterval = setInterval(() => {
1754
- const connCount = _optionalChain([$asai, 'access', _184 => _184.connectionshttp, 'access', _185 => _185[hostdir], 'optionalAccess', _186 => _186.size]) || 0;
1806
+ const connCount = _optionalChain([$asai, 'access', _194 => _194.connectionshttp, 'access', _195 => _195[hostdir], 'optionalAccess', _196 => _196.size]) || 0;
1755
1807
  if (connCount > maxHttp * 0.8) {
1756
1808
  $asai.$log("HTTP", `HTTP Connection HIGH (${connCount}/${maxHttp})`);
1757
1809
  }
@@ -1828,10 +1880,10 @@ function findListeningPids(port) {
1828
1880
  stdio: ["pipe", "pipe", "ignore"]
1829
1881
  });
1830
1882
  return out.split(/\r?\n/).map((s) => parseInt(s.trim(), 10)).filter((n) => n > 0);
1831
- } catch (e28) {
1883
+ } catch (e30) {
1832
1884
  return [];
1833
1885
  }
1834
- } catch (e29) {
1886
+ } catch (e31) {
1835
1887
  return [];
1836
1888
  }
1837
1889
  }
@@ -1845,17 +1897,17 @@ function killPid(pid) {
1845
1897
  _child_process.execSync.call(void 0, `kill -9 ${pid}`, { stdio: "ignore" });
1846
1898
  }
1847
1899
  return true;
1848
- } catch (e30) {
1900
+ } catch (e32) {
1849
1901
  return false;
1850
1902
  }
1851
1903
  }
1852
1904
  _chunkSMVZ3ZDJcjs.__name.call(void 0, killPid, "killPid");
1853
1905
  function releasePort(port, opts) {
1854
- const exclude = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _187 => _187.excludePid]), () => ( OWN_PID));
1906
+ const exclude = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _197 => _197.excludePid]), () => ( OWN_PID));
1855
1907
  const occupants = findListeningPids(port).filter((p) => p !== exclude && p !== OWN_PID);
1856
1908
  if (!occupants.length) return true;
1857
- const label = _optionalChain([opts, 'optionalAccess', _188 => _188.label]) ? `[${opts.label}] ` : "";
1858
- console.warn(`[AsaiHost] ${label}\u7AEF\u53E3 ${port} \u88AB\u5360\u7528\uFF0C\u6B63\u5728\u7ED3\u675F\u8FDB\u7A0B: ${occupants.join(", ")}`);
1909
+ const label = _optionalChain([opts, 'optionalAccess', _198 => _198.label]) ? `[${opts.label}] ` : "";
1910
+ console.warn(`[AsaiHostNodejs] ${label}\u7AEF\u53E3 ${port} \u88AB\u5360\u7528\uFF0C\u6B63\u5728\u7ED3\u675F\u8FDB\u7A0B: ${occupants.join(", ")}`);
1859
1911
  for (const pid of occupants) {
1860
1912
  killPid(pid);
1861
1913
  }
@@ -1866,23 +1918,23 @@ function releasePort(port, opts) {
1866
1918
  _chunkSMVZ3ZDJcjs.__name.call(void 0, releasePort, "releasePort");
1867
1919
  function collectStartupPorts($asai) {
1868
1920
  const ports = /* @__PURE__ */ new Set();
1869
- const hosts = _optionalChain([$asai, 'access', _189 => _189.hostconfig, 'optionalAccess', _190 => _190.hosts]);
1921
+ const hosts = _optionalChain([$asai, 'access', _199 => _199.hostconfig, 'optionalAccess', _200 => _200.hosts]);
1870
1922
  if (hosts) {
1871
1923
  for (const el of Object.keys(hosts)) {
1872
1924
  if (el === "default") continue;
1873
1925
  if (el !== "asai" && !validateHostdir(el)) continue;
1874
1926
  const cfg = getHostCFG(el, $asai);
1875
- if (_optionalChain([cfg, 'optionalAccess', _191 => _191.close])) continue;
1876
- if (_optionalChain([cfg, 'optionalAccess', _192 => _192.port])) ports.add(Number(cfg.port));
1927
+ if (_optionalChain([cfg, 'optionalAccess', _201 => _201.close])) continue;
1928
+ if (_optionalChain([cfg, 'optionalAccess', _202 => _202.port])) ports.add(Number(cfg.port));
1877
1929
  }
1878
1930
  }
1879
- const proxyhosts = _optionalChain([$asai, 'access', _193 => _193.hostconfig, 'optionalAccess', _194 => _194.proxyhosts]);
1931
+ const proxyhosts = _optionalChain([$asai, 'access', _203 => _203.hostconfig, 'optionalAccess', _204 => _204.proxyhosts]);
1880
1932
  if (proxyhosts) {
1881
1933
  for (const el of Object.keys(proxyhosts)) {
1882
1934
  if (el === "default") continue;
1883
1935
  if (!validateHostdir(el)) continue;
1884
1936
  const cfg = getProxyHostCFG(el, $asai);
1885
- if (_optionalChain([cfg, 'optionalAccess', _195 => _195.proxyport])) ports.add(Number(cfg.proxyport));
1937
+ if (_optionalChain([cfg, 'optionalAccess', _205 => _205.proxyport])) ports.add(Number(cfg.proxyport));
1886
1938
  }
1887
1939
  }
1888
1940
  return [...ports];
@@ -1907,7 +1959,7 @@ function scheduleHttpRetry($asai, hostdir) {
1907
1959
  clearTimeout($asai.hostconfig.guardtm);
1908
1960
  $asai.hostconfig.guardtm = null;
1909
1961
  }
1910
- }, _optionalChain([$asai, 'access', _196 => _196.hostconfig, 'access', _197 => _197.tm, 'optionalAccess', _198 => _198.d]) || 2e3);
1962
+ }, _optionalChain([$asai, 'access', _206 => _206.hostconfig, 'access', _207 => _207.tm, 'optionalAccess', _208 => _208.d]) || 2e3);
1911
1963
  }
1912
1964
  _chunkSMVZ3ZDJcjs.__name.call(void 0, scheduleHttpRetry, "scheduleHttpRetry");
1913
1965
  function clearFailedHttpHost($asai, hostdir, ws2) {
@@ -1920,7 +1972,7 @@ function getHTTPServer(httptype = "", cfg, $asai) {
1920
1972
  if (httptype.startsWith("https")) {
1921
1973
  return {
1922
1974
  AsCreateServer: /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (callback) => {
1923
- return https.createServer(_optionalChain([cfg, 'optionalAccess', _199 => _199.httpscert]) || $asai.hostconfig.httpscert, callback);
1975
+ return https.createServer(_optionalChain([cfg, 'optionalAccess', _209 => _209.httpscert]) || $asai.hostconfig.httpscert, callback);
1924
1976
  }, "AsCreateServer"),
1925
1977
  Agent: https.Agent,
1926
1978
  request: https.request
@@ -1972,13 +2024,13 @@ function startHTTPServer($asai, hostdir) {
1972
2024
  return;
1973
2025
  }
1974
2026
  applySecurityHeaders(res, isHttps, $asai.hostconfig);
1975
- if (_optionalChain([req, 'access', _200 => _200.url, 'optionalAccess', _201 => _201.startsWith, 'call', _202 => _202("/sys")]) && sysWork) {
2027
+ if (_optionalChain([req, 'access', _210 => _210.url, 'optionalAccess', _211 => _211.startsWith, 'call', _212 => _212("/sys")]) && sysWork) {
1976
2028
  logHttp($asai, "SYS", req.method, req.url, skipChecker, req, res);
1977
2029
  sysWork(req, res, hostdir);
1978
- } else if (_optionalChain([req, 'access', _203 => _203.url, 'optionalAccess', _204 => _204.startsWith, 'call', _205 => _205("/api")]) && apiWork) {
2030
+ } else if (_optionalChain([req, 'access', _213 => _213.url, 'optionalAccess', _214 => _214.startsWith, 'call', _215 => _215("/api")]) && apiWork) {
1979
2031
  logHttp($asai, "API", req.method, req.url, skipChecker, req, res);
1980
2032
  apiWork(req, res, hostdir);
1981
- } else if (_optionalChain([req, 'access', _206 => _206.url, 'optionalAccess', _207 => _207.startsWith, 'call', _208 => _208("/jsonp")]) && jsonpWork) {
2033
+ } else if (_optionalChain([req, 'access', _216 => _216.url, 'optionalAccess', _217 => _217.startsWith, 'call', _218 => _218("/jsonp")]) && jsonpWork) {
1982
2034
  logHttp($asai, "JSONP", req.method, req.url, skipChecker, req, res);
1983
2035
  jsonpWork(req, res, hostdir);
1984
2036
  } else if (handleStatic) {
@@ -2050,7 +2102,7 @@ function findSameProcessPortOwner($asai, port, excludeHostdir) {
2050
2102
  for (const hostdir of Object.keys($asai.servershttp || {})) {
2051
2103
  if (hostdir === excludeHostdir) continue;
2052
2104
  const cfg = getHostCFG(hostdir, $asai);
2053
- if (_optionalChain([cfg, 'optionalAccess', _209 => _209.port]) === port) return hostdir;
2105
+ if (_optionalChain([cfg, 'optionalAccess', _219 => _219.port]) === port) return hostdir;
2054
2106
  }
2055
2107
  return null;
2056
2108
  }
@@ -2058,7 +2110,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, findSameProcessPortOwner, "findSameProcess
2058
2110
  function asaiGuard($asai, failedHostdir = "asai") {
2059
2111
  const conflictPorts = $asai.hostconfig.asaiport || [];
2060
2112
  const hostcfg = getHostCFG(failedHostdir, $asai);
2061
- const port = _optionalChain([hostcfg, 'optionalAccess', _210 => _210.port]);
2113
+ const port = _optionalChain([hostcfg, 'optionalAccess', _220 => _220.port]);
2062
2114
  if (!port || !conflictPorts.includes(port)) {
2063
2115
  scheduleHttpRetry($asai, failedHostdir);
2064
2116
  return;
@@ -2066,18 +2118,18 @@ function asaiGuard($asai, failedHostdir = "asai") {
2066
2118
  const sameProcessOwner = findSameProcessPortOwner($asai, port, failedHostdir);
2067
2119
  if (sameProcessOwner) {
2068
2120
  console.error(
2069
- `[AsaiHost] \u7AEF\u53E3 ${port} \u5DF2\u88AB\u540C\u8FDB\u7A0B\u7AD9\u70B9 [${sameProcessOwner}] \u5360\u7528\uFF0C[${failedHostdir}] \u505C\u6B62\u91CD\u8BD5\uFF08\u8BF7\u68C0\u67E5 asaihost.json \u662F\u5426\u91CD\u590D\u914D\u7F6E port\uFF09`
2121
+ `[AsaiHostNodejs] \u7AEF\u53E3 ${port} \u5DF2\u88AB\u540C\u8FDB\u7A0B\u7AD9\u70B9 [${sameProcessOwner}] \u5360\u7528\uFF0C[${failedHostdir}] \u505C\u6B62\u91CD\u8BD5\uFF08\u8BF7\u68C0\u67E5 asaihost.json \u662F\u5426\u91CD\u590D\u914D\u7F6E port\uFF09`
2070
2122
  );
2071
2123
  return;
2072
2124
  }
2073
2125
  const released = releasePort(port, { excludePid: process.pid, label: failedHostdir });
2074
2126
  $asai.hostconfig.asaiport = conflictPorts.filter((p) => p !== port);
2075
2127
  if (released) {
2076
- console.warn(`[AsaiHost] \u7AEF\u53E3 ${port} \u5DF2\u91CA\u653E\uFF0C\u6B63\u5728\u91CD\u65B0\u542F\u52A8 [${failedHostdir}]`);
2128
+ console.warn(`[AsaiHostNodejs] \u7AEF\u53E3 ${port} \u5DF2\u91CA\u653E\uFF0C\u6B63\u5728\u91CD\u65B0\u542F\u52A8 [${failedHostdir}]`);
2077
2129
  scheduleHttpRetry($asai, failedHostdir);
2078
2130
  return;
2079
2131
  }
2080
- console.error(`[AsaiHost] \u7AEF\u53E3 ${port} \u65E0\u6CD5\u91CA\u653E\uFF0C\u542F\u52A8\u5931\u8D25\uFF08netstat -ano | findstr :${port}\uFF09`);
2132
+ console.error(`[AsaiHostNodejs] \u7AEF\u53E3 ${port} \u65E0\u6CD5\u91CA\u653E\uFF0C\u542F\u52A8\u5931\u8D25\uFF08netstat -ano | findstr :${port}\uFF09`);
2081
2133
  process.exit(1);
2082
2134
  }
2083
2135
  _chunkSMVZ3ZDJcjs.__name.call(void 0, asaiGuard, "asaiGuard");
@@ -2096,7 +2148,7 @@ var PROXY_SKIP_HEADERS = /* @__PURE__ */ new Set([
2096
2148
  function startProxyServer($asai, proxyhostdir) {
2097
2149
  const proxycfg = getProxyHostCFG(proxyhostdir, $asai);
2098
2150
  if (!proxycfg.url) return;
2099
- if (_optionalChain([$asai, 'access', _211 => _211.serversproxy, 'optionalAccess', _212 => _212[proxyhostdir]])) return;
2151
+ if (_optionalChain([$asai, 'access', _221 => _221.serversproxy, 'optionalAccess', _222 => _222[proxyhostdir]])) return;
2100
2152
  try {
2101
2153
  const httpServer = getHTTPServer(proxycfg.proxyhttptype, proxycfg, $asai);
2102
2154
  const targetHttp = getHTTPServer(proxycfg.url, proxycfg, $asai);
@@ -2178,14 +2230,14 @@ function startProxyServer($asai, proxyhostdir) {
2178
2230
  proxyServer.on("error", (err) => {
2179
2231
  if (err.code === "EADDRINUSE") {
2180
2232
  $asai.$log("PROXY", `\x1B[41mPort ${proxycfg.proxyport} is already start!\x1B[0m`);
2181
- _optionalChainDelete([$asai, 'access', _213 => _213.serversproxy, 'optionalAccess', _214 => delete _214[proxyhostdir]]);
2233
+ _optionalChainDelete([$asai, 'access', _223 => _223.serversproxy, 'optionalAccess', _224 => delete _224[proxyhostdir]]);
2182
2234
  const released = releasePort(proxycfg.proxyport, {
2183
2235
  excludePid: process.pid,
2184
2236
  label: proxyhostdir
2185
2237
  });
2186
2238
  if (released) {
2187
- console.warn(`[AsaiHost] \u4EE3\u7406\u7AEF\u53E3 ${proxycfg.proxyport} \u5DF2\u91CA\u653E\uFF0C\u6B63\u5728\u91CD\u65B0\u542F\u52A8 [${proxyhostdir}]`);
2188
- setTimeout(() => startProxyServer($asai, proxyhostdir), _optionalChain([$asai, 'access', _215 => _215.hostconfig, 'access', _216 => _216.tm, 'optionalAccess', _217 => _217.d]) || 2e3);
2239
+ console.warn(`[AsaiHostNodejs] \u4EE3\u7406\u7AEF\u53E3 ${proxycfg.proxyport} \u5DF2\u91CA\u653E\uFF0C\u6B63\u5728\u91CD\u65B0\u542F\u52A8 [${proxyhostdir}]`);
2240
+ setTimeout(() => startProxyServer($asai, proxyhostdir), _optionalChain([$asai, 'access', _225 => _225.hostconfig, 'access', _226 => _226.tm, 'optionalAccess', _227 => _227.d]) || 2e3);
2189
2241
  }
2190
2242
  } else {
2191
2243
  $asai.$log("PROXY", "Proxy server error:", err);
@@ -2223,11 +2275,11 @@ function src_default($asai, opt) {
2223
2275
  workHandlers.set("apiWork", opt.apiWork);
2224
2276
  workHandlers.set("wsWork", opt.wsWork);
2225
2277
  workHandlers.set("jsonpWork", opt.jsonpWork);
2226
- function StartAsaiHost() {
2227
- initAsaiHost($asai, opt);
2278
+ function StartAsaiHostNodejs() {
2279
+ initAsaiHostNodejs($asai, opt);
2228
2280
  console.log(`\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B\u203B`);
2229
2281
  releaseConfiguredPorts($asai);
2230
- if (_optionalChain([$asai, 'access', _218 => _218.hostconfig, 'optionalAccess', _219 => _219.hosts])) {
2282
+ if (_optionalChain([$asai, 'access', _228 => _228.hostconfig, 'optionalAccess', _229 => _229.hosts])) {
2231
2283
  $asai.startHTTPServer = (hostdir) => startHTTPServer($asai, hostdir);
2232
2284
  Object.keys($asai.hostconfig.hosts).forEach((el) => {
2233
2285
  if (validateHostdir(el)) {
@@ -2238,7 +2290,7 @@ function src_default($asai, opt) {
2238
2290
  startHTTPServer($asai, "asai");
2239
2291
  }
2240
2292
  }
2241
- if (_optionalChain([$asai, 'access', _220 => _220.hostconfig, 'optionalAccess', _221 => _221.proxyhosts])) {
2293
+ if (_optionalChain([$asai, 'access', _230 => _230.hostconfig, 'optionalAccess', _231 => _231.proxyhosts])) {
2242
2294
  Object.keys($asai.hostconfig.proxyhosts).forEach((el) => {
2243
2295
  if (validateHostdir(el)) {
2244
2296
  startProxyServer($asai, el);
@@ -2246,8 +2298,8 @@ function src_default($asai, opt) {
2246
2298
  });
2247
2299
  }
2248
2300
  }
2249
- _chunkSMVZ3ZDJcjs.__name.call(void 0, StartAsaiHost, "StartAsaiHost");
2250
- return { StartAsaiHost, asaiWs: ws };
2301
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, StartAsaiHostNodejs, "StartAsaiHostNodejs");
2302
+ return { StartAsaiHostNodejs, asaiWs: ws };
2251
2303
  }
2252
2304
  _chunkSMVZ3ZDJcjs.__name.call(void 0, src_default, "default");
2253
2305
 
@@ -2261,22 +2313,22 @@ _chunkSMVZ3ZDJcjs.__export.call(void 0, utils_exports, {
2261
2313
  // src/utils/ws-mock.ts
2262
2314
  function wsMock($asai) {
2263
2315
  function getKeyByData(reqdata, hostdir) {
2264
- return "_wstask_" + (hostdir || "") + "_" + (_optionalChain([reqdata, 'optionalAccess', _222 => _222.id]) || _optionalChain([reqdata, 'optionalAccess', _223 => _223.ty]) + "." + _optionalChain([reqdata, 'optionalAccess', _224 => _224.ac]));
2316
+ return "_wstask_" + (hostdir || "") + "_" + (_optionalChain([reqdata, 'optionalAccess', _232 => _232.id]) || _optionalChain([reqdata, 'optionalAccess', _233 => _233.ty]) + "." + _optionalChain([reqdata, 'optionalAccess', _234 => _234.ac]));
2265
2317
  }
2266
2318
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getKeyByData, "getKeyByData");
2267
2319
  function getMockDb(workopt) {
2268
2320
  const { reqdata, mockdata } = workopt;
2269
- const wsfn = _optionalChain([mockdata, 'optionalAccess', _225 => _225.fn]) ? _optionalChain([$asai, 'access', _226 => _226.asaimock, 'access', _227 => _227.fn, 'optionalAccess', _228 => _228[mockdata.fn]]) : null;
2321
+ const wsfn = _optionalChain([mockdata, 'optionalAccess', _235 => _235.fn]) ? _optionalChain([$asai, 'access', _236 => _236.asaimock, 'access', _237 => _237.fn, 'optionalAccess', _238 => _238[mockdata.fn]]) : null;
2270
2322
  if (wsfn) return wsfn({ workopt, $asai, mockName: mockdata.fn });
2271
2323
  return { ...reqdata, ...mockdata || {} };
2272
2324
  }
2273
2325
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getMockDb, "getMockDb");
2274
2326
  function wsWorkApi(workopt) {
2275
- _optionalChain([$asai, 'access', _229 => _229.serversws, 'access', _230 => _230[workopt.hostdir], 'optionalAccess', _231 => _231.sendws, 'optionalCall', _232 => _232(workopt.reqdataisobj ? getMockDb(workopt) : workopt.reqdata, 0, workopt.ws)]);
2327
+ _optionalChain([$asai, 'access', _239 => _239.serversws, 'access', _240 => _240[workopt.hostdir], 'optionalAccess', _241 => _241.sendws, 'optionalCall', _242 => _242(workopt.reqdataisobj ? getMockDb(workopt) : workopt.reqdata, 0, workopt.ws)]);
2276
2328
  }
2277
2329
  _chunkSMVZ3ZDJcjs.__name.call(void 0, wsWorkApi, "wsWorkApi");
2278
2330
  function wsWorkListen(workopt, reqkey) {
2279
- if (_optionalChain([workopt, 'access', _233 => _233.reqdata, 'optionalAccess', _234 => _234.off])) {
2331
+ if (_optionalChain([workopt, 'access', _243 => _243.reqdata, 'optionalAccess', _244 => _244.off])) {
2280
2332
  if ($asai.tasksws[workopt.hostdir][reqkey]) {
2281
2333
  clearInterval($asai.tasksws[workopt.hostdir][reqkey]);
2282
2334
  $asai.tasksws[workopt.hostdir][reqkey] = null;
@@ -2291,9 +2343,9 @@ function wsMock($asai) {
2291
2343
  if (!$asai.tasksws[workopt.hostdir][reqkey]) {
2292
2344
  clearInterval($asai.tasksws[workopt.hostdir][reqkey]);
2293
2345
  }
2294
- }, _optionalChain([newDataMock, 'optionalAccess', _235 => _235.tc]) || 2e3);
2295
- _optionalChain([workopt, 'access', _236 => _236.ws, 'optionalAccess', _237 => _237.once, 'optionalCall', _238 => _238("close", () => {
2296
- if (_optionalChain([$asai, 'access', _239 => _239.tasksws, 'access', _240 => _240[workopt.hostdir], 'optionalAccess', _241 => _241[reqkey]])) {
2346
+ }, _optionalChain([newDataMock, 'optionalAccess', _245 => _245.tc]) || 2e3);
2347
+ _optionalChain([workopt, 'access', _246 => _246.ws, 'optionalAccess', _247 => _247.once, 'optionalCall', _248 => _248("close", () => {
2348
+ if (_optionalChain([$asai, 'access', _249 => _249.tasksws, 'access', _250 => _250[workopt.hostdir], 'optionalAccess', _251 => _251[reqkey]])) {
2297
2349
  clearInterval($asai.tasksws[workopt.hostdir][reqkey]);
2298
2350
  delete $asai.tasksws[workopt.hostdir][reqkey];
2299
2351
  }
@@ -2301,8 +2353,8 @@ function wsMock($asai) {
2301
2353
  }
2302
2354
  _chunkSMVZ3ZDJcjs.__name.call(void 0, wsWorkListen, "wsWorkListen");
2303
2355
  function wsWorkMock(workopt) {
2304
- workopt.mockdata = workopt.reqdataisobj && _optionalChain([$asai, 'access', _242 => _242.asaimock, 'optionalAccess', _243 => _243.db, 'optionalAccess', _244 => _244[workopt.hostdir], 'optionalAccess', _245 => _245[_optionalChain([workopt, 'access', _246 => _246.reqdata, 'optionalAccess', _247 => _247.ty])]]) || {};
2305
- if (_optionalChain([workopt, 'access', _248 => _248.mockdata, 'optionalAccess', _249 => _249.wc])) {
2356
+ workopt.mockdata = workopt.reqdataisobj && _optionalChain([$asai, 'access', _252 => _252.asaimock, 'optionalAccess', _253 => _253.db, 'optionalAccess', _254 => _254[workopt.hostdir], 'optionalAccess', _255 => _255[_optionalChain([workopt, 'access', _256 => _256.reqdata, 'optionalAccess', _257 => _257.ty])]]) || {};
2357
+ if (_optionalChain([workopt, 'access', _258 => _258.mockdata, 'optionalAccess', _259 => _259.wc])) {
2306
2358
  wsWorkListen(workopt, getKeyByData(workopt.reqdata, workopt.hostdir));
2307
2359
  } else {
2308
2360
  wsWorkApi(workopt);
@@ -2315,11 +2367,11 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, wsMock, "wsMock");
2315
2367
 
2316
2368
  // src/infra/user-auth.ts
2317
2369
  async function attachServerUserLevel(req, $asai) {
2318
- const userinfo = _optionalChain([req, 'optionalAccess', _250 => _250.Userinfo]);
2370
+ const userinfo = _optionalChain([req, 'optionalAccess', _260 => _260.Userinfo]);
2319
2371
  if (!Array.isArray(userinfo) || !userinfo[0]) return;
2320
2372
  const us = String(userinfo[0]);
2321
2373
  try {
2322
- const { createUserStore: createUserStore2 } = await Promise.resolve().then(() => _interopRequireWildcard(require("./user-store-SX4N6PQ4.cjs")));
2374
+ const { createUserStore: createUserStore2 } = await Promise.resolve().then(() => _interopRequireWildcard(require("./user-store-6J2PSEIN.cjs")));
2323
2375
  const user = await createUserStore2($asai).findByUsername(us);
2324
2376
  if (user && user.status === "active") {
2325
2377
  req._serverUser = { us: user.us, lv: user.lv, status: user.status };
@@ -2327,34 +2379,34 @@ async function attachServerUserLevel(req, $asai) {
2327
2379
  } else {
2328
2380
  req._serverUser = null;
2329
2381
  }
2330
- } catch (e31) {
2382
+ } catch (e33) {
2331
2383
  req._serverUser = null;
2332
2384
  }
2333
2385
  }
2334
2386
  _chunkSMVZ3ZDJcjs.__name.call(void 0, attachServerUserLevel, "attachServerUserLevel");
2335
2387
  function getRequestUserLevel(req) {
2336
- if (_optionalChain([req, 'optionalAccess', _251 => _251._serverUser, 'optionalAccess', _252 => _252.lv]) != null) return Number(req._serverUser.lv);
2337
- const n = Number(_nullishCoalesce(_optionalChain([req, 'optionalAccess', _253 => _253.Userinfo, 'optionalAccess', _254 => _254[1]]), () => ( -1)));
2388
+ if (_optionalChain([req, 'optionalAccess', _261 => _261._serverUser, 'optionalAccess', _262 => _262.lv]) != null) return Number(req._serverUser.lv);
2389
+ const n = Number(_nullishCoalesce(_optionalChain([req, 'optionalAccess', _263 => _263.Userinfo, 'optionalAccess', _264 => _264[1]]), () => ( -1)));
2338
2390
  return Number.isFinite(n) ? n : -1;
2339
2391
  }
2340
2392
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getRequestUserLevel, "getRequestUserLevel");
2341
2393
  function getRequestUsername(req) {
2342
- if (_optionalChain([req, 'optionalAccess', _255 => _255._serverUser, 'optionalAccess', _256 => _256.us])) return String(req._serverUser.us);
2343
- const us = _optionalChain([req, 'optionalAccess', _257 => _257.Userinfo, 'optionalAccess', _258 => _258[0]]);
2394
+ if (_optionalChain([req, 'optionalAccess', _265 => _265._serverUser, 'optionalAccess', _266 => _266.us])) return String(req._serverUser.us);
2395
+ const us = _optionalChain([req, 'optionalAccess', _267 => _267.Userinfo, 'optionalAccess', _268 => _268[0]]);
2344
2396
  return us ? String(us) : void 0;
2345
2397
  }
2346
2398
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getRequestUsername, "getRequestUsername");
2347
2399
 
2348
2400
  // src/infra/access-control.ts
2349
2401
  function getSecurityConfig($asai) {
2350
- return _optionalChain([$asai, 'optionalAccess', _259 => _259.hostconfig, 'optionalAccess', _260 => _260.security]) || {};
2402
+ return _optionalChain([$asai, 'optionalAccess', _269 => _269.hostconfig, 'optionalAccess', _270 => _270.security]) || {};
2351
2403
  }
2352
2404
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getSecurityConfig, "getSecurityConfig");
2353
- function pathMatchesPattern(path8, pattern) {
2405
+ function pathMatchesPattern(path7, pattern) {
2354
2406
  if (pattern.endsWith("*")) {
2355
- return path8.startsWith(pattern.slice(0, -1));
2407
+ return path7.startsWith(pattern.slice(0, -1));
2356
2408
  }
2357
- return path8 === pattern;
2409
+ return path7 === pattern;
2358
2410
  }
2359
2411
  _chunkSMVZ3ZDJcjs.__name.call(void 0, pathMatchesPattern, "pathMatchesPattern");
2360
2412
  function isAuthSkipped($asai, pathname) {
@@ -2381,13 +2433,13 @@ function validateHttpAuth(req, $asai, pathname) {
2381
2433
  if (!isAuthRequired($asai, pathname)) {
2382
2434
  return { ok: true };
2383
2435
  }
2384
- const userinfo = _optionalChain([req, 'optionalAccess', _261 => _261.Userinfo]);
2436
+ const userinfo = _optionalChain([req, 'optionalAccess', _271 => _271.Userinfo]);
2385
2437
  const ip = getClientIp(req);
2386
2438
  if (!Array.isArray(userinfo) || userinfo.length < 3 || !userinfo[0]) {
2387
2439
  logSecurityEvent($asai, {
2388
2440
  type: "AUTH_MISSING",
2389
2441
  path: pathname,
2390
- method: _optionalChain([req, 'optionalAccess', _262 => _262.method]),
2442
+ method: _optionalChain([req, 'optionalAccess', _272 => _272.method]),
2391
2443
  ip,
2392
2444
  detail: "Userinfo header missing or invalid"
2393
2445
  });
@@ -2401,7 +2453,7 @@ function validateHttpAuth(req, $asai, pathname) {
2401
2453
  logSecurityEvent($asai, {
2402
2454
  type: "ACCESS_DENIED",
2403
2455
  path: pathname,
2404
- method: _optionalChain([req, 'optionalAccess', _263 => _263.method]),
2456
+ method: _optionalChain([req, 'optionalAccess', _273 => _273.method]),
2405
2457
  user: String(us),
2406
2458
  level: userLevel,
2407
2459
  ip,
@@ -2413,13 +2465,13 @@ function validateHttpAuth(req, $asai, pathname) {
2413
2465
  }
2414
2466
  _chunkSMVZ3ZDJcjs.__name.call(void 0, validateHttpAuth, "validateHttpAuth");
2415
2467
  async function validateHttpAuthAsync(req, $asai, pathname) {
2416
- if (Array.isArray(_optionalChain([req, 'optionalAccess', _264 => _264.Userinfo])) && req.Userinfo[0]) {
2468
+ if (Array.isArray(_optionalChain([req, 'optionalAccess', _274 => _274.Userinfo])) && req.Userinfo[0]) {
2417
2469
  await attachServerUserLevel(req, $asai);
2418
2470
  if (!req._serverUser && isAuthRequired($asai, pathname)) {
2419
2471
  logSecurityEvent($asai, {
2420
2472
  type: "ACCESS_DENIED",
2421
2473
  path: pathname,
2422
- method: _optionalChain([req, 'optionalAccess', _265 => _265.method]),
2474
+ method: _optionalChain([req, 'optionalAccess', _275 => _275.method]),
2423
2475
  user: String(req.Userinfo[0]),
2424
2476
  ip: getClientIp(req),
2425
2477
  detail: "User not found or inactive"
@@ -2481,7 +2533,7 @@ function resolveApiCorsOrigin(req, hostcfg, getHeader) {
2481
2533
  if (referer) {
2482
2534
  try {
2483
2535
  origin = new URL(referer).origin;
2484
- } catch (e32) {
2536
+ } catch (e34) {
2485
2537
  const parts = referer.split("/");
2486
2538
  if (parts.length >= 3) origin = `${parts[0]}//${parts[2]}`;
2487
2539
  }
@@ -2493,7 +2545,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, resolveApiCorsOrigin, "resolveApiCorsOrigi
2493
2545
  function isApiCorsAllowed(origin, hostcfg, hostHeader) {
2494
2546
  if (!origin) return false;
2495
2547
  if (origin === "*") return true;
2496
- const corsList = _optionalChain([hostcfg, 'optionalAccess', _266 => _266.cors]);
2548
+ const corsList = _optionalChain([hostcfg, 'optionalAccess', _276 => _276.cors]);
2497
2549
  if (!Array.isArray(corsList) || !corsList.length) return true;
2498
2550
  if (corsList.includes(origin)) return true;
2499
2551
  if (hostHeader && origin.includes(hostHeader)) return true;
@@ -2502,8 +2554,56 @@ function isApiCorsAllowed(origin, hostcfg, hostHeader) {
2502
2554
  _chunkSMVZ3ZDJcjs.__name.call(void 0, isApiCorsAllowed, "isApiCorsAllowed");
2503
2555
 
2504
2556
  // src/common/server/Api.ts
2557
+ function readRequestBody(req, maxBody) {
2558
+ return new Promise((resolve6, reject) => {
2559
+ const chunks = [];
2560
+ let received = 0;
2561
+ let settled = false;
2562
+ const finish = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (err, data) => {
2563
+ if (settled) return;
2564
+ settled = true;
2565
+ if (err) reject(err);
2566
+ else resolve6(_nullishCoalesce(data, () => ( "")));
2567
+ }, "finish");
2568
+ req.on("data", (chunk) => {
2569
+ if (settled) return;
2570
+ received += chunk.length;
2571
+ if (received > maxBody) {
2572
+ req.destroy();
2573
+ finish(new Error("PAYLOAD_TOO_LARGE"));
2574
+ return;
2575
+ }
2576
+ chunks.push(chunk);
2577
+ });
2578
+ req.on("end", () => finish(null, Buffer.concat(chunks).toString("utf8")));
2579
+ req.on("error", (err) => finish(err));
2580
+ });
2581
+ }
2582
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, readRequestBody, "readRequestBody");
2583
+ function processPostPayload($asai, req, postdata, pm) {
2584
+ let isAes = false;
2585
+ let out = postdata;
2586
+ if ($asai.$lib.aesfns && _optionalChain([out, 'optionalAccess', _277 => _277.startsWith, 'optionalCall', _278 => _278('{"aes":')])) {
2587
+ isAes = true;
2588
+ const aesData = JSON.parse(out);
2589
+ out = $asai.$lib.aesfns.reqAES({ data: aesData });
2590
+ if (_optionalChain([aesData, 'optionalAccess', _279 => _279.aes]) === 2 && typeof out === "string") {
2591
+ try {
2592
+ out = JSON.parse(out);
2593
+ } catch (e35) {
2594
+ }
2595
+ }
2596
+ }
2597
+ const plainJson = typeof out === "string" && out.trimStart().startsWith("{");
2598
+ if (_optionalChain([req, 'optionalAccess', _280 => _280.Userinfo, 'optionalAccess', _281 => _281[2]]) && !plainJson) {
2599
+ pm = req.Userinfo[2];
2600
+ out = $asai.$lib.AsCode.asdecode(out, pm);
2601
+ }
2602
+ return { postdata: out, pm, isAes };
2603
+ }
2604
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, processPostPayload, "processPostPayload");
2505
2605
  var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, opt = {}) => {
2506
- _optionalChain([opt, 'optionalAccess', _267 => _267.fn, 'optionalCall', _268 => _268($asai)]);
2606
+ _optionalChain([opt, 'optionalAccess', _282 => _282.fn, 'optionalCall', _283 => _283($asai)]);
2507
2607
  function getHeader(req, key) {
2508
2608
  return req.headers[key.toLowerCase()] || "";
2509
2609
  }
@@ -2512,7 +2612,7 @@ var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2512
2612
  let apiRouteCacheLen = -1;
2513
2613
  function findApiHandler($asai2, pathname) {
2514
2614
  const apis = $asai2.hostserverapis;
2515
- if (!_optionalChain([apis, 'optionalAccess', _269 => _269.length])) return void 0;
2615
+ if (!_optionalChain([apis, 'optionalAccess', _284 => _284.length])) return void 0;
2516
2616
  if (!apiRouteCache || apiRouteCacheLen !== apis.length) {
2517
2617
  apiRouteCache = apis.map((elp) => ({ key: elp, path: `/api/${elp}` }));
2518
2618
  apiRouteCacheLen = apis.length;
@@ -2560,9 +2660,9 @@ var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2560
2660
  pm: decodeURIComponent(urlParse.search.substring(4))
2561
2661
  };
2562
2662
  if (req.url.indexOf("binary") === -1) {
2563
- if (_optionalChain([req, 'optionalAccess', _270 => _270.Userinfo]) && _optionalChain([req, 'optionalAccess', _271 => _271.Userinfo, 'access', _272 => _272[2]]) && _optionalChain([query, 'optionalAccess', _273 => _273.pm])) {
2663
+ if (_optionalChain([req, 'optionalAccess', _285 => _285.Userinfo]) && _optionalChain([req, 'optionalAccess', _286 => _286.Userinfo, 'access', _287 => _287[2]]) && _optionalChain([query, 'optionalAccess', _288 => _288.pm])) {
2564
2664
  pm = req.Userinfo[2];
2565
- query = $asai.$lib.AsCode.asdecode(_optionalChain([query, 'optionalAccess', _274 => _274.pm]), pm);
2665
+ query = $asai.$lib.AsCode.asdecode(_optionalChain([query, 'optionalAccess', _289 => _289.pm]), pm);
2566
2666
  query = Object.fromEntries(new URLSearchParams("?" + query).entries());
2567
2667
  }
2568
2668
  }
@@ -2581,13 +2681,29 @@ var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2581
2681
  const releaseSlot = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, () => releaseApiSlot(hostdir, clientIp), "releaseSlot");
2582
2682
  res.once("finish", releaseSlot);
2583
2683
  res.once("close", releaseSlot);
2684
+ const maxBody = _optionalChain([$asai, 'access', _290 => _290.hostconfig, 'optionalAccess', _291 => _291.maxbody]) || 100 * 1024 * 1024;
2685
+ const isTextPost = req.method === "POST" && req.url.indexOf("binary") === -1;
2686
+ const bodyPromise = isTextPost ? readRequestBody(req, maxBody) : null;
2584
2687
  void (async () => {
2585
- const authResult = await validateHttpAuthAsync(req, $asai, pathname);
2688
+ let authResult;
2689
+ let rawBody = "";
2690
+ try {
2691
+ [authResult, rawBody] = await Promise.all([
2692
+ validateHttpAuthAsync(req, $asai, pathname),
2693
+ _nullishCoalesce(bodyPromise, () => ( Promise.resolve("")))
2694
+ ]);
2695
+ } catch (err) {
2696
+ releaseSlot();
2697
+ if (_optionalChain([err, 'optionalAccess', _292 => _292.message]) === "PAYLOAD_TOO_LARGE") {
2698
+ return sendError(res, 413, "Payload Too Large");
2699
+ }
2700
+ return sendError(res, 400, _optionalChain([err, 'optionalAccess', _293 => _293.message]) || "Bad Request");
2701
+ }
2586
2702
  if (!authResult.ok) {
2587
2703
  releaseSlot();
2588
2704
  return sendAuthError(res, authResult);
2589
2705
  }
2590
- let apiFn = _optionalChain([$asai, 'access', _275 => _275.hostserverapi, 'access', _276 => _276[apiHandlerKey], 'optionalCall', _277 => _277($asai, query)]);
2706
+ let apiFn = _optionalChain([$asai, 'access', _294 => _294.hostserverapi, 'access', _295 => _295[apiHandlerKey], 'optionalCall', _296 => _296($asai, query)]);
2591
2707
  if (!apiFn) {
2592
2708
  return sendError(res, 501, "Not Implemented");
2593
2709
  }
@@ -2596,57 +2712,30 @@ var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2596
2712
  let qrdata;
2597
2713
  let postdata;
2598
2714
  if (req.url.indexOf("binary") === -1) {
2599
- postdata = "";
2600
2715
  qrdata = query;
2601
2716
  if (req.method === "POST") {
2602
- const chunks = [];
2603
- const maxBody = _optionalChain([$asai, 'access', _278 => _278.hostconfig, 'optionalAccess', _279 => _279.maxbody]) || 100 * 1024 * 1024;
2604
- let received = 0;
2605
- let aborted = false;
2606
- req.on("data", (chunk) => {
2607
- if (aborted) return;
2608
- received += chunk.length;
2609
- if (received > maxBody) {
2610
- aborted = true;
2611
- sendError(res, 413, "Payload Too Large");
2612
- req.destroy();
2613
- return;
2614
- }
2615
- chunks.push(chunk);
2616
- });
2617
- req.on("end", () => {
2618
- if (aborted) return;
2619
- postdata = Buffer.concat(chunks).toString();
2620
- isAes = $asai.$lib.aesfns && _optionalChain([postdata, 'optionalAccess', _280 => _280.startsWith, 'optionalCall', _281 => _281('{"aes":')]);
2621
- if (isAes) {
2622
- const aesData = JSON.parse(postdata);
2623
- postdata = $asai.$lib.aesfns.reqAES({ data: aesData });
2624
- if (_optionalChain([aesData, 'optionalAccess', _282 => _282.aes]) === 2) {
2625
- try {
2626
- postdata = JSON.parse(postdata);
2627
- } catch (err) {
2628
- }
2629
- }
2630
- }
2631
- if (_optionalChain([req, 'optionalAccess', _283 => _283.Userinfo]) && _optionalChain([req, 'optionalAccess', _284 => _284.Userinfo, 'access', _285 => _285[2]])) {
2632
- pm = req.Userinfo[2];
2633
- postdata = $asai.$lib.AsCode.asdecode(postdata, pm);
2634
- }
2635
- if (_optionalChain([apiFn, 'optionalAccess', _286 => _286.post]) && typeof _optionalChain([apiFn, 'optionalAccess', _287 => _287.post]) === "function") {
2636
- const optTmp = { qrdata, data: postdata, pm };
2637
- if (isAes || _optionalChain([$asai, 'access', _288 => _288.$lib, 'access', _289 => _289.aesfns, 'optionalAccess', _290 => _290.allaes])) {
2638
- optTmp.resAES = _optionalChain([$asai, 'access', _291 => _291.$lib, 'access', _292 => _292.aesfns, 'optionalAccess', _293 => _293.resAES]);
2639
- }
2640
- apiFn.post(req, res, hostdir, optTmp);
2641
- } else {
2642
- res.end(postdata);
2717
+ try {
2718
+ const processed = processPostPayload($asai, req, rawBody, pm);
2719
+ postdata = processed.postdata;
2720
+ pm = processed.pm;
2721
+ isAes = processed.isAes;
2722
+ } catch (e36) {
2723
+ return sendError(res, 400, "AES decrypt failed");
2724
+ }
2725
+ if (_optionalChain([apiFn, 'optionalAccess', _297 => _297.post]) && typeof _optionalChain([apiFn, 'optionalAccess', _298 => _298.post]) === "function") {
2726
+ const optTmp = { qrdata, data: postdata, pm };
2727
+ if (isAes || _optionalChain([$asai, 'access', _299 => _299.$lib, 'access', _300 => _300.aesfns, 'optionalAccess', _301 => _301.allaes])) {
2728
+ optTmp.resAES = _optionalChain([$asai, 'access', _302 => _302.$lib, 'access', _303 => _303.aesfns, 'optionalAccess', _304 => _304.resAES]);
2643
2729
  }
2644
- });
2730
+ apiFn.post(req, res, hostdir, optTmp);
2731
+ } else {
2732
+ res.end(typeof postdata === "string" ? postdata : JSON.stringify(_nullishCoalesce(postdata, () => ( ""))));
2733
+ }
2645
2734
  } else if (req.method === "GET") {
2646
- if (_optionalChain([apiFn, 'optionalAccess', _294 => _294.get]) && typeof _optionalChain([apiFn, 'optionalAccess', _295 => _295.get]) === "function") {
2735
+ if (_optionalChain([apiFn, 'optionalAccess', _305 => _305.get]) && typeof _optionalChain([apiFn, 'optionalAccess', _306 => _306.get]) === "function") {
2647
2736
  const optTmp = { qrdata, data: qrdata, pm };
2648
- if (isAes || _optionalChain([$asai, 'access', _296 => _296.$lib, 'access', _297 => _297.aesfns, 'optionalAccess', _298 => _298.allaes])) {
2649
- optTmp.resAES = _optionalChain([$asai, 'access', _299 => _299.$lib, 'access', _300 => _300.aesfns, 'optionalAccess', _301 => _301.resAES]);
2737
+ if (isAes || _optionalChain([$asai, 'access', _307 => _307.$lib, 'access', _308 => _308.aesfns, 'optionalAccess', _309 => _309.allaes])) {
2738
+ optTmp.resAES = _optionalChain([$asai, 'access', _310 => _310.$lib, 'access', _311 => _311.aesfns, 'optionalAccess', _312 => _312.resAES]);
2650
2739
  }
2651
2740
  apiFn.get(req, res, hostdir, optTmp);
2652
2741
  } else {
@@ -2654,12 +2743,12 @@ var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2654
2743
  }
2655
2744
  }
2656
2745
  } else {
2657
- if (_optionalChain([Object, 'access', _302 => _302.keys, 'call', _303 => _303(query), 'optionalAccess', _304 => _304.length])) {
2746
+ if (_optionalChain([Object, 'access', _313 => _313.keys, 'call', _314 => _314(query), 'optionalAccess', _315 => _315.length])) {
2658
2747
  qrdata = query;
2659
2748
  }
2660
2749
  if (req.method === "POST") {
2661
2750
  $asai.$lib.AsNodeTool.upBinary(req).then((postdata2) => {
2662
- if (_optionalChain([apiFn, 'optionalAccess', _305 => _305.post]) && typeof _optionalChain([apiFn, 'optionalAccess', _306 => _306.post]) === "function") {
2751
+ if (_optionalChain([apiFn, 'optionalAccess', _316 => _316.post]) && typeof _optionalChain([apiFn, 'optionalAccess', _317 => _317.post]) === "function") {
2663
2752
  apiFn.post(req, res, hostdir, {
2664
2753
  qrdata,
2665
2754
  data: postdata2
@@ -2683,12 +2772,12 @@ var Api_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2683
2772
 
2684
2773
  // src/common/server/Ws.ts
2685
2774
  var Ws_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, opt = {}) => {
2686
- _optionalChain([opt, 'optionalAccess', _307 => _307.fn, 'optionalCall', _308 => _308($asai)]);
2775
+ _optionalChain([opt, 'optionalAccess', _318 => _318.fn, 'optionalCall', _319 => _319($asai)]);
2687
2776
  const wsHandlerCache = /* @__PURE__ */ new Map();
2688
2777
  const routeIndex = ensureWsRouteIndex($asai);
2689
2778
  function getWsHandler(handlerKey) {
2690
2779
  if (!wsHandlerCache.has(handlerKey)) {
2691
- wsHandlerCache.set(handlerKey, _optionalChain([$asai, 'access', _309 => _309.hostserverws, 'access', _310 => _310[handlerKey], 'optionalCall', _311 => _311($asai)]));
2780
+ wsHandlerCache.set(handlerKey, _optionalChain([$asai, 'access', _320 => _320.hostserverws, 'access', _321 => _321[handlerKey], 'optionalCall', _322 => _322($asai)]));
2692
2781
  }
2693
2782
  return wsHandlerCache.get(handlerKey);
2694
2783
  }
@@ -2712,21 +2801,21 @@ var Ws_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, o
2712
2801
  let reqdata = parseMessage(msg);
2713
2802
  let handlerKey;
2714
2803
  if (reqdata === "ping") {
2715
- _optionalChain([ws2, 'access', _312 => _312.send, 'optionalCall', _313 => _313("pong")]);
2804
+ _optionalChain([ws2, 'access', _323 => _323.send, 'optionalCall', _324 => _324("pong")]);
2716
2805
  return;
2717
2806
  } else {
2718
2807
  const reqdataisobj = typeof reqdata === "object" && reqdata !== null;
2719
- handlerKey = reqdataisobj ? routeIndex.matchTy(_optionalChain([reqdata, 'optionalAccess', _314 => _314.ty])) : routeIndex.matchString(reqdata);
2720
- if (!handlerKey && _optionalChain([$asai, 'access', _315 => _315.hostserverwss, 'optionalAccess', _316 => _316.length])) {
2808
+ handlerKey = reqdataisobj ? routeIndex.matchTy(_optionalChain([reqdata, 'optionalAccess', _325 => _325.ty])) : routeIndex.matchString(reqdata);
2809
+ if (!handlerKey && _optionalChain([$asai, 'access', _326 => _326.hostserverwss, 'optionalAccess', _327 => _327.length])) {
2721
2810
  handlerKey = $asai.hostserverwss.find((elp) => {
2722
2811
  if (reqdataisobj) {
2723
- return _optionalChain([reqdata, 'optionalAccess', _317 => _317.ty, 'optionalAccess', _318 => _318.startsWith, 'call', _319 => _319(elp)]);
2812
+ return _optionalChain([reqdata, 'optionalAccess', _328 => _328.ty, 'optionalAccess', _329 => _329.startsWith, 'call', _330 => _330(elp)]);
2724
2813
  }
2725
2814
  return typeof reqdata === "string" && reqdata.startsWith(elp);
2726
2815
  });
2727
2816
  }
2728
2817
  if (!handlerKey) {
2729
- _optionalChain([$asai, 'access', _320 => _320.asaimock, 'optionalAccess', _321 => _321.wsWorkMock, 'call', _322 => _322({
2818
+ _optionalChain([$asai, 'access', _331 => _331.asaimock, 'optionalAccess', _332 => _332.wsWorkMock, 'call', _333 => _333({
2730
2819
  msg,
2731
2820
  ws: ws2,
2732
2821
  hostdir,
@@ -2738,14 +2827,14 @@ var Ws_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, o
2738
2827
  }
2739
2828
  }
2740
2829
  if (!handlerKey) return;
2741
- _optionalChain([getWsHandler, 'call', _323 => _323(handlerKey), 'optionalAccess', _324 => _324.work, 'optionalCall', _325 => _325(reqdata, ws2, hostdir, req)]);
2830
+ _optionalChain([getWsHandler, 'call', _334 => _334(handlerKey), 'optionalAccess', _335 => _335.work, 'optionalCall', _336 => _336(reqdata, ws2, hostdir, req)]);
2742
2831
  } catch (err) {
2743
- _optionalChain([($asai.$log || console.error), 'optionalCall', _326 => _326("WS", "handler error", err instanceof Error ? err.message : err)]);
2832
+ _optionalChain([($asai.$log || console.error), 'optionalCall', _337 => _337("WS", "handler error", err instanceof Error ? err.message : err)]);
2744
2833
  }
2745
2834
  }
2746
2835
  _chunkSMVZ3ZDJcjs.__name.call(void 0, wsWork, "wsWork");
2747
2836
  function _getMessage(msg) {
2748
- if (_optionalChain([msg, 'optionalAccess', _327 => _327.db, 'optionalAccess', _328 => _328.aes]) && _optionalChain([$asai, 'access', _329 => _329.$lib, 'optionalAccess', _330 => _330.aesfns, 'optionalAccess', _331 => _331.reqAES])) {
2837
+ if (_optionalChain([msg, 'optionalAccess', _338 => _338.db, 'optionalAccess', _339 => _339.aes]) && _optionalChain([$asai, 'access', _340 => _340.$lib, 'optionalAccess', _341 => _341.aesfns, 'optionalAccess', _342 => _342.reqAES])) {
2749
2838
  msg.db = $asai.$lib.aesfns.reqAES({ data: msg.db });
2750
2839
  }
2751
2840
  return msg;
@@ -2772,12 +2861,12 @@ var Ws_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, o
2772
2861
 
2773
2862
  // src/common/server/Sys.ts
2774
2863
  var Sys_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, opt = {}) => {
2775
- _optionalChain([opt, 'optionalAccess', _332 => _332.fn, 'optionalCall', _333 => _333($asai)]);
2864
+ _optionalChain([opt, 'optionalAccess', _343 => _343.fn, 'optionalCall', _344 => _344($asai)]);
2776
2865
  let sysRouteCache = null;
2777
2866
  let sysRouteCacheLen = -1;
2778
2867
  function findSystemHandler(req) {
2779
2868
  const routes = $asai.hostserversyss;
2780
- if (!_optionalChain([routes, 'optionalAccess', _334 => _334.length])) return void 0;
2869
+ if (!_optionalChain([routes, 'optionalAccess', _345 => _345.length])) return void 0;
2781
2870
  if (!sysRouteCache || sysRouteCacheLen !== routes.length) {
2782
2871
  sysRouteCache = routes.map((elp) => ({ key: elp, route: `/${elp}` }));
2783
2872
  sysRouteCacheLen = routes.length;
@@ -2810,11 +2899,11 @@ var Sys_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2810
2899
  if (!authResult.ok) {
2811
2900
  return sendAuthError(res, authResult);
2812
2901
  }
2813
- const handler = _optionalChain([$asai, 'access', _335 => _335.hostserversys, 'access', _336 => _336[handlerKey], 'optionalCall', _337 => _337($asai)]);
2902
+ const handler = _optionalChain([$asai, 'access', _346 => _346.hostserversys, 'access', _347 => _347[handlerKey], 'optionalCall', _348 => _348($asai)]);
2814
2903
  if (!handler) {
2815
2904
  return sendError(res, 500, "Handler Initialization Failed");
2816
2905
  }
2817
- if (_optionalChain([handler, 'optionalAccess', _338 => _338.show]) && typeof _optionalChain([handler, 'optionalAccess', _339 => _339.show]) === "function") {
2906
+ if (_optionalChain([handler, 'optionalAccess', _349 => _349.show]) && typeof _optionalChain([handler, 'optionalAccess', _350 => _350.show]) === "function") {
2818
2907
  handler.show(req, res, hostdir);
2819
2908
  } else {
2820
2909
  res.end("postdata");
@@ -2834,18 +2923,18 @@ var Sys_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
2834
2923
 
2835
2924
  // src/common/server/WsClient.ts
2836
2925
  var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, wsname) => {
2837
- if (!_optionalChain([$asai, 'optionalAccess', _340 => _340.clientws])) {
2926
+ if (!_optionalChain([$asai, 'optionalAccess', _351 => _351.clientws])) {
2838
2927
  $asai.clientws = {};
2839
2928
  }
2840
2929
  if (!$asai.clientws[wsname]) {
2841
2930
  $asai.clientws[wsname] = { tasks: /* @__PURE__ */ new Map() };
2842
2931
  }
2843
2932
  function getKeyByData(msgdata) {
2844
- return _optionalChain([msgdata, 'optionalAccess', _341 => _341.id]) || _optionalChain([msgdata, 'optionalAccess', _342 => _342.ty]);
2933
+ return _optionalChain([msgdata, 'optionalAccess', _352 => _352.id]) || _optionalChain([msgdata, 'optionalAccess', _353 => _353.ty]);
2845
2934
  }
2846
2935
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getKeyByData, "getKeyByData");
2847
2936
  function clientwsInit() {
2848
- return new Promise((resolve7, reject) => {
2937
+ return new Promise((resolve6, reject) => {
2849
2938
  $asai.clientws[wsname].socket = new $asai.asaiWs(
2850
2939
  $asai.command.commandconfig.clientws[wsname]
2851
2940
  );
@@ -2854,7 +2943,7 @@ var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($a
2854
2943
  };
2855
2944
  $asai.clientws[wsname].socket.on("error", (err) => {
2856
2945
  $asai.clientws[wsname].open = 0;
2857
- _optionalChain([$asai, 'access', _343 => _343.hostconfig, 'access', _344 => _344.logger, 'optionalAccess', _345 => _345.lv, 'optionalAccess', _346 => _346.view]) && console.error(
2946
+ _optionalChain([$asai, 'access', _354 => _354.hostconfig, 'access', _355 => _355.logger, 'optionalAccess', _356 => _356.lv, 'optionalAccess', _357 => _357.view]) && console.error(
2858
2947
  666.2203,
2859
2948
  `${wsname}=${$asai.command.commandconfig.clientws[wsname]} is error.`,
2860
2949
  err
@@ -2863,19 +2952,19 @@ var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($a
2863
2952
  });
2864
2953
  $asai.clientws[wsname].socket.on("close", () => {
2865
2954
  $asai.clientws[wsname].open = 0;
2866
- _optionalChain([$asai, 'access', _347 => _347.hostconfig, 'access', _348 => _348.logger, 'optionalAccess', _349 => _349.lv, 'optionalAccess', _350 => _350.view]) && console.error(
2955
+ _optionalChain([$asai, 'access', _358 => _358.hostconfig, 'access', _359 => _359.logger, 'optionalAccess', _360 => _360.lv, 'optionalAccess', _361 => _361.view]) && console.error(
2867
2956
  666.2205,
2868
2957
  `${wsname}=${$asai.command.commandconfig.clientws[wsname]} is close.`
2869
2958
  );
2870
2959
  reject();
2871
2960
  });
2872
2961
  $asai.clientws[wsname].socket.onopen = () => {
2873
- _optionalChain([$asai, 'access', _351 => _351.hostconfig, 'access', _352 => _352.logger, 'optionalAccess', _353 => _353.lv, 'optionalAccess', _354 => _354.view]) && console.log(
2962
+ _optionalChain([$asai, 'access', _362 => _362.hostconfig, 'access', _363 => _363.logger, 'optionalAccess', _364 => _364.lv, 'optionalAccess', _365 => _365.view]) && console.log(
2874
2963
  666.2201,
2875
2964
  `${wsname}=${$asai.command.commandconfig.clientws[wsname]} is open.`
2876
2965
  );
2877
2966
  $asai.clientws[wsname].open = 1;
2878
- resolve7();
2967
+ resolve6();
2879
2968
  };
2880
2969
  });
2881
2970
  }
@@ -2893,7 +2982,7 @@ var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($a
2893
2982
  const key = getKeyByData(messageData);
2894
2983
  const task = $asai.clientws[wsname].tasks.get(key);
2895
2984
  if (task) {
2896
- _optionalChain([task, 'optionalAccess', _355 => _355.callback, 'call', _356 => _356(messageData)]);
2985
+ _optionalChain([task, 'optionalAccess', _366 => _366.callback, 'call', _367 => _367(messageData)]);
2897
2986
  if (messageData.ty && !messageData.id) {
2898
2987
  } else {
2899
2988
  $asai.clientws[wsname].tasks.delete(key);
@@ -2905,7 +2994,7 @@ var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($a
2905
2994
  }
2906
2995
  _chunkSMVZ3ZDJcjs.__name.call(void 0, clientwsOnmessage, "clientwsOnmessage");
2907
2996
  function clientwsApi(messageData) {
2908
- return new Promise((resolve7, reject) => {
2997
+ return new Promise((resolve6, reject) => {
2909
2998
  if ($asai.clientws[wsname].open) {
2910
2999
  try {
2911
3000
  const taskOpt = {};
@@ -2917,7 +3006,7 @@ var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($a
2917
3006
  getKeyByData(messageData),
2918
3007
  {
2919
3008
  callback: /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (res) => {
2920
- resolve7(res);
3009
+ resolve6(res);
2921
3010
  }, "callback"),
2922
3011
  ...messageData,
2923
3012
  ...taskOpt
@@ -2947,7 +3036,7 @@ var WsClient_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($a
2947
3036
  }
2948
3037
  _chunkSMVZ3ZDJcjs.__name.call(void 0, clientwsWatch, "clientwsWatch");
2949
3038
  function clientwsWatchOff(messageData) {
2950
- if (_optionalChain([messageData, 'optionalAccess', _357 => _357.ty]) === "clear") {
3039
+ if (_optionalChain([messageData, 'optionalAccess', _368 => _368.ty]) === "clear") {
2951
3040
  $asai.clientws[wsname].tasks = /* @__PURE__ */ new Map();
2952
3041
  } else {
2953
3042
  const key = getKeyByData(messageData);
@@ -2988,7 +3077,7 @@ var ping_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai)
2988
3077
  var web_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
2989
3078
  function chatBoard(msgdata, ws2, hostdir, req) {
2990
3079
  let room;
2991
- if (_optionalChain([msgdata, 'access', _358 => _358.db, 'optionalAccess', _359 => _359.room]) && typeof msgdata.db.room === "string") {
3080
+ if (_optionalChain([msgdata, 'access', _369 => _369.db, 'optionalAccess', _370 => _370.room]) && typeof msgdata.db.room === "string") {
2992
3081
  room = msgdata.db.room;
2993
3082
  delete msgdata.db.room;
2994
3083
  } else {
@@ -3045,26 +3134,26 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3045
3134
  removeFile: removeFile2,
3046
3135
  resolvePathUnderBase: resolvePathUnderBase2
3047
3136
  } = $asai.$lib.AsFs;
3048
- const { sendSuccess, sendFail, mnLog } = _optionalChain([$asai, 'access', _360 => _360.$lib, 'optionalAccess', _361 => _361.reqWork, 'optionalCall', _362 => _362($asai)]);
3137
+ const { sendSuccess, sendFail, mnLog } = _optionalChain([$asai, 'access', _371 => _371.$lib, 'optionalAccess', _372 => _372.reqWork, 'optionalCall', _373 => _373($asai)]);
3049
3138
  function mgLog(...arg) {
3050
3139
  mnLog("LOG", ...arg);
3051
3140
  }
3052
3141
  _chunkSMVZ3ZDJcjs.__name.call(void 0, mgLog, "mgLog");
3053
3142
  function getDir(opt) {
3054
- let tmpDir = _optionalChain([opt, 'access', _363 => _363.qrdata, 'optionalAccess', _364 => _364.dir]) || _optionalChain([opt, 'access', _365 => _365.data, 'optionalAccess', _366 => _366.dir]);
3143
+ let tmpDir = _optionalChain([opt, 'access', _374 => _374.qrdata, 'optionalAccess', _375 => _375.dir]) || _optionalChain([opt, 'access', _376 => _376.data, 'optionalAccess', _377 => _377.dir]);
3055
3144
  if (tmpDir) {
3056
3145
  tmpDir = decodeURIComponent(tmpDir);
3057
3146
  } else {
3058
- tmpDir = _optionalChain([opt, 'access', _367 => _367.qrdata, 'optionalAccess', _368 => _368.ty]) || _optionalChain([opt, 'access', _369 => _369.data, 'optionalAccess', _370 => _370.ty]);
3147
+ tmpDir = _optionalChain([opt, 'access', _378 => _378.qrdata, 'optionalAccess', _379 => _379.ty]) || _optionalChain([opt, 'access', _380 => _380.data, 'optionalAccess', _381 => _381.ty]);
3059
3148
  if (tmpDir) {
3060
3149
  tmpDir = decodeURIComponent(tmpDir);
3061
3150
  if (tmpDir === "access-clf" || tmpDir === "access-w3c") {
3062
- tmpDir = _optionalChain([$asai, 'access', _371 => _371.hostconfig, 'access', _372 => _372.logger, 'optionalAccess', _373 => _373.path, 'optionalAccess', _374 => _374.access]) || "";
3151
+ tmpDir = _optionalChain([$asai, 'access', _382 => _382.hostconfig, 'access', _383 => _383.logger, 'optionalAccess', _384 => _384.path, 'optionalAccess', _385 => _385.access]) || "";
3063
3152
  } else {
3064
- tmpDir = _optionalChain([$asai, 'access', _375 => _375.hostconfig, 'access', _376 => _376.logger, 'optionalAccess', _377 => _377.path, 'optionalAccess', _378 => _378[tmpDir]]) || "";
3153
+ tmpDir = _optionalChain([$asai, 'access', _386 => _386.hostconfig, 'access', _387 => _387.logger, 'optionalAccess', _388 => _388.path, 'optionalAccess', _389 => _389[tmpDir]]) || "";
3065
3154
  }
3066
3155
  } else {
3067
- tmpDir = _optionalChain([$asai, 'access', _379 => _379.hostconfig, 'access', _380 => _380.logger, 'optionalAccess', _381 => _381.path, 'optionalAccess', _382 => _382.client]) || "";
3156
+ tmpDir = _optionalChain([$asai, 'access', _390 => _390.hostconfig, 'access', _391 => _391.logger, 'optionalAccess', _392 => _392.path, 'optionalAccess', _393 => _393.client]) || "";
3068
3157
  }
3069
3158
  }
3070
3159
  return tmpDir;
@@ -3082,7 +3171,7 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3082
3171
  return;
3083
3172
  }
3084
3173
  if (url.startsWith("/api/asailog/manage/add/")) {
3085
- if (!await ensureLv(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3174
+ if (!await ensureLv(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3086
3175
  try {
3087
3176
  mgLog("add", "server:", opt.data);
3088
3177
  await $asai.$log("LOG", "ADD", opt.data);
@@ -3096,7 +3185,7 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3096
3185
  if (!await ensureLv(req, $asai, 3)) return sendFail(res, "Forbidden", opt);
3097
3186
  try {
3098
3187
  const baseDir = getDir(opt);
3099
- const relPath = decodeURIComponent(_optionalChain([opt, 'access', _383 => _383.qrdata, 'optionalAccess', _384 => _384.path]) || _optionalChain([opt, 'access', _385 => _385.data, 'optionalAccess', _386 => _386.path]));
3188
+ const relPath = decodeURIComponent(_optionalChain([opt, 'access', _394 => _394.qrdata, 'optionalAccess', _395 => _395.path]) || _optionalChain([opt, 'access', _396 => _396.data, 'optionalAccess', _397 => _397.path]));
3100
3189
  const jsonpath = resolvePathUnderBase2(baseDir, relPath);
3101
3190
  await ensureFile2(jsonpath);
3102
3191
  mgLog("ENSURE", jsonpath);
@@ -3115,13 +3204,13 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3115
3204
  async function get(req, res, hostdir, opt) {
3116
3205
  const url = req.url;
3117
3206
  if (url.startsWith("/api/asailog/manage/selectlist/")) {
3118
- if (!await ensureLv(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3207
+ if (!await ensureLv(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3119
3208
  try {
3120
- const ty = decodeURIComponent(_optionalChain([opt, 'access', _387 => _387.qrdata, 'optionalAccess', _388 => _388.ty]) || _optionalChain([opt, 'access', _389 => _389.data, 'optionalAccess', _390 => _390.ty]) || "client");
3121
- if (!_chunkVLMM735Qcjs.prefersDiskLogAccess.call(void 0, $asai) && _chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai) && (ty === "client" || ty === "server" || ty === "sec")) {
3209
+ const ty = decodeURIComponent(_optionalChain([opt, 'access', _398 => _398.qrdata, 'optionalAccess', _399 => _399.ty]) || _optionalChain([opt, 'access', _400 => _400.data, 'optionalAccess', _401 => _401.ty]) || "client");
3210
+ if (!_chunkTKJAHTPOcjs.prefersDiskLogAccess.call(void 0, $asai) && _chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai) && (ty === "client" || ty === "server" || ty === "sec")) {
3122
3211
  const kind = ty === "sec" ? "sec" : "web";
3123
- const groups = await _chunkVLMM735Qcjs.listUnifiedGroups.call(void 0, $asai, { kind, source: ty === "sec" ? "sec" : ty });
3124
- const children = _chunkVLMM735Qcjs.groupsToManageChildren.call(void 0, groups);
3212
+ const groups = await _chunkTKJAHTPOcjs.listUnifiedGroups.call(void 0, $asai, { kind, source: ty === "sec" ? "sec" : ty });
3213
+ const children = _chunkTKJAHTPOcjs.groupsToManageChildren.call(void 0, groups);
3125
3214
  if (children.length) {
3126
3215
  mgLog("LIST", `store:${ty}`, children.length);
3127
3216
  return sendSuccess(res, { children, fromStore: true }, opt);
@@ -3143,12 +3232,12 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3143
3232
  return;
3144
3233
  }
3145
3234
  if (url.startsWith("/api/asailog/manage/select/")) {
3146
- if (!await ensureLv(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3235
+ if (!await ensureLv(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3147
3236
  try {
3148
- const ty = decodeURIComponent(_optionalChain([opt, 'access', _391 => _391.qrdata, 'optionalAccess', _392 => _392.ty]) || _optionalChain([opt, 'access', _393 => _393.data, 'optionalAccess', _394 => _394.ty]) || "client");
3149
- const relPath = decodeURIComponent(_optionalChain([opt, 'access', _395 => _395.qrdata, 'optionalAccess', _396 => _396.path]) || _optionalChain([opt, 'access', _397 => _397.data, 'optionalAccess', _398 => _398.path]));
3150
- if (!_chunkVLMM735Qcjs.prefersDiskLogAccess.call(void 0, $asai) && _chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai) && (ty === "client" || ty === "server" || ty === "sec")) {
3151
- const data2 = await _chunkVLMM735Qcjs.readWebLogFromStore.call(void 0, $asai, ty, relPath);
3237
+ const ty = decodeURIComponent(_optionalChain([opt, 'access', _402 => _402.qrdata, 'optionalAccess', _403 => _403.ty]) || _optionalChain([opt, 'access', _404 => _404.data, 'optionalAccess', _405 => _405.ty]) || "client");
3238
+ const relPath = decodeURIComponent(_optionalChain([opt, 'access', _406 => _406.qrdata, 'optionalAccess', _407 => _407.path]) || _optionalChain([opt, 'access', _408 => _408.data, 'optionalAccess', _409 => _409.path]));
3239
+ if (!_chunkTKJAHTPOcjs.prefersDiskLogAccess.call(void 0, $asai) && _chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai) && (ty === "client" || ty === "server" || ty === "sec")) {
3240
+ const data2 = await _chunkTKJAHTPOcjs.readWebLogFromStore.call(void 0, $asai, ty, relPath);
3152
3241
  if (data2) {
3153
3242
  mgLog("READ", `store:${ty}/${relPath}`);
3154
3243
  return sendSuccess(res, data2, opt);
@@ -3174,10 +3263,10 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3174
3263
  if (!await ensureLv(req, $asai, 3)) return sendFail(res, "Forbidden", opt);
3175
3264
  try {
3176
3265
  const baseDir = getDir(opt);
3177
- const relPath = decodeURIComponent(_optionalChain([opt, 'access', _399 => _399.qrdata, 'optionalAccess', _400 => _400.path]) || _optionalChain([opt, 'access', _401 => _401.data, 'optionalAccess', _402 => _402.path]));
3266
+ const relPath = decodeURIComponent(_optionalChain([opt, 'access', _410 => _410.qrdata, 'optionalAccess', _411 => _411.path]) || _optionalChain([opt, 'access', _412 => _412.data, 'optionalAccess', _413 => _413.path]));
3178
3267
  const fileName = relPath.split(/[/\\]/).pop() || relPath;
3179
- if (_chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai)) {
3180
- await _chunkVLMM735Qcjs.purgeStoreEntriesForFile.call(void 0, $asai, fileName).catch(() => void 0);
3268
+ if (_chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai)) {
3269
+ await _chunkTKJAHTPOcjs.purgeStoreEntriesForFile.call(void 0, $asai, fileName).catch(() => void 0);
3181
3270
  }
3182
3271
  const filepath = resolvePathUnderBase2(baseDir, relPath);
3183
3272
  mgLog("DELETE", filepath);
@@ -3197,14 +3286,14 @@ var logmanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($
3197
3286
 
3198
3287
  // src/infra/siem-auth.ts
3199
3288
  function isSiemEnabled($asai) {
3200
- const cfg = _optionalChain([$asai, 'optionalAccess', _403 => _403.hostconfig, 'optionalAccess', _404 => _404.logger, 'optionalAccess', _405 => _405.siem]);
3201
- return !!(_optionalChain([cfg, 'optionalAccess', _406 => _406.enabled]) && getSiemToken($asai));
3289
+ const cfg = _optionalChain([$asai, 'optionalAccess', _414 => _414.hostconfig, 'optionalAccess', _415 => _415.logger, 'optionalAccess', _416 => _416.siem]);
3290
+ return !!(_optionalChain([cfg, 'optionalAccess', _417 => _417.enabled]) && getSiemToken($asai));
3202
3291
  }
3203
3292
  _chunkSMVZ3ZDJcjs.__name.call(void 0, isSiemEnabled, "isSiemEnabled");
3204
3293
  function getSiemToken($asai) {
3205
3294
  const fromEnv = process.env.ASAI_SIEM_TOKEN;
3206
3295
  if (typeof fromEnv === "string" && fromEnv.trim()) return fromEnv.trim();
3207
- const fromCfg = _optionalChain([$asai, 'optionalAccess', _407 => _407.hostconfig, 'optionalAccess', _408 => _408.logger, 'optionalAccess', _409 => _409.siem, 'optionalAccess', _410 => _410.token]);
3296
+ const fromCfg = _optionalChain([$asai, 'optionalAccess', _418 => _418.hostconfig, 'optionalAccess', _419 => _419.logger, 'optionalAccess', _420 => _420.siem, 'optionalAccess', _421 => _421.token]);
3208
3297
  return typeof fromCfg === "string" ? fromCfg.trim() : "";
3209
3298
  }
3210
3299
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getSiemToken, "getSiemToken");
@@ -3212,9 +3301,9 @@ function isSiemTokenValid($asai, req) {
3212
3301
  if (!isSiemEnabled($asai)) return false;
3213
3302
  const expected = getSiemToken($asai);
3214
3303
  if (!expected) return false;
3215
- const header = _optionalChain([req, 'optionalAccess', _411 => _411.headers, 'optionalAccess', _412 => _412["x-siem-token"]]) || _optionalChain([req, 'optionalAccess', _413 => _413.headers, 'optionalAccess', _414 => _414["x-api-key"]]);
3304
+ const header = _optionalChain([req, 'optionalAccess', _422 => _422.headers, 'optionalAccess', _423 => _423["x-siem-token"]]) || _optionalChain([req, 'optionalAccess', _424 => _424.headers, 'optionalAccess', _425 => _425["x-api-key"]]);
3216
3305
  if (typeof header === "string" && header === expected) return true;
3217
- const q = _optionalChain([req, 'optionalAccess', _415 => _415.query]) || {};
3306
+ const q = _optionalChain([req, 'optionalAccess', _426 => _426.query]) || {};
3218
3307
  const qToken = q.siem_token || q.token;
3219
3308
  return typeof qToken === "string" && qToken === expected;
3220
3309
  }
@@ -3238,24 +3327,24 @@ function getNs(raw) {
3238
3327
  }
3239
3328
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getNs, "getNs");
3240
3329
  async function ensureServerUser(req, $asai) {
3241
- if (Array.isArray(_optionalChain([req, 'optionalAccess', _416 => _416.Userinfo])) && req.Userinfo[0]) {
3330
+ if (Array.isArray(_optionalChain([req, 'optionalAccess', _427 => _427.Userinfo])) && req.Userinfo[0]) {
3242
3331
  await attachServerUserLevel(req, $asai);
3243
3332
  }
3244
3333
  }
3245
3334
  _chunkSMVZ3ZDJcjs.__name.call(void 0, ensureServerUser, "ensureServerUser");
3246
3335
  var interventionlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
3247
- const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _417 => _417.$lib, 'optionalAccess', _418 => _418.reqWork, 'optionalCall', _419 => _419($asai)]) || {};
3336
+ const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _428 => _428.$lib, 'optionalAccess', _429 => _429.reqWork, 'optionalCall', _430 => _430($asai)]) || {};
3248
3337
  const IL = $asai.$lib.InterventionLog;
3249
3338
  async function get(req, res, hostdir, opt) {
3250
3339
  const url = req.url || "";
3251
3340
  if (url.startsWith("/api/asailog/intervention/selectlist/")) {
3252
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3341
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3253
3342
  try {
3254
- const ns = getNs(_optionalChain([opt, 'access', _420 => _420.qrdata, 'optionalAccess', _421 => _421.ns]) || _optionalChain([opt, 'access', _422 => _422.data, 'optionalAccess', _423 => _423.ns]));
3343
+ const ns = getNs(_optionalChain([opt, 'access', _431 => _431.qrdata, 'optionalAccess', _432 => _432.ns]) || _optionalChain([opt, 'access', _433 => _433.data, 'optionalAccess', _434 => _434.ns]));
3255
3344
  let list = await IL.listInterventionFiles($asai, ns);
3256
- if (_chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai) && !_chunkVLMM735Qcjs.prefersDiskLogAccess.call(void 0, $asai)) {
3257
- const groups = await _chunkVLMM735Qcjs.listUnifiedGroups.call(void 0, $asai, { kind: "intervention", ns });
3258
- const fromStore = _chunkVLMM735Qcjs.groupsToInterventionFiles.call(void 0, groups, ns);
3345
+ if (_chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai) && !_chunkTKJAHTPOcjs.prefersDiskLogAccess.call(void 0, $asai)) {
3346
+ const groups = await _chunkTKJAHTPOcjs.listUnifiedGroups.call(void 0, $asai, { kind: "intervention", ns });
3347
+ const fromStore = _chunkTKJAHTPOcjs.groupsToInterventionFiles.call(void 0, groups, ns);
3259
3348
  const names = new Set(list.map((f) => f.name));
3260
3349
  for (const f of fromStore) {
3261
3350
  if (!names.has(f.name)) list.push(f);
@@ -3263,27 +3352,27 @@ var interventionlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void
3263
3352
  }
3264
3353
  return sendSuccess(res, { ns, files: list }, opt);
3265
3354
  } catch (err) {
3266
- return sendFail(res, _optionalChain([err, 'optionalAccess', _424 => _424.message]) || err, opt);
3355
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _435 => _435.message]) || err, opt);
3267
3356
  }
3268
3357
  }
3269
3358
  if (url.startsWith("/api/asailog/intervention/select/")) {
3270
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3359
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3271
3360
  try {
3272
- const name = decodeURIComponent(_optionalChain([opt, 'access', _425 => _425.qrdata, 'optionalAccess', _426 => _426.name]) || _optionalChain([opt, 'access', _427 => _427.data, 'optionalAccess', _428 => _428.name]) || "");
3273
- const ns = getNs(_optionalChain([opt, 'access', _429 => _429.qrdata, 'optionalAccess', _430 => _430.ns]) || _optionalChain([opt, 'access', _431 => _431.data, 'optionalAccess', _432 => _432.ns]));
3361
+ const name = decodeURIComponent(_optionalChain([opt, 'access', _436 => _436.qrdata, 'optionalAccess', _437 => _437.name]) || _optionalChain([opt, 'access', _438 => _438.data, 'optionalAccess', _439 => _439.name]) || "");
3362
+ const ns = getNs(_optionalChain([opt, 'access', _440 => _440.qrdata, 'optionalAccess', _441 => _441.ns]) || _optionalChain([opt, 'access', _442 => _442.data, 'optionalAccess', _443 => _443.ns]));
3274
3363
  if (!name) return sendFail(res, "name required", opt);
3275
3364
  const content = await IL.readInterventionFile($asai, name, ns);
3276
3365
  return sendSuccess(res, { ns, ...content }, opt);
3277
3366
  } catch (err) {
3278
- return sendFail(res, _optionalChain([err, 'optionalAccess', _433 => _433.message]) || err, opt);
3367
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _444 => _444.message]) || err, opt);
3279
3368
  }
3280
3369
  }
3281
3370
  if (url.startsWith("/api/asailog/intervention/types/")) {
3282
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3371
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3283
3372
  try {
3284
3373
  return sendSuccess(res, IL.getInterventionTaxonomy($asai), opt);
3285
3374
  } catch (err) {
3286
- return sendFail(res, _optionalChain([err, 'optionalAccess', _434 => _434.message]) || err, opt);
3375
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _445 => _445.message]) || err, opt);
3287
3376
  }
3288
3377
  }
3289
3378
  }
@@ -3291,7 +3380,7 @@ var interventionlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void
3291
3380
  async function post(req, res, hostdir, opt) {
3292
3381
  const url = req.url || "";
3293
3382
  if (url.startsWith("/api/asailog/intervention/delete/")) {
3294
- if (!await ensureLogWriteAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) return sendFail(res, "Forbidden", opt);
3383
+ if (!await ensureLogWriteAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) return sendFail(res, "Forbidden", opt);
3295
3384
  await ensureServerUser(req, $asai);
3296
3385
  const lv = getRequestUserLevel(req);
3297
3386
  const us = getRequestUsername(req);
@@ -3313,7 +3402,7 @@ var interventionlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void
3313
3402
  );
3314
3403
  return sendSuccess(res, { ns, ...result }, opt);
3315
3404
  } catch (err) {
3316
- return sendFail(res, _optionalChain([err, 'optionalAccess', _435 => _435.message]) || err, opt);
3405
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _446 => _446.message]) || err, opt);
3317
3406
  }
3318
3407
  }
3319
3408
  }
@@ -3332,11 +3421,11 @@ function parseQuery(opt) {
3332
3421
  }
3333
3422
  _chunkSMVZ3ZDJcjs.__name.call(void 0, parseQuery, "parseQuery");
3334
3423
  function parseBody(opt) {
3335
- if (!_optionalChain([opt, 'optionalAccess', _436 => _436.data])) return {};
3424
+ if (!_optionalChain([opt, 'optionalAccess', _447 => _447.data])) return {};
3336
3425
  if (typeof opt.data === "string") {
3337
3426
  try {
3338
3427
  return JSON.parse(opt.data);
3339
- } catch (e33) {
3428
+ } catch (e37) {
3340
3429
  return {};
3341
3430
  }
3342
3431
  }
@@ -3344,47 +3433,47 @@ function parseBody(opt) {
3344
3433
  }
3345
3434
  _chunkSMVZ3ZDJcjs.__name.call(void 0, parseBody, "parseBody");
3346
3435
  var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
3347
- const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _437 => _437.$lib, 'optionalAccess', _438 => _438.reqWork, 'optionalCall', _439 => _439($asai)]) || {};
3436
+ const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _448 => _448.$lib, 'optionalAccess', _449 => _449.reqWork, 'optionalCall', _450 => _450($asai)]) || {};
3348
3437
  const IL = $asai.$lib.InterventionLog;
3349
3438
  async function get(req, res, hostdir, opt) {
3350
3439
  const url = req.url || "";
3351
3440
  const q = parseQuery(opt);
3352
3441
  if (url.startsWith("/api/asailog/store/config/")) {
3353
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3442
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3354
3443
  try {
3355
- return sendSuccess(res, _chunkVLMM735Qcjs.getLogStoreMeta.call(void 0, $asai), opt);
3444
+ return sendSuccess(res, _chunkTKJAHTPOcjs.getLogStoreMeta.call(void 0, $asai), opt);
3356
3445
  } catch (err) {
3357
- return sendFail(res, _optionalChain([err, 'optionalAccess', _440 => _440.message]) || err, opt);
3446
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _451 => _451.message]) || err, opt);
3358
3447
  }
3359
3448
  }
3360
3449
  if (url.startsWith("/api/asailog/store/stats/")) {
3361
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3362
- if (!_chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai)) {
3363
- return sendSuccess(res, { store: "disabled", message: "logger.store not configured", config: _chunkVLMM735Qcjs.getLogStoreMeta.call(void 0, $asai) }, opt);
3450
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3451
+ if (!_chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai)) {
3452
+ return sendSuccess(res, { store: "disabled", message: "logger.store not configured", config: _chunkTKJAHTPOcjs.getLogStoreMeta.call(void 0, $asai) }, opt);
3364
3453
  }
3365
3454
  try {
3366
- const storeType = _chunkVLMM735Qcjs.getEffectiveStoreType.call(void 0, $asai);
3367
- const stats = await _chunkVLMM735Qcjs.getUnifiedStats.call(void 0, $asai);
3368
- return sendSuccess(res, { store: storeType, stats, config: _chunkVLMM735Qcjs.getLogStoreMeta.call(void 0, $asai) }, opt);
3455
+ const storeType = _chunkTKJAHTPOcjs.getEffectiveStoreType.call(void 0, $asai);
3456
+ const stats = await _chunkTKJAHTPOcjs.getUnifiedStats.call(void 0, $asai);
3457
+ return sendSuccess(res, { store: storeType, stats, config: _chunkTKJAHTPOcjs.getLogStoreMeta.call(void 0, $asai) }, opt);
3369
3458
  } catch (err) {
3370
- return sendFail(res, _optionalChain([err, 'optionalAccess', _441 => _441.message]) || err, opt);
3459
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _452 => _452.message]) || err, opt);
3371
3460
  }
3372
3461
  }
3373
3462
  if (url.startsWith("/api/asailog/store/compliance/")) {
3374
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3463
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3375
3464
  try {
3376
3465
  const ns = q.ns === "test" ? "test" : "prod";
3377
- const report = await _chunkVLMM735Qcjs.getComplianceReport.call(void 0, $asai, ns);
3466
+ const report = await _chunkTKJAHTPOcjs.getComplianceReport.call(void 0, $asai, ns);
3378
3467
  return sendSuccess(res, report, opt);
3379
3468
  } catch (err) {
3380
- return sendFail(res, _optionalChain([err, 'optionalAccess', _442 => _442.message]) || err, opt);
3469
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _453 => _453.message]) || err, opt);
3381
3470
  }
3382
3471
  }
3383
3472
  if (url.startsWith("/api/asailog/store/search/")) {
3384
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3385
- if (!_chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai)) return sendFail(res, "Log store not enabled", opt);
3473
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3474
+ if (!_chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai)) return sendFail(res, "Log store not enabled", opt);
3386
3475
  try {
3387
- const result = await _chunkVLMM735Qcjs.searchUnifiedLogs.call(void 0, $asai, {
3476
+ const result = await _chunkTKJAHTPOcjs.searchUnifiedLogs.call(void 0, $asai, {
3388
3477
  kind: q.kind ? q.kind : void 0,
3389
3478
  ns: q.ns ? q.ns : void 0,
3390
3479
  source: q.source || q.ty || void 0,
@@ -3399,11 +3488,11 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3399
3488
  });
3400
3489
  return sendSuccess(res, result, opt);
3401
3490
  } catch (err) {
3402
- return sendFail(res, _optionalChain([err, 'optionalAccess', _443 => _443.message]) || err, opt);
3491
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _454 => _454.message]) || err, opt);
3403
3492
  }
3404
3493
  }
3405
3494
  if (url.startsWith("/api/asailog/store/export/")) {
3406
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3495
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3407
3496
  try {
3408
3497
  const kind = q.kind || "intervention";
3409
3498
  const format = q.format || "raw";
@@ -3411,7 +3500,7 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3411
3500
  const ns = q.ns === "test" ? "test" : "prod";
3412
3501
  const source = q.source || q.ty || "server";
3413
3502
  if (!fileName && kind === "intervention") return sendFail(res, "name required", opt);
3414
- const payload = await _chunkVLMM735Qcjs.exportLogContent.call(void 0, $asai, {
3503
+ const payload = await _chunkTKJAHTPOcjs.exportLogContent.call(void 0, $asai, {
3415
3504
  kind,
3416
3505
  ns: kind === "intervention" ? ns : void 0,
3417
3506
  fileName: fileName || void 0,
@@ -3420,36 +3509,36 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3420
3509
  });
3421
3510
  return sendSuccess(res, payload, opt);
3422
3511
  } catch (err) {
3423
- return sendFail(res, _optionalChain([err, 'optionalAccess', _444 => _444.message]) || err, opt);
3512
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _455 => _455.message]) || err, opt);
3424
3513
  }
3425
3514
  }
3426
3515
  if (url.startsWith("/api/asailog/store/taxonomy/")) {
3427
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3516
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3428
3517
  try {
3429
3518
  return sendSuccess(res, IL.getInterventionTaxonomy($asai), opt);
3430
3519
  } catch (err) {
3431
- return sendFail(res, _optionalChain([err, 'optionalAccess', _445 => _445.message]) || err, opt);
3520
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _456 => _456.message]) || err, opt);
3432
3521
  }
3433
3522
  }
3434
3523
  if (url.startsWith("/api/asailog/store/formats/")) {
3435
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3524
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3436
3525
  try {
3437
- const { getLogFormatTaxonomy } = await Promise.resolve().then(() => _interopRequireWildcard(require("./log-formats-FKFMQKNO.cjs")));
3526
+ const { getLogFormatTaxonomy } = await Promise.resolve().then(() => _interopRequireWildcard(require("./log-formats-TUXGMCCU.cjs")));
3438
3527
  return sendSuccess(res, getLogFormatTaxonomy($asai), opt);
3439
3528
  } catch (err) {
3440
- return sendFail(res, _optionalChain([err, 'optionalAccess', _446 => _446.message]) || err, opt);
3529
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _457 => _457.message]) || err, opt);
3441
3530
  }
3442
3531
  }
3443
3532
  if (url.startsWith("/api/asailog/store/selectlist/")) {
3444
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3445
- if (!_chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai)) return sendFail(res, "Log store not enabled", opt);
3533
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3534
+ if (!_chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai)) return sendFail(res, "Log store not enabled", opt);
3446
3535
  try {
3447
3536
  const kind = q.kind ? String(q.kind) : void 0;
3448
3537
  const ns = q.ns ? String(q.ns) : void 0;
3449
3538
  const source = q.source || q.ty ? String(q.source || q.ty) : void 0;
3450
- const groups = await _chunkVLMM735Qcjs.listUnifiedGroups.call(void 0, $asai, { kind, ns, source });
3539
+ const groups = await _chunkTKJAHTPOcjs.listUnifiedGroups.call(void 0, $asai, { kind, ns, source });
3451
3540
  if (kind === "intervention" || ns) {
3452
- return sendSuccess(res, { files: _chunkVLMM735Qcjs.groupsToInterventionFiles.call(void 0, groups, ns || "prod"), ns: ns || "prod" }, opt);
3541
+ return sendSuccess(res, { files: _chunkTKJAHTPOcjs.groupsToInterventionFiles.call(void 0, groups, ns || "prod"), ns: ns || "prod" }, opt);
3453
3542
  }
3454
3543
  if (kind === "web" || kind === "sec" || kind === "access" || source) {
3455
3544
  const children = kind === "access" ? groups.filter((g) => g.kind === "access").map((g) => ({
@@ -3459,21 +3548,21 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3459
3548
  entryCount: g.entryCount,
3460
3549
  source: g.source,
3461
3550
  fromStore: true
3462
- })) : _chunkVLMM735Qcjs.groupsToManageChildren.call(void 0, groups);
3551
+ })) : _chunkTKJAHTPOcjs.groupsToManageChildren.call(void 0, groups);
3463
3552
  return sendSuccess(res, { children, source }, opt);
3464
3553
  }
3465
3554
  return sendSuccess(res, { groups }, opt);
3466
3555
  } catch (err) {
3467
- return sendFail(res, _optionalChain([err, 'optionalAccess', _447 => _447.message]) || err, opt);
3556
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _458 => _458.message]) || err, opt);
3468
3557
  }
3469
3558
  }
3470
3559
  if (url.startsWith("/api/asailog/store/select/")) {
3471
- if (!await ensureLogReadAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3472
- if (!_chunkVLMM735Qcjs.isLogStoreEnabled.call(void 0, $asai)) return sendFail(res, "Log store not enabled", opt);
3560
+ if (!await ensureLogReadAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "logRead"))) return sendFail(res, "Forbidden", opt);
3561
+ if (!_chunkTKJAHTPOcjs.isLogStoreEnabled.call(void 0, $asai)) return sendFail(res, "Log store not enabled", opt);
3473
3562
  try {
3474
3563
  const id = q.id;
3475
3564
  if (id != null) {
3476
- const row = await _chunkVLMM735Qcjs.getUnifiedEntry.call(void 0, $asai, id);
3565
+ const row = await _chunkTKJAHTPOcjs.getUnifiedEntry.call(void 0, $asai, id);
3477
3566
  if (!row) return sendFail(res, "not found", opt);
3478
3567
  return sendSuccess(res, { entry: row }, opt);
3479
3568
  }
@@ -3482,14 +3571,14 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3482
3571
  const ns = q.ns ? String(q.ns) : "";
3483
3572
  const source = q.source || q.ty ? String(q.source || q.ty) : "server";
3484
3573
  if (kind === "web" || kind === "sec" || !kind && fileName.startsWith("log-")) {
3485
- const content = await _chunkVLMM735Qcjs.readWebLogFromStore.call(void 0, $asai, source, fileName);
3574
+ const content = await _chunkTKJAHTPOcjs.readWebLogFromStore.call(void 0, $asai, source, fileName);
3486
3575
  return sendSuccess(res, content, opt);
3487
3576
  }
3488
3577
  if (kind === "intervention" || fileName.includes(".cef.log")) {
3489
3578
  const content = await IL.readInterventionFile($asai, fileName, ns === "test" ? "test" : "prod");
3490
3579
  return sendSuccess(res, { ns: ns || "prod", ...content, fromStore: true }, opt);
3491
3580
  }
3492
- const rows = await _chunkVLMM735Qcjs.queryUnifiedLogs.call(void 0, $asai, {
3581
+ const rows = await _chunkTKJAHTPOcjs.queryUnifiedLogs.call(void 0, $asai, {
3493
3582
  kind,
3494
3583
  ns,
3495
3584
  source,
@@ -3498,7 +3587,7 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3498
3587
  });
3499
3588
  return sendSuccess(res, { entries: rows }, opt);
3500
3589
  } catch (err) {
3501
- return sendFail(res, _optionalChain([err, 'optionalAccess', _448 => _448.message]) || err, opt);
3590
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _459 => _459.message]) || err, opt);
3502
3591
  }
3503
3592
  }
3504
3593
  }
@@ -3506,13 +3595,13 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3506
3595
  async function post(req, res, hostdir, opt) {
3507
3596
  const url = req.url || "";
3508
3597
  if (!url.startsWith("/api/asailog/store/archive/")) return;
3509
- if (!await ensureLogWriteAccess(req, $asai, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) return sendFail(res, "Forbidden", opt);
3598
+ if (!await ensureLogWriteAccess(req, $asai, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) return sendFail(res, "Forbidden", opt);
3510
3599
  try {
3511
3600
  const body = parseBody(opt);
3512
3601
  const year = Number(body.year);
3513
3602
  if (!year || year < 2e3 || year > 2100) return sendFail(res, "invalid year", opt);
3514
3603
  const ns = body.ns === "test" ? "test" : "prod";
3515
- const result = await _chunkVLMM735Qcjs.archiveInterventionYear.call(void 0, $asai, {
3604
+ const result = await _chunkTKJAHTPOcjs.archiveInterventionYear.call(void 0, $asai, {
3516
3605
  year,
3517
3606
  ns,
3518
3607
  dryRun: !!body.dryRun,
@@ -3520,7 +3609,7 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3520
3609
  });
3521
3610
  return sendSuccess(res, result, opt);
3522
3611
  } catch (err) {
3523
- return sendFail(res, _optionalChain([err, 'optionalAccess', _449 => _449.message]) || err, opt);
3612
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _460 => _460.message]) || err, opt);
3524
3613
  }
3525
3614
  }
3526
3615
  _chunkSMVZ3ZDJcjs.__name.call(void 0, post, "post");
@@ -3532,7 +3621,7 @@ var unifiedlog_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3532
3621
 
3533
3622
  var registry = null;
3534
3623
  function resolveFilePath($asai) {
3535
- const root = _optionalChain([$asai, 'optionalAccess', _450 => _450.serverRoot]) || process.cwd();
3624
+ const root = _optionalChain([$asai, 'optionalAccess', _461 => _461.serverRoot]) || process.cwd();
3536
3625
  return nodePath3.join(root, "websys/sys/errorcodes.json");
3537
3626
  }
3538
3627
  _chunkSMVZ3ZDJcjs.__name.call(void 0, resolveFilePath, "resolveFilePath");
@@ -3542,7 +3631,7 @@ function loadErrorCodes($asai) {
3542
3631
  try {
3543
3632
  const raw = fs8.readFileSync(filePath, "utf8");
3544
3633
  registry = JSON.parse(raw);
3545
- } catch (e34) {
3634
+ } catch (e38) {
3546
3635
  registry = { version: "0", errors: {} };
3547
3636
  }
3548
3637
  if ($asai) $asai.errorcodes = registry;
@@ -3550,7 +3639,7 @@ function loadErrorCodes($asai) {
3550
3639
  }
3551
3640
  _chunkSMVZ3ZDJcjs.__name.call(void 0, loadErrorCodes, "loadErrorCodes");
3552
3641
  function getError(ec) {
3553
- return _optionalChain([registry, 'optionalAccess', _451 => _451.errors, 'optionalAccess', _452 => _452[ec]]) || null;
3642
+ return _optionalChain([registry, 'optionalAccess', _462 => _462.errors, 'optionalAccess', _463 => _463[ec]]) || null;
3554
3643
  }
3555
3644
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getError, "getError");
3556
3645
  function hasError(ec) {
@@ -3559,11 +3648,11 @@ function hasError(ec) {
3559
3648
  _chunkSMVZ3ZDJcjs.__name.call(void 0, hasError, "hasError");
3560
3649
  function logError($asai, ec, params) {
3561
3650
  const entry = getError(ec);
3562
- const logFn = _optionalChain([$asai, 'optionalAccess', _453 => _453.$log]) || console.warn;
3651
+ const logFn = _optionalChain([$asai, 'optionalAccess', _464 => _464.$log]) || console.warn;
3563
3652
  if (entry) {
3564
- logFn(`[EC:${ec}]`, entry.id || "", entry.detail || "", _optionalChain([params, 'optionalAccess', _454 => _454.length]) ? params : "");
3653
+ logFn(`[EC:${ec}]`, entry.id || "", entry.detail || "", _optionalChain([params, 'optionalAccess', _465 => _465.length]) ? params : "");
3565
3654
  } else {
3566
- logFn(`[EC:${ec}]`, "(unregistered)", _optionalChain([params, 'optionalAccess', _455 => _455.length]) ? params : "");
3655
+ logFn(`[EC:${ec}]`, "(unregistered)", _optionalChain([params, 'optionalAccess', _466 => _466.length]) ? params : "");
3567
3656
  }
3568
3657
  }
3569
3658
  _chunkSMVZ3ZDJcjs.__name.call(void 0, logError, "logError");
@@ -3591,14 +3680,14 @@ var ErrorCode_default = {
3591
3680
 
3592
3681
  // src/sysserver/api/common/errorcodes.ts
3593
3682
  var errorcodes_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
3594
- const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _456 => _456.$lib, 'optionalAccess', _457 => _457.reqWork, 'optionalCall', _458 => _458($asai)]) || {};
3683
+ const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _467 => _467.$lib, 'optionalAccess', _468 => _468.reqWork, 'optionalCall', _469 => _469($asai)]) || {};
3595
3684
  function get(req, res, _hostdir, opt) {
3596
3685
  const url = req.url || "";
3597
3686
  if (url.startsWith("/api/sys/errorcodes/")) {
3598
3687
  try {
3599
3688
  return sendSuccess(res, loadErrorCodes($asai), opt);
3600
3689
  } catch (err) {
3601
- return sendFail(res, _optionalChain([err, 'optionalAccess', _459 => _459.message]) || err, opt);
3690
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _470 => _470.message]) || err, opt);
3602
3691
  }
3603
3692
  }
3604
3693
  }
@@ -3608,9 +3697,9 @@ var errorcodes_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (
3608
3697
 
3609
3698
  // src/sysserver/api/common/sqlitemanage.ts
3610
3699
  var sqlitemanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
3611
- const { sendSuccess, sendFail, mnLog } = _optionalChain([$asai, 'optionalAccess', _460 => _460.$lib, 'optionalAccess', _461 => _461.reqWork, 'optionalCall', _462 => _462($asai)]) || {};
3700
+ const { sendSuccess, sendFail, mnLog } = _optionalChain([$asai, 'optionalAccess', _471 => _471.$lib, 'optionalAccess', _472 => _472.reqWork, 'optionalCall', _473 => _473($asai)]) || {};
3612
3701
  function mgLog(...arg) {
3613
- _optionalChain([mnLog, 'optionalCall', _463 => _463("SQLite", ...arg)]);
3702
+ _optionalChain([mnLog, 'optionalCall', _474 => _474("SQLite", ...arg)]);
3614
3703
  }
3615
3704
  _chunkSMVZ3ZDJcjs.__name.call(void 0, mgLog, "mgLog");
3616
3705
  return $asai.$lib.AsDb($asai, {
@@ -3628,7 +3717,7 @@ var sqlitemanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0,
3628
3717
  if (req.url.startsWith("/api/asaisqlite/manage/post")) {
3629
3718
  try {
3630
3719
  mgLog("POST", "custom handler triggered");
3631
- _optionalChain([sendSuccess, 'optionalCall', _464 => _464(res, { data: "post" }, opt)]);
3720
+ _optionalChain([sendSuccess, 'optionalCall', _475 => _475(res, { data: "post" }, opt)]);
3632
3721
  } catch (err) {
3633
3722
  mgLog("ERROR", "post handler", err);
3634
3723
  }
@@ -3645,10 +3734,10 @@ var sqlitemanage_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0,
3645
3734
  table: dataObj.table
3646
3735
  });
3647
3736
  mgLog("SELECT", "completed");
3648
- _optionalChain([sendSuccess, 'optionalCall', _465 => _465(res, resdb, opt)]);
3737
+ _optionalChain([sendSuccess, 'optionalCall', _476 => _476(res, resdb, opt)]);
3649
3738
  } catch (errdb) {
3650
3739
  mgLog("ERROR", "select", errdb);
3651
- _optionalChain([sendFail, 'optionalCall', _466 => _466(res, errdb, opt)]);
3740
+ _optionalChain([sendFail, 'optionalCall', _477 => _477(res, errdb, opt)]);
3652
3741
  }
3653
3742
  return "ok";
3654
3743
  }
@@ -3664,7 +3753,7 @@ function promLine(name, value, labels) {
3664
3753
  }
3665
3754
  _chunkSMVZ3ZDJcjs.__name.call(void 0, promLine, "promLine");
3666
3755
  var health_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
3667
- const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _467 => _467.$lib, 'optionalAccess', _468 => _468.reqWork, 'optionalCall', _469 => _469($asai)]) || {};
3756
+ const { sendSuccess, sendFail } = _optionalChain([$asai, 'access', _478 => _478.$lib, 'optionalAccess', _479 => _479.reqWork, 'optionalCall', _480 => _480($asai)]) || {};
3668
3757
  async function get(req, res, _hostdir, opt) {
3669
3758
  const url = req.url || "";
3670
3759
  if (url.startsWith("/api/sys/health/metrics/")) {
@@ -3673,10 +3762,10 @@ var health_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asa
3673
3762
  let httpTotal = 0;
3674
3763
  let wsTotal = 0;
3675
3764
  for (const set of Object.values($asai.connectionshttp || {})) {
3676
- httpTotal += _optionalChain([set, 'optionalAccess', _470 => _470.size]) || 0;
3765
+ httpTotal += _optionalChain([set, 'optionalAccess', _481 => _481.size]) || 0;
3677
3766
  }
3678
3767
  for (const set of Object.values($asai.connectionsws || {})) {
3679
- wsTotal += _optionalChain([set, 'optionalAccess', _471 => _471.size]) || 0;
3768
+ wsTotal += _optionalChain([set, 'optionalAccess', _482 => _482.size]) || 0;
3680
3769
  }
3681
3770
  const lines = [
3682
3771
  "# HELP asai_uptime_seconds Process uptime",
@@ -3698,7 +3787,7 @@ var health_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asa
3698
3787
  res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
3699
3788
  return res.end(lines.join("\n") + "\n");
3700
3789
  } catch (err) {
3701
- return sendFail(res, _optionalChain([err, 'optionalAccess', _472 => _472.message]) || err, opt);
3790
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _483 => _483.message]) || err, opt);
3702
3791
  }
3703
3792
  }
3704
3793
  if (url.startsWith("/api/sys/health/status/")) {
@@ -3711,10 +3800,10 @@ var health_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asa
3711
3800
  memory: process.memoryUsage(),
3712
3801
  quota: {
3713
3802
  http: Object.fromEntries(
3714
- Object.entries($asai.connectionshttp || {}).map(([k, v]) => [k, _optionalChain([v, 'optionalAccess', _473 => _473.size]) || 0])
3803
+ Object.entries($asai.connectionshttp || {}).map(([k, v]) => [k, _optionalChain([v, 'optionalAccess', _484 => _484.size]) || 0])
3715
3804
  ),
3716
3805
  ws: Object.fromEntries(
3717
- Object.entries($asai.connectionsws || {}).map(([k, v]) => [k, _optionalChain([v, 'optionalAccess', _474 => _474.size]) || 0])
3806
+ Object.entries($asai.connectionsws || {}).map(([k, v]) => [k, _optionalChain([v, 'optionalAccess', _485 => _485.size]) || 0])
3718
3807
  )
3719
3808
  }
3720
3809
  },
@@ -3755,7 +3844,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, sanitizeString, "sanitizeString");
3755
3844
  // src/sysserver/api/login/service/session.ts
3756
3845
 
3757
3846
  function getSessionTtlMs($asai) {
3758
- const hours = _nullishCoalesce(_optionalChain([$asai, 'optionalAccess', _475 => _475.hostconfig, 'optionalAccess', _476 => _476.security, 'optionalAccess', _477 => _477.sessionTtlHours]), () => ( 24));
3847
+ const hours = _nullishCoalesce(_optionalChain([$asai, 'optionalAccess', _486 => _486.hostconfig, 'optionalAccess', _487 => _487.security, 'optionalAccess', _488 => _488.sessionTtlHours]), () => ( 24));
3759
3848
  return Number(hours) * 3600 * 1e3;
3760
3849
  }
3761
3850
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getSessionTtlMs, "getSessionTtlMs");
@@ -3772,7 +3861,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, generatePriKey, "generatePriKey");
3772
3861
  function createSessionKeys($asai) {
3773
3862
  const sessionId = _crypto.randomUUID.call(void 0, );
3774
3863
  const pri = generatePriKey();
3775
- const sn = _optionalChain([$asai, 'optionalAccess', _478 => _478.hostconfig, 'optionalAccess', _479 => _479.asaisn]);
3864
+ const sn = _optionalChain([$asai, 'optionalAccess', _489 => _489.hostconfig, 'optionalAccess', _490 => _490.asaisn]);
3776
3865
  if (!sn) throw new Error("[session] ASAI_ASAISN \u672A\u914D\u7F6E");
3777
3866
  const pub = $asai.$lib.AsCode.asencode(pri, sn);
3778
3867
  return { pri, pub, sessionId };
@@ -3798,10 +3887,10 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, buildSessionRecord, "buildSessionRecord");
3798
3887
  var API_ADMIN_PREFIXES = ["/api/user/login/admin/"];
3799
3888
  function getMinLevelForApiPath(pathname, $asai) {
3800
3889
  if (API_ADMIN_PREFIXES.some((p) => pathname.startsWith(p))) {
3801
- if (pathname.includes("/admin/update") || pathname.includes("/admin/kick") || pathname.includes("/admin/delete")) {
3802
- return $asai ? _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite") : _chunkQWVR2HNTcjs.USER_LV.DEVELOPER;
3890
+ if (pathname.includes("/admin/update") || pathname.includes("/admin/kick") || pathname.includes("/admin/delete") || pathname.includes("/admin/resetpass")) {
3891
+ return $asai ? _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite") : _chunkLXJMGLKWcjs.USER_LV.DEVELOPER;
3803
3892
  }
3804
- return $asai ? _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminRead") : _chunkQWVR2HNTcjs.USER_LV.ADMIN;
3893
+ return $asai ? _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminRead") : _chunkLXJMGLKWcjs.USER_LV.ADMIN;
3805
3894
  }
3806
3895
  return 0;
3807
3896
  }
@@ -3811,21 +3900,100 @@ function hasLevel(userLevel, required) {
3811
3900
  }
3812
3901
  _chunkSMVZ3ZDJcjs.__name.call(void 0, hasLevel, "hasLevel");
3813
3902
 
3814
- // src/sysserver/api/login/index.ts
3815
- function parseBody2(opt) {
3816
- if (!_optionalChain([opt, 'optionalAccess', _480 => _480.data])) return {};
3817
- if (typeof opt.data === "string") {
3903
+ // src/sysserver/api/login/service/request-body.ts
3904
+ function isAesEnvelope(body) {
3905
+ return typeof body.data === "string" && typeof body.iv === "string" && typeof body.auth === "string" && body.aes != null && body.us == null && body.pass == null && body.password == null;
3906
+ }
3907
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, isAesEnvelope, "isAesEnvelope");
3908
+ function unwrapJsonString(value) {
3909
+ if (typeof value !== "string") return value;
3910
+ const text = value.trim();
3911
+ if (!text.startsWith("{") && !text.startsWith("[")) return value;
3912
+ try {
3913
+ return JSON.parse(text);
3914
+ } catch (e39) {
3915
+ return value;
3916
+ }
3917
+ }
3918
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, unwrapJsonString, "unwrapJsonString");
3919
+ function parseAuthBody(opt) {
3920
+ let raw = _optionalChain([opt, 'optionalAccess', _491 => _491.data]);
3921
+ if (raw == null || raw === "") return {};
3922
+ if (typeof raw === "string") {
3923
+ const text = raw.trim();
3924
+ if (!text) return {};
3818
3925
  try {
3819
- return JSON.parse(opt.data);
3820
- } catch (e35) {
3821
- return {};
3926
+ raw = JSON.parse(text);
3927
+ } catch (e40) {
3928
+ if (text.includes("=") && !text.startsWith("{") && !text.startsWith("[")) {
3929
+ raw = Object.fromEntries(new URLSearchParams(text));
3930
+ } else {
3931
+ return {};
3932
+ }
3822
3933
  }
3934
+ raw = unwrapJsonString(raw);
3823
3935
  }
3824
- return typeof opt.data === "object" ? opt.data : {};
3936
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
3937
+ const body = raw;
3938
+ if (isAesEnvelope(body)) return {};
3939
+ return body;
3940
+ }
3941
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, parseAuthBody, "parseAuthBody");
3942
+ function pickAuthField(body, ...keys) {
3943
+ for (const key of keys) {
3944
+ const val = body[key];
3945
+ if (val != null && String(val).length > 0) return String(val);
3946
+ }
3947
+ return "";
3948
+ }
3949
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, pickAuthField, "pickAuthField");
3950
+
3951
+ // src/sysserver/api/login/service/online-sessions.ts
3952
+ function resolveOnlineSessions($asai, hostdir, allSessions) {
3953
+ const onlineUsers = new Set(listOnlineWsUsers($asai, hostdir));
3954
+ if (!onlineUsers.size) return [];
3955
+ const byUser = /* @__PURE__ */ new Map();
3956
+ for (const s of allSessions) {
3957
+ if (!onlineUsers.has(s.us)) continue;
3958
+ const prev = byUser.get(s.us);
3959
+ const sTime = _nullishCoalesce(s.lastActivityAt, () => ( s.createdAt));
3960
+ const prevTime = prev ? _nullishCoalesce(prev.lastActivityAt, () => ( prev.createdAt)) : 0;
3961
+ if (!prev || sTime > prevTime) byUser.set(s.us, s);
3962
+ }
3963
+ return [...byUser.values()].sort((a, b) => b.createdAt - a.createdAt);
3964
+ }
3965
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, resolveOnlineSessions, "resolveOnlineSessions");
3966
+ function isSessionUserOnline($asai, us, hostdir) {
3967
+ if (!us) return false;
3968
+ return isUserOnlineOnWs($asai, us, hostdir);
3969
+ }
3970
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, isSessionUserOnline, "isSessionUserOnline");
3971
+ async function countOnlineSessions($asai, hostdir, store) {
3972
+ const all = await store.getSessions();
3973
+ return resolveOnlineSessions($asai, hostdir, all).length;
3974
+ }
3975
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, countOnlineSessions, "countOnlineSessions");
3976
+ async function countOnlineSessionsByUser($asai, hostdir, store, us) {
3977
+ const all = await store.getSessions();
3978
+ return resolveOnlineSessions($asai, hostdir, all).filter((s) => s.us === us).length;
3825
3979
  }
3826
- _chunkSMVZ3ZDJcjs.__name.call(void 0, parseBody2, "parseBody");
3980
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, countOnlineSessionsByUser, "countOnlineSessionsByUser");
3981
+ async function purgeOfflineSessions($asai, hostdir, store) {
3982
+ const onlineUsers = new Set(listOnlineWsUsers($asai, hostdir));
3983
+ const all = await store.getSessions();
3984
+ let purged = 0;
3985
+ for (const s of all) {
3986
+ if (onlineUsers.has(s.us)) continue;
3987
+ await store.removeSession(s.id);
3988
+ purged += 1;
3989
+ }
3990
+ return purged;
3991
+ }
3992
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, purgeOfflineSessions, "purgeOfflineSessions");
3993
+
3994
+ // src/sysserver/api/login/index.ts
3827
3995
  function getSecurity($asai) {
3828
- return _optionalChain([$asai, 'optionalAccess', _481 => _481.hostconfig, 'optionalAccess', _482 => _482.security]) || {};
3996
+ return _optionalChain([$asai, 'optionalAccess', _492 => _492.hostconfig, 'optionalAccess', _493 => _493.security]) || {};
3829
3997
  }
3830
3998
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getSecurity, "getSecurity");
3831
3999
  function getQuota2($asai) {
@@ -3833,16 +4001,16 @@ function getQuota2($asai) {
3833
4001
  return sec.quota || {};
3834
4002
  }
3835
4003
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getQuota2, "getQuota");
3836
- async function canLogin($asai, us) {
4004
+ async function canLogin($asai, us, hostdir) {
3837
4005
  const quota = getQuota2($asai);
3838
4006
  if (!quota.enabled) return { ok: true };
3839
- const store = _chunkQWVR2HNTcjs.createUserStore.call(void 0, $asai);
3840
- const total = await store.countSessions();
3841
- const maxLogin = _nullishCoalesce(_nullishCoalesce(quota.maxLoginSessions, () => ( _optionalChain([$asai, 'optionalAccess', _483 => _483.hostconfig, 'optionalAccess', _484 => _484.hosts, 'optionalAccess', _485 => _485.default, 'optionalAccess', _486 => _486.maxonline]))), () => ( 100));
4007
+ const store = _chunkLXJMGLKWcjs.createUserStore.call(void 0, $asai);
4008
+ const total = await countOnlineSessions($asai, hostdir, store);
4009
+ const maxLogin = _nullishCoalesce(_nullishCoalesce(quota.maxLoginSessions, () => ( _optionalChain([$asai, 'optionalAccess', _494 => _494.hostconfig, 'optionalAccess', _495 => _495.hosts, 'optionalAccess', _496 => _496.default, 'optionalAccess', _497 => _497.maxonline]))), () => ( 100));
3842
4010
  if (total >= maxLogin) {
3843
4011
  return { ok: false, message: "LOGIN_QUOTA_FULL" };
3844
4012
  }
3845
- const perUser = await store.countSessionsByUser(us);
4013
+ const perUser = await countOnlineSessionsByUser($asai, hostdir, store, us);
3846
4014
  const maxPerUser = _nullishCoalesce(quota.maxSessionsPerUser, () => ( 3));
3847
4015
  if (perUser >= maxPerUser) {
3848
4016
  return { ok: false, message: "USER_SESSION_LIMIT" };
@@ -3851,7 +4019,7 @@ async function canLogin($asai, us) {
3851
4019
  }
3852
4020
  _chunkSMVZ3ZDJcjs.__name.call(void 0, canLogin, "canLogin");
3853
4021
  function publicUser($asai, user) {
3854
- const role = user.role || _chunkX7VHW2TDcjs.resolveRoleForLevel.call(void 0, $asai, user.lv).name;
4022
+ const role = user.role || _chunkH3K33HBAcjs.resolveRoleForLevel.call(void 0, $asai, user.lv).name;
3855
4023
  return {
3856
4024
  us: user.us,
3857
4025
  lv: user.lv,
@@ -3865,14 +4033,14 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, publicUser, "publicUser");
3865
4033
  var bootstrapPromise = null;
3866
4034
  function ensureReady($asai) {
3867
4035
  if (!bootstrapPromise) {
3868
- bootstrapPromise = Promise.all([_chunkQWVR2HNTcjs.ensureBootstrapAdmin.call(void 0, $asai), _chunkX7VHW2TDcjs.loadUserLevelConfig.call(void 0, $asai)]).then(() => void 0);
4036
+ bootstrapPromise = Promise.all([_chunkLXJMGLKWcjs.ensureBootstrapAdmin.call(void 0, $asai), _chunkH3K33HBAcjs.loadUserLevelConfig.call(void 0, $asai)]).then(() => void 0);
3869
4037
  }
3870
4038
  return bootstrapPromise;
3871
4039
  }
3872
4040
  _chunkSMVZ3ZDJcjs.__name.call(void 0, ensureReady, "ensureReady");
3873
4041
  var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
3874
- const { sendSuccess, sendFail, sendErr } = _optionalChain([$asai, 'access', _487 => _487.$lib, 'optionalAccess', _488 => _488.reqWork, 'optionalCall', _489 => _489($asai)]) || {};
3875
- const store = _chunkQWVR2HNTcjs.createUserStore.call(void 0, $asai);
4042
+ const { sendSuccess, sendFail, sendErr } = _optionalChain([$asai, 'access', _498 => _498.$lib, 'optionalAccess', _499 => _499.reqWork, 'optionalCall', _500 => _500($asai)]) || {};
4043
+ const store = _chunkLXJMGLKWcjs.createUserStore.call(void 0, $asai);
3876
4044
  async function checkAdmin(req, pathname, minOverride) {
3877
4045
  await attachServerUserLevel(req, $asai);
3878
4046
  const minLv = _nullishCoalesce(minOverride, () => ( getMinLevelForApiPath(pathname, $asai)));
@@ -3882,26 +4050,26 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
3882
4050
  async function post(req, res, hostdir, opt) {
3883
4051
  const url = req.url || "";
3884
4052
  const ip = getClientIp(req);
3885
- const body = parseBody2(opt);
4053
+ const body = parseAuthBody(opt);
3886
4054
  if (url.startsWith("/api/user/login/changepass/")) {
3887
4055
  await ensureReady($asai);
3888
4056
  try {
3889
- const us = sanitizeString(body.us, 64);
3890
- const pass = sanitizeString(body.pass, 128);
3891
- const newPass = sanitizeString(body.newPass, 128);
4057
+ const us = sanitizeString(pickAuthField(body, "us", "username"), 64);
4058
+ const pass = sanitizeString(pickAuthField(body, "pass", "password", "pwd"), 128);
4059
+ const newPass = sanitizeString(pickAuthField(body, "newPass", "newPassword", "newpass"), 128);
3892
4060
  if (!us || !pass || !newPass) return sendErr(res, "AUTH_CREDENTIALS_REQUIRED", void 0, opt);
3893
4061
  const user = await store.findByUsername(us);
3894
- if (!user || !_chunkKOFCBB3Ncjs.verifyPassword.call(void 0, pass, user.passHash, user.passSalt)) {
4062
+ if (!user || !_chunkK2QPSQEVcjs.verifyPassword.call(void 0, pass, user.passHash, user.passSalt)) {
3895
4063
  return sendErr(res, "AUTH_INVALID_CREDENTIALS", void 0, opt);
3896
4064
  }
3897
- const policy = _chunkX7VHW2TDcjs.getPasswordPolicy.call(void 0, $asai);
3898
- const policyErr = _chunkKOFCBB3Ncjs.validatePasswordChange.call(void 0, newPass, $asai, user.passHistory);
4065
+ const policy = _chunkH3K33HBAcjs.getPasswordPolicy.call(void 0, $asai);
4066
+ const policyErr = _chunkK2QPSQEVcjs.validatePasswordChange.call(void 0, newPass, $asai, user.passHistory);
3899
4067
  if (policyErr === "PASSWORD_TOO_SHORT") {
3900
4068
  return sendErr(res, policyErr, [String(policy.minLength)], opt);
3901
4069
  }
3902
4070
  if (policyErr) return sendErr(res, policyErr, void 0, opt);
3903
- const { passHash, passSalt } = _chunkKOFCBB3Ncjs.hashPassword.call(void 0, newPass);
3904
- const passHistory = _chunkKOFCBB3Ncjs.nextPassHistory.call(void 0, pass, user.passHistory, policy.historyCount);
4071
+ const { passHash, passSalt } = _chunkK2QPSQEVcjs.hashPassword.call(void 0, newPass);
4072
+ const passHistory = _chunkK2QPSQEVcjs.nextPassHistory.call(void 0, pass, user.passHistory, policy.historyCount);
3905
4073
  await store.updateUser(us, {
3906
4074
  passHash,
3907
4075
  passSalt,
@@ -3912,7 +4080,7 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
3912
4080
  logSecurityEvent($asai, { type: "AUTH_FAIL", path: url, method: "POST", user: us, ip, detail: "password_changed" });
3913
4081
  return sendSuccess(res, { ok: true }, opt);
3914
4082
  } catch (err) {
3915
- return sendFail(res, _optionalChain([err, 'optionalAccess', _490 => _490.message]) || err, opt);
4083
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _501 => _501.message]) || err, opt);
3916
4084
  }
3917
4085
  }
3918
4086
  if (url.startsWith("/api/user/login/register/")) {
@@ -3922,15 +4090,17 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
3922
4090
  return sendErr(res, "AUTH_REG_DISABLED", void 0, opt);
3923
4091
  }
3924
4092
  try {
3925
- const us = sanitizeString(body.us, 64);
3926
- const pass = sanitizeString(body.pass, 128);
3927
- const email = body.email ? sanitizeString(body.email, 128) : void 0;
3928
- const policyErr = _chunkKOFCBB3Ncjs.validatePasswordChange.call(void 0, pass, $asai);
4093
+ const us = sanitizeString(pickAuthField(body, "us", "username"), 64);
4094
+ const pass = sanitizeString(pickAuthField(body, "pass", "password", "pwd"), 128);
4095
+ const emailRaw = pickAuthField(body, "email");
4096
+ const email = emailRaw ? sanitizeString(emailRaw, 128) : void 0;
4097
+ if (!us || !pass) return sendErr(res, "AUTH_CREDENTIALS_REQUIRED", void 0, opt);
4098
+ const policyErr = _chunkK2QPSQEVcjs.validatePasswordChange.call(void 0, pass, $asai);
3929
4099
  if (policyErr === "PASSWORD_TOO_SHORT") {
3930
- return sendErr(res, policyErr, [String(_chunkX7VHW2TDcjs.getPasswordPolicy.call(void 0, $asai).minLength)], opt);
4100
+ return sendErr(res, policyErr, [String(_chunkH3K33HBAcjs.getPasswordPolicy.call(void 0, $asai).minLength)], opt);
3931
4101
  }
3932
4102
  if (policyErr) return sendErr(res, policyErr, void 0, opt);
3933
- const { passHash, passSalt } = _chunkKOFCBB3Ncjs.hashPassword.call(void 0, pass);
4103
+ const { passHash, passSalt } = _chunkK2QPSQEVcjs.hashPassword.call(void 0, pass);
3934
4104
  const user = await store.createUser({
3935
4105
  us,
3936
4106
  email,
@@ -3943,21 +4113,21 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
3943
4113
  logSecurityEvent($asai, { type: "AUTH_FAIL", path: url, method: "POST", user: us, ip, detail: "register_ok" });
3944
4114
  return sendSuccess(res, { user: publicUser($asai, user) }, opt);
3945
4115
  } catch (err) {
3946
- const msg = _optionalChain([err, 'optionalAccess', _491 => _491.message]) || String(err);
4116
+ const msg = _optionalChain([err, 'optionalAccess', _502 => _502.message]) || String(err);
3947
4117
  if (msg.includes("exists") || msg.includes("\u5DF2\u5B58\u5728")) {
3948
4118
  return sendErr(res, "USER_ALREADY_EXISTS", void 0, opt);
3949
4119
  }
3950
- return sendFail(res, _optionalChain([err, 'optionalAccess', _492 => _492.message]) || err, opt);
4120
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _503 => _503.message]) || err, opt);
3951
4121
  }
3952
4122
  }
3953
4123
  if (url.startsWith("/api/user/login/auth/")) {
3954
4124
  await ensureReady($asai);
3955
4125
  try {
3956
- const us = sanitizeString(body.us, 64);
3957
- const pass = sanitizeString(body.pass, 128);
4126
+ const us = sanitizeString(pickAuthField(body, "us", "username"), 64);
4127
+ const pass = sanitizeString(pickAuthField(body, "pass", "password", "pwd"), 128);
3958
4128
  if (!us || !pass) return sendErr(res, "AUTH_CREDENTIALS_REQUIRED", void 0, opt);
3959
4129
  const user = await store.findByUsername(us);
3960
- if (!user || !_chunkKOFCBB3Ncjs.verifyPassword.call(void 0, pass, user.passHash, user.passSalt)) {
4130
+ if (!user || !_chunkK2QPSQEVcjs.verifyPassword.call(void 0, pass, user.passHash, user.passSalt)) {
3961
4131
  if (user) {
3962
4132
  const sec = getSecurity($asai);
3963
4133
  const lockoutMax = _nullishCoalesce(sec.lockoutMaxFails, () => ( 5));
@@ -3979,21 +4149,13 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
3979
4149
  if (user.status === "locked" && user.lockedUntil && user.lockedUntil > Date.now()) {
3980
4150
  return sendErr(res, "AUTH_ACCOUNT_LOCKED", void 0, opt);
3981
4151
  }
3982
- const policy = _chunkX7VHW2TDcjs.getPasswordPolicy.call(void 0, $asai);
3983
- const mustChange = !!user.mustChangePassword || _chunkX7VHW2TDcjs.isPasswordExpired.call(void 0, user.passwordChangedAt, policy.maxAgeDays);
3984
- const hostcfg = _optionalChain([$asai, 'access', _493 => _493.getHost, 'optionalCall', _494 => _494(hostdir)]) || {};
4152
+ const policy = _chunkH3K33HBAcjs.getPasswordPolicy.call(void 0, $asai);
4153
+ const mustChange = !!user.mustChangePassword || _chunkH3K33HBAcjs.isPasswordExpired.call(void 0, user.passwordChangedAt, policy.maxAgeDays);
4154
+ const hostcfg = _optionalChain([$asai, 'access', _504 => _504.getHost, 'optionalCall', _505 => _505(hostdir)]) || {};
3985
4155
  if (hostcfg.ckws && isUserOnlineOnWs($asai, us, hostdir)) {
3986
- logSecurityEvent($asai, {
3987
- type: "AUTH_FAIL",
3988
- path: url,
3989
- method: "POST",
3990
- user: us,
3991
- ip,
3992
- detail: "user_already_online"
3993
- });
3994
- return sendErr(res, "USER_ALREADY_LOGGED", void 0, opt);
4156
+ kickUserWs($asai, us, hostdir);
3995
4157
  }
3996
- const quotaCheck = await canLogin($asai, us);
4158
+ const quotaCheck = await canLogin($asai, us, hostdir);
3997
4159
  if (!quotaCheck.ok) {
3998
4160
  logSecurityEvent($asai, { type: "RATE_LIMIT", path: url, method: "POST", user: us, ip, detail: quotaCheck.message });
3999
4161
  return sendErr(res, quotaCheck.message || "LOGIN_QUOTA_FULL", void 0, opt);
@@ -4014,22 +4176,22 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4014
4176
  opt
4015
4177
  );
4016
4178
  } catch (err) {
4017
- return sendFail(res, _optionalChain([err, 'optionalAccess', _495 => _495.message]) || err, opt);
4179
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _506 => _506.message]) || err, opt);
4018
4180
  }
4019
4181
  }
4020
4182
  if (url.startsWith("/api/user/login/logout/")) {
4021
4183
  try {
4022
4184
  const bodySid = body.sessionId ? sanitizeString(body.sessionId, 64) : "";
4023
4185
  if (bodySid) await store.removeSession(bodySid);
4024
- const us = _optionalChain([req, 'optionalAccess', _496 => _496.Userinfo, 'optionalAccess', _497 => _497[0]]);
4186
+ const us = _optionalChain([req, 'optionalAccess', _507 => _507.Userinfo, 'optionalAccess', _508 => _508[0]]);
4025
4187
  if (us) logSecurityEvent($asai, { type: "AUTH_FAIL", path: url, method: "POST", user: String(us), ip, detail: "logout" });
4026
4188
  return sendSuccess(res, "ok", opt);
4027
4189
  } catch (err) {
4028
- return sendFail(res, _optionalChain([err, 'optionalAccess', _498 => _498.message]) || err, opt);
4190
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _509 => _509.message]) || err, opt);
4029
4191
  }
4030
4192
  }
4031
4193
  if (url.startsWith("/api/user/login/admin/kick/")) {
4032
- if (!await checkAdmin(req, url, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4194
+ if (!await checkAdmin(req, url, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4033
4195
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4034
4196
  }
4035
4197
  try {
@@ -4037,21 +4199,26 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4037
4199
  if (!sessionId) return sendErr(res, "AUTH_CREDENTIALS_REQUIRED", void 0, opt);
4038
4200
  const sessions = await store.getSessions();
4039
4201
  const target = sessions.find((s) => s.id === sessionId);
4202
+ if (!target) return sendErr(res, "AUTH_SESSION_NOT_FOUND", void 0, opt);
4203
+ if (!isSessionUserOnline($asai, target.us, hostdir)) {
4204
+ return sendErr(res, "SESSION_NOT_ONLINE", void 0, opt);
4205
+ }
4206
+ kickUserWs($asai, target.us, hostdir);
4040
4207
  await store.removeSession(sessionId);
4041
- const operator = String(_optionalChain([req, 'optionalAccess', _499 => _499.Userinfo, 'optionalAccess', _500 => _500[0]]) || "");
4042
- await _chunkNLBFIRDBcjs.logSessionTerminate.call(void 0, $asai, {
4208
+ const operator = String(_optionalChain([req, 'optionalAccess', _510 => _510.Userinfo, 'optionalAccess', _511 => _511[0]]) || "");
4209
+ await _chunkRIRKIYETcjs.logSessionTerminate.call(void 0, $asai, {
4043
4210
  operator,
4044
4211
  sessionId,
4045
- targetUs: _optionalChain([target, 'optionalAccess', _501 => _501.us]),
4212
+ targetUs: target.us,
4046
4213
  ip
4047
4214
  });
4048
4215
  return sendSuccess(res, { ok: true }, opt);
4049
4216
  } catch (err) {
4050
- return sendFail(res, _optionalChain([err, 'optionalAccess', _502 => _502.message]) || err, opt);
4217
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _512 => _512.message]) || err, opt);
4051
4218
  }
4052
4219
  }
4053
4220
  if (url.startsWith("/api/user/login/admin/delete/")) {
4054
- if (!await checkAdmin(req, url, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4221
+ if (!await checkAdmin(req, url, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4055
4222
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4056
4223
  }
4057
4224
  try {
@@ -4059,36 +4226,93 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4059
4226
  if (!targetUs || targetUs === "admin") return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4060
4227
  const ok = await store.deleteUser(targetUs);
4061
4228
  if (!ok) return sendErr(res, "AUTH_USER_NOT_FOUND", void 0, opt);
4062
- const operator = String(_optionalChain([req, 'optionalAccess', _503 => _503.Userinfo, 'optionalAccess', _504 => _504[0]]) || "");
4063
- await _chunkNLBFIRDBcjs.logAccountPurge.call(void 0, $asai, { operator, targetUs, ip });
4229
+ const operator = String(_optionalChain([req, 'optionalAccess', _513 => _513.Userinfo, 'optionalAccess', _514 => _514[0]]) || "");
4230
+ await _chunkRIRKIYETcjs.logAccountPurge.call(void 0, $asai, { operator, targetUs, ip });
4064
4231
  return sendSuccess(res, { ok: true }, opt);
4065
4232
  } catch (err) {
4066
- return sendFail(res, _optionalChain([err, 'optionalAccess', _505 => _505.message]) || err, opt);
4233
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _515 => _515.message]) || err, opt);
4067
4234
  }
4068
4235
  }
4069
4236
  if (url.startsWith("/api/user/login/admin/levels/")) {
4070
- if (!await checkAdmin(req, url, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4237
+ if (!await checkAdmin(req, url, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4071
4238
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4072
4239
  }
4073
4240
  try {
4074
4241
  const levels = Array.isArray(body.levels) ? body.levels : void 0;
4075
4242
  const thresholds = body.thresholds && typeof body.thresholds === "object" ? body.thresholds : void 0;
4076
4243
  const routeRights = Array.isArray(body.routeRights) ? body.routeRights : void 0;
4077
- const operator = String(_optionalChain([req, 'optionalAccess', _506 => _506.Userinfo, 'optionalAccess', _507 => _507[0]]) || "");
4078
- const cfg = await _chunkX7VHW2TDcjs.saveUserLevelConfig.call(void 0,
4244
+ const defaultResetPassword = typeof body.defaultResetPassword === "string" ? body.defaultResetPassword : void 0;
4245
+ const operator = String(_optionalChain([req, 'optionalAccess', _516 => _516.Userinfo, 'optionalAccess', _517 => _517[0]]) || "");
4246
+ const cfg = await _chunkH3K33HBAcjs.saveUserLevelConfig.call(void 0,
4079
4247
  $asai,
4080
- { levels, thresholds, routeRights },
4248
+ {
4249
+ levels,
4250
+ thresholds,
4251
+ routeRights,
4252
+ defaultResetPassword
4253
+ },
4081
4254
  operator
4082
4255
  );
4083
- await _chunkNLBFIRDBcjs.logSecurityConfigIntervention.call(void 0, $asai, {
4256
+ await _chunkRIRKIYETcjs.logSecurityConfigIntervention.call(void 0, $asai, {
4084
4257
  section: "user_levels",
4085
- detail: JSON.stringify({ levels: _optionalChain([levels, 'optionalAccess', _508 => _508.length]), thresholds: !!thresholds, routeRights: _optionalChain([routeRights, 'optionalAccess', _509 => _509.length]) }),
4258
+ detail: JSON.stringify({ levels: _optionalChain([levels, 'optionalAccess', _518 => _518.length]), thresholds: !!thresholds, routeRights: _optionalChain([routeRights, 'optionalAccess', _519 => _519.length]) }),
4086
4259
  operator,
4087
4260
  ip
4088
4261
  });
4089
4262
  return sendSuccess(res, cfg, opt);
4090
4263
  } catch (err) {
4091
- return sendFail(res, _optionalChain([err, 'optionalAccess', _510 => _510.message]) || err, opt);
4264
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _520 => _520.message]) || err, opt);
4265
+ }
4266
+ }
4267
+ if (url.startsWith("/api/user/login/admin/resetpass/")) {
4268
+ await ensureReady($asai);
4269
+ if (!await checkAdmin(req, url, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminWrite"))) {
4270
+ logSecurityEvent($asai, { type: "ACCESS_DENIED", path: url, method: "POST", ip });
4271
+ return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4272
+ }
4273
+ try {
4274
+ const targetUs = sanitizeString(body.us, 64);
4275
+ if (!targetUs) return sendErr(res, "AUTH_USER_NOT_FOUND", void 0, opt);
4276
+ let newPass = sanitizeString(pickAuthField(body, "newPass", "newPassword", "newpass"), 128);
4277
+ if (!newPass) newPass = _chunkH3K33HBAcjs.getDefaultResetPassword.call(void 0, $asai);
4278
+ const policy = _chunkH3K33HBAcjs.getPasswordPolicy.call(void 0, $asai);
4279
+ const policyErr = _chunkH3K33HBAcjs.validatePasswordWithPolicy.call(void 0, newPass, policy);
4280
+ if (policyErr === "PASSWORD_TOO_SHORT") {
4281
+ return sendErr(res, policyErr, [String(policy.minLength)], opt);
4282
+ }
4283
+ if (policyErr) return sendErr(res, policyErr, void 0, opt);
4284
+ const user = await store.findByUsername(targetUs);
4285
+ if (!user) return sendErr(res, "AUTH_USER_NOT_FOUND", void 0, opt);
4286
+ const { passHash, passSalt } = _chunkK2QPSQEVcjs.hashPassword.call(void 0, newPass);
4287
+ const updated = await store.updateUser(targetUs, {
4288
+ passHash,
4289
+ passSalt,
4290
+ mustChangePassword: 1,
4291
+ passwordChangedAt: Date.now(),
4292
+ failCount: 0,
4293
+ status: "active",
4294
+ lockedUntil: void 0,
4295
+ passHistory: "[]"
4296
+ });
4297
+ if (!updated) return sendErr(res, "AUTH_USER_NOT_FOUND", void 0, opt);
4298
+ const operator = String(_optionalChain([req, 'optionalAccess', _521 => _521.Userinfo, 'optionalAccess', _522 => _522[0]]) || "");
4299
+ await _chunkRIRKIYETcjs.logUserRbacChange.call(void 0, $asai, {
4300
+ operator,
4301
+ targetUs,
4302
+ patch: { resetPassword: true, mustChangePassword: 1 },
4303
+ ip
4304
+ });
4305
+ logSecurityEvent($asai, {
4306
+ type: "AUTH_FAIL",
4307
+ path: url,
4308
+ method: "POST",
4309
+ user: targetUs,
4310
+ ip,
4311
+ detail: "admin_password_reset"
4312
+ });
4313
+ return sendSuccess(res, { user: publicUser($asai, updated) }, opt);
4314
+ } catch (err) {
4315
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _523 => _523.message]) || err, opt);
4092
4316
  }
4093
4317
  }
4094
4318
  if (url.startsWith("/api/user/login/admin/update/")) {
@@ -4102,11 +4326,11 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4102
4326
  const patch = {};
4103
4327
  if (body.lv != null) {
4104
4328
  const newLv = Number(body.lv);
4105
- if (!Number.isFinite(newLv) || !_chunkX7VHW2TDcjs.isValidUserLv.call(void 0, $asai, newLv)) {
4329
+ if (!Number.isFinite(newLv) || !_chunkH3K33HBAcjs.isValidUserLv.call(void 0, $asai, newLv)) {
4106
4330
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4107
4331
  }
4108
4332
  patch.lv = newLv;
4109
- patch.role = _chunkX7VHW2TDcjs.resolveRoleForLevel.call(void 0, $asai, newLv).name;
4333
+ patch.role = _chunkH3K33HBAcjs.resolveRoleForLevel.call(void 0, $asai, newLv).name;
4110
4334
  }
4111
4335
  if (body.status) patch.status = sanitizeString(body.status, 16);
4112
4336
  if (body.resetLock) {
@@ -4118,8 +4342,8 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4118
4342
  const updated = await store.updateUser(targetUs, patch);
4119
4343
  if (!updated) return sendErr(res, "AUTH_USER_NOT_FOUND", void 0, opt);
4120
4344
  if (Object.keys(patch).length) {
4121
- await _chunkNLBFIRDBcjs.logUserRbacChange.call(void 0, $asai, {
4122
- operator: String(_optionalChain([req, 'optionalAccess', _511 => _511.Userinfo, 'optionalAccess', _512 => _512[0]]) || ""),
4345
+ await _chunkRIRKIYETcjs.logUserRbacChange.call(void 0, $asai, {
4346
+ operator: String(_optionalChain([req, 'optionalAccess', _524 => _524.Userinfo, 'optionalAccess', _525 => _525[0]]) || ""),
4123
4347
  targetUs,
4124
4348
  patch,
4125
4349
  ip
@@ -4127,32 +4351,33 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4127
4351
  }
4128
4352
  return sendSuccess(res, { user: publicUser($asai, updated) }, opt);
4129
4353
  } catch (err) {
4130
- return sendFail(res, _optionalChain([err, 'optionalAccess', _513 => _513.message]) || err, opt);
4354
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _526 => _526.message]) || err, opt);
4131
4355
  }
4132
4356
  }
4133
4357
  if (url.startsWith("/api/user/login/profile/")) {
4134
- const us = _optionalChain([req, 'optionalAccess', _514 => _514.Userinfo, 'optionalAccess', _515 => _515[0]]);
4358
+ const us = _optionalChain([req, 'optionalAccess', _527 => _527.Userinfo, 'optionalAccess', _528 => _528[0]]);
4135
4359
  if (!us) return sendErr(res, "AUTH_UNAUTHORIZED", void 0, opt);
4136
4360
  try {
4137
4361
  const user = await store.findByUsername(String(us));
4138
4362
  if (!user) return sendErr(res, "AUTH_USER_NOT_FOUND", void 0, opt);
4139
- if (body.newPass) {
4140
- const newPass = sanitizeString(body.newPass, 128);
4141
- const policy = _chunkX7VHW2TDcjs.getPasswordPolicy.call(void 0, $asai);
4142
- if (body.pass) {
4143
- if (!_chunkKOFCBB3Ncjs.verifyPassword.call(void 0, String(body.pass), user.passHash, user.passSalt)) {
4363
+ if (pickAuthField(body, "newPass", "newPassword", "newpass")) {
4364
+ const newPass = sanitizeString(pickAuthField(body, "newPass", "newPassword", "newpass"), 128);
4365
+ const policy = _chunkH3K33HBAcjs.getPasswordPolicy.call(void 0, $asai);
4366
+ const oldPass = pickAuthField(body, "pass", "password", "pwd");
4367
+ if (oldPass) {
4368
+ if (!_chunkK2QPSQEVcjs.verifyPassword.call(void 0, oldPass, user.passHash, user.passSalt)) {
4144
4369
  return sendErr(res, "AUTH_INVALID_PASSWORD", void 0, opt);
4145
4370
  }
4146
4371
  } else if (!user.mustChangePassword) {
4147
4372
  return sendErr(res, "AUTH_INVALID_PASSWORD", void 0, opt);
4148
4373
  }
4149
- const policyErr = _chunkKOFCBB3Ncjs.validatePasswordChange.call(void 0, newPass, $asai, user.passHistory);
4374
+ const policyErr = _chunkK2QPSQEVcjs.validatePasswordChange.call(void 0, newPass, $asai, user.passHistory);
4150
4375
  if (policyErr === "PASSWORD_TOO_SHORT") {
4151
4376
  return sendErr(res, policyErr, [String(policy.minLength)], opt);
4152
4377
  }
4153
4378
  if (policyErr) return sendErr(res, policyErr, void 0, opt);
4154
- const { passHash, passSalt } = _chunkKOFCBB3Ncjs.hashPassword.call(void 0, newPass);
4155
- const passHistory = _chunkKOFCBB3Ncjs.nextPassHistory.call(void 0, String(body.pass || newPass), user.passHistory, policy.historyCount);
4379
+ const { passHash, passSalt } = _chunkK2QPSQEVcjs.hashPassword.call(void 0, newPass);
4380
+ const passHistory = _chunkK2QPSQEVcjs.nextPassHistory.call(void 0, oldPass || newPass, user.passHistory, policy.historyCount);
4156
4381
  await store.updateUser(String(us), {
4157
4382
  passHash,
4158
4383
  passSalt,
@@ -4164,7 +4389,7 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4164
4389
  const fresh = await store.findByUsername(String(us));
4165
4390
  return sendSuccess(res, { user: fresh ? publicUser($asai, fresh) : null }, opt);
4166
4391
  } catch (err) {
4167
- return sendFail(res, _optionalChain([err, 'optionalAccess', _516 => _516.message]) || err, opt);
4392
+ return sendFail(res, _optionalChain([err, 'optionalAccess', _529 => _529.message]) || err, opt);
4168
4393
  }
4169
4394
  }
4170
4395
  }
@@ -4173,21 +4398,23 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4173
4398
  const url = req.url || "";
4174
4399
  const ip = getClientIp(req);
4175
4400
  if (url.startsWith("/api/user/login/config/")) {
4176
- const lang = String(_optionalChain([req, 'optionalAccess', _517 => _517.headers, 'optionalAccess', _518 => _518["accept-language"]]) || _optionalChain([opt, 'optionalAccess', _519 => _519.headers, 'optionalAccess', _520 => _520["accept-language"]]) || "zh-CN").split(",")[0];
4177
- return sendSuccess(res, _chunkX7VHW2TDcjs.getPublicSecurityConfig.call(void 0, $asai, lang), opt);
4401
+ const lang = String(_optionalChain([req, 'optionalAccess', _530 => _530.headers, 'optionalAccess', _531 => _531["accept-language"]]) || _optionalChain([opt, 'optionalAccess', _532 => _532.headers, 'optionalAccess', _533 => _533["accept-language"]]) || "zh-CN").split(",")[0];
4402
+ await _chunkH3K33HBAcjs.loadUserLevelConfig.call(void 0, $asai);
4403
+ return sendSuccess(res, _chunkH3K33HBAcjs.getPublicSecurityConfig.call(void 0, $asai, lang), opt);
4178
4404
  }
4179
4405
  if (url.startsWith("/api/user/login/admin/levels/")) {
4180
- if (!await checkAdmin(req, url, _chunkX7VHW2TDcjs.getPermissionThreshold.call(void 0, $asai, "adminRead"))) {
4406
+ if (!await checkAdmin(req, url, _chunkH3K33HBAcjs.getPermissionThreshold.call(void 0, $asai, "adminRead"))) {
4181
4407
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4182
4408
  }
4183
- await _chunkX7VHW2TDcjs.loadUserLevelConfig.call(void 0, $asai);
4184
- return sendSuccess(res, _chunkX7VHW2TDcjs.getUserLevelConfigSync.call(void 0, $asai), opt);
4409
+ await _chunkH3K33HBAcjs.loadUserLevelConfig.call(void 0, $asai);
4410
+ return sendSuccess(res, _chunkH3K33HBAcjs.getUserLevelConfigSync.call(void 0, $asai), opt);
4185
4411
  }
4186
4412
  if (url.startsWith("/api/user/login/admin/sessions/")) {
4187
4413
  if (!await checkAdmin(req, url)) {
4188
4414
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4189
4415
  }
4190
- const sessions = await store.getSessions();
4416
+ const allSessions = await store.getSessions();
4417
+ const sessions = resolveOnlineSessions($asai, hostdir, allSessions);
4191
4418
  return sendSuccess(
4192
4419
  res,
4193
4420
  {
@@ -4197,7 +4424,8 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4197
4424
  ip: s.ip,
4198
4425
  createdAt: s.createdAt,
4199
4426
  expiresAt: s.expiresAt,
4200
- lastActivityAt: s.lastActivityAt
4427
+ lastActivityAt: s.lastActivityAt,
4428
+ online: true
4201
4429
  }))
4202
4430
  },
4203
4431
  opt
@@ -4215,12 +4443,13 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4215
4443
  if (!await checkAdmin(req, url)) {
4216
4444
  return sendErr(res, "AUTH_FORBIDDEN", void 0, opt);
4217
4445
  }
4218
- const sessions = await store.getSessions();
4446
+ await purgeOfflineSessions($asai, hostdir, store);
4447
+ const onlineCount = await countOnlineSessions($asai, hostdir, store);
4219
4448
  const quota = getQuota2($asai);
4220
4449
  return sendSuccess(
4221
4450
  res,
4222
4451
  {
4223
- sessions: sessions.length,
4452
+ sessions: onlineCount,
4224
4453
  maxLoginSessions: _nullishCoalesce(quota.maxLoginSessions, () => ( 100)),
4225
4454
  quotaEnabled: !!quota.enabled,
4226
4455
  http: $asai.connectionshttp,
@@ -4230,7 +4459,7 @@ var login_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4230
4459
  );
4231
4460
  }
4232
4461
  if (url.startsWith("/api/user/login/profile/")) {
4233
- const us = _optionalChain([req, 'optionalAccess', _521 => _521.Userinfo, 'optionalAccess', _522 => _522[0]]);
4462
+ const us = _optionalChain([req, 'optionalAccess', _534 => _534.Userinfo, 'optionalAccess', _535 => _535[0]]);
4234
4463
  if (!us) return sendErr(res, "AUTH_UNAUTHORIZED", void 0, opt);
4235
4464
  const user = await store.findByUsername(String(us));
4236
4465
  return sendSuccess(res, { user: user ? publicUser($asai, user) : null }, opt);
@@ -4272,16 +4501,16 @@ var As_default = {
4272
4501
  return { code: 908, data: val };
4273
4502
  },
4274
4503
  ctxSuccess(val, opt = null) {
4275
- if (typeof _optionalChain([opt, 'optionalAccess', _523 => _523.resAES]) === "function") {
4504
+ if (typeof _optionalChain([opt, 'optionalAccess', _536 => _536.resAES]) === "function") {
4276
4505
  val = opt.resAES(val);
4277
4506
  }
4278
4507
  return { code: 909, data: val };
4279
4508
  },
4280
4509
  getPath(str = "-") {
4281
- return _optionalChain([str, 'optionalAccess', _524 => _524.replace, 'call', _525 => _525(/[^a-zA-Z0-9.\-_\\\/]/g, "")]);
4510
+ return _optionalChain([str, 'optionalAccess', _537 => _537.replace, 'call', _538 => _538(/[^a-zA-Z0-9.\-_\\\/]/g, "")]);
4282
4511
  },
4283
4512
  getName(str = "-") {
4284
- return _optionalChain([str, 'optionalAccess', _526 => _526.replace, 'call', _527 => _527(/[^a-zA-Z0-9.\-_]/g, "")]);
4513
+ return _optionalChain([str, 'optionalAccess', _539 => _539.replace, 'call', _540 => _540(/[^a-zA-Z0-9.\-_]/g, "")]);
4285
4514
  },
4286
4515
  toDirPath(relativePath) {
4287
4516
  const pathArr = relativePath.split("/");
@@ -4295,10 +4524,10 @@ var As_default = {
4295
4524
  return relativePath;
4296
4525
  },
4297
4526
  //创建多层文件夹 同步
4298
- ensureDir(fs13, relativePath) {
4527
+ ensureDir(fs12, relativePath) {
4299
4528
  const absPathDir = this.toDirPath(relativePath);
4300
4529
  const absPath = this.toAbsolutePath(relativePath);
4301
- if (!fs13.existsSync(absPath)) {
4530
+ if (!fs12.existsSync(absPath)) {
4302
4531
  let pathTmp = "";
4303
4532
  absPathDir.split("/").forEach((el) => {
4304
4533
  if (el) {
@@ -4306,8 +4535,8 @@ var As_default = {
4306
4535
  pathTmp += "/";
4307
4536
  }
4308
4537
  pathTmp += el;
4309
- if (!fs13.existsSync(pathTmp)) {
4310
- if (!fs13.mkdirSync(pathTmp, { recursive: true })) {
4538
+ if (!fs12.existsSync(pathTmp)) {
4539
+ if (!fs12.mkdirSync(pathTmp, { recursive: true })) {
4311
4540
  return absPath;
4312
4541
  }
4313
4542
  }
@@ -4316,11 +4545,11 @@ var As_default = {
4316
4545
  }
4317
4546
  return absPath;
4318
4547
  },
4319
- makeDir(fs13, filePaths) {
4320
- return new Promise((resolve7, reject) => {
4548
+ makeDir(fs12, filePaths) {
4549
+ return new Promise((resolve6, reject) => {
4321
4550
  try {
4322
- const newPath = this.ensureDir(fs13, filePaths);
4323
- resolve7(newPath);
4551
+ const newPath = this.ensureDir(fs12, filePaths);
4552
+ resolve6(newPath);
4324
4553
  } catch (err) {
4325
4554
  reject(err);
4326
4555
  }
@@ -4352,7 +4581,7 @@ var As_default = {
4352
4581
  // immediate: false,
4353
4582
  // });
4354
4583
  dtImmediate(fn, opt) {
4355
- if (_optionalChain([opt, 'optionalAccess', _528 => _528.immediate])) {
4584
+ if (_optionalChain([opt, 'optionalAccess', _541 => _541.immediate])) {
4356
4585
  fn();
4357
4586
  opt.immediate = false;
4358
4587
  }
@@ -4374,7 +4603,7 @@ var As_default = {
4374
4603
  if (opt.endtime - opt.starttime < opt.wait) {
4375
4604
  this.dtClearTimeout(opt);
4376
4605
  }
4377
- if (!_optionalChain([opt, 'optionalAccess', _529 => _529.timeout])) {
4606
+ if (!_optionalChain([opt, 'optionalAccess', _542 => _542.timeout])) {
4378
4607
  opt.starttime = opt.endtime;
4379
4608
  opt.timeout = this.dtSetTimeout(fn, opt);
4380
4609
  }
@@ -4382,7 +4611,7 @@ var As_default = {
4382
4611
  // 节流:指定长度时间内有多次触发,只fn最后一次触发
4383
4612
  throttle(fn, opt) {
4384
4613
  this.dtImmediate(fn, opt);
4385
- if (!_optionalChain([opt, 'optionalAccess', _530 => _530.timeout])) {
4614
+ if (!_optionalChain([opt, 'optionalAccess', _543 => _543.timeout])) {
4386
4615
  opt.timeout = this.dtSetTimeout(fn, opt);
4387
4616
  }
4388
4617
  },
@@ -4418,8 +4647,8 @@ var As_default = {
4418
4647
  var AsCode_default = {
4419
4648
  // 加密
4420
4649
  asencode(str, keys) {
4421
- const strlen = _optionalChain([str, 'optionalAccess', _531 => _531.length]) || 0;
4422
- const keyslen = _optionalChain([keys, 'optionalAccess', _532 => _532.length]) || 0;
4650
+ const strlen = _optionalChain([str, 'optionalAccess', _544 => _544.length]) || 0;
4651
+ const keyslen = _optionalChain([keys, 'optionalAccess', _545 => _545.length]) || 0;
4423
4652
  let newstr = "";
4424
4653
  for (let i = 0; i < strlen; i++) {
4425
4654
  const rnum = Math.round(Math.random() * 1e3) % keyslen;
@@ -4444,7 +4673,7 @@ var AsCode_default = {
4444
4673
  const rnum = keys.indexOf(str[i + 3]);
4445
4674
  const rnumx = Number(rnum.toString().slice(-1)) + 1;
4446
4675
  const ylen = keyslen - rnumx;
4447
- newstr += _optionalChain([String, 'optionalAccess', _533 => _533.fromCodePoint, 'call', _534 => _534(
4676
+ newstr += _optionalChain([String, 'optionalAccess', _546 => _546.fromCodePoint, 'call', _547 => _547(
4448
4677
  (keys.indexOf(str[i++]) - rnumx) * ylen * ylen + (keys.indexOf(str[i++]) - rnumx) * ylen + (keys.indexOf(str[i++]) - rnumx)
4449
4678
  )]);
4450
4679
  }
@@ -4491,7 +4720,7 @@ var AsAES_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4491
4720
  if (typeof value !== "string") return value;
4492
4721
  try {
4493
4722
  return JSON.parse(value);
4494
- } catch (e36) {
4723
+ } catch (e41) {
4495
4724
  return value;
4496
4725
  }
4497
4726
  }
@@ -4527,7 +4756,7 @@ var AsAES_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4527
4756
  }
4528
4757
  _chunkSMVZ3ZDJcjs.__name.call(void 0, decrypt, "decrypt");
4529
4758
  function validateFields(payload, fields) {
4530
- return fields.every((key) => typeof _optionalChain([payload, 'optionalAccess', _535 => _535[key]]) === "string" && payload[key].length > 0);
4759
+ return fields.every((key) => typeof _optionalChain([payload, 'optionalAccess', _548 => _548[key]]) === "string" && payload[key].length > 0);
4531
4760
  }
4532
4761
  _chunkSMVZ3ZDJcjs.__name.call(void 0, validateFields, "validateFields");
4533
4762
  function reqAES(opt, fn = (data) => data) {
@@ -4535,7 +4764,7 @@ var AsAES_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4535
4764
  try {
4536
4765
  if (validateFields(reqData, ["data", "iv", "auth"])) {
4537
4766
  let aesData = decrypt(reqData);
4538
- if (_optionalChain([reqData, 'optionalAccess', _536 => _536.aes]) === 2) {
4767
+ if (_optionalChain([reqData, 'optionalAccess', _549 => _549.aes]) === 2) {
4539
4768
  aesData = JSON.parse(aesData);
4540
4769
  }
4541
4770
  return fn(aesData);
@@ -4543,7 +4772,10 @@ var AsAES_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4543
4772
  return fn(reqData);
4544
4773
  }
4545
4774
  } catch (error) {
4546
- return reqData;
4775
+ if (validateFields(reqData, ["data", "iv", "auth"])) {
4776
+ throw error;
4777
+ }
4778
+ return fn(reqData);
4547
4779
  }
4548
4780
  }
4549
4781
  _chunkSMVZ3ZDJcjs.__name.call(void 0, reqAES, "reqAES");
@@ -4565,25 +4797,25 @@ var AsAES_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai
4565
4797
 
4566
4798
  // src/sysserver/lib/common/AsDb.ts
4567
4799
  var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, cfg) => {
4568
- const DataServer = _chunkHHPGUJ75cjs.getDataServerForAsDb.call(void 0, $asai, {
4569
- type: _optionalChain([cfg, 'optionalAccess', _537 => _537.type]) || "sqlite",
4800
+ const DataServer = _chunk2BCIIKRGcjs.getDataServerForAsDb.call(void 0, $asai, {
4801
+ type: _optionalChain([cfg, 'optionalAccess', _550 => _550.type]) || "sqlite",
4570
4802
  opt: {
4571
- ..._optionalChain([cfg, 'optionalAccess', _538 => _538.opt]) || {
4803
+ ..._optionalChain([cfg, 'optionalAccess', _551 => _551.opt]) || {
4572
4804
  database: "./webdata/webdb/sqlite/asaisqlite.db",
4573
4805
  create: 1
4574
4806
  }
4575
4807
  },
4576
- storeKey: _optionalChain([cfg, 'optionalAccess', _539 => _539.storeKey])
4808
+ storeKey: _optionalChain([cfg, 'optionalAccess', _552 => _552.storeKey])
4577
4809
  });
4578
4810
  function reqwherestr(str) {
4579
- if (_optionalChain([cfg, 'optionalAccess', _540 => _540.type]) === "sqlite" || _optionalChain([cfg, 'optionalAccess', _541 => _541.type]) === "mysql") {
4811
+ if (_optionalChain([cfg, 'optionalAccess', _553 => _553.type]) === "sqlite" || _optionalChain([cfg, 'optionalAccess', _554 => _554.type]) === "mysql") {
4580
4812
  return `'${str}'`;
4581
4813
  }
4582
4814
  return str;
4583
4815
  }
4584
4816
  _chunkSMVZ3ZDJcjs.__name.call(void 0, reqwherestr, "reqwherestr");
4585
4817
  function reqfield(queryData) {
4586
- if (_optionalChain([queryData, 'optionalAccess', _542 => _542.fd])) {
4818
+ if (_optionalChain([queryData, 'optionalAccess', _555 => _555.fd])) {
4587
4819
  return queryData.fd.split("-");
4588
4820
  }
4589
4821
  return cfg.field.data;
@@ -4591,14 +4823,14 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4591
4823
  _chunkSMVZ3ZDJcjs.__name.call(void 0, reqfield, "reqfield");
4592
4824
  function reqwhere(queryData) {
4593
4825
  const wheretmp = [];
4594
- if ((_optionalChain([cfg, 'optionalAccess', _543 => _543.type]) === "sqlite" || _optionalChain([cfg, 'optionalAccess', _544 => _544.type]) === "mysql") && _optionalChain([queryData, 'optionalAccess', _545 => _545.wlv])) {
4826
+ if ((_optionalChain([cfg, 'optionalAccess', _556 => _556.type]) === "sqlite" || _optionalChain([cfg, 'optionalAccess', _557 => _557.type]) === "mysql") && _optionalChain([queryData, 'optionalAccess', _558 => _558.wlv])) {
4595
4827
  const wlvarr = queryData.wlv.split("-");
4596
4828
  wheretmp.push([wlvarr[0], ">", Number(wlvarr[1] || 0)]);
4597
4829
  }
4598
- if (_optionalChain([queryData, 'optionalAccess', _546 => _546.fl])) {
4830
+ if (_optionalChain([queryData, 'optionalAccess', _559 => _559.fl])) {
4599
4831
  wheretmp.push([cfg.field.class, "LIKE", reqwherestr(`${queryData.fl}%`)]);
4600
4832
  }
4601
- if (_optionalChain([queryData, 'optionalAccess', _547 => _547.ss]) && _optionalChain([queryData, 'optionalAccess', _548 => _548.ssty])) {
4833
+ if (_optionalChain([queryData, 'optionalAccess', _560 => _560.ss]) && _optionalChain([queryData, 'optionalAccess', _561 => _561.ssty])) {
4602
4834
  wheretmp.push([queryData.ssty, "LIKE", reqwherestr(`%${queryData.ss}%`)]);
4603
4835
  }
4604
4836
  if (wheretmp.length > 1) {
@@ -4609,16 +4841,16 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4609
4841
  _chunkSMVZ3ZDJcjs.__name.call(void 0, reqwhere, "reqwhere");
4610
4842
  function reqorder(queryData) {
4611
4843
  const ordertmp = [];
4612
- if (_optionalChain([queryData, 'optionalAccess', _549 => _549.sx])) {
4613
- ordertmp.push([queryData.sx, _optionalChain([queryData, 'optionalAccess', _550 => _550.sxty]) == 1 ? "DESC" : "ASC"]);
4844
+ if (_optionalChain([queryData, 'optionalAccess', _562 => _562.sx])) {
4845
+ ordertmp.push([queryData.sx, _optionalChain([queryData, 'optionalAccess', _563 => _563.sxty]) == 1 ? "DESC" : "ASC"]);
4614
4846
  }
4615
4847
  return ordertmp;
4616
4848
  }
4617
4849
  _chunkSMVZ3ZDJcjs.__name.call(void 0, reqorder, "reqorder");
4618
4850
  function reqlimit(queryData) {
4619
4851
  let limittmp = "";
4620
- let limitps = _optionalChain([queryData, 'optionalAccess', _551 => _551.ps]);
4621
- if (_optionalChain([queryData, 'optionalAccess', _552 => _552.pg])) {
4852
+ let limitps = _optionalChain([queryData, 'optionalAccess', _564 => _564.ps]);
4853
+ if (_optionalChain([queryData, 'optionalAccess', _565 => _565.pg])) {
4622
4854
  limitps = limitps || 20;
4623
4855
  limittmp = `${(queryData.pg - 1) * limitps},${limitps}`;
4624
4856
  } else if (limitps) {
@@ -4627,10 +4859,52 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4627
4859
  return limittmp;
4628
4860
  }
4629
4861
  _chunkSMVZ3ZDJcjs.__name.call(void 0, reqlimit, "reqlimit");
4862
+ function decodePathSegment(seg) {
4863
+ try {
4864
+ return decodeURIComponent(seg);
4865
+ } catch (e42) {
4866
+ return seg;
4867
+ }
4868
+ }
4869
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, decodePathSegment, "decodePathSegment");
4870
+ function bareFileName(name) {
4871
+ const base = String(name).replace(/\.json$/i, "");
4872
+ const slash = base.lastIndexOf("/");
4873
+ return slash > -1 ? base.substring(slash + 1) : base;
4874
+ }
4875
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, bareFileName, "bareFileName");
4876
+ function parseFileBody(raw) {
4877
+ let body = raw;
4878
+ if (typeof body === "string") {
4879
+ try {
4880
+ body = JSON.parse(body);
4881
+ } catch (e43) {
4882
+ return { content: body };
4883
+ }
4884
+ }
4885
+ if (body && typeof body === "object" && !Array.isArray(body)) {
4886
+ return {
4887
+ name: body.name != null ? String(body.name) : void 0,
4888
+ content: body.content !== void 0 ? body.content : body
4889
+ };
4890
+ }
4891
+ return { content: body };
4892
+ }
4893
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, parseFileBody, "parseFileBody");
4894
+ function fileContentString(content) {
4895
+ if (content == null) return "";
4896
+ if (typeof content === "string") return content;
4897
+ return JSON.stringify(content);
4898
+ }
4899
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, fileContentString, "fileContentString");
4900
+ function fileKeyFromSegment(seg, bodyName) {
4901
+ return bareFileName(decodePathSegment(seg || bodyName || ""));
4902
+ }
4903
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, fileKeyFromSegment, "fileKeyFromSegment");
4630
4904
  function getSqlParamsByUrl(req, opt) {
4631
4905
  let tmpSqlParams;
4632
- const reqArr = _optionalChain([req, 'optionalAccess', _553 => _553.url, 'optionalAccess', _554 => _554.split, 'call', _555 => _555("?"), 'access', _556 => _556[0], 'optionalAccess', _557 => _557.split, 'call', _558 => _558("/")]) || [];
4633
- const table = (_optionalChain([opt, 'optionalAccess', _559 => _559.qrdata, 'optionalAccess', _560 => _560.table]) || _optionalChain([opt, 'optionalAccess', _561 => _561.data, 'optionalAccess', _562 => _562.table]) || reqArr[3]).replaceAll("_", "/");
4906
+ const reqArr = _optionalChain([req, 'optionalAccess', _566 => _566.url, 'optionalAccess', _567 => _567.split, 'call', _568 => _568("?"), 'access', _569 => _569[0], 'optionalAccess', _570 => _570.split, 'call', _571 => _571("/")]) || [];
4907
+ const table = (_optionalChain([opt, 'optionalAccess', _572 => _572.qrdata, 'optionalAccess', _573 => _573.table]) || _optionalChain([opt, 'optionalAccess', _574 => _574.data, 'optionalAccess', _575 => _575.table]) || reqArr[3]).replaceAll("_", "/");
4634
4908
  if (!table) return tmpSqlParams;
4635
4909
  tmpSqlParams = {
4636
4910
  type: "select",
@@ -4639,9 +4913,11 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4639
4913
  if (reqArr[5]) {
4640
4914
  if (reqArr[4] === "insert") {
4641
4915
  tmpSqlParams.type = reqArr[4];
4642
- if (_optionalChain([cfg, 'optionalAccess', _563 => _563.type]) === "file") {
4916
+ if (_optionalChain([cfg, 'optionalAccess', _576 => _576.type]) === "file") {
4917
+ const { name: bodyName, content } = parseFileBody(opt.data);
4918
+ const fileKey = fileKeyFromSegment(reqArr[5], bodyName);
4643
4919
  tmpSqlParams.field = cfg.field.data;
4644
- tmpSqlParams.value = [[reqwherestr(reqArr[5]), reqwherestr(opt.data)]];
4920
+ tmpSqlParams.value = [[fileKey, fileContentString(content)]];
4645
4921
  } else {
4646
4922
  tmpSqlParams.field = [];
4647
4923
  tmpSqlParams.value = [];
@@ -4661,9 +4937,12 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4661
4937
  }
4662
4938
  } else if (reqArr[4] === "update") {
4663
4939
  tmpSqlParams.type = reqArr[4];
4664
- tmpSqlParams.where = [[cfg.field.key, "=", reqwherestr(reqArr[5])]];
4665
- if (_optionalChain([cfg, 'optionalAccess', _564 => _564.type]) === "file") {
4666
- tmpSqlParams.set = [[cfg.field.key, reqwherestr(opt.data)]];
4940
+ const rowKey = _optionalChain([cfg, 'optionalAccess', _577 => _577.type]) === "file" ? fileKeyFromSegment(reqArr[5]) : decodePathSegment(reqArr[5]);
4941
+ tmpSqlParams.where = [[cfg.field.key, "=", reqwherestr(rowKey)]];
4942
+ if (_optionalChain([cfg, 'optionalAccess', _578 => _578.type]) === "file") {
4943
+ const { content } = parseFileBody(opt.data);
4944
+ const contentField = _optionalChain([cfg, 'access', _579 => _579.field, 'access', _580 => _580.data, 'optionalAccess', _581 => _581[1]]) || "content";
4945
+ tmpSqlParams.set = [[contentField, fileContentString(content)]];
4667
4946
  } else {
4668
4947
  tmpSqlParams.set = [];
4669
4948
  const dbData = typeof opt.data === "string" ? JSON.parse(opt.data) : opt.data;
@@ -4679,16 +4958,18 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4679
4958
  }
4680
4959
  } else if (reqArr[4] === "delete") {
4681
4960
  tmpSqlParams.type = reqArr[4];
4682
- tmpSqlParams.where = [[cfg.field.key, "=", reqwherestr(reqArr[5])]];
4961
+ const rowKey = _optionalChain([cfg, 'optionalAccess', _582 => _582.type]) === "file" ? fileKeyFromSegment(reqArr[5]) : decodePathSegment(reqArr[5]);
4962
+ tmpSqlParams.where = [[cfg.field.key, "=", reqwherestr(rowKey)]];
4683
4963
  } else {
4684
- if (_optionalChain([cfg, 'optionalAccess', _565 => _565.as]) > 1) {
4964
+ if (_optionalChain([cfg, 'optionalAccess', _583 => _583.as]) > 1) {
4685
4965
  tmpSqlParams.as = +cfg.as - 1;
4686
4966
  }
4687
4967
  tmpSqlParams.field = cfg.field.data;
4688
- tmpSqlParams.where = [[cfg.field.key, "=", reqwherestr(reqArr[5])]];
4968
+ const rowKey = _optionalChain([cfg, 'optionalAccess', _584 => _584.type]) === "file" ? fileKeyFromSegment(reqArr[5]) : decodePathSegment(reqArr[5]);
4969
+ tmpSqlParams.where = [[cfg.field.key, "=", reqwherestr(rowKey)]];
4689
4970
  }
4690
4971
  } else {
4691
- tmpSqlParams.as = _optionalChain([cfg, 'optionalAccess', _566 => _566.as]);
4972
+ tmpSqlParams.as = _optionalChain([cfg, 'optionalAccess', _585 => _585.as]);
4692
4973
  tmpSqlParams.field = reqfield(opt.data);
4693
4974
  tmpSqlParams.where = reqwhere(opt.data);
4694
4975
  tmpSqlParams.order = reqorder(opt.data);
@@ -4698,24 +4979,55 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4698
4979
  }
4699
4980
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getSqlParamsByUrl, "getSqlParamsByUrl");
4700
4981
  function dbFresh(req, resdb) {
4701
- if (_optionalChain([req, 'optionalAccess', _567 => _567.url, 'optionalAccess', _568 => _568.includes, 'call', _569 => _569("/selectlist/")])) {
4702
- const list = Array.isArray(resdb) ? resdb : _optionalChain([resdb, 'optionalAccess', _570 => _570.data]);
4982
+ if (_optionalChain([req, 'optionalAccess', _586 => _586.url, 'optionalAccess', _587 => _587.includes, 'call', _588 => _588("/selectlist/")])) {
4983
+ const list = Array.isArray(resdb) ? resdb : _optionalChain([resdb, 'optionalAccess', _589 => _589.data]);
4703
4984
  if (Array.isArray(list)) {
4704
- const mapped = list.map((el) => {
4985
+ const names = list.map((el) => {
4986
+ if (typeof el === "string") {
4987
+ const dot2 = el.lastIndexOf(".");
4988
+ return dot2 > -1 ? el.substring(0, dot2) : el;
4989
+ }
4705
4990
  const rawName = _nullishCoalesce(_nullishCoalesce(el.name, () => ( el.file)), () => ( ""));
4706
4991
  let tmpName = String(rawName).substring(String(rawName).lastIndexOf("/") + 1);
4707
4992
  const dot = tmpName.lastIndexOf(".");
4708
4993
  return dot > -1 ? tmpName.substring(0, dot) : tmpName;
4709
4994
  });
4710
- if (Array.isArray(resdb)) return mapped;
4711
- resdb.data = mapped;
4995
+ const children = names.map((name) => ({ name, path: name }));
4996
+ if (Array.isArray(resdb)) return { children };
4997
+ resdb.data = children;
4998
+ return resdb;
4712
4999
  }
4713
5000
  }
4714
5001
  return resdb;
4715
5002
  }
4716
5003
  _chunkSMVZ3ZDJcjs.__name.call(void 0, dbFresh, "dbFresh");
5004
+ function normalizeSelectResult(params, resdb) {
5005
+ let data = resdb;
5006
+ if (_optionalChain([params, 'optionalAccess', _590 => _590.where, 'optionalAccess', _591 => _591.length]) && Array.isArray(data) && data.length === 1) {
5007
+ data = data[0];
5008
+ }
5009
+ if (_optionalChain([cfg, 'optionalAccess', _592 => _592.type]) === "file" && data && typeof data === "object" && !Array.isArray(data)) {
5010
+ const nameKey = _optionalChain([cfg, 'access', _593 => _593.field, 'optionalAccess', _594 => _594.data, 'optionalAccess', _595 => _595[0]]) || "name";
5011
+ const contentKey = _optionalChain([cfg, 'access', _596 => _596.field, 'optionalAccess', _597 => _597.data, 'optionalAccess', _598 => _598[1]]) || "content";
5012
+ if (data[nameKey] != null) {
5013
+ data[nameKey] = bareFileName(String(data[nameKey]));
5014
+ }
5015
+ const raw = data[contentKey];
5016
+ if (typeof raw === "string") {
5017
+ const text = raw.trim();
5018
+ if (text.startsWith("{") || text.startsWith("[")) {
5019
+ try {
5020
+ data[contentKey] = JSON.parse(text);
5021
+ } catch (e44) {
5022
+ }
5023
+ }
5024
+ }
5025
+ }
5026
+ return data;
5027
+ }
5028
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, normalizeSelectResult, "normalizeSelectResult");
4717
5029
  function dbCodePm(req, resdb) {
4718
- if (_optionalChain([req, 'optionalAccess', _571 => _571.Userinfo]) && _optionalChain([req, 'optionalAccess', _572 => _572.Userinfo, 'access', _573 => _573[2]])) {
5030
+ if (_optionalChain([req, 'optionalAccess', _599 => _599.Userinfo]) && _optionalChain([req, 'optionalAccess', _600 => _600.Userinfo, 'access', _601 => _601[2]])) {
4719
5031
  resdb.data = $asai.$lib.AsCode.asencode(JSON.stringify(resdb.data), req.Userinfo[2]);
4720
5032
  }
4721
5033
  return resdb;
@@ -4727,8 +5039,8 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4727
5039
  DataServer.sqlDb(params).then((resdb) => {
4728
5040
  res.end(JSON.stringify($asai.$lib.As.ctxSuccess(dbCodePm(req, dbFresh(req, resdb)), opt)));
4729
5041
  }).catch((errdb) => {
4730
- const msg = String(_optionalChain([errdb, 'optionalAccess', _574 => _574.message]) || errdb || "");
4731
- if (_optionalChain([params, 'optionalAccess', _575 => _575.type]) === "select" && msg.includes("no such table")) {
5042
+ const msg = String(_optionalChain([errdb, 'optionalAccess', _602 => _602.message]) || errdb || "");
5043
+ if (_optionalChain([params, 'optionalAccess', _603 => _603.type]) === "select" && msg.includes("no such table")) {
4732
5044
  res.end(JSON.stringify($asai.$lib.As.ctxSuccess([], opt)));
4733
5045
  return;
4734
5046
  }
@@ -4744,30 +5056,30 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4744
5056
  if (params && typeof DataServer.sqlDb === "function") {
4745
5057
  try {
4746
5058
  DataServer.sqlDb(params).then((resdb) => {
4747
- let resData = dbFresh(req, resdb);
4748
- if (_optionalChain([params, 'optionalAccess', _576 => _576.as]) === 2 && _optionalChain([params, 'optionalAccess', _577 => _577.field, 'optionalAccess', _578 => _578.length]) > 1) {
5059
+ let resData = normalizeSelectResult(params, dbFresh(req, resdb));
5060
+ if (_optionalChain([params, 'optionalAccess', _604 => _604.as]) === 2 && _optionalChain([params, 'optionalAccess', _605 => _605.field, 'optionalAccess', _606 => _606.length]) > 1) {
4749
5061
  let limitArr = [];
4750
- if (_optionalChain([params, 'access', _579 => _579.limit, 'optionalAccess', _580 => _580.split, 'call', _581 => _581(","), 'optionalAccess', _582 => _582.length]) < 2) {
4751
- limitArr = [0, +_optionalChain([params, 'access', _583 => _583.limit, 'optionalAccess', _584 => _584.split, 'call', _585 => _585(","), 'optionalAccess', _586 => _586[0]])];
5062
+ if (_optionalChain([params, 'access', _607 => _607.limit, 'optionalAccess', _608 => _608.split, 'call', _609 => _609(","), 'optionalAccess', _610 => _610.length]) < 2) {
5063
+ limitArr = [0, +_optionalChain([params, 'access', _611 => _611.limit, 'optionalAccess', _612 => _612.split, 'call', _613 => _613(","), 'optionalAccess', _614 => _614[0]])];
4752
5064
  } else {
4753
5065
  limitArr = params.limit.split(",");
4754
5066
  limitArr = [+limitArr[0], +limitArr[0] + +limitArr[1]];
4755
5067
  }
4756
- if (_optionalChain([resData, 'access', _587 => _587.data, 'optionalAccess', _588 => _588.length])) {
5068
+ if (_optionalChain([resData, 'access', _615 => _615.data, 'optionalAccess', _616 => _616.length])) {
4757
5069
  resData.data = resData.data.slice(+limitArr[0], +limitArr[1]);
4758
5070
  }
4759
5071
  }
4760
5072
  resData = dbCodePm(req, resData);
4761
5073
  res.end(JSON.stringify($asai.$lib.As.ctxSuccess(resData, opt)));
4762
5074
  }).catch((errdb) => {
4763
- const msg = String(_optionalChain([errdb, 'optionalAccess', _589 => _589.message]) || errdb || "");
4764
- if (_optionalChain([params, 'optionalAccess', _590 => _590.type]) === "select" && msg.includes("no such table")) {
5075
+ const msg = String(_optionalChain([errdb, 'optionalAccess', _617 => _617.message]) || errdb || "");
5076
+ if (_optionalChain([params, 'optionalAccess', _618 => _618.type]) === "select" && msg.includes("no such table")) {
4765
5077
  res.end(JSON.stringify($asai.$lib.As.ctxSuccess([], opt)));
4766
5078
  return;
4767
5079
  }
4768
5080
  res.end(JSON.stringify($asai.$lib.As.ctxFail(errdb)));
4769
5081
  });
4770
- } catch (e37) {
5082
+ } catch (e45) {
4771
5083
  res.end(JSON.stringify({ code: 901 }));
4772
5084
  }
4773
5085
  } else {
@@ -4776,7 +5088,7 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4776
5088
  }
4777
5089
  _chunkSMVZ3ZDJcjs.__name.call(void 0, runDefaultGet, "runDefaultGet");
4778
5090
  function post(req, res, hostdir, opt) {
4779
- if (_optionalChain([cfg, 'optionalAccess', _591 => _591.post]) && typeof cfg.post === "function") {
5091
+ if (_optionalChain([cfg, 'optionalAccess', _619 => _619.post]) && typeof cfg.post === "function") {
4780
5092
  Promise.resolve(cfg.post(req, res, hostdir, opt, DataServer)).then((reqstat) => {
4781
5093
  if (!reqstat) runDefaultPost(req, res, opt);
4782
5094
  }).catch((errdb) => {
@@ -4788,7 +5100,7 @@ var AsDb_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai,
4788
5100
  }
4789
5101
  _chunkSMVZ3ZDJcjs.__name.call(void 0, post, "post");
4790
5102
  function get(req, res, hostdir, opt) {
4791
- if (_optionalChain([cfg, 'optionalAccess', _592 => _592.get]) && typeof cfg.get === "function") {
5103
+ if (_optionalChain([cfg, 'optionalAccess', _620 => _620.get]) && typeof cfg.get === "function") {
4792
5104
  Promise.resolve(cfg.get(req, res, hostdir, opt, DataServer)).then((reqstat) => {
4793
5105
  if (!reqstat) runDefaultGet(req, res, opt);
4794
5106
  }).catch((errdb) => {
@@ -4813,7 +5125,7 @@ var reqWork_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($as
4813
5125
  }
4814
5126
  _chunkSMVZ3ZDJcjs.__name.call(void 0, hostDefault2, "hostDefault");
4815
5127
  function getPathFromOpt(opt) {
4816
- const rawPath = _optionalChain([opt, 'access', _593 => _593.qrdata, 'optionalAccess', _594 => _594.path]) || _optionalChain([opt, 'access', _595 => _595.data, 'optionalAccess', _596 => _596.path]);
5128
+ const rawPath = _optionalChain([opt, 'access', _621 => _621.qrdata, 'optionalAccess', _622 => _622.path]) || _optionalChain([opt, 'access', _623 => _623.data, 'optionalAccess', _624 => _624.path]);
4817
5129
  return decodeURIComponent(rawPath);
4818
5130
  }
4819
5131
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getPathFromOpt, "getPathFromOpt");
@@ -4823,18 +5135,18 @@ var reqWork_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($as
4823
5135
  }
4824
5136
  _chunkSMVZ3ZDJcjs.__name.call(void 0, sendSuccess, "sendSuccess");
4825
5137
  function sendErr(res, ec, params, opt) {
4826
- const ErrorCode = _optionalChain([$asai, 'access', _597 => _597.$lib, 'optionalAccess', _598 => _598.ErrorCode]);
4827
- _optionalChain([ErrorCode, 'optionalAccess', _599 => _599.loadErrorCodes, 'optionalCall', _600 => _600($asai)]);
4828
- _optionalChain([ErrorCode, 'optionalAccess', _601 => _601.logError, 'optionalCall', _602 => _602($asai, ec, Array.isArray(params) ? params.map(String) : params != null ? [String(params)] : void 0)]);
5138
+ const ErrorCode = _optionalChain([$asai, 'access', _625 => _625.$lib, 'optionalAccess', _626 => _626.ErrorCode]);
5139
+ _optionalChain([ErrorCode, 'optionalAccess', _627 => _627.loadErrorCodes, 'optionalCall', _628 => _628($asai)]);
5140
+ _optionalChain([ErrorCode, 'optionalAccess', _629 => _629.logError, 'optionalCall', _630 => _630($asai, ec, Array.isArray(params) ? params.map(String) : params != null ? [String(params)] : void 0)]);
4829
5141
  const response = $asai.$lib.As.ctxErr(ec, params, opt);
4830
5142
  res.end(JSON.stringify(response));
4831
5143
  }
4832
5144
  _chunkSMVZ3ZDJcjs.__name.call(void 0, sendErr, "sendErr");
4833
5145
  function sendFail(res, err, opt) {
4834
- const ErrorCode = _optionalChain([$asai, 'access', _603 => _603.$lib, 'optionalAccess', _604 => _604.ErrorCode]);
4835
- _optionalChain([ErrorCode, 'optionalAccess', _605 => _605.loadErrorCodes, 'optionalCall', _606 => _606($asai)]);
4836
- const normalized = _optionalChain([ErrorCode, 'optionalAccess', _607 => _607.normalizeErrPayload, 'optionalCall', _608 => _608(err)]);
4837
- if (_optionalChain([normalized, 'optionalAccess', _609 => _609.ec])) {
5146
+ const ErrorCode = _optionalChain([$asai, 'access', _631 => _631.$lib, 'optionalAccess', _632 => _632.ErrorCode]);
5147
+ _optionalChain([ErrorCode, 'optionalAccess', _633 => _633.loadErrorCodes, 'optionalCall', _634 => _634($asai)]);
5148
+ const normalized = _optionalChain([ErrorCode, 'optionalAccess', _635 => _635.normalizeErrPayload, 'optionalCall', _636 => _636(err)]);
5149
+ if (_optionalChain([normalized, 'optionalAccess', _637 => _637.ec])) {
4838
5150
  return sendErr(res, normalized.ec, normalized.pm, opt);
4839
5151
  }
4840
5152
  const response = $asai.$lib.As.ctxFail(err);
@@ -4842,7 +5154,7 @@ var reqWork_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($as
4842
5154
  }
4843
5155
  _chunkSMVZ3ZDJcjs.__name.call(void 0, sendFail, "sendFail");
4844
5156
  function mnLog(...arg) {
4845
- (_optionalChain([$asai, 'optionalAccess', _610 => _610.$log]) || console.log)(...arg);
5157
+ (_optionalChain([$asai, 'optionalAccess', _638 => _638.$log]) || console.log)(...arg);
4846
5158
  }
4847
5159
  _chunkSMVZ3ZDJcjs.__name.call(void 0, mnLog, "mnLog");
4848
5160
  return { hostDefault: hostDefault2, getPathFromOpt, sendSuccess, sendFail, sendErr, mnLog };
@@ -4875,7 +5187,7 @@ async function pathExists(filePath) {
4875
5187
  try {
4876
5188
  await _promises2.default.access(nodePath2.default.normalize(filePath));
4877
5189
  return true;
4878
- } catch (e38) {
5190
+ } catch (e46) {
4879
5191
  return false;
4880
5192
  }
4881
5193
  }
@@ -4942,7 +5254,7 @@ async function removeFile(filePath) {
4942
5254
  try {
4943
5255
  await _promises2.default.unlink(nodePath2.default.normalize(filePath));
4944
5256
  } catch (err) {
4945
- if (_optionalChain([err, 'optionalAccess', _611 => _611.code]) !== "ENOENT") throw err;
5257
+ if (_optionalChain([err, 'optionalAccess', _639 => _639.code]) !== "ENOENT") throw err;
4946
5258
  }
4947
5259
  }
4948
5260
  _chunkSMVZ3ZDJcjs.__name.call(void 0, removeFile, "removeFile");
@@ -4980,7 +5292,7 @@ function isPkgRuntime() {
4980
5292
  _chunkSMVZ3ZDJcjs.__name.call(void 0, isPkgRuntime, "isPkgRuntime");
4981
5293
  function getPkgSnapshotDir() {
4982
5294
  if (!isPkgRuntime()) return void 0;
4983
- const entry = _nullishCoalesce(_optionalChain([process, 'access', _612 => _612.pkg, 'optionalAccess', _613 => _613.entrypoint]), () => ( _optionalChain([process, 'access', _614 => _614.pkg, 'optionalAccess', _615 => _615.defaultEntrypoint])));
5295
+ const entry = _nullishCoalesce(_optionalChain([process, 'access', _640 => _640.pkg, 'optionalAccess', _641 => _641.entrypoint]), () => ( _optionalChain([process, 'access', _642 => _642.pkg, 'optionalAccess', _643 => _643.defaultEntrypoint])));
4984
5296
  if (!entry) return void 0;
4985
5297
  return nodePath4.resolve(nodePath4.dirname(entry));
4986
5298
  }
@@ -5029,7 +5341,7 @@ function getPrimaryServerRoot() {
5029
5341
  if (fs10.statSync(nodePath4.join(base, "websys")).isDirectory()) {
5030
5342
  return base;
5031
5343
  }
5032
- } catch (e39) {
5344
+ } catch (e47) {
5033
5345
  }
5034
5346
  }
5035
5347
  if (isPkgRuntime()) {
@@ -5049,25 +5361,37 @@ var lib_default = {
5049
5361
  AsPath: AsPath_exports,
5050
5362
  reqWork: reqWork_default,
5051
5363
  ErrorCode: ErrorCode_default,
5052
- InterventionLog: _chunkG4WVDUBHcjs.InterventionLog_exports,
5053
- LogStore: _chunkVLMM735Qcjs.LogStore_exports,
5054
- InterventionHooks: _chunkNLBFIRDBcjs.intervention_hooks_exports
5364
+ InterventionLog: _chunk4E7Z5K5Ucjs.InterventionLog_exports,
5365
+ LogStore: _chunkTKJAHTPOcjs.LogStore_exports,
5366
+ InterventionHooks: _chunkRIRKIYETcjs.intervention_hooks_exports
5055
5367
  };
5056
5368
 
5057
5369
  // src/sysserver/db/src/common.ts
5370
+ var common_exports = {};
5371
+ _chunkSMVZ3ZDJcjs.__export.call(void 0, common_exports, {
5372
+ fieldHasId: () => fieldHasId,
5373
+ isPathInside: () => isPathInside,
5374
+ isTableMissingError: () => isTableMissingError,
5375
+ joinTablePath: () => joinTablePath,
5376
+ promisifySqlDb: () => promisifySqlDb,
5377
+ toFieldArray: () => toFieldArray,
5378
+ toInsertRows: () => toInsertRows,
5379
+ toSetObject: () => toSetObject,
5380
+ toWherePairs: () => toWherePairs
5381
+ });
5058
5382
 
5059
5383
  function promisifySqlDb(query, sql) {
5060
- return new Promise((resolve7, reject) => {
5384
+ return new Promise((resolve6, reject) => {
5061
5385
  query(sql, (err, result) => {
5062
5386
  if (err) {
5063
5387
  reject(err);
5064
5388
  return;
5065
5389
  }
5066
5390
  if (!result || Array.isArray(result) && result.length === 0) {
5067
- resolve7("");
5391
+ resolve6("");
5068
5392
  return;
5069
5393
  }
5070
- resolve7(result);
5394
+ resolve6(result);
5071
5395
  });
5072
5396
  });
5073
5397
  }
@@ -5077,6 +5401,48 @@ function toFieldArray(field) {
5077
5401
  return typeof field === "string" ? field.split(",") : field;
5078
5402
  }
5079
5403
  _chunkSMVZ3ZDJcjs.__name.call(void 0, toFieldArray, "toFieldArray");
5404
+ function toWherePairs(where) {
5405
+ if (!where || !Array.isArray(where)) return [];
5406
+ const pairs = [];
5407
+ for (const item of where) {
5408
+ if (typeof item === "string") continue;
5409
+ if (Array.isArray(item) && item.length >= 3) {
5410
+ pairs.push([item[0], item[2]]);
5411
+ }
5412
+ }
5413
+ return pairs;
5414
+ }
5415
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, toWherePairs, "toWherePairs");
5416
+ function toSetObject(set) {
5417
+ if (!set) return {};
5418
+ if (typeof set === "string") return {};
5419
+ const obj = {};
5420
+ for (const item of set) {
5421
+ if (typeof item === "string") continue;
5422
+ if (Array.isArray(item)) {
5423
+ if (item.length >= 3 && typeof item[1] === "string") {
5424
+ obj[item[0]] = item[2];
5425
+ } else if (item.length >= 2) {
5426
+ obj[item[0]] = item[1];
5427
+ }
5428
+ }
5429
+ }
5430
+ return obj;
5431
+ }
5432
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, toSetObject, "toSetObject");
5433
+ function toInsertRows(sql) {
5434
+ const fields = toFieldArray(sql.field);
5435
+ const values = sql.value;
5436
+ if (!fields.length || !Array.isArray(values)) return [];
5437
+ return values.map((row) => {
5438
+ const rowObj = {};
5439
+ fields.forEach((field, index) => {
5440
+ rowObj[field] = row[index];
5441
+ });
5442
+ return rowObj;
5443
+ });
5444
+ }
5445
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, toInsertRows, "toInsertRows");
5080
5446
  function isPathInside(baseDir, targetPath) {
5081
5447
  const base = path5.resolve(baseDir);
5082
5448
  const target = path5.resolve(targetPath);
@@ -5262,936 +5628,426 @@ var Sql_default = {
5262
5628
  }
5263
5629
  };
5264
5630
 
5265
- // src/sysserver/db/src/mysql/Index.ts
5266
- var _mysql = require('mysql'); var _mysql2 = _interopRequireDefault(_mysql);
5267
- var DbMySQL = class {
5268
- static {
5269
- _chunkSMVZ3ZDJcjs.__name.call(void 0, this, "DbMySQL");
5270
- }
5271
- constructor(config) {
5272
- this.config = config;
5273
- this.pool = _mysql2.default.createPool(config);
5274
- }
5275
- getErr(sql, err) {
5276
- if (this.config.create && isTableMissingError(err)) {
5277
- this.createTable(sql);
5631
+ // src/sysserver/db/src/file/Index.ts
5632
+
5633
+
5634
+ function dbDriver(opt = {}) {
5635
+ const { Sql, DbCommon } = opt;
5636
+ const { isPathInside: isPathInside2, joinTablePath: joinTablePath2 } = DbCommon;
5637
+ class DbFile {
5638
+ static {
5639
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, this, "DbFile");
5278
5640
  }
5279
- return _optionalChain([err, 'optionalAccess', _616 => _616.message]) || null;
5280
- }
5281
- getResult(rows) {
5282
- return _nullishCoalesce(rows, () => ( null));
5283
- }
5284
- query(sql, callback) {
5285
- this.pool.getConnection((error, connection) => {
5286
- if (error) {
5287
- callback(this.getErr(sql, error), this.getResult(null));
5288
- return;
5289
- }
5290
- connection.query(Sql_default.makeSql(sql), (err, rows) => {
5291
- try {
5292
- callback(this.getErr(sql, err), this.getResult(rows));
5293
- } finally {
5294
- connection.release();
5295
- }
5296
- });
5297
- });
5298
- }
5299
- sqlDb(sql) {
5300
- return promisifySqlDb(this.query.bind(this), sql);
5301
- }
5302
- /** 关闭连接池,释放所有连接 */
5303
- close(callback) {
5304
- this.pool.end(callback);
5305
- }
5306
- /** 表不存在时自动创建数据库与表(需 config.create 为 true) */
5307
- createTable(sql) {
5308
- if (!this.config.create) return;
5309
- const conn = _mysql2.default.createConnection({
5310
- host: this.config.host,
5311
- user: this.config.user,
5312
- password: this.config.password
5313
- });
5314
- conn.connect((err) => {
5315
- if (err) {
5316
- conn.end();
5317
- return;
5318
- }
5319
- conn.query(`CREATE DATABASE IF NOT EXISTS ${this.config.database};`, (dbErr) => {
5320
- if (dbErr) {
5321
- conn.end();
5322
- return;
5323
- }
5324
- this.pool = _mysql2.default.createPool(this.config);
5325
- this.pool.getConnection((poolErr, connection) => {
5326
- if (poolErr || !connection) {
5327
- conn.end();
5328
- return;
5329
- }
5330
- connection.query(Sql_default.createSql(sql, "mysql"), () => {
5331
- connection.release();
5332
- conn.end();
5333
- });
5334
- });
5335
- });
5336
- });
5337
- }
5338
- };
5339
- var Index_default2 = DbMySQL;
5340
-
5341
- // src/sysserver/db/src/sqlite/Index.ts
5342
-
5343
-
5344
- var _sqlite3 = require('sqlite3'); var _sqlite32 = _interopRequireDefault(_sqlite3);
5345
- var sqlite3 = _nullishCoalesce(_sqlite32.default.default, () => ( _sqlite32.default));
5346
- var DEFAULT_BUSY_TIMEOUT_MS = 1e4;
5347
- var DEFAULT_ACQUIRE_TIMEOUT_MS = 15e3;
5348
- function configureSqliteConnection(db, busyTimeoutMs = DEFAULT_BUSY_TIMEOUT_MS) {
5349
- const busyMs = Math.max(0, Math.floor(busyTimeoutMs));
5350
- return new Promise((resolve7, reject) => {
5351
- db.serialize(() => {
5352
- db.run("PRAGMA journal_mode = WAL");
5353
- db.run(`PRAGMA busy_timeout = ${busyMs}`);
5354
- db.run("PRAGMA synchronous = NORMAL", (err) => {
5355
- if (err) reject(err);
5356
- else resolve7();
5357
- });
5358
- });
5359
- });
5360
- }
5361
- _chunkSMVZ3ZDJcjs.__name.call(void 0, configureSqliteConnection, "configureSqliteConnection");
5362
- var PooledConnection = class _PooledConnection {
5363
- static {
5364
- _chunkSMVZ3ZDJcjs.__name.call(void 0, this, "PooledConnection");
5365
- }
5366
- // 连接是否有效
5367
- constructor(db, config) {
5368
- this.db = db;
5369
- this.config = config;
5370
- this.lastUsed = Date.now();
5371
- this.inUse = false;
5372
- this.isValid = true;
5373
- }
5374
- /**
5375
- * 异步创建连接,确保目录存在并打开数据库
5376
- */
5377
- static async create(config) {
5378
- function dbLog(...args) {
5379
- (_optionalChain([config, 'optionalAccess', _617 => _617.$asai, 'optionalAccess', _618 => _618.$log]) || console.log)("SQLITE", ...args);
5380
- }
5381
- _chunkSMVZ3ZDJcjs.__name.call(void 0, dbLog, "dbLog");
5382
- const absolutePath = path6.resolve(config.database);
5383
- const dir = path6.dirname(absolutePath);
5384
- if (!fs11.existsSync(dir)) {
5385
- fs11.mkdirSync(dir, { recursive: true });
5386
- dbLog("MKDIR", dir);
5387
- }
5388
- return new Promise((resolve7, reject) => {
5389
- const db = new sqlite3.Database(absolutePath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, async (err) => {
5390
- if (err) {
5391
- dbLog("open failed", "[ERROR] Failed to open database:", absolutePath, err.message);
5392
- reject(err);
5393
- return;
5394
- }
5395
- try {
5396
- await configureSqliteConnection(db, _nullishCoalesce(config.busyTimeout, () => ( DEFAULT_BUSY_TIMEOUT_MS)));
5397
- dbLog("OPEN", absolutePath);
5398
- resolve7(new _PooledConnection(db, config));
5399
- } catch (pragmaErr) {
5400
- db.close(() => {
5401
- });
5402
- reject(pragmaErr);
5403
- }
5404
- });
5405
- });
5406
- }
5407
- /** 测试连接是否有效(执行 SELECT 1) */
5408
- async test() {
5409
- return new Promise((resolve7) => {
5410
- if (!this.isValid) return resolve7(false);
5411
- this.db.get("SELECT 1", (err) => {
5412
- this.isValid = !err;
5413
- resolve7(this.isValid);
5414
- });
5415
- });
5416
- }
5417
- /** 关闭连接 */
5418
- async close() {
5419
- return new Promise((resolve7, reject) => {
5420
- this.db.close((err) => {
5421
- if (err) reject(err);
5422
- else resolve7();
5423
- });
5424
- });
5425
- }
5426
- /** 标记连接为无效 */
5427
- invalidate() {
5428
- this.isValid = false;
5429
- }
5430
- };
5431
- var SQLitePool = class {
5432
- // 初始化完成 Promise
5433
- constructor(config) {
5434
- this.pool = [];
5435
- this.waitingQueue = [];
5436
- this.idleCheckerTimer = null;
5437
- this.isDestroyed = false;
5438
- this.config = {
5439
- database: config.database,
5440
- poolMin: _nullishCoalesce(config.poolMin, () => ( 1)),
5441
- poolMax: _nullishCoalesce(config.poolMax, () => ( 1)),
5442
- idleTimeout: _nullishCoalesce(config.idleTimeout, () => ( 3e4)),
5443
- acquireTimeout: _nullishCoalesce(config.acquireTimeout, () => ( DEFAULT_ACQUIRE_TIMEOUT_MS)),
5444
- busyTimeout: _nullishCoalesce(config.busyTimeout, () => ( DEFAULT_BUSY_TIMEOUT_MS)),
5445
- enableCreateTable: _nullishCoalesce(config.enableCreateTable, () => ( true)),
5446
- $asai: _nullishCoalesce(config.$asai, () => ( null))
5447
- };
5448
- this.initPromise = this.initializePool();
5449
- this.startIdleChecker();
5450
- }
5451
- static {
5452
- _chunkSMVZ3ZDJcjs.__name.call(void 0, this, "SQLitePool");
5453
- }
5454
- /** 统一日志输出(前缀 ♣ 标识来自 SQLite 连接池模块) */
5455
- dbLog(...args) {
5456
- (_optionalChain([this, 'access', _619 => _619.config, 'optionalAccess', _620 => _620.$asai, 'optionalAccess', _621 => _621.$log]) || console.log)("sqlite", ...args);
5457
- }
5458
- /** 初始化连接池,创建最小连接数 */
5459
- async initializePool() {
5460
- const promises = [];
5461
- for (let i = 0; i < this.config.poolMin; i++) {
5462
- promises.push(this.createConnection());
5463
- }
5464
- const results = await Promise.allSettled(promises);
5465
- const successCount = results.filter((r) => r.status === "fulfilled").length;
5466
- if (successCount === 0) {
5467
- this.dbLog("Initialization failed", "[POOL] Initialization failed: no connections created");
5468
- } else {
5469
- this.dbLog("Initialized", "[POOL] Initialized, size:", this.pool.length);
5641
+ constructor(config) {
5642
+ this.config = config;
5643
+ this.fileExt = config.ext === ".*" ? "" : config.ext || "";
5644
+ this.fileDel = (config.del || 0) !== 0;
5645
+ this.createDir = config.create || false;
5646
+ this.baseDirAbs = path6.resolve(process.cwd(), config.dir);
5470
5647
  }
5471
- }
5472
- /** 创建一个新连接并加入池中 */
5473
- async createConnection() {
5474
- if (this.pool.length >= this.config.poolMax) return;
5475
- try {
5476
- const conn = await PooledConnection.create(this.config);
5477
- const isValid = await conn.test();
5478
- if (isValid) {
5479
- this.pool.push(conn);
5480
- } else {
5481
- await conn.close().catch(() => {
5482
- });
5483
- throw new Error("Connection test failed");
5484
- }
5485
- } catch (err) {
5486
- this.dbLog("Database create failed", "[CONN] Failed to create connection:", err.message);
5487
- throw err;
5648
+ dbLog(...args) {
5649
+ (_optionalChain([this, 'access', _644 => _644.config, 'optionalAccess', _645 => _645.$asai, 'optionalAccess', _646 => _646.$log]) || console.log)("FILE", ...args);
5488
5650
  }
5489
- }
5490
- /**
5491
- * 获取一个可用连接
5492
- * - 优先返回空闲连接
5493
- * - 若连接数未达上限则创建新连接
5494
- * - 否则进入等待队列
5495
- */
5496
- async acquire() {
5497
- await this.initPromise;
5498
- if (this.isDestroyed) {
5499
- throw new Error("Pool has been destroyed");
5651
+ checkFile(file) {
5652
+ return fs11.existsSync(this.getAbsPath(file, false));
5500
5653
  }
5501
- const now = Date.now();
5502
- const staleCheckMs = Math.min(this.config.idleTimeout, 5e3);
5503
- for (const conn of this.pool) {
5504
- if (!conn.inUse) {
5505
- if (now - conn.lastUsed > staleCheckMs) {
5506
- const isValid = await conn.test();
5507
- if (!isValid) {
5508
- this.removeConnection(conn);
5509
- continue;
5510
- }
5511
- }
5512
- conn.inUse = true;
5513
- conn.lastUsed = now;
5514
- return conn;
5654
+ /** 解析相对路径并限制在数据根目录内,防止路径穿越(跨平台) */
5655
+ resolvePath(relPath) {
5656
+ if (!relPath) {
5657
+ return this.baseDirAbs;
5515
5658
  }
5516
- }
5517
- if (this.pool.length < this.config.poolMax) {
5518
- try {
5519
- const conn = await PooledConnection.create(this.config);
5520
- const isValid = await conn.test();
5521
- if (isValid) {
5522
- conn.inUse = true;
5523
- conn.lastUsed = Date.now();
5524
- this.pool.push(conn);
5525
- return conn;
5526
- } else {
5527
- await conn.close().catch(() => {
5528
- });
5529
- }
5530
- } catch (e) {
5531
- this.dbLog("create failed", "[ACQUIRE] Failed to create new connection, waiting:", e.message);
5659
+ const abs = path6.isAbsolute(relPath) ? path6.normalize(relPath) : path6.resolve(this.baseDirAbs, relPath);
5660
+ if (!isPathInside2(this.baseDirAbs, abs)) {
5661
+ return this.baseDirAbs;
5532
5662
  }
5663
+ return abs;
5533
5664
  }
5534
- return new Promise((resolve7, reject) => {
5535
- const timer = setTimeout(() => {
5536
- const idx = this.waitingQueue.findIndex((item) => item.timer === timer);
5537
- if (idx !== -1) {
5538
- this.waitingQueue.splice(idx, 1);
5539
- }
5540
- reject(new Error(`Acquire timeout (${this.config.acquireTimeout}ms)`));
5541
- }, this.config.acquireTimeout);
5542
- this.waitingQueue.push({ resolve: resolve7, reject, timer });
5543
- });
5544
- }
5545
- /** 释放连接回池中 */
5546
- release(conn) {
5547
- if (!conn) return;
5548
- conn.inUse = false;
5549
- conn.lastUsed = Date.now();
5550
- if (this.waitingQueue.length > 0) {
5551
- const next = this.waitingQueue.shift();
5552
- clearTimeout(next.timer);
5553
- conn.inUse = true;
5554
- conn.lastUsed = Date.now();
5555
- next.resolve(conn);
5556
- }
5557
- }
5558
- /** 从池中移除并关闭指定连接 */
5559
- removeConnection(conn) {
5560
- const index = this.pool.indexOf(conn);
5561
- if (index !== -1) {
5562
- this.pool.splice(index, 1);
5563
- conn.close().catch(() => {
5564
- });
5665
+ /** table 与文件名片段拼为平台无关相对路径 */
5666
+ tableFilePath(table, ...segments) {
5667
+ return joinTablePath2(table, ...segments);
5565
5668
  }
5566
- }
5567
- /** 启动空闲连接回收定时器(每 60 秒检查一次) */
5568
- startIdleChecker() {
5569
- this.idleCheckerTimer = setInterval(async () => {
5570
- if (this.isDestroyed) return;
5571
- const now = Date.now();
5572
- const toRemove = [];
5573
- for (const conn of this.pool) {
5574
- if (!conn.inUse && now - conn.lastUsed > this.config.idleTimeout && this.pool.length > this.config.poolMin) {
5575
- toRemove.push(conn);
5576
- }
5577
- }
5578
- for (const conn of toRemove) {
5579
- this.removeConnection(conn);
5580
- }
5581
- if (toRemove.length > 0) {
5582
- this.dbLog("Reclaimed", "[IDLE] Reclaimed", toRemove.length, "idle connections, current pool size:", this.pool.length);
5669
+ normalizeRelPath(relPath) {
5670
+ if (!relPath) {
5671
+ return "";
5583
5672
  }
5584
- }, 6e4);
5585
- }
5586
- /** 获取连接池当前状态 */
5587
- getStatus() {
5588
- const inUse = this.pool.filter((c) => c.inUse).length;
5589
- return {
5590
- total: this.pool.length,
5591
- inUse,
5592
- idle: this.pool.length - inUse,
5593
- waiting: this.waitingQueue.length,
5594
- min: this.config.poolMin,
5595
- max: this.config.poolMax
5596
- };
5597
- }
5598
- /** 销毁连接池,释放所有资源 */
5599
- async destroy() {
5600
- if (this.isDestroyed) return;
5601
- this.isDestroyed = true;
5602
- if (this.idleCheckerTimer) {
5603
- clearInterval(this.idleCheckerTimer);
5604
- this.idleCheckerTimer = null;
5673
+ return path6.isAbsolute(relPath) ? path6.relative(this.baseDirAbs, relPath) : relPath;
5605
5674
  }
5606
- for (const waiter of this.waitingQueue) {
5607
- clearTimeout(waiter.timer);
5608
- waiter.reject(new Error("Pool has been closed"));
5675
+ ensureDir(relPath) {
5676
+ const relative4 = this.normalizeRelPath(relPath);
5677
+ const dirPath = path6.dirname(relative4);
5678
+ const absDir = this.resolvePath(dirPath === "." ? "" : dirPath);
5679
+ if (this.createDir && !fs11.existsSync(absDir)) {
5680
+ this.dbLog("mkdir", "[MKDIR]", absDir);
5681
+ fs11.mkdirSync(absDir, { recursive: true });
5682
+ }
5683
+ return absDir;
5609
5684
  }
5610
- this.waitingQueue = [];
5611
- await Promise.allSettled(this.pool.map((conn) => conn.close()));
5612
- this.pool = [];
5613
- this.dbLog("Destroyed", "[POOL] Destroyed");
5614
- }
5615
- };
5616
- var DbSQLite3 = class {
5617
- constructor(config) {
5618
- this.pool = null;
5619
- this.singleDb = null;
5620
- this.singleDbReady = null;
5621
- /** 串行化同库 CRUD,避免 node-sqlite3 回调并发导致锁等待与连接泄漏 */
5622
- this.opChain = Promise.resolve();
5623
- this.config = config;
5624
- const verbose = sqlite3.verbose();
5625
- if (config.usePool === true) {
5626
- this.pool = new SQLitePool({
5627
- database: config.database,
5628
- poolMin: _nullishCoalesce(config.poolMin, () => ( 1)),
5629
- poolMax: _nullishCoalesce(config.poolMax, () => ( 1)),
5630
- idleTimeout: config.idleTimeout,
5631
- acquireTimeout: _nullishCoalesce(config.acquireTimeout, () => ( DEFAULT_ACQUIRE_TIMEOUT_MS)),
5632
- busyTimeout: _nullishCoalesce(config.busyTimeout, () => ( DEFAULT_BUSY_TIMEOUT_MS)),
5633
- enableCreateTable: config.create,
5634
- $asai: config.$asai
5635
- });
5636
- } else {
5637
- this.singleDbReady = this.initSingleConnection(config.database, verbose);
5685
+ getAbsPath(file, autoCreateDir = true) {
5686
+ let rel = file;
5687
+ if (this.fileExt && !rel.endsWith(this.fileExt)) {
5688
+ rel += this.fileExt;
5689
+ }
5690
+ if (autoCreateDir) {
5691
+ this.ensureDir(rel);
5692
+ }
5693
+ return this.resolvePath(rel);
5638
5694
  }
5639
- }
5640
- static {
5641
- _chunkSMVZ3ZDJcjs.__name.call(void 0, this, "DbSQLite3");
5642
- }
5643
- runSerialized(task) {
5644
- const run = this.opChain.then(() => task());
5645
- this.opChain = run.then(
5646
- () => void 0,
5647
- () => void 0
5648
- );
5649
- return run;
5650
- }
5651
- dbLog(...args) {
5652
- (_optionalChain([this, 'access', _622 => _622.config, 'optionalAccess', _623 => _623.$asai, 'optionalAccess', _624 => _624.$log]) || console.log)("sqlite", ...args);
5653
- }
5654
- async initSingleConnection(databasePath, verbose) {
5655
- const absolutePath = path6.resolve(databasePath);
5656
- const dir = path6.dirname(absolutePath);
5657
- if (!fs11.existsSync(dir)) {
5658
- fs11.mkdirSync(dir, { recursive: true });
5659
- this.dbLog("mkdir", "[MKDIR]", dir);
5660
- }
5661
- return new Promise((resolve7, reject) => {
5662
- this.singleDb = new verbose.Database(absolutePath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, async (err) => {
5663
- if (err) {
5664
- this.dbLog("open failed", "[ERROR] Failed to open single connection:", absolutePath, err.message);
5665
- reject(err);
5666
- return;
5667
- }
5668
- try {
5669
- await configureSqliteConnection(this.singleDb, _nullishCoalesce(this.config.busyTimeout, () => ( DEFAULT_BUSY_TIMEOUT_MS)));
5670
- this.dbLog("open", "[OPEN] Single connection:", absolutePath);
5671
- resolve7();
5672
- } catch (pragmaErr) {
5673
- this.singleDb.close(() => {
5674
- });
5675
- reject(pragmaErr);
5676
- }
5677
- });
5678
- });
5679
- }
5680
- getErr(_sql, err) {
5681
- return _optionalChain([err, 'optionalAccess', _625 => _625.message]) || null;
5682
- }
5683
- getResult(rows) {
5684
- return _nullishCoalesce(rows, () => ( "OK"));
5685
- }
5686
- /**
5687
- * 执行 SQL 查询(回调风格)
5688
- */
5689
- query(sql, callback) {
5690
- const sqlStr = Sql_default.makeSql(sql);
5691
- const executeQuery = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (db, release) => {
5692
- const finish = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (err, rows) => {
5693
- _optionalChain([release, 'optionalCall', _626 => _626()]);
5694
- callback(this.getErr(sql, err), this.getResult(rows));
5695
- }, "finish");
5696
- try {
5697
- if (sql.type === "select") {
5698
- db.all(sqlStr, finish);
5695
+ deldir(relativePath) {
5696
+ const absPath = this.resolvePath(relativePath);
5697
+ if (!fs11.existsSync(absPath)) {
5698
+ return;
5699
+ }
5700
+ this.dbLog("delete", "[RMDIR]", absPath);
5701
+ const entries = fs11.readdirSync(absPath, { withFileTypes: true });
5702
+ for (const entry of entries) {
5703
+ const current = path6.join(absPath, entry.name);
5704
+ if (entry.isDirectory()) {
5705
+ this.deldir(path6.join(relativePath, entry.name));
5699
5706
  } else {
5700
- db.run(sqlStr, (err) => {
5701
- finish(err, "OK");
5702
- });
5707
+ this.dbLog("delete", "[UNLINK]", current);
5708
+ fs11.unlinkSync(current);
5703
5709
  }
5704
- } catch (e) {
5705
- _optionalChain([release, 'optionalCall', _627 => _627()]);
5706
- callback(this.getErr(sql, e), this.getResult("sql error"));
5707
- }
5708
- }, "executeQuery");
5709
- if (this.pool) {
5710
- this.pool.acquire().then((conn) => {
5711
- executeQuery(conn.db, () => this.pool.release(conn));
5712
- }).catch((err) => {
5713
- callback(this.getErr(sql, err), this.getResult("pool error"));
5714
- });
5715
- } else {
5716
- (this.singleDbReady || Promise.resolve()).then(() => {
5717
- executeQuery(this.singleDb);
5718
- }).catch((err) => {
5719
- callback(this.getErr(sql, err), this.getResult("connection error"));
5720
- });
5721
- }
5722
- }
5723
- /** 执行 SQL 操作(Promise 风格,串行 + 缺表时自动建表并重试一次) */
5724
- sqlDb(sql) {
5725
- return this.runSerialized(() => this.executeSqlDb(sql));
5726
- }
5727
- async executeSqlDb(sql) {
5728
- try {
5729
- return await promisifySqlDb(this.query.bind(this), sql);
5730
- } catch (err) {
5731
- const errObj = { message: String(_optionalChain([err, 'optionalAccess', _628 => _628.message]) || err || "") };
5732
- if (this.config.create && sql.type === "insert" && isTableMissingError(errObj)) {
5733
- await this.createTable(sql);
5734
- return promisifySqlDb(this.query.bind(this), sql);
5735
- }
5736
- throw err;
5737
- }
5738
- }
5739
- /**
5740
- * 自动建表(当表不存在时触发)
5741
- */
5742
- async createTable(sql) {
5743
- const createSql = Sql_default.createSql(sql, "sqlite");
5744
- if (!createSql) return;
5745
- if (this.pool) {
5746
- let conn = null;
5747
- try {
5748
- conn = await this.pool.acquire();
5749
- await new Promise((resolve7, reject) => {
5750
- conn.db.run(createSql, (err) => {
5751
- if (err) reject(err);
5752
- else resolve7();
5753
- });
5754
- });
5755
- this.dbLog("Created", "[TABLE] Created:", createSql);
5756
- } catch (e) {
5757
- this.dbLog("Creation failed", "[TABLE] Creation failed:", e);
5758
- } finally {
5759
- if (conn) this.pool.release(conn);
5760
5710
  }
5761
- } else {
5762
- await this.singleDbReady;
5763
- await new Promise((resolve7, reject) => {
5764
- this.singleDb.run(createSql, (err) => {
5765
- if (err) reject(err);
5766
- else resolve7();
5767
- });
5768
- });
5711
+ fs11.rmdirSync(absPath);
5769
5712
  }
5770
- }
5771
- /** 获取连接池状态(仅连接池模式有效) */
5772
- getPoolStatus() {
5773
- if (this.pool) {
5774
- return this.pool.getStatus();
5775
- }
5776
- return { mode: "single-connection" };
5777
- }
5778
- /** 关闭所有连接 */
5779
- async close() {
5780
- if (this.pool) {
5781
- await this.pool.destroy();
5782
- } else if (this.singleDb) {
5783
- await new Promise((resolve7, reject) => {
5784
- this.singleDb.close((err) => {
5785
- if (err) reject(err);
5786
- else resolve7();
5787
- });
5788
- });
5789
- }
5790
- }
5791
- };
5792
- var Index_default3 = DbSQLite3;
5793
-
5794
- // src/sysserver/db/src/file/Index.ts
5795
-
5796
-
5797
- var DbFile = class {
5798
- static {
5799
- _chunkSMVZ3ZDJcjs.__name.call(void 0, this, "DbFile");
5800
- }
5801
- constructor(config) {
5802
- this.config = config;
5803
- this.fileExt = config.ext === ".*" ? "" : config.ext || "";
5804
- this.fileDel = (config.del || 0) !== 0;
5805
- this.createDir = config.create || false;
5806
- this.baseDirAbs = path7.resolve(process.cwd(), config.dir);
5807
- }
5808
- dbLog(...args) {
5809
- (_optionalChain([this, 'access', _629 => _629.config, 'optionalAccess', _630 => _630.$asai, 'optionalAccess', _631 => _631.$log]) || console.log)("FILE", ...args);
5810
- }
5811
- checkFile(file) {
5812
- return fs12.existsSync(this.getAbsPath(file, false));
5813
- }
5814
- /** 解析相对路径并限制在数据根目录内,防止路径穿越(跨平台) */
5815
- resolvePath(relPath) {
5816
- if (!relPath) {
5817
- return this.baseDirAbs;
5818
- }
5819
- const abs = path7.isAbsolute(relPath) ? path7.normalize(relPath) : path7.resolve(this.baseDirAbs, relPath);
5820
- if (!isPathInside(this.baseDirAbs, abs)) {
5821
- return this.baseDirAbs;
5822
- }
5823
- return abs;
5824
- }
5825
- /** 将 table 与文件名片段拼为平台无关相对路径 */
5826
- tableFilePath(table, ...segments) {
5827
- return joinTablePath(table, ...segments);
5828
- }
5829
- normalizeRelPath(relPath) {
5830
- if (!relPath) {
5831
- return "";
5832
- }
5833
- return path7.isAbsolute(relPath) ? path7.relative(this.baseDirAbs, relPath) : relPath;
5834
- }
5835
- ensureDir(relPath) {
5836
- const relative4 = this.normalizeRelPath(relPath);
5837
- const dirPath = path7.dirname(relative4);
5838
- const absDir = this.resolvePath(dirPath === "." ? "" : dirPath);
5839
- if (this.createDir && !fs12.existsSync(absDir)) {
5840
- this.dbLog("mkdir", "[MKDIR]", absDir);
5841
- fs12.mkdirSync(absDir, { recursive: true });
5842
- }
5843
- return absDir;
5844
- }
5845
- getAbsPath(file, autoCreateDir = true) {
5846
- let rel = file;
5847
- if (this.fileExt && !rel.endsWith(this.fileExt)) {
5848
- rel += this.fileExt;
5849
- }
5850
- if (autoCreateDir) {
5851
- this.ensureDir(rel);
5852
- }
5853
- return this.resolvePath(rel);
5854
- }
5855
- deldir(relativePath) {
5856
- const absPath = this.resolvePath(relativePath);
5857
- if (!fs12.existsSync(absPath)) {
5858
- return;
5859
- }
5860
- this.dbLog("delete", "[RMDIR]", absPath);
5861
- const entries = fs12.readdirSync(absPath, { withFileTypes: true });
5862
- for (const entry of entries) {
5863
- const current = path7.join(absPath, entry.name);
5864
- if (entry.isDirectory()) {
5865
- this.deldir(path7.join(relativePath, entry.name));
5713
+ getReadPath(file, sql) {
5714
+ const candidates = [];
5715
+ if (_optionalChain([sql, 'optionalAccess', _647 => _647.filename])) {
5716
+ candidates.push({ dir: path6.join(file, sql.filename) });
5717
+ candidates.push({ dir: path6.join(file + ".delete" + this.fileExt, sql.filename) });
5866
5718
  } else {
5867
- this.dbLog("delete", "[UNLINK]", current);
5868
- fs12.unlinkSync(current);
5719
+ candidates.push({ dir: file });
5720
+ candidates.push({ dir: file + this.fileExt + ".delete" });
5869
5721
  }
5870
- }
5871
- fs12.rmdirSync(absPath);
5872
- }
5873
- getReadPath(file, sql) {
5874
- const candidates = [];
5875
- if (_optionalChain([sql, 'optionalAccess', _632 => _632.filename])) {
5876
- candidates.push({ dir: path7.join(file, sql.filename) });
5877
- candidates.push({ dir: path7.join(file + ".delete" + this.fileExt, sql.filename) });
5878
- } else {
5879
- candidates.push({ dir: file });
5880
- candidates.push({ dir: file + this.fileExt + ".delete" });
5881
- }
5882
- for (const candidate of candidates) {
5883
- const abs = this.getAbsPath(candidate.dir, false);
5884
- if (fs12.existsSync(abs)) {
5885
- return { path: abs, dir: candidate.dir };
5722
+ for (const candidate of candidates) {
5723
+ const abs = this.getAbsPath(candidate.dir, false);
5724
+ if (fs11.existsSync(abs)) {
5725
+ return { path: abs, dir: candidate.dir };
5726
+ }
5886
5727
  }
5728
+ return { path: "", dir: "" };
5887
5729
  }
5888
- return { path: "", dir: "" };
5889
- }
5890
- getDelPath(file, sql) {
5891
- const read2 = this.getReadPath(file, sql);
5892
- if (!read2.path) {
5893
- return { path: "", dir: read2.dir };
5894
- }
5895
- if (_optionalChain([sql, 'optionalAccess', _633 => _633.filename])) {
5896
- return { path: path7.dirname(read2.path), dir: path7.dirname(read2.dir) };
5897
- }
5898
- return { path: read2.path, dir: read2.dir };
5899
- }
5900
- getNewPath(file, sql) {
5901
- if (_optionalChain([sql, 'optionalAccess', _634 => _634.filename])) {
5902
- return this.getAbsPath(path7.join(file, sql.filename), true);
5903
- }
5904
- return this.getAbsPath(file, true);
5905
- }
5906
- write(file, data, sql) {
5907
- try {
5908
- const filePath = _optionalChain([sql, 'optionalAccess', _635 => _635.type]) === "insert" ? this.getNewPath(file, sql) : this.getReadPath(file, sql).path || this.getNewPath(file, sql);
5909
- this.dbLog("write", "[WRITE]", filePath);
5910
- fs12.writeFileSync(filePath, data, "utf8");
5911
- return "ok";
5912
- } catch (e) {
5913
- this.dbLog("write failed", "[WRITE ERROR]", e);
5914
- return e;
5915
- }
5916
- }
5917
- read(file, sql, encoding = "utf8") {
5918
- try {
5730
+ getDelPath(file, sql) {
5919
5731
  const read2 = this.getReadPath(file, sql);
5920
5732
  if (!read2.path) {
5921
- return { error: "empty" };
5733
+ return { path: "", dir: read2.dir };
5734
+ }
5735
+ if (_optionalChain([sql, 'optionalAccess', _648 => _648.filename])) {
5736
+ return { path: path6.dirname(read2.path), dir: path6.dirname(read2.dir) };
5922
5737
  }
5923
- this.dbLog("read", "[READ]", read2.path);
5924
- const data = fs12.readFileSync(read2.path, { encoding }) || "";
5925
- const fileName = this.fileExt && read2.dir.endsWith(this.fileExt) ? read2.dir : read2.dir + this.fileExt;
5926
- return [{ data, file: fileName }];
5927
- } catch (e) {
5928
- this.dbLog("read failed", "[READ ERROR]", e);
5929
- return e;
5738
+ return { path: read2.path, dir: read2.dir };
5930
5739
  }
5931
- }
5932
- del(file, sql) {
5933
- try {
5934
- const del = this.getDelPath(file, sql);
5935
- if (!del.path) {
5936
- return "";
5740
+ getNewPath(file, sql) {
5741
+ if (_optionalChain([sql, 'optionalAccess', _649 => _649.filename])) {
5742
+ return this.getAbsPath(path6.join(file, sql.filename), true);
5937
5743
  }
5938
- if (this.fileDel && _optionalChain([sql, 'optionalAccess', _636 => _636.deltrue])) {
5939
- const target = del.path + ".delete" + this.fileExt;
5940
- this.dbLog("soft delete", "[SOFT DELETE]", `${del.path} -> ${target}`);
5941
- fs12.renameSync(del.path, target);
5942
- } else if (_optionalChain([sql, 'optionalAccess', _637 => _637.filename])) {
5943
- this.deldir(del.dir);
5944
- } else {
5945
- this.dbLog("delete", "[DELETE]", del.path);
5946
- fs12.unlinkSync(del.path);
5744
+ return this.getAbsPath(file, true);
5745
+ }
5746
+ write(file, data, sql) {
5747
+ try {
5748
+ const filePath = _optionalChain([sql, 'optionalAccess', _650 => _650.type]) === "insert" ? this.getNewPath(file, sql) : this.getReadPath(file, sql).path || this.getNewPath(file, sql);
5749
+ this.dbLog("write", "[WRITE]", filePath);
5750
+ fs11.writeFileSync(filePath, data, "utf8");
5751
+ return "ok";
5752
+ } catch (e) {
5753
+ this.dbLog("write failed", "[WRITE ERROR]", e);
5754
+ return e;
5947
5755
  }
5948
- return "ok";
5949
- } catch (e) {
5950
- this.dbLog("delete failed", "[DELETE ERROR]", e);
5951
- return e;
5952
5756
  }
5953
- }
5954
- re(file, sql) {
5955
- try {
5956
- const del = this.getDelPath(file, sql);
5957
- if (!del.path) {
5958
- return "";
5757
+ read(file, sql, encoding = "utf8") {
5758
+ try {
5759
+ const read2 = this.getReadPath(file, sql);
5760
+ if (!read2.path) {
5761
+ return { error: "empty" };
5762
+ }
5763
+ this.dbLog("read", "[READ]", read2.path);
5764
+ const data = fs11.readFileSync(read2.path, { encoding }) || "";
5765
+ const fileName = this.fileExt && read2.dir.endsWith(this.fileExt) ? read2.dir : read2.dir + this.fileExt;
5766
+ return [{ data, file: fileName }];
5767
+ } catch (e) {
5768
+ this.dbLog("read failed", "[READ ERROR]", e);
5769
+ return e;
5959
5770
  }
5960
- if (this.fileDel) {
5961
- const extPattern = this.fileExt ? this.fileExt.replace(/\./g, "\\.") : "";
5962
- const original = del.path.replace(new RegExp(`.delete${extPattern}$`), "");
5963
- if (original !== del.path) {
5964
- this.dbLog("restore", "[RESTORE]", `${del.path} -> ${original}`);
5965
- fs12.renameSync(del.path, original);
5771
+ }
5772
+ del(file, sql) {
5773
+ try {
5774
+ const del = this.getDelPath(file, sql);
5775
+ if (!del.path) {
5776
+ return "";
5966
5777
  }
5967
- } else {
5968
- this.dbLog("force delete", "[FORCE DELETE]", del.path);
5969
- fs12.unlinkSync(del.path);
5778
+ if (this.fileDel && _optionalChain([sql, 'optionalAccess', _651 => _651.deltrue])) {
5779
+ const target = del.path + ".delete" + this.fileExt;
5780
+ this.dbLog("soft delete", "[SOFT DELETE]", `${del.path} -> ${target}`);
5781
+ fs11.renameSync(del.path, target);
5782
+ } else if (_optionalChain([sql, 'optionalAccess', _652 => _652.filename])) {
5783
+ this.deldir(del.dir);
5784
+ } else {
5785
+ this.dbLog("delete", "[DELETE]", del.path);
5786
+ fs11.unlinkSync(del.path);
5787
+ }
5788
+ return "ok";
5789
+ } catch (e) {
5790
+ this.dbLog("delete failed", "[DELETE ERROR]", e);
5791
+ return e;
5970
5792
  }
5971
- return "ok";
5972
- } catch (e) {
5973
- this.dbLog("restore failed", "[RESTORE ERROR]", e);
5974
- return e;
5975
5793
  }
5976
- }
5977
- list(dir, sql) {
5978
- try {
5979
- const absDir = this.resolvePath(dir);
5980
- this.dbLog("list", "[LIST]", absDir);
5981
- let entries;
5794
+ re(file, sql) {
5982
5795
  try {
5983
- entries = fs12.readdirSync(absDir, { withFileTypes: true });
5984
- } catch (e40) {
5985
- return _optionalChain([sql, 'optionalAccess', _638 => _638.list]) ? { open: [], delete: [] } : [];
5796
+ const del = this.getDelPath(file, sql);
5797
+ if (!del.path) {
5798
+ return "";
5799
+ }
5800
+ if (this.fileDel) {
5801
+ const extPattern = this.fileExt ? this.fileExt.replace(/\./g, "\\.") : "";
5802
+ const original = del.path.replace(new RegExp(`.delete${extPattern}$`), "");
5803
+ if (original !== del.path) {
5804
+ this.dbLog("restore", "[RESTORE]", `${del.path} -> ${original}`);
5805
+ fs11.renameSync(del.path, original);
5806
+ }
5807
+ } else {
5808
+ this.dbLog("force delete", "[FORCE DELETE]", del.path);
5809
+ fs11.unlinkSync(del.path);
5810
+ }
5811
+ return "ok";
5812
+ } catch (e) {
5813
+ this.dbLog("restore failed", "[RESTORE ERROR]", e);
5814
+ return e;
5986
5815
  }
5987
- const result = { open: [], delete: [] };
5988
- const deleteSuffix = ".delete" + this.fileExt;
5989
- for (const entry of entries) {
5990
- if (!entry.isFile()) continue;
5991
- const fileName = entry.name;
5992
- const isDelete = fileName.endsWith(deleteSuffix);
5993
- const baseName = isDelete ? fileName.slice(0, -deleteSuffix.length) : fileName;
5994
- if (this.fileExt && !baseName.endsWith(this.fileExt)) continue;
5995
- const fullPath = path7.join(absDir, fileName);
5816
+ }
5817
+ list(dir, sql) {
5818
+ try {
5819
+ const absDir = this.resolvePath(dir);
5820
+ this.dbLog("list", "[LIST]", absDir);
5821
+ let entries;
5996
5822
  try {
5997
- const data = fs12.readFileSync(fullPath, "utf8");
5998
- const entryData = { data, file: baseName };
5999
- if (isDelete) {
6000
- if (_optionalChain([sql, 'optionalAccess', _639 => _639.list])) result.delete.push(entryData);
6001
- } else {
6002
- result.open.push(entryData);
5823
+ entries = fs11.readdirSync(absDir, { withFileTypes: true });
5824
+ } catch (e48) {
5825
+ return _optionalChain([sql, 'optionalAccess', _653 => _653.list]) ? { open: [], delete: [] } : [];
5826
+ }
5827
+ const result = { open: [], delete: [] };
5828
+ const deleteSuffix = ".delete" + this.fileExt;
5829
+ for (const entry of entries) {
5830
+ if (!entry.isFile()) continue;
5831
+ const fileName = entry.name;
5832
+ const isDelete = fileName.endsWith(deleteSuffix);
5833
+ const baseName = isDelete ? fileName.slice(0, -deleteSuffix.length) : fileName;
5834
+ if (this.fileExt && !baseName.endsWith(this.fileExt)) continue;
5835
+ const fullPath = path6.join(absDir, fileName);
5836
+ try {
5837
+ const data = fs11.readFileSync(fullPath, "utf8");
5838
+ const entryData = { data, file: baseName };
5839
+ if (isDelete) {
5840
+ if (_optionalChain([sql, 'optionalAccess', _654 => _654.list])) result.delete.push(entryData);
5841
+ } else {
5842
+ result.open.push(entryData);
5843
+ }
5844
+ } catch (e49) {
6003
5845
  }
6004
- } catch (e41) {
6005
5846
  }
5847
+ return _optionalChain([sql, 'optionalAccess', _655 => _655.list]) ? result : result.open;
5848
+ } catch (e) {
5849
+ this.dbLog("list failed", "[LIST ERROR]", e);
5850
+ return e;
6006
5851
  }
6007
- return _optionalChain([sql, 'optionalAccess', _640 => _640.list]) ? result : result.open;
6008
- } catch (e) {
6009
- this.dbLog("list failed", "[LIST ERROR]", e);
6010
- return e;
6011
5852
  }
6012
- }
6013
- /** 从 where 首条条件中提取文件名(去掉 SQL 风格引号) */
6014
- getFileNameFromWhere(where) {
6015
- if (!where || !Array.isArray(where)) return "";
6016
- const first = where.find((item) => Array.isArray(item));
6017
- const raw = _optionalChain([first, 'optionalAccess', _641 => _641[2]]);
6018
- if (typeof raw === "string") {
6019
- return raw.replace(/^'+|'+$/g, "");
5853
+ /** 从 where 首条条件中提取文件名(去掉 SQL 风格引号) */
5854
+ getFileNameFromWhere(where) {
5855
+ if (!where || !Array.isArray(where)) return "";
5856
+ const first = where.find((item) => Array.isArray(item));
5857
+ const raw = _optionalChain([first, 'optionalAccess', _656 => _656[2]]);
5858
+ if (typeof raw === "string") {
5859
+ return raw.replace(/^'+|'+$/g, "");
5860
+ }
5861
+ return String(_nullishCoalesce(raw, () => ( "")));
6020
5862
  }
6021
- return String(_nullishCoalesce(raw, () => ( "")));
6022
- }
6023
- sqlDb(sql) {
6024
- return new Promise((resolve7, reject) => {
6025
- try {
6026
- let result;
6027
- const tableDir = this.tableFilePath(sql.table);
6028
- if (sql.type === "insert") {
6029
- const [file, data] = sql.value[0];
6030
- result = this.write(this.tableFilePath(sql.table, file), data, sql);
6031
- } else if (sql.type === "delete") {
6032
- const file = this.getFileNameFromWhere(sql.where);
6033
- result = this.del(this.tableFilePath(sql.table, file), sql);
6034
- } else if (sql.type === "re") {
6035
- const file = this.getFileNameFromWhere(sql.where);
6036
- result = this.re(this.tableFilePath(sql.table, file), sql);
6037
- } else if (sql.type === "update") {
6038
- const file = this.getFileNameFromWhere(sql.where);
6039
- const data = sql.set[0][1];
6040
- result = this.write(this.tableFilePath(sql.table, file), data, sql);
6041
- } else if (sql.type === "select") {
6042
- if (_optionalChain([sql, 'optionalAccess', _642 => _642.where, 'optionalAccess', _643 => _643.length]) && _optionalChain([sql, 'optionalAccess', _644 => _644.as]) !== 2) {
5863
+ sqlDb(sql) {
5864
+ return new Promise((resolve6, reject) => {
5865
+ try {
5866
+ let result;
5867
+ const tableDir = this.tableFilePath(sql.table);
5868
+ if (sql.type === "insert") {
5869
+ const [file, data] = sql.value[0];
5870
+ result = this.write(this.tableFilePath(sql.table, file), data, sql);
5871
+ } else if (sql.type === "delete") {
6043
5872
  const file = this.getFileNameFromWhere(sql.where);
6044
- const readRes = this.read(this.tableFilePath(sql.table, file), sql);
6045
- const resObj = {};
6046
- if (_optionalChain([readRes, 'optionalAccess', _645 => _645[0], 'optionalAccess', _646 => _646.file]) && !readRes.error) {
6047
- if (sql.as === 1) {
6048
- try {
6049
- const parsed = JSON.parse(readRes[0].data);
6050
- if (_optionalChain([sql, 'access', _647 => _647.field, 'optionalAccess', _648 => _648.length])) {
6051
- sql.field.forEach((f) => {
6052
- resObj[f] = _nullishCoalesce(parsed[f], () => ( ""));
6053
- });
6054
- } else {
6055
- Object.assign(resObj, parsed);
5873
+ result = this.del(this.tableFilePath(sql.table, file), sql);
5874
+ } else if (sql.type === "re") {
5875
+ const file = this.getFileNameFromWhere(sql.where);
5876
+ result = this.re(this.tableFilePath(sql.table, file), sql);
5877
+ } else if (sql.type === "update") {
5878
+ const file = this.getFileNameFromWhere(sql.where);
5879
+ const data = sql.set[0][1];
5880
+ result = this.write(this.tableFilePath(sql.table, file), data, sql);
5881
+ } else if (sql.type === "select") {
5882
+ if (_optionalChain([sql, 'optionalAccess', _657 => _657.where, 'optionalAccess', _658 => _658.length]) && _optionalChain([sql, 'optionalAccess', _659 => _659.as]) !== 2) {
5883
+ const file = this.getFileNameFromWhere(sql.where);
5884
+ const readRes = this.read(this.tableFilePath(sql.table, file), sql);
5885
+ const resObj = {};
5886
+ if (_optionalChain([readRes, 'optionalAccess', _660 => _660[0], 'optionalAccess', _661 => _661.file]) && !readRes.error) {
5887
+ if (sql.as === 1) {
5888
+ try {
5889
+ const parsed = JSON.parse(readRes[0].data);
5890
+ if (_optionalChain([sql, 'access', _662 => _662.field, 'optionalAccess', _663 => _663.length])) {
5891
+ sql.field.forEach((f) => {
5892
+ resObj[f] = _nullishCoalesce(parsed[f], () => ( ""));
5893
+ });
5894
+ } else {
5895
+ Object.assign(resObj, parsed);
5896
+ }
5897
+ } catch (e50) {
5898
+ }
5899
+ } else {
5900
+ const fields = sql.field;
5901
+ resObj[fields[0]] = readRes[0].file;
5902
+ if (fields[1]) {
5903
+ resObj[fields[1]] = readRes[0].data;
6056
5904
  }
6057
- } catch (e42) {
6058
- }
6059
- } else {
6060
- const fields = sql.field;
6061
- resObj[fields[0]] = readRes[0].file;
6062
- if (fields[1]) {
6063
- resObj[fields[1]] = readRes[0].data;
6064
5905
  }
6065
5906
  }
6066
- }
6067
- result = [resObj];
6068
- } else {
6069
- const listRes = this.list(tableDir, sql);
6070
- if (listRes && !listRes.error) {
6071
- if (_optionalChain([sql, 'optionalAccess', _649 => _649.list])) {
6072
- const mapEntry = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (el) => {
6073
- const fields = sql.field;
6074
- const item = { [fields[0]]: el.file };
6075
- if (fields[1]) item[fields[1]] = el.data;
6076
- return item;
6077
- }, "mapEntry");
6078
- if (listRes.open) listRes.open = listRes.open.map(mapEntry);
6079
- if (listRes.delete) listRes.delete = listRes.delete.map(mapEntry);
6080
- result = listRes;
6081
- } else {
6082
- if (_optionalChain([sql, 'optionalAccess', _650 => _650.as]) === 2) {
6083
- let items = listRes;
6084
- if (_optionalChain([sql, 'access', _651 => _651.where, 'optionalAccess', _652 => _652.length])) {
6085
- const where = sql.where;
6086
- const whereType = typeof where[0] === "string" ? where[0] : "and";
6087
- items = items.filter((el) => {
6088
- let match = whereType === "and";
6089
- for (let i = 0; i < where.length; i++) {
6090
- if (typeof where[i] === "string") continue;
6091
- const cond = where[i];
6092
- if (!cond) continue;
6093
- const field = cond[0];
6094
- const searchVal = String(cond[2]).replace(/%/g, "");
6095
- let fieldVal = "";
6096
- try {
6097
- fieldVal = _nullishCoalesce(JSON.parse(el.data)[field], () => ( ""));
6098
- } catch (e43) {
5907
+ result = [resObj];
5908
+ } else {
5909
+ const listRes = this.list(tableDir, sql);
5910
+ if (listRes && !listRes.error) {
5911
+ if (_optionalChain([sql, 'optionalAccess', _664 => _664.list])) {
5912
+ const mapEntry = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (el) => {
5913
+ const fields = sql.field;
5914
+ const item = { [fields[0]]: el.file };
5915
+ if (fields[1]) item[fields[1]] = el.data;
5916
+ return item;
5917
+ }, "mapEntry");
5918
+ if (listRes.open) listRes.open = listRes.open.map(mapEntry);
5919
+ if (listRes.delete) listRes.delete = listRes.delete.map(mapEntry);
5920
+ result = listRes;
5921
+ } else {
5922
+ if (_optionalChain([sql, 'optionalAccess', _665 => _665.as]) === 2) {
5923
+ let items = listRes;
5924
+ if (_optionalChain([sql, 'access', _666 => _666.where, 'optionalAccess', _667 => _667.length])) {
5925
+ const where = sql.where;
5926
+ const whereType = typeof where[0] === "string" ? where[0] : "and";
5927
+ items = items.filter((el) => {
5928
+ let match = whereType === "and";
5929
+ for (let i = 0; i < where.length; i++) {
5930
+ if (typeof where[i] === "string") continue;
5931
+ const cond = where[i];
5932
+ if (!cond) continue;
5933
+ const field = cond[0];
5934
+ const searchVal = String(cond[2]).replace(/%/g, "");
5935
+ let fieldVal = "";
5936
+ try {
5937
+ fieldVal = _nullishCoalesce(JSON.parse(el.data)[field], () => ( ""));
5938
+ } catch (e51) {
5939
+ }
5940
+ const condMatch = String(fieldVal).includes(searchVal);
5941
+ if (whereType === "and") {
5942
+ match = match && condMatch;
5943
+ if (!match) break;
5944
+ } else {
5945
+ match = match || condMatch;
5946
+ if (match) break;
5947
+ }
6099
5948
  }
6100
- const condMatch = String(fieldVal).includes(searchVal);
6101
- if (whereType === "and") {
6102
- match = match && condMatch;
6103
- if (!match) break;
5949
+ return match;
5950
+ });
5951
+ }
5952
+ items = items.map((el) => {
5953
+ const obj = {};
5954
+ try {
5955
+ const parsed = JSON.parse(el.data);
5956
+ if (_optionalChain([sql, 'access', _668 => _668.field, 'optionalAccess', _669 => _669.length])) {
5957
+ sql.field.forEach((f) => {
5958
+ obj[f] = _nullishCoalesce(parsed[f], () => ( ""));
5959
+ });
6104
5960
  } else {
6105
- match = match || condMatch;
6106
- if (match) break;
5961
+ Object.assign(obj, parsed);
6107
5962
  }
5963
+ } catch (e52) {
6108
5964
  }
6109
- return match;
5965
+ return obj;
6110
5966
  });
6111
- }
6112
- items = items.map((el) => {
6113
- const obj = {};
6114
- try {
6115
- const parsed = JSON.parse(el.data);
6116
- if (_optionalChain([sql, 'access', _653 => _653.field, 'optionalAccess', _654 => _654.length])) {
6117
- sql.field.forEach((f) => {
6118
- obj[f] = _nullishCoalesce(parsed[f], () => ( ""));
6119
- });
6120
- } else {
6121
- Object.assign(obj, parsed);
6122
- }
6123
- } catch (e44) {
5967
+ if (_optionalChain([sql, 'access', _670 => _670.order, 'optionalAccess', _671 => _671.length])) {
5968
+ const orderField = sql.order[0];
5969
+ const orderFieldName = typeof orderField === "string" ? orderField : orderField[0];
5970
+ const direction = typeof orderField === "string" ? "ASC" : String(orderField[1]).toUpperCase();
5971
+ items.sort((a, b) => {
5972
+ const valA = String(_nullishCoalesce(a[orderFieldName], () => ( "")));
5973
+ const valB = String(_nullishCoalesce(b[orderFieldName], () => ( "")));
5974
+ const cmp = valA.localeCompare(valB);
5975
+ return direction === "DESC" ? -cmp : cmp;
5976
+ });
6124
5977
  }
6125
- return obj;
6126
- });
6127
- if (_optionalChain([sql, 'access', _655 => _655.order, 'optionalAccess', _656 => _656.length])) {
6128
- const orderField = sql.order[0];
6129
- const orderFieldName = typeof orderField === "string" ? orderField : orderField[0];
6130
- const direction = typeof orderField === "string" ? "ASC" : String(orderField[1]).toUpperCase();
6131
- items.sort((a, b) => {
6132
- const valA = String(_nullishCoalesce(a[orderFieldName], () => ( "")));
6133
- const valB = String(_nullishCoalesce(b[orderFieldName], () => ( "")));
6134
- const cmp = valA.localeCompare(valB);
6135
- return direction === "DESC" ? -cmp : cmp;
6136
- });
5978
+ result = items;
5979
+ } else {
5980
+ const fields = sql.field;
5981
+ result = listRes.map((el) => ({
5982
+ [fields[0]]: el.file,
5983
+ ...fields[1] ? { [fields[1]]: el.data } : {}
5984
+ }));
6137
5985
  }
6138
- result = items;
6139
- } else {
6140
- const fields = sql.field;
6141
- result = listRes.map((el) => ({
6142
- [fields[0]]: el.file,
6143
- ...fields[1] ? { [fields[1]]: el.data } : {}
6144
- }));
6145
5986
  }
5987
+ } else {
5988
+ result = _optionalChain([sql, 'optionalAccess', _672 => _672.list]) ? { open: [], delete: [] } : [];
6146
5989
  }
6147
- } else {
6148
- result = _optionalChain([sql, 'optionalAccess', _657 => _657.list]) ? { open: [], delete: [] } : [];
6149
5990
  }
6150
5991
  }
5992
+ if (result !== void 0) {
5993
+ resolve6(result);
5994
+ } else {
5995
+ reject("");
5996
+ }
5997
+ } catch (e) {
5998
+ reject(e);
6151
5999
  }
6152
- if (result !== void 0) {
6153
- resolve7(result);
6154
- } else {
6155
- reject("");
6156
- }
6157
- } catch (e) {
6158
- reject(e);
6159
- }
6160
- });
6000
+ });
6001
+ }
6161
6002
  }
6162
- };
6163
- var Index_default4 = DbFile;
6003
+ return DbFile;
6004
+ }
6005
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, dbDriver, "dbDriver");
6006
+ var Index_default2 = dbDriver;
6164
6007
 
6165
6008
  // src/sysserver/db/db.ts
6166
- var DRIVERS = {
6167
- mysql: Index_default2,
6168
- sqlite: Index_default3,
6169
- file: Index_default4
6170
- };
6171
- function initDb(type = "file", config = {}) {
6172
- const Driver = DRIVERS[type];
6173
- if (Driver) {
6174
- return new Driver(config);
6009
+ var BUILTIN_FILE = "file";
6010
+ function buildFileDriver() {
6011
+ return Index_default2({ IdbType: {}, Sql: Sql_default, DbCommon: common_exports });
6012
+ }
6013
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, buildFileDriver, "buildFileDriver");
6014
+ function resolveDriver(type, dbDrivers) {
6015
+ if (type === BUILTIN_FILE) {
6016
+ return buildFileDriver();
6017
+ }
6018
+ const factory = dbDrivers[type];
6019
+ if (typeof factory !== "function") {
6020
+ return null;
6175
6021
  }
6176
- return {};
6022
+ return factory({ IdbType: {}, Sql: Sql_default, DbCommon: common_exports });
6177
6023
  }
6178
- _chunkSMVZ3ZDJcjs.__name.call(void 0, initDb, "initDb");
6024
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, resolveDriver, "resolveDriver");
6025
+ var initDb = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, (type = BUILTIN_FILE, config = {}, dbDrivers = {}) => {
6026
+ let Driver = resolveDriver(type, dbDrivers);
6027
+ if (!Driver) {
6028
+ if (type !== BUILTIN_FILE) {
6029
+ console.warn(
6030
+ `[initDb] \u672A\u6CE8\u518C\u9A71\u52A8 "${type}"\uFF08\u8BF7\u5728 sysserver($asai, { db: { ${type}: driver } }) \u6302\u8F7D\uFF09\uFF0C\u5DF2\u56DE\u9000 file \u5B58\u50A8`
6031
+ );
6032
+ }
6033
+ Driver = buildFileDriver();
6034
+ }
6035
+ return new Driver(config);
6036
+ }, "initDb");
6179
6037
  var db_default = initDb;
6180
6038
 
6181
6039
  // src/sysserver/index.ts
6182
- var sysserver_default = /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai) => {
6040
+ function sysserver($asai, opt = {}) {
6183
6041
  if (!$asai.$lib) $asai.$lib = {};
6042
+ $asai.$lib = { ...lib_default, ...$asai.$lib, ...opt || {} };
6184
6043
  $asai.dataserver = db_default;
6185
- $asai.$lib = { ...lib_default, ...$asai.$lib };
6186
- if (!$asai.asaifs) {
6187
- $asai.asaifs = $asai.$lib.AsFs;
6188
- }
6189
- _optionalChain([$asai, 'access', _658 => _658.$lib, 'access', _659 => _659.ErrorCode, 'optionalAccess', _660 => _660.loadErrorCodes, 'optionalCall', _661 => _661($asai)]);
6044
+ _optionalChain([$asai, 'access', _673 => _673.$lib, 'access', _674 => _674.ErrorCode, 'optionalAccess', _675 => _675.loadErrorCodes, 'optionalCall', _676 => _676($asai)]);
6190
6045
  if (!$asai.$lib.api) $asai.$lib.api = {};
6191
6046
  $asai.$lib.api = { ...api_default, ...$asai.$lib.api };
6192
6047
  if (!$asai.$lib.ws) $asai.$lib.ws = {};
6193
6048
  $asai.$lib.ws = { ...ws_default, ...$asai.$lib.ws };
6194
- }, "default");
6049
+ }
6050
+ _chunkSMVZ3ZDJcjs.__name.call(void 0, sysserver, "sysserver");
6195
6051
 
6196
6052
  // src/config/validate.ts
6197
6053
  function normalizeHostConfig(cfg) {
@@ -6306,6 +6162,12 @@ function normalizeUserStoreConfig(cfg) {
6306
6162
  } else if (store.type === "sqlite") {
6307
6163
  if (!store.opt.database) store.opt.database = "./webdata/webdb/users/users.db";
6308
6164
  if (store.opt.create == null) store.opt.create = 1;
6165
+ } else if (store.type === "mysql") {
6166
+ if (!store.opt.host) store.opt.host = "127.0.0.1";
6167
+ if (!store.opt.user) store.opt.user = "root";
6168
+ if (store.opt.password == null) store.opt.password = "";
6169
+ if (!store.opt.database) store.opt.database = "asai";
6170
+ if (store.opt.create == null) store.opt.create = 1;
6309
6171
  }
6310
6172
  }
6311
6173
  _chunkSMVZ3ZDJcjs.__name.call(void 0, normalizeUserStoreConfig, "normalizeUserStoreConfig");
@@ -6348,7 +6210,31 @@ function normalizeDataStoresConfig(cfg) {
6348
6210
  if (!stores.user && cfg.userStore) {
6349
6211
  stores.user = { type: cfg.userStore.type || "file", opt: { ...cfg.userStore.opt || {} } };
6350
6212
  }
6351
- if (!stores.log && _optionalChain([cfg, 'access', _662 => _662.logger, 'optionalAccess', _663 => _663.store])) {
6213
+ if (!stores.user) {
6214
+ stores.user = {
6215
+ type: "file",
6216
+ opt: { dir: "webdata/webdb/users/", ext: ".json", create: 1 }
6217
+ };
6218
+ }
6219
+ if (stores.user && typeof stores.user === "object") {
6220
+ const userStore = stores.user;
6221
+ const userType = userStore.type || "file";
6222
+ if (!userStore.type) userStore.type = "file";
6223
+ if (!userStore.opt || typeof userStore.opt !== "object") userStore.opt = {};
6224
+ if (userType === "file") {
6225
+ if (!userStore.opt.dir) userStore.opt.dir = "webdata/webdb/users/";
6226
+ if (!userStore.opt.ext) userStore.opt.ext = ".json";
6227
+ } else if (userType === "sqlite") {
6228
+ if (!userStore.opt.database) userStore.opt.database = "./webdata/webdb/users/users.db";
6229
+ } else if (userType === "mysql") {
6230
+ if (!userStore.opt.host) userStore.opt.host = "127.0.0.1";
6231
+ if (!userStore.opt.user) userStore.opt.user = "root";
6232
+ if (userStore.opt.password == null) userStore.opt.password = "";
6233
+ if (!userStore.opt.database) userStore.opt.database = "asai";
6234
+ }
6235
+ if (userStore.opt.create == null) userStore.opt.create = 1;
6236
+ }
6237
+ if (!stores.log && _optionalChain([cfg, 'access', _677 => _677.logger, 'optionalAccess', _678 => _678.store])) {
6352
6238
  const s = cfg.logger.store;
6353
6239
  stores.log = {
6354
6240
  type: s.type || "file",
@@ -6412,13 +6298,13 @@ function validateHostConfig(cfg) {
6412
6298
  if (cfg.asaisn != null) {
6413
6299
  errors.push("asaisn \u7981\u6B62\u5199\u5165 asaihost.json\uFF0C\u8BF7\u4F7F\u7528 ASAI_ASAISN");
6414
6300
  }
6415
- if (_optionalChain([cfg, 'access', _664 => _664.aes, 'optionalAccess', _665 => _665.keybase64]) != null) {
6301
+ if (_optionalChain([cfg, 'access', _679 => _679.aes, 'optionalAccess', _680 => _680.keybase64]) != null) {
6416
6302
  errors.push("aes.keybase64 \u7981\u6B62\u5199\u5165 asaihost.json\uFF0C\u8BF7\u4F7F\u7528 ASAI_AES_KEYBASE64");
6417
6303
  }
6418
- if (_optionalChain([cfg, 'access', _666 => _666.httpscert, 'optionalAccess', _667 => _667.key]) != null || _optionalChain([cfg, 'access', _668 => _668.httpscert, 'optionalAccess', _669 => _669.cert]) != null) {
6304
+ if (_optionalChain([cfg, 'access', _681 => _681.httpscert, 'optionalAccess', _682 => _682.key]) != null || _optionalChain([cfg, 'access', _683 => _683.httpscert, 'optionalAccess', _684 => _684.cert]) != null) {
6419
6305
  errors.push("httpscert.key/cert \u7981\u6B62\u5185\u8054\u4E8E asaihost.json\uFF0C\u8BF7\u4F7F\u7528 keyPath/certPath \u6216\u73AF\u5883\u53D8\u91CF");
6420
6306
  }
6421
- if (_optionalChain([cfg, 'access', _670 => _670.security, 'optionalAccess', _671 => _671.sessionSecret]) != null) {
6307
+ if (_optionalChain([cfg, 'access', _685 => _685.security, 'optionalAccess', _686 => _686.sessionSecret]) != null) {
6422
6308
  errors.push("security.sessionSecret \u7981\u6B62\u5199\u5165 asaihost.json\uFF0C\u8BF7\u4F7F\u7528 ASAI_SESSION_SECRET");
6423
6309
  }
6424
6310
  if (Array.isArray(cfg.wssec) && typeof cfg.wssec[0] === "string" && cfg.wssec[0].length > 0) {
@@ -6473,10 +6359,10 @@ function validateHostConfig(cfg) {
6473
6359
  validateHostSiteLimits(name, h, errors);
6474
6360
  }
6475
6361
  }
6476
- if (_optionalChain([cfg, 'access', _672 => _672.logger, 'optionalAccess', _673 => _673.sample]) && typeof cfg.logger.sample !== "object") {
6362
+ if (_optionalChain([cfg, 'access', _687 => _687.logger, 'optionalAccess', _688 => _688.sample]) && typeof cfg.logger.sample !== "object") {
6477
6363
  errors.push('logger.sample \u5FC5\u987B\u4E3A\u5BF9\u8C61\uFF08\u5982 { "REQ_OTHER": 0.1 }\uFF09');
6478
6364
  }
6479
- if (_optionalChain([cfg, 'access', _674 => _674.logger, 'optionalAccess', _675 => _675.skip]) != null && !Array.isArray(cfg.logger.skip)) {
6365
+ if (_optionalChain([cfg, 'access', _689 => _689.logger, 'optionalAccess', _690 => _690.skip]) != null && !Array.isArray(cfg.logger.skip)) {
6480
6366
  errors.push('logger.skip \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\u6570\u7EC4\uFF08\u5982 ["/sys/info/metrics"]\uFF09');
6481
6367
  }
6482
6368
  if (cfg.proxyhosts && typeof cfg.proxyhosts === "object") {
@@ -6510,7 +6396,7 @@ _chunkSMVZ3ZDJcjs.__name.call(void 0, validateHostSiteLimits, "validateHostSiteL
6510
6396
  function validateProductionSecurity(cfg) {
6511
6397
  const errors = [];
6512
6398
  if (process.env.NODE_ENV !== "production") return errors;
6513
- const sec = _optionalChain([cfg, 'optionalAccess', _676 => _676.security]);
6399
+ const sec = _optionalChain([cfg, 'optionalAccess', _691 => _691.security]);
6514
6400
  if (!sec || typeof sec !== "object") {
6515
6401
  errors.push("\u751F\u4EA7\u73AF\u5883\u5FC5\u987B\u914D\u7F6E security \u5BF9\u8C61");
6516
6402
  return errors;
@@ -6521,7 +6407,7 @@ function validateProductionSecurity(cfg) {
6521
6407
  if (sec.allowRegister === 1) {
6522
6408
  errors.push("\u751F\u4EA7\u73AF\u5883 security.allowRegister \u5E94\u4E3A 0\uFF08CR 1.3 \u7981\u6B62\u5F00\u653E\u6CE8\u518C\uFF09");
6523
6409
  }
6524
- if (!_optionalChain([sec, 'access', _677 => _677.quota, 'optionalAccess', _678 => _678.enabled])) {
6410
+ if (!_optionalChain([sec, 'access', _692 => _692.quota, 'optionalAccess', _693 => _693.enabled])) {
6525
6411
  errors.push("\u751F\u4EA7\u73AF\u5883 security.quota.enabled \u5E94\u4E3A 1\uFF08CR 7.1 \u8D44\u6E90\u9650\u5236\uFF09");
6526
6412
  }
6527
6413
  if (sec.csp !== 1) {
@@ -6530,7 +6416,7 @@ function validateProductionSecurity(cfg) {
6530
6416
  if (typeof sec.minUserLevel !== "number" || sec.minUserLevel < 0) {
6531
6417
  errors.push("\u751F\u4EA7\u73AF\u5883 security.minUserLevel \u5E94\u663E\u5F0F\u914D\u7F6E");
6532
6418
  }
6533
- if (sec.forceWss === 1 && !_optionalChain([cfg, 'optionalAccess', _679 => _679.httpscert, 'optionalAccess', _680 => _680.keyPath]) && !_optionalChain([cfg, 'optionalAccess', _681 => _681.httpscert, 'optionalAccess', _682 => _682.key])) {
6419
+ if (sec.forceWss === 1 && !_optionalChain([cfg, 'optionalAccess', _694 => _694.httpscert, 'optionalAccess', _695 => _695.keyPath]) && !_optionalChain([cfg, 'optionalAccess', _696 => _696.httpscert, 'optionalAccess', _697 => _697.key])) {
6534
6420
  errors.push("\u751F\u4EA7\u73AF\u5883 security.forceWss=1 \u65F6\u9700\u914D\u7F6E HTTPS \u8BC1\u4E66");
6535
6421
  }
6536
6422
  return errors;
@@ -6549,12 +6435,12 @@ var DEFAULT_RECONNECT = {
6549
6435
  rs485: { enabled: true, maxRetries: 60, initialDelay: 3e3, maxDelay: 3e4, factor: 2 }
6550
6436
  };
6551
6437
  function getTransportBlock(cfg, kind) {
6552
- const block = _optionalChain([cfg, 'optionalAccess', _683 => _683[kind]]);
6438
+ const block = _optionalChain([cfg, 'optionalAccess', _698 => _698[kind]]);
6553
6439
  return block && typeof block === "object" ? block : null;
6554
6440
  }
6555
6441
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getTransportBlock, "getTransportBlock");
6556
6442
  function getTransportDefault(cfg, kind) {
6557
- const def = _optionalChain([getTransportBlock, 'call', _684 => _684(cfg, kind), 'optionalAccess', _685 => _685.default]);
6443
+ const def = _optionalChain([getTransportBlock, 'call', _699 => _699(cfg, kind), 'optionalAccess', _700 => _700.default]);
6558
6444
  return def && typeof def === "object" ? def : null;
6559
6445
  }
6560
6446
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getTransportDefault, "getTransportDefault");
@@ -6564,7 +6450,7 @@ function hasTransportDefault(cfg, kind) {
6564
6450
  _chunkSMVZ3ZDJcjs.__name.call(void 0, hasTransportDefault, "hasTransportDefault");
6565
6451
  function getDefaultConnId(cfg, kind) {
6566
6452
  const def = getTransportDefault(cfg, kind);
6567
- const id = _optionalChain([def, 'optionalAccess', _686 => _686.id]);
6453
+ const id = _optionalChain([def, 'optionalAccess', _701 => _701.id]);
6568
6454
  return typeof id === "string" && id.length > 0 ? id : DEFAULT_CONN_ID[kind];
6569
6455
  }
6570
6456
  _chunkSMVZ3ZDJcjs.__name.call(void 0, getDefaultConnId, "getDefaultConnId");
@@ -6575,14 +6461,14 @@ function shouldAutoConnect(def) {
6575
6461
  _chunkSMVZ3ZDJcjs.__name.call(void 0, shouldAutoConnect, "shouldAutoConnect");
6576
6462
  function resolveReconnectOptions(def, kind, cfg) {
6577
6463
  const base = DEFAULT_RECONNECT[kind];
6578
- const rc = _optionalChain([def, 'optionalAccess', _687 => _687.reconnect]);
6579
- const tmMaxTry = _optionalChain([cfg, 'optionalAccess', _688 => _688.tm, 'optionalAccess', _689 => _689.maxtry]);
6464
+ const rc = _optionalChain([def, 'optionalAccess', _702 => _702.reconnect]);
6465
+ const tmMaxTry = _optionalChain([cfg, 'optionalAccess', _703 => _703.tm, 'optionalAccess', _704 => _704.maxtry]);
6580
6466
  return {
6581
- enabled: _optionalChain([rc, 'optionalAccess', _690 => _690.enabled]) !== false && base.enabled !== false,
6582
- maxRetries: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _691 => _691.maxRetries]), () => ( tmMaxTry)), () => ( base.maxRetries)), () => ( 60)),
6583
- initialDelay: _nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _692 => _692.initialDelay]), () => ( base.initialDelay)), () => ( 1e3)),
6584
- maxDelay: _nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _693 => _693.maxDelay]), () => ( base.maxDelay)), () => ( 3e4)),
6585
- factor: _nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _694 => _694.factor]), () => ( base.factor)), () => ( 2))
6467
+ enabled: _optionalChain([rc, 'optionalAccess', _705 => _705.enabled]) !== false && base.enabled !== false,
6468
+ maxRetries: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _706 => _706.maxRetries]), () => ( tmMaxTry)), () => ( base.maxRetries)), () => ( 60)),
6469
+ initialDelay: _nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _707 => _707.initialDelay]), () => ( base.initialDelay)), () => ( 1e3)),
6470
+ maxDelay: _nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _708 => _708.maxDelay]), () => ( base.maxDelay)), () => ( 3e4)),
6471
+ factor: _nullishCoalesce(_nullishCoalesce(_optionalChain([rc, 'optionalAccess', _709 => _709.factor]), () => ( base.factor)), () => ( 2))
6586
6472
  };
6587
6473
  }
6588
6474
  _chunkSMVZ3ZDJcjs.__name.call(void 0, resolveReconnectOptions, "resolveReconnectOptions");
@@ -6632,17 +6518,17 @@ function createTransportDataHandler($asai, manager) {
6632
6518
  if (typeof event.data === "string") {
6633
6519
  try {
6634
6520
  event.data = JSON.parse(event.data);
6635
- } catch (e45) {
6521
+ } catch (e53) {
6636
6522
  }
6637
6523
  }
6638
- if (_optionalChain([event, 'access', _695 => _695.data, 'optionalAccess', _696 => _696.id])) {
6524
+ if (_optionalChain([event, 'access', _710 => _710.data, 'optionalAccess', _711 => _711.id])) {
6639
6525
  manager.watch(event.id, event.data);
6640
6526
  return;
6641
6527
  }
6642
6528
  try {
6643
- const wsKey = _optionalChain([$asai, 'optionalAccess', _697 => _697.command, 'optionalAccess', _698 => _698.commandconfig, 'optionalAccess', _699 => _699.config, 'optionalAccess', _700 => _700.commandclient]);
6644
- _optionalChain([$asai, 'access', _701 => _701.serversws, 'optionalAccess', _702 => _702[wsKey], 'optionalAccess', _703 => _703.broadws, 'optionalCall', _704 => _704(event.data)]);
6645
- } catch (e46) {
6529
+ const wsKey = _optionalChain([$asai, 'optionalAccess', _712 => _712.command, 'optionalAccess', _713 => _713.commandconfig, 'optionalAccess', _714 => _714.config, 'optionalAccess', _715 => _715.commandclient]);
6530
+ _optionalChain([$asai, 'access', _716 => _716.serversws, 'optionalAccess', _717 => _717[wsKey], 'optionalAccess', _718 => _718.broadws, 'optionalCall', _719 => _719(event.data)]);
6531
+ } catch (e54) {
6646
6532
  }
6647
6533
  };
6648
6534
  }
@@ -6674,10 +6560,10 @@ function hostDefault(mod) {
6674
6560
  }
6675
6561
  _chunkSMVZ3ZDJcjs.__name.call(void 0, hostDefault, "hostDefault");
6676
6562
  var hostMain = hostDefault(src_default);
6677
- var initAsaiHost2 = {
6563
+ var initAsaiHostNodejs2 = {
6678
6564
  name: PLUGIN_NAME,
6679
6565
  fn: /* @__PURE__ */ _chunkSMVZ3ZDJcjs.__name.call(void 0, ($asai, opt) => hostMain($asai, opt), "fn"),
6680
- sysserver: sysserver_default,
6566
+ sysserver,
6681
6567
  AsaiCommon: Index_default,
6682
6568
  AsaiUtils: utils_exports,
6683
6569
  normalizeHostConfig,
@@ -6689,20 +6575,20 @@ var initAsaiHost2 = {
6689
6575
  initHostserverWs,
6690
6576
  syncApiRouteKeys,
6691
6577
  syncWsRouteKeys,
6692
- secureCompare: _chunkKOFCBB3Ncjs.secureCompare,
6578
+ secureCompare: _chunkK2QPSQEVcjs.secureCompare,
6693
6579
  resolvePathUnderRoots,
6694
6580
  getHostAllowedRoots,
6695
6581
  logSecurityEvent,
6696
6582
  sanitizeString,
6697
6583
  validateHttpAuth,
6698
6584
  normalizeSecurityConfig,
6699
- stripForbiddenSecretsFromHostConfig: _chunkQWVR2HNTcjs.stripForbiddenSecretsFromHostConfig,
6700
- loadAsaiSecrets: _chunkQWVR2HNTcjs.loadAsaiSecrets,
6701
- loadDotEnvFile: _chunkQWVR2HNTcjs.loadDotEnvFile,
6702
- applySecretsToHostConfig: _chunkQWVR2HNTcjs.applySecretsToHostConfig,
6703
- resolveHttpsCertFromPaths: _chunkQWVR2HNTcjs.resolveHttpsCertFromPaths,
6704
- validateAsaiSecrets: _chunkQWVR2HNTcjs.validateAsaiSecrets,
6705
- isDevDefaultPassword: _chunkQWVR2HNTcjs.isDevDefaultPassword,
6585
+ stripForbiddenSecretsFromHostConfig: _chunkLXJMGLKWcjs.stripForbiddenSecretsFromHostConfig,
6586
+ loadAsaiSecrets: _chunkLXJMGLKWcjs.loadAsaiSecrets,
6587
+ loadDotEnvFile: _chunkLXJMGLKWcjs.loadDotEnvFile,
6588
+ applySecretsToHostConfig: _chunkLXJMGLKWcjs.applySecretsToHostConfig,
6589
+ resolveHttpsCertFromPaths: _chunkLXJMGLKWcjs.resolveHttpsCertFromPaths,
6590
+ validateAsaiSecrets: _chunkLXJMGLKWcjs.validateAsaiSecrets,
6591
+ isDevDefaultPassword: _chunkLXJMGLKWcjs.isDevDefaultPassword,
6706
6592
  getTransportBlock,
6707
6593
  getTransportDefault,
6708
6594
  hasTransportDefault,
@@ -6714,8 +6600,8 @@ var initAsaiHost2 = {
6714
6600
  createTransportDataHandler,
6715
6601
  wireTransportConnectionLogs
6716
6602
  };
6717
- var PLUGIN_VERSION = true ? "0.0.1" : "0.0.1";
6718
- var index_default = initAsaiHost2;
6603
+ var PLUGIN_VERSION = true ? "0.0.2" : "0.0.1";
6604
+ var index_default = initAsaiHostNodejs2;
6719
6605
 
6720
6606
 
6721
6607
 
@@ -6757,5 +6643,5 @@ var index_default = initAsaiHost2;
6757
6643
 
6758
6644
 
6759
6645
 
6760
- exports.AsaiCommon = Index_default; exports.AsaiUtils = utils_exports; exports.PLUGIN_NAME = PLUGIN_NAME; exports.PLUGIN_VERSION = PLUGIN_VERSION; exports.applySecretsToHostConfig = _chunkQWVR2HNTcjs.applySecretsToHostConfig; exports.createTransportDataHandler = createTransportDataHandler; exports.default = index_default; exports.ensureDefaultConnection = ensureDefaultConnection; exports.getDefaultConnId = getDefaultConnId; exports.getHostAllowedRoots = getHostAllowedRoots; exports.getTransportBlock = getTransportBlock; exports.getTransportDefault = getTransportDefault; exports.hasTransportDefault = hasTransportDefault; exports.initAsaiHost = initAsaiHost2; exports.initHostserverApi = initHostserverApi; exports.initHostserverWs = initHostserverWs; exports.initTransportBridge = initTransportBridge; exports.isDevDefaultPassword = _chunkQWVR2HNTcjs.isDevDefaultPassword; exports.loadAsaiSecrets = _chunkQWVR2HNTcjs.loadAsaiSecrets; exports.loadDotEnvFile = _chunkQWVR2HNTcjs.loadDotEnvFile; exports.logSecurityEvent = logSecurityEvent; exports.normalizeHostConfig = normalizeHostConfig; exports.normalizeSecurityConfig = normalizeSecurityConfig; exports.registerApi = registerApi; exports.registerWs = registerWs; exports.resolveHttpsCertFromPaths = _chunkQWVR2HNTcjs.resolveHttpsCertFromPaths; exports.resolvePathUnderRoots = resolvePathUnderRoots; exports.resolveReconnectOptions = resolveReconnectOptions; exports.sanitizeString = sanitizeString; exports.secureCompare = _chunkKOFCBB3Ncjs.secureCompare; exports.shouldAutoConnect = shouldAutoConnect; exports.stripForbiddenSecretsFromHostConfig = _chunkQWVR2HNTcjs.stripForbiddenSecretsFromHostConfig; exports.syncApiRouteKeys = syncApiRouteKeys; exports.syncWsRouteKeys = syncWsRouteKeys; exports.sysserver = sysserver_default; exports.validateAsaiSecrets = _chunkQWVR2HNTcjs.validateAsaiSecrets; exports.validateHostConfig = validateHostConfig; exports.validateHttpAuth = validateHttpAuth; exports.validateProductionSecurity = validateProductionSecurity; exports.wireTransportConnectionLogs = wireTransportConnectionLogs;
6646
+ exports.AsaiCommon = Index_default; exports.AsaiUtils = utils_exports; exports.PLUGIN_NAME = PLUGIN_NAME; exports.PLUGIN_VERSION = PLUGIN_VERSION; exports.applySecretsToHostConfig = _chunkLXJMGLKWcjs.applySecretsToHostConfig; exports.createTransportDataHandler = createTransportDataHandler; exports.default = index_default; exports.ensureDefaultConnection = ensureDefaultConnection; exports.getDefaultConnId = getDefaultConnId; exports.getHostAllowedRoots = getHostAllowedRoots; exports.getTransportBlock = getTransportBlock; exports.getTransportDefault = getTransportDefault; exports.hasTransportDefault = hasTransportDefault; exports.initAsaiHostNodejs = initAsaiHostNodejs2; exports.initHostserverApi = initHostserverApi; exports.initHostserverWs = initHostserverWs; exports.initTransportBridge = initTransportBridge; exports.isDevDefaultPassword = _chunkLXJMGLKWcjs.isDevDefaultPassword; exports.loadAsaiSecrets = _chunkLXJMGLKWcjs.loadAsaiSecrets; exports.loadDotEnvFile = _chunkLXJMGLKWcjs.loadDotEnvFile; exports.logSecurityEvent = logSecurityEvent; exports.normalizeHostConfig = normalizeHostConfig; exports.normalizeSecurityConfig = normalizeSecurityConfig; exports.registerApi = registerApi; exports.registerWs = registerWs; exports.resolveHttpsCertFromPaths = _chunkLXJMGLKWcjs.resolveHttpsCertFromPaths; exports.resolvePathUnderRoots = resolvePathUnderRoots; exports.resolveReconnectOptions = resolveReconnectOptions; exports.sanitizeString = sanitizeString; exports.secureCompare = _chunkK2QPSQEVcjs.secureCompare; exports.shouldAutoConnect = shouldAutoConnect; exports.stripForbiddenSecretsFromHostConfig = _chunkLXJMGLKWcjs.stripForbiddenSecretsFromHostConfig; exports.syncApiRouteKeys = syncApiRouteKeys; exports.syncWsRouteKeys = syncWsRouteKeys; exports.sysserver = sysserver; exports.validateAsaiSecrets = _chunkLXJMGLKWcjs.validateAsaiSecrets; exports.validateHostConfig = validateHostConfig; exports.validateHttpAuth = validateHttpAuth; exports.validateProductionSecurity = validateProductionSecurity; exports.wireTransportConnectionLogs = wireTransportConnectionLogs;
6761
6647
  //# sourceMappingURL=asaihost-nodejs.cjs.map