@metamask-previews/wallet-cli 0.0.0-preview-bbd2df29f → 0.0.0-preview-ea5e7f6d0

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 (93) hide show
  1. package/CHANGELOG.md +1 -4
  2. package/README.md +0 -41
  3. package/dist/daemon/daemon-entry.cjs +0 -4
  4. package/dist/daemon/daemon-entry.cjs.map +1 -1
  5. package/dist/daemon/daemon-entry.mjs +0 -4
  6. package/dist/daemon/daemon-entry.mjs.map +1 -1
  7. package/dist/daemon/daemon-spawn.cjs +25 -46
  8. package/dist/daemon/daemon-spawn.cjs.map +1 -1
  9. package/dist/daemon/daemon-spawn.d.cts.map +1 -1
  10. package/dist/daemon/daemon-spawn.d.mts.map +1 -1
  11. package/dist/daemon/daemon-spawn.mjs +26 -47
  12. package/dist/daemon/daemon-spawn.mjs.map +1 -1
  13. package/dist/daemon/socket-line.cjs +4 -8
  14. package/dist/daemon/socket-line.cjs.map +1 -1
  15. package/dist/daemon/socket-line.d.cts +0 -2
  16. package/dist/daemon/socket-line.d.cts.map +1 -1
  17. package/dist/daemon/socket-line.d.mts +0 -2
  18. package/dist/daemon/socket-line.d.mts.map +1 -1
  19. package/dist/daemon/socket-line.mjs +4 -8
  20. package/dist/daemon/socket-line.mjs.map +1 -1
  21. package/dist/daemon/stop-daemon.cjs +9 -23
  22. package/dist/daemon/stop-daemon.cjs.map +1 -1
  23. package/dist/daemon/stop-daemon.d.cts +7 -17
  24. package/dist/daemon/stop-daemon.d.cts.map +1 -1
  25. package/dist/daemon/stop-daemon.d.mts +7 -17
  26. package/dist/daemon/stop-daemon.d.mts.map +1 -1
  27. package/dist/daemon/stop-daemon.mjs +9 -23
  28. package/dist/daemon/stop-daemon.mjs.map +1 -1
  29. package/dist/daemon/utils.cjs +1 -52
  30. package/dist/daemon/utils.cjs.map +1 -1
  31. package/dist/daemon/utils.d.cts +0 -28
  32. package/dist/daemon/utils.d.cts.map +1 -1
  33. package/dist/daemon/utils.d.mts +0 -28
  34. package/dist/daemon/utils.d.mts.map +1 -1
  35. package/dist/daemon/utils.mjs +0 -48
  36. package/dist/daemon/utils.mjs.map +1 -1
  37. package/package.json +2 -5
  38. package/dist/commands/daemon/call.cjs +0 -79
  39. package/dist/commands/daemon/call.cjs.map +0 -1
  40. package/dist/commands/daemon/call.d.cts +0 -14
  41. package/dist/commands/daemon/call.d.cts.map +0 -1
  42. package/dist/commands/daemon/call.d.mts +0 -14
  43. package/dist/commands/daemon/call.d.mts.map +0 -1
  44. package/dist/commands/daemon/call.mjs +0 -77
  45. package/dist/commands/daemon/call.mjs.map +0 -1
  46. package/dist/commands/daemon/list.cjs +0 -48
  47. package/dist/commands/daemon/list.cjs.map +0 -1
  48. package/dist/commands/daemon/list.d.cts +0 -7
  49. package/dist/commands/daemon/list.d.cts.map +0 -1
  50. package/dist/commands/daemon/list.d.mts +0 -7
  51. package/dist/commands/daemon/list.d.mts.map +0 -1
  52. package/dist/commands/daemon/list.mjs +0 -46
  53. package/dist/commands/daemon/list.mjs.map +0 -1
  54. package/dist/commands/daemon/purge.cjs +0 -58
  55. package/dist/commands/daemon/purge.cjs.map +0 -1
  56. package/dist/commands/daemon/purge.d.cts +0 -10
  57. package/dist/commands/daemon/purge.d.cts.map +0 -1
  58. package/dist/commands/daemon/purge.d.mts +0 -10
  59. package/dist/commands/daemon/purge.d.mts.map +0 -1
  60. package/dist/commands/daemon/purge.mjs +0 -56
  61. package/dist/commands/daemon/purge.mjs.map +0 -1
  62. package/dist/commands/daemon/start.cjs +0 -48
  63. package/dist/commands/daemon/start.cjs.map +0 -1
  64. package/dist/commands/daemon/start.d.cts +0 -12
  65. package/dist/commands/daemon/start.d.cts.map +0 -1
  66. package/dist/commands/daemon/start.d.mts +0 -12
  67. package/dist/commands/daemon/start.d.mts.map +0 -1
  68. package/dist/commands/daemon/start.mjs +0 -46
  69. package/dist/commands/daemon/start.mjs.map +0 -1
  70. package/dist/commands/daemon/status.cjs +0 -59
  71. package/dist/commands/daemon/status.cjs.map +0 -1
  72. package/dist/commands/daemon/status.d.cts +0 -7
  73. package/dist/commands/daemon/status.d.cts.map +0 -1
  74. package/dist/commands/daemon/status.d.mts +0 -7
  75. package/dist/commands/daemon/status.d.mts.map +0 -1
  76. package/dist/commands/daemon/status.mjs +0 -57
  77. package/dist/commands/daemon/status.mjs.map +0 -1
  78. package/dist/commands/daemon/stop.cjs +0 -26
  79. package/dist/commands/daemon/stop.cjs.map +0 -1
  80. package/dist/commands/daemon/stop.d.cts +0 -7
  81. package/dist/commands/daemon/stop.d.cts.map +0 -1
  82. package/dist/commands/daemon/stop.d.mts +0 -7
  83. package/dist/commands/daemon/stop.d.mts.map +0 -1
  84. package/dist/commands/daemon/stop.mjs +0 -24
  85. package/dist/commands/daemon/stop.mjs.map +0 -1
  86. package/dist/test/run-command.cjs +0 -73
  87. package/dist/test/run-command.cjs.map +0 -1
  88. package/dist/test/run-command.d.cts +0 -27
  89. package/dist/test/run-command.d.cts.map +0 -1
  90. package/dist/test/run-command.d.mts +0 -27
  91. package/dist/test/run-command.d.mts.map +0 -1
  92. package/dist/test/run-command.mjs +0 -69
  93. package/dist/test/run-command.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"daemon-spawn.mjs","sourceRoot":"","sources":["../../src/daemon/daemon-spawn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,2BAA2B;AAC3C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,gBAAgB;AAC1D,OAAO,EAAE,IAAI,EAAE,kBAAkB;AAEjC,OAAO,EAAE,UAAU,EAAE,4BAAwB;AAC7C,OAAO,EAAE,wBAAwB,EAAE,uBAAmB;AACtD,OAAO,EAAE,cAAc,EAAE,oBAAgB;AAGzC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,SAAS,GAAG,GAAG,CAAC,CAAC,aAAa;AAgBpC;;;;;;;;;;;GAWG;AACH,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,CAAC;QAC1B,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,iBAAiB,CAAC,CAAC;IACvE,OAAO;QACL,SAAS,EAAE,QAAQ;QACnB,IAAI,EAAE,CAAC,UAAU,EAAE,KAAK,CAAC;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from 'node:child_process';\nimport { closeSync, existsSync, openSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { pingDaemon } from './daemon-client';\nimport { ensureOwnerOnlyDirectory } from './data-dir';\nimport { getDaemonPaths } from './paths';\nimport type { DaemonSpawnConfig } from './types';\n\nconst POLL_INTERVAL_MS = 100;\nconst MAX_POLLS = 300; // 30 seconds\n\n/**\n * Outcome of {@link ensureDaemon}.\n *\n * - `'already-running'`: a responsive daemon was found at the configured\n * socket path. The supplied flags (`infuraProjectId`, `password`, `srp`)\n * were NOT applied to that daemon; the caller should surface this so a\n * user who is trying to change them isn't silently ignored.\n * - `'started'`: a new daemon was spawned and is now responsive.\n */\nexport type EnsureDaemonResult = {\n state: 'already-running' | 'started';\n socketPath: string;\n};\n\n/**\n * Ensure the daemon is running. If a responsive daemon already exists, return\n * `'already-running'` (caller decides how to surface that). Otherwise spawn\n * one as a detached process and wait until the socket becomes responsive.\n *\n * Refuses to spawn when pinging the existing socket fails with anything other\n * than `ENOENT` (wedged or foreign daemon) — taking over could orphan the\n * existing process and corrupt its PID file.\n *\n * @param config - Spawn configuration.\n * @returns The state of the daemon and the socket path it's listening on.\n */\nexport async function ensureDaemon(\n config: DaemonSpawnConfig,\n): Promise<EnsureDaemonResult> {\n const { socketPath, logPath } = getDaemonPaths(config.dataDir);\n\n const initialPing = await pingDaemon(socketPath);\n switch (initialPing.status) {\n case 'responsive':\n return { state: 'already-running', socketPath };\n case 'unreachable':\n if (initialPing.reason === 'permission') {\n throw new Error(\n `Refusing to start: the socket at ${socketPath} is owned by another user. ` +\n `Choose a different data directory (MM_DAEMON_DATA_DIR) or remove the socket manually. ` +\n `(${initialPing.error.message})`,\n );\n }\n throw new Error(\n `Refusing to start: a daemon socket already exists at ${socketPath} but is unresponsive. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon. ` +\n `(${initialPing.error.message})`,\n );\n case 'absent':\n break;\n /* istanbul ignore next -- exhaustiveness guard; unreachable for the current PingResult union */\n default: {\n const exhaustiveCheck: never = initialPing;\n throw new Error(\n `Unexpected daemon ping status: ${String(exhaustiveCheck)}`,\n );\n }\n }\n\n process.stderr.write('Starting daemon...\\n');\n\n const { entryPath, args } = resolveEntryPoint(config.packageRoot);\n\n // Create the data directory before opening the log file inside it. The daemon\n // entry also does this, but only after spawn — opening the log first would\n // ENOENT on a fresh data directory.\n await ensureOwnerOnlyDirectory(config.dataDir);\n\n // Redirect the detached daemon's stderr to its log file rather than\n // discarding it, so a crash after startup stays diagnosable. stdout stays\n // ignored — structured status goes through the file logger.\n const logFileDescriptor = openSync(logPath, 'a');\n const child = spawn(process.execPath, [...args, entryPath], {\n detached: true,\n stdio: ['ignore', 'ignore', logFileDescriptor],\n env: {\n ...process.env,\n MM_DAEMON_DATA_DIR: config.dataDir,\n MM_DAEMON_SOCKET_PATH: socketPath,\n INFURA_PROJECT_ID: config.infuraProjectId,\n MM_WALLET_PASSWORD: config.password,\n MM_WALLET_SRP: config.srp,\n },\n });\n // The child dup'd the file descriptor into its stderr, so drop the parent's\n // copy. Safe on the success path: `spawn` reports failures via the 'error'\n // event, not a synchronous throw.\n closeSync(logFileDescriptor);\n\n type StartupOutcome =\n | { kind: 'pending' }\n | { kind: 'error'; error: Error }\n | { kind: 'exited'; code: number | null; signal: NodeJS.Signals | null };\n\n // A failed spawn (bad interpreter, EACCES, ENOENT) emits 'error' and may\n // never emit 'exit', so 'error' is recorded first and not overwritten by a\n // later 'exit' — the loop surfaces the real cause instead of hanging.\n const outcome: { current: StartupOutcome } = { current: { kind: 'pending' } };\n\n child.on('error', (error: Error) => {\n process.stderr.write(`Failed to spawn daemon process: ${String(error)}\\n`);\n outcome.current = { kind: 'error', error };\n });\n child.on('exit', (code, signal) => {\n if (outcome.current.kind === 'pending') {\n outcome.current = { kind: 'exited', code, signal };\n }\n });\n child.unref();\n\n for (let i = 0; i < MAX_POLLS; i++) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n const settled = outcome.current;\n if (settled.kind === 'error') {\n throw new Error(\n `Failed to spawn daemon process: ${settled.error.message}. ` +\n `Check the daemon log at ${logPath}.`,\n );\n }\n if (settled.kind === 'exited') {\n throw new Error(\n `Daemon process exited during startup (code=${String(settled.code)}, signal=${String(settled.signal)}). ` +\n `Check the daemon log at ${logPath}.`,\n );\n }\n const ping = await pingDaemon(socketPath);\n if (ping.status === 'responsive') {\n process.stderr.write('Daemon ready.\\n');\n return { state: 'started', socketPath };\n }\n }\n\n throw new Error(\n `Daemon did not start within ${(MAX_POLLS * POLL_INTERVAL_MS) / 1000}s`,\n );\n}\n\n/**\n * Resolve the daemon entry point path and any extra Node.js args needed.\n *\n * In production, uses the compiled dist output. In development, uses tsx\n * to run TypeScript source directly.\n *\n * @param packageRoot - The root directory of the wallet-cli package.\n * @returns The entry path and any extra node args.\n */\nfunction resolveEntryPoint(packageRoot: string): {\n entryPath: string;\n args: string[];\n} {\n const distEntry = join(packageRoot, 'dist', 'daemon', 'daemon-entry.mjs');\n if (existsSync(distEntry)) {\n return { entryPath: distEntry, args: [] };\n }\n\n const srcEntry = join(packageRoot, 'src', 'daemon', 'daemon-entry.ts');\n return {\n entryPath: srcEntry,\n args: ['--import', 'tsx'],\n };\n}\n"]}
