cli.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. 'use strict';
  2. const { spawn, execFile, execFileSync } = require('node:child_process');
  3. const fs = require('node:fs');
  4. const path = require('node:path');
  5. /**
  6. * Locate the bundled luatos-cli binary.
  7. *
  8. * Priority:
  9. * 1. LUATOS_CLI env var (absolute path)
  10. * 2. packaged app: Contents/Resources/bin/luatos-cli
  11. * 3. dev: <project>/resources/bin/luatos-cli
  12. * 4. PATH
  13. */
  14. function resolveCliPath(app) {
  15. const exe = process.platform === 'win32' ? 'luatos-cli.exe' : 'luatos-cli';
  16. const candidates = [];
  17. if (process.env.LUATOS_CLI) {
  18. candidates.push(process.env.LUATOS_CLI);
  19. }
  20. if (app && app.isPackaged) {
  21. candidates.push(path.join(process.resourcesPath, 'bin', exe));
  22. // Windows packages may keep the binary under bin/ as well.
  23. candidates.push(path.join(process.resourcesPath, 'bin', 'luatos-cli.exe'));
  24. }
  25. if (app) {
  26. const root = app.getAppPath();
  27. candidates.push(path.join(root, 'resources', 'bin', exe));
  28. candidates.push(path.join(root, 'resources', 'win', 'luatos-cli.exe'));
  29. candidates.push(path.join(root, 'resources', 'bin', 'luatos-cli.exe'));
  30. }
  31. candidates.push(path.join(__dirname, '..', 'resources', 'bin', exe));
  32. candidates.push(path.join(__dirname, '..', 'resources', 'win', 'luatos-cli.exe'));
  33. for (const candidate of candidates) {
  34. try {
  35. if (candidate && fs.statSync(candidate).isFile()) {
  36. return candidate;
  37. }
  38. } catch {
  39. // ignore
  40. }
  41. }
  42. // Fall back to PATH lookup. We cannot resolve it here, but spawning the bare
  43. // name lets the OS decide; report it as "found" so the UI can still try.
  44. return exe;
  45. }
  46. const preparedBinaries = new Set();
  47. function ensureExecutable(binPath) {
  48. if (process.platform === 'win32') return;
  49. try {
  50. fs.chmodSync(binPath, 0o755);
  51. } catch {
  52. // best effort; the app may still run if the mode is already correct
  53. }
  54. if (process.platform !== 'darwin' || preparedBinaries.has(binPath)) return;
  55. preparedBinaries.add(binPath);
  56. // A binary downloaded with a browser can carry the quarantine attribute.
  57. // The sidecar is part of the app; clearing it here avoids a confusing
  58. // "developer cannot be verified" failure on first flash.
  59. try {
  60. execFileSync('xattr', ['-d', 'com.apple.quarantine', binPath], { stdio: 'ignore' });
  61. } catch {
  62. // attribute absent or xattr unavailable
  63. }
  64. // If the release binary is unsigned, ad-hoc sign it so macOS can exec it.
  65. try {
  66. execFileSync('codesign', ['--verify', binPath], { stdio: 'ignore' });
  67. } catch {
  68. try {
  69. execFileSync('codesign', ['--force', '--sign', '-', binPath], { stdio: 'ignore' });
  70. } catch {
  71. // last resort: leave as-is
  72. }
  73. }
  74. }
  75. function runJson(binPath, args, options = {}) {
  76. const timeoutMs = options.timeoutMs ?? 20000;
  77. return new Promise((resolve, reject) => {
  78. ensureExecutable(binPath);
  79. const child = spawn(binPath, args, {
  80. cwd: options.cwd,
  81. windowsHide: true,
  82. env: { ...process.env, NO_COLOR: '1' },
  83. });
  84. let stdout = '';
  85. let stderr = '';
  86. let settled = false;
  87. const timer = setTimeout(() => {
  88. if (settled) return;
  89. settled = true;
  90. try {
  91. killProcessTree(child);
  92. } catch {
  93. // ignore
  94. }
  95. reject(new Error(`命令超时(${Math.round(timeoutMs / 1000)}s):${args.join(' ')}`));
  96. }, timeoutMs);
  97. child.stdout.setEncoding('utf8');
  98. child.stderr.setEncoding('utf8');
  99. child.stdout.on('data', (chunk) => {
  100. stdout += chunk;
  101. });
  102. child.stderr.on('data', (chunk) => {
  103. stderr += chunk;
  104. });
  105. child.on('error', (error) => {
  106. if (settled) return;
  107. settled = true;
  108. clearTimeout(timer);
  109. reject(new Error(`无法启动 luatos-cli:${error.message}\n路径:${binPath}`));
  110. });
  111. child.on('close', (code) => {
  112. if (settled) return;
  113. settled = true;
  114. clearTimeout(timer);
  115. if (code !== 0) {
  116. const detail = (stderr || stdout).trim();
  117. reject(new Error(detail || `luatos-cli 退出码 ${code}`));
  118. return;
  119. }
  120. try {
  121. resolve(JSON.parse(stdout));
  122. } catch (error) {
  123. reject(new Error(`无法解析 luatos-cli JSON 输出:${error.message}\n${stdout.slice(0, 800)}`));
  124. }
  125. });
  126. });
  127. }
  128. function runText(binPath, args, options = {}) {
  129. const timeoutMs = options.timeoutMs ?? 10000;
  130. return new Promise((resolve, reject) => {
  131. ensureExecutable(binPath);
  132. const child = spawn(binPath, args, {
  133. cwd: options.cwd,
  134. windowsHide: true,
  135. env: { ...process.env, NO_COLOR: '1' },
  136. });
  137. let stdout = '';
  138. let stderr = '';
  139. let settled = false;
  140. const timer = setTimeout(() => {
  141. if (settled) return;
  142. settled = true;
  143. killProcessTree(child);
  144. reject(new Error(`命令超时:${args.join(' ')}`));
  145. }, timeoutMs);
  146. child.stdout.setEncoding('utf8');
  147. child.stderr.setEncoding('utf8');
  148. child.stdout.on('data', (chunk) => { stdout += chunk; });
  149. child.stderr.on('data', (chunk) => { stderr += chunk; });
  150. child.on('error', (error) => {
  151. if (settled) return;
  152. settled = true;
  153. clearTimeout(timer);
  154. reject(new Error(`无法启动 luatos-cli:${error.message}`));
  155. });
  156. child.on('close', (code) => {
  157. if (settled) return;
  158. settled = true;
  159. clearTimeout(timer);
  160. if (code !== 0) {
  161. reject(new Error((stderr || stdout).trim() || `luatos-cli 退出码 ${code}`));
  162. return;
  163. }
  164. resolve((stdout || stderr).trim());
  165. });
  166. });
  167. }
  168. function runJsonl(binPath, args, handlers = {}, options = {}) {
  169. ensureExecutable(binPath);
  170. return new Promise((resolve, reject) => {
  171. const child = spawn(binPath, args, {
  172. cwd: options.cwd,
  173. windowsHide: true,
  174. env: { ...process.env, NO_COLOR: '1' },
  175. });
  176. let stdoutBuffer = '';
  177. let stderrBuffer = '';
  178. let settled = false;
  179. child.stdout.setEncoding('utf8');
  180. child.stderr.setEncoding('utf8');
  181. const emitLine = (line, source) => {
  182. const trimmed = line.trim();
  183. if (!trimmed) return;
  184. if (source === 'stdout' && trimmed.startsWith('{')) {
  185. try {
  186. const event = JSON.parse(trimmed);
  187. handlers.onEvent?.(event);
  188. return;
  189. } catch {
  190. // Not valid JSON: fall through to a plain log line.
  191. }
  192. }
  193. // Non-JSON output is still useful: tool notices, progress bars from
  194. // vendor stubs, stdout banners, etc.
  195. handlers.onLine?.(trimmed, source);
  196. };
  197. const feed = (chunk, source) => {
  198. if (source === 'stdout') {
  199. stdoutBuffer += chunk;
  200. let index;
  201. while ((index = stdoutBuffer.indexOf('\n')) >= 0) {
  202. const line = stdoutBuffer.slice(0, index);
  203. stdoutBuffer = stdoutBuffer.slice(index + 1);
  204. emitLine(line, source);
  205. }
  206. } else {
  207. stderrBuffer += chunk;
  208. let index;
  209. while ((index = stderrBuffer.indexOf('\n')) >= 0) {
  210. const line = stderrBuffer.slice(0, index);
  211. stderrBuffer = stderrBuffer.slice(index + 1);
  212. emitLine(line, source);
  213. }
  214. }
  215. };
  216. child.stdout.on('data', (chunk) => feed(chunk, 'stdout'));
  217. child.stderr.on('data', (chunk) => feed(chunk, 'stderr'));
  218. const finish = (code, signal, error) => {
  219. if (settled) return;
  220. settled = true;
  221. if (stdoutBuffer.trim()) emitLine(stdoutBuffer, 'stdout');
  222. if (stderrBuffer.trim()) emitLine(stderrBuffer, 'stderr');
  223. if (error) {
  224. reject(error);
  225. return;
  226. }
  227. handlers.onExit?.({ code, signal });
  228. resolve({ code, signal });
  229. };
  230. child.on('error', (error) => {
  231. finish(null, null, new Error(`无法启动 luatos-cli:${error.message}\n路径:${binPath}`));
  232. });
  233. child.on('close', (code, signal) => {
  234. finish(code, signal, null);
  235. });
  236. if (options.onChild) {
  237. options.onChild(child);
  238. }
  239. });
  240. }
  241. function killProcessTree(child) {
  242. if (!child || child.killed) return;
  243. if (process.platform === 'win32') {
  244. // `child.kill()` does not reliably kill descendants on Windows.
  245. execFile('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }, () => {});
  246. return;
  247. }
  248. try {
  249. child.kill('SIGINT');
  250. } catch {
  251. // ignore
  252. }
  253. setTimeout(() => {
  254. try {
  255. if (!child.killed) child.kill('SIGKILL');
  256. } catch {
  257. // ignore
  258. }
  259. }, 2500).unref?.();
  260. }
  261. module.exports = {
  262. resolveCliPath,
  263. ensureExecutable,
  264. runJson,
  265. runText,
  266. runJsonl,
  267. killProcessTree,
  268. };