| 1 | const { spawn: spawnChild } = require("child_process"); |
| 2 | const os = require("os"); |
| 3 | const { getBinaryPath, installFailureHint } = require("./install"); |
| 4 | const { openHarmonyDirections } = require("./artifacts"); |
| 5 | |
| 6 | const pkg = require("../package.json"); |
| 7 | |
| 8 | function isVersionFlag(args = process.argv.slice(2)) { |
| 9 | return args.includes("--version") || args.includes("-V"); |
| 10 | } |
| 11 | |
| 12 | const OPEN_HARMONY_EXEC_ERRORS = ["ENOEXEC", "EACCES", "EPERM"]; |
| 13 | const OPEN_HARMONY_STARTUP_SIGNALS = ["SIGKILL", "SIGSYS", "SIGSEGV", "SIGBUS", "SIGILL", "SIGABRT"]; |
| 14 | const OPEN_HARMONY_STARTUP_MS = 5_000; |
| 15 | |
| 16 | // Print the install hint (mirror / release-base guidance) for a failure that |
| 17 | // looks like a download problem, or the HarmonyOS directions when the Linux |
| 18 | // build cannot be executed on native HarmonyOS. Prints nothing otherwise. |
| 19 | function printInstallFailureHint(error, log = console.error) { |
| 20 | if (os.platform() === "openharmony" && OPEN_HARMONY_EXEC_ERRORS.includes(error && error.code)) { |
| 21 | log(`The Linux build could not start on native HarmonyOS/OpenHarmony.\n${openHarmonyDirections()}`); |
| 22 | return; |
| 23 | } |
| 24 | const hint = installFailureHint(error); |
| 25 | if (hint) { |
| 26 | log(hint); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // Shared by the `codewhale` and `codew` bin shims: the error and, when the |
| 31 | // binary could not be downloaded, the hint that says what to do about it. |
| 32 | function reportStartFailure(binaryName, error, log = console.error) { |
| 33 | log(`Failed to start ${binaryName}:`, error && error.message ? error.message : String(error)); |
| 34 | printInstallFailureHint(error, log); |
| 35 | } |
| 36 | |
| 37 | // `--version` must still answer when the native binary is missing, but it |
| 38 | // must not report a binary version that is not actually installed: the |
| 39 | // expected version goes to stdout labelled as such, the failure to stderr. |
| 40 | function printVersionFallback(binaryName, error) { |
| 41 | const binVersion = |
| 42 | process.env.CODEWHALE_VERSION || |
| 43 | process.env.DEEPSEEK_TUI_VERSION || |
| 44 | process.env.DEEPSEEK_VERSION || |
| 45 | pkg.codewhaleBinaryVersion || pkg.deepseekBinaryVersion || pkg.version; |
| 46 | console.log(`${binaryName} (npm wrapper) v${pkg.version}`); |
| 47 | console.log(`binary: not installed (expected v${binVersion})`); |
| 48 | console.log(`repo: ${pkg.repository?.url || "N/A"}`); |
| 49 | if (error) { |
| 50 | console.error(`${binaryName}: native binary unavailable: ${error.message || String(error)}`); |
| 51 | printInstallFailureHint(error); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Signals that end the wrapper must end the native binary too. With a |
| 56 | // blocking spawn the wrapper died on SIGTERM and left the child running (still |
| 57 | // executing tools, still holding its port); as PID 1 in a container it ignored |
| 58 | // SIGTERM entirely. So SIGTERM, which a terminal never sends, is forwarded. |
| 59 | // |
| 60 | // SIGINT (Ctrl-C) and SIGHUP (terminal hangup) come from the terminal, which |
| 61 | // delivers them to the whole foreground process group, native child included. |
| 62 | // Forwarding them would deliver each one twice, and the native binary treats a |
| 63 | // second signal as "skip the graceful drain". On Windows `child.kill()` is a |
| 64 | // hard TerminateProcess, which would race the child's own Ctrl-C cleanup. The |
| 65 | // wrapper only has to outlive them, then mirror how the child ended. |
| 66 | const FORWARDED_SIGNALS = process.platform === "win32" ? [] : ["SIGTERM"]; |
| 67 | const OUTLIVED_SIGNALS = ["SIGINT", "SIGHUP"]; |
| 68 | |
| 69 | function ignoreSignal() {} |
| 70 | |
| 71 | // Run the native binary and settle with how it ended. While it runs, the |
| 72 | // forwarded signals go to the child and the outlived ones do not kill the |
| 73 | // wrapper. |
| 74 | function runChild(spawn, binaryPath, args, proc) { |
| 75 | return new Promise((resolve) => { |
| 76 | let child; |
| 77 | try { |
| 78 | child = spawn(binaryPath, args, { stdio: "inherit" }); |
| 79 | } catch (error) { |
| 80 | resolve({ error }); |
| 81 | return; |
| 82 | } |
| 83 | const listeners = [ |
| 84 | ...FORWARDED_SIGNALS.map((signal) => [ |
| 85 | signal, |
| 86 | () => { |
| 87 | try { |
| 88 | child.kill(signal); |
| 89 | } catch { |
| 90 | // The child already exited; its exit event settles the run. |
| 91 | } |
| 92 | }, |
| 93 | ]), |
| 94 | ...OUTLIVED_SIGNALS.map((signal) => [signal, ignoreSignal]), |
| 95 | ]; |
| 96 | for (const [signal, listener] of listeners) { |
| 97 | proc.on(signal, listener); |
| 98 | } |
| 99 | let settled = false; |
| 100 | const settle = (result) => { |
| 101 | if (settled) return; |
| 102 | settled = true; |
| 103 | for (const [signal, listener] of listeners) { |
| 104 | proc.removeListener(signal, listener); |
| 105 | } |
| 106 | resolve(result); |
| 107 | }; |
| 108 | child.once("error", (error) => settle({ error })); |
| 109 | child.once("exit", (status, signal) => settle({ status, signal })); |
| 110 | }); |
| 111 | } |
| 112 | |
| 113 | // Mirror a signal death to the parent shell: re-raise it on the wrapper once |
| 114 | // our listeners are gone, and fall back to the conventional 128 + n. |
| 115 | function exitLikeChild(result, exit, proc) { |
| 116 | if (result.signal) { |
| 117 | try { |
| 118 | proc.kill(proc.pid, result.signal); |
| 119 | } catch { |
| 120 | // fall through to the numeric status |
| 121 | } |
| 122 | const number = os.constants.signals[result.signal]; |
| 123 | return exit(number ? 128 + number : 1); |
| 124 | } |
| 125 | return exit(result.status ?? 1); |
| 126 | } |
| 127 | |
| 128 | async function run(binaryName, options = {}) { |
| 129 | const args = options.args || process.argv.slice(2); |
| 130 | const resolveBinaryPath = options.getBinaryPath || getBinaryPath; |
| 131 | const spawn = options.spawn || spawnChild; |
| 132 | const exit = options.exit || process.exit; |
| 133 | const proc = options.process || process; |
| 134 | const versionFlag = isVersionFlag(args); |
| 135 | |
| 136 | let binaryPath; |
| 137 | try { |
| 138 | binaryPath = await resolveBinaryPath(binaryName); |
| 139 | } catch (error) { |
| 140 | if (versionFlag) { |
| 141 | printVersionFallback(binaryName, error); |
| 142 | return exit(0); |
| 143 | } |
| 144 | throw error; |
| 145 | } |
| 146 | |
| 147 | const startedAt = Date.now(); |
| 148 | const result = await runChild(spawn, binaryPath, args, proc); |
| 149 | if (result.error) { |
| 150 | if (versionFlag) { |
| 151 | printVersionFallback(binaryName, result.error); |
| 152 | return exit(0); |
| 153 | } |
| 154 | throw result.error; |
| 155 | } |
| 156 | if ( |
| 157 | os.platform() === "openharmony" && |
| 158 | OPEN_HARMONY_STARTUP_SIGNALS.includes(result.signal) && |
| 159 | Date.now() - startedAt < OPEN_HARMONY_STARTUP_MS |
| 160 | ) { |
| 161 | console.error( |
| 162 | `${binaryName} stopped with ${result.signal} at startup; the Linux build may not run on native HarmonyOS/OpenHarmony.\n` + |
| 163 | openHarmonyDirections(), |
| 164 | ); |
| 165 | } |
| 166 | return exitLikeChild(result, exit, proc); |
| 167 | } |
| 168 | |
| 169 | async function runCodeWhale() { |
| 170 | await run("codewhale"); |
| 171 | } |
| 172 | |
| 173 | async function runCodeWhaleTui() { |
| 174 | // v0.9.5 single-binary: tui is now an alias to codewhale (kept for backwards compat, will warn) |
| 175 | if (!process.env.CODEWHALE_SUPPRESS_TUI_DEPRECATION) { |
| 176 | process.stderr.write("codewhale-tui: deprecated alias to `codewhale` (single binary since v0.9.5). Use `codewhale` instead.\n"); |
| 177 | } |
| 178 | await run("codewhale"); |
| 179 | } |
| 180 | |
| 181 | module.exports = { |
| 182 | run, |
| 183 | runCodeWhale, |
| 184 | runCodeWhaleTui, |
| 185 | reportStartFailure, |
| 186 | _internal: { isVersionFlag, printVersionFallback, FORWARDED_SIGNALS, OUTLIVED_SIGNALS }, |
| 187 | }; |
| 188 | |
| 189 | if (require.main === module) { |
| 190 | const command = process.argv[1] || ""; |
| 191 | if (command.includes("tui")) { |
| 192 | runCodeWhaleTui().catch((error) => { |
| 193 | reportStartFailure("codewhale", error); |
| 194 | process.exit(1); |
| 195 | }); |
| 196 | } else { |
| 197 | runCodeWhale().catch((error) => { |
| 198 | reportStartFailure("codewhale", error); |
| 199 | process.exit(1); |
| 200 | }); |
| 201 | } |
| 202 | } |
| 203 |