Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

index.js 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. 'use strict';
  2. const {promisify} = require('util');
  3. const path = require('path');
  4. const childProcess = require('child_process');
  5. const fs = require('fs');
  6. const isWsl = require('is-wsl');
  7. const isDocker = require('is-docker');
  8. const pAccess = promisify(fs.access);
  9. const pExecFile = promisify(childProcess.execFile);
  10. // Path to included `xdg-open`.
  11. const localXdgOpenPath = path.join(__dirname, 'xdg-open');
  12. // Convert a path from WSL format to Windows format:
  13. // `/mnt/c/Program Files/Example/MyApp.exe` → `C:\Program Files\Example\MyApp.exe`
  14. const wslToWindowsPath = async path => {
  15. const {stdout} = await pExecFile('wslpath', ['-w', path]);
  16. return stdout.trim();
  17. };
  18. // Convert a path from Windows format to WSL format
  19. const windowsToWslPath = async path => {
  20. const {stdout} = await pExecFile('wslpath', [path]);
  21. return stdout.trim();
  22. };
  23. // Get an environment variable from Windows
  24. const wslGetWindowsEnvVar = async envVar => {
  25. const {stdout} = await pExecFile('wslvar', [envVar]);
  26. return stdout.trim();
  27. };
  28. module.exports = async (target, options) => {
  29. if (typeof target !== 'string') {
  30. throw new TypeError('Expected a `target`');
  31. }
  32. options = {
  33. wait: false,
  34. background: false,
  35. allowNonzeroExitCode: false,
  36. ...options
  37. };
  38. let command;
  39. let {app} = options;
  40. let appArguments = [];
  41. const cliArguments = [];
  42. const childProcessOptions = {};
  43. if (Array.isArray(app)) {
  44. appArguments = app.slice(1);
  45. app = app[0];
  46. }
  47. if (process.platform === 'darwin') {
  48. command = 'open';
  49. if (options.wait) {
  50. cliArguments.push('--wait-apps');
  51. }
  52. if (options.background) {
  53. cliArguments.push('--background');
  54. }
  55. if (app) {
  56. cliArguments.push('-a', app);
  57. }
  58. } else if (process.platform === 'win32' || (isWsl && !isDocker())) {
  59. const windowsRoot = isWsl ? await wslGetWindowsEnvVar('systemroot') : process.env.SYSTEMROOT;
  60. command = String.raw`${windowsRoot}\System32\WindowsPowerShell\v1.0\powershell${isWsl ? '.exe' : ''}`;
  61. cliArguments.push(
  62. '-NoProfile',
  63. '-NonInteractive',
  64. '–ExecutionPolicy',
  65. 'Bypass',
  66. '-EncodedCommand'
  67. );
  68. if (isWsl) {
  69. command = await windowsToWslPath(command);
  70. } else {
  71. childProcessOptions.windowsVerbatimArguments = true;
  72. }
  73. const encodedArguments = ['Start'];
  74. if (options.wait) {
  75. encodedArguments.push('-Wait');
  76. }
  77. if (app) {
  78. if (isWsl && app.startsWith('/mnt/')) {
  79. const windowsPath = await wslToWindowsPath(app);
  80. app = windowsPath;
  81. }
  82. // Double quote with double quotes to ensure the inner quotes are passed through.
  83. // Inner quotes are delimited for PowerShell interpretation with backticks.
  84. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
  85. appArguments.unshift(target);
  86. } else {
  87. encodedArguments.push(`"\`"${target}\`""`);
  88. }
  89. if (appArguments.length > 0) {
  90. appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
  91. encodedArguments.push(appArguments.join(','));
  92. }
  93. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  94. target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  95. } else {
  96. if (app) {
  97. command = app;
  98. } else {
  99. // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
  100. const isBundled = !__dirname || __dirname === '/';
  101. // Check if local `xdg-open` exists and is executable.
  102. let exeLocalXdgOpen = false;
  103. try {
  104. await pAccess(localXdgOpenPath, fs.constants.X_OK);
  105. exeLocalXdgOpen = true;
  106. } catch (_) {}
  107. const useSystemXdgOpen = process.versions.electron ||
  108. process.platform === 'android' || isBundled || !exeLocalXdgOpen;
  109. command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
  110. }
  111. if (appArguments.length > 0) {
  112. cliArguments.push(...appArguments);
  113. }
  114. if (!options.wait) {
  115. // `xdg-open` will block the process unless stdio is ignored
  116. // and it's detached from the parent even if it's unref'd.
  117. childProcessOptions.stdio = 'ignore';
  118. childProcessOptions.detached = true;
  119. }
  120. }
  121. cliArguments.push(target);
  122. if (process.platform === 'darwin' && appArguments.length > 0) {
  123. cliArguments.push('--args', ...appArguments);
  124. }
  125. const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
  126. if (options.wait) {
  127. return new Promise((resolve, reject) => {
  128. subprocess.once('error', reject);
  129. subprocess.once('close', exitCode => {
  130. if (options.allowNonzeroExitCode && exitCode > 0) {
  131. reject(new Error(`Exited with code ${exitCode}`));
  132. return;
  133. }
  134. resolve(subprocess);
  135. });
  136. });
  137. }
  138. subprocess.unref();
  139. return subprocess;
  140. };