import { spawn } from 'child_process' import fs from 'node:fs' import os from 'os' import path from 'path' import { getPaths } from '@cedarjs/project-config' /** * Quotes a single argument for a Windows shell command string. * * The Windows branch below spawns with `shell: true` and a command string, so * every argument is re-parsed by the shell. Without quoting, anything with a * space in it is split: a project at `C:\Users\Ada Lovelace\app` makes node * try to load `C:\Users\Ada` and the background process dies immediately with * MODULE_NOT_FOUND, silently, because its output goes to a log file. * * Follows the usual Windows argument-encoding rules: backslashes immediately * before a double quote are doubled, the quote itself is escaped, and trailing * backslashes are doubled so they can't escape the closing quote. */ export function quoteForWindowsShell(arg: string) { let quoted = '"' let backslashes = 0 for (const char of arg) { if (char === '\\') { backslashes += 1 continue } if (char === '"') { // Double the run of backslashes before the quote so they aren't read as // escapes themselves, then escape the quote quoted += '\\'.repeat(backslashes * 2 + 1) + '"' } else { quoted += '\\'.repeat(backslashes) + char } backslashes = 0 } // Trailing backslashes would escape the closing quote, so double them return quoted + '\\'.repeat(backslashes * 2) + '"' } /** * Spawn a background process with the stdout/stderr redirected to log files * within the `.cedar` directory. Stdin will not be available to the process as * it will be set to the 'ignore' value. * * @param {string} name A name for this background process, will be used to name * the log files * @param {string} cmd Command to pass to the `spawn` function * @param {string[]} args Arguments to pass to the `spawn` function */ export function spawnBackgroundProcess( name: string, cmd: string, args: string[], ) { const logDirectory = path.join(getPaths().generated.base, 'logs') fs.mkdirSync(logDirectory, { recursive: true }) const safeName = name.replace(/[^a-z0-9]/gi, '_').toLowerCase() const logHeader = [ `Starting log:`, ` - Time: ${new Date().toISOString()}`, ` - Name: ${name} (${safeName})`, ` - Command: ${cmd}`, ` - Arguments: ${args.join(' ')}`, '', '', ].join('\n') const stdout = fs.openSync( path.join(logDirectory, `${safeName}.out.log`), 'w', ) fs.writeSync(stdout, logHeader) const stderr = fs.openSync( path.join(logDirectory, `${safeName}.err.log`), 'w', ) fs.writeSync(stderr, logHeader) // We must account for some platform specific behaviour if (os.type() === 'Windows_NT') { const spawnOptions = { // The following options run the process in the background without a // console window, even though they don't look like they would. // See https://github.com/nodejs/node/issues/21825#issuecomment-503766781 // for information. detached: false, windowsHide: false, shell: true, stdio: ['ignore' as const, stdout, stderr], } // Spawn and detach the process // // The best way to use `spawn` is to pass the process args as a separate // argument, but when the spawn options include `shell: true`, like they do // here, that causes Node.js to print a DEP0190 warning. To get around this // we instead concatenate the command and arguments into a single string. // Each argument has to be quoted on the way in -- they're not // user-provided, but they are filesystem paths, and those routinely // contain spaces. // // https://nodejs.org/api/deprecations.html#DEP0190 const command = [cmd, ...args].map(quoteForWindowsShell).join(' ') const child = spawn(command, spawnOptions) child.unref() } else { const spawnOptions = { detached: true, stdio: ['ignore' as const, stdout, stderr], } // Spawn and detach the process // // For Linux and MacOS we don't need `shell: true`, so here we can use the // `cmd` and `args` arguments separately. const child = spawn(cmd, args, spawnOptions) child.unref() } // Close the parent's copies of the stdio file descriptors. // The child process inherited its own copies via spawn(), so leaving these // open in the parent leaks fds until process exit. fs.closeSync(stdout) fs.closeSync(stderr) }