add deps for js angular1.8

This commit is contained in:
Tykayn 2025-02-14 14:17:23 +01:00 committed by tykayn
parent 8e2da4f159
commit b373892ddc
3800 changed files with 125627 additions and 40 deletions

View file

@ -0,0 +1,250 @@
// Copyright 2017 - Refael Ackermann
// Distributed under MIT style license
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
// Usage:
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace VisualStudioConfiguration
{
[Flags]
public enum InstanceState : uint
{
None = 0,
Local = 1,
Registered = 2,
NoRebootRequired = 4,
NoErrors = 8,
Complete = 4294967295,
}
[Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IEnumSetupInstances
{
void Next([MarshalAs(UnmanagedType.U4), In] int celt,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface), Out] ISetupInstance[] rgelt,
[MarshalAs(UnmanagedType.U4)] out int pceltFetched);
void Skip([MarshalAs(UnmanagedType.U4), In] int celt);
void Reset();
[return: MarshalAs(UnmanagedType.Interface)]
IEnumSetupInstances Clone();
}
[Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupConfiguration
{
}
[Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupConfiguration2 : ISetupConfiguration
{
[return: MarshalAs(UnmanagedType.Interface)]
IEnumSetupInstances EnumInstances();
[return: MarshalAs(UnmanagedType.Interface)]
ISetupInstance GetInstanceForCurrentProcess();
[return: MarshalAs(UnmanagedType.Interface)]
ISetupInstance GetInstanceForPath([MarshalAs(UnmanagedType.LPWStr), In] string path);
[return: MarshalAs(UnmanagedType.Interface)]
IEnumSetupInstances EnumAllInstances();
}
[Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupInstance
{
}
[Guid("89143C9A-05AF-49B0-B717-72E218A2185C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupInstance2 : ISetupInstance
{
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstanceId();
[return: MarshalAs(UnmanagedType.Struct)]
System.Runtime.InteropServices.ComTypes.FILETIME GetInstallDate();
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstallationName();
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstallationPath();
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstallationVersion();
[return: MarshalAs(UnmanagedType.BStr)]
string GetDisplayName([MarshalAs(UnmanagedType.U4), In] int lcid);
[return: MarshalAs(UnmanagedType.BStr)]
string GetDescription([MarshalAs(UnmanagedType.U4), In] int lcid);
[return: MarshalAs(UnmanagedType.BStr)]
string ResolvePath([MarshalAs(UnmanagedType.LPWStr), In] string pwszRelativePath);
[return: MarshalAs(UnmanagedType.U4)]
InstanceState GetState();
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
ISetupPackageReference[] GetPackages();
ISetupPackageReference GetProduct();
[return: MarshalAs(UnmanagedType.BStr)]
string GetProductPath();
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsLaunchable();
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsComplete();
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
ISetupPropertyStore GetProperties();
[return: MarshalAs(UnmanagedType.BStr)]
string GetEnginePath();
}
[Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupPackageReference
{
[return: MarshalAs(UnmanagedType.BStr)]
string GetId();
[return: MarshalAs(UnmanagedType.BStr)]
string GetVersion();
[return: MarshalAs(UnmanagedType.BStr)]
string GetChip();
[return: MarshalAs(UnmanagedType.BStr)]
string GetLanguage();
[return: MarshalAs(UnmanagedType.BStr)]
string GetBranch();
[return: MarshalAs(UnmanagedType.BStr)]
string GetType();
[return: MarshalAs(UnmanagedType.BStr)]
string GetUniqueId();
[return: MarshalAs(UnmanagedType.VariantBool)]
bool GetIsExtension();
}
[Guid("c601c175-a3be-44bc-91f6-4568d230fc83")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupPropertyStore
{
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
string[] GetNames();
object GetValue([MarshalAs(UnmanagedType.LPWStr), In] string pwszName);
}
[Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")]
[CoClass(typeof(SetupConfigurationClass))]
[ComImport]
public interface SetupConfiguration : ISetupConfiguration2, ISetupConfiguration
{
}
[Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")]
[ClassInterface(ClassInterfaceType.None)]
[ComImport]
public class SetupConfigurationClass
{
}
public static class Main
{
public static void PrintJson()
{
ISetupConfiguration query = new SetupConfiguration();
ISetupConfiguration2 query2 = (ISetupConfiguration2)query;
IEnumSetupInstances e = query2.EnumAllInstances();
int pceltFetched;
ISetupInstance2[] rgelt = new ISetupInstance2[1];
List<string> instances = new List<string>();
while (true)
{
e.Next(1, rgelt, out pceltFetched);
if (pceltFetched <= 0)
{
Console.WriteLine(String.Format("[{0}]", string.Join(",", instances.ToArray())));
return;
}
try
{
instances.Add(InstanceJson(rgelt[0]));
}
catch (COMException)
{
// Ignore instances that can't be queried.
}
}
}
private static string JsonString(string s)
{
return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
}
private static string InstanceJson(ISetupInstance2 setupInstance2)
{
// Visual Studio component directory:
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
StringBuilder json = new StringBuilder();
json.Append("{");
string path = JsonString(setupInstance2.GetInstallationPath());
json.Append(String.Format("\"path\":{0},", path));
string version = JsonString(setupInstance2.GetInstallationVersion());
json.Append(String.Format("\"version\":{0},", version));
List<string> packages = new List<string>();
foreach (ISetupPackageReference package in setupInstance2.GetPackages())
{
string id = JsonString(package.GetId());
packages.Add(id);
}
json.Append(String.Format("\"packages\":[{0}]", string.Join(",", packages.ToArray())));
json.Append("}");
return json.ToString();
}
}
}

View file

@ -0,0 +1,227 @@
'use strict'
const gracefulFs = require('graceful-fs')
const fs = gracefulFs.promises
const path = require('path')
const { glob } = require('glob')
const log = require('./log')
const which = require('which')
const win = process.platform === 'win32'
async function build (gyp, argv) {
let platformMake = 'make'
if (process.platform === 'aix') {
platformMake = 'gmake'
} else if (process.platform === 'os400') {
platformMake = 'gmake'
} else if (process.platform.indexOf('bsd') !== -1) {
platformMake = 'gmake'
} else if (win && argv.length > 0) {
argv = argv.map(function (target) {
return '/t:' + target
})
}
const makeCommand = gyp.opts.make || process.env.MAKE || platformMake
let command = win ? 'msbuild' : makeCommand
const jobs = gyp.opts.jobs || process.env.JOBS
let buildType
let config
let arch
let nodeDir
let guessedSolution
let python
let buildBinsDir
await loadConfigGypi()
/**
* Load the "config.gypi" file that was generated during "configure".
*/
async function loadConfigGypi () {
let data
try {
const configPath = path.resolve('build', 'config.gypi')
data = await fs.readFile(configPath, 'utf8')
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('You must run `node-gyp configure` first!')
} else {
throw err
}
}
config = JSON.parse(data.replace(/#.+\n/, ''))
// get the 'arch', 'buildType', and 'nodeDir' vars from the config
buildType = config.target_defaults.default_configuration
arch = config.variables.target_arch
nodeDir = config.variables.nodedir
python = config.variables.python
if ('debug' in gyp.opts) {
buildType = gyp.opts.debug ? 'Debug' : 'Release'
}
if (!buildType) {
buildType = 'Release'
}
log.verbose('build type', buildType)
log.verbose('architecture', arch)
log.verbose('node dev dir', nodeDir)
log.verbose('python', python)
if (win) {
await findSolutionFile()
} else {
await doWhich()
}
}
/**
* On Windows, find the first build/*.sln file.
*/
async function findSolutionFile () {
const files = await glob('build/*.sln')
if (files.length === 0) {
if (gracefulFs.existsSync('build/Makefile') || (await glob('build/*.mk')).length !== 0) {
command = makeCommand
await doWhich(false)
return
} else {
throw new Error('Could not find *.sln file or Makefile. Did you run "configure"?')
}
}
guessedSolution = files[0]
log.verbose('found first Solution file', guessedSolution)
await doWhich(true)
}
/**
* Uses node-which to locate the msbuild / make executable.
*/
async function doWhich (msvs) {
// On Windows use msbuild provided by node-gyp configure
if (msvs) {
if (!config.variables.msbuild_path) {
throw new Error('MSBuild is not set, please run `node-gyp configure`.')
}
command = config.variables.msbuild_path
log.verbose('using MSBuild:', command)
await doBuild(msvs)
return
}
// First make sure we have the build command in the PATH
const execPath = await which(command)
log.verbose('`which` succeeded for `' + command + '`', execPath)
await doBuild(msvs)
}
/**
* Actually spawn the process and compile the module.
*/
async function doBuild (msvs) {
// Enable Verbose build
const verbose = log.logger.isVisible('verbose')
let j
if (!msvs && verbose) {
argv.push('V=1')
}
if (msvs && !verbose) {
argv.push('/clp:Verbosity=minimal')
}
if (msvs) {
// Turn off the Microsoft logo on Windows
argv.push('/nologo')
}
// Specify the build type, Release by default
if (msvs) {
// Convert .gypi config target_arch to MSBuild /Platform
// Since there are many ways to state '32-bit Intel', default to it.
// N.B. msbuild's Condition string equality tests are case-insensitive.
const archLower = arch.toLowerCase()
const p = archLower === 'x64'
? 'x64'
: (archLower === 'arm'
? 'ARM'
: (archLower === 'arm64' ? 'ARM64' : 'Win32'))
argv.push('/p:Configuration=' + buildType + ';Platform=' + p)
if (jobs) {
j = parseInt(jobs, 10)
if (!isNaN(j) && j > 0) {
argv.push('/m:' + j)
} else if (jobs.toUpperCase() === 'MAX') {
argv.push('/m:' + require('os').cpus().length)
}
}
} else {
argv.push('BUILDTYPE=' + buildType)
// Invoke the Makefile in the 'build' dir.
argv.push('-C')
argv.push('build')
if (jobs) {
j = parseInt(jobs, 10)
if (!isNaN(j) && j > 0) {
argv.push('--jobs')
argv.push(j)
} else if (jobs.toUpperCase() === 'MAX') {
argv.push('--jobs')
argv.push(require('os').cpus().length)
}
}
}
if (msvs) {
// did the user specify their own .sln file?
const hasSln = argv.some(function (arg) {
return path.extname(arg) === '.sln'
})
if (!hasSln) {
argv.unshift(gyp.opts.solution || guessedSolution)
}
}
if (!win) {
// Add build-time dependency symlinks (such as Python) to PATH
buildBinsDir = path.resolve('build', 'node_gyp_bins')
process.env.PATH = `${buildBinsDir}:${process.env.PATH}`
await fs.mkdir(buildBinsDir, { recursive: true })
const symlinkDestination = path.join(buildBinsDir, 'python3')
try {
await fs.unlink(symlinkDestination)
} catch (err) {
if (err.code !== 'ENOENT') throw err
}
await fs.symlink(python, symlinkDestination)
log.verbose('bin symlinks', `created symlink to "${python}" in "${buildBinsDir}" and added to PATH`)
}
const proc = gyp.spawn(command, argv)
await new Promise((resolve, reject) => proc.on('exit', async (code, signal) => {
if (buildBinsDir) {
// Clean up the build-time dependency symlinks:
await fs.rm(buildBinsDir, { recursive: true })
}
if (code !== 0) {
return reject(new Error('`' + command + '` failed with exit code: ' + code))
}
if (signal) {
return reject(new Error('`' + command + '` got signal: ' + signal))
}
resolve()
}))
}
}
module.exports = build
module.exports.usage = 'Invokes `' + (win ? 'msbuild' : 'make') + '` and builds the module'

View file

@ -0,0 +1,15 @@
'use strict'
const fs = require('graceful-fs').promises
const log = require('./log')
async function clean (gyp, argv) {
// Remove the 'build' dir
const buildDir = 'build'
log.verbose('clean', 'removing "%s" directory', buildDir)
await fs.rm(buildDir, { recursive: true, force: true })
}
module.exports = clean
module.exports.usage = 'Removes any generated build files and the "out" dir'

View file

@ -0,0 +1,328 @@
'use strict'
const { promises: fs, readFileSync } = require('graceful-fs')
const path = require('path')
const log = require('./log')
const os = require('os')
const processRelease = require('./process-release')
const win = process.platform === 'win32'
const findNodeDirectory = require('./find-node-directory')
const { createConfigGypi } = require('./create-config-gypi')
const { format: msgFormat } = require('util')
const { findAccessibleSync } = require('./util')
const { findPython } = require('./find-python')
const { findVisualStudio } = win ? require('./find-visualstudio') : {}
const majorRe = /^#define NODE_MAJOR_VERSION (\d+)/m
const minorRe = /^#define NODE_MINOR_VERSION (\d+)/m
const patchRe = /^#define NODE_PATCH_VERSION (\d+)/m
async function configure (gyp, argv) {
const buildDir = path.resolve('build')
const configNames = ['config.gypi', 'common.gypi']
const configs = []
let nodeDir
const release = processRelease(argv, gyp, process.version, process.release)
const python = await findPython(gyp.opts.python)
return getNodeDir()
async function getNodeDir () {
// 'python' should be set by now
process.env.PYTHON = python
if (!gyp.opts.nodedir &&
process.config.variables.use_prefix_to_find_headers) {
// check if the headers can be found using the prefix specified
// at build time. Use them if they match the version expected
const prefix = process.config.variables.node_prefix
let availVersion
try {
const nodeVersionH = readFileSync(path.join(prefix,
'include', 'node', 'node_version.h'), { encoding: 'utf8' })
const major = nodeVersionH.match(majorRe)[1]
const minor = nodeVersionH.match(minorRe)[1]
const patch = nodeVersionH.match(patchRe)[1]
availVersion = major + '.' + minor + '.' + patch
} catch {}
if (availVersion === release.version) {
// ok version matches, use the headers
gyp.opts.nodedir = prefix
log.verbose('using local node headers based on prefix',
'setting nodedir to ' + gyp.opts.nodedir)
}
}
if (gyp.opts.nodedir) {
// --nodedir was specified. use that for the dev files
nodeDir = gyp.opts.nodedir.replace(/^~/, os.homedir())
log.verbose('get node dir', 'compiling against specified --nodedir dev files: %s', nodeDir)
} else {
// if no --nodedir specified, ensure node dependencies are installed
if ('v' + release.version !== process.version) {
// if --target was given, then determine a target version to compile for
log.verbose('get node dir', 'compiling against --target node version: %s', release.version)
} else {
// if no --target was specified then use the current host node version
log.verbose('get node dir', 'no --target version specified, falling back to host node version: %s', release.version)
}
if (!release.semver) {
// could not parse the version string with semver
throw new Error('Invalid version number: ' + release.version)
}
// If the tarball option is set, always remove and reinstall the headers
// into devdir. Otherwise only install if they're not already there.
gyp.opts.ensure = !gyp.opts.tarball
await gyp.commands.install([release.version])
log.verbose('get node dir', 'target node version installed:', release.versionDir)
nodeDir = path.resolve(gyp.devDir, release.versionDir)
}
return createBuildDir()
}
async function createBuildDir () {
log.verbose('build dir', 'attempting to create "build" dir: %s', buildDir)
const isNew = await fs.mkdir(buildDir, { recursive: true })
log.verbose(
'build dir', '"build" dir needed to be created?', isNew ? 'Yes' : 'No'
)
if (win) {
let usingMakeGenerator = false
for (let i = argv.length - 1; i >= 0; --i) {
const arg = argv[i]
if (arg === '-f' || arg === '--format') {
const format = argv[i + 1]
if (typeof format === 'string' && format.startsWith('make')) {
usingMakeGenerator = true
break
}
} else if (arg.startsWith('--format=make')) {
usingMakeGenerator = true
break
}
}
let vsInfo = {}
if (!usingMakeGenerator) {
vsInfo = await findVisualStudio(release.semver, gyp.opts['msvs-version'])
}
return createConfigFile(vsInfo)
}
return createConfigFile(null)
}
async function createConfigFile (vsInfo) {
if (win) {
process.env.GYP_MSVS_VERSION = Math.min(vsInfo.versionYear, 2015)
process.env.GYP_MSVS_OVERRIDE_PATH = vsInfo.path
}
const configPath = await createConfigGypi({ gyp, buildDir, nodeDir, vsInfo, python })
configs.push(configPath)
return findConfigs()
}
async function findConfigs () {
const name = configNames.shift()
if (!name) {
return runGyp()
}
const fullPath = path.resolve(name)
log.verbose(name, 'checking for gypi file: %s', fullPath)
try {
await fs.stat(fullPath)
log.verbose(name, 'found gypi file')
configs.push(fullPath)
} catch (err) {
// ENOENT will check next gypi filename
if (err.code !== 'ENOENT') {
throw err
}
}
return findConfigs()
}
async function runGyp () {
if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) {
if (win) {
log.verbose('gyp', 'gyp format was not specified; forcing "msvs"')
// force the 'make' target for non-Windows
argv.push('-f', 'msvs')
} else {
log.verbose('gyp', 'gyp format was not specified; forcing "make"')
// force the 'make' target for non-Windows
argv.push('-f', 'make')
}
}
// include all the ".gypi" files that were found
configs.forEach(function (config) {
argv.push('-I', config)
})
// For AIX and z/OS we need to set up the path to the exports file
// which contains the symbols needed for linking.
let nodeExpFile
let nodeRootDir
let candidates
let logprefix = 'find exports file'
if (process.platform === 'aix' || process.platform === 'os390' || process.platform === 'os400') {
const ext = process.platform === 'os390' ? 'x' : 'exp'
nodeRootDir = findNodeDirectory()
if (process.platform === 'aix' || process.platform === 'os400') {
candidates = [
'include/node/node',
'out/Release/node',
'out/Debug/node',
'node'
].map(function (file) {
return file + '.' + ext
})
} else {
candidates = [
'out/Release/lib.target/libnode',
'out/Debug/lib.target/libnode',
'out/Release/obj.target/libnode',
'out/Debug/obj.target/libnode',
'lib/libnode'
].map(function (file) {
return file + '.' + ext
})
}
nodeExpFile = findAccessibleSync(logprefix, nodeRootDir, candidates)
if (nodeExpFile !== undefined) {
log.verbose(logprefix, 'Found exports file: %s', nodeExpFile)
} else {
const msg = msgFormat('Could not find node.%s file in %s', ext, nodeRootDir)
log.error(logprefix, 'Could not find exports file')
throw new Error(msg)
}
}
// For z/OS we need to set up the path to zoslib include directory,
// which contains headers included in v8config.h.
let zoslibIncDir
if (process.platform === 'os390') {
logprefix = "find zoslib's zos-base.h:"
let msg
let zoslibIncPath = process.env.ZOSLIB_INCLUDES
if (zoslibIncPath) {
zoslibIncPath = findAccessibleSync(logprefix, zoslibIncPath, ['zos-base.h'])
if (zoslibIncPath === undefined) {
msg = msgFormat('Could not find zos-base.h file in the directory set ' +
'in ZOSLIB_INCLUDES environment variable: %s; set it ' +
'to the correct path, or unset it to search %s', process.env.ZOSLIB_INCLUDES, nodeRootDir)
}
} else {
candidates = [
'include/node/zoslib/zos-base.h',
'include/zoslib/zos-base.h',
'zoslib/include/zos-base.h',
'install/include/node/zoslib/zos-base.h'
]
zoslibIncPath = findAccessibleSync(logprefix, nodeRootDir, candidates)
if (zoslibIncPath === undefined) {
msg = msgFormat('Could not find any of %s in directory %s; set ' +
'environmant variable ZOSLIB_INCLUDES to the path ' +
'that contains zos-base.h', candidates.toString(), nodeRootDir)
}
}
if (zoslibIncPath !== undefined) {
zoslibIncDir = path.dirname(zoslibIncPath)
log.verbose(logprefix, "Found zoslib's zos-base.h in: %s", zoslibIncDir)
} else if (release.version.split('.')[0] >= 16) {
// zoslib is only shipped in Node v16 and above.
log.error(logprefix, msg)
throw new Error(msg)
}
}
// this logic ported from the old `gyp_addon` python file
const gypScript = path.resolve(__dirname, '..', 'gyp', 'gyp_main.py')
const addonGypi = path.resolve(__dirname, '..', 'addon.gypi')
let commonGypi = path.resolve(nodeDir, 'include/node/common.gypi')
try {
await fs.stat(commonGypi)
} catch (err) {
commonGypi = path.resolve(nodeDir, 'common.gypi')
}
let outputDir = 'build'
if (win) {
// Windows expects an absolute path
outputDir = buildDir
}
const nodeGypDir = path.resolve(__dirname, '..')
let nodeLibFile = path.join(nodeDir,
!gyp.opts.nodedir ? '<(target_arch)' : '$(Configuration)',
release.name + '.lib')
argv.push('-I', addonGypi)
argv.push('-I', commonGypi)
argv.push('-Dlibrary=shared_library')
argv.push('-Dvisibility=default')
argv.push('-Dnode_root_dir=' + nodeDir)
if (process.platform === 'aix' || process.platform === 'os390' || process.platform === 'os400') {
argv.push('-Dnode_exp_file=' + nodeExpFile)
if (process.platform === 'os390' && zoslibIncDir) {
argv.push('-Dzoslib_include_dir=' + zoslibIncDir)
}
}
argv.push('-Dnode_gyp_dir=' + nodeGypDir)
// Do this to keep Cygwin environments happy, else the unescaped '\' gets eaten up,
// resulting in bad paths, Ex c:parentFolderfolderanotherFolder instead of c:\parentFolder\folder\anotherFolder
if (win) {
nodeLibFile = nodeLibFile.replace(/\\/g, '\\\\')
}
argv.push('-Dnode_lib_file=' + nodeLibFile)
argv.push('-Dmodule_root_dir=' + process.cwd())
argv.push('-Dnode_engine=' +
(gyp.opts.node_engine || process.jsEngine || 'v8'))
argv.push('--depth=.')
argv.push('--no-parallel')
// tell gyp to write the Makefile/Solution files into output_dir
argv.push('--generator-output', outputDir)
// tell make to write its output into the same dir
argv.push('-Goutput_dir=.')
// enforce use of the "binding.gyp" file
argv.unshift('binding.gyp')
// execute `gyp` from the current target nodedir
argv.unshift(gypScript)
// make sure python uses files that came with this particular node package
const pypath = [path.join(__dirname, '..', 'gyp', 'pylib')]
if (process.env.PYTHONPATH) {
pypath.push(process.env.PYTHONPATH)
}
process.env.PYTHONPATH = pypath.join(win ? ';' : ':')
await new Promise((resolve, reject) => {
const cp = gyp.spawn(python, argv)
cp.on('exit', (code) => {
if (code !== 0) {
reject(new Error('`gyp` failed with exit code: ' + code))
} else {
// we're done
resolve()
}
})
})
}
}
module.exports = configure
module.exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module'

View file

@ -0,0 +1,153 @@
'use strict'
const fs = require('graceful-fs').promises
const log = require('./log')
const path = require('path')
function parseConfigGypi (config) {
// translated from tools/js2c.py of Node.js
// 1. string comments
config = config.replace(/#.*/g, '')
// 2. join multiline strings
config = config.replace(/'$\s+'/mg, '')
// 3. normalize string literals from ' into "
config = config.replace(/'/g, '"')
return JSON.parse(config)
}
async function getBaseConfigGypi ({ gyp, nodeDir }) {
// try reading $nodeDir/include/node/config.gypi first when:
// 1. --dist-url or --nodedir is specified
// 2. and --force-process-config is not specified
const useCustomHeaders = gyp.opts.nodedir || gyp.opts.disturl || gyp.opts['dist-url']
const shouldReadConfigGypi = useCustomHeaders && !gyp.opts['force-process-config']
if (shouldReadConfigGypi && nodeDir) {
try {
const baseConfigGypiPath = path.resolve(nodeDir, 'include/node/config.gypi')
const baseConfigGypi = await fs.readFile(baseConfigGypiPath)
return parseConfigGypi(baseConfigGypi.toString())
} catch (err) {
log.warn('read config.gypi', err.message)
}
}
// fallback to process.config if it is invalid
return JSON.parse(JSON.stringify(process.config))
}
async function getCurrentConfigGypi ({ gyp, nodeDir, vsInfo, python }) {
const config = await getBaseConfigGypi({ gyp, nodeDir })
if (!config.target_defaults) {
config.target_defaults = {}
}
if (!config.variables) {
config.variables = {}
}
const defaults = config.target_defaults
const variables = config.variables
// don't inherit the "defaults" from the base config.gypi.
// doing so could cause problems in cases where the `node` executable was
// compiled on a different machine (with different lib/include paths) than
// the machine where the addon is being built to
defaults.cflags = []
defaults.defines = []
defaults.include_dirs = []
defaults.libraries = []
// set the default_configuration prop
if ('debug' in gyp.opts) {
defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release'
}
if (!defaults.default_configuration) {
defaults.default_configuration = 'Release'
}
// set the target_arch variable
variables.target_arch = gyp.opts.arch || process.arch || 'ia32'
if (variables.target_arch === 'arm64') {
defaults.msvs_configuration_platform = 'ARM64'
defaults.xcode_configuration_platform = 'arm64'
}
// set the node development directory
variables.nodedir = nodeDir
// set the configured Python path
variables.python = python
// disable -T "thin" static archives by default
variables.standalone_static_library = gyp.opts.thin ? 0 : 1
if (process.platform === 'win32') {
defaults.msbuild_toolset = vsInfo.toolset
if (vsInfo.sdk) {
defaults.msvs_windows_target_platform_version = vsInfo.sdk
}
if (variables.target_arch === 'arm64') {
if (vsInfo.versionMajor > 15 ||
(vsInfo.versionMajor === 15 && vsInfo.versionMajor >= 9)) {
defaults.msvs_enable_marmasm = 1
} else {
log.warn('Compiling ARM64 assembly is only available in\n' +
'Visual Studio 2017 version 15.9 and above')
}
}
variables.msbuild_path = vsInfo.msBuild
if (config.variables.clang === 1) {
config.variables.clang = 0
}
}
// loop through the rest of the opts and add the unknown ones as variables.
// this allows for module-specific configure flags like:
//
// $ node-gyp configure --shared-libxml2
Object.keys(gyp.opts).forEach(function (opt) {
if (opt === 'argv') {
return
}
if (opt in gyp.configDefs) {
return
}
variables[opt.replace(/-/g, '_')] = gyp.opts[opt]
})
return config
}
async function createConfigGypi ({ gyp, buildDir, nodeDir, vsInfo, python }) {
const configFilename = 'config.gypi'
const configPath = path.resolve(buildDir, configFilename)
log.verbose('build/' + configFilename, 'creating config file')
const config = await getCurrentConfigGypi({ gyp, nodeDir, vsInfo, python })
// ensures that any boolean values in config.gypi get stringified
function boolsToString (k, v) {
if (typeof v === 'boolean') {
return String(v)
}
return v
}
log.silly('build/' + configFilename, config)
// now write out the config.gypi file to the build/ dir
const prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step'
const json = JSON.stringify(config, boolsToString, 2)
log.verbose('build/' + configFilename, 'writing out config file: %s', configPath)
await fs.writeFile(configPath, [prefix, json, ''].join('\n'))
return configPath
}
module.exports = {
createConfigGypi,
parseConfigGypi,
getCurrentConfigGypi
}

View file

@ -0,0 +1,39 @@
const fetch = require('make-fetch-happen')
const { promises: fs } = require('graceful-fs')
const log = require('./log')
async function download (gyp, url) {
log.http('GET', url)
const requestOpts = {
headers: {
'User-Agent': `node-gyp v${gyp.version} (node ${process.version})`,
Connection: 'keep-alive'
},
proxy: gyp.opts.proxy,
noProxy: gyp.opts.noproxy
}
const cafile = gyp.opts.cafile
if (cafile) {
requestOpts.ca = await readCAFile(cafile)
}
const res = await fetch(url, requestOpts)
log.http(res.status, res.url)
return res
}
async function readCAFile (filename) {
// The CA file can contain multiple certificates so split on certificate
// boundaries. [\S\s]*? is used to match everything including newlines.
const ca = await fs.readFile(filename, 'utf8')
const re = /(-----BEGIN CERTIFICATE-----[\S\s]*?-----END CERTIFICATE-----)/g
return ca.match(re)
}
module.exports = {
download,
readCAFile
}

View file

@ -0,0 +1,63 @@
'use strict'
const path = require('path')
const log = require('./log')
function findNodeDirectory (scriptLocation, processObj) {
// set dirname and process if not passed in
// this facilitates regression tests
if (scriptLocation === undefined) {
scriptLocation = __dirname
}
if (processObj === undefined) {
processObj = process
}
// Have a look to see what is above us, to try and work out where we are
const npmParentDirectory = path.join(scriptLocation, '../../../..')
log.verbose('node-gyp root', 'npm_parent_directory is ' +
path.basename(npmParentDirectory))
let nodeRootDir = ''
log.verbose('node-gyp root', 'Finding node root directory')
if (path.basename(npmParentDirectory) === 'deps') {
// We are in a build directory where this script lives in
// deps/npm/node_modules/node-gyp/lib
nodeRootDir = path.join(npmParentDirectory, '..')
log.verbose('node-gyp root', 'in build directory, root = ' +
nodeRootDir)
} else if (path.basename(npmParentDirectory) === 'node_modules') {
// We are in a node install directory where this script lives in
// lib/node_modules/npm/node_modules/node-gyp/lib or
// node_modules/npm/node_modules/node-gyp/lib depending on the
// platform
if (processObj.platform === 'win32') {
nodeRootDir = path.join(npmParentDirectory, '..')
} else {
nodeRootDir = path.join(npmParentDirectory, '../..')
}
log.verbose('node-gyp root', 'in install directory, root = ' +
nodeRootDir)
} else {
// We don't know where we are, try working it out from the location
// of the node binary
const nodeDir = path.dirname(processObj.execPath)
const directoryUp = path.basename(nodeDir)
if (directoryUp === 'bin') {
nodeRootDir = path.join(nodeDir, '..')
} else if (directoryUp === 'Release' || directoryUp === 'Debug') {
// If we are a recently built node, and the directory structure
// is that of a repository. If we are on Windows then we only need
// to go one level up, everything else, two
if (processObj.platform === 'win32') {
nodeRootDir = path.join(nodeDir, '..')
} else {
nodeRootDir = path.join(nodeDir, '../..')
}
}
// Else return the default blank, "".
}
return nodeRootDir
}
module.exports = findNodeDirectory

View file

@ -0,0 +1,310 @@
'use strict'
const log = require('./log')
const semver = require('semver')
const { execFile } = require('./util')
const win = process.platform === 'win32'
function getOsUserInfo () {
try {
return require('os').userInfo().username
} catch {}
}
const systemDrive = process.env.SystemDrive || 'C:'
const username = process.env.USERNAME || process.env.USER || getOsUserInfo()
const localAppData = process.env.LOCALAPPDATA || `${systemDrive}\\${username}\\AppData\\Local`
const foundLocalAppData = process.env.LOCALAPPDATA || username
const programFiles = process.env.ProgramW6432 || process.env.ProgramFiles || `${systemDrive}\\Program Files`
const programFilesX86 = process.env['ProgramFiles(x86)'] || `${programFiles} (x86)`
const winDefaultLocationsArray = []
for (const majorMinor of ['311', '310', '39', '38']) {
if (foundLocalAppData) {
winDefaultLocationsArray.push(
`${localAppData}\\Programs\\Python\\Python${majorMinor}\\python.exe`,
`${programFiles}\\Python${majorMinor}\\python.exe`,
`${localAppData}\\Programs\\Python\\Python${majorMinor}-32\\python.exe`,
`${programFiles}\\Python${majorMinor}-32\\python.exe`,
`${programFilesX86}\\Python${majorMinor}-32\\python.exe`
)
} else {
winDefaultLocationsArray.push(
`${programFiles}\\Python${majorMinor}\\python.exe`,
`${programFiles}\\Python${majorMinor}-32\\python.exe`,
`${programFilesX86}\\Python${majorMinor}-32\\python.exe`
)
}
}
class PythonFinder {
static findPython = (...args) => new PythonFinder(...args).findPython()
log = log.withPrefix('find Python')
argsExecutable = ['-c', 'import sys; sys.stdout.buffer.write(sys.executable.encode(\'utf-8\'));']
argsVersion = ['-c', 'import sys; print("%s.%s.%s" % sys.version_info[:3]);']
semverRange = '>=3.6.0'
// These can be overridden for testing:
execFile = execFile
env = process.env
win = win
pyLauncher = 'py.exe'
winDefaultLocations = winDefaultLocationsArray
constructor (configPython) {
this.configPython = configPython
this.errorLog = []
}
// Logs a message at verbose level, but also saves it to be displayed later
// at error level if an error occurs. This should help diagnose the problem.
addLog (message) {
this.log.verbose(message)
this.errorLog.push(message)
}
// Find Python by trying a sequence of possibilities.
// Ignore errors, keep trying until Python is found.
async findPython () {
const SKIP = 0
const FAIL = 1
const toCheck = (() => {
if (this.env.NODE_GYP_FORCE_PYTHON) {
return [{
before: () => {
this.addLog(
'checking Python explicitly set from NODE_GYP_FORCE_PYTHON')
this.addLog('- process.env.NODE_GYP_FORCE_PYTHON is ' +
`"${this.env.NODE_GYP_FORCE_PYTHON}"`)
},
check: () => this.checkCommand(this.env.NODE_GYP_FORCE_PYTHON)
}]
}
const checks = [
{
before: () => {
if (!this.configPython) {
this.addLog(
'Python is not set from command line or npm configuration')
return SKIP
}
this.addLog('checking Python explicitly set from command line or ' +
'npm configuration')
this.addLog('- "--python=" or "npm config get python" is ' +
`"${this.configPython}"`)
},
check: () => this.checkCommand(this.configPython)
},
{
before: () => {
if (!this.env.PYTHON) {
this.addLog('Python is not set from environment variable ' +
'PYTHON')
return SKIP
}
this.addLog('checking Python explicitly set from environment ' +
'variable PYTHON')
this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`)
},
check: () => this.checkCommand(this.env.PYTHON)
}
]
if (this.win) {
checks.push({
before: () => {
this.addLog(
'checking if the py launcher can be used to find Python 3')
},
check: () => this.checkPyLauncher()
})
}
checks.push(...[
{
before: () => { this.addLog('checking if "python3" can be used') },
check: () => this.checkCommand('python3')
},
{
before: () => { this.addLog('checking if "python" can be used') },
check: () => this.checkCommand('python')
}
])
if (this.win) {
for (let i = 0; i < this.winDefaultLocations.length; ++i) {
const location = this.winDefaultLocations[i]
checks.push({
before: () => this.addLog(`checking if Python is ${location}`),
check: () => this.checkExecPath(location)
})
}
}
return checks
})()
for (const check of toCheck) {
const before = check.before()
if (before === SKIP) {
continue
}
if (before === FAIL) {
return this.fail()
}
try {
return await check.check()
} catch (err) {
this.log.silly('runChecks: err = %j', (err && err.stack) || err)
}
}
return this.fail()
}
// Check if command is a valid Python to use.
// Will exit the Python finder on success.
// If on Windows, run in a CMD shell to support BAT/CMD launchers.
async checkCommand (command) {
let exec = command
let args = this.argsExecutable
let shell = false
if (this.win) {
// Arguments have to be manually quoted
exec = `"${exec}"`
args = args.map(a => `"${a}"`)
shell = true
}
this.log.verbose(`- executing "${command}" to get executable path`)
// Possible outcomes:
// - Error: not in PATH, not executable or execution fails
// - Gibberish: the next command to check version will fail
// - Absolute path to executable
try {
const execPath = await this.run(exec, args, shell)
this.addLog(`- executable path is "${execPath}"`)
return this.checkExecPath(execPath)
} catch (err) {
this.addLog(`- "${command}" is not in PATH or produced an error`)
throw err
}
}
// Check if the py launcher can find a valid Python to use.
// Will exit the Python finder on success.
// Distributions of Python on Windows by default install with the "py.exe"
// Python launcher which is more likely to exist than the Python executable
// being in the $PATH.
// Because the Python launcher supports Python 2 and Python 3, we should
// explicitly request a Python 3 version. This is done by supplying "-3" as
// the first command line argument. Since "py.exe -3" would be an invalid
// executable for "execFile", we have to use the launcher to figure out
// where the actual "python.exe" executable is located.
async checkPyLauncher () {
this.log.verbose(`- executing "${this.pyLauncher}" to get Python 3 executable path`)
// Possible outcomes: same as checkCommand
try {
const execPath = await this.run(this.pyLauncher, ['-3', ...this.argsExecutable], false)
this.addLog(`- executable path is "${execPath}"`)
return this.checkExecPath(execPath)
} catch (err) {
this.addLog(`- "${this.pyLauncher}" is not in PATH or produced an error`)
throw err
}
}
// Check if a Python executable is the correct version to use.
// Will exit the Python finder on success.
async checkExecPath (execPath) {
this.log.verbose(`- executing "${execPath}" to get version`)
// Possible outcomes:
// - Error: executable can not be run (likely meaning the command wasn't
// a Python executable and the previous command produced gibberish)
// - Gibberish: somehow the last command produced an executable path,
// this will fail when verifying the version
// - Version of the Python executable
try {
const version = await this.run(execPath, this.argsVersion, false)
this.addLog(`- version is "${version}"`)
const range = new semver.Range(this.semverRange)
let valid = false
try {
valid = range.test(version)
} catch (err) {
this.log.silly('range.test() threw:\n%s', err.stack)
this.addLog(`- "${execPath}" does not have a valid version`)
this.addLog('- is it a Python executable?')
throw err
}
if (!valid) {
this.addLog(`- version is ${version} - should be ${this.semverRange}`)
this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED')
throw new Error(`Found unsupported Python version ${version}`)
}
return this.succeed(execPath, version)
} catch (err) {
this.addLog(`- "${execPath}" could not be run`)
throw err
}
}
// Run an executable or shell command, trimming the output.
async run (exec, args, shell) {
const env = Object.assign({}, this.env)
env.TERM = 'dumb'
const opts = { env, shell }
this.log.silly('execFile: exec = %j', exec)
this.log.silly('execFile: args = %j', args)
this.log.silly('execFile: opts = %j', opts)
try {
const [err, stdout, stderr] = await this.execFile(exec, args, opts)
this.log.silly('execFile result: err = %j', (err && err.stack) || err)
this.log.silly('execFile result: stdout = %j', stdout)
this.log.silly('execFile result: stderr = %j', stderr)
return stdout.trim()
} catch (err) {
this.log.silly('execFile: threw:\n%s', err.stack)
throw err
}
}
succeed (execPath, version) {
this.log.info(`using Python version ${version} found at "${execPath}"`)
return execPath
}
fail () {
const errorLog = this.errorLog.join('\n')
const pathExample = this.win
? 'C:\\Path\\To\\python.exe'
: '/path/to/pythonexecutable'
// For Windows 80 col console, use up to the column before the one marked
// with X (total 79 chars including logger prefix, 58 chars usable here):
// X
const info = [
'**********************************************************',
'You need to install the latest version of Python.',
'Node-gyp should be able to find and use Python. If not,',
'you can try one of the following options:',
`- Use the switch --python="${pathExample}"`,
' (accepted by both node-gyp and npm)',
'- Set the environment variable PYTHON',
'- Set the npm configuration variable python:',
` npm config set python "${pathExample}"`,
'For more information consult the documentation at:',
'https://github.com/nodejs/node-gyp#installation',
'**********************************************************'
].join('\n')
this.log.error(`\n${errorLog}\n\n${info}\n`)
throw new Error('Could not find any Python installation to use')
}
}
module.exports = PythonFinder

View file

@ -0,0 +1,600 @@
'use strict'
const log = require('./log')
const { existsSync } = require('fs')
const { win32: path } = require('path')
const { regSearchKeys, execFile } = require('./util')
class VisualStudioFinder {
static findVisualStudio = (...args) => new VisualStudioFinder(...args).findVisualStudio()
log = log.withPrefix('find VS')
regSearchKeys = regSearchKeys
constructor (nodeSemver, configMsvsVersion) {
this.nodeSemver = nodeSemver
this.configMsvsVersion = configMsvsVersion
this.errorLog = []
this.validVersions = []
}
// Logs a message at verbose level, but also saves it to be displayed later
// at error level if an error occurs. This should help diagnose the problem.
addLog (message) {
this.log.verbose(message)
this.errorLog.push(message)
}
async findVisualStudio () {
this.configVersionYear = null
this.configPath = null
if (this.configMsvsVersion) {
this.addLog('msvs_version was set from command line or npm config')
if (this.configMsvsVersion.match(/^\d{4}$/)) {
this.configVersionYear = parseInt(this.configMsvsVersion, 10)
this.addLog(
`- looking for Visual Studio version ${this.configVersionYear}`)
} else {
this.configPath = path.resolve(this.configMsvsVersion)
this.addLog(
`- looking for Visual Studio installed in "${this.configPath}"`)
}
} else {
this.addLog('msvs_version not set from command line or npm config')
}
if (process.env.VCINSTALLDIR) {
this.envVcInstallDir =
path.resolve(process.env.VCINSTALLDIR, '..')
this.addLog('running in VS Command Prompt, installation path is:\n' +
`"${this.envVcInstallDir}"\n- will only use this version`)
} else {
this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt')
}
const checks = [
() => this.findVisualStudio2019OrNewerFromSpecifiedLocation(),
() => this.findVisualStudio2019OrNewerUsingSetupModule(),
() => this.findVisualStudio2019OrNewer(),
() => this.findVisualStudio2017FromSpecifiedLocation(),
() => this.findVisualStudio2017UsingSetupModule(),
() => this.findVisualStudio2017(),
() => this.findVisualStudio2015(),
() => this.findVisualStudio2013()
]
for (const check of checks) {
const info = await check()
if (info) {
return this.succeed(info)
}
}
return this.fail()
}
succeed (info) {
this.log.info(`using VS${info.versionYear} (${info.version}) found at:` +
`\n"${info.path}"` +
'\nrun with --verbose for detailed information')
return info
}
fail () {
if (this.configMsvsVersion && this.envVcInstallDir) {
this.errorLog.push(
'msvs_version does not match this VS Command Prompt or the',
'installation cannot be used.')
} else if (this.configMsvsVersion) {
// If msvs_version was specified but finding VS failed, print what would
// have been accepted
this.errorLog.push('')
if (this.validVersions) {
this.errorLog.push('valid versions for msvs_version:')
this.validVersions.forEach((version) => {
this.errorLog.push(`- "${version}"`)
})
} else {
this.errorLog.push('no valid versions for msvs_version were found')
}
}
const errorLog = this.errorLog.join('\n')
// For Windows 80 col console, use up to the column before the one marked
// with X (total 79 chars including logger prefix, 62 chars usable here):
// X
const infoLog = [
'**************************************************************',
'You need to install the latest version of Visual Studio',
'including the "Desktop development with C++" workload.',
'For more information consult the documentation at:',
'https://github.com/nodejs/node-gyp#on-windows',
'**************************************************************'
].join('\n')
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
throw new Error('Could not find any Visual Studio installation to use')
}
async findVisualStudio2019OrNewerFromSpecifiedLocation () {
return this.findVSFromSpecifiedLocation([2019, 2022])
}
async findVisualStudio2017FromSpecifiedLocation () {
if (this.nodeSemver.major >= 22) {
this.addLog(
'not looking for VS2017 as it is only supported up to Node.js 21')
return null
}
return this.findVSFromSpecifiedLocation([2017])
}
async findVSFromSpecifiedLocation (supportedYears) {
if (!this.envVcInstallDir) {
return null
}
const info = {
path: path.resolve(this.envVcInstallDir),
// Assume the version specified by the user is correct.
// Since Visual Studio 2015, the Developer Command Prompt sets the
// VSCMD_VER environment variable which contains the version information
// for Visual Studio.
// https://learn.microsoft.com/en-us/visualstudio/ide/reference/command-prompt-powershell?view=vs-2022
version: process.env.VSCMD_VER,
packages: [
'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
'Microsoft.VisualStudio.Component.VC.Tools.ARM64',
// Assume MSBuild exists. It will be checked in processing.
'Microsoft.VisualStudio.VC.MSBuild.Base'
]
}
// Is there a better way to get SDK information?
const envWindowsSDKVersion = process.env.WindowsSDKVersion
const sdkVersionMatched = envWindowsSDKVersion?.match(/^(\d+)\.(\d+)\.(\d+)\..*/)
if (sdkVersionMatched) {
info.packages.push(`Microsoft.VisualStudio.Component.Windows10SDK.${sdkVersionMatched[3]}.Desktop`)
}
// pass for further processing
return this.processData([info], supportedYears)
}
async findVisualStudio2019OrNewerUsingSetupModule () {
return this.findNewVSUsingSetupModule([2019, 2022])
}
async findVisualStudio2017UsingSetupModule () {
if (this.nodeSemver.major >= 22) {
this.addLog(
'not looking for VS2017 as it is only supported up to Node.js 21')
return null
}
return this.findNewVSUsingSetupModule([2017])
}
async findNewVSUsingSetupModule (supportedYears) {
const ps = path.join(process.env.SystemRoot, 'System32',
'WindowsPowerShell', 'v1.0', 'powershell.exe')
const vcInstallDir = this.envVcInstallDir
const checkModuleArgs = [
'-NoProfile',
'-Command',
'&{@(Get-Module -ListAvailable -Name VSSetup).Version.ToString()}'
]
this.log.silly('Running', ps, checkModuleArgs)
const [cErr] = await this.execFile(ps, checkModuleArgs)
if (cErr) {
this.addLog('VSSetup module doesn\'t seem to exist. You can install it via: "Install-Module VSSetup -Scope CurrentUser"')
this.log.silly('VSSetup error = %j', cErr && (cErr.stack || cErr))
return null
}
const filterArg = vcInstallDir !== undefined ? `| where {$_.InstallationPath -eq '${vcInstallDir}' }` : ''
const psArgs = [
'-NoProfile',
'-Command',
`&{Get-VSSetupInstance ${filterArg} | ConvertTo-Json -Depth 3}`
]
this.log.silly('Running', ps, psArgs)
const [err, stdout, stderr] = await this.execFile(ps, psArgs)
let parsedData = this.parseData(err, stdout, stderr)
if (parsedData === null) {
return null
}
this.log.silly('Parsed data', parsedData)
if (!Array.isArray(parsedData)) {
// if there are only 1 result, then Powershell will output non-array
parsedData = [parsedData]
}
// normalize output
parsedData = parsedData.map((info) => {
info.path = info.InstallationPath
info.version = `${info.InstallationVersion.Major}.${info.InstallationVersion.Minor}.${info.InstallationVersion.Build}.${info.InstallationVersion.Revision}`
info.packages = info.Packages.map((p) => p.Id)
return info
})
// pass for further processing
return this.processData(parsedData, supportedYears)
}
// Invoke the PowerShell script to get information about Visual Studio 2019
// or newer installations
async findVisualStudio2019OrNewer () {
return this.findNewVS([2019, 2022])
}
// Invoke the PowerShell script to get information about Visual Studio 2017
async findVisualStudio2017 () {
if (this.nodeSemver.major >= 22) {
this.addLog(
'not looking for VS2017 as it is only supported up to Node.js 21')
return null
}
return this.findNewVS([2017])
}
// Invoke the PowerShell script to get information about Visual Studio 2017
// or newer installations
async findNewVS (supportedYears) {
const ps = path.join(process.env.SystemRoot, 'System32',
'WindowsPowerShell', 'v1.0', 'powershell.exe')
const csFile = path.join(__dirname, 'Find-VisualStudio.cs')
const psArgs = [
'-ExecutionPolicy',
'Unrestricted',
'-NoProfile',
'-Command',
'&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}'
]
this.log.silly('Running', ps, psArgs)
const [err, stdout, stderr] = await this.execFile(ps, psArgs)
const parsedData = this.parseData(err, stdout, stderr, { checkIsArray: true })
if (parsedData === null) {
return null
}
return this.processData(parsedData, supportedYears)
}
// Parse the output of the PowerShell script, make sanity checks
parseData (err, stdout, stderr, sanityCheckOptions) {
const defaultOptions = {
checkIsArray: false
}
// Merging provided options with the default options
const sanityOptions = { ...defaultOptions, ...sanityCheckOptions }
this.log.silly('PS stderr = %j', stderr)
const failPowershell = (failureDetails) => {
this.addLog(
`could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details. \n
Failure details: ${failureDetails}`)
return null
}
if (err) {
this.log.silly('PS err = %j', err && (err.stack || err))
return failPowershell(`${err}`.substring(0, 40))
}
let vsInfo
try {
vsInfo = JSON.parse(stdout)
} catch (e) {
this.log.silly('PS stdout = %j', stdout)
this.log.silly(e)
return failPowershell()
}
if (sanityOptions.checkIsArray && !Array.isArray(vsInfo)) {
this.log.silly('PS stdout = %j', stdout)
return failPowershell('Expected array as output of the PS script')
}
return vsInfo
}
// Process parsed data containing information about VS installations
// Look for the required parts, extract and output them back
processData (vsInfo, supportedYears) {
vsInfo = vsInfo.map((info) => {
this.log.silly(`processing installation: "${info.path}"`)
info.path = path.resolve(info.path)
const ret = this.getVersionInfo(info)
ret.path = info.path
ret.msBuild = this.getMSBuild(info, ret.versionYear)
ret.toolset = this.getToolset(info, ret.versionYear)
ret.sdk = this.getSDK(info)
return ret
})
this.log.silly('vsInfo:', vsInfo)
// Remove future versions or errors parsing version number
// Also remove any unsupported versions
vsInfo = vsInfo.filter((info) => {
if (info.versionYear && supportedYears.indexOf(info.versionYear) !== -1) {
return true
}
this.addLog(`${info.versionYear ? 'unsupported' : 'unknown'} version "${info.version}" found at "${info.path}"`)
return false
})
// Sort to place newer versions first
vsInfo.sort((a, b) => b.versionYear - a.versionYear)
for (let i = 0; i < vsInfo.length; ++i) {
const info = vsInfo[i]
this.addLog(`checking VS${info.versionYear} (${info.version}) found ` +
`at:\n"${info.path}"`)
if (info.msBuild) {
this.addLog('- found "Visual Studio C++ core features"')
} else {
this.addLog('- "Visual Studio C++ core features" missing')
continue
}
if (info.toolset) {
this.addLog(`- found VC++ toolset: ${info.toolset}`)
} else {
this.addLog('- missing any VC++ toolset')
continue
}
if (info.sdk) {
this.addLog(`- found Windows SDK: ${info.sdk}`)
} else {
this.addLog('- missing any Windows SDK')
continue
}
if (!this.checkConfigVersion(info.versionYear, info.path)) {
continue
}
return info
}
this.addLog(
'could not find a version of Visual Studio 2017 or newer to use')
return null
}
// Helper - process version information
getVersionInfo (info) {
const match = /^(\d+)\.(\d+)(?:\..*)?/.exec(info.version)
if (!match) {
this.log.silly('- failed to parse version:', info.version)
return {}
}
this.log.silly('- version match = %j', match)
const ret = {
version: info.version,
versionMajor: parseInt(match[1], 10),
versionMinor: parseInt(match[2], 10)
}
if (ret.versionMajor === 15) {
ret.versionYear = 2017
return ret
}
if (ret.versionMajor === 16) {
ret.versionYear = 2019
return ret
}
if (ret.versionMajor === 17) {
ret.versionYear = 2022
return ret
}
this.log.silly('- unsupported version:', ret.versionMajor)
return {}
}
msBuildPathExists (path) {
return existsSync(path)
}
// Helper - process MSBuild information
getMSBuild (info, versionYear) {
const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base'
const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe')
const msbuildPathArm64 = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'arm64', 'MSBuild.exe')
if (info.packages.indexOf(pkg) !== -1) {
this.log.silly('- found VC.MSBuild.Base')
if (versionYear === 2017) {
return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe')
}
if (versionYear === 2019) {
if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
return msbuildPathArm64
} else {
return msbuildPath
}
}
}
/**
* Visual Studio 2022 doesn't have the MSBuild package.
* Support for compiling _on_ ARM64 was added in MSVC 14.32.31326,
* so let's leverage it if the user has an ARM64 device.
*/
if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
return msbuildPathArm64
} else if (this.msBuildPathExists(msbuildPath)) {
return msbuildPath
}
return null
}
// Helper - process toolset information
getToolset (info, versionYear) {
const vcToolsArm64 = 'VC.Tools.ARM64'
const pkgArm64 = `Microsoft.VisualStudio.Component.${vcToolsArm64}`
const vcToolsX64 = 'VC.Tools.x86.x64'
const pkgX64 = `Microsoft.VisualStudio.Component.${vcToolsX64}`
const express = 'Microsoft.VisualStudio.WDExpress'
if (process.arch === 'arm64' && info.packages.includes(pkgArm64)) {
this.log.silly(`- found ${vcToolsArm64}`)
} else if (info.packages.includes(pkgX64)) {
if (process.arch === 'arm64') {
this.addLog(`- found ${vcToolsX64} on ARM64 platform. Expect less performance and/or link failure with ARM64 binary.`)
} else {
this.log.silly(`- found ${vcToolsX64}`)
}
} else if (info.packages.includes(express)) {
this.log.silly('- found Visual Studio Express (looking for toolset)')
} else {
return null
}
if (versionYear === 2017) {
return 'v141'
} else if (versionYear === 2019) {
return 'v142'
} else if (versionYear === 2022) {
return 'v143'
}
this.log.silly('- invalid versionYear:', versionYear)
return null
}
// Helper - process Windows SDK information
getSDK (info) {
const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK'
const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.'
const win11SDKPrefix = 'Microsoft.VisualStudio.Component.Windows11SDK.'
let Win10or11SDKVer = 0
info.packages.forEach((pkg) => {
if (!pkg.startsWith(win10SDKPrefix) && !pkg.startsWith(win11SDKPrefix)) {
return
}
const parts = pkg.split('.')
if (parts.length > 5 && parts[5] !== 'Desktop') {
this.log.silly('- ignoring non-Desktop Win10/11SDK:', pkg)
return
}
const foundSdkVer = parseInt(parts[4], 10)
if (isNaN(foundSdkVer)) {
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
this.log.silly('- failed to parse Win10/11SDK number:', pkg)
return
}
this.log.silly('- found Win10/11SDK:', foundSdkVer)
Win10or11SDKVer = Math.max(Win10or11SDKVer, foundSdkVer)
})
if (Win10or11SDKVer !== 0) {
return `10.0.${Win10or11SDKVer}.0`
} else if (info.packages.indexOf(win8SDK) !== -1) {
this.log.silly('- found Win8SDK')
return '8.1'
}
return null
}
// Find an installation of Visual Studio 2015 to use
async findVisualStudio2015 () {
if (this.nodeSemver.major >= 19) {
this.addLog(
'not looking for VS2015 as it is only supported up to Node.js 18')
return null
}
return this.findOldVS({
version: '14.0',
versionMajor: 14,
versionMinor: 0,
versionYear: 2015,
toolset: 'v140'
})
}
// Find an installation of Visual Studio 2013 to use
async findVisualStudio2013 () {
if (this.nodeSemver.major >= 9) {
this.addLog(
'not looking for VS2013 as it is only supported up to Node.js 8')
return null
}
return this.findOldVS({
version: '12.0',
versionMajor: 12,
versionMinor: 0,
versionYear: 2013,
toolset: 'v120'
})
}
// Helper - common code for VS2013 and VS2015
async findOldVS (info) {
const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7',
'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7']
const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions'
this.addLog(`looking for Visual Studio ${info.versionYear}`)
try {
let res = await this.regSearchKeys(regVC7, info.version, [])
const vsPath = path.resolve(res, '..')
this.addLog(`- found in "${vsPath}"`)
const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32']
try {
res = await this.regSearchKeys([`${regMSBuild}\\${info.version}`], 'MSBuildToolsPath', msBuildRegOpts)
} catch (err) {
this.addLog('- could not find MSBuild in registry for this version')
return null
}
const msBuild = path.join(res, 'MSBuild.exe')
this.addLog(`- MSBuild in "${msBuild}"`)
if (!this.checkConfigVersion(info.versionYear, vsPath)) {
return null
}
info.path = vsPath
info.msBuild = msBuild
info.sdk = null
return info
} catch (err) {
this.addLog('- not found')
return null
}
}
// After finding a usable version of Visual Studio:
// - add it to validVersions to be displayed at the end if a specific
// version was requested and not found;
// - check if this is the version that was requested.
// - check if this matches the Visual Studio Command Prompt
checkConfigVersion (versionYear, vsPath) {
this.validVersions.push(versionYear)
this.validVersions.push(vsPath)
if (this.configVersionYear && this.configVersionYear !== versionYear) {
this.addLog('- msvs_version does not match this version')
return false
}
if (this.configPath &&
path.relative(this.configPath, vsPath) !== '') {
this.addLog('- msvs_version does not point to this installation')
return false
}
if (this.envVcInstallDir &&
path.relative(this.envVcInstallDir, vsPath) !== '') {
this.addLog('- does not match this Visual Studio Command Prompt')
return false
}
return true
}
async execFile (exec, args) {
return await execFile(exec, args, { encoding: 'utf8' })
}
}
module.exports = VisualStudioFinder

View file

@ -0,0 +1,415 @@
'use strict'
const { createWriteStream, promises: fs } = require('graceful-fs')
const os = require('os')
const { backOff } = require('exponential-backoff')
const tar = require('tar')
const path = require('path')
const { Transform, promises: { pipeline } } = require('stream')
const crypto = require('crypto')
const log = require('./log')
const semver = require('semver')
const { download } = require('./download')
const processRelease = require('./process-release')
const win = process.platform === 'win32'
async function install (gyp, argv) {
log.stdout()
const release = processRelease(argv, gyp, process.version, process.release)
// Detecting target_arch based on logic from create-cnfig-gyp.js. Used on Windows only.
const arch = win ? (gyp.opts.target_arch || gyp.opts.arch || process.arch || 'ia32') : ''
// Used to prevent downloading tarball if only new node.lib is required on Windows.
let shouldDownloadTarball = true
// Determine which node dev files version we are installing
log.verbose('install', 'input version string %j', release.version)
if (!release.semver) {
// could not parse the version string with semver
throw new Error('Invalid version number: ' + release.version)
}
if (semver.lt(release.version, '0.8.0')) {
throw new Error('Minimum target version is `0.8.0` or greater. Got: ' + release.version)
}
// 0.x.y-pre versions are not published yet and cannot be installed. Bail.
if (release.semver.prerelease[0] === 'pre') {
log.verbose('detected "pre" node version', release.version)
if (!gyp.opts.nodedir) {
throw new Error('"pre" versions of node cannot be installed, use the --nodedir flag instead')
}
log.verbose('--nodedir flag was passed; skipping install', gyp.opts.nodedir)
return
}
// flatten version into String
log.verbose('install', 'installing version: %s', release.versionDir)
// the directory where the dev files will be installed
const devDir = path.resolve(gyp.devDir, release.versionDir)
// If '--ensure' was passed, then don't *always* install the version;
// check if it is already installed, and only install when needed
if (gyp.opts.ensure) {
log.verbose('install', '--ensure was passed, so won\'t reinstall if already installed')
try {
await fs.stat(devDir)
} catch (err) {
if (err.code === 'ENOENT') {
log.verbose('install', 'version not already installed, continuing with install', release.version)
try {
return await go()
} catch (err) {
return rollback(err)
}
} else if (err.code === 'EACCES') {
return eaccesFallback(err)
}
throw err
}
log.verbose('install', 'version is already installed, need to check "installVersion"')
const installVersionFile = path.resolve(devDir, 'installVersion')
let installVersion = 0
try {
const ver = await fs.readFile(installVersionFile, 'ascii')
installVersion = parseInt(ver, 10) || 0
} catch (err) {
if (err.code !== 'ENOENT') {
throw err
}
}
log.verbose('got "installVersion"', installVersion)
log.verbose('needs "installVersion"', gyp.package.installVersion)
if (installVersion < gyp.package.installVersion) {
log.verbose('install', 'version is no good; reinstalling')
try {
return await go()
} catch (err) {
return rollback(err)
}
}
log.verbose('install', 'version is good')
if (win) {
log.verbose('on Windows; need to check node.lib')
const nodeLibPath = path.resolve(devDir, arch, 'node.lib')
try {
await fs.stat(nodeLibPath)
} catch (err) {
if (err.code === 'ENOENT') {
log.verbose('install', `version not already installed for ${arch}, continuing with install`, release.version)
try {
shouldDownloadTarball = false
return await go()
} catch (err) {
return rollback(err)
}
} else if (err.code === 'EACCES') {
return eaccesFallback(err)
}
throw err
}
}
} else {
try {
return await go()
} catch (err) {
return rollback(err)
}
}
async function copyDirectory (src, dest) {
try {
await fs.stat(src)
} catch {
throw new Error(`Missing source directory for copy: ${src}`)
}
await fs.mkdir(dest, { recursive: true })
const entries = await fs.readdir(src, { withFileTypes: true })
for (const entry of entries) {
if (entry.isDirectory()) {
await copyDirectory(path.join(src, entry.name), path.join(dest, entry.name))
} else if (entry.isFile()) {
// with parallel installs, copying files may cause file errors on
// Windows so use an exponential backoff to resolve collisions
await backOff(async () => {
try {
await fs.copyFile(path.join(src, entry.name), path.join(dest, entry.name))
} catch (err) {
// if ensure, check if file already exists and that's good enough
if (gyp.opts.ensure && err.code === 'EBUSY') {
try {
await fs.stat(path.join(dest, entry.name))
return
} catch {}
}
throw err
}
})
} else {
throw new Error('Unexpected file directory entry type')
}
}
}
async function go () {
log.verbose('ensuring devDir is created', devDir)
// first create the dir for the node dev files
try {
const created = await fs.mkdir(devDir, { recursive: true })
if (created) {
log.verbose('created devDir', created)
}
} catch (err) {
if (err.code === 'EACCES') {
return eaccesFallback(err)
}
throw err
}
// now download the node tarball
const tarPath = gyp.opts.tarball
let extractErrors = false
let extractCount = 0
const contentShasums = {}
const expectShasums = {}
// checks if a file to be extracted from the tarball is valid.
// only .h header files and the gyp files get extracted
function isValid (path) {
const isValid = valid(path)
if (isValid) {
log.verbose('extracted file from tarball', path)
extractCount++
} else {
// invalid
log.silly('ignoring from tarball', path)
}
return isValid
}
function onwarn (code, message) {
extractErrors = true
log.error('error while extracting tarball', code, message)
}
// download the tarball and extract!
// Ommited on Windows if only new node.lib is required
// on Windows there can be file errors from tar if parallel installs
// are happening (not uncommon with multiple native modules) so
// extract the tarball to a temp directory first and then copy over
const tarExtractDir = win ? await fs.mkdtemp(path.join(os.tmpdir(), 'node-gyp-tmp-')) : devDir
try {
if (shouldDownloadTarball) {
if (tarPath) {
await tar.extract({
file: tarPath,
strip: 1,
filter: isValid,
onwarn,
cwd: tarExtractDir
})
} else {
try {
const res = await download(gyp, release.tarballUrl)
if (res.status !== 200) {
throw new Error(`${res.status} response downloading ${release.tarballUrl}`)
}
await pipeline(
res.body,
// content checksum
new ShaSum((_, checksum) => {
const filename = path.basename(release.tarballUrl).trim()
contentShasums[filename] = checksum
log.verbose('content checksum', filename, checksum)
}),
tar.extract({
strip: 1,
cwd: tarExtractDir,
filter: isValid,
onwarn
})
)
} catch (err) {
// something went wrong downloading the tarball?
if (err.code === 'ENOTFOUND') {
throw new Error('This is most likely not a problem with node-gyp or the package itself and\n' +
'is related to network connectivity. In most cases you are behind a proxy or have bad \n' +
'network settings.')
}
throw err
}
}
// invoked after the tarball has finished being extracted
if (extractErrors || extractCount === 0) {
throw new Error('There was a fatal problem while downloading/extracting the tarball')
}
log.verbose('tarball', 'done parsing tarball')
}
const installVersionPath = path.resolve(tarExtractDir, 'installVersion')
await Promise.all([
// need to download node.lib
...(win ? [downloadNodeLib()] : []),
// write the "installVersion" file
fs.writeFile(installVersionPath, gyp.package.installVersion + '\n'),
// Only download SHASUMS.txt if we downloaded something in need of SHA verification
...(!tarPath || win ? [downloadShasums()] : [])
])
log.verbose('download contents checksum', JSON.stringify(contentShasums))
// check content shasums
for (const k in contentShasums) {
log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k])
if (contentShasums[k] !== expectShasums[k]) {
throw new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])
}
}
// copy over the files from the temp tarball extract directory to devDir
if (tarExtractDir !== devDir) {
await copyDirectory(tarExtractDir, devDir)
}
} finally {
if (tarExtractDir !== devDir) {
try {
// try to cleanup temp dir
await fs.rm(tarExtractDir, { recursive: true })
} catch {
log.warn('failed to clean up temp tarball extract directory')
}
}
}
async function downloadShasums () {
log.verbose('check download content checksum, need to download `SHASUMS256.txt`...')
log.verbose('checksum url', release.shasumsUrl)
const res = await download(gyp, release.shasumsUrl)
if (res.status !== 200) {
throw new Error(`${res.status} status code downloading checksum`)
}
for (const line of (await res.text()).trim().split('\n')) {
const items = line.trim().split(/\s+/)
if (items.length !== 2) {
return
}
// 0035d18e2dcf9aad669b1c7c07319e17abfe3762 ./node-v0.11.4.tar.gz
const name = items[1].replace(/^\.\//, '')
expectShasums[name] = items[0]
}
log.verbose('checksum data', JSON.stringify(expectShasums))
}
async function downloadNodeLib () {
log.verbose('on Windows; need to download `' + release.name + '.lib`...')
const dir = path.resolve(tarExtractDir, arch)
const targetLibPath = path.resolve(dir, release.name + '.lib')
const { libUrl, libPath } = release[arch]
const name = `${arch} ${release.name}.lib`
log.verbose(name, 'dir', dir)
log.verbose(name, 'url', libUrl)
await fs.mkdir(dir, { recursive: true })
log.verbose('streaming', name, 'to:', targetLibPath)
const res = await download(gyp, libUrl)
// Since only required node.lib is downloaded throw error if it is not fetched
if (res.status !== 200) {
throw new Error(`${res.status} status code downloading ${name}`)
}
return pipeline(
res.body,
new ShaSum((_, checksum) => {
contentShasums[libPath] = checksum
log.verbose('content checksum', libPath, checksum)
}),
createWriteStream(targetLibPath)
)
} // downloadNodeLib()
} // go()
/**
* Checks if a given filename is "valid" for this installation.
*/
function valid (file) {
// header files
const extname = path.extname(file)
return extname === '.h' || extname === '.gypi'
}
async function rollback (err) {
log.warn('install', 'got an error, rolling back install')
// roll-back the install if anything went wrong
await gyp.commands.remove([release.versionDir])
throw err
}
/**
* The EACCES fallback is a workaround for npm's `sudo` behavior, where
* it drops the permissions before invoking any child processes (like
* node-gyp). So what happens is the "nobody" user doesn't have
* permission to create the dev dir. As a fallback, make the tmpdir() be
* the dev dir for this installation. This is not ideal, but at least
* the compilation will succeed...
*/
async function eaccesFallback (err) {
const noretry = '--node_gyp_internal_noretry'
if (argv.indexOf(noretry) !== -1) {
throw err
}
const tmpdir = os.tmpdir()
gyp.devDir = path.resolve(tmpdir, '.node-gyp')
let userString = ''
try {
// os.userInfo can fail on some systems, it's not critical here
userString = ` ("${os.userInfo().username}")`
} catch (e) {}
log.warn('EACCES', 'current user%s does not have permission to access the dev dir "%s"', userString, devDir)
log.warn('EACCES', 'attempting to reinstall using temporary dev dir "%s"', gyp.devDir)
if (process.cwd() === tmpdir) {
log.verbose('tmpdir == cwd', 'automatically will remove dev files after to save disk space')
gyp.todo.push({ name: 'remove', args: argv })
}
return gyp.commands.install([noretry].concat(argv))
}
}
class ShaSum extends Transform {
constructor (callback) {
super()
this._callback = callback
this._digester = crypto.createHash('sha256')
}
_transform (chunk, _, callback) {
this._digester.update(chunk)
callback(null, chunk)
}
_flush (callback) {
this._callback(null, this._digester.digest('hex'))
callback()
}
}
module.exports = install
module.exports.usage = 'Install node development files for the specified node version.'

View file

@ -0,0 +1,26 @@
'use strict'
const fs = require('graceful-fs').promises
const log = require('./log')
async function list (gyp, args) {
const devDir = gyp.devDir
log.verbose('list', 'using node-gyp dir:', devDir)
let versions = []
try {
const dir = await fs.readdir(devDir)
if (Array.isArray(dir)) {
versions = dir.filter((v) => v !== 'current')
}
} catch (err) {
if (err && err.code !== 'ENOENT') {
throw err
}
}
return versions
}
module.exports = list
module.exports.usage = 'Prints a listing of the currently installed node development files'

View file

@ -0,0 +1,168 @@
'use strict'
const { log } = require('proc-log')
const { format } = require('util')
// helper to emit log messages with a predefined prefix
const withPrefix = (prefix) => log.LEVELS.reduce((acc, level) => {
acc[level] = (...args) => log[level](prefix, ...args)
return acc
}, {})
// very basic ansi color generator
const COLORS = {
wrap: (str, colors) => {
const codes = colors.filter(c => typeof c === 'number')
return `\x1b[${codes.join(';')}m${str}\x1b[0m`
},
inverse: 7,
fg: {
black: 30,
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35,
cyan: 36,
white: 37
},
bg: {
black: 40,
red: 41,
green: 42,
yellow: 43,
blue: 44,
magenta: 45,
cyan: 46,
white: 47
}
}
class Logger {
#buffer = []
#paused = null
#level = null
#stream = null
// ordered from loudest to quietest
#levels = [{
id: 'silly',
display: 'sill',
style: { inverse: true }
}, {
id: 'verbose',
display: 'verb',
style: { fg: 'cyan', bg: 'black' }
}, {
id: 'info',
style: { fg: 'green' }
}, {
id: 'http',
style: { fg: 'green', bg: 'black' }
}, {
id: 'notice',
style: { fg: 'cyan', bg: 'black' }
}, {
id: 'warn',
display: 'WARN',
style: { fg: 'black', bg: 'yellow' }
}, {
id: 'error',
display: 'ERR!',
style: { fg: 'red', bg: 'black' }
}]
constructor (stream) {
process.on('log', (...args) => this.#onLog(...args))
this.#levels = new Map(this.#levels.map((level, index) => [level.id, { ...level, index }]))
this.level = 'info'
this.stream = stream
log.pause()
}
get stream () {
return this.#stream
}
set stream (stream) {
this.#stream = stream
}
get level () {
return this.#levels.get(this.#level) ?? null
}
set level (level) {
this.#level = this.#levels.get(level)?.id ?? null
}
isVisible (level) {
return this.level?.index <= this.#levels.get(level)?.index ?? -1
}
#onLog (...args) {
const [level] = args
if (level === 'pause') {
this.#paused = true
return
}
if (level === 'resume') {
this.#paused = false
this.#buffer.forEach((b) => this.#log(...b))
this.#buffer.length = 0
return
}
if (this.#paused) {
this.#buffer.push(args)
return
}
this.#log(...args)
}
#color (str, { fg, bg, inverse }) {
if (!this.#stream?.isTTY) {
return str
}
return COLORS.wrap(str, [
COLORS.fg[fg],
COLORS.bg[bg],
inverse && COLORS.inverse
])
}
#log (levelId, msgPrefix, ...args) {
if (!this.isVisible(levelId) || typeof this.#stream?.write !== 'function') {
return
}
const level = this.#levels.get(levelId)
const prefixParts = [
this.#color('gyp', { fg: 'white', bg: 'black' }),
this.#color(level.display ?? level.id, level.style)
]
if (msgPrefix) {
prefixParts.push(this.#color(msgPrefix, { fg: 'magenta' }))
}
const prefix = prefixParts.join(' ').trim() + ' '
const lines = format(...args).split(/\r?\n/).map(l => prefix + l.trim())
this.#stream.write(lines.join('\n') + '\n')
}
}
// used to suppress logs in tests
const NULL_LOGGER = !!process.env.NODE_GYP_NULL_LOGGER
module.exports = {
logger: new Logger(NULL_LOGGER ? null : process.stderr),
stdout: NULL_LOGGER ? () => {} : (...args) => console.log(...args),
withPrefix,
...log
}

View file

@ -0,0 +1,188 @@
'use strict'
const path = require('path')
const nopt = require('nopt')
const log = require('./log')
const childProcess = require('child_process')
const { EventEmitter } = require('events')
const commands = [
// Module build commands
'build',
'clean',
'configure',
'rebuild',
// Development Header File management commands
'install',
'list',
'remove'
]
class Gyp extends EventEmitter {
/**
* Export the contents of the package.json.
*/
package = require('../package.json')
/**
* nopt configuration definitions
*/
configDefs = {
help: Boolean, // everywhere
arch: String, // 'configure'
cafile: String, // 'install'
debug: Boolean, // 'build'
directory: String, // bin
make: String, // 'build'
'msvs-version': String, // 'configure'
ensure: Boolean, // 'install'
solution: String, // 'build' (windows only)
proxy: String, // 'install'
noproxy: String, // 'install'
devdir: String, // everywhere
nodedir: String, // 'configure'
loglevel: String, // everywhere
python: String, // 'configure'
'dist-url': String, // 'install'
tarball: String, // 'install'
jobs: String, // 'build'
thin: String, // 'configure'
'force-process-config': Boolean // 'configure'
}
/**
* nopt shorthands
*/
shorthands = {
release: '--no-debug',
C: '--directory',
debug: '--debug',
j: '--jobs',
silly: '--loglevel=silly',
verbose: '--loglevel=verbose',
silent: '--loglevel=silent'
}
/**
* expose the command aliases for the bin file to use.
*/
aliases = {
ls: 'list',
rm: 'remove'
}
constructor (...args) {
super(...args)
this.devDir = ''
this.commands = commands.reduce((acc, command) => {
acc[command] = (argv) => require('./' + command)(this, argv)
return acc
}, {})
Object.defineProperty(this, 'version', {
enumerable: true,
get: function () { return this.package.version }
})
}
/**
* Parses the given argv array and sets the 'opts',
* 'argv' and 'command' properties.
*/
parseArgv (argv) {
this.opts = nopt(this.configDefs, this.shorthands, argv)
this.argv = this.opts.argv.remain.slice()
const commands = this.todo = []
// create a copy of the argv array with aliases mapped
argv = this.argv.map((arg) => {
// is this an alias?
if (arg in this.aliases) {
arg = this.aliases[arg]
}
return arg
})
// process the mapped args into "command" objects ("name" and "args" props)
argv.slice().forEach((arg) => {
if (arg in this.commands) {
const args = argv.splice(0, argv.indexOf(arg))
argv.shift()
if (commands.length > 0) {
commands[commands.length - 1].args = args
}
commands.push({ name: arg, args: [] })
}
})
if (commands.length > 0) {
commands[commands.length - 1].args = argv.splice(0)
}
// support for inheriting config env variables from npm
const npmConfigPrefix = 'npm_config_'
Object.keys(process.env).forEach((name) => {
if (name.indexOf(npmConfigPrefix) !== 0) {
return
}
const val = process.env[name]
if (name === npmConfigPrefix + 'loglevel') {
log.logger.level = val
} else {
// add the user-defined options to the config
name = name.substring(npmConfigPrefix.length)
// gyp@741b7f1 enters an infinite loop when it encounters
// zero-length options so ensure those don't get through.
if (name) {
// convert names like force_process_config to force-process-config
if (name.includes('_')) {
name = name.replace(/_/g, '-')
}
this.opts[name] = val
}
}
})
if (this.opts.loglevel) {
log.logger.level = this.opts.loglevel
}
log.resume()
}
/**
* Spawns a child process and emits a 'spawn' event.
*/
spawn (command, args, opts) {
if (!opts) {
opts = {}
}
if (!opts.silent && !opts.stdio) {
opts.stdio = [0, 1, 2]
}
const cp = childProcess.spawn(command, args, opts)
log.info('spawn', command)
log.info('spawn args', args)
return cp
}
/**
* Returns the usage instructions for node-gyp.
*/
usage () {
return [
'',
' Usage: node-gyp <command> [options]',
'',
' where <command> is one of:',
commands.map((c) => ' - ' + c + ' - ' + require('./' + c).usage).join('\n'),
'',
'node-gyp@' + this.version + ' ' + path.resolve(__dirname, '..'),
'node@' + process.versions.node
].join('\n')
}
}
module.exports = () => new Gyp()
module.exports.Gyp = Gyp

View file

@ -0,0 +1,146 @@
/* eslint-disable n/no-deprecated-api */
'use strict'
const semver = require('semver')
const url = require('url')
const path = require('path')
const log = require('./log')
// versions where -headers.tar.gz started shipping
const headersTarballRange = '>= 3.0.0 || ~0.12.10 || ~0.10.42'
const bitsre = /\/win-(x86|x64|arm64)\//
const bitsreV3 = /\/win-(x86|ia32|x64)\// // io.js v3.x.x shipped with "ia32" but should
// have been "x86"
// Captures all the logic required to determine download URLs, local directory and
// file names. Inputs come from command-line switches (--target, --dist-url),
// `process.version` and `process.release` where it exists.
function processRelease (argv, gyp, defaultVersion, defaultRelease) {
let version = (semver.valid(argv[0]) && argv[0]) || gyp.opts.target || defaultVersion
const versionSemver = semver.parse(version)
let overrideDistUrl = gyp.opts['dist-url'] || gyp.opts.disturl
let isNamedForLegacyIojs
let name
let distBaseUrl
let baseUrl
let libUrl32
let libUrl64
let libUrlArm64
let tarballUrl
let canGetHeaders
if (!versionSemver) {
// not a valid semver string, nothing we can do
return { version }
}
// flatten version into String
version = versionSemver.version
// defaultVersion should come from process.version so ought to be valid semver
const isDefaultVersion = version === semver.parse(defaultVersion).version
// can't use process.release if we're using --target=x.y.z
if (!isDefaultVersion) {
defaultRelease = null
}
if (defaultRelease) {
// v3 onward, has process.release
name = defaultRelease.name.replace(/io\.js/, 'iojs') // remove the '.' for directory naming purposes
} else {
// old node or alternative --target=
// semver.satisfies() doesn't like prerelease tags so test major directly
isNamedForLegacyIojs = versionSemver.major >= 1 && versionSemver.major < 4
// isNamedForLegacyIojs is required to support Electron < 4 (in particular Electron 3)
// as previously this logic was used to ensure "iojs" was used to download iojs releases
// and "node" for node releases. Unfortunately the logic was broad enough that electron@3
// published release assets as "iojs" so that the node-gyp logic worked. Once Electron@3 has
// been EOL for a while (late 2019) we should remove this hack.
name = isNamedForLegacyIojs ? 'iojs' : 'node'
}
// check for the nvm.sh standard mirror env variables
if (!overrideDistUrl && process.env.NODEJS_ORG_MIRROR) {
overrideDistUrl = process.env.NODEJS_ORG_MIRROR
}
if (overrideDistUrl) {
log.verbose('download', 'using dist-url', overrideDistUrl)
}
if (overrideDistUrl) {
distBaseUrl = overrideDistUrl.replace(/\/+$/, '')
} else {
distBaseUrl = 'https://nodejs.org/dist'
}
distBaseUrl += '/v' + version + '/'
// new style, based on process.release so we have a lot of the data we need
if (defaultRelease && defaultRelease.headersUrl && !overrideDistUrl) {
baseUrl = url.resolve(defaultRelease.headersUrl, './')
libUrl32 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'x86', versionSemver.major)
libUrl64 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'x64', versionSemver.major)
libUrlArm64 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'arm64', versionSemver.major)
tarballUrl = defaultRelease.headersUrl
} else {
// older versions without process.release are captured here and we have to make
// a lot of assumptions, additionally if you --target=x.y.z then we can't use the
// current process.release
baseUrl = distBaseUrl
libUrl32 = resolveLibUrl(name, baseUrl, 'x86', versionSemver.major)
libUrl64 = resolveLibUrl(name, baseUrl, 'x64', versionSemver.major)
libUrlArm64 = resolveLibUrl(name, baseUrl, 'arm64', versionSemver.major)
// making the bold assumption that anything with a version number >3.0.0 will
// have a *-headers.tar.gz file in its dist location, even some frankenstein
// custom version
canGetHeaders = semver.satisfies(versionSemver, headersTarballRange)
tarballUrl = url.resolve(baseUrl, name + '-v' + version + (canGetHeaders ? '-headers' : '') + '.tar.gz')
}
return {
version,
semver: versionSemver,
name,
baseUrl,
tarballUrl,
shasumsUrl: url.resolve(baseUrl, 'SHASUMS256.txt'),
versionDir: (name !== 'node' ? name + '-' : '') + version,
ia32: {
libUrl: libUrl32,
libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl32).path))
},
x64: {
libUrl: libUrl64,
libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl64).path))
},
arm64: {
libUrl: libUrlArm64,
libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrlArm64).path))
}
}
}
function normalizePath (p) {
return path.normalize(p).replace(/\\/g, '/')
}
function resolveLibUrl (name, defaultUrl, arch, versionMajor) {
const base = url.resolve(defaultUrl, './')
const hasLibUrl = bitsre.test(defaultUrl) || (versionMajor === 3 && bitsreV3.test(defaultUrl))
if (!hasLibUrl) {
// let's assume it's a baseUrl then
if (versionMajor >= 1) {
return url.resolve(base, 'win-' + arch + '/' + name + '.lib')
}
// prior to io.js@1.0.0 32-bit node.lib lives in /, 64-bit lives in /x64/
return url.resolve(base, (arch === 'x86' ? '' : arch + '/') + name + '.lib')
}
// else we have a proper url to a .lib, just make sure it's the right arch
return defaultUrl.replace(versionMajor === 3 ? bitsreV3 : bitsre, '/win-' + arch + '/')
}
module.exports = processRelease

View file

@ -0,0 +1,12 @@
'use strict'
async function rebuild (gyp, argv) {
gyp.todo.push(
{ name: 'clean', args: [] }
, { name: 'configure', args: argv }
, { name: 'build', args: [] }
)
}
module.exports = rebuild
module.exports.usage = 'Runs "clean", "configure" and "build" all at once'

View file

@ -0,0 +1,43 @@
'use strict'
const fs = require('graceful-fs').promises
const path = require('path')
const log = require('./log')
const semver = require('semver')
async function remove (gyp, argv) {
const devDir = gyp.devDir
log.verbose('remove', 'using node-gyp dir:', devDir)
// get the user-specified version to remove
let version = argv[0] || gyp.opts.target
log.verbose('remove', 'removing target version:', version)
if (!version) {
throw new Error('You must specify a version number to remove. Ex: "' + process.version + '"')
}
const versionSemver = semver.parse(version)
if (versionSemver) {
// flatten the version Array into a String
version = versionSemver.version
}
const versionPath = path.resolve(gyp.devDir, version)
log.verbose('remove', 'removing development files for version:', version)
// first check if its even installed
try {
await fs.stat(versionPath)
} catch (err) {
if (err.code === 'ENOENT') {
return 'version was already uninstalled: ' + version
}
throw err
}
await fs.rm(versionPath, { recursive: true, force: true })
}
module.exports = remove
module.exports.usage = 'Removes the node development files for the specified version'

View file

@ -0,0 +1,81 @@
'use strict'
const cp = require('child_process')
const path = require('path')
const { openSync, closeSync } = require('graceful-fs')
const log = require('./log')
const execFile = async (...args) => new Promise((resolve) => {
const child = cp.execFile(...args, (...a) => resolve(a))
child.stdin.end()
})
async function regGetValue (key, value, addOpts) {
const outReValue = value.replace(/\W/g, '.')
const outRe = new RegExp(`^\\s+${outReValue}\\s+REG_\\w+\\s+(\\S.*)$`, 'im')
const reg = path.join(process.env.SystemRoot, 'System32', 'reg.exe')
const regArgs = ['query', key, '/v', value].concat(addOpts)
log.silly('reg', 'running', reg, regArgs)
const [err, stdout, stderr] = await execFile(reg, regArgs, { encoding: 'utf8' })
log.silly('reg', 'reg.exe stdout = %j', stdout)
if (err || stderr.trim() !== '') {
log.silly('reg', 'reg.exe err = %j', err && (err.stack || err))
log.silly('reg', 'reg.exe stderr = %j', stderr)
if (err) {
throw err
}
throw new Error(stderr)
}
const result = outRe.exec(stdout)
if (!result) {
log.silly('reg', 'error parsing stdout')
throw new Error('Could not parse output of reg.exe')
}
log.silly('reg', 'found: %j', result[1])
return result[1]
}
async function regSearchKeys (keys, value, addOpts) {
for (const key of keys) {
try {
return await regGetValue(key, value, addOpts)
} catch {
continue
}
}
}
/**
* Returns the first file or directory from an array of candidates that is
* readable by the current user, or undefined if none of the candidates are
* readable.
*/
function findAccessibleSync (logprefix, dir, candidates) {
for (let next = 0; next < candidates.length; next++) {
const candidate = path.resolve(dir, candidates[next])
let fd
try {
fd = openSync(candidate, 'r')
} catch (e) {
// this candidate was not found or not readable, do nothing
log.silly(logprefix, 'Could not open %s: %s', candidate, e.message)
continue
}
closeSync(fd)
log.silly(logprefix, 'Found readable %s', candidate)
return candidate
}
return undefined
}
module.exports = {
execFile,
regGetValue,
regSearchKeys,
findAccessibleSync
}