@bmfk/api 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1293 -2
  4. package/dist/apiServer/APIService.d.ts +125 -0
  5. package/dist/apiServer/APIService.js +769 -0
  6. package/dist/apiServer/BaseEndpoint.d.ts +90 -0
  7. package/dist/apiServer/BaseEndpoint.js +314 -0
  8. package/dist/apiServer/BaseService.d.ts +17 -0
  9. package/dist/apiServer/BaseService.js +39 -0
  10. package/dist/apiServer/DBService.d.ts +131 -0
  11. package/dist/apiServer/DBService.js +290 -0
  12. package/dist/apiServer/DocumentService.d.ts +9 -0
  13. package/dist/apiServer/DocumentService.js +65 -0
  14. package/dist/apiServer/LocalRequest.d.ts +3 -0
  15. package/dist/apiServer/LocalRequest.js +6 -0
  16. package/dist/apiServer/LogService.d.ts +78 -0
  17. package/dist/apiServer/LogService.js +349 -0
  18. package/dist/apiServer/MonitorService.d.ts +102 -0
  19. package/dist/apiServer/MonitorService.js +615 -0
  20. package/dist/apiServer/StatService.d.ts +4 -0
  21. package/dist/apiServer/StatService.js +10 -0
  22. package/dist/apiServer/TimeframeService.d.ts +28 -0
  23. package/dist/apiServer/TimeframeService.js +97 -0
  24. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  25. package/dist/apiServer/WebSocketServer.js +173 -0
  26. package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
  27. package/dist/apiServer/db/IDBAdapter.js +2 -0
  28. package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
  29. package/dist/apiServer/db/MysqlAdapter.js +869 -0
  30. package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
  31. package/dist/apiServer/db/PostgresAdapter.js +73 -0
  32. package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
  33. package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
  34. package/dist/apiServer/deployment/Activate.d.ts +4 -0
  35. package/dist/apiServer/deployment/Activate.js +124 -0
  36. package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
  37. package/dist/apiServer/deployment/BackupManager.js +174 -0
  38. package/dist/apiServer/deployment/Backups.d.ts +2 -0
  39. package/dist/apiServer/deployment/Backups.js +44 -0
  40. package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
  41. package/dist/apiServer/deployment/BlueGreenState.js +150 -0
  42. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  43. package/dist/apiServer/deployment/Bundler.js +178 -0
  44. package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
  45. package/dist/apiServer/deployment/ConfigService.js +195 -0
  46. package/dist/apiServer/deployment/Deploy.d.ts +4 -0
  47. package/dist/apiServer/deployment/Deploy.js +404 -0
  48. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  49. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  50. package/dist/apiServer/deployment/Deployer.d.ts +13 -0
  51. package/dist/apiServer/deployment/Deployer.js +96 -0
  52. package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
  53. package/dist/apiServer/deployment/DeployerInit.js +214 -0
  54. package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
  55. package/dist/apiServer/deployment/DeployerService.js +1553 -0
  56. package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
  57. package/dist/apiServer/deployment/HashPassword.js +126 -0
  58. package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
  59. package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
  60. package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
  61. package/dist/apiServer/deployment/MigrateProject.js +335 -0
  62. package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
  63. package/dist/apiServer/deployment/NginxHelper.js +111 -0
  64. package/dist/apiServer/deployment/Notifier.d.ts +30 -0
  65. package/dist/apiServer/deployment/Notifier.js +82 -0
  66. package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
  67. package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
  68. package/dist/apiServer/deployment/Restore.d.ts +2 -0
  69. package/dist/apiServer/deployment/Restore.js +89 -0
  70. package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
  71. package/dist/apiServer/deployment/ReviewStore.js +186 -0
  72. package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
  73. package/dist/apiServer/deployment/SecretsInjector.js +189 -0
  74. package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
  75. package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
  76. package/dist/apiServer/deployment/Status.d.ts +2 -0
  77. package/dist/apiServer/deployment/Status.js +83 -0
  78. package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
  79. package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
  80. package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
  81. package/dist/apiServer/deployment/Watchdog.js +65 -0
  82. package/dist/apiServer/deployment/Wizards.d.ts +1 -0
  83. package/dist/apiServer/deployment/Wizards.js +83 -0
  84. package/dist/apiServer/deployment/cli.d.ts +2 -0
  85. package/dist/apiServer/deployment/cli.js +224 -0
  86. package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
  87. package/dist/apiServer/deployment/cliCommon.js +110 -0
  88. package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
  89. package/dist/apiServer/deployment/cliPrompt.js +38 -0
  90. package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
  91. package/dist/apiServer/deployment/resolveConfig.js +139 -0
  92. package/dist/apiServer/documentation/Documentation.d.ts +18 -0
  93. package/dist/apiServer/documentation/Documentation.js +143 -0
  94. package/dist/apiServer/documentation/index.html +460 -0
  95. package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
  96. package/dist/apiServer/external/MicroserviceClient.js +144 -0
  97. package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
  98. package/dist/apiServer/external/MicroserviceHost.js +183 -0
  99. package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
  100. package/dist/apiServer/external/MicroserviceHostController.js +65 -0
  101. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  102. package/dist/apiServer/helper/AppDataPath.js +81 -0
  103. package/dist/apiServer/helper/ClientIp.d.ts +3 -0
  104. package/dist/apiServer/helper/ClientIp.js +33 -0
  105. package/dist/apiServer/helper/DataProvider.d.ts +18 -0
  106. package/dist/apiServer/helper/DataProvider.js +57 -0
  107. package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
  108. package/dist/apiServer/helper/IpAllowList.js +40 -0
  109. package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
  110. package/dist/apiServer/helper/JSONStableStringify.js +15 -0
  111. package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
  112. package/dist/apiServer/helper/PasswordHash.js +52 -0
  113. package/dist/apiServer/helper/Sleep.d.ts +1 -0
  114. package/dist/apiServer/helper/Sleep.js +5 -0
  115. package/dist/apiServer/helper/Trace.d.ts +8 -0
  116. package/dist/apiServer/helper/Trace.js +30 -0
  117. package/dist/apiServer/helper/UID.d.ts +16 -0
  118. package/dist/apiServer/helper/UID.js +98 -0
  119. package/dist/apiServer/helper/Validator.d.ts +86 -0
  120. package/dist/apiServer/helper/Validator.js +560 -0
  121. package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
  122. package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
  123. package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
  124. package/dist/apiServer/helper/ZipUtils.js +28 -0
  125. package/dist/apiServer/http/Http.d.ts +183 -0
  126. package/dist/apiServer/http/Http.js +627 -0
  127. package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
  128. package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
  129. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  130. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  131. package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
  132. package/dist/apiServer/monitor/AccessStore.js +163 -0
  133. package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
  134. package/dist/apiServer/monitor/LogFiles.js +109 -0
  135. package/dist/apiServer/monitor/Monitor.d.ts +54 -0
  136. package/dist/apiServer/monitor/Monitor.js +447 -0
  137. package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
  138. package/dist/apiServer/monitor/MonitorAuth.js +474 -0
  139. package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
  140. package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
  141. package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
  142. package/dist/apiServer/monitor/SystemInfo.js +217 -0
  143. package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
  144. package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
  145. package/dist/apiServer/monitor/index.html +591 -0
  146. package/dist/apiServer/review/Review.d.ts +23 -0
  147. package/dist/apiServer/review/Review.js +149 -0
  148. package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
  149. package/dist/apiServer/review/ReviewAuth.js +147 -0
  150. package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
  151. package/dist/apiServer/review/ReviewDiff.js +175 -0
  152. package/dist/apiServer/review/index.html +501 -0
  153. package/dist/apiServer/routes/Liveness.d.ts +7 -0
  154. package/dist/apiServer/routes/Liveness.js +27 -0
  155. package/dist/apiServer/routes/Readiness.d.ts +13 -0
  156. package/dist/apiServer/routes/Readiness.js +20 -0
  157. package/dist/apiServer/security/BlockedIps.d.ts +46 -0
  158. package/dist/apiServer/security/BlockedIps.js +185 -0
  159. package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
  160. package/dist/apiServer/structures/DefaultErrors.js +52 -0
  161. package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
  162. package/dist/apiServer/structures/HTTPStatus.js +11 -0
  163. package/dist/apiServer/structures/Interfaces.d.ts +55 -0
  164. package/dist/apiServer/structures/Interfaces.js +2 -0
  165. package/dist/index.d.ts +45 -0
  166. package/dist/index.js +110 -0
  167. package/dist/signal/Signal.d.ts +23 -0
  168. package/dist/signal/Signal.js +85 -0
  169. package/package.json +88 -4
