computer-vitals 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +165 -2
- package/package.json +48 -4
- package/src/data/os-support.json +33 -0
- package/src/index.js +160 -0
- package/src/lib/apps.js +211 -0
- package/src/lib/diagnose.js +285 -0
- package/src/lib/disk.js +346 -0
- package/src/lib/gather.js +346 -0
- package/src/lib/parse.js +328 -0
- package/src/lib/report.js +70 -0
- package/src/lib/run.js +79 -0
- package/src/lib/safety.js +443 -0
- package/src/lib/startup.js +255 -0
- package/src/lib/text.js +16 -0
- package/src/lib/units.js +16 -0
- package/src/lib/win.js +40 -0
- package/src/win/computer.ps1 +88 -0
- package/src/win/folders.ps1 +29 -0
- package/src/win/safety.ps1 +57 -0
- package/src/win/startup.ps1 +54 -0
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
// Collects the facts the computer check is built from. Everything here only looks: no setting
|
|
2
|
+
// is changed, nothing needs admin rights, and nothing is sent anywhere.
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { run, readText } from "./run.js";
|
|
8
|
+
import { cleanText } from "./text.js";
|
|
9
|
+
import { runWinScript, arr } from "./win.js";
|
|
10
|
+
import {
|
|
11
|
+
parseMeminfo,
|
|
12
|
+
parsePressure,
|
|
13
|
+
parseProcStat,
|
|
14
|
+
parseStatusMemory,
|
|
15
|
+
parseDiskstats,
|
|
16
|
+
parseMountinfo,
|
|
17
|
+
mountFor,
|
|
18
|
+
parseOsRelease,
|
|
19
|
+
parsePs,
|
|
20
|
+
parseMacMemory,
|
|
21
|
+
parsePmset,
|
|
22
|
+
parsePmsetTherm,
|
|
23
|
+
parseDiskutil,
|
|
24
|
+
parseSpPower,
|
|
25
|
+
parseLinuxBattery,
|
|
26
|
+
} from "./parse.js";
|
|
27
|
+
import { groupApps } from "./apps.js";
|
|
28
|
+
import { gatherStartup, optionalCount } from "./startup.js";
|
|
29
|
+
|
|
30
|
+
const PLATFORM = process.platform;
|
|
31
|
+
export const SAMPLE_MS = 1500;
|
|
32
|
+
const CLK_TCK = 100; // Linux reports processor time in hundredths of a second
|
|
33
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
34
|
+
const round = (n, d = 1) => (n === null || n === undefined || !Number.isFinite(n) ? null : Math.round(n * 10 ** d) / 10 ** d);
|
|
35
|
+
const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
|
|
36
|
+
|
|
37
|
+
// ---------- processor -------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
function cpuTimes() {
|
|
40
|
+
let idle = 0;
|
|
41
|
+
let total = 0;
|
|
42
|
+
for (const c of os.cpus()) {
|
|
43
|
+
for (const k of Object.keys(c.times)) total += c.times[k];
|
|
44
|
+
idle += c.times.idle;
|
|
45
|
+
}
|
|
46
|
+
return { idle, total };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** How busy all processor cores were, together, over the sample. */
|
|
50
|
+
export async function sampleCpu(ms = SAMPLE_MS) {
|
|
51
|
+
const a = cpuTimes();
|
|
52
|
+
await sleep(ms);
|
|
53
|
+
const b = cpuTimes();
|
|
54
|
+
const dt = b.total - a.total;
|
|
55
|
+
const cores = os.cpus().length || os.availableParallelism?.() || 1;
|
|
56
|
+
return { cores, usePct: dt > 0 ? round(clamp(100 * (1 - (b.idle - a.idle) / dt), 0, 100)) : null };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------- drives ----------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
/** Size and free space of the drive a folder is on, in bytes. */
|
|
62
|
+
export function driveSpace(p) {
|
|
63
|
+
try {
|
|
64
|
+
const s = fs.statfsSync(p);
|
|
65
|
+
const total = s.blocks * s.bsize;
|
|
66
|
+
return total > 0 ? { total, free: s.bavail * s.bsize } : null;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const VIRTUAL = /QEMU|KVM|VMware|VirtualBox|innotek|Xen|Bochs|Parallels|Virtual Machine|Amazon EC2|Google Compute|OpenStack|Hyper-V|VBOX|Virtual/i;
|
|
73
|
+
|
|
74
|
+
/** Linux: the physical disk behind a mounted filesystem, whether it spins, and whether it is encrypted. */
|
|
75
|
+
export function linuxDevice(mount, sys = "/sys") {
|
|
76
|
+
const out = { disk: null, rotational: null, encrypted: false, virtual: false };
|
|
77
|
+
if (!mount) return out;
|
|
78
|
+
let dir = null;
|
|
79
|
+
try {
|
|
80
|
+
dir = fs.realpathSync(`${sys}/dev/block/${mount.majmin}`);
|
|
81
|
+
} catch {
|
|
82
|
+
try {
|
|
83
|
+
if (mount.source?.startsWith("/dev/")) dir = fs.realpathSync(`${sys}/class/block/${path.basename(fs.realpathSync(mount.source))}`);
|
|
84
|
+
} catch {
|
|
85
|
+
/* a filesystem without a block device (network, btrfs subvolume on an unknown device) */
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
for (let depth = 0; dir && depth < 5; depth += 1) {
|
|
89
|
+
if ((readText(`${dir}/dm/uuid`) || "").startsWith("CRYPT-")) out.encrypted = true;
|
|
90
|
+
let slaves = [];
|
|
91
|
+
try {
|
|
92
|
+
slaves = fs.readdirSync(`${dir}/slaves`);
|
|
93
|
+
} catch {
|
|
94
|
+
/* not a stacked device */
|
|
95
|
+
}
|
|
96
|
+
if (!slaves.length) break;
|
|
97
|
+
try {
|
|
98
|
+
dir = fs.realpathSync(`${dir}/slaves/${slaves[0]}`);
|
|
99
|
+
} catch {
|
|
100
|
+
dir = null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!dir) return out;
|
|
104
|
+
if (fs.existsSync(`${dir}/partition`)) dir = path.dirname(dir);
|
|
105
|
+
out.disk = path.basename(dir);
|
|
106
|
+
const rot = readText(`${dir}/queue/rotational`);
|
|
107
|
+
out.rotational = rot === null ? null : rot.trim() === "1";
|
|
108
|
+
const model = `${readText(`${dir}/device/model`) || ""} ${readText(`${dir}/device/vendor`) || ""}`;
|
|
109
|
+
const dmi = `${readText(`${sys}/class/dmi/id/sys_vendor`) || ""} ${readText(`${sys}/class/dmi/id/product_name`) || ""}`;
|
|
110
|
+
out.virtual = VIRTUAL.test(model) || VIRTUAL.test(dmi) || /^(vd|xvd)/.test(out.disk);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---------- Linux -------------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
const INTERPRETER = /^(node|nodejs|python[\d.]*|java|ruby[\d.]*|perl[\d.]*|php[\d.]*|bash|sh|dash|zsh|fish|bun|deno)$/;
|
|
117
|
+
const INTERPRETER_NAME = { node: "Node.js programs", nodejs: "Node.js programs", python: "Python programs", java: "Java programs" };
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A Linux process's name. The kernel's short name (comm) is cut to 15 letters and is often a
|
|
121
|
+
* thread name, so the program file's name is used when it can be read. Programs run by a
|
|
122
|
+
* language runtime (node, python) keep the name they gave themselves, if they gave one.
|
|
123
|
+
*/
|
|
124
|
+
export function linuxProcessName(comm, exePath) {
|
|
125
|
+
const exe = exePath ? path.basename(String(exePath).replace(/ \(deleted\)$/, "")) : null;
|
|
126
|
+
if (!exe) return comm;
|
|
127
|
+
if (!INTERPRETER.test(exe)) return exe;
|
|
128
|
+
const own = comm && comm !== "MainThread" && !exe.startsWith(comm) && !comm.startsWith(exe.slice(0, 15));
|
|
129
|
+
if (own) return comm.split(" ")[0];
|
|
130
|
+
return INTERPRETER_NAME[exe.replace(/[\d.]+$/, "")] || exe;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function readLinuxProcs() {
|
|
134
|
+
const out = new Map();
|
|
135
|
+
let names = [];
|
|
136
|
+
try {
|
|
137
|
+
names = fs.readdirSync("/proc");
|
|
138
|
+
} catch {
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
for (const d of names) {
|
|
142
|
+
if (!/^\d+$/.test(d)) continue;
|
|
143
|
+
const st = parseProcStat(readText(`/proc/${d}/stat`));
|
|
144
|
+
if (st) out.set(Number(d), st);
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function exeOf(pid) {
|
|
150
|
+
try {
|
|
151
|
+
return fs.readlinkSync(`/proc/${pid}/exe`);
|
|
152
|
+
} catch {
|
|
153
|
+
return null; // someone else's process, or a kernel thread
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Times the processor was slowed down for heat since start-up (Intel only), or null. */
|
|
158
|
+
function throttleCount() {
|
|
159
|
+
let total = null;
|
|
160
|
+
try {
|
|
161
|
+
for (const c of fs.readdirSync("/sys/devices/system/cpu")) {
|
|
162
|
+
if (!/^cpu\d+$/.test(c)) continue;
|
|
163
|
+
const v = readText(`/sys/devices/system/cpu/${c}/thermal_throttle/core_throttle_count`);
|
|
164
|
+
if (v !== null && Number.isFinite(Number(v))) total = (total || 0) + Number(v);
|
|
165
|
+
}
|
|
166
|
+
} catch {
|
|
167
|
+
/* no such folder on this machine */
|
|
168
|
+
}
|
|
169
|
+
return total;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function linuxBattery() {
|
|
173
|
+
try {
|
|
174
|
+
const base = "/sys/class/power_supply";
|
|
175
|
+
const bat = fs.readdirSync(base).find((n) => /^BAT/i.test(n));
|
|
176
|
+
if (!bat) return { present: false };
|
|
177
|
+
const values = {};
|
|
178
|
+
for (const k of ["energy_full", "energy_full_design", "charge_full", "charge_full_design", "cycle_count", "capacity", "status"]) values[k] = readText(`${base}/${bat}/${k}`);
|
|
179
|
+
return parseLinuxBattery(values);
|
|
180
|
+
} catch {
|
|
181
|
+
return { present: false };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function linuxFacts() {
|
|
186
|
+
const mounts = parseMountinfo(readText("/proc/self/mountinfo"));
|
|
187
|
+
const dev = linuxDevice(mountFor(mounts, "/"));
|
|
188
|
+
const p1 = readLinuxProcs();
|
|
189
|
+
const d1 = parseDiskstats(readText("/proc/diskstats"));
|
|
190
|
+
const th1 = throttleCount();
|
|
191
|
+
const t1 = performance.now();
|
|
192
|
+
await sleep(SAMPLE_MS);
|
|
193
|
+
const p2 = readLinuxProcs();
|
|
194
|
+
const d2 = parseDiskstats(readText("/proc/diskstats"));
|
|
195
|
+
const th2 = throttleCount();
|
|
196
|
+
const dt = (performance.now() - t1) / 1000;
|
|
197
|
+
|
|
198
|
+
const procs = [];
|
|
199
|
+
for (const [pid, b] of p2) {
|
|
200
|
+
if (pid === process.pid) continue;
|
|
201
|
+
const a = p1.get(pid);
|
|
202
|
+
const cpu = a && a.name === b.name && dt > 0 ? ((b.ticks - a.ticks) / CLK_TCK / dt) * 100 : 0;
|
|
203
|
+
procs.push({ name: b.kernel ? b.name : linuxProcessName(b.name, exeOf(pid)), cpu, mem: b.kernel ? 0 : parseStatusMemory(readText(`/proc/${pid}/status`)), kernel: b.kernel });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
let busyPct = null;
|
|
207
|
+
if (dev.disk && d1.has(dev.disk) && d2.has(dev.disk) && dt > 0) busyPct = round(clamp(((d2.get(dev.disk) - d1.get(dev.disk)) / (dt * 1000)) * 100, 0, 100));
|
|
208
|
+
|
|
209
|
+
const mem = parseMeminfo(readText("/proc/meminfo"));
|
|
210
|
+
const psi = parsePressure(readText("/proc/pressure/memory"));
|
|
211
|
+
const rel = parseOsRelease(readText("/etc/os-release") || readText("/usr/lib/os-release"));
|
|
212
|
+
const profile = (readText("/sys/firmware/acpi/platform_profile") || "").trim();
|
|
213
|
+
return {
|
|
214
|
+
osName: cleanText(rel.PRETTY_NAME, 48) || "Linux",
|
|
215
|
+
procs,
|
|
216
|
+
memory: mem
|
|
217
|
+
? { total: mem.total, available: mem.available, swapTotal: mem.swapTotal, swapUsed: mem.swapTotal - mem.swapFree, waitPct: psi ? psi.some10 : null, pressure: null, commitPct: null }
|
|
218
|
+
: null,
|
|
219
|
+
drive: { ...(driveSpace("/") || {}), kind: dev.virtual ? null : dev.rotational === null ? null : dev.rotational ? "hdd" : "ssd", health: null, busyPct, virtual: dev.virtual },
|
|
220
|
+
restart: { pending: fs.existsSync("/var/run/reboot-required") ? true : fs.existsSync("/var/run") ? false : null, fastStartup: null },
|
|
221
|
+
battery: linuxBattery(),
|
|
222
|
+
power: { saver: profile ? profile === "low-power" : null, efficiencyMode: null },
|
|
223
|
+
thermal: { speedLimit: null, throttledNow: th1 !== null && th2 !== null ? th2 > th1 : null },
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ---------- macOS ---------------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
async function macFacts() {
|
|
230
|
+
const [ps, mem, pm, therm, du, sp, ver] = await Promise.all([
|
|
231
|
+
run("ps", ["-axo", "pid=,pcpu=,rss=,comm="]),
|
|
232
|
+
run("sysctl", ["kern.memorystatus_vm_pressure_level", "kern.memorystatus_level", "vm.swapusage"]),
|
|
233
|
+
run("pmset", ["-g"]),
|
|
234
|
+
run("pmset", ["-g", "therm"]),
|
|
235
|
+
run("diskutil", ["info", "/"]),
|
|
236
|
+
run("system_profiler", ["-json", "SPPowerDataType"], { timeoutMs: 8000 }),
|
|
237
|
+
run("sw_vers", ["-productVersion"]),
|
|
238
|
+
]);
|
|
239
|
+
const procs = parsePs(ps.stdout)
|
|
240
|
+
.filter((p) => p.pid !== process.pid && p.name !== "/bin/ps" && p.name !== "ps")
|
|
241
|
+
.map((p) => ({ name: p.name, cpu: p.cpu, mem: p.mem }));
|
|
242
|
+
const m = parseMacMemory(mem.stdout);
|
|
243
|
+
const total = os.totalmem();
|
|
244
|
+
const disk = parseDiskutil(du.stdout);
|
|
245
|
+
const battery = parseSpPower(sp.stdout);
|
|
246
|
+
const low = parsePmset(pm.stdout).lowPower;
|
|
247
|
+
const pressure = m.pressureLevel === 4 ? "critical" : m.pressureLevel === 2 ? "warn" : m.pressureLevel === 1 ? "normal" : null;
|
|
248
|
+
return {
|
|
249
|
+
osName: `macOS ${ver.stdout.trim() || ""}`.trim(),
|
|
250
|
+
procs,
|
|
251
|
+
memory: { total, available: m.freePct === null ? null : (total * m.freePct) / 100, swapTotal: m.swapTotal, swapUsed: m.swapUsed, waitPct: null, pressure, commitPct: null },
|
|
252
|
+
drive: {
|
|
253
|
+
...(driveSpace("/System/Volumes/Data") || driveSpace("/") || {}),
|
|
254
|
+
kind: disk.solidState === null ? null : disk.solidState ? "ssd" : "hdd",
|
|
255
|
+
health: disk.health,
|
|
256
|
+
busyPct: null,
|
|
257
|
+
virtual: false,
|
|
258
|
+
},
|
|
259
|
+
restart: { pending: null, fastStartup: null },
|
|
260
|
+
battery,
|
|
261
|
+
power: { saver: low ?? battery.lowPower ?? null, efficiencyMode: null },
|
|
262
|
+
thermal: { speedLimit: parsePmsetTherm(therm.stdout).speedLimit, throttledNow: null },
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ---------- Windows ---------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
const POWER_SAVER_SCHEME = "a1841308-3541-4fab-bc81-f71556f20b4a";
|
|
269
|
+
const EFFICIENCY_OVERLAY = "961cc777-2547-4f9d-8174-7d86181b8a7a";
|
|
270
|
+
|
|
271
|
+
/** The JSON from src/win/computer.ps1 -> the same shape the other systems produce. */
|
|
272
|
+
export function normalizeWinComputer(j, systemDrive = process.env.SystemDrive || "C:") {
|
|
273
|
+
if (!j) return null;
|
|
274
|
+
const o = j.os || {};
|
|
275
|
+
const total = Number.isFinite(o.totalKb) ? o.totalKb * 1024 : null;
|
|
276
|
+
const commitPct = o.commitLimitKb > 0 && Number.isFinite(o.commitFreeKb) ? round(100 * (1 - o.commitFreeKb / o.commitLimitKb)) : null;
|
|
277
|
+
const disks = arr(j.disks);
|
|
278
|
+
const sys = disks.find((d) => String(d.id) === String(j.sysDisk)) || (disks.filter((d) => d.bus !== 7).length === 1 ? disks.filter((d) => d.bus !== 7)[0] : null);
|
|
279
|
+
const classic = arr(j.drives).find((d) => d.index === j.sysDisk) || (arr(j.drives).length === 1 ? arr(j.drives)[0] : null);
|
|
280
|
+
let health = null;
|
|
281
|
+
if (sys) health = sys.health === 0 ? "ok" : sys.health === 1 ? "warn" : sys.health === 2 ? "failing" : null;
|
|
282
|
+
if (classic && /pred\s*fail/i.test(classic.status || "")) health = "failing";
|
|
283
|
+
else if (health === null && classic && /^ok$/i.test(classic.status || "")) health = "ok";
|
|
284
|
+
const b = j.battery;
|
|
285
|
+
const onBattery = b?.present ? b.status === 1 : null;
|
|
286
|
+
const overlay = onBattery ? j.power?.overlayDc : j.power?.overlayAc;
|
|
287
|
+
return {
|
|
288
|
+
osName: cleanText(String(o.caption || "Windows").replace(/^Microsoft\s+/, ""), 48) || "Windows",
|
|
289
|
+
procs: arr(j.procs).map((p) => ({ name: p.n, cpu: p.c, mem: p.m })),
|
|
290
|
+
memory: total
|
|
291
|
+
? { total, available: Number.isFinite(o.freeKb) ? o.freeKb * 1024 : null, swapTotal: null, swapUsed: null, waitPct: null, pressure: null, commitPct }
|
|
292
|
+
: null,
|
|
293
|
+
drive: {
|
|
294
|
+
...(driveSpace(`${systemDrive}\\`) || {}),
|
|
295
|
+
kind: sys ? (sys.media === 3 ? "hdd" : sys.media === 4 || sys.media === 5 ? "ssd" : null) : null,
|
|
296
|
+
health,
|
|
297
|
+
busyPct: Number.isFinite(j.diskBusy) ? j.diskBusy : null,
|
|
298
|
+
virtual: /virtual/i.test(String(j.model || "")),
|
|
299
|
+
},
|
|
300
|
+
restart: {
|
|
301
|
+
pending: j.restartUpdate === null && j.restartServicing === null ? null : Boolean(j.restartUpdate || j.restartServicing),
|
|
302
|
+
fastStartup: j.fastStartup === null || j.fastStartup === undefined ? null : j.fastStartup === 1,
|
|
303
|
+
},
|
|
304
|
+
battery: b?.present
|
|
305
|
+
? {
|
|
306
|
+
present: true,
|
|
307
|
+
healthPct: b.full > 0 && b.design > 0 ? Math.min(100, Math.round((b.full / b.design) * 100)) : null,
|
|
308
|
+
cycles: Number.isFinite(b.cycles) && b.cycles > 0 ? b.cycles : null,
|
|
309
|
+
percent: Number.isFinite(b.percent) ? b.percent : null,
|
|
310
|
+
onBattery,
|
|
311
|
+
condition: null,
|
|
312
|
+
}
|
|
313
|
+
: { present: false },
|
|
314
|
+
power: {
|
|
315
|
+
saver: j.energySaver ? j.energySaver === "On" : j.power ? String(j.power.scheme).toLowerCase() === POWER_SAVER_SCHEME : null,
|
|
316
|
+
efficiencyMode: overlay ? String(overlay).toLowerCase() === EFFICIENCY_OVERLAY : null,
|
|
317
|
+
},
|
|
318
|
+
thermal: { speedLimit: null, throttledNow: null },
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function winFacts() {
|
|
323
|
+
return normalizeWinComputer(await runWinScript("computer"));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ---------- everything ------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
export async function gatherComputer() {
|
|
329
|
+
const t0 = performance.now();
|
|
330
|
+
const specific = PLATFORM === "linux" ? linuxFacts() : PLATFORM === "darwin" ? macFacts() : PLATFORM === "win32" ? winFacts() : Promise.resolve(null);
|
|
331
|
+
const [cpu, f, startup] = await Promise.all([sampleCpu(), specific.catch(() => null), gatherStartup().catch(() => null)]);
|
|
332
|
+
const facts = f || { osName: PLATFORM, procs: [], memory: null, drive: driveSpace(os.homedir()) || {}, restart: { pending: null }, battery: { present: false }, power: {}, thermal: {} };
|
|
333
|
+
const { procs, ...rest } = facts;
|
|
334
|
+
return {
|
|
335
|
+
platform: PLATFORM,
|
|
336
|
+
seconds: Math.round((performance.now() - t0) / 1000),
|
|
337
|
+
cores: cpu.cores,
|
|
338
|
+
cpu: { usePct: cpu.usePct },
|
|
339
|
+
apps: groupApps(PLATFORM, procs, cpu.cores),
|
|
340
|
+
processCount: procs.length,
|
|
341
|
+
uptimeSec: Math.round(os.uptime()),
|
|
342
|
+
startup: startup?.readable ? { count: optionalCount(startup.items), readable: true } : { count: null, readable: false },
|
|
343
|
+
incomplete: !f,
|
|
344
|
+
...rest,
|
|
345
|
+
};
|
|
346
|
+
}
|
package/src/lib/parse.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// Readers for the text that Linux and macOS programs and files print. Pure functions, tested
|
|
2
|
+
// against recorded output in test/fixtures. (Windows facts arrive as JSON; see win.js.)
|
|
3
|
+
|
|
4
|
+
const num = (s) => {
|
|
5
|
+
const n = Number(String(s).replace(",", "."));
|
|
6
|
+
return Number.isFinite(n) ? n : null;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
// ---------- Linux ---------------------------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
/** /proc/meminfo -> bytes. */
|
|
12
|
+
export function parseMeminfo(text) {
|
|
13
|
+
const kb = {};
|
|
14
|
+
for (const line of String(text || "").split("\n")) {
|
|
15
|
+
const m = /^(\w+):\s+(\d+)\s*kB/.exec(line);
|
|
16
|
+
if (m) kb[m[1]] = Number(m[2]);
|
|
17
|
+
}
|
|
18
|
+
if (!kb.MemTotal) return null;
|
|
19
|
+
const available = kb.MemAvailable ?? (kb.MemFree || 0) + (kb.Buffers || 0) + (kb.Cached || 0);
|
|
20
|
+
return { total: kb.MemTotal * 1024, available: available * 1024, swapTotal: (kb.SwapTotal || 0) * 1024, swapFree: (kb.SwapFree || 0) * 1024 };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** /proc/pressure/memory -> share of the last 10 seconds in which programs waited for memory. */
|
|
24
|
+
export function parsePressure(text) {
|
|
25
|
+
const some = /^some\s+avg10=([\d.]+)/m.exec(String(text || ""));
|
|
26
|
+
const full = /^full\s+avg10=([\d.]+)/m.exec(String(text || ""));
|
|
27
|
+
if (!some) return null;
|
|
28
|
+
return { some10: Number(some[1]), full10: full ? Number(full[1]) : null };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One /proc/<pid>/stat line -> program name, processor time used so far (in clock ticks), kernel thread or not. */
|
|
32
|
+
export function parseProcStat(text) {
|
|
33
|
+
const s = String(text || "");
|
|
34
|
+
const open = s.indexOf("(");
|
|
35
|
+
const close = s.lastIndexOf(")");
|
|
36
|
+
if (open < 0 || close < open) return null;
|
|
37
|
+
const rest = s.slice(close + 2).trim().split(/\s+/);
|
|
38
|
+
if (rest.length < 13) return null;
|
|
39
|
+
const ticks = Number(rest[11]) + Number(rest[12]);
|
|
40
|
+
if (!Number.isFinite(ticks)) return null;
|
|
41
|
+
return { name: s.slice(open + 1, close), ticks, kernel: (Number(rest[6]) & 0x00200000) !== 0 };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** /proc/<pid>/status -> memory this process holds for itself, in bytes. */
|
|
45
|
+
export function parseStatusMemory(text) {
|
|
46
|
+
const s = String(text || "");
|
|
47
|
+
const anon = /^RssAnon:\s+(\d+)\s*kB/m.exec(s);
|
|
48
|
+
if (anon) return Number(anon[1]) * 1024;
|
|
49
|
+
const rss = /^VmRSS:\s+(\d+)\s*kB/m.exec(s);
|
|
50
|
+
return rss ? Number(rss[1]) * 1024 : 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** /proc/diskstats -> Map(device name -> milliseconds spent doing input/output). */
|
|
54
|
+
export function parseDiskstats(text) {
|
|
55
|
+
const out = new Map();
|
|
56
|
+
for (const line of String(text || "").split("\n")) {
|
|
57
|
+
const p = line.trim().split(/\s+/);
|
|
58
|
+
if (p.length >= 13 && Number.isFinite(Number(p[12]))) out.set(p[2], Number(p[12]));
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const unescapeMount = (s) => s.replace(/\\([0-7]{3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)));
|
|
64
|
+
|
|
65
|
+
/** /proc/self/mountinfo -> [{ majmin, mount, fstype, source }]. */
|
|
66
|
+
export function parseMountinfo(text) {
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const line of String(text || "").split("\n")) {
|
|
69
|
+
const i = line.indexOf(" - ");
|
|
70
|
+
if (i < 0) continue;
|
|
71
|
+
const left = line.slice(0, i).split(" ");
|
|
72
|
+
const right = line.slice(i + 3).split(" ");
|
|
73
|
+
if (left.length < 5 || right.length < 2) continue;
|
|
74
|
+
out.push({ majmin: left[2], mount: unescapeMount(left[4]), fstype: right[0], source: unescapeMount(right[1]) });
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The mounted filesystem a path lives on (the longest mount point that is a prefix of it). */
|
|
80
|
+
export function mountFor(mounts, p) {
|
|
81
|
+
let best = null;
|
|
82
|
+
for (const m of mounts || []) {
|
|
83
|
+
const hit = m.mount === "/" || p === m.mount || p.startsWith(m.mount.endsWith("/") ? m.mount : `${m.mount}/`);
|
|
84
|
+
if (hit && (!best || m.mount.length >= best.mount.length)) best = m;
|
|
85
|
+
}
|
|
86
|
+
return best;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** /etc/os-release -> { ID, VERSION_ID, PRETTY_NAME, ... }. */
|
|
90
|
+
export function parseOsRelease(text) {
|
|
91
|
+
const out = {};
|
|
92
|
+
for (const line of String(text || "").split("\n")) {
|
|
93
|
+
const m = /^([A-Z0-9_]+)=(.*)$/.exec(line.trim());
|
|
94
|
+
if (m) out[m[1]] = m[2].replace(/^["']|["']$/g, "");
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A row of the distribution's own release table (/usr/share/distro-info/*.csv) for this version.
|
|
101
|
+
* Returns { eol, eolEsm } as YYYY-MM-DD strings (or null), or null when the version is not listed.
|
|
102
|
+
*/
|
|
103
|
+
export function parseDistroCsv(text, versionId) {
|
|
104
|
+
const lines = String(text || "").split(/\r?\n/).filter(Boolean);
|
|
105
|
+
if (lines.length < 2 || !versionId) return null;
|
|
106
|
+
const head = lines[0].split(",");
|
|
107
|
+
const col = (name) => head.indexOf(name);
|
|
108
|
+
for (const line of lines.slice(1)) {
|
|
109
|
+
const c = line.split(",");
|
|
110
|
+
const version = (c[col("version")] || "").replace(/\s*LTS$/, "");
|
|
111
|
+
if (version !== String(versionId)) continue;
|
|
112
|
+
const pick = (name) => (col(name) >= 0 && /^\d{4}-\d{2}-\d{2}$/.test(c[col(name)] || "") ? c[col(name)] : null);
|
|
113
|
+
return { eol: pick("eol"), eolEsm: pick("eol-esm") || pick("eol-lts") };
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** An autostart .desktop file -> { name, enabled }. */
|
|
119
|
+
export function parseDesktopEntry(text) {
|
|
120
|
+
let inEntry = false;
|
|
121
|
+
let name = null;
|
|
122
|
+
let enabled = true;
|
|
123
|
+
for (const raw of String(text || "").split("\n")) {
|
|
124
|
+
const line = raw.trim();
|
|
125
|
+
if (line.startsWith("[")) {
|
|
126
|
+
inEntry = line === "[Desktop Entry]";
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (!inEntry) continue;
|
|
130
|
+
const m = /^([A-Za-z0-9-]+)\s*=\s*(.*)$/.exec(line);
|
|
131
|
+
if (!m) continue;
|
|
132
|
+
if (m[1] === "Name" && !name) name = m[2];
|
|
133
|
+
if (m[1] === "Hidden" && /^true$/i.test(m[2])) enabled = false;
|
|
134
|
+
if (m[1] === "X-GNOME-Autostart-enabled" && /^false$/i.test(m[2])) enabled = false;
|
|
135
|
+
}
|
|
136
|
+
return { name, enabled };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Ubuntu's /var/lib/update-notifier/updates-available -> { updates, security }. */
|
|
140
|
+
export function parseUpdatesAvailable(text) {
|
|
141
|
+
const s = String(text || "");
|
|
142
|
+
const u = /(\d+) updates? can be applied immediately/.exec(s);
|
|
143
|
+
if (!u) return null;
|
|
144
|
+
const sec = /(\d+) of these updates? (?:is a|are) standard security updates?/.exec(s);
|
|
145
|
+
return { updates: Number(u[1]), security: sec ? Number(sec[1]) : 0 };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* /proc/net/tcp or /proc/net/tcp6 -> ports this computer accepts connections on from other
|
|
150
|
+
* devices (programs that only listen to the computer itself are left out).
|
|
151
|
+
*/
|
|
152
|
+
export function parseListening(text) {
|
|
153
|
+
const ports = new Set();
|
|
154
|
+
for (const line of String(text || "").split("\n").slice(1)) {
|
|
155
|
+
const p = line.trim().split(/\s+/);
|
|
156
|
+
if (p.length < 4 || p[3] !== "0A") continue;
|
|
157
|
+
const [addr, port] = p[1].split(":");
|
|
158
|
+
// Addresses are printed as hex words: 127.x.x.x ends in 7F, ::1 is all zeros and a final 01000000.
|
|
159
|
+
const loopback = addr.length === 8 ? /7F$/i.test(addr) : addr === "00000000000000000000000001000000" || /^0{16}FFFF0000[0-9A-F]{6}7F$/i.test(addr);
|
|
160
|
+
if (!loopback) ports.add(parseInt(port, 16));
|
|
161
|
+
}
|
|
162
|
+
return ports;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ---------- macOS ---------------------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
/** `ps -axo pid=,pcpu=,rss=,comm=` -> [{ pid, cpu, mem, name }]; cpu is % of one core, mem in bytes. */
|
|
168
|
+
export function parsePs(text) {
|
|
169
|
+
const out = [];
|
|
170
|
+
for (const line of String(text || "").split("\n")) {
|
|
171
|
+
const m = /^\s*(\d+)\s+([\d.,]+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
|
|
172
|
+
if (m) out.push({ pid: Number(m[1]), cpu: num(m[2]) ?? 0, mem: Number(m[3]) * 1024, name: m[4] });
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const sizeToBytes = (value, unit) => Number(value) * ({ K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 }[unit.toUpperCase()] || 1);
|
|
178
|
+
|
|
179
|
+
/** `sysctl kern.memorystatus_vm_pressure_level kern.memorystatus_level vm.swapusage`. */
|
|
180
|
+
export function parseMacMemory(text) {
|
|
181
|
+
const s = String(text || "");
|
|
182
|
+
const level = /kern\.memorystatus_vm_pressure_level:\s*(\d+)/.exec(s);
|
|
183
|
+
const free = /kern\.memorystatus_level:\s*(\d+)/.exec(s);
|
|
184
|
+
const total = /vm\.swapusage:.*?total\s*=\s*([\d.]+)([KMGT])/.exec(s);
|
|
185
|
+
const used = /vm\.swapusage:.*?used\s*=\s*([\d.]+)([KMGT])/.exec(s);
|
|
186
|
+
return {
|
|
187
|
+
pressureLevel: level ? Number(level[1]) : null,
|
|
188
|
+
freePct: free ? Number(free[1]) : null,
|
|
189
|
+
swapTotal: total ? sizeToBytes(total[1], total[2]) : null,
|
|
190
|
+
swapUsed: used ? sizeToBytes(used[1], used[2]) : null,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** `pmset -g` -> is Low Power Mode on? (null when this Mac has no such setting) */
|
|
195
|
+
export function parsePmset(text) {
|
|
196
|
+
const m = /^\s*lowpowermode\s+(\d)/m.exec(String(text || ""));
|
|
197
|
+
return { lowPower: m ? m[1] === "1" : null };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** `pmset -g therm` -> the speed limit macOS has put on the processor because of heat (100 = none). */
|
|
201
|
+
export function parsePmsetTherm(text) {
|
|
202
|
+
const m = /CPU_Speed_Limit\s*=\s*(\d+)/.exec(String(text || ""));
|
|
203
|
+
return { speedLimit: m ? Number(m[1]) : null };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** `diskutil info /` -> drive type and its own health report. */
|
|
207
|
+
export function parseDiskutil(text) {
|
|
208
|
+
const s = String(text || "");
|
|
209
|
+
const solid = /^\s*Solid State:\s*(Yes|No)/im.exec(s);
|
|
210
|
+
const smart = /^\s*SMART Status:\s*(.+?)\s*$/im.exec(s);
|
|
211
|
+
let health = null;
|
|
212
|
+
if (smart) health = /verified/i.test(smart[1]) ? "ok" : /fail/i.test(smart[1]) ? "failing" : null;
|
|
213
|
+
return { solidState: solid ? /yes/i.test(solid[1]) : null, health };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** `system_profiler -json SPPowerDataType` -> battery facts. Serial numbers in it are never read. */
|
|
217
|
+
export function parseSpPower(json) {
|
|
218
|
+
let data;
|
|
219
|
+
try {
|
|
220
|
+
data = typeof json === "string" ? JSON.parse(json) : json;
|
|
221
|
+
} catch {
|
|
222
|
+
return { present: false };
|
|
223
|
+
}
|
|
224
|
+
const items = data?.SPPowerDataType || [];
|
|
225
|
+
const batt = items.find((x) => x._name === "spbattery_information");
|
|
226
|
+
if (!batt) return { present: false };
|
|
227
|
+
const health = batt.sppower_battery_health_info || {};
|
|
228
|
+
const charge = batt.sppower_battery_charge_info || {};
|
|
229
|
+
const cap = /(\d+)/.exec(String(health.sppower_battery_health_maximum_capacity || ""));
|
|
230
|
+
const power = items.find((x) => x._name === "sppower_information") || {};
|
|
231
|
+
const source = Object.values(power).find((v) => v && typeof v === "object" && v["Current Power Source"] === "TRUE");
|
|
232
|
+
return {
|
|
233
|
+
present: true,
|
|
234
|
+
cycles: Number.isFinite(health.sppower_battery_cycle_count) ? health.sppower_battery_cycle_count : null,
|
|
235
|
+
condition: health.sppower_battery_health || null,
|
|
236
|
+
healthPct: cap ? Number(cap[1]) : null,
|
|
237
|
+
percent: Number.isFinite(charge.sppower_battery_state_of_charge) ? charge.sppower_battery_state_of_charge : null,
|
|
238
|
+
onBattery: power["Battery Power"]?.["Current Power Source"] === "TRUE" ? true : power["AC Power"]?.["Current Power Source"] === "TRUE" ? false : null,
|
|
239
|
+
lowPower: source && "LowPowerMode" in source ? source.LowPowerMode === "Yes" : null,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** `defaults read /Library/Preferences/com.apple.SoftwareUpdate` -> update settings and what is waiting. */
|
|
244
|
+
export function parseSoftwareUpdate(text) {
|
|
245
|
+
const s = String(text || "");
|
|
246
|
+
if (!/[{]/.test(s)) return null;
|
|
247
|
+
const flag = (key) => {
|
|
248
|
+
const m = new RegExp(`^\\s*${key}\\s*=\\s*(\\d+);`, "m").exec(s);
|
|
249
|
+
return m ? m[1] !== "0" : null;
|
|
250
|
+
};
|
|
251
|
+
const block = /RecommendedUpdates\s*=\s*\(([\s\S]*?)\n\s*\);/.exec(s);
|
|
252
|
+
const pending = block ? [...block[1].matchAll(/"Display Name"\s*=\s*"?([^";]+)"?;/g)].map((m) => m[1].trim()) : [];
|
|
253
|
+
const installs = /InstallDateDictionary\s*=\s*\{([\s\S]*?)\}/.exec(s);
|
|
254
|
+
let lastInstall = null;
|
|
255
|
+
if (installs) {
|
|
256
|
+
for (const m of installs[1].matchAll(/"(\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [+-]\d{4}"/g)) if (!lastInstall || m[1] > lastInstall) lastInstall = m[1];
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
autoCheck: flag("AutomaticCheckEnabled"),
|
|
260
|
+
autoDownload: flag("AutomaticDownload"),
|
|
261
|
+
autoInstallOS: flag("AutomaticallyInstallMacOSUpdates"),
|
|
262
|
+
criticalInstall: flag("CriticalUpdateInstall"),
|
|
263
|
+
pending,
|
|
264
|
+
lastInstall,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** /Library/Receipts/InstallHistory.plist -> date (YYYY-MM-DD) of the newest macOS system update. */
|
|
269
|
+
export function parseInstallHistory(xml) {
|
|
270
|
+
let last = null;
|
|
271
|
+
for (const m of String(xml || "").matchAll(/<dict>([\s\S]*?)<\/dict>/g)) {
|
|
272
|
+
const name = /<key>displayName<\/key>\s*<string>([^<]*)<\/string>/.exec(m[1]);
|
|
273
|
+
const date = /<key>date<\/key>\s*<date>(\d{4}-\d{2}-\d{2})T/.exec(m[1]);
|
|
274
|
+
if (name && date && /^macOS\b/.test(name[1]) && (!last || date[1] > last)) last = date[1];
|
|
275
|
+
}
|
|
276
|
+
return last;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export const parseFileVault = (text) => (/FileVault is On/i.test(text || "") ? true : /FileVault is Off/i.test(text || "") ? false : null);
|
|
280
|
+
|
|
281
|
+
/** `socketfilterfw --getglobalstate`: State = 0 is off, 1 is on, 2 is on and blocking everything incoming. */
|
|
282
|
+
export function parseMacFirewall(text) {
|
|
283
|
+
const m = /State\s*=\s*(\d)/.exec(String(text || ""));
|
|
284
|
+
if (m) return m[1] !== "0";
|
|
285
|
+
return /Firewall is enabled/i.test(text || "") ? true : /Firewall is disabled/i.test(text || "") ? false : null;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export const parseGatekeeper = (text) => (/assessments enabled/i.test(text || "") ? true : /assessments disabled/i.test(text || "") ? false : null);
|
|
289
|
+
export const parseSip = (text) => (/status:\s*enabled/i.test(text || "") ? true : /status:\s*disabled/i.test(text || "") ? false : null);
|
|
290
|
+
|
|
291
|
+
/** `sysadminctl -screenLock status` (it prints to the error stream, with a timestamp in front). */
|
|
292
|
+
export function parseScreenLock(text) {
|
|
293
|
+
const s = String(text || "");
|
|
294
|
+
if (/screenLock is off/i.test(s)) return { on: false, delaySec: null };
|
|
295
|
+
if (/screenLock delay is immediate/i.test(s)) return { on: true, delaySec: 0 };
|
|
296
|
+
const m = /screenLock delay is (\d+) seconds/i.exec(s);
|
|
297
|
+
if (m) return { on: true, delaySec: Number(m[1]) };
|
|
298
|
+
return { on: null, delaySec: null };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** `tmutil destinationinfo` -> is a Time Machine backup drive set up? */
|
|
302
|
+
export function parseTimeMachine(text) {
|
|
303
|
+
const s = String(text || "");
|
|
304
|
+
if (/No destinations configured/i.test(s)) return { configured: false };
|
|
305
|
+
if (/^\s*(Name|Kind|ID)\s*:/m.test(s)) return { configured: true };
|
|
306
|
+
return { configured: null };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ---------- Linux power ----------------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
/** Battery wear from the numbers under /sys/class/power_supply/BAT*. values: { name: text }. */
|
|
312
|
+
export function parseLinuxBattery(values) {
|
|
313
|
+
const n = (k) => {
|
|
314
|
+
const v = Number(String(values?.[k] ?? "").trim());
|
|
315
|
+
return Number.isFinite(v) && String(values?.[k] ?? "").trim() !== "" ? v : null;
|
|
316
|
+
};
|
|
317
|
+
const full = n("energy_full") ?? n("charge_full");
|
|
318
|
+
const design = n("energy_full_design") ?? n("charge_full_design");
|
|
319
|
+
const status = String(values?.status ?? "").trim();
|
|
320
|
+
return {
|
|
321
|
+
present: true,
|
|
322
|
+
healthPct: full && design ? Math.min(100, Math.round((full / design) * 100)) : null,
|
|
323
|
+
cycles: n("cycle_count") || null,
|
|
324
|
+
percent: n("capacity"),
|
|
325
|
+
onBattery: status ? /^Discharging$/i.test(status) : null,
|
|
326
|
+
condition: null,
|
|
327
|
+
};
|
|
328
|
+
}
|