@nice-code/commander 0.105.0 → 0.106.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/build/cli.cjs CHANGED
@@ -13,11 +13,11 @@ let jiti = require("jiti");
13
13
  let node_crypto = require("node:crypto");
14
14
  let module$1 = require("module");
15
15
  let ws = require("ws");
16
- let node_os = require("node:os");
17
16
  let node_child_process = require("node:child_process");
17
+ let node_util = require("node:util");
18
+ let node_os = require("node:os");
18
19
  let node_net = require("node:net");
19
20
  let node_dns_promises = require("node:dns/promises");
20
- let node_util = require("node:util");
21
21
  let node_readline_promises = require("node:readline/promises");
22
22
  //#region src/cli/args.ts
23
23
  const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
@@ -24084,6 +24084,85 @@ function createRealmAcceptor(options) {
24084
24084
  };
24085
24085
  }
24086
24086
  //#endregion
24087
+ //#region src/daemon/daemonProcesses.ts
24088
+ const exec$2 = (0, node_util.promisify)(node_child_process.execFile);
24089
+ /** `pid<space>command line` for every process this user can see. */
24090
+ async function processTable() {
24091
+ if (process.platform === "win32") {
24092
+ const { stdout } = await exec$2("powershell.exe", [
24093
+ "-NoProfile",
24094
+ "-NonInteractive",
24095
+ "-Command",
24096
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }"
24097
+ ], {
24098
+ maxBuffer: 16 * 1024 * 1024,
24099
+ timeout: 15e3,
24100
+ windowsHide: true
24101
+ });
24102
+ return parseTable(stdout);
24103
+ }
24104
+ const { stdout } = await exec$2("ps", [
24105
+ "-axww",
24106
+ "-o",
24107
+ "pid=",
24108
+ "-o",
24109
+ "args="
24110
+ ], {
24111
+ maxBuffer: 16 * 1024 * 1024,
24112
+ timeout: 1e4
24113
+ });
24114
+ return parseTable(stdout);
24115
+ }
24116
+ function parseTable(text) {
24117
+ const rows = [];
24118
+ for (const line of text.split(/\r?\n/)) {
24119
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
24120
+ if (match != null) rows.push({
24121
+ pid: Number(match[1]),
24122
+ commandLine: match[2] ?? ""
24123
+ });
24124
+ }
24125
+ return rows;
24126
+ }
24127
+ /**
24128
+ * Is this command line the daemon for `configPath` under `dataDir`? Quotes are dropped first:
24129
+ * Windows quotes an argument holding a space (`--data-dir "C:\…\App Data"`), `ps` does not.
24130
+ */
24131
+ function isDaemonCommandLine(commandLine, configPath, dataDir) {
24132
+ const line = ` ${commandLine.replaceAll("\"", "")} `;
24133
+ return line.includes(` daemon --config ${configPath} `) && line.includes(` --data-dir ${dataDir} `);
24134
+ }
24135
+ /** One sentence naming record-less daemons and the one command that clears them. */
24136
+ function orphanMessage(orphans) {
24137
+ const one = orphans.length === 1;
24138
+ const pids = orphans.map((orphan) => orphan.pid).join(", ");
24139
+ const them = one ? "it" : "them";
24140
+ return `${one ? "a daemon" : `${orphans.length} daemons`} for this config ${one ? "is" : "are"} running without an instance record (pid ${pids}), so this CLI cannot talk to ${them}. Run \`nice-commander shutdown\` (it stops ${them} and everything ${one ? "it runs" : "they run"}), then retry.`;
24141
+ }
24142
+ /**
24143
+ * Every live daemon process for this config and data dir, except `excludePid` (a daemon asking
24144
+ * about its peers, or a caller that already holds the recorded one). Best effort: a process
24145
+ * table that cannot be read answers "none", never an error — this is a fallback, not the path.
24146
+ */
24147
+ async function findDaemonProcesses(configPath, dataDir, excludePid) {
24148
+ let table;
24149
+ try {
24150
+ table = await processTable();
24151
+ } catch {
24152
+ return [];
24153
+ }
24154
+ const found = [];
24155
+ for (const row of table) {
24156
+ if (row.pid === process.pid || row.pid === excludePid) continue;
24157
+ if (!isDaemonCommandLine(row.commandLine, configPath, dataDir)) continue;
24158
+ found.push({
24159
+ pid: row.pid,
24160
+ startStamp: await (0, _nice_code_process.readProcessStartStamp)(row.pid)
24161
+ });
24162
+ }
24163
+ return found;
24164
+ }
24165
+ //#endregion
24087
24166
  //#region src/daemon/dataDir.ts