@@ -0,0 +1,468 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ProcessMonitor = void 0;
7
+ const os_1 = __importDefault(require("os"));
8
+ const v8_1 = __importDefault(require("v8"));
9
+ const perf_hooks_1 = require("perf_hooks");
10
+ const promises_1 = __importDefault(require("fs/promises"));
11
+ class ProcessMonitor {
12
+ static _inited = false;
13
+ static _eld = null;
14
+ static _gcObserver = null;
15
+ static _gc = {
16
+ totalCount: 0,
17
+ totalTimeMs: 0,
18
+ maxPauseMs: 0,
19
+ byKind: {},
20
+ lastPauses: [],
21
+ };
22
+ static _prevCpu = process.cpuUsage();
23
+ static _prevCpuAt = Date.now();
24
+ static _cpuPct = { userPct: 0, systemPct: 0 };
25
+ static _eluPrev = perf_hooks_1.performance.eventLoopUtilization();
26
+ static _elu = { idle: 0, active: 0, utilizationPct: 0 };
27
+ static _processStartedAt = Date.now() - process.uptime() * 1000;
28
+ static _fdHistory = [];
29
+ static _fdHistoryMax = 300;
30
+ static _fdSampleEveryMs = Math.max(1, parseInt(process.env.MONITOR_FD_SAMPLE_MINUTES || "10", 10) || 10) * 60 * 1000;
31
+ static init() {
32
+ if (this._inited)
33
+ return;
34
+ this._inited = true;
35
+ this._eld = (0, perf_hooks_1.monitorEventLoopDelay)({ resolution: 20 });
36
+ this._eld.enable();
37
+ this._gcObserver = new perf_hooks_1.PerformanceObserver((list) => {
38
+ for (const entry of list.getEntries()) {
39
+ const kind = this._mapGcKind(entry.detail?.kind ?? entry.kind);
40
+ this._gc.totalCount++;
41
+ this._gc.totalTimeMs += entry.duration;
42
+ if (entry.duration > this._gc.maxPauseMs)
43
+ this._gc.maxPauseMs = entry.duration;
44
+ const bucket = this._gc.byKind[kind] ?? { count: 0, timeMs: 0 };
45
+ bucket.count++;
46
+ bucket.timeMs += entry.duration;
47
+ this._gc.byKind[kind] = bucket;
48
+ this._gc.lastPauses.push({ kind, ms: entry.duration, timestamp: Date.now() });
49
+ if (this._gc.lastPauses.length > 20)
50
+ this._gc.lastPauses.shift();
51
+ }
52
+ });
53
+ try {
54
+ this._gcObserver.observe({ entryTypes: ["gc"], buffered: false });
55
+ }
56
+ catch {
57
+ try {
58
+ this._gcObserver.observe({ type: "gc" });
59
+ }
60
+ catch { }
61
+ }
62
+ const cpuTimer = setInterval(() => this._sampleCpu(), 5000);
63
+ if (cpuTimer.unref)
64
+ cpuTimer.unref();
65
+ const eluTimer = setInterval(() => this._sampleELU(), 5000);
66
+ if (eluTimer.unref)
67
+ eluTimer.unref();
68
+ this._sampleFdSeries().catch(() => { });
69
+ const fdTimer = setInterval(() => this._sampleFdSeries().catch(() => { }), this._fdSampleEveryMs);
70
+ if (fdTimer.unref)
71
+ fdTimer.unref();
72
+ }
73
+ static async _sampleFdSeries() {
74
+ const fdOpen = await this._countFds();
75
+ const sockets = await this._readSocketBreakdown();
76
+ const limits = await this._readProcLimits();
77
+ const softRaw = limits?.["Max open files"]?.soft;
78
+ const mem = process.memoryUsage();
79
+ this._fdHistory.push({
80
+ ts: Date.now(),
81
+ fdOpen,
82
+ fdSoftLimit: softRaw ? this._parseLimitValue(softRaw) : null,
83
+ socketTotal: sockets ? sockets.total : null,
84
+ byState: sockets ? sockets.byState : {},
85
+ topRemote: sockets && sockets.topRemotes.length > 0 ? sockets.topRemotes[0] : null,
86
+ rss: mem.rss,
87
+ });
88
+ if (this._fdHistory.length > this._fdHistoryMax)
89
+ this._fdHistory.shift();
90
+ }
91
+ static _sampleCpu() {
92
+ const now = process.cpuUsage();
93
+ const nowAt = Date.now();
94
+ const dtMs = nowAt - this._prevCpuAt;
95
+ if (dtMs <= 0)
96
+ return;
97
+ const userPct = (now.user - this._prevCpu.user) / (dtMs * 1000) * 100;
98
+ const systemPct = (now.system - this._prevCpu.system) / (dtMs * 1000) * 100;
99
+ this._cpuPct = {
100
+ userPct: Math.round(userPct * 10) / 10,
101
+ systemPct: Math.round(systemPct * 10) / 10,
102
+ };
103
+ this._prevCpu = now;
104
+ this._prevCpuAt = nowAt;
105
+ }
106
+ static _sampleELU() {
107
+ const cur = perf_hooks_1.performance.eventLoopUtilization();
108
+ const delta = perf_hooks_1.performance.eventLoopUtilization(cur, this._eluPrev);
109
+ this._elu = {
110
+ idle: delta.idle,
111
+ active: delta.active,
112
+ utilizationPct: Math.round(delta.utilization * 10000) / 100,
113
+ };
114
+ this._eluPrev = cur;
115
+ }
116
+ static _mapGcKind(kind) {
117
+ if (typeof kind === "string")
118
+ return kind;
119
+ switch (kind) {
120
+ case 1: return "minor";
121
+ case 2: return "major";
122
+ case 4: return "incremental";
123
+ case 8: return "weakcb";
124
+ case 15: return "all";
125
+ default: return "unknown";
126
+ }
127
+ }
128
+ static async getSnapshot() {
129
+ const tStart = process.hrtime.bigint();
130
+ await new Promise(r => setImmediate(() => r()));
131
+ const spotLagMs = Number(process.hrtime.bigint() - tStart) / 1e6;
132
+ const mem = process.memoryUsage();
133
+ const heap = v8_1.default.getHeapStatistics();
134
+ const heapSpaces = v8_1.default.getHeapSpaceStatistics().map(s => ({
135
+ name: s.space_name,
136
+ size: s.space_size,
137
+ used: s.space_used_size,
138
+ available: s.space_available_size,
139
+ physical: s.physical_space_size,
140
+ }));
141
+ const procStatus = await this._readProcStatus();
142
+ const io = await this._readProcIo();
143
+ const limitsParsed = await this._readProcLimits();
144
+ const cpuTotal = process.cpuUsage();
145
+ let resource = null;
146
+ try {
147
+ const r = process.resourceUsage();
148
+ resource = {
149
+ maxRSS: r.maxRSS,
150
+ voluntaryContextSwitches: r.voluntaryContextSwitches,
151
+ involuntaryContextSwitches: r.involuntaryContextSwitches,
152
+ fsRead: r.fsRead,
153
+ fsWrite: r.fsWrite,
154
+ signalsCount: r.signalsCount,
155
+ ipcSent: r.ipcSent,
156
+ ipcReceived: r.ipcReceived,
157
+ userCPUTimeMs: Math.round(r.userCPUTime / 1000),
158
+ systemCPUTimeMs: Math.round(r.systemCPUTime / 1000),
159
+ };
160
+ }
161
+ catch { }
162
+ const fdOpen = await this._countFds();
163
+ const fdSoft = limitsParsed?.["Max open files"]?.soft;
164
+ const fdHard = limitsParsed?.["Max open files"]?.hard;
165
+ const sockets = await this._readSocketBreakdown();
166
+ const h = this._eld;
167
+ const eventLoop = h ? {
168
+ minMs: this._toMsFinite(h.min),
169
+ maxMs: this._toMsFinite(h.max),
170
+ meanMs: this._toMsFinite(h.mean),
171
+ stddevMs: this._toMsFinite(h.stddev),
172
+ p50Ms: this._safePercentileMs(h, 50),
173
+ p90Ms: this._safePercentileMs(h, 90),
174
+ p99Ms: this._safePercentileMs(h, 99),
175
+ utilizationPct: this._elu.utilizationPct,
176
+ activeHandles: this._safeCount(() => process._getActiveHandles?.()?.length),
177
+ activeRequests: this._safeCount(() => process._getActiveRequests?.()?.length),
178
+ spotLagMs: Math.round(spotLagMs * 100) / 100,
179
+ } : null;
180
+ return {
181
+ identity: {
182
+ pid: process.pid,
183
+ ppid: process.ppid,
184
+ title: process.title,
185
+ argv: process.argv,
186
+ execPath: process.execPath,
187
+ cwd: process.cwd(),
188
+ nodeVersion: process.version,
189
+ v8Version: process.versions.v8,
190
+ platform: process.platform,
191
+ arch: process.arch,
192
+ hostname: os_1.default.hostname(),
193
+ user: typeof process.getuid === "function"
194
+ ? { uid: process.getuid(), gid: process.getgid?.() ?? -1 }
195
+ : null,
196
+ startedAtUnix: this._processStartedAt,
197
+ uptimeSec: Math.round(process.uptime()),
198
+ availableParallelism: typeof os_1.default.availableParallelism === "function"
199
+ ? os_1.default.availableParallelism()
200
+ : os_1.default.cpus().length,
201
+ pm2: this.getPm2Identity(),
202
+ },
203
+ memory: {
204
+ rss: mem.rss,
205
+ heapTotal: mem.heapTotal,
206
+ heapUsed: mem.heapUsed,
207
+ external: mem.external,
208
+ arrayBuffers: mem.arrayBuffers ?? 0,
209
+ heap: {
210
+ sizeLimit: heap.heap_size_limit,
211
+ usedHeap: heap.used_heap_size,
212
+ totalAvailable: heap.total_available_size,
213
+ totalPhysical: heap.total_physical_size,
214
+ mallocedMemory: heap.malloced_memory,
215
+ peakMallocedMemory: heap.peak_malloced_memory,
216
+ numberOfNativeContexts: heap.number_of_native_contexts,
217
+ numberOfDetachedContexts: heap.number_of_detached_contexts,
218
+ },
219
+ heapSpaces,
220
+ procStatus,
221
+ },
222
+ cpu: {
223
+ userPct: this._cpuPct.userPct,
224
+ systemPct: this._cpuPct.systemPct,
225
+ userMicros: cpuTotal.user,
226
+ systemMicros: cpuTotal.system,
227
+ resource,
228
+ },
229
+ eventLoop,
230
+ gc: {
231
+ totalCount: this._gc.totalCount,
232
+ totalTimeMs: Math.round(this._gc.totalTimeMs * 100) / 100,
233
+ maxPauseMs: Math.round(this._gc.maxPauseMs * 100) / 100,
234
+ byKind: this._gc.byKind,
235
+ lastPauses: this._gc.lastPauses.slice(-20),
236
+ },
237
+ fileDescriptors: {
238
+ open: fdOpen,
239
+ limitSoft: fdSoft ? this._parseLimitValue(fdSoft) : null,
240
+ limitHard: fdHard ? this._parseLimitValue(fdHard) : null,
241
+ },
242
+ sockets,
243
+ io,
244
+ limits: limitsParsed,
245
+ };
246
+ }
247
+ static getPm2Identity() {
248
+ const env = process.env;
249
+ const pmId = env.pm_id ?? null;
250
+ return {
251
+ managed: pmId !== null && pmId !== "",
252
+ name: env.name ?? null,
253
+ pmId,
254
+ instanceId: env.NODE_APP_INSTANCE ?? null,
255
+ execPath: env.pm_exec_path ?? null,
256
+ cwd: env.pm_cwd ?? null,
257
+ };
258
+ }
259
+ static async getFdReport() {
260
+ const [sockets, limits, fdOpen] = await Promise.all([
261
+ this._readSocketBreakdown(),
262
+ this._readProcLimits(),
263
+ this._countFds(),
264
+ ]);
265
+ const softRaw = limits?.["Max open files"]?.soft;
266
+ const hardRaw = limits?.["Max open files"]?.hard;
267
+ return {
268
+ now: {
269
+ ts: Date.now(),
270
+ fdOpen,
271
+ limitSoft: softRaw ? this._parseLimitValue(softRaw) : null,
272
+ limitHard: hardRaw ? this._parseLimitValue(hardRaw) : null,
273
+ sockets,
274
+ },
275
+ sampleEveryMs: this._fdSampleEveryMs,
276
+ historyMax: this._fdHistoryMax,
277
+ history: this._fdHistory,
278
+ };
279
+ }
280
+ static async _readProcStatus() {
281
+ try {
282
+ const txt = await promises_1.default.readFile(`/proc/${process.pid}/status`, "utf-8");
283
+ const keys = ["VmPeak", "VmSize", "VmHWM", "VmRSS", "VmData", "VmStk", "VmExe", "VmSwap", "Threads"];
284
+ const result = {};
285
+ for (const line of txt.split("\n")) {
286
+ for (const k of keys) {
287
+ if (line.startsWith(k + ":")) {
288
+ const m = line.match(new RegExp(`${k}:\\s+(\\d+)`));
289
+ if (m) {
290
+ const v = parseInt(m[1], 10);
291
+ result[k] = k === "Threads" ? v : v * 1024;
292
+ }
293
+ }
294
+ }
295
+ }
296
+ return result;
297
+ }
298
+ catch {
299
+ return null;
300
+ }
301
+ }
302
+ static async _readProcIo() {
303
+ try {
304
+ const txt = await promises_1.default.readFile(`/proc/${process.pid}/io`, "utf-8");
305
+ const result = {};
306
+ for (const line of txt.split("\n")) {
307
+ const m = line.match(/^(\w+):\s+(\d+)$/);
308
+ if (m)
309
+ result[m[1]] = parseInt(m[2], 10);
310
+ }
311
+ return result;
312
+ }
313
+ catch {
314
+ return null;
315
+ }
316
+ }
317
+ static async _readProcLimits() {
318
+ try {
319
+ const txt = await promises_1.default.readFile(`/proc/${process.pid}/limits`, "utf-8");
320
+ const result = {};
321
+ const lines = txt.split("\n").slice(1);
322
+ for (const line of lines) {
323
+ const m = line.match(/^(.+?)\s{2,}(\S+)\s+(\S+)\s+(\S+)\s*$/);
324
+ if (m)
325
+ result[m[1].trim()] = { soft: m[2], hard: m[3], unit: m[4] };
326
+ }
327
+ return result;
328
+ }
329
+ catch {
330
+ return null;
331
+ }
332
+ }
333
+ static async _countFds() {
334
+ try {
335
+ const entries = await promises_1.default.readdir(`/proc/${process.pid}/fd`);
336
+ return entries.length;
337
+ }
338
+ catch {
339
+ return null;
340
+ }
341
+ }
342
+ static async _readSocketBreakdown() {
343
+ try {
344
+ const fdDir = `/proc/${process.pid}/fd`;
345
+ const fds = await promises_1.default.readdir(fdDir);
346
+ const inodes = new Set();
347
+ await Promise.all(fds.map(async (fd) => {
348
+ try {
349
+ const link = await promises_1.default.readlink(`${fdDir}/${fd}`);
350
+ const m = link.match(/^socket:\[(\d+)\]$/);
351
+ if (m)
352
+ inodes.add(m[1]);
353
+ }
354
+ catch { }
355
+ }));
356
+ if (inodes.size === 0)
357
+ return { total: 0, byState: {}, topRemotes: [] };
358
+ const byState = {};
359
+ const remoteEstab = {};
360
+ let total = 0;
361
+ for (const [file, isV6] of [["/proc/net/tcp", false], ["/proc/net/tcp6", true]]) {
362
+ let txt;
363
+ try {
364
+ txt = await promises_1.default.readFile(file, "utf-8");
365
+ }
366
+ catch {
367
+ continue;
368
+ }
369
+ for (const line of txt.split("\n").slice(1)) {
370
+ const parts = line.trim().split(/\s+/);
371
+ if (parts.length < 10)
372
+ continue;
373
+ const inode = parts[9];
374
+ if (!inodes.has(inode))
375
+ continue;
376
+ total++;
377
+ const state = this._tcpState(parts[3]);
378
+ byState[state] = (byState[state] ?? 0) + 1;
379
+ if (state === "ESTABLISHED") {
380
+ const host = this._parseHexAddr((parts[2] ?? "").split(":")[0], isV6);
381
+ remoteEstab[host] = (remoteEstab[host] ?? 0) + 1;
382
+ }
383
+ }
384
+ }
385
+ const topRemotes = Object.entries(remoteEstab)
386
+ .map(([host, established]) => ({ host, established }))
387
+ .sort((a, b) => b.established - a.established)
388
+ .slice(0, 10);
389
+ return { total, byState, topRemotes };
390
+ }
391
+ catch {
392
+ return null;
393
+ }
394
+ }
395
+ static _tcpState(hex) {
396
+ switch ((hex || "").toUpperCase()) {
397
+ case "01": return "ESTABLISHED";
398
+ case "02": return "SYN_SENT";
399
+ case "03": return "SYN_RECV";
400
+ case "04": return "FIN_WAIT1";
401
+ case "05": return "FIN_WAIT2";
402
+ case "06": return "TIME_WAIT";
403
+ case "07": return "CLOSE";
404
+ case "08": return "CLOSE_WAIT";
405
+ case "09": return "LAST_ACK";
406
+ case "0A": return "LISTEN";
407
+ case "0B": return "CLOSING";
408
+ case "0C": return "NEW_SYN_RECV";
409
+ default: return "UNKNOWN(" + hex + ")";
410
+ }
411
+ }
412
+ static _parseHexAddr(hex, isV6) {
413
+ try {
414
+ if (!isV6) {
415
+ if (hex.length !== 8)
416
+ return hex;
417
+ return [
418
+ parseInt(hex.slice(6, 8), 16),
419
+ parseInt(hex.slice(4, 6), 16),
420
+ parseInt(hex.slice(2, 4), 16),
421
+ parseInt(hex.slice(0, 2), 16),
422
+ ].join(".");
423
+ }
424
+ if (hex.length !== 32)
425
+ return hex;
426
+ const bytes = [];
427
+ for (let w = 0; w < 4; w++) {
428
+ const word = hex.slice(w * 8, w * 8 + 8);
429
+ for (let b = 3; b >= 0; b--)
430
+ bytes.push(parseInt(word.slice(b * 2, b * 2 + 2), 16));
431
+ }
432
+ const hextets = [];
433
+ for (let i = 0; i < 16; i += 2)
434
+ hextets.push((((bytes[i] << 8) | bytes[i + 1]) >>> 0).toString(16));
435
+ return hextets.join(":");
436
+ }
437
+ catch {
438
+ return hex;
439
+ }
440
+ }
441
+ static _parseLimitValue(v) {
442
+ if (v === "unlimited")
443
+ return -1;
444
+ const n = parseInt(v, 10);
445
+ return Number.isFinite(n) ? n : null;
446
+ }
447
+ static _toMsFinite(ns) {
448
+ return Number.isFinite(ns) ? Math.round((ns / 1e6) * 100) / 100 : 0;
449
+ }
450
+ static _safePercentileMs(h, p) {
451
+ try {
452
+ return this._toMsFinite(h.percentile(p));
453
+ }
454
+ catch {
455
+ return 0;
456
+ }
457
+ }
458
+ static _safeCount(fn) {
459
+ try {
460
+ return fn() ?? 0;
461
+ }
462
+ catch {
463
+ return 0;
464
+ }
465
+ }
466
+ }
467
+ exports.ProcessMonitor = ProcessMonitor;
468
+ ProcessMonitor.init();
@@ -0,0 +1,70 @@
1
+ export declare function collectSystemInfo(): Promise<{
2
+ cpu: {
3
+ count: number;
4
+ models: Record<string, number>;
5
+ loadAvg: number[];
6
+ platform: NodeJS.Platform;
7
+ arch: NodeJS.Architecture;
8
+ uptimeSec: number;
9
+ usage: {
10
+ userPct: number;
11
+ systemPct: number;
12
+ idlePct: number;
13
+ iowaitPct: number;
14
+ } | null;
15
+ };
16
+ memory: {
17
+ total: number;
18
+ free: number;
19
+ used: number;
20
+ usedPct: number;
21
+ };
22
+ disk: {
23
+ filesystem: string;
24
+ size: number;
25
+ used: number;
26
+ available: number;
27
+ usePct: string;
28
+ mount: string;
29
+ }[] | null;
30
+ connections: {
31
+ ports: number[];
32
+ total: number;
33
+ topRemote: {
34
+ ip: string;
35
+ count: number;
36
+ }[];
37
+ } | null;
38
+ nginx: {
39
+ installed: boolean;
40
+ version?: undefined;
41
+ status?: undefined;
42
+ listening?: undefined;
43
+ workerCount?: undefined;
44
+ } | {
45
+ installed: boolean;
46
+ version: string;
47
+ status: string;
48
+ listening: string[];
49
+ workerCount: number;
50
+ } | {
51
+ installed: boolean;
52
+ error: string;
53
+ };
54
+ pm2: {
55
+ installed: boolean;
56
+ error?: undefined;
57
+ processes?: undefined;
58
+ } | {
59
+ installed: boolean;
60
+ error: string;
61
+ processes?: undefined;
62
+ } | {
63
+ error?: undefined;
64
+ installed: boolean;
65
+ processes: any;
66
+ } | {
67
+ installed: boolean;
68
+ error: string;
69
+ };
70
+ }>;