mirror of
https://github.com/actions/setup-node
synced 2026-12-01 11:03:07 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0265558534 |
No files matched your search
@@ -151,32 +151,6 @@ jobs:
|
||||
run: __tests__/verify-node.sh "${{ matrix.node-version }}"
|
||||
shell: bash
|
||||
|
||||
allow-alpha:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
node-version: [27, 27.0.0]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Setup Node with allow-alpha
|
||||
uses: ./
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
allow-alpha: true
|
||||
- name: Verify an alpha is installed
|
||||
run: |
|
||||
nodeVersion=$(node --version)
|
||||
if [[ "$nodeVersion" != *-alpha* ]]; then
|
||||
echo "Expected a Node.js alpha but found $nodeVersion. Move this job to the next alpha release line."
|
||||
exit 1
|
||||
fi
|
||||
shell: bash
|
||||
- name: Verify node and npm
|
||||
run: __tests__/verify-node.sh "${{ matrix.node-version }}"
|
||||
shell: bash
|
||||
|
||||
version-file:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
@@ -296,10 +270,7 @@ jobs:
|
||||
steps:
|
||||
- name: Get node version
|
||||
run: |
|
||||
latestNodeVersion=$(
|
||||
curl -fsSL https://nodejs.org/dist/index.json |
|
||||
jq -r 'first(.[] | select(.version | test("-") | not) | .version)'
|
||||
)
|
||||
latestNodeVersion=$(curl https://nodejs.org/dist/index.json | jq -r '. [0].version')
|
||||
echo "LATEST_NODE_VERSION=$latestNodeVersion" >> $GITHUB_OUTPUT
|
||||
id: version
|
||||
shell: bash
|
||||
|
||||
@@ -59,10 +59,6 @@ See [action.yml](action.yml)
|
||||
# Default: false
|
||||
check-latest: false
|
||||
|
||||
# Allow alpha releases when no stable release matches the version spec.
|
||||
# Default: false
|
||||
allow-alpha: false
|
||||
|
||||
# Target architecture for Node to use. Examples: x86, x64. Will use system architecture by default.
|
||||
# Default: ''. The action use system architecture by default
|
||||
architecture: ''
|
||||
@@ -155,10 +151,9 @@ Examples:
|
||||
|
||||
**Note:** Like the other values, `*` will get the latest [locally-cached Node.js version](https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2204-Readme.md#nodejs), or the latest version from [actions/node-versions](https://github.com/actions/node-versions/blob/main/versions-manifest.json), depending on the [`check-latest`](docs/advanced-usage.md#check-latest-version) input.
|
||||
|
||||
`current`/`latest`/`node` always resolve to the latest stable version from [dist index](https://nodejs.org/dist/index.json) (prerelease entries are skipped).
|
||||
`current`/`latest`/`node` always resolve to the latest [dist version](https://nodejs.org/dist/index.json).
|
||||
That version is then downloaded from actions/node-versions if possible, or directly from Node.js if not.
|
||||
If no stable version is available in the dist index, setup fails with an explicit error.
|
||||
Since it will not always be cached, there is a possibility of hitting rate limits when downloading from dist.
|
||||
Since it will not be cached always, there is possibility of hitting rate limit when downloading from dist
|
||||
|
||||
### Checking in lockfiles
|
||||
|
||||
@@ -238,11 +233,7 @@ jobs:
|
||||
|
||||
## Using `setup-node` on GHES
|
||||
|
||||
`setup-node` comes pre-installed on the appliance with GHES if Actions is enabled. It downloads Node.js distributions from [`actions/node-versions`](https://github.com/actions/node-versions) on github.com, outside the appliance.
|
||||
|
||||
Manifest requests use the GitHub API first, with the `token` input for authentication when supplied. If API retrieval fails, the action tries the manifest on `raw.githubusercontent.com`. This fallback also applies when `check-latest` is enabled. If both manifest sources are unavailable, numeric versions can fall back to nodejs.org. LTS aliases require a manifest to resolve the requested version.
|
||||
|
||||
Unauthenticated API requests are limited to [60 requests per hour per IP](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Supplying a token increases the API rate limit.
|
||||
`setup-node` comes pre-installed on the appliance with GHES if Actions is enabled. When dynamically downloading Nodejs distributions, `setup-node` downloads distributions from [`actions/node-versions`](https://github.com/actions/node-versions) on github.com (outside of the appliance). These calls to `actions/node-versions` are made via unauthenticated requests, which are limited to [60 requests per hour per IP](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). If more requests are made within the time frame, then you will start to see rate-limit errors during downloading that looks like: `##[error]API rate limit exceeded for...`. After that error the action will try to download versions directly from the official site, but it also can have rate limit so it's better to put token.
|
||||
|
||||
To get a higher rate limit, you can [generate a personal access token on github.com](https://github.com/settings/tokens/new) and pass it as the `token` input for the action:
|
||||
|
||||
@@ -259,7 +250,6 @@ If the runner is not able to access github.com, any Nodejs versions requested du
|
||||
## Advanced usage
|
||||
|
||||
- [Check latest version](docs/advanced-usage.md#check-latest-version)
|
||||
- [Allow alpha releases](docs/advanced-usage.md#allow-alpha-releases)
|
||||
- [Using a node version file](docs/advanced-usage.md#node-version-file)
|
||||
- [Using different architectures](docs/advanced-usage.md#architecture)
|
||||
- [Using v8 canary versions](docs/advanced-usage.md#v8-canary-versions)
|
||||
|
||||
@@ -14,8 +14,6 @@ import osm from 'os';
|
||||
import path from 'path';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const nodeVersionsManifestUrl =
|
||||
'https://raw.githubusercontent.com/actions/node-versions/main/versions-manifest.json';
|
||||
|
||||
// Mock @actions modules before importing anything that depends on them
|
||||
jest.unstable_mockModule('@actions/core', () => ({
|
||||
@@ -131,21 +129,6 @@ const {default: nodeV8CanaryTestDist} = await import(
|
||||
import type {INodeVersion} from '../src/distributions/base-models.js';
|
||||
import type {IToolRelease} from '@actions/tool-cache';
|
||||
|
||||
function useRetryTimers() {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
}
|
||||
|
||||
async function runWithRetries() {
|
||||
const setup = main.run();
|
||||
await jest.runAllTimersAsync();
|
||||
await setup;
|
||||
}
|
||||
|
||||
describe('setup-node', () => {
|
||||
let build: InstanceType<typeof OfficialBuilds>;
|
||||
let inputs = {} as any;
|
||||
@@ -250,9 +233,7 @@ describe('setup-node', () => {
|
||||
|
||||
getJsonSpy.mockImplementation((url: any) => {
|
||||
let res: any;
|
||||
if (url === nodeVersionsManifestUrl) {
|
||||
throw new Error('Unable to download raw manifest');
|
||||
} else if (url.includes('/rc')) {
|
||||
if (url.includes('/rc')) {
|
||||
res = <INodeVersion[]>nodeTestDistRc;
|
||||
} else if (url.includes('/nightly')) {
|
||||
res = <INodeVersion[]>nodeTestDistNightly;
|
||||
@@ -668,7 +649,7 @@ describe('setup-node', () => {
|
||||
expect(logSpy).toHaveBeenCalledWith(
|
||||
'Attempt to resolve the latest version from manifest...'
|
||||
);
|
||||
expect(dbgSpy).not.toHaveBeenCalledWith('No manifest cached');
|
||||
expect(dbgSpy).toHaveBeenCalledWith('No manifest cached');
|
||||
expect(dbgSpy).toHaveBeenCalledWith(
|
||||
'Getting manifest from actions/node-versions@main'
|
||||
);
|
||||
@@ -696,7 +677,7 @@ describe('setup-node', () => {
|
||||
expect(logSpy).toHaveBeenCalledWith(
|
||||
'Attempt to resolve the latest version from manifest...'
|
||||
);
|
||||
expect(dbgSpy).not.toHaveBeenCalledWith('No manifest cached');
|
||||
expect(dbgSpy).toHaveBeenCalledWith('No manifest cached');
|
||||
expect(dbgSpy).toHaveBeenCalledWith(
|
||||
'Getting manifest from actions/node-versions@main'
|
||||
);
|
||||
@@ -735,7 +716,7 @@ describe('setup-node', () => {
|
||||
expect(logSpy).toHaveBeenCalledWith(
|
||||
'Attempt to resolve the latest version from manifest...'
|
||||
);
|
||||
expect(dbgSpy).not.toHaveBeenCalledWith('No manifest cached');
|
||||
expect(dbgSpy).toHaveBeenCalledWith('No manifest cached');
|
||||
expect(dbgSpy).toHaveBeenCalledWith(
|
||||
'Getting manifest from actions/node-versions@main'
|
||||
);
|
||||
@@ -792,163 +773,7 @@ describe('setup-node', () => {
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
describe('allow-alpha', () => {
|
||||
const olderAlpha = '27.0.0-alpha.0.0.9';
|
||||
const newestAlpha = '27.0.0-alpha.0.0.10';
|
||||
const files = ['linux-x64'];
|
||||
let releases: INodeVersion[];
|
||||
|
||||
function expectInstalled(version: string) {
|
||||
const toolPath = path.normalize(`/cache/node/${version}/${os.arch}`);
|
||||
cacheSpy.mockImplementation(async () => toolPath);
|
||||
getExecOutputSpy.mockImplementation(async () => ({
|
||||
stdout: `v${version}`,
|
||||
stderr: '',
|
||||
exitCode: 0
|
||||
}));
|
||||
return toolPath;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
os.platform = 'linux';
|
||||
os.arch = 'x64';
|
||||
inputs['allow-alpha'] = 'true';
|
||||
inputs['node-version'] = '27';
|
||||
releases = [
|
||||
{version: `v${olderAlpha}`, files},
|
||||
{version: `v${newestAlpha}`, files},
|
||||
{version: 'v28.0.0-alpha.0.0.0', files},
|
||||
{version: 'v26.1.0', files}
|
||||
];
|
||||
getJsonSpy.mockImplementation(async () => ({result: releases}));
|
||||
findSpy.mockReturnValue('');
|
||||
dlSpy.mockImplementation(async () => '/some/temp/path');
|
||||
exSpy.mockImplementation(async () => '/some/extracted/path');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'27',
|
||||
'27.x',
|
||||
'27.0',
|
||||
'27.0.0',
|
||||
'^27.0.0',
|
||||
'~27.0.0',
|
||||
'>=27.0.0 <28.0.0'
|
||||
])('selects the newest matching alpha for %s', async versionSpec => {
|
||||
inputs['node-version'] = versionSpec;
|
||||
expectInstalled(newestAlpha);
|
||||
|
||||
await main.run();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(dlSpy).toHaveBeenCalledWith(
|
||||
`https://nodejs.org/dist/v${newestAlpha}/node-v${newestAlpha}-linux-x64.tar.gz`,
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['27', '27.0.0'])(
|
||||
'prefers a stable release for %s over a newer alpha',
|
||||
async versionSpec => {
|
||||
inputs['node-version'] = versionSpec;
|
||||
releases.push({version: 'v27.0.0', files});
|
||||
expectInstalled('27.0.0');
|
||||
|
||||
await main.run();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(cacheSpy).toHaveBeenCalledWith(
|
||||
'/some/extracted/path',
|
||||
'node',
|
||||
'27.0.0',
|
||||
'x64'
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([undefined, 'false'])(
|
||||
'does not select an alpha and suggests the input when allow-alpha is %s',
|
||||
async allowAlpha => {
|
||||
inputs['allow-alpha'] = allowAlpha;
|
||||
await main.run();
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
"Unable to find Node version '27' for platform linux and architecture x64. A matching alpha release is available; set 'allow-alpha: true' to use it."
|
||||
);
|
||||
expect(dlSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['latest', 'current', 'node'])(
|
||||
'installs the newest stable release for %s',
|
||||
async versionSpec => {
|
||||
inputs['node-version'] = versionSpec;
|
||||
expectInstalled('26.1.0');
|
||||
|
||||
await main.run();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(cacheSpy).toHaveBeenCalledWith(
|
||||
'/some/extracted/path',
|
||||
'node',
|
||||
'26.1.0',
|
||||
'x64'
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('does not suggest allow-alpha when no alpha matches', async () => {
|
||||
inputs['allow-alpha'] = 'false';
|
||||
inputs['node-version'] = '29';
|
||||
await main.run();
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
"Unable to find Node version '29' for platform linux and architecture x64."
|
||||
);
|
||||
});
|
||||
|
||||
it('respects an explicit prerelease lower bound', async () => {
|
||||
inputs['node-version'] = '>=27.0.0-alpha.0.0.99';
|
||||
await main.run();
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
"Unable to find Node version '>=27.0.0-alpha.0.0.99' for platform linux and architecture x64."
|
||||
);
|
||||
expect(dlSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reuses a cached alpha instead of downloading it again', async () => {
|
||||
const toolPath = expectInstalled(newestAlpha);
|
||||
findSpy.mockImplementation((_tool, version) =>
|
||||
version === `v${newestAlpha}` ? toolPath : ''
|
||||
);
|
||||
|
||||
await main.run();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(dlSpy).not.toHaveBeenCalled();
|
||||
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin'));
|
||||
});
|
||||
|
||||
it('downloads a newer alpha when only an older alpha is cached', async () => {
|
||||
findSpy.mockImplementation((_tool, version) =>
|
||||
version === `v${olderAlpha}` ? `/cache/node/${olderAlpha}/x64` : ''
|
||||
);
|
||||
expectInstalled(newestAlpha);
|
||||
|
||||
await main.run();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(cacheSpy).toHaveBeenCalledWith(
|
||||
'/some/extracted/path',
|
||||
'node',
|
||||
newestAlpha,
|
||||
'x64'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('LTS version', () => {
|
||||
useRetryTimers();
|
||||
|
||||
beforeEach(() => {
|
||||
os.platform = 'linux';
|
||||
os.arch = 'x64';
|
||||
@@ -1104,7 +929,7 @@ describe('setup-node', () => {
|
||||
});
|
||||
|
||||
// act
|
||||
await runWithRetries();
|
||||
await main.run();
|
||||
|
||||
// assert
|
||||
expect(logSpy).toHaveBeenCalledWith(
|
||||
@@ -1114,14 +939,12 @@ describe('setup-node', () => {
|
||||
'Getting manifest from actions/node-versions@main'
|
||||
);
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
'Failed to fetch a valid manifest from the GitHub API and raw URL. API: Unable to download manifest. Raw: Unable to download raw manifest'
|
||||
`Failed to fetch a valid manifest after 3 attempts. Last error: Unable to download manifest`
|
||||
);
|
||||
});
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
describe('latest alias syntax', () => {
|
||||
useRetryTimers();
|
||||
|
||||
it.each(['latest', 'current', 'node'])(
|
||||
'download the %s version if alias is provided',
|
||||
async inputVersion => {
|
||||
@@ -1137,120 +960,16 @@ describe('setup-node', () => {
|
||||
});
|
||||
|
||||
// Act
|
||||
await runWithRetries();
|
||||
await main.run();
|
||||
|
||||
// assert
|
||||
expect(logSpy).toHaveBeenCalledWith(
|
||||
'Failed to fetch a valid manifest from the GitHub API and raw URL. API: Unable to download manifest. Raw: Unable to download raw manifest'
|
||||
'Failed to fetch a valid manifest after 3 attempts. Last error: Unable to download manifest'
|
||||
);
|
||||
|
||||
expect(logSpy).toHaveBeenCalledWith('getting latest node version...');
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['latest', 'current', 'node'])(
|
||||
'skips a newer prerelease and selects the latest stable version for %s',
|
||||
async inputVersion => {
|
||||
// Arrange
|
||||
inputs['node-version'] = inputVersion;
|
||||
const stableVersion = nodeTestDist[0];
|
||||
const prereleaseVersion = {
|
||||
...nodeTestDist[0],
|
||||
version: 'v99.0.0-alpha.1'
|
||||
};
|
||||
|
||||
os.platform = 'darwin';
|
||||
os.arch = 'x64';
|
||||
|
||||
const cleanStableVersion = stableVersion.version.replace(/^v/, '');
|
||||
const toolPath = path.normalize(
|
||||
`/cache/node/${cleanStableVersion}/x64`
|
||||
);
|
||||
|
||||
findSpy.mockImplementation(() => '');
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
throw new Error('Unable to download manifest');
|
||||
});
|
||||
getJsonSpy.mockImplementation((url: any) => {
|
||||
if (url === nodeVersionsManifestUrl) {
|
||||
throw new Error('Unable to download raw manifest');
|
||||
}
|
||||
|
||||
return {result: [prereleaseVersion, ...nodeTestDist]};
|
||||
});
|
||||
dlSpy.mockImplementation(async () => '/some/temp/path');
|
||||
exSpy.mockImplementation(async () => '/some/other/temp/path');
|
||||
cacheSpy.mockImplementation(async () => toolPath);
|
||||
getExecOutputSpy.mockImplementation(async () => ({
|
||||
stdout: `v${cleanStableVersion}\n`,
|
||||
stderr: '',
|
||||
exitCode: 0
|
||||
}));
|
||||
|
||||
// Act
|
||||
await runWithRetries();
|
||||
|
||||
// assert
|
||||
expect(findSpy).toHaveBeenCalledWith(
|
||||
'node',
|
||||
stableVersion.version,
|
||||
'x64'
|
||||
);
|
||||
expect(findSpy).not.toHaveBeenCalledWith(
|
||||
'node',
|
||||
prereleaseVersion.version,
|
||||
'x64'
|
||||
);
|
||||
expect(dlSpy).toHaveBeenCalledWith(
|
||||
`https://nodejs.org/dist/v${cleanStableVersion}/node-v${cleanStableVersion}-darwin-x64.tar.gz`,
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(addPathSpy).toHaveBeenCalledWith(path.join(toolPath, 'bin'));
|
||||
}
|
||||
);
|
||||
|
||||
const prereleaseOnlyIndex = [
|
||||
{...nodeTestDist[0], version: 'v99.0.0-alpha.1'}
|
||||
];
|
||||
|
||||
it.each([
|
||||
['latest', 'an empty index', []],
|
||||
['current', 'an empty index', []],
|
||||
['node', 'an empty index', []],
|
||||
['latest', 'a prerelease-only index', prereleaseOnlyIndex],
|
||||
['current', 'a prerelease-only index', prereleaseOnlyIndex],
|
||||
['node', 'a prerelease-only index', prereleaseOnlyIndex]
|
||||
])(
|
||||
'fails with the stable-version error for %s with %s',
|
||||
async (inputVersion, _description, index) => {
|
||||
// Arrange
|
||||
inputs['node-version'] = inputVersion;
|
||||
|
||||
os.platform = 'darwin';
|
||||
os.arch = 'x64';
|
||||
|
||||
findSpy.mockImplementation(() => '');
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
throw new Error('Unable to download manifest');
|
||||
});
|
||||
getJsonSpy.mockImplementation((url: any) => {
|
||||
if (url === nodeVersionsManifestUrl) {
|
||||
throw new Error('Unable to download raw manifest');
|
||||
}
|
||||
|
||||
return {result: index};
|
||||
});
|
||||
|
||||
// Act
|
||||
await runWithRetries();
|
||||
|
||||
// assert
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
`Unable to find a stable Node version for '${inputVersion}' on platform ${os.platform} and architecture ${os.arch}.`
|
||||
);
|
||||
}
|
||||
},
|
||||
10000
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1276,11 +995,6 @@ describe('setup-node', () => {
|
||||
// assert
|
||||
|
||||
expect(logSpy).toHaveBeenCalledWith('getting latest node version...');
|
||||
expect(findSpy).toHaveBeenCalledWith(
|
||||
'node',
|
||||
expectedVersion.version,
|
||||
'x64'
|
||||
);
|
||||
expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`);
|
||||
}
|
||||
);
|
||||
@@ -1326,272 +1040,53 @@ describe('setup-node', () => {
|
||||
}
|
||||
}, 100000);
|
||||
|
||||
describe('manifest retrieval', () => {
|
||||
useRetryTimers();
|
||||
let installedVersion: string;
|
||||
|
||||
describe('manifest retry and validation', () => {
|
||||
beforeEach(() => {
|
||||
installedVersion = '12.16.2';
|
||||
os.platform = 'linux';
|
||||
os.arch = 'x64';
|
||||
inputs['node-version'] = 'lts/erbium';
|
||||
inputs['token'] = 'manifest-token';
|
||||
whichSpy.mockImplementation(async (tool: string) => tool);
|
||||
findSpy.mockImplementation(() => '');
|
||||
getJsonSpy.mockImplementation((url: string) => ({
|
||||
result:
|
||||
url === nodeVersionsManifestUrl ? nodeTestManifest : nodeTestDist
|
||||
}));
|
||||
dlSpy.mockImplementation(async () => '/some/temp/path');
|
||||
exSpy.mockImplementation(async () => '/some/other/temp/path');
|
||||
cacheSpy.mockImplementation(
|
||||
async (
|
||||
_sourceDirectory: string,
|
||||
_tool: string,
|
||||
version: string,
|
||||
arch: string
|
||||
) => {
|
||||
installedVersion = version;
|
||||
return path.normalize(`/cache/node/${version}/${arch}`);
|
||||
});
|
||||
|
||||
it('retries fetching the manifest and succeeds on a later attempt', async () => {
|
||||
let calls = 0;
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
calls++;
|
||||
if (calls < 2) {
|
||||
throw new Error('transient network failure');
|
||||
}
|
||||
);
|
||||
return <tc.IToolRelease[]>nodeTestManifest;
|
||||
});
|
||||
|
||||
dlSpy.mockImplementation(async () => '/some/temp/path');
|
||||
const toolPath = path.normalize('/cache/node/12.16.2/x64');
|
||||
exSpy.mockImplementation(async () => '/some/other/temp/path');
|
||||
cacheSpy.mockImplementation(async () => toolPath);
|
||||
getExecOutputSpy.mockImplementation(async () => ({
|
||||
stdout: `v${installedVersion}\n`,
|
||||
stdout: `v${path.basename(path.dirname(toolPath))}\n`,
|
||||
stderr: '',
|
||||
exitCode: 0
|
||||
}));
|
||||
});
|
||||
|
||||
describe.each([
|
||||
{versionSpec: 'lts/erbium', checkLatest: 'false'},
|
||||
{versionSpec: 'lts/erbium', checkLatest: 'true'},
|
||||
{versionSpec: '12', checkLatest: 'false'},
|
||||
{versionSpec: '12', checkLatest: 'true'}
|
||||
])('$versionSpec, check-latest: $checkLatest', mode => {
|
||||
beforeEach(() => {
|
||||
inputs['node-version'] = mode.versionSpec;
|
||||
inputs['check-latest'] = mode.checkLatest;
|
||||
});
|
||||
await main.run();
|
||||
|
||||
it('uses the authenticated API without requesting raw', async () => {
|
||||
await runWithRetries();
|
||||
|
||||
expect(getJsonSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(1);
|
||||
expect(getManifestSpy).toHaveBeenCalledWith(
|
||||
'actions',
|
||||
'node-versions',
|
||||
'token manifest-token',
|
||||
'main'
|
||||
);
|
||||
expect(core.setOutput).toHaveBeenCalledWith('node-version', 'v12.16.2');
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([403, 429])(
|
||||
'falls back to raw immediately after API HTTP %i',
|
||||
async statusCode => {
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
throw Object.assign(new Error('API unavailable'), {statusCode});
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(1);
|
||||
expect(getJsonSpy).toHaveBeenCalledTimes(1);
|
||||
expect(getJsonSpy).toHaveBeenCalledWith(nodeVersionsManifestUrl);
|
||||
expect(getManifestSpy.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
getJsonSpy.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(Date.now()).toBe(startedAt);
|
||||
expect(core.setOutput).toHaveBeenCalledWith(
|
||||
'node-version',
|
||||
'v12.16.2'
|
||||
);
|
||||
}
|
||||
expect(calls).toBe(2);
|
||||
expect(logSpy).toHaveBeenCalledWith('Retrying to fetch the manifest...');
|
||||
expect(dbgSpy).toHaveBeenCalledWith(
|
||||
`Found LTS release '12.16.2' for Node version 'lts/erbium'`
|
||||
);
|
||||
});
|
||||
}, 10000);
|
||||
|
||||
it('refreshes the manifest for a later action invocation', async () => {
|
||||
inputs['node-version'] = '12';
|
||||
await runWithRetries();
|
||||
getManifestSpy.mockClear();
|
||||
it('rejects an empty manifest as invalid and retries', async () => {
|
||||
getManifestSpy.mockImplementation(() => []);
|
||||
|
||||
const latestVersion = '12.17.0';
|
||||
getManifestSpy.mockImplementation(() => [
|
||||
{
|
||||
version: latestVersion,
|
||||
stable: true,
|
||||
release_url: `https://github.com/actions/node-versions/releases/tag/${latestVersion}`,
|
||||
files: [
|
||||
{
|
||||
filename: `node-${latestVersion}-linux-x64.tar.gz`,
|
||||
arch: 'x64',
|
||||
platform: 'linux',
|
||||
download_url: `https://github.com/actions/node-versions/releases/download/${latestVersion}/node-${latestVersion}-linux-x64.tar.gz`
|
||||
}
|
||||
]
|
||||
},
|
||||
...nodeTestManifest
|
||||
]);
|
||||
inputs['check-latest'] = 'true';
|
||||
await main.run();
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(logSpy).toHaveBeenCalledWith(`Resolved as '${latestVersion}'`);
|
||||
expect(getJsonSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(1);
|
||||
expect(core.setOutput).toHaveBeenCalledWith('node-version', 'v12.17.0');
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not fetch a manifest for an installed numeric version', async () => {
|
||||
inputs['node-version'] = '12';
|
||||
findSpy.mockReturnValue(path.normalize('/cache/node/12.16.2/x64'));
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(getManifestSpy).not.toHaveBeenCalled();
|
||||
expect(getJsonSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(core.setOutput).toHaveBeenCalledWith('node-version', 'v12.16.2');
|
||||
});
|
||||
|
||||
it('checks the manifest before using an installed version with check-latest', async () => {
|
||||
inputs['node-version'] = '12';
|
||||
inputs['check-latest'] = 'true';
|
||||
findSpy.mockReturnValue(path.normalize('/cache/node/12.16.2/x64'));
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(getJsonSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(1);
|
||||
expect(getManifestSpy.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
findSpy.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses an installed version when check-latest finds no matching release', async () => {
|
||||
os.arch = 'arm64';
|
||||
inputs['node-version'] = '12';
|
||||
inputs['check-latest'] = 'true';
|
||||
findSpy.mockReturnValue(path.normalize('/cache/node/12.16.2/arm64'));
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(getJsonSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(1);
|
||||
expect(logSpy).toHaveBeenCalledWith(
|
||||
'Failed to resolve version 12 from manifest'
|
||||
);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(core.setOutput).toHaveBeenCalledWith('node-version', 'v12.16.2');
|
||||
});
|
||||
|
||||
it('retries a transient API failure before requesting raw', async () => {
|
||||
getManifestSpy.mockImplementationOnce(() => {
|
||||
throw new Error('transient network failure');
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(getJsonSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(2);
|
||||
expect(Date.now() - startedAt).toBe(1000);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['empty', 'unavailable'])(
|
||||
'uses raw after retrying an %s API manifest',
|
||||
async failure => {
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
if (failure === 'unavailable') {
|
||||
throw new Error('API unavailable');
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(3);
|
||||
expect(getJsonSpy).toHaveBeenCalledTimes(1);
|
||||
expect(getJsonSpy).toHaveBeenCalledWith(nodeVersionsManifestUrl);
|
||||
expect(Date.now() - startedAt).toBe(3000);
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(core.setOutput).toHaveBeenCalledWith('node-version', 'v12.16.2');
|
||||
}
|
||||
);
|
||||
|
||||
it.each([
|
||||
['empty', []],
|
||||
['malformed', null]
|
||||
])(
|
||||
'fails LTS setup when the API fails and raw is %s',
|
||||
async (_, result) => {
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
throw Object.assign(new Error('API unavailable'), {statusCode: 429});
|
||||
});
|
||||
getJsonSpy.mockImplementationOnce(() => ({result}));
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(getJsonSpy).toHaveBeenCalledWith(nodeVersionsManifestUrl);
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(1);
|
||||
expect(dlSpy).not.toHaveBeenCalled();
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('API: API unavailable. Raw: The manifest')
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('retains both source errors when LTS setup cannot fetch a manifest', async () => {
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
throw Object.assign(new Error('API unavailable'), {statusCode: 403});
|
||||
});
|
||||
getJsonSpy.mockImplementationOnce(() => {
|
||||
throw new Error('Raw unavailable');
|
||||
});
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(dlSpy).not.toHaveBeenCalled();
|
||||
expect(getManifestSpy).toHaveBeenCalledTimes(3);
|
||||
expect(setFailedSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('API: API unavailable. Raw: Raw unavailable')
|
||||
`Failed to fetch a valid manifest after 3 attempts. Last error: The manifest fetched is empty, truncated, or does not contain any valid tool release entries.`
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['false', 'true'])(
|
||||
'uses Node dist when both sources fail with check-latest: %s',
|
||||
async checkLatest => {
|
||||
inputs['node-version'] = '12';
|
||||
inputs['check-latest'] = checkLatest;
|
||||
getManifestSpy.mockImplementation(() => {
|
||||
throw Object.assign(new Error('API unavailable'), {statusCode: 403});
|
||||
});
|
||||
getJsonSpy.mockImplementation((url: string) => {
|
||||
if (url === nodeVersionsManifestUrl) {
|
||||
throw new Error('Raw unavailable');
|
||||
}
|
||||
return {result: nodeTestDist};
|
||||
});
|
||||
|
||||
await runWithRetries();
|
||||
|
||||
expect(setFailedSpy).not.toHaveBeenCalled();
|
||||
expect(getJsonSpy).toHaveBeenCalledWith(nodeVersionsManifestUrl);
|
||||
expect(dlSpy).toHaveBeenCalledWith(
|
||||
'https://nodejs.org/dist/v12.16.3/node-v12.16.3-linux-x64.tar.gz',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
expect(core.setOutput).toHaveBeenCalledWith('node-version', 'v12.16.3');
|
||||
}
|
||||
);
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
describe('node version verification', () => {
|
||||
|
||||
@@ -11,9 +11,6 @@ inputs:
|
||||
check-latest:
|
||||
description: 'Set this option if you want the action to check for the latest available version that satisfies the version spec.'
|
||||
default: false
|
||||
allow-alpha:
|
||||
description: 'Allow alpha releases when no stable release matches the version spec.'
|
||||
default: false
|
||||
registry-url:
|
||||
description: 'Optional registry to set up for auth. Will set the registry in a project level .npmrc and .yarnrc file, and set up auth to read in from env.NODE_AUTH_TOKEN.'
|
||||
scope:
|
||||
|
||||
Vendored
+30
-101
@@ -98982,21 +98982,12 @@ class NightlyNodejs extends BasePrereleaseNodejs {
|
||||
}
|
||||
}
|
||||
|
||||
;// CONCATENATED MODULE: external "node:path"
|
||||
const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path");
|
||||
var external_node_path_default = /*#__PURE__*/__nccwpck_require__.n(external_node_path_namespaceObject);
|
||||
;// CONCATENATED MODULE: ./src/distributions/official_builds/official_builds.ts
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const nodeVersionsManifestUrl = 'https://raw.githubusercontent.com/actions/node-versions/main/versions-manifest.json';
|
||||
const invalidManifestMessage = 'The manifest fetched is empty, truncated, or does not contain any valid tool release entries.';
|
||||
function isValidManifest(manifest) {
|
||||
return Array.isArray(manifest) && manifest.length > 0;
|
||||
}
|
||||
class OfficialBuilds extends BaseDistribution {
|
||||
constructor(nodeInfo) {
|
||||
super(nodeInfo);
|
||||
@@ -99019,16 +99010,7 @@ class OfficialBuilds extends BaseDistribution {
|
||||
}
|
||||
if (this.nodeInfo.checkLatest) {
|
||||
core_info('Attempt to resolve the latest version from manifest...');
|
||||
let resolvedVersion;
|
||||
try {
|
||||
manifest ??= await this.getManifest();
|
||||
const info = await this.getInfoFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest);
|
||||
resolvedVersion = info?.resolvedVersion;
|
||||
}
|
||||
catch (error) {
|
||||
core_info('Unable to resolve version from manifest...');
|
||||
core_debug(error.message);
|
||||
}
|
||||
const resolvedVersion = await this.resolveVersionFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest);
|
||||
if (resolvedVersion) {
|
||||
this.nodeInfo.versionSpec = resolvedVersion;
|
||||
core_info(`Resolved as '${resolvedVersion}'`);
|
||||
@@ -99075,39 +99057,27 @@ class OfficialBuilds extends BaseDistribution {
|
||||
core_info('Falling back to download directly from Node');
|
||||
}
|
||||
if (!toolPath) {
|
||||
toolPath = await this.downloadDirectlyFromNode(nodeJsVersions);
|
||||
toolPath = await this.downloadDirectlyFromNode();
|
||||
}
|
||||
const installedDir = toolPath;
|
||||
if (this.osPlat != 'win32') {
|
||||
toolPath = external_node_path_default().join(toolPath, 'bin');
|
||||
toolPath = external_path_default().join(toolPath, 'bin');
|
||||
}
|
||||
addPath(toolPath);
|
||||
await this.verifyNodeVersion(installedDir);
|
||||
}
|
||||
addToolPath(toolPath) {
|
||||
if (this.osPlat != 'win32') {
|
||||
toolPath = external_node_path_default().join(toolPath, 'bin');
|
||||
toolPath = external_path_default().join(toolPath, 'bin');
|
||||
}
|
||||
addPath(toolPath);
|
||||
}
|
||||
async downloadDirectlyFromNode(nodeJsVersions) {
|
||||
nodeJsVersions ??= await this.getNodeJsVersions();
|
||||
async downloadDirectlyFromNode() {
|
||||
const nodeJsVersions = await this.getNodeJsVersions();
|
||||
const versions = this.filterVersions(nodeJsVersions);
|
||||
const evaluatedVersion = this.evaluateVersions(versions);
|
||||
if (!evaluatedVersion) {
|
||||
let message = `Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`;
|
||||
if (!this.nodeInfo.allowAlpha && this.findAlphaVersion(versions)) {
|
||||
message += ` A matching alpha release is available; set 'allow-alpha: true' to use it.`;
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
// The tool cache cannot match prereleases against a range such as `27`, so reuse a cached alpha here.
|
||||
if (semver_default().prerelease(evaluatedVersion)) {
|
||||
const cachedPath = find('node', evaluatedVersion, this.translateArchToDistUrl(this.nodeInfo.arch));
|
||||
if (cachedPath) {
|
||||
core_info(`Found in cache @ ${cachedPath}`);
|
||||
return cachedPath;
|
||||
}
|
||||
throw new Error(`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`);
|
||||
}
|
||||
const toolName = this.getNodejsDistInfo(evaluatedVersion);
|
||||
try {
|
||||
@@ -99124,45 +99094,13 @@ class OfficialBuilds extends BaseDistribution {
|
||||
}
|
||||
}
|
||||
evaluateVersions(versions) {
|
||||
let version = '';
|
||||
if (this.isLatestSyntax(this.nodeInfo.versionSpec)) {
|
||||
core_info(`getting latest node version...`);
|
||||
const stableVersion = versions.find(potential => semver_default().prerelease(potential) === null);
|
||||
if (!stableVersion) {
|
||||
throw new Error(`Unable to find a stable Node version for '${this.nodeInfo.versionSpec}' on platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`);
|
||||
}
|
||||
return stableVersion;
|
||||
return versions[0];
|
||||
}
|
||||
const version = super.evaluateVersions(versions);
|
||||
if (version || !this.nodeInfo.allowAlpha) {
|
||||
return version;
|
||||
}
|
||||
// Only fall back to an alpha when no stable release matches the spec.
|
||||
const alphaVersion = this.findAlphaVersion(versions);
|
||||
if (alphaVersion) {
|
||||
core_info(`No stable release matches '${this.nodeInfo.versionSpec}', using ${alphaVersion}`);
|
||||
}
|
||||
return alphaVersion;
|
||||
}
|
||||
// Alphas are matched by their release version, so `27.0.0` or `^27.0.0` select `27.0.0-alpha.*`.
|
||||
// Ranges with explicit prerelease bounds are already handled by standard semver.
|
||||
findAlphaVersion(versions) {
|
||||
const { range } = this.validRange(this.nodeInfo.versionSpec);
|
||||
if (!semver_default().validRange(range) || this.hasPrereleaseBound(range)) {
|
||||
return '';
|
||||
}
|
||||
return (versions.find(potential => {
|
||||
const parsed = semver_default().parse(potential);
|
||||
return (parsed?.prerelease[0] === 'alpha' &&
|
||||
semver_default().satisfies(`${parsed.major}.${parsed.minor}.${parsed.patch}`, range));
|
||||
}) ?? '');
|
||||
}
|
||||
hasPrereleaseBound(range) {
|
||||
// semver desugars `27`, `^27.0.0`, etc. into an upper bound such as `<28.0.0-0`; ignore that synthetic `-0`.
|
||||
return new (semver_default()).Range(range).set.some(comparators => comparators.some(({ operator, semver: bound }) => {
|
||||
const prerelease = bound.prerelease ?? [];
|
||||
const isSyntheticUpperBound = operator === '<' && prerelease.length === 1 && prerelease[0] === 0;
|
||||
return prerelease.length > 0 && !isSyntheticUpperBound;
|
||||
}));
|
||||
version = super.evaluateVersions(versions);
|
||||
return version;
|
||||
}
|
||||
getDistributionUrl(mirror) {
|
||||
const url = mirror || 'https://nodejs.org';
|
||||
@@ -99171,44 +99109,27 @@ class OfficialBuilds extends BaseDistribution {
|
||||
async getManifest() {
|
||||
let lastError;
|
||||
const maxAttempts = 3;
|
||||
core_debug('Getting manifest from actions/node-versions@main');
|
||||
core_debug(`Getting manifest from actions/node-versions@main`);
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
const manifest = await getManifestFromRepo('actions', 'node-versions', this.nodeInfo.mirror && this.nodeInfo.mirrorToken
|
||||
? this.nodeInfo.mirrorToken
|
||||
: this.nodeInfo.auth, 'main');
|
||||
if (isValidManifest(manifest)) {
|
||||
if (Array.isArray(manifest) && manifest.length > 0) {
|
||||
return manifest;
|
||||
}
|
||||
lastError = new Error(invalidManifestMessage);
|
||||
lastError = new Error(`The manifest fetched is empty, truncated, or does not contain any valid tool release entries.`);
|
||||
}
|
||||
catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
const status = error?.statusCode;
|
||||
if (status === 403 || status === 429) {
|
||||
core_debug(`GitHub API returned HTTP ${status}; trying raw manifest.`);
|
||||
break;
|
||||
}
|
||||
catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
}
|
||||
core_debug(`Attempt ${attempt}/${maxAttempts} to fetch the manifest failed: ${lastError.message}`);
|
||||
if (attempt < maxAttempts) {
|
||||
core_info('Retrying to fetch the manifest...');
|
||||
await new Promise(resolve => setTimeout(resolve, 1000 * 2 ** (attempt - 1)));
|
||||
core_info(`Retrying to fetch the manifest...`);
|
||||
await new Promise(resolve => setTimeout(resolve, 1000 * 2 ** (attempt - 1))); // Retry after a delay
|
||||
}
|
||||
}
|
||||
core_debug(`GitHub API manifest fetch failed: ${lastError?.message}`);
|
||||
core_debug(`Getting manifest from ${nodeVersionsManifestUrl}`);
|
||||
try {
|
||||
const { result } = await this.httpClient.getJson(nodeVersionsManifestUrl);
|
||||
if (!isValidManifest(result)) {
|
||||
throw new Error(invalidManifestMessage);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (error) {
|
||||
const message = error.message;
|
||||
throw new Error(`Failed to fetch a valid manifest from the GitHub API and raw URL. API: ${lastError?.message}. Raw: ${message}`, { cause: error });
|
||||
}
|
||||
throw new Error(`Failed to fetch a valid manifest after ${maxAttempts} attempts. Last error: ${lastError?.message}`);
|
||||
}
|
||||
resolveLtsAliasFromManifest(versionSpec, stable, manifest) {
|
||||
const alias = versionSpec.split('lts/')[1]?.toLowerCase();
|
||||
@@ -99234,6 +99155,16 @@ class OfficialBuilds extends BaseDistribution {
|
||||
core_debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`);
|
||||
return release.version.split('.')[0];
|
||||
}
|
||||
async resolveVersionFromManifest(versionSpec, stable, osArch, manifest) {
|
||||
try {
|
||||
const info = await this.getInfoFromManifest(versionSpec, stable, osArch, manifest);
|
||||
return info?.resolvedVersion;
|
||||
}
|
||||
catch (err) {
|
||||
core_info('Unable to resolve version from manifest...');
|
||||
core_debug(err.message);
|
||||
}
|
||||
}
|
||||
async getInfoFromManifest(versionSpec, stable, osArch, manifest) {
|
||||
let info = null;
|
||||
if (!manifest) {
|
||||
@@ -99258,7 +99189,7 @@ class OfficialBuilds extends BaseDistribution {
|
||||
}
|
||||
async verifyNodeVersion(installedDir) {
|
||||
// tool-cache layout: <root>/node/<version>/<arch>
|
||||
const expectedVersion = 'v' + external_node_path_default().basename(external_node_path_default().dirname(installedDir));
|
||||
const expectedVersion = 'v' + external_path_default().basename(external_path_default().dirname(installedDir));
|
||||
let actualVersion = '';
|
||||
try {
|
||||
const { stdout } = await getExecOutput('node', ['--version'], {
|
||||
@@ -99369,11 +99300,9 @@ async function run() {
|
||||
const mirrorToken = getInput('mirror-token');
|
||||
const stable = (getInput('stable') || 'true').toUpperCase() === 'TRUE';
|
||||
const checkLatest = (getInput('check-latest') || 'false').toUpperCase() === 'TRUE';
|
||||
const allowAlpha = (getInput('allow-alpha') || 'false').toUpperCase() === 'TRUE';
|
||||
const nodejsInfo = {
|
||||
versionSpec: version,
|
||||
checkLatest,
|
||||
allowAlpha,
|
||||
auth,
|
||||
stable,
|
||||
arch,
|
||||
|
||||
@@ -74,28 +74,6 @@ steps:
|
||||
- run: npm test
|
||||
```
|
||||
|
||||
## Allow alpha releases
|
||||
|
||||
The `allow-alpha` input defaults to `false`. Set it to `true` to use an alpha release when no stable release matches the requested version.
|
||||
|
||||
Alphas are matched by their release version, so `27`, `27.x`, `27.0.0`, `^27.0.0`, and `~27.0.0` all select the newest Node.js 27 alpha. Ranges with an explicit prerelease bound, such as `>=27.0.0-alpha.3`, use standard semver matching.
|
||||
|
||||
Alpha builds are not published for every platform. For example, Node.js 27 alphas are not available for macOS x64, so setup fails on those runners.
|
||||
|
||||
```yaml
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '27'
|
||||
allow-alpha: true
|
||||
package-manager-cache: false # Disable automatic npm caching if not required
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
```
|
||||
|
||||
Exact alpha versions such as `27.0.0-alpha.0.0.0` work without `allow-alpha`.
|
||||
|
||||
## Node version file
|
||||
|
||||
The `node-version-file` input accepts a path to a file containing the version of Node.js to be used by a project, for example `.nvmrc`, `.node-version`, `.tool-versions`, `mise.toml`, or `package.json`. If both the `node-version` and the `node-version-file` inputs are provided then the `node-version` input is used.
|
||||
|
||||
Generated
+8
-8
@@ -35,7 +35,7 @@
|
||||
"globals": "^17.7.0",
|
||||
"jest": "^30.4.2",
|
||||
"jest-each": "^30.5.2",
|
||||
"prettier": "^3.9.6",
|
||||
"prettier": "^3.9.9",
|
||||
"ts-jest": "^29.4.11",
|
||||
"typescript": "^6.0.3"
|
||||
},
|
||||
@@ -4237,13 +4237,13 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/handlebars": {
|
||||
"version": "4.7.10",
|
||||
"resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.10.tgz",
|
||||
"integrity": "sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==",
|
||||
"version": "4.7.9",
|
||||
"resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.9.tgz",
|
||||
"integrity": "sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"minimist": "^1.2.8",
|
||||
"minimist": "^1.2.5",
|
||||
"neo-async": "^2.6.2",
|
||||
"source-map": "^0.6.1",
|
||||
"wordwrap": "^1.0.0"
|
||||
@@ -5910,9 +5910,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.9.6",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz",
|
||||
"integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==",
|
||||
"version": "3.9.9",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.9.tgz",
|
||||
"integrity": "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@
|
||||
"globals": "^17.7.0",
|
||||
"jest": "^30.4.2",
|
||||
"jest-each": "^30.5.2",
|
||||
"prettier": "^3.9.6",
|
||||
"prettier": "^3.9.9",
|
||||
"ts-jest": "^29.4.11",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ export interface NodeInputs {
|
||||
arch: string;
|
||||
auth?: string;
|
||||
checkLatest: boolean;
|
||||
allowAlpha: boolean;
|
||||
stable: boolean;
|
||||
mirror: string;
|
||||
mirrorToken: string;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import * as core from '@actions/core';
|
||||
import * as exec from '@actions/exec';
|
||||
import * as tc from '@actions/tool-cache';
|
||||
import semver from 'semver';
|
||||
import path from 'path';
|
||||
import * as exec from '@actions/exec';
|
||||
|
||||
import BaseDistribution from '../base-distribution.js';
|
||||
import {NodeInputs, INodeVersion, INodeVersionInfo} from '../base-models.js';
|
||||
@@ -12,15 +10,6 @@ interface INodeRelease extends tc.IToolRelease {
|
||||
lts?: string;
|
||||
}
|
||||
|
||||
const nodeVersionsManifestUrl =
|
||||
'https://raw.githubusercontent.com/actions/node-versions/main/versions-manifest.json';
|
||||
const invalidManifestMessage =
|
||||
'The manifest fetched is empty, truncated, or does not contain any valid tool release entries.';
|
||||
|
||||
function isValidManifest(manifest: unknown): manifest is tc.IToolRelease[] {
|
||||
return Array.isArray(manifest) && manifest.length > 0;
|
||||
}
|
||||
|
||||
export default class OfficialBuilds extends BaseDistribution {
|
||||
constructor(nodeInfo: NodeInputs) {
|
||||
super(nodeInfo);
|
||||
@@ -54,20 +43,12 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
|
||||
if (this.nodeInfo.checkLatest) {
|
||||
core.info('Attempt to resolve the latest version from manifest...');
|
||||
let resolvedVersion: string | undefined;
|
||||
try {
|
||||
manifest ??= await this.getManifest();
|
||||
const info = await this.getInfoFromManifest(
|
||||
this.nodeInfo.versionSpec,
|
||||
this.nodeInfo.stable,
|
||||
osArch,
|
||||
manifest
|
||||
);
|
||||
resolvedVersion = info?.resolvedVersion;
|
||||
} catch (error) {
|
||||
core.info('Unable to resolve version from manifest...');
|
||||
core.debug((error as Error).message);
|
||||
}
|
||||
const resolvedVersion = await this.resolveVersionFromManifest(
|
||||
this.nodeInfo.versionSpec,
|
||||
this.nodeInfo.stable,
|
||||
osArch,
|
||||
manifest
|
||||
);
|
||||
if (resolvedVersion) {
|
||||
this.nodeInfo.versionSpec = resolvedVersion;
|
||||
core.info(`Resolved as '${resolvedVersion}'`);
|
||||
@@ -142,7 +123,7 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
}
|
||||
|
||||
if (!toolPath) {
|
||||
toolPath = await this.downloadDirectlyFromNode(nodeJsVersions);
|
||||
toolPath = await this.downloadDirectlyFromNode();
|
||||
}
|
||||
|
||||
const installedDir = toolPath;
|
||||
@@ -162,30 +143,15 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
core.addPath(toolPath);
|
||||
}
|
||||
|
||||
protected async downloadDirectlyFromNode(nodeJsVersions?: INodeVersion[]) {
|
||||
nodeJsVersions ??= await this.getNodeJsVersions();
|
||||
protected async downloadDirectlyFromNode() {
|
||||
const nodeJsVersions = await this.getNodeJsVersions();
|
||||
const versions = this.filterVersions(nodeJsVersions);
|
||||
const evaluatedVersion = this.evaluateVersions(versions);
|
||||
|
||||
if (!evaluatedVersion) {
|
||||
let message = `Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`;
|
||||
if (!this.nodeInfo.allowAlpha && this.findAlphaVersion(versions)) {
|
||||
message += ` A matching alpha release is available; set 'allow-alpha: true' to use it.`;
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
// The tool cache cannot match prereleases against a range such as `27`, so reuse a cached alpha here.
|
||||
if (semver.prerelease(evaluatedVersion)) {
|
||||
const cachedPath = tc.find(
|
||||
'node',
|
||||
evaluatedVersion,
|
||||
this.translateArchToDistUrl(this.nodeInfo.arch)
|
||||
throw new Error(
|
||||
`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`
|
||||
);
|
||||
if (cachedPath) {
|
||||
core.info(`Found in cache @ ${cachedPath}`);
|
||||
return cachedPath;
|
||||
}
|
||||
}
|
||||
|
||||
const toolName = this.getNodejsDistInfo(evaluatedVersion);
|
||||
@@ -207,70 +173,16 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
}
|
||||
|
||||
protected evaluateVersions(versions: string[]): string {
|
||||
let version = '';
|
||||
|
||||
if (this.isLatestSyntax(this.nodeInfo.versionSpec)) {
|
||||
core.info(`getting latest node version...`);
|
||||
|
||||
const stableVersion = versions.find(
|
||||
potential => semver.prerelease(potential) === null
|
||||
);
|
||||
|
||||
if (!stableVersion) {
|
||||
throw new Error(
|
||||
`Unable to find a stable Node version for '${this.nodeInfo.versionSpec}' on platform ${this.osPlat} and architecture ${this.nodeInfo.arch}.`
|
||||
);
|
||||
}
|
||||
|
||||
return stableVersion;
|
||||
return versions[0];
|
||||
}
|
||||
|
||||
const version = super.evaluateVersions(versions);
|
||||
if (version || !this.nodeInfo.allowAlpha) {
|
||||
return version;
|
||||
}
|
||||
version = super.evaluateVersions(versions);
|
||||
|
||||
// Only fall back to an alpha when no stable release matches the spec.
|
||||
const alphaVersion = this.findAlphaVersion(versions);
|
||||
if (alphaVersion) {
|
||||
core.info(
|
||||
`No stable release matches '${this.nodeInfo.versionSpec}', using ${alphaVersion}`
|
||||
);
|
||||
}
|
||||
|
||||
return alphaVersion;
|
||||
}
|
||||
|
||||
// Alphas are matched by their release version, so `27.0.0` or `^27.0.0` select `27.0.0-alpha.*`.
|
||||
// Ranges with explicit prerelease bounds are already handled by standard semver.
|
||||
private findAlphaVersion(versions: string[]): string {
|
||||
const {range} = this.validRange(this.nodeInfo.versionSpec);
|
||||
if (!semver.validRange(range) || this.hasPrereleaseBound(range)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return (
|
||||
versions.find(potential => {
|
||||
const parsed = semver.parse(potential);
|
||||
return (
|
||||
parsed?.prerelease[0] === 'alpha' &&
|
||||
semver.satisfies(
|
||||
`${parsed.major}.${parsed.minor}.${parsed.patch}`,
|
||||
range
|
||||
)
|
||||
);
|
||||
}) ?? ''
|
||||
);
|
||||
}
|
||||
|
||||
private hasPrereleaseBound(range: string): boolean {
|
||||
// semver desugars `27`, `^27.0.0`, etc. into an upper bound such as `<28.0.0-0`; ignore that synthetic `-0`.
|
||||
return new semver.Range(range).set.some(comparators =>
|
||||
comparators.some(({operator, semver: bound}) => {
|
||||
const prerelease = bound.prerelease ?? [];
|
||||
const isSyntheticUpperBound =
|
||||
operator === '<' && prerelease.length === 1 && prerelease[0] === 0;
|
||||
return prerelease.length > 0 && !isSyntheticUpperBound;
|
||||
})
|
||||
);
|
||||
return version;
|
||||
}
|
||||
|
||||
protected getDistributionUrl(mirror: string): string {
|
||||
@@ -281,7 +193,7 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
private async getManifest(): Promise<tc.IToolRelease[]> {
|
||||
let lastError: Error | undefined;
|
||||
const maxAttempts = 3;
|
||||
core.debug('Getting manifest from actions/node-versions@main');
|
||||
core.debug(`Getting manifest from actions/node-versions@main`);
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
const manifest = await tc.getManifestFromRepo(
|
||||
@@ -292,48 +204,28 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
: this.nodeInfo.auth,
|
||||
'main'
|
||||
);
|
||||
if (isValidManifest(manifest)) {
|
||||
if (Array.isArray(manifest) && manifest.length > 0) {
|
||||
return manifest;
|
||||
}
|
||||
lastError = new Error(invalidManifestMessage);
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
const status = (error as {statusCode?: number})?.statusCode;
|
||||
if (status === 403 || status === 429) {
|
||||
core.debug(
|
||||
`GitHub API returned HTTP ${status}; trying raw manifest.`
|
||||
);
|
||||
break;
|
||||
}
|
||||
lastError = new Error(
|
||||
`The manifest fetched is empty, truncated, or does not contain any valid tool release entries.`
|
||||
);
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
}
|
||||
core.debug(
|
||||
`Attempt ${attempt}/${maxAttempts} to fetch the manifest failed: ${lastError.message}`
|
||||
);
|
||||
if (attempt < maxAttempts) {
|
||||
core.info('Retrying to fetch the manifest...');
|
||||
core.info(`Retrying to fetch the manifest...`);
|
||||
await new Promise(resolve =>
|
||||
setTimeout(resolve, 1000 * 2 ** (attempt - 1))
|
||||
);
|
||||
); // Retry after a delay
|
||||
}
|
||||
}
|
||||
|
||||
core.debug(`GitHub API manifest fetch failed: ${lastError?.message}`);
|
||||
core.debug(`Getting manifest from ${nodeVersionsManifestUrl}`);
|
||||
try {
|
||||
const {result} = await this.httpClient.getJson<tc.IToolRelease[]>(
|
||||
nodeVersionsManifestUrl
|
||||
);
|
||||
if (!isValidManifest(result)) {
|
||||
throw new Error(invalidManifestMessage);
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
const message = (error as Error).message;
|
||||
throw new Error(
|
||||
`Failed to fetch a valid manifest from the GitHub API and raw URL. API: ${lastError?.message}. Raw: ${message}`,
|
||||
{cause: error}
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to fetch a valid manifest after ${maxAttempts} attempts. Last error: ${lastError?.message}`
|
||||
);
|
||||
}
|
||||
|
||||
private resolveLtsAliasFromManifest(
|
||||
@@ -380,6 +272,26 @@ export default class OfficialBuilds extends BaseDistribution {
|
||||
return release.version.split('.')[0];
|
||||
}
|
||||
|
||||
private async resolveVersionFromManifest(
|
||||
versionSpec: string,
|
||||
stable: boolean,
|
||||
osArch: string,
|
||||
manifest: tc.IToolRelease[] | undefined
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
const info = await this.getInfoFromManifest(
|
||||
versionSpec,
|
||||
stable,
|
||||
osArch,
|
||||
manifest
|
||||
);
|
||||
return info?.resolvedVersion;
|
||||
} catch (err) {
|
||||
core.info('Unable to resolve version from manifest...');
|
||||
core.debug((err as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
private async getInfoFromManifest(
|
||||
versionSpec: string,
|
||||
stable: boolean,
|
||||
|
||||
@@ -47,12 +47,9 @@ export async function run() {
|
||||
(core.getInput('stable') || 'true').toUpperCase() === 'TRUE';
|
||||
const checkLatest =
|
||||
(core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE';
|
||||
const allowAlpha =
|
||||
(core.getInput('allow-alpha') || 'false').toUpperCase() === 'TRUE';
|
||||
const nodejsInfo = {
|
||||
versionSpec: version,
|
||||
checkLatest,
|
||||
allowAlpha,
|
||||
auth,
|
||||
stable,
|
||||
arch,
|
||||
|
||||
Reference in new issue
Block a user