@sdeck/plugin-system 0.0.0-stage → 0.3.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/dist/controls.d.ts +36 -0
- package/dist/controls.d.ts.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1731 -0
- package/dist/index.js.map +13 -0
- package/dist/monitor.d.ts +80 -0
- package/dist/monitor.d.ts.map +1 -0
- package/dist/watchers.d.ts +34 -0
- package/dist/watchers.d.ts.map +1 -0
- package/package.json +60 -4
- package/src/controls.ts +305 -0
- package/src/index.tsx +1075 -0
- package/src/monitor.ts +432 -0
- package/src/watchers.ts +245 -0
- package/README.md +0 -3
package/src/monitor.ts
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Measurements behind the monitoring state: per-core CPU, disks, network throughput, ping, GPU,
|
|
3
|
+
* CPU temperature and frame rate. Anything this computer cannot measure throws an
|
|
4
|
+
* {@link Unavailable} saying why.
|
|
5
|
+
*/
|
|
6
|
+
import { type ChildProcess, execFile, spawn } from "node:child_process";
|
|
7
|
+
import { readdir, readFile, statfs } from "node:fs/promises";
|
|
8
|
+
import { cpus, homedir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
/** This computer (or what is installed on it) cannot provide a value. */
|
|
12
|
+
export class Unavailable extends Error {}
|
|
13
|
+
|
|
14
|
+
/** Runs a program; a missing one is {@link Unavailable}. */
|
|
15
|
+
export function capture(
|
|
16
|
+
file: string,
|
|
17
|
+
args: string[],
|
|
18
|
+
options: { timeoutMs?: number; signal?: AbortSignal } = {},
|
|
19
|
+
): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
execFile(
|
|
22
|
+
file,
|
|
23
|
+
args,
|
|
24
|
+
{
|
|
25
|
+
windowsHide: true,
|
|
26
|
+
timeout: options.timeoutMs ?? 10_000,
|
|
27
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
28
|
+
...(options.signal && { signal: options.signal }),
|
|
29
|
+
},
|
|
30
|
+
(error, stdout, stderr) => {
|
|
31
|
+
const code = error ? (error as { code?: unknown }).code : 0;
|
|
32
|
+
if (code === "ENOENT") return reject(new Unavailable(`"${file}" is not installed`));
|
|
33
|
+
resolve({ code: typeof code === "number" ? code : -1, stdout, stderr });
|
|
34
|
+
},
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// -- CPU and disks ------------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
type Times = { idle: number; total: number };
|
|
42
|
+
|
|
43
|
+
const coreTimes = (): Times[] =>
|
|
44
|
+
cpus().map(({ times: t }) => ({
|
|
45
|
+
idle: t.idle,
|
|
46
|
+
total: t.user + t.nice + t.sys + t.irq + t.idle,
|
|
47
|
+
}));
|
|
48
|
+
|
|
49
|
+
/** Each core's use since the previous call, 0–100. */
|
|
50
|
+
export function coreSampler(read: () => Times[] = coreTimes): () => number[] {
|
|
51
|
+
let last = read();
|
|
52
|
+
return () => {
|
|
53
|
+
const now = read();
|
|
54
|
+
const out = now.map((core, i) => {
|
|
55
|
+
const total = core.total - (last[i]?.total ?? 0);
|
|
56
|
+
const idle = core.idle - (last[i]?.idle ?? 0);
|
|
57
|
+
return total > 0 ? Math.round(100 * (1 - idle / total)) : 0;
|
|
58
|
+
});
|
|
59
|
+
last = now;
|
|
60
|
+
return out;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface Disk {
|
|
65
|
+
/** 0–100. */
|
|
66
|
+
percent: number;
|
|
67
|
+
free: number;
|
|
68
|
+
total: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The disk holding `path`. */
|
|
72
|
+
export async function diskUsage(path: string): Promise<Disk> {
|
|
73
|
+
const s = await statfs(path);
|
|
74
|
+
const total = s.blocks * s.bsize;
|
|
75
|
+
const free = s.bavail * s.bsize;
|
|
76
|
+
if (total <= 0) throw new Unavailable(`no size for ${path}`);
|
|
77
|
+
return { percent: Math.round(100 * (1 - free / total)), free, total };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// -- Network ------------------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
/** Bytes moved since the computer started, over its physical interfaces. */
|
|
83
|
+
export interface Counters {
|
|
84
|
+
received: number;
|
|
85
|
+
sent: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Interfaces that repeat traffic or never leave the computer. */
|
|
89
|
+
const VIRTUAL = /^(lo|docker|veth|br-|virbr|vmnet|utun|awdl|llw|bridge)/;
|
|
90
|
+
|
|
91
|
+
export function parseProcNetDev(text: string): Counters {
|
|
92
|
+
const total = { received: 0, sent: 0 };
|
|
93
|
+
for (const line of text.split("\n")) {
|
|
94
|
+
const match = /^\s*([^:]+):\s*(.*)$/.exec(line);
|
|
95
|
+
if (!match?.[1] || VIRTUAL.test(match[1].trim())) continue;
|
|
96
|
+
const fields = (match[2] ?? "").trim().split(/\s+/).map(Number);
|
|
97
|
+
total.received += fields[0] || 0;
|
|
98
|
+
total.sent += fields[8] || 0;
|
|
99
|
+
}
|
|
100
|
+
return total;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** `netstat -ibn`: one `<Link#n>` row per interface, with its byte columns. */
|
|
104
|
+
export function parseNetstat(text: string): Counters {
|
|
105
|
+
const total = { received: 0, sent: 0 };
|
|
106
|
+
const lines = text.split("\n");
|
|
107
|
+
const header = (lines[0] ?? "").trim().split(/\s+/);
|
|
108
|
+
const fromEnd = (name: string) => header.length - header.indexOf(name);
|
|
109
|
+
for (const line of lines.slice(1)) {
|
|
110
|
+
const fields = line.trim().split(/\s+/);
|
|
111
|
+
if (!fields[0] || VIRTUAL.test(fields[0]) || !fields[2]?.startsWith("<Link")) continue;
|
|
112
|
+
// The address column is empty for some interfaces, so count from the end.
|
|
113
|
+
total.received += Number(fields[fields.length - fromEnd("Ibytes")]) || 0;
|
|
114
|
+
total.sent += Number(fields[fields.length - fromEnd("Obytes")]) || 0;
|
|
115
|
+
}
|
|
116
|
+
return total;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Bytes per second between two readings; counters that went backwards count as zero. */
|
|
120
|
+
export function throughput(before: Counters, after: Counters, seconds: number): Counters {
|
|
121
|
+
const rate = (a: number, b: number) =>
|
|
122
|
+
seconds > 0 ? Math.max(0, Math.round((b - a) / seconds)) : 0;
|
|
123
|
+
return {
|
|
124
|
+
received: rate(before.received, after.received),
|
|
125
|
+
sent: rate(before.sent, after.sent),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const WINDOWS_NETWORK = `
|
|
130
|
+
while ($true) {
|
|
131
|
+
$rx = 0; $tx = 0
|
|
132
|
+
foreach ($n in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
|
133
|
+
if ($n.OperationalStatus -ne 'Up' -or $n.NetworkInterfaceType -eq 'Loopback' -or $n.NetworkInterfaceType -eq 'Tunnel') { continue }
|
|
134
|
+
if ($n.Description -match 'Virtual|Hyper-V|vEthernet|Filter|VirtualBox|VMware') { continue }
|
|
135
|
+
$s = $n.GetIPStatistics(); $rx += $s.BytesReceived; $tx += $s.BytesSent
|
|
136
|
+
}
|
|
137
|
+
[Console]::Out.WriteLine("$rx $tx"); [Console]::Out.Flush()
|
|
138
|
+
Start-Sleep -Seconds 1
|
|
139
|
+
}
|
|
140
|
+
`;
|
|
141
|
+
|
|
142
|
+
/** Runs `read` for every line a child process prints; returns a function that kills it. */
|
|
143
|
+
function lines(
|
|
144
|
+
child: ChildProcess,
|
|
145
|
+
read: (line: string) => void,
|
|
146
|
+
onError: (error: Error) => void,
|
|
147
|
+
): () => void {
|
|
148
|
+
let buffer = "";
|
|
149
|
+
let stopped = false;
|
|
150
|
+
child.stdout?.setEncoding("utf8");
|
|
151
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
152
|
+
buffer += chunk;
|
|
153
|
+
const parts = buffer.split(/\r?\n/);
|
|
154
|
+
buffer = parts.pop() ?? "";
|
|
155
|
+
for (const line of parts) read(line);
|
|
156
|
+
});
|
|
157
|
+
child.once("error", (error) => {
|
|
158
|
+
stopped = true;
|
|
159
|
+
const missing = (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
160
|
+
onError(missing ? new Unavailable(`"${child.spawnfile}" is not installed`) : error);
|
|
161
|
+
});
|
|
162
|
+
child.once("close", (code) => {
|
|
163
|
+
if (!stopped && code !== 0) onError(new Unavailable(`"${child.spawnfile}" exited (${code})`));
|
|
164
|
+
});
|
|
165
|
+
return () => {
|
|
166
|
+
stopped = true;
|
|
167
|
+
child.kill();
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Download and upload speed in bytes per second, about once a second. */
|
|
172
|
+
export function watchNetwork(
|
|
173
|
+
emit: (rate: Counters) => void,
|
|
174
|
+
onError: (error: Error) => void,
|
|
175
|
+
): () => void {
|
|
176
|
+
let last: { counters: Counters; at: number } | undefined;
|
|
177
|
+
const sample = (counters: Counters) => {
|
|
178
|
+
const at = performance.now();
|
|
179
|
+
if (last) emit(throughput(last.counters, counters, (at - last.at) / 1000));
|
|
180
|
+
last = { counters, at };
|
|
181
|
+
};
|
|
182
|
+
if (process.platform === "win32") {
|
|
183
|
+
const encoded = Buffer.from(WINDOWS_NETWORK, "utf16le").toString("base64");
|
|
184
|
+
const child = spawn(
|
|
185
|
+
"powershell.exe",
|
|
186
|
+
["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded],
|
|
187
|
+
{ cwd: homedir(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true },
|
|
188
|
+
);
|
|
189
|
+
return lines(
|
|
190
|
+
child,
|
|
191
|
+
(line) => {
|
|
192
|
+
const [received, sent] = line.trim().split(" ").map(Number);
|
|
193
|
+
if (Number.isFinite(received) && Number.isFinite(sent)) {
|
|
194
|
+
sample({ received: received as number, sent: sent as number });
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
onError,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
const read = async () => {
|
|
201
|
+
try {
|
|
202
|
+
sample(
|
|
203
|
+
process.platform === "darwin"
|
|
204
|
+
? parseNetstat((await capture("netstat", ["-ibn"])).stdout)
|
|
205
|
+
: parseProcNetDev(await readFile("/proc/net/dev", "utf8")),
|
|
206
|
+
);
|
|
207
|
+
} catch (error) {
|
|
208
|
+
onError(error as Error);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
void read();
|
|
212
|
+
const timer = setInterval(read, 1000);
|
|
213
|
+
return () => clearInterval(timer);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// -- Ping ---------------------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
/** A host name or address; nothing that `ping` could read as an option. */
|
|
219
|
+
export function isHost(host: string): boolean {
|
|
220
|
+
return /^[A-Za-z0-9_[][A-Za-z0-9_.:%[\]-]{0,252}$/.test(host);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The round trip in a `ping` reply, in ms. Output is localised (`time=12ms`, `Zeit<1ms`,
|
|
225
|
+
* `temps=3 ms`), so only the `=`/`<`, the number and `ms` on a line with a TTL are relied on.
|
|
226
|
+
*/
|
|
227
|
+
export function parsePing(output: string): number | undefined {
|
|
228
|
+
for (const line of output.split(/\r?\n/)) {
|
|
229
|
+
if (!/ttl/i.test(line) && !/time[=<]/i.test(line)) continue;
|
|
230
|
+
const match = /[=<]\s*([\d.,]+)\s*ms/i.exec(line);
|
|
231
|
+
if (match?.[1]) return Number(match[1].replace(",", "."));
|
|
232
|
+
}
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** One ping to `host`; its round trip in ms. Rejects when there is no answer. */
|
|
237
|
+
export async function ping(host: string, signal?: AbortSignal): Promise<number> {
|
|
238
|
+
const target = host.trim();
|
|
239
|
+
if (!isHost(target)) throw new Error(`"${host}" is not a host name or address`);
|
|
240
|
+
const args =
|
|
241
|
+
process.platform === "win32"
|
|
242
|
+
? ["-n", "1", "-w", "2000", target]
|
|
243
|
+
: ["-c", "1", "-W", process.platform === "darwin" ? "2000" : "2", target];
|
|
244
|
+
const { stdout } = await capture("ping", args, { timeoutMs: 5000, ...(signal && { signal }) });
|
|
245
|
+
const ms = parsePing(stdout);
|
|
246
|
+
if (ms === undefined) throw new Error(`${target} did not answer`);
|
|
247
|
+
return ms;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// -- GPU and temperatures -----------------------------------------------------------------------
|
|
251
|
+
|
|
252
|
+
export interface Gpu {
|
|
253
|
+
name: string;
|
|
254
|
+
/** Percent busy. */
|
|
255
|
+
load: number | undefined;
|
|
256
|
+
/** °C. */
|
|
257
|
+
temperature: number | undefined;
|
|
258
|
+
/** Percent of its memory in use. */
|
|
259
|
+
memory: number | undefined;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export const NVIDIA_QUERY = [
|
|
263
|
+
"--query-gpu=name,utilization.gpu,temperature.gpu,memory.used,memory.total",
|
|
264
|
+
"--format=csv,noheader,nounits",
|
|
265
|
+
];
|
|
266
|
+
|
|
267
|
+
/** The first GPU in `nvidia-smi`'s CSV (`[N/A]` fields are left out). */
|
|
268
|
+
export function parseNvidia(csv: string): Gpu | undefined {
|
|
269
|
+
const fields = csv
|
|
270
|
+
.split(/\r?\n/)[0]
|
|
271
|
+
?.split(",")
|
|
272
|
+
.map((f) => f.trim());
|
|
273
|
+
if (!fields || fields.length < 5 || !fields[0]) return undefined;
|
|
274
|
+
const number = (text: string | undefined) => {
|
|
275
|
+
const n = Number(text);
|
|
276
|
+
return text && Number.isFinite(n) ? n : undefined;
|
|
277
|
+
};
|
|
278
|
+
const used = number(fields[3]);
|
|
279
|
+
const total = number(fields[4]);
|
|
280
|
+
return {
|
|
281
|
+
name: fields[0],
|
|
282
|
+
load: number(fields[1]),
|
|
283
|
+
temperature: number(fields[2]),
|
|
284
|
+
memory: used !== undefined && total ? Math.round((100 * used) / total) : undefined,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export async function readGpu(): Promise<Gpu> {
|
|
289
|
+
const { code, stdout, stderr } = await capture("nvidia-smi", NVIDIA_QUERY);
|
|
290
|
+
const gpu = code === 0 ? parseNvidia(stdout) : undefined;
|
|
291
|
+
if (!gpu) throw new Unavailable(stderr.trim() || "nvidia-smi reported no GPU");
|
|
292
|
+
return gpu;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const WINDOWS_TEMPERATURE =
|
|
296
|
+
"(Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature -ErrorAction Stop | Measure-Object -Property CurrentTemperature -Maximum).Maximum";
|
|
297
|
+
|
|
298
|
+
/** WMI thermal zones are in tenths of a kelvin. */
|
|
299
|
+
export function parseThermalZone(output: string): number | undefined {
|
|
300
|
+
const raw = Number(output.trim());
|
|
301
|
+
return output.trim() && Number.isFinite(raw) && raw > 0
|
|
302
|
+
? Math.round(raw / 10 - 273.15)
|
|
303
|
+
: undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The CPU temperature in °C, where the system exposes one. */
|
|
307
|
+
export async function cpuTemperature(thermal = "/sys/class/thermal"): Promise<number> {
|
|
308
|
+
if (process.platform === "win32") {
|
|
309
|
+
const { code, stdout } = await capture("powershell.exe", [
|
|
310
|
+
"-NoProfile",
|
|
311
|
+
"-NonInteractive",
|
|
312
|
+
"-Command",
|
|
313
|
+
WINDOWS_TEMPERATURE,
|
|
314
|
+
]);
|
|
315
|
+
const value = code === 0 ? parseThermalZone(stdout) : undefined;
|
|
316
|
+
if (value === undefined) {
|
|
317
|
+
throw new Unavailable(
|
|
318
|
+
"Windows exposes no thermal zone (common on desktops; it may need administrator rights)",
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
return value;
|
|
322
|
+
}
|
|
323
|
+
const readings: { type: string; value: number }[] = [];
|
|
324
|
+
for (const zone of await readdir(thermal).catch(() => [])) {
|
|
325
|
+
if (!zone.startsWith("thermal_zone")) continue;
|
|
326
|
+
try {
|
|
327
|
+
const type = (await readFile(join(thermal, zone, "type"), "utf8")).trim();
|
|
328
|
+
const value = Number(await readFile(join(thermal, zone, "temp"), "utf8")) / 1000;
|
|
329
|
+
if (Number.isFinite(value)) readings.push({ type, value });
|
|
330
|
+
} catch {
|
|
331
|
+
// Some zones cannot be read; use the others.
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const cpu = readings.filter((r) => /pkg|cpu|k10|core/i.test(r.type));
|
|
335
|
+
const pool = cpu.length > 0 ? cpu : readings;
|
|
336
|
+
if (pool.length === 0) throw new Unavailable("no temperature sensor is exposed");
|
|
337
|
+
return Math.round(Math.max(...pool.map((r) => r.value)));
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// -- Frame rate ---------------------------------------------------------------------------------
|
|
341
|
+
|
|
342
|
+
export interface Frame {
|
|
343
|
+
app: string;
|
|
344
|
+
/** Time since the app's previous frame, ms. */
|
|
345
|
+
ms: number;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Reads PresentMon's CSV (1.x and 2.x column names): the header first, then one frame a line. */
|
|
349
|
+
export function presentMonParser(): (line: string) => Frame | undefined {
|
|
350
|
+
let app = -1;
|
|
351
|
+
let time = -1;
|
|
352
|
+
return (line) => {
|
|
353
|
+
const fields = line.split(",");
|
|
354
|
+
if (time < 0) {
|
|
355
|
+
const names = fields.map((f) => f.trim().toLowerCase());
|
|
356
|
+
app = names.indexOf("application");
|
|
357
|
+
time =
|
|
358
|
+
["msbetweenpresents", "frametime"].map((n) => names.indexOf(n)).find((i) => i >= 0) ?? -1;
|
|
359
|
+
return undefined;
|
|
360
|
+
}
|
|
361
|
+
const ms = Number(fields[time]);
|
|
362
|
+
const name = fields[app]?.trim().toLowerCase();
|
|
363
|
+
return name && Number.isFinite(ms) && ms > 0 ? { app: name, ms } : undefined;
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** The desktop compositor presents all the time; it is not what anyone means by "FPS". */
|
|
368
|
+
const COMPOSITORS = new Set(["dwm.exe"]);
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Frames per second of `foreground` among these frames, or else of the app that drew most.
|
|
372
|
+
* `undefined` when nothing drew.
|
|
373
|
+
*/
|
|
374
|
+
export function frameRate(frames: readonly Frame[], foreground?: string): number | undefined {
|
|
375
|
+
const byApp = new Map<string, Frame[]>();
|
|
376
|
+
for (const frame of frames) {
|
|
377
|
+
if (COMPOSITORS.has(frame.app)) continue;
|
|
378
|
+
const list = byApp.get(frame.app);
|
|
379
|
+
if (list) list.push(frame);
|
|
380
|
+
else byApp.set(frame.app, [frame]);
|
|
381
|
+
}
|
|
382
|
+
const chosen =
|
|
383
|
+
(foreground ? byApp.get(foreground.toLowerCase()) : undefined) ??
|
|
384
|
+
[...byApp.values()].sort((a, b) => b.length - a.length)[0];
|
|
385
|
+
if (!chosen) return undefined;
|
|
386
|
+
const total = chosen.reduce((sum, f) => sum + f.ms, 0);
|
|
387
|
+
return Math.round((1000 * chosen.length) / total);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Frames per second once a second, from PresentMon (Windows; it needs administrator rights). */
|
|
391
|
+
export function watchFrameRate(
|
|
392
|
+
command: string,
|
|
393
|
+
foreground: () => string | undefined,
|
|
394
|
+
emit: (fps: number | undefined) => void,
|
|
395
|
+
onError: (error: Error) => void,
|
|
396
|
+
): () => void {
|
|
397
|
+
if (process.platform !== "win32") {
|
|
398
|
+
onError(new Unavailable("frame rates need PresentMon, which is Windows only"));
|
|
399
|
+
return () => {};
|
|
400
|
+
}
|
|
401
|
+
const parse = presentMonParser();
|
|
402
|
+
let frames: Frame[] = [];
|
|
403
|
+
const child = spawn(command, ["--output_stdout", "--stop_existing_session"], {
|
|
404
|
+
cwd: homedir(),
|
|
405
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
406
|
+
windowsHide: true,
|
|
407
|
+
});
|
|
408
|
+
const stop = lines(
|
|
409
|
+
child,
|
|
410
|
+
(line) => {
|
|
411
|
+
const frame = parse(line);
|
|
412
|
+
if (frame) frames.push(frame);
|
|
413
|
+
},
|
|
414
|
+
(error) => {
|
|
415
|
+
clearInterval(timer);
|
|
416
|
+
emit(undefined);
|
|
417
|
+
onError(
|
|
418
|
+
new Unavailable(
|
|
419
|
+
`${error.message}. Install PresentMon and run sdeck as administrator (or add your user to "Performance Log Users")`,
|
|
420
|
+
),
|
|
421
|
+
);
|
|
422
|
+
},
|
|
423
|
+
);
|
|
424
|
+
const timer = setInterval(() => {
|
|
425
|
+
emit(frameRate(frames, foreground()));
|
|
426
|
+
frames = [];
|
|
427
|
+
}, 1000);
|
|
428
|
+
return () => {
|
|
429
|
+
clearInterval(timer);
|
|
430
|
+
stop();
|
|
431
|
+
};
|
|
432
|
+
}
|
package/src/watchers.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Long-lived watchers behind the system triggers: process start/stop, new files, network
|
|
3
|
+
* changes and user idle time. Each is shared between everything that listens to it.
|
|
4
|
+
*/
|
|
5
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
6
|
+
import { existsSync, type FSWatcher, readdirSync, watch } from "node:fs";
|
|
7
|
+
import { homedir, networkInterfaces } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
export { Shared } from "@sdeck/plugin";
|
|
11
|
+
|
|
12
|
+
/** What changed between two process lists. */
|
|
13
|
+
export function processChanges(
|
|
14
|
+
before: ReadonlySet<string>,
|
|
15
|
+
after: ReadonlySet<string>,
|
|
16
|
+
): { started: string[]; stopped: string[] } {
|
|
17
|
+
return {
|
|
18
|
+
started: [...after].filter((p) => !before.has(p)),
|
|
19
|
+
stopped: [...before].filter((p) => !after.has(p)),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `*.png`, `report-??.csv` → a case-insensitive RegExp over a file name. Empty = every file. */
|
|
24
|
+
export function namePattern(glob: string): RegExp {
|
|
25
|
+
const trimmed = glob.trim();
|
|
26
|
+
if (!trimmed) return /^/;
|
|
27
|
+
const escaped = trimmed.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
28
|
+
return new RegExp(`^${escaped.replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Calls `onCreated(name)` for files that appear in `folder` (not ones that only change).
|
|
33
|
+
* Throws when the folder does not exist.
|
|
34
|
+
*/
|
|
35
|
+
export function watchFolder(folder: string, onCreated: (name: string) => void): () => void {
|
|
36
|
+
if (!existsSync(folder)) throw new Error(`folder "${folder}" does not exist`);
|
|
37
|
+
const known = new Set(readdirSync(folder));
|
|
38
|
+
let watcher: FSWatcher | undefined = watch(folder, (_event, name) => {
|
|
39
|
+
if (!name) return;
|
|
40
|
+
const file = String(name);
|
|
41
|
+
const exists = existsSync(join(folder, file));
|
|
42
|
+
if (exists && !known.has(file)) {
|
|
43
|
+
known.add(file);
|
|
44
|
+
onCreated(file);
|
|
45
|
+
} else if (!exists) known.delete(file);
|
|
46
|
+
});
|
|
47
|
+
watcher.on("error", () => {
|
|
48
|
+
watcher?.close();
|
|
49
|
+
watcher = undefined;
|
|
50
|
+
});
|
|
51
|
+
return () => watcher?.close();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Addresses of the non-internal network interfaces, sorted (`"Wi-Fi 192.168.1.4"`). */
|
|
55
|
+
export function networkAddresses(): string[] {
|
|
56
|
+
const out: string[] = [];
|
|
57
|
+
for (const [name, addresses] of Object.entries(networkInterfaces())) {
|
|
58
|
+
for (const a of addresses ?? []) if (!a.internal) out.push(`${name} ${a.address}`);
|
|
59
|
+
}
|
|
60
|
+
return out.sort();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// -- Idle time ---------------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
const WINDOWS_IDLE = `
|
|
66
|
+
Add-Type @'
|
|
67
|
+
using System;
|
|
68
|
+
using System.Runtime.InteropServices;
|
|
69
|
+
public static class SdeckIdle {
|
|
70
|
+
[StructLayout(LayoutKind.Sequential)] struct Info { public uint Size; public uint Time; }
|
|
71
|
+
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref Info info);
|
|
72
|
+
public static long Ms() {
|
|
73
|
+
var info = new Info(); info.Size = (uint)Marshal.SizeOf(info);
|
|
74
|
+
if (!GetLastInputInfo(ref info)) return -1;
|
|
75
|
+
return (long)(uint)((uint)Environment.TickCount - info.Time);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
'@
|
|
79
|
+
while ($true) { [Console]::Out.WriteLine([SdeckIdle]::Ms()); [Console]::Out.Flush(); Start-Sleep -Seconds 2 }
|
|
80
|
+
`;
|
|
81
|
+
|
|
82
|
+
/** Whole seconds from a reading in milliseconds (or `undefined` for a bad line). */
|
|
83
|
+
export function idleSeconds(line: string, unit: "ms" | "ns" = "ms"): number | undefined {
|
|
84
|
+
const n = Number(line.trim());
|
|
85
|
+
if (!Number.isFinite(n) || n < 0) return undefined;
|
|
86
|
+
return Math.floor(unit === "ns" ? n / 1e9 : n / 1000);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Seconds since the last keyboard or mouse input, every ~2 s. Windows: one PowerShell process
|
|
91
|
+
* reading `GetLastInputInfo`. macOS: `ioreg` HIDIdleTime. Linux: `xprintidle` (X11), if installed.
|
|
92
|
+
*/
|
|
93
|
+
export function watchIdle(emit: (seconds: number) => void, onError: (e: Error) => void) {
|
|
94
|
+
if (process.platform === "win32") {
|
|
95
|
+
const encoded = Buffer.from(WINDOWS_IDLE, "utf16le").toString("base64");
|
|
96
|
+
const child: ChildProcess = spawn(
|
|
97
|
+
"powershell.exe",
|
|
98
|
+
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
|
|
99
|
+
{ cwd: homedir(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true },
|
|
100
|
+
);
|
|
101
|
+
let buffer = "";
|
|
102
|
+
child.stdout?.setEncoding("utf8");
|
|
103
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
104
|
+
buffer += chunk;
|
|
105
|
+
const lines = buffer.split(/\r?\n/);
|
|
106
|
+
buffer = lines.pop() ?? "";
|
|
107
|
+
for (const line of lines) {
|
|
108
|
+
const s = idleSeconds(line);
|
|
109
|
+
if (s !== undefined) emit(s);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
child.once("error", (error) => onError(error));
|
|
113
|
+
return () => child.kill();
|
|
114
|
+
}
|
|
115
|
+
const [file, args, parse] =
|
|
116
|
+
process.platform === "darwin"
|
|
117
|
+
? ([
|
|
118
|
+
"ioreg",
|
|
119
|
+
["-c", "IOHIDSystem", "-d", "4"],
|
|
120
|
+
(out: string) => idleSeconds(/"HIDIdleTime" = (\d+)/.exec(out)?.[1] ?? "", "ns"),
|
|
121
|
+
] as const)
|
|
122
|
+
: (["xprintidle", [], (out: string) => idleSeconds(out)] as const);
|
|
123
|
+
let stopped = false;
|
|
124
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
125
|
+
const tick = () => {
|
|
126
|
+
const child = spawn(file, [...args], { stdio: ["ignore", "pipe", "ignore"] });
|
|
127
|
+
let out = "";
|
|
128
|
+
child.stdout?.setEncoding("utf8");
|
|
129
|
+
child.stdout?.on("data", (c: string) => {
|
|
130
|
+
out += c;
|
|
131
|
+
});
|
|
132
|
+
child.once("error", () => {
|
|
133
|
+
stopped = true;
|
|
134
|
+
onError(new Error(`idle time is unavailable: "${file}" could not run`));
|
|
135
|
+
});
|
|
136
|
+
child.once("close", () => {
|
|
137
|
+
const s = parse(out);
|
|
138
|
+
if (s !== undefined) emit(s);
|
|
139
|
+
if (!stopped) timer = setTimeout(tick, 2000);
|
|
140
|
+
});
|
|
141
|
+
};
|
|
142
|
+
tick();
|
|
143
|
+
return () => {
|
|
144
|
+
stopped = true;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// -- Foreground app ----------------------------------------------------------------------------
|
|
150
|
+
|
|
151
|
+
const WINDOWS_FOREGROUND = `
|
|
152
|
+
Add-Type @'
|
|
153
|
+
using System;
|
|
154
|
+
using System.Runtime.InteropServices;
|
|
155
|
+
public static class SdeckFg {
|
|
156
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
157
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
|
158
|
+
public static uint Pid() { uint pid; GetWindowThreadProcessId(GetForegroundWindow(), out pid); return pid; }
|
|
159
|
+
}
|
|
160
|
+
'@
|
|
161
|
+
$last = $null
|
|
162
|
+
while ($true) {
|
|
163
|
+
$name = ""
|
|
164
|
+
$id = [SdeckFg]::Pid()
|
|
165
|
+
if ($id -ne 0) { $p = Get-Process -Id $id -ErrorAction SilentlyContinue; if ($p) { $name = $p.ProcessName + ".exe" } }
|
|
166
|
+
if ($name -ne $last) { [Console]::Out.WriteLine($name); [Console]::Out.Flush(); $last = $name }
|
|
167
|
+
Start-Sleep -Milliseconds 700
|
|
168
|
+
}
|
|
169
|
+
`;
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* An executable name as the process list spells it (`javaw.exe`, `firefox`): the last path part,
|
|
173
|
+
* trimmed and lowercased. Empty for nothing in the foreground.
|
|
174
|
+
*/
|
|
175
|
+
export function foregroundName(line: string): string {
|
|
176
|
+
const trimmed = line.trim();
|
|
177
|
+
return (trimmed.split(/[\\/]/).pop() ?? "").toLowerCase();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The executable of the focused window, emitted when it changes (`""` = none, e.g. the desktop
|
|
182
|
+
* has focus). Windows: one PowerShell process reading `GetForegroundWindow`. macOS: System Events
|
|
183
|
+
* via `osascript` (may ask for Automation permission). Linux: `xdotool` (X11), if installed.
|
|
184
|
+
*/
|
|
185
|
+
export function watchForeground(emit: (app: string) => void, onError: (e: Error) => void) {
|
|
186
|
+
if (process.platform === "win32") {
|
|
187
|
+
const encoded = Buffer.from(WINDOWS_FOREGROUND, "utf16le").toString("base64");
|
|
188
|
+
const child: ChildProcess = spawn(
|
|
189
|
+
"powershell.exe",
|
|
190
|
+
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
|
|
191
|
+
{ cwd: homedir(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true },
|
|
192
|
+
);
|
|
193
|
+
let buffer = "";
|
|
194
|
+
child.stdout?.setEncoding("utf8");
|
|
195
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
196
|
+
buffer += chunk;
|
|
197
|
+
const lines = buffer.split(/\r?\n/);
|
|
198
|
+
buffer = lines.pop() ?? "";
|
|
199
|
+
for (const line of lines) emit(foregroundName(line));
|
|
200
|
+
});
|
|
201
|
+
child.once("error", (error) => onError(error));
|
|
202
|
+
return () => child.kill();
|
|
203
|
+
}
|
|
204
|
+
const script =
|
|
205
|
+
process.platform === "darwin"
|
|
206
|
+
? `ps -p "$(osascript -e 'tell application "System Events" to get unix id of first application process whose frontmost is true')" -o comm=`
|
|
207
|
+
: `cat "/proc/$(xdotool getactivewindow getwindowpid)/comm"`;
|
|
208
|
+
const tool = process.platform === "darwin" ? "osascript" : "xdotool";
|
|
209
|
+
let stopped = false;
|
|
210
|
+
let last: string | undefined;
|
|
211
|
+
let failures = 0;
|
|
212
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
213
|
+
const tick = () => {
|
|
214
|
+
const child = spawn("sh", ["-c", script], { stdio: ["ignore", "pipe", "ignore"] });
|
|
215
|
+
let out = "";
|
|
216
|
+
child.stdout?.setEncoding("utf8");
|
|
217
|
+
child.stdout?.on("data", (c: string) => {
|
|
218
|
+
out += c;
|
|
219
|
+
});
|
|
220
|
+
child.once("error", (error) => {
|
|
221
|
+
stopped = true;
|
|
222
|
+
onError(error);
|
|
223
|
+
});
|
|
224
|
+
child.once("close", (code) => {
|
|
225
|
+
if (stopped) return;
|
|
226
|
+
if (code === 0) {
|
|
227
|
+
failures = 0;
|
|
228
|
+
const app = foregroundName(out);
|
|
229
|
+
if (app !== last) {
|
|
230
|
+
last = app;
|
|
231
|
+
emit(app);
|
|
232
|
+
}
|
|
233
|
+
} else if (++failures === 3) {
|
|
234
|
+
// A locked screen fails now and then; failing every time means the tool is missing.
|
|
235
|
+
onError(new Error(`the foreground app is unavailable: "${tool}" did not answer`));
|
|
236
|
+
}
|
|
237
|
+
timer = setTimeout(tick, 1000);
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
tick();
|
|
241
|
+
return () => {
|
|
242
|
+
stopped = true;
|
|
243
|
+
clearTimeout(timer);
|
|
244
|
+
};
|
|
245
|
+
}
|
package/README.md
DELETED