Skip to content

Commit

Permalink
Improve Node.js version validation
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Feb 6, 2022
1 parent 819e3cd commit e4fb854
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions src/runners/node/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,52 +8,47 @@ import { normalizeNumberString } from '../../config/normalize/transform.js'
import { validateNumberString } from '../../config/normalize/validate/simple.js'
import { wrapError } from '../../error/wrap.js'

// Validate the Node.js version
// We apply `transformVersion` twice (during `validate` and `transform`) so that
// error messages show the non-transformed value, and because `nvexeca()` return
// value is memoized.
export const validateVersion = async function (version) {
const [allowedVersions, { version: versionA }] = await Promise.all([
// Normalize and validate the Node.js version
const transformVersion = async function (version) {
const [versionInfo, allowedVersions] = await Promise.all([
normalizeVersion(version),
getAllowedVersions(),
transformVersion(version),
])

if (!semver.satisfies(versionA, allowedVersions)) {
if (!semver.satisfies(versionInfo.version, allowedVersions)) {
throw new Error(`must be ${allowedVersions}`)
}
}

// We can only allow Node versions that are valid with the runner's code
const getAllowedVersions = async function () {
const cwd = dirname(fileURLToPath(import.meta.url))
const { packageJson } = await readPackageUp({ cwd })
return packageJson.engines.node
return versionInfo.version
}

// Resolve the Node.js version to a full version.
// This also:
// - Downloads the Node.js binary
// - Exposes running it as a `command` with `spawnOptions`
export const transformVersion = async function (version) {
const normalizeVersion = async function (version) {
const versionA = normalizeNumberString(version)
// Lazy loading for performance reasons
const { default: nvexeca } = await import('nvexeca')

try {
return await nvexeca(version, 'node', { progress: true, dry: true })
return await nvexeca(versionA, 'node', { progress: true, dry: true })
} catch (error) {
throw wrapError(error, 'must be a valid Node.js version:')
}
}

// We can only allow Node versions that are valid with the runner's code
const getAllowedVersions = async function () {
const cwd = dirname(fileURLToPath(import.meta.url))
const { packageJson } = await readPackageUp({ cwd })
return packageJson.engines.node
}

export const config = [
{
name: 'version',
validate: validateNumberString,
transform: normalizeNumberString,
},
{
name: 'version',
validate: validateVersion,
transform: transformVersion,
},
]

0 comments on commit e4fb854

Please sign in to comment.