版博士V2.0程序
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

2139 rindas
51 KiB

  1. import { Buffer as Buffer$1 } from 'node:buffer';
  2. import path$3 from 'node:path';
  3. import childProcess from 'node:child_process';
  4. import process$2 from 'node:process';
  5. import require$$0$1 from 'child_process';
  6. import k from 'path';
  7. import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js';
  8. import require$$0 from 'fs';
  9. import url from 'node:url';
  10. import os, { constants } from 'node:os';
  11. import require$$0$2 from 'assert';
  12. import require$$2 from 'events';
  13. import require$$0$5 from 'buffer';
  14. import require$$0$3 from 'stream';
  15. import require$$0$4 from 'util';
  16. var crossSpawn = {exports: {}};
  17. var windows;
  18. var hasRequiredWindows;
  19. function requireWindows () {
  20. if (hasRequiredWindows) return windows;
  21. hasRequiredWindows = 1;
  22. windows = isexe;
  23. isexe.sync = sync;
  24. var fs = require$$0;
  25. function checkPathExt (path, options) {
  26. var pathext = options.pathExt !== undefined ?
  27. options.pathExt : process.env.PATHEXT;
  28. if (!pathext) {
  29. return true
  30. }
  31. pathext = pathext.split(';');
  32. if (pathext.indexOf('') !== -1) {
  33. return true
  34. }
  35. for (var i = 0; i < pathext.length; i++) {
  36. var p = pathext[i].toLowerCase();
  37. if (p && path.substr(-p.length).toLowerCase() === p) {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. function checkStat (stat, path, options) {
  44. if (!stat.isSymbolicLink() && !stat.isFile()) {
  45. return false
  46. }
  47. return checkPathExt(path, options)
  48. }
  49. function isexe (path, options, cb) {
  50. fs.stat(path, function (er, stat) {
  51. cb(er, er ? false : checkStat(stat, path, options));
  52. });
  53. }
  54. function sync (path, options) {
  55. return checkStat(fs.statSync(path), path, options)
  56. }
  57. return windows;
  58. }
  59. var mode;
  60. var hasRequiredMode;
  61. function requireMode () {
  62. if (hasRequiredMode) return mode;
  63. hasRequiredMode = 1;
  64. mode = isexe;
  65. isexe.sync = sync;
  66. var fs = require$$0;
  67. function isexe (path, options, cb) {
  68. fs.stat(path, function (er, stat) {
  69. cb(er, er ? false : checkStat(stat, options));
  70. });
  71. }
  72. function sync (path, options) {
  73. return checkStat(fs.statSync(path), options)
  74. }
  75. function checkStat (stat, options) {
  76. return stat.isFile() && checkMode(stat, options)
  77. }
  78. function checkMode (stat, options) {
  79. var mod = stat.mode;
  80. var uid = stat.uid;
  81. var gid = stat.gid;
  82. var myUid = options.uid !== undefined ?
  83. options.uid : process.getuid && process.getuid();
  84. var myGid = options.gid !== undefined ?
  85. options.gid : process.getgid && process.getgid();
  86. var u = parseInt('100', 8);
  87. var g = parseInt('010', 8);
  88. var o = parseInt('001', 8);
  89. var ug = u | g;
  90. var ret = (mod & o) ||
  91. (mod & g) && gid === myGid ||
  92. (mod & u) && uid === myUid ||
  93. (mod & ug) && myUid === 0;
  94. return ret
  95. }
  96. return mode;
  97. }
  98. var core;
  99. if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
  100. core = requireWindows();
  101. } else {
  102. core = requireMode();
  103. }
  104. var isexe_1 = isexe$1;
  105. isexe$1.sync = sync;
  106. function isexe$1 (path, options, cb) {
  107. if (typeof options === 'function') {
  108. cb = options;
  109. options = {};
  110. }
  111. if (!cb) {
  112. if (typeof Promise !== 'function') {
  113. throw new TypeError('callback not provided')
  114. }
  115. return new Promise(function (resolve, reject) {
  116. isexe$1(path, options || {}, function (er, is) {
  117. if (er) {
  118. reject(er);
  119. } else {
  120. resolve(is);
  121. }
  122. });
  123. })
  124. }
  125. core(path, options || {}, function (er, is) {
  126. // ignore EACCES because that just means we aren't allowed to run it
  127. if (er) {
  128. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  129. er = null;
  130. is = false;
  131. }
  132. }
  133. cb(er, is);
  134. });
  135. }
  136. function sync (path, options) {
  137. // my kingdom for a filtered catch
  138. try {
  139. return core.sync(path, options || {})
  140. } catch (er) {
  141. if (options && options.ignoreErrors || er.code === 'EACCES') {
  142. return false
  143. } else {
  144. throw er
  145. }
  146. }
  147. }
  148. const isWindows = process.platform === 'win32' ||
  149. process.env.OSTYPE === 'cygwin' ||
  150. process.env.OSTYPE === 'msys';
  151. const path$2 = k;
  152. const COLON = isWindows ? ';' : ':';
  153. const isexe = isexe_1;
  154. const getNotFoundError = (cmd) =>
  155. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
  156. const getPathInfo = (cmd, opt) => {
  157. const colon = opt.colon || COLON;
  158. // If it has a slash, then we don't bother searching the pathenv.
  159. // just check the file itself, and that's it.
  160. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  161. : (
  162. [
  163. // windows always checks the cwd first
  164. ...(isWindows ? [process.cwd()] : []),
  165. ...(opt.path || process.env.PATH ||
  166. /* istanbul ignore next: very unusual */ '').split(colon),
  167. ]
  168. );
  169. const pathExtExe = isWindows
  170. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  171. : '';
  172. const pathExt = isWindows ? pathExtExe.split(colon) : [''];
  173. if (isWindows) {
  174. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  175. pathExt.unshift('');
  176. }
  177. return {
  178. pathEnv,
  179. pathExt,
  180. pathExtExe,
  181. }
  182. };
  183. const which$1 = (cmd, opt, cb) => {
  184. if (typeof opt === 'function') {
  185. cb = opt;
  186. opt = {};
  187. }
  188. if (!opt)
  189. opt = {};
  190. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  191. const found = [];
  192. const step = i => new Promise((resolve, reject) => {
  193. if (i === pathEnv.length)
  194. return opt.all && found.length ? resolve(found)
  195. : reject(getNotFoundError(cmd))
  196. const ppRaw = pathEnv[i];
  197. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  198. const pCmd = path$2.join(pathPart, cmd);
  199. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  200. : pCmd;
  201. resolve(subStep(p, i, 0));
  202. });
  203. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  204. if (ii === pathExt.length)
  205. return resolve(step(i + 1))
  206. const ext = pathExt[ii];
  207. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  208. if (!er && is) {
  209. if (opt.all)
  210. found.push(p + ext);
  211. else
  212. return resolve(p + ext)
  213. }
  214. return resolve(subStep(p, i, ii + 1))
  215. });
  216. });
  217. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  218. };
  219. const whichSync = (cmd, opt) => {
  220. opt = opt || {};
  221. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  222. const found = [];
  223. for (let i = 0; i < pathEnv.length; i ++) {
  224. const ppRaw = pathEnv[i];
  225. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  226. const pCmd = path$2.join(pathPart, cmd);
  227. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  228. : pCmd;
  229. for (let j = 0; j < pathExt.length; j ++) {
  230. const cur = p + pathExt[j];
  231. try {
  232. const is = isexe.sync(cur, { pathExt: pathExtExe });
  233. if (is) {
  234. if (opt.all)
  235. found.push(cur);
  236. else
  237. return cur
  238. }
  239. } catch (ex) {}
  240. }
  241. }
  242. if (opt.all && found.length)
  243. return found
  244. if (opt.nothrow)
  245. return null
  246. throw getNotFoundError(cmd)
  247. };
  248. var which_1 = which$1;
  249. which$1.sync = whichSync;
  250. var pathKey$2 = {exports: {}};
  251. const pathKey$1 = (options = {}) => {
  252. const environment = options.env || process.env;
  253. const platform = options.platform || process.platform;
  254. if (platform !== 'win32') {
  255. return 'PATH';
  256. }
  257. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  258. };
  259. pathKey$2.exports = pathKey$1;
  260. // TODO: Remove this for the next major release
  261. pathKey$2.exports.default = pathKey$1;
  262. const path$1 = k;
  263. const which = which_1;
  264. const getPathKey = pathKey$2.exports;
  265. function resolveCommandAttempt(parsed, withoutPathExt) {
  266. const env = parsed.options.env || process.env;
  267. const cwd = process.cwd();
  268. const hasCustomCwd = parsed.options.cwd != null;
  269. // Worker threads do not have process.chdir()
  270. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
  271. // If a custom `cwd` was specified, we need to change the process cwd
  272. // because `which` will do stat calls but does not support a custom cwd
  273. if (shouldSwitchCwd) {
  274. try {
  275. process.chdir(parsed.options.cwd);
  276. } catch (err) {
  277. /* Empty */
  278. }
  279. }
  280. let resolved;
  281. try {
  282. resolved = which.sync(parsed.command, {
  283. path: env[getPathKey({ env })],
  284. pathExt: withoutPathExt ? path$1.delimiter : undefined,
  285. });
  286. } catch (e) {
  287. /* Empty */
  288. } finally {
  289. if (shouldSwitchCwd) {
  290. process.chdir(cwd);
  291. }
  292. }
  293. // If we successfully resolved, ensure that an absolute path is returned
  294. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  295. if (resolved) {
  296. resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  297. }
  298. return resolved;
  299. }
  300. function resolveCommand$1(parsed) {
  301. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  302. }
  303. var resolveCommand_1 = resolveCommand$1;
  304. var _escape = {};
  305. // See http://www.robvanderwoude.com/escapechars.php
  306. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  307. function escapeCommand(arg) {
  308. // Escape meta chars
  309. arg = arg.replace(metaCharsRegExp, '^$1');
  310. return arg;
  311. }
  312. function escapeArgument(arg, doubleEscapeMetaChars) {
  313. // Convert to string
  314. arg = `${arg}`;
  315. // Algorithm below is based on https://qntm.org/cmd
  316. // Sequence of backslashes followed by a double quote:
  317. // double up all the backslashes and escape the double quote
  318. arg = arg.replace(/(\\*)"/g, '$1$1\\"');
  319. // Sequence of backslashes followed by the end of the string
  320. // (which will become a double quote later):
  321. // double up all the backslashes
  322. arg = arg.replace(/(\\*)$/, '$1$1');
  323. // All other backslashes occur literally
  324. // Quote the whole thing:
  325. arg = `"${arg}"`;
  326. // Escape meta chars
  327. arg = arg.replace(metaCharsRegExp, '^$1');
  328. // Double escape meta chars if necessary
  329. if (doubleEscapeMetaChars) {
  330. arg = arg.replace(metaCharsRegExp, '^$1');
  331. }
  332. return arg;
  333. }
  334. _escape.command = escapeCommand;
  335. _escape.argument = escapeArgument;
  336. var shebangRegex$1 = /^#!(.*)/;
  337. const shebangRegex = shebangRegex$1;
  338. var shebangCommand$1 = (string = '') => {
  339. const match = string.match(shebangRegex);
  340. if (!match) {
  341. return null;
  342. }
  343. const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
  344. const binary = path.split('/').pop();
  345. if (binary === 'env') {
  346. return argument;
  347. }
  348. return argument ? `${binary} ${argument}` : binary;
  349. };
  350. const fs = require$$0;
  351. const shebangCommand = shebangCommand$1;
  352. function readShebang$1(command) {
  353. // Read the first 150 bytes from the file
  354. const size = 150;
  355. const buffer = Buffer.alloc(size);
  356. let fd;
  357. try {
  358. fd = fs.openSync(command, 'r');
  359. fs.readSync(fd, buffer, 0, size, 0);
  360. fs.closeSync(fd);
  361. } catch (e) { /* Empty */ }
  362. // Attempt to extract shebang (null is returned if not a shebang)
  363. return shebangCommand(buffer.toString());
  364. }
  365. var readShebang_1 = readShebang$1;
  366. const path = k;
  367. const resolveCommand = resolveCommand_1;
  368. const escape = _escape;
  369. const readShebang = readShebang_1;
  370. const isWin$2 = process.platform === 'win32';
  371. const isExecutableRegExp = /\.(?:com|exe)$/i;
  372. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  373. function detectShebang(parsed) {
  374. parsed.file = resolveCommand(parsed);
  375. const shebang = parsed.file && readShebang(parsed.file);
  376. if (shebang) {
  377. parsed.args.unshift(parsed.file);
  378. parsed.command = shebang;
  379. return resolveCommand(parsed);
  380. }
  381. return parsed.file;
  382. }
  383. function parseNonShell(parsed) {
  384. if (!isWin$2) {
  385. return parsed;
  386. }
  387. // Detect & add support for shebangs
  388. const commandFile = detectShebang(parsed);
  389. // We don't need a shell if the command filename is an executable
  390. const needsShell = !isExecutableRegExp.test(commandFile);
  391. // If a shell is required, use cmd.exe and take care of escaping everything correctly
  392. // Note that `forceShell` is an hidden option used only in tests
  393. if (parsed.options.forceShell || needsShell) {
  394. // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
  395. // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
  396. // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
  397. // we need to double escape them
  398. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  399. // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
  400. // This is necessary otherwise it will always fail with ENOENT in those cases
  401. parsed.command = path.normalize(parsed.command);
  402. // Escape command & arguments
  403. parsed.command = escape.command(parsed.command);
  404. parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
  405. const shellCommand = [parsed.command].concat(parsed.args).join(' ');
  406. parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
  407. parsed.command = process.env.comspec || 'cmd.exe';
  408. parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
  409. }
  410. return parsed;
  411. }
  412. function parse$1(command, args, options) {
  413. // Normalize arguments, similar to nodejs
  414. if (args && !Array.isArray(args)) {
  415. options = args;
  416. args = null;
  417. }
  418. args = args ? args.slice(0) : []; // Clone array to avoid changing the original
  419. options = Object.assign({}, options); // Clone object to avoid changing the original
  420. // Build our parsed object
  421. const parsed = {
  422. command,
  423. args,
  424. options,
  425. file: undefined,
  426. original: {
  427. command,
  428. args,
  429. },
  430. };
  431. // Delegate further parsing to shell or non-shell
  432. return options.shell ? parsed : parseNonShell(parsed);
  433. }
  434. var parse_1 = parse$1;
  435. const isWin$1 = process.platform === 'win32';
  436. function notFoundError(original, syscall) {
  437. return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
  438. code: 'ENOENT',
  439. errno: 'ENOENT',
  440. syscall: `${syscall} ${original.command}`,
  441. path: original.command,
  442. spawnargs: original.args,
  443. });
  444. }
  445. function hookChildProcess(cp, parsed) {
  446. if (!isWin$1) {
  447. return;
  448. }
  449. const originalEmit = cp.emit;
  450. cp.emit = function (name, arg1) {
  451. // If emitting "exit" event and exit code is 1, we need to check if
  452. // the command exists and emit an "error" instead
  453. // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
  454. if (name === 'exit') {
  455. const err = verifyENOENT(arg1, parsed);
  456. if (err) {
  457. return originalEmit.call(cp, 'error', err);
  458. }
  459. }
  460. return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
  461. };
  462. }
  463. function verifyENOENT(status, parsed) {
  464. if (isWin$1 && status === 1 && !parsed.file) {
  465. return notFoundError(parsed.original, 'spawn');
  466. }
  467. return null;
  468. }
  469. function verifyENOENTSync(status, parsed) {
  470. if (isWin$1 && status === 1 && !parsed.file) {
  471. return notFoundError(parsed.original, 'spawnSync');
  472. }
  473. return null;
  474. }
  475. var enoent$1 = {
  476. hookChildProcess,
  477. verifyENOENT,
  478. verifyENOENTSync,
  479. notFoundError,
  480. };
  481. const cp = require$$0$1;
  482. const parse = parse_1;
  483. const enoent = enoent$1;
  484. function spawn(command, args, options) {
  485. // Parse the arguments
  486. const parsed = parse(command, args, options);
  487. // Spawn the child process
  488. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  489. // Hook into child process "exit" event to emit an error if the command
  490. // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  491. enoent.hookChildProcess(spawned, parsed);
  492. return spawned;
  493. }
  494. function spawnSync(command, args, options) {
  495. // Parse the arguments
  496. const parsed = parse(command, args, options);
  497. // Spawn the child process
  498. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  499. // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  500. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  501. return result;
  502. }
  503. crossSpawn.exports = spawn;
  504. crossSpawn.exports.spawn = spawn;
  505. crossSpawn.exports.sync = spawnSync;
  506. crossSpawn.exports._parse = parse;
  507. crossSpawn.exports._enoent = enoent;
  508. function stripFinalNewline(input) {
  509. const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
  510. const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();
  511. if (input[input.length - 1] === LF) {
  512. input = input.slice(0, -1);
  513. }
  514. if (input[input.length - 1] === CR) {
  515. input = input.slice(0, -1);
  516. }
  517. return input;
  518. }
  519. function pathKey(options = {}) {
  520. const {
  521. env = process.env,
  522. platform = process.platform
  523. } = options;
  524. if (platform !== 'win32') {
  525. return 'PATH';
  526. }
  527. return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  528. }
  529. function npmRunPath(options = {}) {
  530. const {
  531. cwd = process$2.cwd(),
  532. path: path_ = process$2.env[pathKey()],
  533. execPath = process$2.execPath,
  534. } = options;
  535. let previous;
  536. const cwdString = cwd instanceof URL ? url.fileURLToPath(cwd) : cwd;
  537. let cwdPath = path$3.resolve(cwdString);
  538. const result = [];
  539. while (previous !== cwdPath) {
  540. result.push(path$3.join(cwdPath, 'node_modules/.bin'));
  541. previous = cwdPath;
  542. cwdPath = path$3.resolve(cwdPath, '..');
  543. }
  544. // Ensure the running `node` binary is used.
  545. result.push(path$3.resolve(cwdString, execPath, '..'));
  546. return [...result, path_].join(path$3.delimiter);
  547. }
  548. function npmRunPathEnv({env = process$2.env, ...options} = {}) {
  549. env = {...env};
  550. const path = pathKey({env});
  551. options.path = env[path];
  552. env[path] = npmRunPath(options);
  553. return env;
  554. }
  555. const copyProperty = (to, from, property, ignoreNonConfigurable) => {
  556. // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
  557. // `Function#prototype` is non-writable and non-configurable so can never be modified.
  558. if (property === 'length' || property === 'prototype') {
  559. return;
  560. }
  561. // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
  562. if (property === 'arguments' || property === 'caller') {
  563. return;
  564. }
  565. const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
  566. const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
  567. if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
  568. return;
  569. }
  570. Object.defineProperty(to, property, fromDescriptor);
  571. };
  572. // `Object.defineProperty()` throws if the property exists, is not configurable and either:
  573. // - one its descriptors is changed
  574. // - it is non-writable and its value is changed
  575. const canCopyProperty = function (toDescriptor, fromDescriptor) {
  576. return toDescriptor === undefined || toDescriptor.configurable || (
  577. toDescriptor.writable === fromDescriptor.writable &&
  578. toDescriptor.enumerable === fromDescriptor.enumerable &&
  579. toDescriptor.configurable === fromDescriptor.configurable &&
  580. (toDescriptor.writable || toDescriptor.value === fromDescriptor.value)
  581. );
  582. };
  583. const changePrototype = (to, from) => {
  584. const fromPrototype = Object.getPrototypeOf(from);
  585. if (fromPrototype === Object.getPrototypeOf(to)) {
  586. return;
  587. }
  588. Object.setPrototypeOf(to, fromPrototype);
  589. };
  590. const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
  591. const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
  592. const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
  593. // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
  594. // We use `bind()` instead of a closure for the same reason.
  595. // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
  596. const changeToString = (to, from, name) => {
  597. const withName = name === '' ? '' : `with ${name.trim()}() `;
  598. const newToString = wrappedToString.bind(null, withName, from.toString());
  599. // Ensure `to.toString.toString` is non-enumerable and has the same `same`
  600. Object.defineProperty(newToString, 'name', toStringName);
  601. Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});
  602. };
  603. function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) {
  604. const {name} = to;
  605. for (const property of Reflect.ownKeys(from)) {
  606. copyProperty(to, from, property, ignoreNonConfigurable);
  607. }
  608. changePrototype(to, from);
  609. changeToString(to, from, name);
  610. return to;
  611. }
  612. const calledFunctions = new WeakMap();
  613. const onetime = (function_, options = {}) => {
  614. if (typeof function_ !== 'function') {
  615. throw new TypeError('Expected a function');
  616. }
  617. let returnValue;
  618. let callCount = 0;
  619. const functionName = function_.displayName || function_.name || '<anonymous>';
  620. const onetime = function (...arguments_) {
  621. calledFunctions.set(onetime, ++callCount);
  622. if (callCount === 1) {
  623. returnValue = function_.apply(this, arguments_);
  624. function_ = null;
  625. } else if (options.throw === true) {
  626. throw new Error(`Function \`${functionName}\` can only be called once`);
  627. }
  628. return returnValue;
  629. };
  630. mimicFunction(onetime, function_);
  631. calledFunctions.set(onetime, callCount);
  632. return onetime;
  633. };
  634. onetime.callCount = function_ => {
  635. if (!calledFunctions.has(function_)) {
  636. throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
  637. }
  638. return calledFunctions.get(function_);
  639. };
  640. const getRealtimeSignals=function(){
  641. const length=SIGRTMAX-SIGRTMIN+1;
  642. return Array.from({length},getRealtimeSignal);
  643. };
  644. const getRealtimeSignal=function(value,index){
  645. return {
  646. name:`SIGRT${index+1}`,
  647. number:SIGRTMIN+index,
  648. action:"terminate",
  649. description:"Application-specific signal (realtime)",
  650. standard:"posix"};
  651. };
  652. const SIGRTMIN=34;
  653. const SIGRTMAX=64;
  654. const SIGNALS=[
  655. {
  656. name:"SIGHUP",
  657. number:1,
  658. action:"terminate",
  659. description:"Terminal closed",
  660. standard:"posix"},
  661. {
  662. name:"SIGINT",
  663. number:2,
  664. action:"terminate",
  665. description:"User interruption with CTRL-C",
  666. standard:"ansi"},
  667. {
  668. name:"SIGQUIT",
  669. number:3,
  670. action:"core",
  671. description:"User interruption with CTRL-\\",
  672. standard:"posix"},
  673. {
  674. name:"SIGILL",
  675. number:4,
  676. action:"core",
  677. description:"Invalid machine instruction",
  678. standard:"ansi"},
  679. {
  680. name:"SIGTRAP",
  681. number:5,
  682. action:"core",
  683. description:"Debugger breakpoint",
  684. standard:"posix"},
  685. {
  686. name:"SIGABRT",
  687. number:6,
  688. action:"core",
  689. description:"Aborted",
  690. standard:"ansi"},
  691. {
  692. name:"SIGIOT",
  693. number:6,
  694. action:"core",
  695. description:"Aborted",
  696. standard:"bsd"},
  697. {
  698. name:"SIGBUS",
  699. number:7,
  700. action:"core",
  701. description:
  702. "Bus error due to misaligned, non-existing address or paging error",
  703. standard:"bsd"},
  704. {
  705. name:"SIGEMT",
  706. number:7,
  707. action:"terminate",
  708. description:"Command should be emulated but is not implemented",
  709. standard:"other"},
  710. {
  711. name:"SIGFPE",
  712. number:8,
  713. action:"core",
  714. description:"Floating point arithmetic error",
  715. standard:"ansi"},
  716. {
  717. name:"SIGKILL",
  718. number:9,
  719. action:"terminate",
  720. description:"Forced termination",
  721. standard:"posix",
  722. forced:true},
  723. {
  724. name:"SIGUSR1",
  725. number:10,
  726. action:"terminate",
  727. description:"Application-specific signal",
  728. standard:"posix"},
  729. {
  730. name:"SIGSEGV",
  731. number:11,
  732. action:"core",
  733. description:"Segmentation fault",
  734. standard:"ansi"},
  735. {
  736. name:"SIGUSR2",
  737. number:12,
  738. action:"terminate",
  739. description:"Application-specific signal",
  740. standard:"posix"},
  741. {
  742. name:"SIGPIPE",
  743. number:13,
  744. action:"terminate",
  745. description:"Broken pipe or socket",
  746. standard:"posix"},
  747. {
  748. name:"SIGALRM",
  749. number:14,
  750. action:"terminate",
  751. description:"Timeout or timer",
  752. standard:"posix"},
  753. {
  754. name:"SIGTERM",
  755. number:15,
  756. action:"terminate",
  757. description:"Termination",
  758. standard:"ansi"},
  759. {
  760. name:"SIGSTKFLT",
  761. number:16,
  762. action:"terminate",
  763. description:"Stack is empty or overflowed",
  764. standard:"other"},
  765. {
  766. name:"SIGCHLD",
  767. number:17,
  768. action:"ignore",
  769. description:"Child process terminated, paused or unpaused",
  770. standard:"posix"},
  771. {
  772. name:"SIGCLD",
  773. number:17,
  774. action:"ignore",
  775. description:"Child process terminated, paused or unpaused",
  776. standard:"other"},
  777. {
  778. name:"SIGCONT",
  779. number:18,
  780. action:"unpause",
  781. description:"Unpaused",
  782. standard:"posix",
  783. forced:true},
  784. {
  785. name:"SIGSTOP",
  786. number:19,
  787. action:"pause",
  788. description:"Paused",
  789. standard:"posix",
  790. forced:true},
  791. {
  792. name:"SIGTSTP",
  793. number:20,
  794. action:"pause",
  795. description:"Paused using CTRL-Z or \"suspend\"",
  796. standard:"posix"},
  797. {
  798. name:"SIGTTIN",
  799. number:21,
  800. action:"pause",
  801. description:"Background process cannot read terminal input",
  802. standard:"posix"},
  803. {
  804. name:"SIGBREAK",
  805. number:21,
  806. action:"terminate",
  807. description:"User interruption with CTRL-BREAK",
  808. standard:"other"},
  809. {
  810. name:"SIGTTOU",
  811. number:22,
  812. action:"pause",
  813. description:"Background process cannot write to terminal output",
  814. standard:"posix"},
  815. {
  816. name:"SIGURG",
  817. number:23,
  818. action:"ignore",
  819. description:"Socket received out-of-band data",
  820. standard:"bsd"},
  821. {
  822. name:"SIGXCPU",
  823. number:24,
  824. action:"core",
  825. description:"Process timed out",
  826. standard:"bsd"},
  827. {
  828. name:"SIGXFSZ",
  829. number:25,
  830. action:"core",
  831. description:"File too big",
  832. standard:"bsd"},
  833. {
  834. name:"SIGVTALRM",
  835. number:26,
  836. action:"terminate",
  837. description:"Timeout or timer",
  838. standard:"bsd"},
  839. {
  840. name:"SIGPROF",
  841. number:27,
  842. action:"terminate",
  843. description:"Timeout or timer",
  844. standard:"bsd"},
  845. {
  846. name:"SIGWINCH",
  847. number:28,
  848. action:"ignore",
  849. description:"Terminal window size changed",
  850. standard:"bsd"},
  851. {
  852. name:"SIGIO",
  853. number:29,
  854. action:"terminate",
  855. description:"I/O is available",
  856. standard:"other"},
  857. {
  858. name:"SIGPOLL",
  859. number:29,
  860. action:"terminate",
  861. description:"Watched event",
  862. standard:"other"},
  863. {
  864. name:"SIGINFO",
  865. number:29,
  866. action:"ignore",
  867. description:"Request for process information",
  868. standard:"other"},
  869. {
  870. name:"SIGPWR",
  871. number:30,
  872. action:"terminate",
  873. description:"Device running out of power",
  874. standard:"systemv"},
  875. {
  876. name:"SIGSYS",
  877. number:31,
  878. action:"core",
  879. description:"Invalid system call",
  880. standard:"other"},
  881. {
  882. name:"SIGUNUSED",
  883. number:31,
  884. action:"terminate",
  885. description:"Invalid system call",
  886. standard:"other"}];
  887. const getSignals=function(){
  888. const realtimeSignals=getRealtimeSignals();
  889. const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal);
  890. return signals;
  891. };
  892. const normalizeSignal=function({
  893. name,
  894. number:defaultNumber,
  895. description,
  896. action,
  897. forced=false,
  898. standard})
  899. {
  900. const{
  901. signals:{[name]:constantSignal}}=
  902. constants;
  903. const supported=constantSignal!==undefined;
  904. const number=supported?constantSignal:defaultNumber;
  905. return {name,number,description,supported,action,forced,standard};
  906. };
  907. const getSignalsByName=function(){
  908. const signals=getSignals();
  909. return Object.fromEntries(signals.map(getSignalByName));
  910. };
  911. const getSignalByName=function({
  912. name,
  913. number,
  914. description,
  915. supported,
  916. action,
  917. forced,
  918. standard})
  919. {
  920. return [
  921. name,
  922. {name,number,description,supported,action,forced,standard}];
  923. };
  924. const signalsByName=getSignalsByName();
  925. const getSignalsByNumber=function(){
  926. const signals=getSignals();
  927. const length=SIGRTMAX+1;
  928. const signalsA=Array.from({length},(value,number)=>
  929. getSignalByNumber(number,signals));
  930. return Object.assign({},...signalsA);
  931. };
  932. const getSignalByNumber=function(number,signals){
  933. const signal=findSignalByNumber(number,signals);
  934. if(signal===undefined){
  935. return {};
  936. }
  937. const{name,description,supported,action,forced,standard}=signal;
  938. return {
  939. [number]:{
  940. name,
  941. number,
  942. description,
  943. supported,
  944. action,
  945. forced,
  946. standard}};
  947. };
  948. const findSignalByNumber=function(number,signals){
  949. const signal=signals.find(({name})=>constants.signals[name]===number);
  950. if(signal!==undefined){
  951. return signal;
  952. }
  953. return signals.find((signalA)=>signalA.number===number);
  954. };
  955. getSignalsByNumber();
  956. const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
  957. if (timedOut) {
  958. return `timed out after ${timeout} milliseconds`;
  959. }
  960. if (isCanceled) {
  961. return 'was canceled';
  962. }
  963. if (errorCode !== undefined) {
  964. return `failed with ${errorCode}`;
  965. }
  966. if (signal !== undefined) {
  967. return `was killed with ${signal} (${signalDescription})`;
  968. }
  969. if (exitCode !== undefined) {
  970. return `failed with exit code ${exitCode}`;
  971. }
  972. return 'failed';
  973. };
  974. const makeError = ({
  975. stdout,
  976. stderr,
  977. all,
  978. error,
  979. signal,
  980. exitCode,
  981. command,
  982. escapedCommand,
  983. timedOut,
  984. isCanceled,
  985. killed,
  986. parsed: {options: {timeout}},
  987. }) => {
  988. // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
  989. // We normalize them to `undefined`
  990. exitCode = exitCode === null ? undefined : exitCode;
  991. signal = signal === null ? undefined : signal;
  992. const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
  993. const errorCode = error && error.code;
  994. const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
  995. const execaMessage = `Command ${prefix}: ${command}`;
  996. const isError = Object.prototype.toString.call(error) === '[object Error]';
  997. const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
  998. const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
  999. if (isError) {
  1000. error.originalMessage = error.message;
  1001. error.message = message;
  1002. } else {
  1003. error = new Error(message);
  1004. }
  1005. error.shortMessage = shortMessage;
  1006. error.command = command;
  1007. error.escapedCommand = escapedCommand;
  1008. error.exitCode = exitCode;
  1009. error.signal = signal;
  1010. error.signalDescription = signalDescription;
  1011. error.stdout = stdout;
  1012. error.stderr = stderr;
  1013. if (all !== undefined) {
  1014. error.all = all;
  1015. }
  1016. if ('bufferedData' in error) {
  1017. delete error.bufferedData;
  1018. }
  1019. error.failed = true;
  1020. error.timedOut = Boolean(timedOut);
  1021. error.isCanceled = isCanceled;
  1022. error.killed = killed && !timedOut;
  1023. return error;
  1024. };
  1025. const aliases = ['stdin', 'stdout', 'stderr'];
  1026. const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
  1027. const normalizeStdio = options => {
  1028. if (!options) {
  1029. return;
  1030. }
  1031. const {stdio} = options;
  1032. if (stdio === undefined) {
  1033. return aliases.map(alias => options[alias]);
  1034. }
  1035. if (hasAlias(options)) {
  1036. throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
  1037. }
  1038. if (typeof stdio === 'string') {
  1039. return stdio;
  1040. }
  1041. if (!Array.isArray(stdio)) {
  1042. throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
  1043. }
  1044. const length = Math.max(stdio.length, aliases.length);
  1045. return Array.from({length}, (value, index) => stdio[index]);
  1046. };
  1047. var signalExit = {exports: {}};
  1048. var signals$1 = {exports: {}};
  1049. var hasRequiredSignals;
  1050. function requireSignals () {
  1051. if (hasRequiredSignals) return signals$1.exports;
  1052. hasRequiredSignals = 1;
  1053. (function (module) {
  1054. // This is not the set of all possible signals.
  1055. //
  1056. // It IS, however, the set of all signals that trigger
  1057. // an exit on either Linux or BSD systems. Linux is a
  1058. // superset of the signal names supported on BSD, and
  1059. // the unknown signals just fail to register, so we can
  1060. // catch that easily enough.
  1061. //
  1062. // Don't bother with SIGKILL. It's uncatchable, which
  1063. // means that we can't fire any callbacks anyway.
  1064. //
  1065. // If a user does happen to register a handler on a non-
  1066. // fatal signal like SIGWINCH or something, and then
  1067. // exit, it'll end up firing `process.emit('exit')`, so
  1068. // the handler will be fired anyway.
  1069. //
  1070. // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
  1071. // artificially, inherently leave the process in a
  1072. // state from which it is not safe to try and enter JS
  1073. // listeners.
  1074. module.exports = [
  1075. 'SIGABRT',
  1076. 'SIGALRM',
  1077. 'SIGHUP',
  1078. 'SIGINT',
  1079. 'SIGTERM'
  1080. ];
  1081. if (process.platform !== 'win32') {
  1082. module.exports.push(
  1083. 'SIGVTALRM',
  1084. 'SIGXCPU',
  1085. 'SIGXFSZ',
  1086. 'SIGUSR2',
  1087. 'SIGTRAP',
  1088. 'SIGSYS',
  1089. 'SIGQUIT',
  1090. 'SIGIOT'
  1091. // should detect profiler and enable/disable accordingly.
  1092. // see #21
  1093. // 'SIGPROF'
  1094. );
  1095. }
  1096. if (process.platform === 'linux') {
  1097. module.exports.push(
  1098. 'SIGIO',
  1099. 'SIGPOLL',
  1100. 'SIGPWR',
  1101. 'SIGSTKFLT',
  1102. 'SIGUNUSED'
  1103. );
  1104. }
  1105. } (signals$1));
  1106. return signals$1.exports;
  1107. }
  1108. // Note: since nyc uses this module to output coverage, any lines
  1109. // that are in the direct sync flow of nyc's outputCoverage are
  1110. // ignored, since we can never get coverage for them.
  1111. // grab a reference to node's real process object right away
  1112. var process$1 = commonjsGlobal.process;
  1113. const processOk = function (process) {
  1114. return process &&
  1115. typeof process === 'object' &&
  1116. typeof process.removeListener === 'function' &&
  1117. typeof process.emit === 'function' &&
  1118. typeof process.reallyExit === 'function' &&
  1119. typeof process.listeners === 'function' &&
  1120. typeof process.kill === 'function' &&
  1121. typeof process.pid === 'number' &&
  1122. typeof process.on === 'function'
  1123. };
  1124. // some kind of non-node environment, just no-op
  1125. /* istanbul ignore if */
  1126. if (!processOk(process$1)) {
  1127. signalExit.exports = function () {
  1128. return function () {}
  1129. };
  1130. } else {
  1131. var assert = require$$0$2;
  1132. var signals = requireSignals();
  1133. var isWin = /^win/i.test(process$1.platform);
  1134. var EE = require$$2;
  1135. /* istanbul ignore if */
  1136. if (typeof EE !== 'function') {
  1137. EE = EE.EventEmitter;
  1138. }
  1139. var emitter;
  1140. if (process$1.__signal_exit_emitter__) {
  1141. emitter = process$1.__signal_exit_emitter__;
  1142. } else {
  1143. emitter = process$1.__signal_exit_emitter__ = new EE();
  1144. emitter.count = 0;
  1145. emitter.emitted = {};
  1146. }
  1147. // Because this emitter is a global, we have to check to see if a
  1148. // previous version of this library failed to enable infinite listeners.
  1149. // I know what you're about to say. But literally everything about
  1150. // signal-exit is a compromise with evil. Get used to it.
  1151. if (!emitter.infinite) {
  1152. emitter.setMaxListeners(Infinity);
  1153. emitter.infinite = true;
  1154. }
  1155. signalExit.exports = function (cb, opts) {
  1156. /* istanbul ignore if */
  1157. if (!processOk(commonjsGlobal.process)) {
  1158. return function () {}
  1159. }
  1160. assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
  1161. if (loaded === false) {
  1162. load();
  1163. }
  1164. var ev = 'exit';
  1165. if (opts && opts.alwaysLast) {
  1166. ev = 'afterexit';
  1167. }
  1168. var remove = function () {
  1169. emitter.removeListener(ev, cb);
  1170. if (emitter.listeners('exit').length === 0 &&
  1171. emitter.listeners('afterexit').length === 0) {
  1172. unload();
  1173. }
  1174. };
  1175. emitter.on(ev, cb);
  1176. return remove
  1177. };
  1178. var unload = function unload () {
  1179. if (!loaded || !processOk(commonjsGlobal.process)) {
  1180. return
  1181. }
  1182. loaded = false;
  1183. signals.forEach(function (sig) {
  1184. try {
  1185. process$1.removeListener(sig, sigListeners[sig]);
  1186. } catch (er) {}
  1187. });
  1188. process$1.emit = originalProcessEmit;
  1189. process$1.reallyExit = originalProcessReallyExit;
  1190. emitter.count -= 1;
  1191. };
  1192. signalExit.exports.unload = unload;
  1193. var emit = function emit (event, code, signal) {
  1194. /* istanbul ignore if */
  1195. if (emitter.emitted[event]) {
  1196. return
  1197. }
  1198. emitter.emitted[event] = true;
  1199. emitter.emit(event, code, signal);
  1200. };
  1201. // { <signal>: <listener fn>, ... }
  1202. var sigListeners = {};
  1203. signals.forEach(function (sig) {
  1204. sigListeners[sig] = function listener () {
  1205. /* istanbul ignore if */
  1206. if (!processOk(commonjsGlobal.process)) {
  1207. return
  1208. }
  1209. // If there are no other listeners, an exit is coming!
  1210. // Simplest way: remove us and then re-send the signal.
  1211. // We know that this will kill the process, so we can
  1212. // safely emit now.
  1213. var listeners = process$1.listeners(sig);
  1214. if (listeners.length === emitter.count) {
  1215. unload();
  1216. emit('exit', null, sig);
  1217. /* istanbul ignore next */
  1218. emit('afterexit', null, sig);
  1219. /* istanbul ignore next */
  1220. if (isWin && sig === 'SIGHUP') {
  1221. // "SIGHUP" throws an `ENOSYS` error on Windows,
  1222. // so use a supported signal instead
  1223. sig = 'SIGINT';
  1224. }
  1225. /* istanbul ignore next */
  1226. process$1.kill(process$1.pid, sig);
  1227. }
  1228. };
  1229. });
  1230. signalExit.exports.signals = function () {
  1231. return signals
  1232. };
  1233. var loaded = false;
  1234. var load = function load () {
  1235. if (loaded || !processOk(commonjsGlobal.process)) {
  1236. return
  1237. }
  1238. loaded = true;
  1239. // This is the number of onSignalExit's that are in play.
  1240. // It's important so that we can count the correct number of
  1241. // listeners on signals, and don't wait for the other one to
  1242. // handle it instead of us.
  1243. emitter.count += 1;
  1244. signals = signals.filter(function (sig) {
  1245. try {
  1246. process$1.on(sig, sigListeners[sig]);
  1247. return true
  1248. } catch (er) {
  1249. return false
  1250. }
  1251. });
  1252. process$1.emit = processEmit;
  1253. process$1.reallyExit = processReallyExit;
  1254. };
  1255. signalExit.exports.load = load;
  1256. var originalProcessReallyExit = process$1.reallyExit;
  1257. var processReallyExit = function processReallyExit (code) {
  1258. /* istanbul ignore if */
  1259. if (!processOk(commonjsGlobal.process)) {
  1260. return
  1261. }
  1262. process$1.exitCode = code || /* istanbul ignore next */ 0;
  1263. emit('exit', process$1.exitCode, null);
  1264. /* istanbul ignore next */
  1265. emit('afterexit', process$1.exitCode, null);
  1266. /* istanbul ignore next */
  1267. originalProcessReallyExit.call(process$1, process$1.exitCode);
  1268. };
  1269. var originalProcessEmit = process$1.emit;
  1270. var processEmit = function processEmit (ev, arg) {
  1271. if (ev === 'exit' && processOk(commonjsGlobal.process)) {
  1272. /* istanbul ignore else */
  1273. if (arg !== undefined) {
  1274. process$1.exitCode = arg;
  1275. }
  1276. var ret = originalProcessEmit.apply(this, arguments);
  1277. /* istanbul ignore next */
  1278. emit('exit', process$1.exitCode, null);
  1279. /* istanbul ignore next */
  1280. emit('afterexit', process$1.exitCode, null);
  1281. /* istanbul ignore next */
  1282. return ret
  1283. } else {
  1284. return originalProcessEmit.apply(this, arguments)
  1285. }
  1286. };
  1287. }
  1288. const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
  1289. // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
  1290. const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
  1291. const killResult = kill(signal);
  1292. setKillTimeout(kill, signal, options, killResult);
  1293. return killResult;
  1294. };
  1295. const setKillTimeout = (kill, signal, options, killResult) => {
  1296. if (!shouldForceKill(signal, options, killResult)) {
  1297. return;
  1298. }
  1299. const timeout = getForceKillAfterTimeout(options);
  1300. const t = setTimeout(() => {
  1301. kill('SIGKILL');
  1302. }, timeout);
  1303. // Guarded because there's no `.unref()` when `execa` is used in the renderer
  1304. // process in Electron. This cannot be tested since we don't run tests in
  1305. // Electron.
  1306. // istanbul ignore else
  1307. if (t.unref) {
  1308. t.unref();
  1309. }
  1310. };
  1311. const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
  1312. const isSigterm = signal => signal === os.constants.signals.SIGTERM
  1313. || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
  1314. const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
  1315. if (forceKillAfterTimeout === true) {
  1316. return DEFAULT_FORCE_KILL_TIMEOUT;
  1317. }
  1318. if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
  1319. throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
  1320. }
  1321. return forceKillAfterTimeout;
  1322. };
  1323. // `childProcess.cancel()`
  1324. const spawnedCancel = (spawned, context) => {
  1325. const killResult = spawned.kill();
  1326. if (killResult) {
  1327. context.isCanceled = true;
  1328. }
  1329. };
  1330. const timeoutKill = (spawned, signal, reject) => {
  1331. spawned.kill(signal);
  1332. reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
  1333. };
  1334. // `timeout` option handling
  1335. const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
  1336. if (timeout === 0 || timeout === undefined) {
  1337. return spawnedPromise;
  1338. }
  1339. let timeoutId;
  1340. const timeoutPromise = new Promise((resolve, reject) => {
  1341. timeoutId = setTimeout(() => {
  1342. timeoutKill(spawned, killSignal, reject);
  1343. }, timeout);
  1344. });
  1345. const safeSpawnedPromise = spawnedPromise.finally(() => {
  1346. clearTimeout(timeoutId);
  1347. });
  1348. return Promise.race([timeoutPromise, safeSpawnedPromise]);
  1349. };
  1350. const validateTimeout = ({timeout}) => {
  1351. if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
  1352. throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
  1353. }
  1354. };
  1355. // `cleanup` option handling
  1356. const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
  1357. if (!cleanup || detached) {
  1358. return timedPromise;
  1359. }
  1360. const removeExitHandler = signalExit.exports(() => {
  1361. spawned.kill();
  1362. });
  1363. return timedPromise.finally(() => {
  1364. removeExitHandler();
  1365. });
  1366. };
  1367. function isStream(stream) {
  1368. return stream !== null
  1369. && typeof stream === 'object'
  1370. && typeof stream.pipe === 'function';
  1371. }
  1372. var getStream$1 = {exports: {}};
  1373. const {PassThrough: PassThroughStream} = require$$0$3;
  1374. var bufferStream$1 = options => {
  1375. options = {...options};
  1376. const {array} = options;
  1377. let {encoding} = options;
  1378. const isBuffer = encoding === 'buffer';
  1379. let objectMode = false;
  1380. if (array) {
  1381. objectMode = !(encoding || isBuffer);
  1382. } else {
  1383. encoding = encoding || 'utf8';
  1384. }
  1385. if (isBuffer) {
  1386. encoding = null;
  1387. }
  1388. const stream = new PassThroughStream({objectMode});
  1389. if (encoding) {
  1390. stream.setEncoding(encoding);
  1391. }
  1392. let length = 0;
  1393. const chunks = [];
  1394. stream.on('data', chunk => {
  1395. chunks.push(chunk);
  1396. if (objectMode) {
  1397. length = chunks.length;
  1398. } else {
  1399. length += chunk.length;
  1400. }
  1401. });
  1402. stream.getBufferedValue = () => {
  1403. if (array) {
  1404. return chunks;
  1405. }
  1406. return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
  1407. };
  1408. stream.getBufferedLength = () => length;
  1409. return stream;
  1410. };
  1411. const {constants: BufferConstants} = require$$0$5;
  1412. const stream = require$$0$3;
  1413. const {promisify} = require$$0$4;
  1414. const bufferStream = bufferStream$1;
  1415. const streamPipelinePromisified = promisify(stream.pipeline);
  1416. class MaxBufferError extends Error {
  1417. constructor() {
  1418. super('maxBuffer exceeded');
  1419. this.name = 'MaxBufferError';
  1420. }
  1421. }
  1422. async function getStream(inputStream, options) {
  1423. if (!inputStream) {
  1424. throw new Error('Expected a stream');
  1425. }
  1426. options = {
  1427. maxBuffer: Infinity,
  1428. ...options
  1429. };
  1430. const {maxBuffer} = options;
  1431. const stream = bufferStream(options);
  1432. await new Promise((resolve, reject) => {
  1433. const rejectPromise = error => {
  1434. // Don't retrieve an oversized buffer.
  1435. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
  1436. error.bufferedData = stream.getBufferedValue();
  1437. }
  1438. reject(error);
  1439. };
  1440. (async () => {
  1441. try {
  1442. await streamPipelinePromisified(inputStream, stream);
  1443. resolve();
  1444. } catch (error) {
  1445. rejectPromise(error);
  1446. }
  1447. })();
  1448. stream.on('data', () => {
  1449. if (stream.getBufferedLength() > maxBuffer) {
  1450. rejectPromise(new MaxBufferError());
  1451. }
  1452. });
  1453. });
  1454. return stream.getBufferedValue();
  1455. }
  1456. getStream$1.exports = getStream;
  1457. getStream$1.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});
  1458. getStream$1.exports.array = (stream, options) => getStream(stream, {...options, array: true});
  1459. getStream$1.exports.MaxBufferError = MaxBufferError;
  1460. const { PassThrough } = require$$0$3;
  1461. var mergeStream = function (/*streams...*/) {
  1462. var sources = [];
  1463. var output = new PassThrough({objectMode: true});
  1464. output.setMaxListeners(0);
  1465. output.add = add;
  1466. output.isEmpty = isEmpty;
  1467. output.on('unpipe', remove);
  1468. Array.prototype.slice.call(arguments).forEach(add);
  1469. return output
  1470. function add (source) {
  1471. if (Array.isArray(source)) {
  1472. source.forEach(add);
  1473. return this
  1474. }
  1475. sources.push(source);
  1476. source.once('end', remove.bind(null, source));
  1477. source.once('error', output.emit.bind(output, 'error'));
  1478. source.pipe(output, {end: false});
  1479. return this
  1480. }
  1481. function isEmpty () {
  1482. return sources.length == 0;
  1483. }
  1484. function remove (source) {
  1485. sources = sources.filter(function (it) { return it !== source });
  1486. if (!sources.length && output.readable) { output.end(); }
  1487. }
  1488. };
  1489. // `input` option
  1490. const handleInput = (spawned, input) => {
  1491. if (input === undefined) {
  1492. return;
  1493. }
  1494. if (isStream(input)) {
  1495. input.pipe(spawned.stdin);
  1496. } else {
  1497. spawned.stdin.end(input);
  1498. }
  1499. };
  1500. // `all` interleaves `stdout` and `stderr`
  1501. const makeAllStream = (spawned, {all}) => {
  1502. if (!all || (!spawned.stdout && !spawned.stderr)) {
  1503. return;
  1504. }
  1505. const mixed = mergeStream();
  1506. if (spawned.stdout) {
  1507. mixed.add(spawned.stdout);
  1508. }
  1509. if (spawned.stderr) {
  1510. mixed.add(spawned.stderr);
  1511. }
  1512. return mixed;
  1513. };
  1514. // On failure, `result.stdout|stderr|all` should contain the currently buffered stream
  1515. const getBufferedData = async (stream, streamPromise) => {
  1516. // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve
  1517. if (!stream || streamPromise === undefined) {
  1518. return;
  1519. }
  1520. stream.destroy();
  1521. try {
  1522. return await streamPromise;
  1523. } catch (error) {
  1524. return error.bufferedData;
  1525. }
  1526. };
  1527. const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
  1528. if (!stream || !buffer) {
  1529. return;
  1530. }
  1531. if (encoding) {
  1532. return getStream$1.exports(stream, {encoding, maxBuffer});
  1533. }
  1534. return getStream$1.exports.buffer(stream, {maxBuffer});
  1535. };
  1536. // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
  1537. const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
  1538. const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
  1539. const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
  1540. const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
  1541. try {
  1542. return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
  1543. } catch (error) {
  1544. return Promise.all([
  1545. {error, signal: error.signal, timedOut: error.timedOut},
  1546. getBufferedData(stdout, stdoutPromise),
  1547. getBufferedData(stderr, stderrPromise),
  1548. getBufferedData(all, allPromise),
  1549. ]);
  1550. }
  1551. };
  1552. // eslint-disable-next-line unicorn/prefer-top-level-await
  1553. const nativePromisePrototype = (async () => {})().constructor.prototype;
  1554. const descriptors = ['then', 'catch', 'finally'].map(property => [
  1555. property,
  1556. Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),
  1557. ]);
  1558. // The return value is a mixin of `childProcess` and `Promise`
  1559. const mergePromise = (spawned, promise) => {
  1560. for (const [property, descriptor] of descriptors) {
  1561. // Starting the main `promise` is deferred to avoid consuming streams
  1562. const value = typeof promise === 'function'
  1563. ? (...args) => Reflect.apply(descriptor.value, promise(), args)
  1564. : descriptor.value.bind(promise);
  1565. Reflect.defineProperty(spawned, property, {...descriptor, value});
  1566. }
  1567. return spawned;
  1568. };
  1569. // Use promises instead of `child_process` events
  1570. const getSpawnedPromise = spawned => new Promise((resolve, reject) => {
  1571. spawned.on('exit', (exitCode, signal) => {
  1572. resolve({exitCode, signal});
  1573. });
  1574. spawned.on('error', error => {
  1575. reject(error);
  1576. });
  1577. if (spawned.stdin) {
  1578. spawned.stdin.on('error', error => {
  1579. reject(error);
  1580. });
  1581. }
  1582. });
  1583. const normalizeArgs = (file, args = []) => {
  1584. if (!Array.isArray(args)) {
  1585. return [file];
  1586. }
  1587. return [file, ...args];
  1588. };
  1589. const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
  1590. const DOUBLE_QUOTES_REGEXP = /"/g;
  1591. const escapeArg = arg => {
  1592. if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {
  1593. return arg;
  1594. }
  1595. return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
  1596. };
  1597. const joinCommand = (file, args) => normalizeArgs(file, args).join(' ');
  1598. const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
  1599. const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
  1600. const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
  1601. const env = extendEnv ? {...process$2.env, ...envOption} : envOption;
  1602. if (preferLocal) {
  1603. return npmRunPathEnv({env, cwd: localDir, execPath});
  1604. }
  1605. return env;
  1606. };
  1607. const handleArguments = (file, args, options = {}) => {
  1608. const parsed = crossSpawn.exports._parse(file, args, options);
  1609. file = parsed.command;
  1610. args = parsed.args;
  1611. options = parsed.options;
  1612. options = {
  1613. maxBuffer: DEFAULT_MAX_BUFFER,
  1614. buffer: true,
  1615. stripFinalNewline: true,
  1616. extendEnv: true,
  1617. preferLocal: false,
  1618. localDir: options.cwd || process$2.cwd(),
  1619. execPath: process$2.execPath,
  1620. encoding: 'utf8',
  1621. reject: true,
  1622. cleanup: true,
  1623. all: false,
  1624. windowsHide: true,
  1625. ...options,
  1626. };
  1627. options.env = getEnv(options);
  1628. options.stdio = normalizeStdio(options);
  1629. if (process$2.platform === 'win32' && path$3.basename(file, '.exe') === 'cmd') {
  1630. // #116
  1631. args.unshift('/q');
  1632. }
  1633. return {file, args, options, parsed};
  1634. };
  1635. const handleOutput = (options, value, error) => {
  1636. if (typeof value !== 'string' && !Buffer$1.isBuffer(value)) {
  1637. // When `execaSync()` errors, we normalize it to '' to mimic `execa()`
  1638. return error === undefined ? undefined : '';
  1639. }
  1640. if (options.stripFinalNewline) {
  1641. return stripFinalNewline(value);
  1642. }
  1643. return value;
  1644. };
  1645. function execa(file, args, options) {
  1646. const parsed = handleArguments(file, args, options);
  1647. const command = joinCommand(file, args);
  1648. const escapedCommand = getEscapedCommand(file, args);
  1649. validateTimeout(parsed.options);
  1650. let spawned;
  1651. try {
  1652. spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
  1653. } catch (error) {
  1654. // Ensure the returned error is always both a promise and a child process
  1655. const dummySpawned = new childProcess.ChildProcess();
  1656. const errorPromise = Promise.reject(makeError({
  1657. error,
  1658. stdout: '',
  1659. stderr: '',
  1660. all: '',
  1661. command,
  1662. escapedCommand,
  1663. parsed,
  1664. timedOut: false,
  1665. isCanceled: false,
  1666. killed: false,
  1667. }));
  1668. return mergePromise(dummySpawned, errorPromise);
  1669. }
  1670. const spawnedPromise = getSpawnedPromise(spawned);
  1671. const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
  1672. const processDone = setExitHandler(spawned, parsed.options, timedPromise);
  1673. const context = {isCanceled: false};
  1674. spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
  1675. spawned.cancel = spawnedCancel.bind(null, spawned, context);
  1676. const handlePromise = async () => {
  1677. const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
  1678. const stdout = handleOutput(parsed.options, stdoutResult);
  1679. const stderr = handleOutput(parsed.options, stderrResult);
  1680. const all = handleOutput(parsed.options, allResult);
  1681. if (error || exitCode !== 0 || signal !== null) {
  1682. const returnedError = makeError({
  1683. error,
  1684. exitCode,
  1685. signal,
  1686. stdout,
  1687. stderr,
  1688. all,
  1689. command,
  1690. escapedCommand,
  1691. parsed,
  1692. timedOut,
  1693. isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),
  1694. killed: spawned.killed,
  1695. });
  1696. if (!parsed.options.reject) {
  1697. return returnedError;
  1698. }
  1699. throw returnedError;
  1700. }
  1701. return {
  1702. command,
  1703. escapedCommand,
  1704. exitCode: 0,
  1705. stdout,
  1706. stderr,
  1707. all,
  1708. failed: false,
  1709. timedOut: false,
  1710. isCanceled: false,
  1711. killed: false,
  1712. };
  1713. };
  1714. const handlePromiseOnce = onetime(handlePromise);
  1715. handleInput(spawned, parsed.options.input);
  1716. spawned.all = makeAllStream(spawned, parsed.options);
  1717. return mergePromise(spawned, handlePromiseOnce);
  1718. }
  1719. export { crossSpawn as c, execa as e, getStream$1 as g, mergeStream as m, pathKey$2 as p, signalExit as s };