1
+ {"version":3,"file":"daemon-spawn.mjs","sourceRoot":"","sources":["../../src/daemon/daemon-spawn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,2BAA2B;AAC3C,OAAO,EAAE,UA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B,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { pingDaemon } from './daemon-client';\nimport { getDaemonPaths } from './paths';\nimport type { DaemonSpawnConfig } from './types';\n\nconst POLL_INTERVAL_MS = 100;\nconst MAX_POLLS = 300; // 30 seconds\n\n/**\n * Outcome of {@link ensureDaemon}.\n *\n * - `'already-running'`: a responsive daemon was found at the configured\n * socket path. The supplied flags (`infuraProjectId`, `password`, `srp`)\n * were NOT applied to that daemon; the caller should surface this so a\n * user who is trying to change them isn't silently ignored.\n * - `'started'`: a new daemon was spawned and is now responsive.\n */\nexport type EnsureDaemonResult = {\n state: 'already-running' | 'started';\n socketPath: string;\n};\n\n/**\n * Ensure the daemon is running. If a responsive daemon already exists, return\n * `'already-running'` (caller decides how to surface that). Otherwise spawn\n * one as a detached process and wait until the socket becomes responsive.\n *\n * Refuses to spawn when pinging the existing socket fails with anything other\n * than `ENOENT` (wedged or foreign daemon) — taking over could orphan the\n * existing process and corrupt its PID file.\n *\n * @param config - Spawn configuration.\n * @returns The state of the daemon and the socket path it's listening on.\n */\nexport async function ensureDaemon(\n config: DaemonSpawnConfig,\n): Promise<EnsureDaemonResult> {\n const { socketPath } = getDaemonPaths(config.dataDir);\n\n const initialPing = await pingDaemon(socketPath);\n if (initialPing.status === 'responsive') {\n return { state: 'already-running', socketPath };\n }\n if (initialPing.status === 'unreachable') {\n if (initialPing.reason === 'permission') {\n throw new Error(\n `Refusing to start: the socket at ${socketPath} is owned by another user. ` +\n `Choose a different data directory (MM_DAEMON_DATA_DIR) or remove the socket manually. ` +\n `(${initialPing.error.message})`,\n );\n }\n throw new Error(\n `Refusing to start: a daemon socket already exists at ${socketPath} but is unresponsive. ` +\n `Run \\`mm daemon stop\\` (or \\`mm daemon purge\\`) before starting a new daemon. ` +\n `(${initialPing.error.message})`,\n );\n }\n\n process.stderr.write('Starting daemon...\\n');\n\n const { entryPath, args } = resolveEntryPoint(config.packageRoot);\n\n const child = spawn(process.execPath, [...args, entryPath], {\n detached: true,\n stdio: 'ignore',\n env: {\n ...process.env,\n MM_DAEMON_DATA_DIR: config.dataDir,\n MM_DAEMON_SOCKET_PATH: socketPath,\n INFURA_PROJECT_ID: config.infuraProjectId,\n MM_WALLET_PASSWORD: config.password,\n MM_WALLET_SRP: config.srp,\n },\n });\n\n type ExitInfo = { code: number | null; signal: NodeJS.Signals | null };\n const exitInfo: { value: ExitInfo | null } = { value: null };\n // A failed spawn (bad interpreter, EACCES, ENOENT) emits 'error' and may\n // never emit 'exit'. Capture it so the readiness loop can surface the real\n // cause immediately instead of hanging for the full timeout.\n const spawnError: { value: Error | null } = { value: null };\n\n child.on('error', (error: Error) => {\n process.stderr.write(`Failed to spawn daemon process: ${String(error)}\\n`);\n spawnError.value = error;\n });\n child.on('exit', (code, signal) => {\n exitInfo.value = { code, signal };\n });\n child.unref();\n\n for (let i = 0; i < MAX_POLLS; i++) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n if (spawnError.value !== null) {\n throw new Error(\n `Failed to spawn daemon process: ${spawnError.value.message}. ` +\n `Check the daemon log at ${getDaemonPaths(config.dataDir).logPath}.`,\n );\n }\n if (exitInfo.value !== null) {\n const { code, signal } = exitInfo.value;\n throw new Error(\n `Daemon process exited during startup (code=${String(code)}, signal=${String(signal)}). ` +\n `Check the daemon log at ${getDaemonPaths(config.dataDir).logPath}.`,\n );\n }\n const ping = await pingDaemon(socketPath);\n if (ping.status === 'responsive') {\n process.stderr.write('Daemon ready.\\n');\n return { state: 'started', socketPath };\n }\n }\n\n throw new Error(\n `Daemon did not start within ${(MAX_POLLS * POLL_INTERVAL_MS) / 1000}s`,\n );\n}\n\n/**\n * Resolve the daemon entry point path and any extra Node.js args needed.\n *\n * In production, uses the compiled dist output. In development, uses tsx\n * to run TypeScript source directly.\n *\n * @param packageRoot - The root directory of the wallet-cli package.\n * @returns The entry path and any extra node args.\n */\nfunction resolveEntryPoint(packageRoot: string): {\n entryPath: string;\n args: string[];\n} {\n const distEntry = join(packageRoot, 'dist', 'daemon', 'daemon-entry.mjs');\n if (existsSync(distEntry)) {\n return { entryPath: distEntry, args: [] };\n }\n\n const srcEntry = join(packageRoot, 'src', 'daemon', 'daemon-entry.ts');\n return {\n entryPath: srcEntry,\n args: ['--import', 'tsx'],\n };\n}\n"]}
@@ -18,17 +18,13 @@ async function writeLine(socket, line) {
18
18
  };