24088
24167
  function resolveCommanderDataDir(environment = process.env, platform = process.platform) {
24089
24168
  const override = environment["NICE_COMMANDER_DATA_DIR"];
@@ -24408,6 +24487,16 @@ async function replaceSkewedDaemon(paths, skewed) {
24408
24487
  case "identity-unverified": throw new Error(`${daemonLabel}, but pid ${skewed.pid} could not be verified as that daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed. Verify the pid yourself, and if the daemon is really gone remove ${paths.instanceRecordPath}.`);
24409
24488
  }
24410
24489
  }
24490
+ /** How long `ensureDaemon` lets a record-less daemon finish exiting before calling it an orphan. */
24491
+ const ORPHAN_GRACE_MS = 5e3;
24492
+ async function waitForOrphansToExit(configPath, dataDir, recordedPid) {
24493
+ const deadline = Date.now() + ORPHAN_GRACE_MS;
24494
+ for (;;) {
24495
+ const orphans = await findDaemonProcesses(configPath, dataDir, recordedPid);
24496
+ if (orphans.length === 0 || Date.now() > deadline) return orphans;
24497
+ await new Promise((resolveWait) => setTimeout(resolveWait, 250));
24498
+ }
24499
+ }
24411
24500
  async function ensureDaemon(options) {
24412
24501
  const runtimeError = commanderRuntimeError();
24413
24502
  if (runtimeError != null) throw new Error(runtimeError);
@@ -24429,6 +24518,9 @@ async function ensureDaemon(options) {
24429
24518
  const skewed = await readSkewedInstanceRecord(paths.instanceRecordPath, commanderStatusRealm.schemaHash);
24430
24519
  if (skewed != null && pidAlive$1(skewed.pid)) replaced = await replaceSkewedDaemon(paths, skewed);
24431
24520
  }
24521
+ const recordedPid = existing != null ? existing.pid : void 0;
24522
+ const orphans = await waitForOrphansToExit(options.config.configPath, dataDir, recordedPid);
24523
+ if (orphans.length > 0) throw new Error(orphanMessage(orphans));
24432
24524
  await ensureStateDir(paths);
24433
24525
  const bootFd = (0, node_fs.openSync)(paths.bootLogPath, "w", 384);
24434
24526
  const child = (0, node_child_process.spawn)(process.execPath, [
@@ -24849,12 +24941,21 @@ async function findSkewedDaemon(config) {
24849
24941
  servesOwnClient: skewed.servesOwnClient
24850
24942
  };
24851
24943
  }
24944
+ /**
24945
+ * This config's daemons that no instance record points at (see `daemonProcesses.ts`). The CLI
24946
+ * cannot talk to them — no token — but it can name them, and `shutdown` can stop them.
24947
+ */
24948
+ async function findOrphanDaemons(config, recordedPid) {
24949
+ return findDaemonProcesses(config.configPath, resolveCommanderDataDir(), recordedPid);
24950
+ }
24852
24951
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
24853
24952
  async function requireDaemon(config) {
24854
24953
  const handle = await findDaemon(config);
24855
24954
  if (handle != null) return handle;
24856
24955
  const skewed = await findSkewedDaemon(config);
24857
24956
  if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);
24957
+ const orphans = await findOrphanDaemons(config);
24958
+ if (orphans.length > 0) throw new CliExit(EXIT.notRunning, orphanMessage(orphans));
24858
24959
  throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
24859
24960
  }
24860
24961
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
@@ -25145,17 +25246,47 @@ async function cmdRestart(ctx) {
25145
25246
  async function cmdShutdown(ctx) {
25146
25247
  const bad = unknownFlags(ctx.args.flags, []);
25147
25248
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25148
- const { out } = ctx;
25149
- const handle = await findDaemon(ctx.config);
25150
- if (handle != null) try {
25249
+ const { out, config } = ctx;
25250
+ const reports = [];
25251
+ let code = null;
25252
+ let recordedPid;
25253
+ const handle = await findDaemon(config);
25254
+ if (handle != null) {
25255
+ recordedPid = handle.record.pid;
25256
+ code = await shutdownRecorded(ctx, handle, reports);
25257
+ } else {
25258
+ const skewed = await findSkewedDaemon(config);
25259
+ if (skewed != null) {
25260
+ recordedPid = skewed.pid;
25261
+ if (!out.json) out.print(out.paint("gray", skewed.message));
25262
+ code = reportSignalShutdown(ctx, await signalDaemonShutdown({
25263
+ pid: skewed.pid,
25264
+ startStamp: skewed.startStamp
25265
+ }), "could not be reached over the wire", reports);
25266
+ }
25267
+ }
25268
+ for (const orphan of await findOrphanDaemons(config, recordedPid)) {
25269
+ const next = reportSignalShutdown(ctx, await signalDaemonShutdown(orphan), "was running without an instance record (the CLI had lost track of it)", reports);
25270
+ code = code == null ? next : Math.max(code, next);
25271
+ }
25272
+ if (code == null) throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}"`);
25273
+ if (out.json) out.printJson(reports.length === 1 ? reports[0] : {
25274
+ ok: reports.every((report) => report["ok"] === true),
25275
+ daemons: reports
25276
+ });
25277
+ return code;
25278
+ }
25279
+ /** The recorded daemon: the wire first (the graceful ask), a verified signal when it refuses. */
25280
+ async function shutdownRecorded(ctx, handle, reports) {
25281
+ try {
25151
25282
  const client = await connectDaemon(handle);
25152
25283
  try {
25153
25284
  await client.shutdown();
25154
- if (out.json) out.printJson({
25285
+ reports.push({
25155
25286
  ok: true,
25156
25287
  via: "wire"
25157
25288
  });
25158
- else out.print(`daemon for "${ctx.config.name}" is shutting down`);
25289
+ if (!ctx.out.json) ctx.out.print(`daemon for "${ctx.config.name}" is shutting down`);
25159
25290
  return EXIT.ok;
25160
25291
  } finally {
25161
25292
  client.dispose();
@@ -25165,42 +25296,33 @@ async function cmdShutdown(ctx) {
25165
25296
  return reportSignalShutdown(ctx, await signalDaemonShutdown({
25166
25297
  pid: handle.record.pid,
25167
25298
  startStamp: handle.record.startStamp
25168
- }));
25169
- }
25170
- const skewed = await findSkewedDaemon(ctx.config);
25171
- if (skewed != null) {
25172
- if (!out.json) out.print(out.paint("gray", skewed.message));
25173
- return reportSignalShutdown(ctx, await signalDaemonShutdown({
25174
- pid: skewed.pid,
25175
- startStamp: skewed.startStamp
25176
- }));
25299
+ }), "could not be reached over the wire", reports);
25177
25300
  }
25178
- throw new CliExit(EXIT.notRunning, `daemon not running for "${ctx.config.name}"`);
25179
25301
  }
25180
- function reportSignalShutdown(ctx, result) {
25302
+ function reportSignalShutdown(ctx, result, why, reports) {
25181
25303
  const { out } = ctx;
25182
- if (out.json) {
25183
- out.printJson({
25184
- ok: result.outcome === "exited",
25185
- via: "signal",
25186
- ...result
25187
- });
25188
- return result.outcome === "exited" ? EXIT.ok : EXIT.failure;
25189
- }
25304
+ const code = result.outcome === "exited" || result.outcome === "not-running" ? EXIT.ok : EXIT.failure;
25305
+ reports.push({
25306
+ ok: result.outcome === "exited",
25307
+ via: "signal",
25308
+ ...result
25309
+ });
25310
+ if (out.json) return code;
25190
25311
  switch (result.outcome) {
25191
25312
  case "exited":
25192
- out.print(`daemon for "${ctx.config.name}" (pid ${result.pid}) could not be reached over the wire — stopped via signal (its own shutdown ladder ran)`);
25193
- return EXIT.ok;
25313
+ out.print(`daemon for "${ctx.config.name}" (pid ${result.pid}) ${why} — stopped via signal (its own shutdown ladder ran)`);
25314
+ break;
25194
25315
  case "still-stopping":
25195
25316
  out.print(out.paint("yellow", `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run \`shutdown\` again to escalate if it stays stuck`));
25196
- return EXIT.failure;
25317
+ break;
25197
25318
  case "identity-unverified":
25198
- out.print(out.paint("yellow", `⚠ pid ${result.pid} could not be verified as the recorded daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed; verify the pid yourself, and remove the instance record if the daemon is really gone.`));
25199
- return EXIT.failure;
25319
+ out.print(out.paint("yellow", `⚠ pid ${result.pid} could not be verified as this config's daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed; verify the pid yourself, and remove the instance record if the daemon is really gone.`));
25320
+ break;
25200
25321
  case "not-running":
25201
25322
  out.print(`daemon not running for "${ctx.config.name}" (stale record)`);
25202
- return EXIT.ok;
25323
+ break;
25203
25324
  }
25325
+ return code;
25204
25326
  }
25205
25327
  //#endregion
25206
25328
  //#region src/daemon/envOverrides.ts
@@ -27140,29 +27262,36 @@ async function stopExistingDaemon(ctx) {
27140
27262
  const { config, out } = ctx;
27141
27263
  const live = await findDaemon(config);
27142
27264
  const skewed = live == null ? await findSkewedDaemon(config) : null;
27143
- const target = live != null ? {
27265
+ const recorded = live != null ? {
27144
27266
  pid: live.record.pid,
27145
27267
  startStamp: live.record.startStamp
27146
27268
  } : skewed != null ? {
27147
27269
  pid: skewed.pid,
27148
27270
  startStamp: skewed.startStamp
27149
27271
  } : null;
27150
- if (target == null) return;
27151
- if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27152
- if (live != null) try {
27272
+ const targets = [...recorded != null ? [recorded] : [], ...await findOrphanDaemons(config, recorded?.pid)];
27273
+ for (const target of targets) {
27274
+ if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27275
+ if (target === recorded && live != null && await stopOverWire(live)) continue;
27276
+ const result = await signalDaemonShutdown(target);
27277
+ if (result.outcome === "exited" || result.outcome === "not-running") continue;
27278
+ throw new CliExit(EXIT.failure, result.outcome === "still-stopping" ? `--fresh: the daemon (pid ${target.pid}) is still stopping — retry in a moment` : `--fresh: pid ${target.pid} could not be verified as this config's daemon (possibly pid reuse), so nothing was stopped — verify it yourself, then retry`);
27279
+ }
27280
+ }
27281
+ /** The graceful ask; false when the wire refuses us or the ladder outlasts the wait. */
27282
+ async function stopOverWire(live) {
27283
+ try {
27153
27284
  const client = await connectDaemon(live);
27154
27285
  try {
27155
27286
  await client.shutdown();
27156
27287
  } finally {
27157
27288
  client.dispose();
27158
27289
  }
27159
- if (await waitForExit(target.pid, FRESH_EXIT_WAIT_MS)) return;
27160
27290
  } catch (error) {
27161
27291
  if (!(error instanceof CliExit)) throw error;
27292
+ return false;
27162
27293
  }
27163
- const result = await signalDaemonShutdown(target);
27164
- if (result.outcome === "exited" || result.outcome === "not-running") return;
27165
- throw new CliExit(EXIT.failure, result.outcome === "still-stopping" ? `--fresh: the daemon (pid ${target.pid}) is still stopping — retry in a moment` : `--fresh: pid ${target.pid} could not be verified as this config's daemon (possibly pid reuse), so nothing was stopped — verify it yourself, then retry`);
27294
+ return waitForExit(live.record.pid, FRESH_EXIT_WAIT_MS);
27166
27295
  }
27167
27296
  async function waitForExit(pid, timeoutMs) {
27168
27297
  const deadline = Date.now() + timeoutMs;
@@ -27377,7 +27506,7 @@ async function withTimeout(ctx, run) {
27377
27506
  async function main() {
27378
27507
  const argv = process.argv.slice(2);
27379
27508
  if (argv[0] === "daemon") {
27380
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-vXl0q1X7.cjs"));
27509
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-BHPsC_5Q.cjs"));
27381
27510
  return runCommanderDaemon(argv.slice(1));
27382
27511
  }
27383
27512
  const parsed = parseCliArgs(argv);
@@ -27447,6 +27576,7 @@ exports.createRealmServerEngine = createRealmServerEngine;
27447
27576
  exports.effectiveEnv = effectiveEnv;
27448
27577
  exports.ensureStateDir = ensureStateDir;
27449
27578
  exports.envVarViews = envVarViews;
27579
+ exports.findDaemonProcesses = findDaemonProcesses;
27450
27580
  exports.hashCanonical = hashCanonical;
27451
27581
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
27452
27582
  exports.identifyEndpointOwner = identifyEndpointOwner;