19
19
  socket.once('error', onError);
20
20
  socket.write(`${line}\n`, (error) => {
21
+ socket.removeListener('error', onError);
21
22
  if (error) {
22
- // A failed write (e.g. EPIPE) is delivered BOTH here AND as a later
23
- // 'error' event. Leave `onError` attached to handle that event —
24
- // detaching here would let Node treat it as unhandled and crash the
25
- // process. This reject settles the promise; `onError` detaches itself
26
- // when/if the event arrives.
27
23
  reject(error);
28
- return;
29
24
  }
30
- socket.removeListener('error', onError);
31
- resolve();
25
+ else {
26
+ resolve();
27
+ }
32
28
  });
33
29
  });
34
30
  }
@@ -1 +1 @@
1
- {"version":3,"file":"socket-line.cjs","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":";;;AAEA;;;;;GAKG;AACI,KAAK,UAAU,SAAS,CAAC,MAAc,EAAE,IAAY;IAC1D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,sEAAsE;QACtE,yEAAyE;QACzE,uDAAuD;QACvD,MAAM,OAAO,GAAG,CAAC,KAAY,EAAQ,EAAE;YACrC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE9B,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE;YAClC,IAAI,KAAK,EAAE,CAAC;gBACV,oE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C;YACV,MAAM,CAAC,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC,CAAC;QAC9D,CAAC,CAAC;QAEF,MAAM,OAAO,GAAG,GAAS,EAAE;YACzB,OAAO,EAAE,CAAC;YACV,MAAM,CAAC,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC,CAAC;QAC9D,CAAC,CAAC;QAEF;;WAEG;QACH,SAAS,OAAO;YACd,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACxB,YAAY,CAAC,KAAK,CAAC,CAAC;YACtB,CAAC;YACD,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YACtC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YACpC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC1C,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9B,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;AACL,CAAC;AAzDD,4BAyDC","sourcesContent":["import type { Socket } from 'node:net';\n\n/**\n * Write a newline-delimited line to a socket.\n *\n * @param socket - The socket to write to.\n * @param line - The line to write (without trailing newline).\n */\nexport async function writeLine(socket: Socket, line: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // A socket 'error' can fire while the write is in flight without ever\n // reaching the write callback; without this listener Node would treat it\n // as an unhandled 'error' event and crash the process.\n const onError = (error: Error): void => {\n socket.removeListener('error', onError);\n reject(error);\n };\n socket.once('error', onError);\n\n socket.write(`${line}\\n`, (error) => {\n if (error) {\n // A failed write (e.g. EPIPE) is delivered BOTH here AND as a later\n // 'error' event. Leave `onError` attached to handle that event —\n // detaching here would let Node treat it as unhandled and crash the\n // process. This reject settles the promise; `onError` detaches itself\n // when/if the event arrives.\n reject(error);\n return;\n }\n socket.removeListener('error', onError);\n resolve();\n });\n });\n}\n\n/**\n * Read a single newline-delimited line from a socket.\n *\n * @param socket - The socket to read from.\n * @param timeoutMs - Optional timeout in milliseconds. Rejects with a timeout\n * error if no complete line is received within the limit.\n * @returns The line read (without trailing newline).\n */\nexport async function readLine(\n socket: Socket,\n timeoutMs?: number,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n let buffer = '';\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n cleanup();\n reject(new Error('Socket read timed out'));\n }, timeoutMs);\n }\n\n const onData = (data: Buffer): void => {\n buffer += data.toString();\n const idx = buffer.indexOf('\\n');\n if (idx !== -1) {\n cleanup();\n resolve(buffer.slice(0, idx));\n }\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onEnd = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n const onClose = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n /**\n * Remove listeners registered by this call and clear the timeout.\n */\n function cleanup(): void {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n socket.removeListener('data', onData);\n socket.removeListener('error', onError);\n socket.removeListener('end', onEnd);\n socket.removeListener('close', onClose);\n }\n\n socket.on('data', onData);\n socket.once('error', onError);\n socket.once('end', onEnd);\n socket.once('close', onClose);\n });\n}\n"]}
1
+ {"version":3,"file":"socket-line.cjs","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":";;;AAEA;;;;;GAKG;AACI,KAAK,UAAU,SAAS,CAAC,MAAc,EAAE,IAAY;IAC1D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,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n/**\n * Write a newline-delimited line to a socket.\n *\n * @param socket - The socket to write to.\n * @param line - The line to write (without trailing newline).\n */\nexport async function writeLine(socket: Socket, line: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // A socket 'error' can fire while the write is in flight without ever\n // reaching the write callback; without this listener Node would treat it\n // as an unhandled 'error' event and crash the process.\n const onError = (error: Error): void => {\n socket.removeListener('error', onError);\n reject(error);\n };\n socket.once('error', onError);\n\n socket.write(`${line}\\n`, (error) => {\n socket.removeListener('error', onError);\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n}\n\n/**\n * Read a single newline-delimited line from a socket.\n *\n * @param socket - The socket to read from.\n * @param timeoutMs - Optional timeout in milliseconds. Rejects with a timeout\n * error if no complete line is received within the limit.\n * @returns The line read (without trailing newline).\n */\nexport async function readLine(\n socket: Socket,\n timeoutMs?: number,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n let buffer = '';\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n cleanup();\n reject(new Error('Socket read timed out'));\n }, timeoutMs);\n }\n\n const onData = (data: Buffer): void => {\n buffer += data.toString();\n const idx = buffer.indexOf('\\n');\n if (idx !== -1) {\n cleanup();\n resolve(buffer.slice(0, idx));\n }\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onEnd = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n const onClose = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n /**\n * Remove listeners registered by this call and clear the timeout.\n */\n function cleanup(): void {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n socket.removeListener('data', onData);\n socket.removeListener('error', onError);\n socket.removeListener('end', onEnd);\n socket.removeListener('close', onClose);\n }\n\n socket.on('data', onData);\n socket.once('error', onError);\n socket.once('end', onEnd);\n socket.once('close', onClose);\n });\n}\n"]}
@@ -1,6 +1,4 @@
1
1
  /// <reference types="node" />
2
- /// <reference types="node/net" />
3
- /// <reference types="npm-which/node_modules/@types/node/net" />
4
2
  import type { Socket } from "node:net";
5
3
  /**
6
4
  * Write a newline-delimited line to a socket.
@@ -1 +1 @@
1
- {"version":3,"file":"socket-line.d.cts","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":";;;AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB;AAEvC;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB3E;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAsDjB"}
1
+ {"version":3,"file":"socket-line.d.cts","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB;AAEvC;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB3E;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAsDjB"}
@@ -1,6 +1,4 @@
1
1
  /// <reference types="node" />
2
- /// <reference types="node/net" />
3
- /// <reference types="npm-which/node_modules/@types/node/net" />
4
2
  import type { Socket } from "node:net";
5
3
  /**
6
4
  * Write a newline-delimited line to a socket.
@@ -1 +1 @@
1
- {"version":3,"file":"socket-line.d.mts","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":";;;AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB;AAEvC;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB3E;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAsDjB"}
1
+ {"version":3,"file":"socket-line.d.mts","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB;AAEvC;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB3E;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAsDjB"}
@@ -15,17 +15,13 @@ export async function writeLine(socket, line) {
15
15
  };
16
16
  socket.once('error', onError);
17
17
  socket.write(`${line}\n`, (error) => {
18
+ socket.removeListener('error', onError);
18
19
  if (error) {
19
- // A failed write (e.g. EPIPE) is delivered BOTH here AND as a later
20
- // 'error' event. Leave `onError` attached to handle that event —
21
- // detaching here would let Node treat it as unhandled and crash the
22
- // process. This reject settles the promise; `onError` detaches itself
23
- // when/if the event arrives.
24
20
  reject(error);
25
- return;
26
21
  }
27
- socket.removeListener('error', onError);
28
- resolve();
22
+ else {
23
+ resolve();
24
+ }
29
25
  });
30
26
  });
31
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"socket-line.mjs","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,MAAc,EAAE,IAAY;IAC1D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,sEAAsE;QACtE,yEAAyE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Content":["import type { Socket } from 'node:net';\n\n/**\n * Write a newline-delimited line to a socket.\n *\n * @param socket - The socket to write to.\n * @param line - The line to write (without trailing newline).\n */\nexport async function writeLine(socket: Socket, line: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // A socket 'error' can fire while the write is in flight without ever\n // reaching the write callback; without this listener Node would treat it\n // as an unhandled 'error' event and crash the process.\n const onError = (error: Error): void => {\n socket.removeListener('error', onError);\n reject(error);\n };\n socket.once('error', onError);\n\n socket.write(`${line}\\n`, (error) => {\n if (error) {\n // A failed write (e.g. EPIPE) is delivered BOTH here AND as a later\n // 'error' event. Leave `onError` attached to handle that event —\n // detaching here would let Node treat it as unhandled and crash the\n // process. This reject settles the promise; `onError` detaches itself\n // when/if the event arrives.\n reject(error);\n return;\n }\n socket.removeListener('error', onError);\n resolve();\n });\n });\n}\n\n/**\n * Read a single newline-delimited line from a socket.\n *\n * @param socket - The socket to read from.\n * @param timeoutMs - Optional timeout in milliseconds. Rejects with a timeout\n * error if no complete line is received within the limit.\n * @returns The line read (without trailing newline).\n */\nexport async function readLine(\n socket: Socket,\n timeoutMs?: number,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n let buffer = '';\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n cleanup();\n reject(new Error('Socket read timed out'));\n }, timeoutMs);\n }\n\n const onData = (data: Buffer): void => {\n buffer += data.toString();\n const idx = buffer.indexOf('\\n');\n if (idx !== -1) {\n cleanup();\n resolve(buffer.slice(0, idx));\n }\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onEnd = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n const onClose = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n /**\n * Remove listeners registered by this call and clear the timeout.\n */\n function cleanup(): void {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n socket.removeListener('data', onData);\n socket.removeListener('error', onError);\n socket.removeListener('end', onEnd);\n socket.removeListener('close', onClose);\n }\n\n socket.on('data', onData);\n socket.once('error', onError);\n socket.once('end', onEnd);\n socket.once('close', onClose);\n });\n}\n"]}
1
+ {"version":3,"file":"socket-line.mjs","sourceRoot":"","sources":["../../src/daemon/socket-line.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,MAAc,EAAE,IAAY;IAC1D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,sEAAsE;QACtE,yEAAyE;QACzE,uDAAuD;QACvD,MAAM,OAAO,GAAG,CAAC,KAAY,EAAQ,EAAE;YACrC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE9B,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE;YAClC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,IAAI,KAAK,EAAE,CAAC;gBACV,MAAM,CAAC,KAAK,CAAC,CAAC;YAChB,CAAC;iBAAM,CAAC;gBACN,OAAO,EAAE,CAAC;YACZ,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,MAAc,EACd,SAAkB;IAElB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,IAAI,KAAgD,CAAC;QAErD,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC5B,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBACtB,OA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,CAAC;QAC1C,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9B,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Socket } from 'node:net';\n\n/**\n * Write a newline-delimited line to a socket.\n *\n * @param socket - The socket to write to.\n * @param line - The line to write (without trailing newline).\n */\nexport async function writeLine(socket: Socket, line: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // A socket 'error' can fire while the write is in flight without ever\n // reaching the write callback; without this listener Node would treat it\n // as an unhandled 'error' event and crash the process.\n const onError = (error: Error): void => {\n socket.removeListener('error', onError);\n reject(error);\n };\n socket.once('error', onError);\n\n socket.write(`${line}\\n`, (error) => {\n socket.removeListener('error', onError);\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n}\n\n/**\n * Read a single newline-delimited line from a socket.\n *\n * @param socket - The socket to read from.\n * @param timeoutMs - Optional timeout in milliseconds. Rejects with a timeout\n * error if no complete line is received within the limit.\n * @returns The line read (without trailing newline).\n */\nexport async function readLine(\n socket: Socket,\n timeoutMs?: number,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n let buffer = '';\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n cleanup();\n reject(new Error('Socket read timed out'));\n }, timeoutMs);\n }\n\n const onData = (data: Buffer): void => {\n buffer += data.toString();\n const idx = buffer.indexOf('\\n');\n if (idx !== -1) {\n cleanup();\n resolve(buffer.slice(0, idx));\n }\n };\n\n const onError = (error: Error): void => {\n cleanup();\n reject(error);\n };\n\n const onEnd = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n const onClose = (): void => {\n cleanup();\n reject(new Error('Socket closed before response received'));\n };\n\n /**\n * Remove listeners registered by this call and clear the timeout.\n */\n function cleanup(): void {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n socket.removeListener('data', onData);\n socket.removeListener('error', onError);\n socket.removeListener('end', onEnd);\n socket.removeListener('close', onClose);\n }\n\n socket.on('data', onData);\n socket.once('error', onError);\n socket.once('end', onEnd);\n socket.once('close', onClose);\n });\n}\n"]}
@@ -5,25 +5,15 @@ const promises_1 = require("node:fs/promises");
5
5
  const daemon_client_1 = require("./daemon-client.cjs");
6
6
  const utils_1 = require("./utils.cjs");
7
7
  /**
8
- * Stop the daemon, preferring a graceful shutdown.
8
+ * Stop the daemon via a `shutdown` RPC call. Falls back to PID + SIGTERM if
9
+ * the socket is unresponsive, and escalates to SIGKILL if SIGTERM is ignored.
9
10
  *
10
- * Resolution order when a live daemon is present:
11
- * 1. If the socket is responsive, request a graceful `shutdown` over it.
12
- * 2. If the recorded PID is still alive, escalate to SIGTERM.
13
- * 3. ...then SIGKILL.
14
- *
15
- * Signals (steps 2-3) are only ever sent against a PID that is observed alive.
16
- * The socket-absent + alive-PID branch trades a small risk of signalling a
11
+ * Signals are sent when EITHER the socket was observed (`responsive` or
12
+ * `unreachable`) OR the recorded PID is still alive on its own. The
13
+ * socket-absent + alive-PID branch trades a small risk of signalling a
17
14
  * recycled PID for the larger risk of leaving an orphan daemon holding the
18
- * SQLite database — which `daemon purge` would otherwise wipe out from under
19
- * it.
20
- *
21
- * When the socket is NOT responsive AND the recorded PID is dead (or there is
22
- * no PID file), there is no live daemon: a lingering socket or PID file is
23
- * stale leftovers from a daemon that already exited — typically one that
24
- * crashed without running its own cleanup. Those files are removed and the
25
- * stop is reported as successful, rather than failing on a daemon that is
26
- * already gone.
15
+ * SQLite database — which `daemon purge` would otherwise wipe out from
16
+ * under it.
27
17
  *
28
18
  * @param socketPath - The daemon socket path.
29
19
  * @param pidPath - The daemon PID file path.
@@ -35,13 +25,9 @@ async function stopDaemon(socketPath, pidPath, log) {
35
25
  const ping = await (0, daemon_client_1.pingDaemon)(socketPath);
36
26
  const socketObserved = ping.status === 'responsive' || ping.status === 'unreachable';
37
27
  const processAlive = pid !== undefined && (0, utils_1.isProcessAlive)(pid);
38
- // Only `absent` and `refused` prove no live daemon; `permission`/`timeout`/
39
- // `protocol` may be a wedged or foreign daemon, so those fall through.
40
- const socketProvenGone = ping.status === 'absent' ||
41
- (ping.status === 'unreachable' && ping.reason === 'refused');
42
- if (socketProvenGone && !processAlive) {
28
+ if (!socketObserved && !processAlive) {
29
+ // No live daemon evidence. Just remove the stale PID file if any.
43
30
  await cleanupFile(pidPath, 'PID file', log);
44
- await cleanupFile(socketPath, 'socket file', log);
45
31
  return true;
46
32
  }
47
33
  log?.('Stopping daemon...');
@@ -1 +1 @@
1
- {"version":3,"file":"stop-daemon.cjs","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":";;;AAAA,+CAAsC;AAEtC,uDAA0D;AAC1D,uCAA2E;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACI,KAAK,UAAU,UAAU,CAC9B,UAAkB,EAClB,OAAe,EACf,GAA+B;IAE/B,MAAM,GAAG,GAAG,MAAM,IAAA,mBAAW,EAAC,OAAO,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAU,EAAC,UAAU,CAAC,CAAC;IAC1C,MAAM,cAAc,GAClB,IAAI,CAAC,MAAM,KAAK,YAAY,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC;IAChE,MAAM,YAAY,GAAG,GAAG,KAAK,SAAS,IAAI,IAAA,sBAAc,EAAC,GAAG,CAAC,CAAC;IAE9D,4EAA4E;IAC5E,uEAAuE;IACvE,MAAM,gBAAgB,GACpB,IAAI,CAAC,MAAM,KAAK,QAAQ;QACxB,CAAC,IAAI,CAAC,MAAM,KAAK,aAAa,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS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AAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACvD,GAAG,EAAE,CAAC,oBAAoB,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { rm } from 'node:fs/promises';\n\nimport { pingDaemon, sendCommand } from './daemon-client';\nimport { isProcessAlive, readPidFile, sendSignal, waitFor } from './utils';\n\n/**\n * Stop the daemon, preferring a graceful shutdown.\n *\n * Resolution order when a live daemon is present:\n * 1. If the socket is responsive, request a graceful `shutdown` over it.\n * 2. If the recorded PID is still alive, escalate to SIGTERM.\n * 3. ...then SIGKILL.\n *\n * Signals (steps 2-3) are only ever sent against a PID that is observed alive.\n * The socket-absent + alive-PID branch trades a small risk of signalling a\n * recycled PID for the larger risk of leaving an orphan daemon holding the\n * SQLite database — which `daemon purge` would otherwise wipe out from under\n * it.\n *\n * When the socket is NOT responsive AND the recorded PID is dead (or there is\n * no PID file), there is no live daemon: a lingering socket or PID file is\n * stale leftovers from a daemon that already exited — typically one that\n * crashed without running its own cleanup. Those files are removed and the\n * stop is reported as successful, rather than failing on a daemon that is\n * already gone.\n *\n * @param socketPath - The daemon socket path.\n * @param pidPath - The daemon PID file path.\n * @param log - Optional logging function for status messages.\n * @returns True if the daemon was stopped (or was not running).\n */\nexport async function stopDaemon(\n socketPath: string,\n pidPath: string,\n log?: (message: string) => void,\n): Promise<boolean> {\n const pid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n const socketObserved =\n ping.status === 'responsive' || ping.status === 'unreachable';\n const processAlive = pid !== undefined && isProcessAlive(pid);\n\n // Only `absent` and `refused` prove no live daemon; `permission`/`timeout`/\n // `protocol` may be a wedged or foreign daemon, so those fall through.\n const socketProvenGone =\n ping.status === 'absent' ||\n (ping.status === 'unreachable' && ping.reason === 'refused');\n\n if (socketProvenGone && !processAlive) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n return true;\n }\n\n log?.('Stopping daemon...');\n\n let stopped = false;\n\n // Strategy 1: Graceful socket-based shutdown.\n if (ping.status === 'responsive') {\n try {\n await sendCommand({ socketPath, method: 'shutdown' });\n } catch (error) {\n log?.(`Graceful shutdown request failed: ${String(error)}`);\n }\n // A quiet socket does not prove the process exited; require the recorded\n // pid to be gone too, so a daemon that outlived its socket falls through to\n // SIGTERM/SIGKILL rather than being orphaned.\n stopped = await waitFor(\n async () =>\n (await pingDaemon(socketPath)).status !== 'responsive' &&\n (pid === undefined || !isProcessAlive(pid)),\n 5_000,\n );\n }\n\n // Strategy 2: SIGTERM. Signal when either the socket was observed or the\n // recorded PID is alive; the absent+alive case typically means someone\n // removed the socket from under a live daemon.\n if (!stopped && processAlive && pid !== undefined) {\n if (!socketObserved) {\n log?.(\n `Socket at ${socketPath} is absent but recorded pid ${pid} is alive; signalling anyway.`,\n );\n }\n try {\n if (sendSignal(pid, 'SIGTERM')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 5_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGTERM failed: ${String(error)}`);\n }\n }\n\n // Strategy 3: SIGKILL.\n if (!stopped && processAlive && pid !== undefined) {\n try {\n if (sendSignal(pid, 'SIGKILL')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 2_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGKILL failed: ${String(error)}`);\n }\n }\n\n if (stopped) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n log?.('Daemon stopped.');\n }\n\n return stopped;\n}\n\n/**\n * Remove a file best-effort, logging any failure rather than letting it\n * propagate. ENOENT is silently ignored via `force: true`.\n *\n * @param path - The file path to remove.\n * @param label - Human-readable label for log messages.\n * @param log - Optional log sink.\n */\nasync function cleanupFile(\n path: string,\n label: string,\n log: ((message: string) => void) | undefined,\n): Promise<void> {\n await rm(path, { force: true }).catch((error: unknown) => {\n log?.(`Failed to remove ${label}: ${String(error)}`);\n });\n}\n"]}
1
+ {"version":3,"file":"stop-daemon.cjs","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":";;;AAAA,+CAAsC;AAEtC,uDAA0D;AAC1D,uCAA2E;AAE3E;;;;;;;;;;;;;;;GAeG;AACI,KAAK,UAAU,UAAU,CAC9B,UAAkB,EAClB,OAAe,EACf,GAA+B;IAE/B,MAAM,GAAG,GAAG,MAAM,IAAA,mBAAW,EAAC,OAAO,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAU,EAAC,UAAU,CAAC,CAAC;IAC1C,MAAM,cAAc,GAClB,IAAI,CAAC,MAAM,KAAK,YAAY,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC;IAChE,MAAM,YAAY,GAAG,GAAG,KAAK,SAAS,IAAI,IAAA,sBAAc,EAAC,GAAG,CAAC,CAAC;IAE9D,IAAI,CAAC,cAAc,IAAI,CAAC,YAAY,EAAE,CAAC;QACrC,kEAAkE;QAClE,MAAM,WAAW,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,GAAG,EAAE,CAAC,oBAAoB,CAAC,CAAC;IAE5B,IAAI,OAAO,GAAG,KAAK,CAAC;IAEpB,8CAA8C;IAC9C,IAAI,IAAI,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC;YACH,MAAM,IAAA,2BAAW,EAAC,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;QACxD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,EAAE,CAAC,qCAAqC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC9D,CAAC;QACD,yEAAyE;QACzE,4EAA4E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D,CAAC;iBAAM,CAAC;gBACN,OAAO,GAAG,IAAI,CAAC,CAAC,gCAAgC;YAClD,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,EAAE,CAAC,mBAAmB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,IAAI,OAAO,EAAE,CAAC;QACZ,MAAM,WAAW,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC5C,MAAM,WAAW,CAAC,UAAU,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAClD,GAAG,EAAE,CAAC,iBAAiB,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AA/ED,gCA+EC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,WAAW,CACxB,IAAY,EACZ,KAAa,EACb,GAA4C;IAE5C,MAAM,IAAA,aAAE,EAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACvD,GAAG,EAAE,CAAC,oBAAoB,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { rm } from 'node:fs/promises';\n\nimport { pingDaemon, sendCommand } from './daemon-client';\nimport { isProcessAlive, readPidFile, sendSignal, waitFor } from './utils';\n\n/**\n * Stop the daemon via a `shutdown` RPC call. Falls back to PID + SIGTERM if\n * the socket is unresponsive, and escalates to SIGKILL if SIGTERM is ignored.\n *\n * Signals are sent when EITHER the socket was observed (`responsive` or\n * `unreachable`) OR the recorded PID is still alive on its own. The\n * socket-absent + alive-PID branch trades a small risk of signalling a\n * recycled PID for the larger risk of leaving an orphan daemon holding the\n * SQLite database — which `daemon purge` would otherwise wipe out from\n * under it.\n *\n * @param socketPath - The daemon socket path.\n * @param pidPath - The daemon PID file path.\n * @param log - Optional logging function for status messages.\n * @returns True if the daemon was stopped (or was not running).\n */\nexport async function stopDaemon(\n socketPath: string,\n pidPath: string,\n log?: (message: string) => void,\n): Promise<boolean> {\n const pid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n const socketObserved =\n ping.status === 'responsive' || ping.status === 'unreachable';\n const processAlive = pid !== undefined && isProcessAlive(pid);\n\n if (!socketObserved && !processAlive) {\n // No live daemon evidence. Just remove the stale PID file if any.\n await cleanupFile(pidPath, 'PID file', log);\n return true;\n }\n\n log?.('Stopping daemon...');\n\n let stopped = false;\n\n // Strategy 1: Graceful socket-based shutdown.\n if (ping.status === 'responsive') {\n try {\n await sendCommand({ socketPath, method: 'shutdown' });\n } catch (error) {\n log?.(`Graceful shutdown request failed: ${String(error)}`);\n }\n // A quiet socket does not prove the process exited; require the recorded\n // pid to be gone too, so a daemon that outlived its socket falls through to\n // SIGTERM/SIGKILL rather than being orphaned.\n stopped = await waitFor(\n async () =>\n (await pingDaemon(socketPath)).status !== 'responsive' &&\n (pid === undefined || !isProcessAlive(pid)),\n 5_000,\n );\n }\n\n // Strategy 2: SIGTERM. Signal when either the socket was observed or the\n // recorded PID is alive; the absent+alive case typically means someone\n // removed the socket from under a live daemon.\n if (!stopped && processAlive && pid !== undefined) {\n if (!socketObserved) {\n log?.(\n `Socket at ${socketPath} is absent but recorded pid ${pid} is alive; signalling anyway.`,\n );\n }\n try {\n if (sendSignal(pid, 'SIGTERM')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 5_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGTERM failed: ${String(error)}`);\n }\n }\n\n // Strategy 3: SIGKILL.\n if (!stopped && processAlive && pid !== undefined) {\n try {\n if (sendSignal(pid, 'SIGKILL')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 2_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGKILL failed: ${String(error)}`);\n }\n }\n\n if (stopped) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n log?.('Daemon stopped.');\n }\n\n return stopped;\n}\n\n/**\n * Remove a file best-effort, logging any failure rather than letting it\n * propagate. ENOENT is silently ignored via `force: true`.\n *\n * @param path - The file path to remove.\n * @param label - Human-readable label for log messages.\n * @param log - Optional log sink.\n */\nasync function cleanupFile(\n path: string,\n label: string,\n log: ((message: string) => void) | undefined,\n): Promise<void> {\n await rm(path, { force: true }).catch((error: unknown) => {\n log?.(`Failed to remove ${label}: ${String(error)}`);\n });\n}\n"]}
@@ -1,23 +1,13 @@
1
1
  /**
2
- * Stop the daemon, preferring a graceful shutdown.
2
+ * Stop the daemon via a `shutdown` RPC call. Falls back to PID + SIGTERM if
3
+ * the socket is unresponsive, and escalates to SIGKILL if SIGTERM is ignored.
3
4
  *
4
- * Resolution order when a live daemon is present:
5
- * 1. If the socket is responsive, request a graceful `shutdown` over it.
6
- * 2. If the recorded PID is still alive, escalate to SIGTERM.
7
- * 3. ...then SIGKILL.
8
- *
9
- * Signals (steps 2-3) are only ever sent against a PID that is observed alive.
10
- * The socket-absent + alive-PID branch trades a small risk of signalling a
5
+ * Signals are sent when EITHER the socket was observed (`responsive` or
6
+ * `unreachable`) OR the recorded PID is still alive on its own. The
7
+ * socket-absent + alive-PID branch trades a small risk of signalling a
11
8
  * recycled PID for the larger risk of leaving an orphan daemon holding the
12
- * SQLite database — which `daemon purge` would otherwise wipe out from under
13
- * it.
14
- *
15
- * When the socket is NOT responsive AND the recorded PID is dead (or there is
16
- * no PID file), there is no live daemon: a lingering socket or PID file is
17
- * stale leftovers from a daemon that already exited — typically one that
18
- * crashed without running its own cleanup. Those files are removed and the
19
- * stop is reported as successful, rather than failing on a daemon that is
20
- * already gone.
9
+ * SQLite database — which `daemon purge` would otherwise wipe out from
10
+ * under it.
21
11
  *
22
12
  * @param socketPath - The daemon socket path.
23
13
  * @param pidPath - The daemon PID file path.
@@ -1 +1 @@
1
- {"version":3,"file":"stop-daemon.d.cts","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,OAAO,CAAC,OAAO,CAAC,CAiFlB"}
1
+ {"version":3,"file":"stop-daemon.d.cts","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,OAAO,CAAC,OAAO,CAAC,CA2ElB"}
@@ -1,23 +1,13 @@
1
1
  /**
2
- * Stop the daemon, preferring a graceful shutdown.
2
+ * Stop the daemon via a `shutdown` RPC call. Falls back to PID + SIGTERM if
3
+ * the socket is unresponsive, and escalates to SIGKILL if SIGTERM is ignored.
3
4
  *
4
- * Resolution order when a live daemon is present:
5
- * 1. If the socket is responsive, request a graceful `shutdown` over it.
6
- * 2. If the recorded PID is still alive, escalate to SIGTERM.
7
- * 3. ...then SIGKILL.
8
- *
9
- * Signals (steps 2-3) are only ever sent against a PID that is observed alive.
10
- * The socket-absent + alive-PID branch trades a small risk of signalling a
5
+ * Signals are sent when EITHER the socket was observed (`responsive` or
6
+ * `unreachable`) OR the recorded PID is still alive on its own. The
7
+ * socket-absent + alive-PID branch trades a small risk of signalling a
11
8
  * recycled PID for the larger risk of leaving an orphan daemon holding the
12
- * SQLite database — which `daemon purge` would otherwise wipe out from under
13
- * it.
14
- *
15
- * When the socket is NOT responsive AND the recorded PID is dead (or there is
16
- * no PID file), there is no live daemon: a lingering socket or PID file is
17
- * stale leftovers from a daemon that already exited — typically one that
18
- * crashed without running its own cleanup. Those files are removed and the
19
- * stop is reported as successful, rather than failing on a daemon that is
20
- * already gone.
9
+ * SQLite database — which `daemon purge` would otherwise wipe out from
10
+ * under it.
21
11
  *
22
12
  * @param socketPath - The daemon socket path.
23
13
  * @param pidPath - The daemon PID file path.
@@ -1 +1 @@
1
- {"version":3,"file":"stop-daemon.d.mts","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,OAAO,CAAC,OAAO,CAAC,CAiFlB"}
1
+ {"version":3,"file":"stop-daemon.d.mts","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,OAAO,CAAC,OAAO,CAAC,CA2ElB"}
@@ -2,25 +2,15 @@ import { rm } from "node:fs/promises";
2
2
  import { pingDaemon, sendCommand } from "./daemon-client.mjs";
3
3
  import { isProcessAlive, readPidFile, sendSignal, waitFor } from "./utils.mjs";
4
4
  /**
5
- * Stop the daemon, preferring a graceful shutdown.
5
+ * Stop the daemon via a `shutdown` RPC call. Falls back to PID + SIGTERM if
6
+ * the socket is unresponsive, and escalates to SIGKILL if SIGTERM is ignored.
6
7
  *
7
- * Resolution order when a live daemon is present:
8
- * 1. If the socket is responsive, request a graceful `shutdown` over it.
9
- * 2. If the recorded PID is still alive, escalate to SIGTERM.
10
- * 3. ...then SIGKILL.
11
- *
12
- * Signals (steps 2-3) are only ever sent against a PID that is observed alive.
13
- * The socket-absent + alive-PID branch trades a small risk of signalling a
8
+ * Signals are sent when EITHER the socket was observed (`responsive` or
9
+ * `unreachable`) OR the recorded PID is still alive on its own. The
10
+ * socket-absent + alive-PID branch trades a small risk of signalling a
14
11
  * recycled PID for the larger risk of leaving an orphan daemon holding the
15
- * SQLite database — which `daemon purge` would otherwise wipe out from under
16
- * it.
17
- *
18
- * When the socket is NOT responsive AND the recorded PID is dead (or there is
19
- * no PID file), there is no live daemon: a lingering socket or PID file is
20
- * stale leftovers from a daemon that already exited — typically one that
21
- * crashed without running its own cleanup. Those files are removed and the
22
- * stop is reported as successful, rather than failing on a daemon that is
23
- * already gone.
12
+ * SQLite database — which `daemon purge` would otherwise wipe out from
13
+ * under it.
24
14
  *
25
15
  * @param socketPath - The daemon socket path.
26
16
  * @param pidPath - The daemon PID file path.
@@ -32,13 +22,9 @@ export async function stopDaemon(socketPath, pidPath, log) {
32
22
  const ping = await pingDaemon(socketPath);
33
23
  const socketObserved = ping.status === 'responsive' || ping.status === 'unreachable';
34
24
  const processAlive = pid !== undefined && isProcessAlive(pid);
35
- // Only `absent` and `refused` prove no live daemon; `permission`/`timeout`/
36
- // `protocol` may be a wedged or foreign daemon, so those fall through.
37
- const socketProvenGone = ping.status === 'absent' ||
38
- (ping.status === 'unreachable' && ping.reason === 'refused');
39
- if (socketProvenGone && !processAlive) {
25
+ if (!socketObserved && !processAlive) {
26
+ // No live daemon evidence. Just remove the stale PID file if any.
40
27
  await cleanupFile(pidPath, 'PID file', log);
41
- await cleanupFile(socketPath, 'socket file', log);
42
28
  return true;
43
29
  }
44
30
  log?.('Stopping daemon...');
@@ -1 +1 @@
1
- {"version":3,"file":"stop-daemon.mjs","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,yBAAyB;AAEtC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,4BAAwB;AAC1D,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,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CAAC,gCAAgC;YAClD,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,EAAE,CAAC,mBAAmB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,IAAI,OAAO,EAAE,CAAC;QACZ,MAAM,WAAW,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC5C,MAAM,WAAW,CAAC,UAAU,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAClD,GAAG,EAAE,CAAC,iBAAiB,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,WAAW,CACxB,IAAY,EACZ,KAAa,EACb,GAA4C;IAE5C,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACvD,GAAG,EAAE,CAAC,oBAAoB,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { rm } from 'node:fs/promises';\n\nimport { pingDaemon, sendCommand } from './daemon-client';\nimport { isProcessAlive, readPidFile, sendSignal, waitFor } from './utils';\n\n/**\n * Stop the daemon, preferring a graceful shutdown.\n *\n * Resolution order when a live daemon is present:\n * 1. If the socket is responsive, request a graceful `shutdown` over it.\n * 2. If the recorded PID is still alive, escalate to SIGTERM.\n * 3. ...then SIGKILL.\n *\n * Signals (steps 2-3) are only ever sent against a PID that is observed alive.\n * The socket-absent + alive-PID branch trades a small risk of signalling a\n * recycled PID for the larger risk of leaving an orphan daemon holding the\n * SQLite database — which `daemon purge` would otherwise wipe out from under\n * it.\n *\n * When the socket is NOT responsive AND the recorded PID is dead (or there is\n * no PID file), there is no live daemon: a lingering socket or PID file is\n * stale leftovers from a daemon that already exited — typically one that\n * crashed without running its own cleanup. Those files are removed and the\n * stop is reported as successful, rather than failing on a daemon that is\n * already gone.\n *\n * @param socketPath - The daemon socket path.\n * @param pidPath - The daemon PID file path.\n * @param log - Optional logging function for status messages.\n * @returns True if the daemon was stopped (or was not running).\n */\nexport async function stopDaemon(\n socketPath: string,\n pidPath: string,\n log?: (message: string) => void,\n): Promise<boolean> {\n const pid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n const socketObserved =\n ping.status === 'responsive' || ping.status === 'unreachable';\n const processAlive = pid !== undefined && isProcessAlive(pid);\n\n // Only `absent` and `refused` prove no live daemon; `permission`/`timeout`/\n // `protocol` may be a wedged or foreign daemon, so those fall through.\n const socketProvenGone =\n ping.status === 'absent' ||\n (ping.status === 'unreachable' && ping.reason === 'refused');\n\n if (socketProvenGone && !processAlive) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n return true;\n }\n\n log?.('Stopping daemon...');\n\n let stopped = false;\n\n // Strategy 1: Graceful socket-based shutdown.\n if (ping.status === 'responsive') {\n try {\n await sendCommand({ socketPath, method: 'shutdown' });\n } catch (error) {\n log?.(`Graceful shutdown request failed: ${String(error)}`);\n }\n // A quiet socket does not prove the process exited; require the recorded\n // pid to be gone too, so a daemon that outlived its socket falls through to\n // SIGTERM/SIGKILL rather than being orphaned.\n stopped = await waitFor(\n async () =>\n (await pingDaemon(socketPath)).status !== 'responsive' &&\n (pid === undefined || !isProcessAlive(pid)),\n 5_000,\n );\n }\n\n // Strategy 2: SIGTERM. Signal when either the socket was observed or the\n // recorded PID is alive; the absent+alive case typically means someone\n // removed the socket from under a live daemon.\n if (!stopped && processAlive && pid !== undefined) {\n if (!socketObserved) {\n log?.(\n `Socket at ${socketPath} is absent but recorded pid ${pid} is alive; signalling anyway.`,\n );\n }\n try {\n if (sendSignal(pid, 'SIGTERM')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 5_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGTERM failed: ${String(error)}`);\n }\n }\n\n // Strategy 3: SIGKILL.\n if (!stopped && processAlive && pid !== undefined) {\n try {\n if (sendSignal(pid, 'SIGKILL')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 2_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGKILL failed: ${String(error)}`);\n }\n }\n\n if (stopped) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n log?.('Daemon stopped.');\n }\n\n return stopped;\n}\n\n/**\n * Remove a file best-effort, logging any failure rather than letting it\n * propagate. ENOENT is silently ignored via `force: true`.\n *\n * @param path - The file path to remove.\n * @param label - Human-readable label for log messages.\n * @param log - Optional log sink.\n */\nasync function cleanupFile(\n path: string,\n label: string,\n log: ((message: string) => void) | undefined,\n): Promise<void> {\n await rm(path, { force: true }).catch((error: unknown) => {\n log?.(`Failed to remove ${label}: ${String(error)}`);\n });\n}\n"]}
1
+ {"version":3,"file":"stop-daemon.mjs","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,yBAAyB;AAEtC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,4BAAwB;AAC1D,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,oBAAgB;AAE3E;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,UAAkB,EAClB,OAAe,EACf,GAA+B;IAE/B,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,MAAM,UAAU,CAAC,UAAU,CAAC,CAAC;IAC1C,MAAM,cAAc,GAClB,IAAI,CAAC,MAAM,KAAK,YAAY,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC;IAChE,MAAM,YAAY,GAAG,GAAG,KAA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,EAAE,CAAC,oBAAoB,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { rm } from 'node:fs/promises';\n\nimport { pingDaemon, sendCommand } from './daemon-client';\nimport { isProcessAlive, readPidFile, sendSignal, waitFor } from './utils';\n\n/**\n * Stop the daemon via a `shutdown` RPC call. Falls back to PID + SIGTERM if\n * the socket is unresponsive, and escalates to SIGKILL if SIGTERM is ignored.\n *\n * Signals are sent when EITHER the socket was observed (`responsive` or\n * `unreachable`) OR the recorded PID is still alive on its own. The\n * socket-absent + alive-PID branch trades a small risk of signalling a\n * recycled PID for the larger risk of leaving an orphan daemon holding the\n * SQLite database — which `daemon purge` would otherwise wipe out from\n * under it.\n *\n * @param socketPath - The daemon socket path.\n * @param pidPath - The daemon PID file path.\n * @param log - Optional logging function for status messages.\n * @returns True if the daemon was stopped (or was not running).\n */\nexport async function stopDaemon(\n socketPath: string,\n pidPath: string,\n log?: (message: string) => void,\n): Promise<boolean> {\n const pid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n const socketObserved =\n ping.status === 'responsive' || ping.status === 'unreachable';\n const processAlive = pid !== undefined && isProcessAlive(pid);\n\n if (!socketObserved && !processAlive) {\n // No live daemon evidence. Just remove the stale PID file if any.\n await cleanupFile(pidPath, 'PID file', log);\n return true;\n }\n\n log?.('Stopping daemon...');\n\n let stopped = false;\n\n // Strategy 1: Graceful socket-based shutdown.\n if (ping.status === 'responsive') {\n try {\n await sendCommand({ socketPath, method: 'shutdown' });\n } catch (error) {\n log?.(`Graceful shutdown request failed: ${String(error)}`);\n }\n // A quiet socket does not prove the process exited; require the recorded\n // pid to be gone too, so a daemon that outlived its socket falls through to\n // SIGTERM/SIGKILL rather than being orphaned.\n stopped = await waitFor(\n async () =>\n (await pingDaemon(socketPath)).status !== 'responsive' &&\n (pid === undefined || !isProcessAlive(pid)),\n 5_000,\n );\n }\n\n // Strategy 2: SIGTERM. Signal when either the socket was observed or the\n // recorded PID is alive; the absent+alive case typically means someone\n // removed the socket from under a live daemon.\n if (!stopped && processAlive && pid !== undefined) {\n if (!socketObserved) {\n log?.(\n `Socket at ${socketPath} is absent but recorded pid ${pid} is alive; signalling anyway.`,\n );\n }\n try {\n if (sendSignal(pid, 'SIGTERM')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 5_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGTERM failed: ${String(error)}`);\n }\n }\n\n // Strategy 3: SIGKILL.\n if (!stopped && processAlive && pid !== undefined) {\n try {\n if (sendSignal(pid, 'SIGKILL')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 2_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGKILL failed: ${String(error)}`);\n }\n }\n\n if (stopped) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n log?.('Daemon stopped.');\n }\n\n return stopped;\n}\n\n/**\n * Remove a file best-effort, logging any failure rather than letting it\n * propagate. ENOENT is silently ignored via `force: true`.\n *\n * @param path - The file path to remove.\n * @param label - Human-readable label for log messages.\n * @param log - Optional log sink.\n */\nasync function cleanupFile(\n path: string,\n label: string,\n log: ((message: string) => void) | undefined,\n): Promise<void> {\n await rm(path, { force: true }).catch((error: unknown) => {\n log?.(`Failed to remove ${label}: ${String(error)}`);\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.waitFor = exports.sendSignal = exports.isProcessAlive = exports.readPidFile = exports.isStringArray = exports.formatJsonRpcError = exports.makeDaemonConnectionError = exports.isErrorWithCode = void 0;
3
+ exports.waitFor = exports.sendSignal = exports.isProcessAlive = exports.readPidFile = exports.isErrorWithCode = void 0;
4
4
  const utils_1 = require("@metamask/utils");
5
5
  const promises_1 = require("node:fs/promises");
6
6
  /**
@@ -14,57 +14,6 @@ function isErrorWithCode(error, code) {
14
14
  return (0, utils_1.isErrorWithCode)(error) && error.code === code;
15
15
  }
16
16
  exports.isErrorWithCode = isErrorWithCode;
17
- /**
18
- * Turn an error thrown while contacting the daemon socket into a user-facing
19
- * message for `Command.error`, so every command reports the same failure the
20
- * same way. Distinguishes a stopped daemon (`ENOENT`/`ECONNREFUSED`), a
21
- * connection dropped mid-request (`ECONNRESET`), and a permission problem
22
- * (`EACCES`/`EPERM`), falling back to the raw error message.
23
- *
24
- * @param error - The value thrown while contacting the daemon.
25
- * @returns A human-readable explanation of the failure.
26
- */
27
- function makeDaemonConnectionError(error) {
28
- if (isErrorWithCode(error, 'ENOENT') ||
29
- isErrorWithCode(error, 'ECONNREFUSED')) {
30
- return 'Daemon is not running. Start it with `mm daemon start`.';
31
- }
32
- // A reset drops an already-established connection, so the daemon was running
33
- // — most likely it crashed mid-request. Don't tell the user to start it.
34
- if (isErrorWithCode(error, 'ECONNRESET')) {
35
- return ('Lost the connection to the daemon; it may have crashed while ' +
36
- 'handling the request. Check `mm daemon status` and the daemon log.');
37
- }
38
- if (isErrorWithCode(error, 'EACCES') || isErrorWithCode(error, 'EPERM')) {
39
- return ('Cannot connect to the daemon socket: permission denied. ' +
40
- 'The socket may be owned by another user, or MM_DATA_DIR ' +
41
- 'may point to a directory you cannot access.');
42
- }
43
- return error instanceof Error ? error.message : String(error);
44
- }
45
- exports.makeDaemonConnectionError = makeDaemonConnectionError;
46
- /**
47
- * Format the error of a JSON-RPC failure response into a user-facing message
48
- * for `Command.error`, so every command reports RPC failures the same way.
49
- *
50
- * @param error - The `error` field of a JSON-RPC failure response.
51
- * @returns The error message annotated with its numeric code.
52
- */
53
- function formatJsonRpcError(error) {
54
- return `${error.message} (code ${String(error.code)})`;
55
- }
56
- exports.formatJsonRpcError = formatJsonRpcError;
57
- /**
58
- * Check whether a value is an array of strings. Used to validate untyped RPC
59
- * results (e.g. the daemon's `listActions`) before treating them as `string[]`.
60
- *
61
- * @param value - The value to check.
62
- * @returns True if the value is an array whose every element is a string.
63
- */
64
- function isStringArray(value) {
65
- return (Array.isArray(value) && value.every((item) => typeof item === 'string'));
66
- }
67
- exports.isStringArray = isStringArray;
68
17
  /**
69
18
  * Read a PID from a file. The file may contain just the PID, or the PID on
70
19
  * the first line followed by additional metadata (e.g. start time written by
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/daemon/utils.ts"],"names":[],"mappings":";;;AACA,2CAAkE;AAClE,+CAA4C;AAE5C;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,KAAc,EAAE,IAAY;IAC1D,OAAO,IAAA,uBAAY,EAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACpD,CAAC;AAFD,0CAEC;AAED;;;;;;;;;GASG;AACH,SAAgB,yBAAyB,CAAC,KAAc;IACtD,IACE,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC;QAChC,eAAe,CAAC,KAAK,EAAE,cAAc,CAAC,EACtC,CAAC;QACD,OAAO,yDAAyD,CAAC;IACnE,CAAC;IACD,6EAA6E;IAC7E,yEAAyE;IACzE,IAAI,eAAe,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE,CAAC;QACzC,OAAO,CACL,+DAA+D;YAC/D,oEAAoE,CACrE,CAAC;IACJ,CAAC;IACD,IAAI,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC,IAAI,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;QACxE,OAAO,CACL,0DAA0D;YAC1D,0DAA0D;YAC1D,6CAA6C,CAC9C,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAvBD,8DAuBC;AAED;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAAC,KAAmB;IACpD,OAAO,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AO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAbD,wCAaC;AAED;;;;;;;;GAQG;AACH,SAAgB,UAAU,CAAC,GAAW,EAAE,MAAsB;IAC5D,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC1B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;YACpC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAVD,gCAUC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,OAAO,CAC3B,KAAuC,EACvC,SAAiB;IAEjB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;IACxC,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,EAAE,CAAC;QAC7B,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC3D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAZD,0BAYC","sourcesContent":["import type { JsonRpcError } from '@metamask/utils';\nimport { isErrorWithCode as hasErrorCode } from '@metamask/utils';\nimport { readFile } from 'node:fs/promises';\n\n/**\n * Check whether an unknown error is a Node.js system error with the given code.\n *\n * @param error - The error to check.\n * @param code - The expected error code (e.g. 'ENOENT', 'EPERM').\n * @returns True if the error matches the code.\n */\nexport function isErrorWithCode(error: unknown, code: string): boolean {\n return hasErrorCode(error) && error.code === code;\n}\n\n/**\n * Turn an error thrown while contacting the daemon socket into a user-facing\n * message for `Command.error`, so every command reports the same failure the\n * same way. Distinguishes a stopped daemon (`ENOENT`/`ECONNREFUSED`), a\n * connection dropped mid-request (`ECONNRESET`), and a permission problem\n * (`EACCES`/`EPERM`), falling back to the raw error message.\n *\n * @param error - The value thrown while contacting the daemon.\n * @returns A human-readable explanation of the failure.\n */\nexport function makeDaemonConnectionError(error: unknown): string {\n if (\n isErrorWithCode(error, 'ENOENT') ||\n isErrorWithCode(error, 'ECONNREFUSED')\n ) {\n return 'Daemon is not running. Start it with `mm daemon start`.';\n }\n // A reset drops an already-established connection, so the daemon was running\n // — most likely it crashed mid-request. Don't tell the user to start it.\n if (isErrorWithCode(error, 'ECONNRESET')) {\n return (\n 'Lost the connection to the daemon; it may have crashed while ' +\n 'handling the request. Check `mm daemon status` and the daemon log.'\n );\n }\n if (isErrorWithCode(error, 'EACCES') || isErrorWithCode(error, 'EPERM')) {\n return (\n 'Cannot connect to the daemon socket: permission denied. ' +\n 'The socket may be owned by another user, or MM_DATA_DIR ' +\n 'may point to a directory you cannot access.'\n );\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Format the error of a JSON-RPC failure response into a user-facing message\n * for `Command.error`, so every command reports RPC failures the same way.\n *\n * @param error - The `error` field of a JSON-RPC failure response.\n * @returns The error message annotated with its numeric code.\n */\nexport function formatJsonRpcError(error: JsonRpcError): string {\n return `${error.message} (code ${String(error.code)})`;\n}\n\n/**\n * Check whether a value is an array of strings. Used to validate untyped RPC\n * results (e.g. the daemon's `listActions`) before treating them as `string[]`.\n *\n * @param value - The value to check.\n * @returns True if the value is an array whose every element is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return (\n Array.isArray(value) && value.every((item) => typeof item === 'string')\n );\n}\n\n/**\n * Read a PID from a file. The file may contain just the PID, or the PID on\n * the first line followed by additional metadata (e.g. start time written by\n * the daemon).\n *\n * @param pidPath - The PID file path.\n * @returns The PID, or undefined if the file is missing or its first line is\n * not a positive integer.\n */\nexport async function readPidFile(\n pidPath: string,\n): Promise<number | undefined> {\n let contents: string;\n try {\n contents = await readFile(pidPath, 'utf-8');\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ENOENT')) {\n return undefined;\n }\n throw error;\n }\n // String.prototype.split always returns at least one element, so [0] is safe.\n const pid = Number(contents.split('\\n')[0].trim());\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n}\n\n/**\n * Check whether a process is alive by sending signal 0.\n *\n * Treats `ESRCH` as \"process is gone\", `EPERM` as \"process exists but we\n * cannot signal it\" (still alive from our perspective), and rethrows\n * anything else so the caller can surface unexpected failures rather than\n * silently assuming the process is dead.\n *\n * @param pid - The process ID to check.\n * @returns True if the process exists.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ESRCH')) {\n return false;\n }\n if (isErrorWithCode(error, 'EPERM')) {\n return true;\n }\n throw error;\n }\n}\n\n/**\n * Send a signal to a process. Returns true if the signal was sent, false if\n * the process does not exist (ESRCH). Re-throws on permission errors and\n * other failures.\n *\n * @param pid - The process ID.\n * @param signal - The signal to send.\n * @returns True if the signal was delivered, false if the process is gone.\n */\nexport function sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal);\n return true;\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ESRCH')) {\n return false;\n }\n throw error;\n }\n}\n\n/**\n * Poll until a condition is met or the timeout elapses.\n *\n * @param check - A function that returns true when the condition is met.\n * @param timeoutMs - Maximum time to wait in milliseconds.\n * @returns True if the condition was met, false on timeout.\n */\nexport async function waitFor(\n check: () => boolean | Promise<boolean>,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await check()) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n return false;\n}\n"]}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EAAE,OAAO,CAAC,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAbD,wCAaC;AAED;;;;;;;;GAQG;AACH,SAAgB,UAAU,CAAC,GAAW,EAAE,MAAsB;IAC5D,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC1B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;YACpC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAVD,gCAUC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,OAAO,CAC3B,KAAuC,EACvC,SAAiB;IAEjB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;IACxC,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,EAAE,CAAC;QAC7B,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC3D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAZD,0BAYC","sourcesContent":["import { isErrorWithCode as hasErrorCode } from '@metamask/utils';\nimport { readFile } from 'node:fs/promises';\n\n/**\n * Check whether an unknown error is a Node.js system error with the given code.\n *\n * @param error - The error to check.\n * @param code - The expected error code (e.g. 'ENOENT', 'EPERM').\n * @returns True if the error matches the code.\n */\nexport function isErrorWithCode(error: unknown, code: string): boolean {\n return hasErrorCode(error) && error.code === code;\n}\n\n/**\n * Read a PID from a file. The file may contain just the PID, or the PID on\n * the first line followed by additional metadata (e.g. start time written by\n * the daemon).\n *\n * @param pidPath - The PID file path.\n * @returns The PID, or undefined if the file is missing or its first line is\n * not a positive integer.\n */\nexport async function readPidFile(\n pidPath: string,\n): Promise<number | undefined> {\n let contents: string;\n try {\n contents = await readFile(pidPath, 'utf-8');\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ENOENT')) {\n return undefined;\n }\n throw error;\n }\n // String.prototype.split always returns at least one element, so [0] is safe.\n const pid = Number(contents.split('\\n')[0].trim());\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n}\n\n/**\n * Check whether a process is alive by sending signal 0.\n *\n * Treats `ESRCH` as \"process is gone\", `EPERM` as \"process exists but we\n * cannot signal it\" (still alive from our perspective), and rethrows\n * anything else so the caller can surface unexpected failures rather than\n * silently assuming the process is dead.\n *\n * @param pid - The process ID to check.\n * @returns True if the process exists.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ESRCH')) {\n return false;\n }\n if (isErrorWithCode(error, 'EPERM')) {\n return true;\n }\n throw error;\n }\n}\n\n/**\n * Send a signal to a process. Returns true if the signal was sent, false if\n * the process does not exist (ESRCH). Re-throws on permission errors and\n * other failures.\n *\n * @param pid - The process ID.\n * @param signal - The signal to send.\n * @returns True if the signal was delivered, false if the process is gone.\n */\nexport function sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal);\n return true;\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ESRCH')) {\n return false;\n }\n throw error;\n }\n}\n\n/**\n * Poll until a condition is met or the timeout elapses.\n *\n * @param check - A function that returns true when the condition is met.\n * @param timeoutMs - Maximum time to wait in milliseconds.\n * @returns True if the condition was met, false on timeout.\n */\nexport async function waitFor(\n check: () => boolean | Promise<boolean>,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await check()) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n return false;\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  /// <reference types="node" />
2
- import type { JsonRpcError } from "@metamask/utils";
3
2
  /**
4
3
  * Check whether an unknown error is a Node.js system error with the given code.
5
4
  *
@@ -8,33 +7,6 @@ import type { JsonRpcError } from "@metamask/utils";
8
7
  * @returns True if the error matches the code.
9
8
  */
10
9
  export declare function isErrorWithCode(error: unknown, code: string): boolean;
11
- /**
12
- * Turn an error thrown while contacting the daemon socket into a user-facing
13
- * message for `Command.error`, so every command reports the same failure the
14
- * same way. Distinguishes a stopped daemon (`ENOENT`/`ECONNREFUSED`), a
15
- * connection dropped mid-request (`ECONNRESET`), and a permission problem
16
- * (`EACCES`/`EPERM`), falling back to the raw error message.
17
- *
18
- * @param error - The value thrown while contacting the daemon.
19
- * @returns A human-readable explanation of the failure.
20
- */
21
- export declare function makeDaemonConnectionError(error: unknown): string;
22
- /**
23
- * Format the error of a JSON-RPC failure response into a user-facing message
24
- * for `Command.error`, so every command reports RPC failures the same way.
25
- *
26
- * @param error - The `error` field of a JSON-RPC failure response.
27
- * @returns The error message annotated with its numeric code.
28
- */
29
- export declare function formatJsonRpcError(error: JsonRpcError): string;
30
- /**
31
- * Check whether a value is an array of strings. Used to validate untyped RPC
32
- * results (e.g. the daemon's `listActions`) before treating them as `string[]`.
33
- *
34
- * @param value - The value to check.
35
- * @returns True if the value is an array whose every element is a string.
36
- */
37
- export declare function isStringArray(value: unknown): value is string[];
38
10
  /**
39
11
  * Read a PID from a file. The file may contain just the PID, or the PID on
40
12
  * the first line followed by additional metadata (e.g. start time written by
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/daemon/utils.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,wBAAwB;AAIpD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,C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