This commit is contained in:
aparnajyothi-y
2025-02-24 07:38:19 +00:00
committed by GitHub
13 changed files with 563 additions and 171 deletions

View File

@@ -14,6 +14,12 @@ import * as main from '../src/main';
import * as util from '../src/util'; import * as util from '../src/util';
import OfficialBuilds from '../src/distributions/official_builds/official_builds'; import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import * as installerFactory from '../src/distributions/installer-factory';
jest.mock('../src/distributions/installer-factory', () => ({
getNodejsDistribution: jest.fn()
}));
import {validateMirrorURL} from '../src/util';
describe('main tests', () => { describe('main tests', () => {
let inputs = {} as any; let inputs = {} as any;
let os = {} as any; let os = {} as any;
@@ -38,6 +44,8 @@ describe('main tests', () => {
let setupNodeJsSpy: jest.SpyInstance; let setupNodeJsSpy: jest.SpyInstance;
let validateMirrorUrlSpy: jest.SpyInstance;
beforeEach(() => { beforeEach(() => {
inputs = {}; inputs = {};
@@ -165,6 +173,8 @@ describe('main tests', () => {
}); });
}); });
describe('node-version-file flag', () => { describe('node-version-file flag', () => {
beforeEach(() => { beforeEach(() => {
delete inputs['node-version']; delete inputs['node-version'];
@@ -280,4 +290,6 @@ describe('main tests', () => {
); );
}); });
}); });
}); });

View File

@@ -10,6 +10,8 @@ import osm from 'os';
import path from 'path'; import path from 'path';
import * as main from '../src/main'; import * as main from '../src/main';
import * as auth from '../src/authutil'; import * as auth from '../src/authutil';
import isLtsAlias from '../src/distributions/official_builds/official_builds';
import OfficialBuilds from '../src/distributions/official_builds/official_builds'; import OfficialBuilds from '../src/distributions/official_builds/official_builds';
import {INodeVersion} from '../src/distributions/base-models'; import {INodeVersion} from '../src/distributions/base-models';
@@ -828,4 +830,80 @@ describe('setup-node', () => {
} }
); );
}); });
describe('mirror-url parameter', () => {
it('Download mirror url if mirror-url is provided', async () => {
// Set up test inputs and environment
os.platform = 'linux';
os.arch = 'x64';
inputs['check-latest'] = 'true';
const mirrorURL = (inputs['mirror-url'] =
'https://custom-mirror-url.com');
inputs['token'] = 'faketoken';
// Mock that the version is not in cache (simulate a fresh download)
findSpy.mockImplementation(() => '');
// Mock implementations for other dependencies
const toolPath = path.normalize('/cache/node/11.11.0/x64');
exSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath);
const dlmirrorSpy = jest.fn(); // Create a spy to track the download logic
const mockDownloadNodejs = jest
.spyOn(OfficialBuilds.prototype as any, 'downloadFromMirrorURL')
.mockImplementation(async () => {
dlmirrorSpy();
});
// Run the main method or your logic that invokes `downloadFromMirrorURL`
await main.run(); // This should internally call `downloadFromMirrorURL`
// Prepare the expected path after download
const expPath = path.join(toolPath, 'bin');
// Assert that the spy was called, meaning the download logic was triggered
expect(dlmirrorSpy).toHaveBeenCalled(); // This verifies that the download occurred
// Other assertions to verify the flow
expect(exSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(
`Attempting to download from ${mirrorURL}...`
);
expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
// Clean up mocks after the test
mockDownloadNodejs.mockRestore(); // Ensure to restore the original method after the test
});
it('fallback to default if mirror url is not provided', async () => {
os.platform = 'linux';
os.arch = 'x64';
inputs['node-version'] = '11';
inputs['check-latest'] = 'true';
inputs['always-auth'] = false;
inputs['token'] = 'faketoken';
dlSpy.mockImplementation(async () => '/some/temp/path');
const toolPath = path.normalize('/cache/node/12.11.0/x64');
exSpy.mockImplementation(async () => '/some/other/temp/path');
cacheSpy.mockImplementation(async () => toolPath);
const dlmirrorSpy = jest.fn();
dlmirrorSpy.mockImplementation(async () => 'mocked-download-path');
await main.run();
const expPath = path.join(toolPath, 'bin');
expect(dlSpy).toHaveBeenCalled();
expect(exSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith(
'Attempt to resolve the latest version from manifest...'
);
expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`);
});
});
}); });

View File

@@ -16,6 +16,9 @@ inputs:
default: false default: false
registry-url: 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.' 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.'
mirror-url:
description: 'Custom mirror URL to download Node.js from (optional)'
required: false
scope: scope:
description: 'Optional scope for authenticating against scoped registries. Will fall back to the repository owner when using the GitHub Packages registry (https://npm.pkg.github.com/).' description: 'Optional scope for authenticating against scoped registries. Will fall back to the repository owner when using the GitHub Packages registry (https://npm.pkg.github.com/).'
token: token:

View File

@@ -91098,7 +91098,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unique = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0; exports.unique = exports.validateMirrorURL = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0;
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514)); const exec = __importStar(__nccwpck_require__(1514));
const io = __importStar(__nccwpck_require__(7436)); const io = __importStar(__nccwpck_require__(7436));
@@ -91186,6 +91186,15 @@ function getToolVersion(tool, options) {
} }
}); });
} }
function validateMirrorURL(mirrorURL) {
if (mirrorURL === ' ' || mirrorURL.trim() === 'undefined') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
}
else {
return mirrorURL;
}
}
exports.validateMirrorURL = validateMirrorURL;
const unique = () => { const unique = () => {
const encountered = new Set(); const encountered = new Set();
return (value) => { return (value) => {

268
dist/setup/index.js vendored
View File

@@ -100154,6 +100154,32 @@ class BaseDistribution {
return response.result || []; return response.result || [];
}); });
} }
getMirrorUrlVersions() {
return __awaiter(this, void 0, void 0, function* () {
const initialUrl = this.getDistributionUrl();
const dataUrl = `${initialUrl}/index.json`;
try {
const response = yield this.httpClient.getJson(dataUrl);
return response.result || [];
}
catch (err) {
if (err instanceof Error &&
err.message.includes('getaddrinfo EAI_AGAIN')) {
core.error(`Network error: Failed to resolve the server at ${dataUrl}.
Please check your DNS settings or verify that the URL is correct.`);
}
else if (err instanceof hc.HttpClientError && err.statusCode === 404) {
core.error(`404 Error: Unable to find versions at ${dataUrl}.
Please verify that the mirror URL is valid.`);
}
else {
core.error(`Failed to fetch Node.js versions from ${dataUrl}.
Please check the URL and try again.}`);
}
throw err;
}
});
}
getNodejsDistInfo(version) { getNodejsDistInfo(version) {
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);
version = semver_1.default.clean(version) || ''; version = semver_1.default.clean(version) || '';
@@ -100174,6 +100200,26 @@ class BaseDistribution {
fileName: fileName fileName: fileName
}; };
} }
getNodejsMirrorURLInfo(version) {
const mirrorURL = this.nodeInfo.mirrorURL;
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);
version = semver_1.default.clean(version) || '';
const fileName = this.osPlat == 'win32'
? `node-v${version}-win-${osArch}`
: `node-v${version}-${this.osPlat}-${osArch}`;
const urlFileName = this.osPlat == 'win32'
? this.nodeInfo.arch === 'arm64'
? `${fileName}.zip`
: `${fileName}.7z`
: `${fileName}.tar.gz`;
const url = `${mirrorURL}/v${version}/${urlFileName}`;
return {
downloadUrl: url,
resolvedVersion: version,
arch: osArch,
fileName: fileName
};
}
downloadNodejs(info) { downloadNodejs(info) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let downloadPath = ''; let downloadPath = '';
@@ -100185,8 +100231,15 @@ class BaseDistribution {
if (err instanceof tc.HTTPError && if (err instanceof tc.HTTPError &&
err.httpStatusCode == 404 && err.httpStatusCode == 404 &&
this.osPlat == 'win32') { this.osPlat == 'win32') {
return yield this.acquireWindowsNodeFromFallbackLocation(info.resolvedVersion, info.arch); return yield this.acquireWindowsNodeFromFallbackLocation(info.resolvedVersion, info.arch, info.downloadUrl);
} }
// Handle network-related issues (e.g., DNS resolution failures)
if (err instanceof Error &&
err.message.includes('getaddrinfo EAI_AGAIN')) {
core.error(`Network error: Failed to resolve the server at ${info.downloadUrl}.
This could be due to a DNS resolution issue. Please verify the URL or check your network connection.`);
}
core.error(`Download failed from ${info.downloadUrl}. Please check the URl and try again.`);
throw err; throw err;
} }
const toolPath = yield this.extractArchive(downloadPath, info, true); const toolPath = yield this.extractArchive(downloadPath, info, true);
@@ -100202,8 +100255,9 @@ class BaseDistribution {
return { range: valid, options }; return { range: valid, options };
} }
acquireWindowsNodeFromFallbackLocation(version_1) { acquireWindowsNodeFromFallbackLocation(version_1) {
return __awaiter(this, arguments, void 0, function* (version, arch = os_1.default.arch()) { return __awaiter(this, arguments, void 0, function* (version, arch = os_1.default.arch(), downloadUrl) {
const initialUrl = this.getDistributionUrl(); const initialUrl = this.getDistributionUrl();
core.info('url: ' + initialUrl);
const osArch = this.translateArchToDistUrl(arch); const osArch = this.translateArchToDistUrl(arch);
// Create temporary folder to download to // Create temporary folder to download to
const tempDownloadFolder = `temp_${(0, uuid_1.v4)()}`; const tempDownloadFolder = `temp_${(0, uuid_1.v4)()}`;
@@ -100217,6 +100271,9 @@ class BaseDistribution {
exeUrl = `${initialUrl}/v${version}/win-${osArch}/node.exe`; exeUrl = `${initialUrl}/v${version}/win-${osArch}/node.exe`;
libUrl = `${initialUrl}/v${version}/win-${osArch}/node.lib`; libUrl = `${initialUrl}/v${version}/win-${osArch}/node.lib`;
core.info(`Downloading only node binary from ${exeUrl}`); core.info(`Downloading only node binary from ${exeUrl}`);
if (downloadUrl != exeUrl) {
core.error('unable to download node binary with the provided URL. Please check and try again');
}
const exePath = yield tc.downloadTool(exeUrl); const exePath = yield tc.downloadTool(exeUrl);
yield io.cp(exePath, path.join(tempDir, 'node.exe')); yield io.cp(exePath, path.join(tempDir, 'node.exe'));
const libPath = yield tc.downloadTool(libUrl); const libPath = yield tc.downloadTool(libUrl);
@@ -100392,7 +100449,12 @@ class NightlyNodejs extends base_distribution_prerelease_1.default {
this.distribution = 'nightly'; this.distribution = 'nightly';
} }
getDistributionUrl() { getDistributionUrl() {
return 'https://nodejs.org/download/nightly'; if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
else {
return 'https://nodejs.org/download/nightly';
}
} }
} }
exports["default"] = NightlyNodejs; exports["default"] = NightlyNodejs;
@@ -100451,73 +100513,93 @@ class OfficialBuilds extends base_distribution_1.default {
} }
setupNodeJs() { setupNodeJs() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
var _a; var _a, _b;
let manifest; if (this.nodeInfo.mirrorURL) {
let nodeJsVersions; let downloadPath = '';
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch); try {
if (this.isLtsAlias(this.nodeInfo.versionSpec)) { core.info(`Attempting to download using mirror URL...`);
core.info('Attempt to resolve LTS alias from manifest...'); downloadPath = yield this.downloadFromMirrorURL(); // Attempt to download from the mirror
// No try-catch since it's not possible to resolve LTS alias without manifest core.info('downloadPath from downloadFromMirrorURL() ' + downloadPath);
manifest = yield this.getManifest();
this.nodeInfo.versionSpec = this.resolveLtsAliasFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, manifest);
}
if (this.isLatestSyntax(this.nodeInfo.versionSpec)) {
nodeJsVersions = yield this.getNodeJsVersions();
const versions = this.filterVersions(nodeJsVersions);
this.nodeInfo.versionSpec = this.evaluateVersions(versions);
core.info('getting latest node version...');
}
if (this.nodeInfo.checkLatest) {
core.info('Attempt to resolve the latest version from manifest...');
const resolvedVersion = yield this.resolveVersionFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest);
if (resolvedVersion) {
this.nodeInfo.versionSpec = resolvedVersion;
core.info(`Resolved as '${resolvedVersion}'`);
}
else {
core.info(`Failed to resolve version ${this.nodeInfo.versionSpec} from manifest`);
}
}
let toolPath = this.findVersionInHostedToolCacheDirectory();
if (toolPath) {
core.info(`Found in cache @ ${toolPath}`);
this.addToolPath(toolPath);
return;
}
let downloadPath = '';
try {
core.info(`Attempting to download ${this.nodeInfo.versionSpec}...`);
const versionInfo = yield this.getInfoFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest);
if (versionInfo) {
core.info(`Acquiring ${versionInfo.resolvedVersion} - ${versionInfo.arch} from ${versionInfo.downloadUrl}`);
downloadPath = yield tc.downloadTool(versionInfo.downloadUrl, undefined, this.nodeInfo.auth);
if (downloadPath) { if (downloadPath) {
toolPath = yield this.extractArchive(downloadPath, versionInfo, false); const toolPath = downloadPath;
} }
} }
else { catch (err) {
core.info('Not found in manifest. Falling back to download directly from Node');
}
}
catch (err) {
// Rate limit?
if (err instanceof tc.HTTPError &&
(err.httpStatusCode === 403 || err.httpStatusCode === 429)) {
core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`);
}
else {
core.info(err.message); core.info(err.message);
core.info('Download failed');
core.debug((_a = err.stack) !== null && _a !== void 0 ? _a : 'empty stack');
} }
core.debug((_a = err.stack) !== null && _a !== void 0 ? _a : 'empty stack');
core.info('Falling back to download directly from Node');
} }
if (!toolPath) { else {
toolPath = yield this.downloadDirectlyFromNode(); core.info('No mirror URL found. Falling back to default setup...');
core.info('Setup Node.js');
let manifest;
let nodeJsVersions;
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);
if (this.isLtsAlias(this.nodeInfo.versionSpec)) {
core.info('Attempt to resolve LTS alias from manifest...');
// No try-catch since it's not possible to resolve LTS alias without manifest
manifest = yield this.getManifest();
this.nodeInfo.versionSpec = this.resolveLtsAliasFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, manifest);
}
if (this.isLatestSyntax(this.nodeInfo.versionSpec)) {
nodeJsVersions = yield this.getNodeJsVersions();
const versions = this.filterVersions(nodeJsVersions);
this.nodeInfo.versionSpec = this.evaluateVersions(versions);
core.info('getting latest node version...');
}
if (this.nodeInfo.checkLatest) {
core.info('Attempt to resolve the latest version from manifest...');
const resolvedVersion = yield this.resolveVersionFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest);
if (resolvedVersion) {
this.nodeInfo.versionSpec = resolvedVersion;
core.info(`Resolved as '${resolvedVersion}'`);
}
else {
core.info(`Failed to resolve version ${this.nodeInfo.versionSpec} from manifest`);
}
}
let toolPath = this.findVersionInHostedToolCacheDirectory();
if (toolPath) {
core.info(`Found in cache @ ${toolPath}`);
this.addToolPath(toolPath);
return;
}
let downloadPath = '';
try {
core.info(`Attempting to download ${this.nodeInfo.versionSpec}...`);
const versionInfo = yield this.getInfoFromManifest(this.nodeInfo.versionSpec, this.nodeInfo.stable, osArch, manifest);
if (versionInfo) {
core.info(`Acquiring ${versionInfo.resolvedVersion} - ${versionInfo.arch} from ${versionInfo.downloadUrl}`);
downloadPath = yield tc.downloadTool(versionInfo.downloadUrl, undefined, this.nodeInfo.auth);
if (downloadPath) {
toolPath = yield this.extractArchive(downloadPath, versionInfo, false);
}
}
else {
core.info('Not found in manifest. Falling back to download directly from Node');
}
}
catch (err) {
// Rate limit?
if (err instanceof tc.HTTPError &&
(err.httpStatusCode === 403 || err.httpStatusCode === 429)) {
core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`);
}
else {
core.info(err.message);
}
core.debug((_b = err.stack) !== null && _b !== void 0 ? _b : 'empty stack');
core.info('Falling back to download directly from Node');
}
if (!toolPath) {
toolPath = yield this.downloadDirectlyFromNode();
}
if (this.osPlat != 'win32') {
toolPath = path_1.default.join(toolPath, 'bin');
}
core.addPath(toolPath);
} }
if (this.osPlat != 'win32') {
toolPath = path_1.default.join(toolPath, 'bin');
}
core.addPath(toolPath);
}); });
} }
addToolPath(toolPath) { addToolPath(toolPath) {
@@ -100559,6 +100641,9 @@ class OfficialBuilds extends base_distribution_1.default {
return version; return version;
} }
getDistributionUrl() { getDistributionUrl() {
if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
return `https://nodejs.org/dist`; return `https://nodejs.org/dist`;
} }
getManifest() { getManifest() {
@@ -100626,6 +100711,33 @@ class OfficialBuilds extends base_distribution_1.default {
isLatestSyntax(versionSpec) { isLatestSyntax(versionSpec) {
return ['current', 'latest', 'node'].includes(versionSpec); return ['current', 'latest', 'node'].includes(versionSpec);
} }
downloadFromMirrorURL() {
return __awaiter(this, void 0, void 0, function* () {
const nodeJsVersions = yield this.getMirrorUrlVersions();
const versions = this.filterVersions(nodeJsVersions);
const evaluatedVersion = this.evaluateVersions(versions);
if (!evaluatedVersion) {
throw new Error(`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch} from the provided mirror-url ${this.nodeInfo.mirrorURL}. Please check the mirror-url`);
}
const toolName = this.getNodejsMirrorURLInfo(evaluatedVersion);
try {
const toolPath = yield this.downloadNodejs(toolName);
return toolPath;
}
catch (error) {
if (error instanceof tc.HTTPError && error.httpStatusCode === 404) {
core.error(`Node version ${this.nodeInfo.versionSpec} for platform ${this.osPlat} and architecture ${this.nodeInfo.arch} was found but failed to download. ` +
'This usually happens when downloadable binaries are not fully updated at https://nodejs.org/. ' +
'To resolve this issue you may either fall back to the older version or try again later.');
}
else {
// For any other error type, you can log the error message.
core.error(`An unexpected error occurred like url might not correct`);
}
throw error;
}
});
}
} }
exports["default"] = OfficialBuilds; exports["default"] = OfficialBuilds;
@@ -100647,7 +100759,12 @@ class RcBuild extends base_distribution_1.default {
super(nodeInfo); super(nodeInfo);
} }
getDistributionUrl() { getDistributionUrl() {
return 'https://nodejs.org/download/rc'; if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
else {
return 'https://nodejs.org/download/rc';
}
} }
} }
exports["default"] = RcBuild; exports["default"] = RcBuild;
@@ -100671,7 +100788,12 @@ class CanaryBuild extends base_distribution_prerelease_1.default {
this.distribution = 'v8-canary'; this.distribution = 'v8-canary';
} }
getDistributionUrl() { getDistributionUrl() {
return 'https://nodejs.org/download/v8-canary'; if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
else {
return 'https://nodejs.org/download/v8-canary';
}
} }
} }
exports["default"] = CanaryBuild; exports["default"] = CanaryBuild;
@@ -100748,6 +100870,8 @@ function run() {
if (!arch) { if (!arch) {
arch = os_1.default.arch(); arch = os_1.default.arch();
} }
const mirrorurl = core.getInput('mirror-url');
const mirrorURL = (0, util_1.validateMirrorURL)(mirrorurl);
if (version) { if (version) {
const token = core.getInput('token'); const token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`; const auth = !token ? undefined : `token ${token}`;
@@ -100758,7 +100882,8 @@ function run() {
checkLatest, checkLatest,
auth, auth,
stable, stable,
arch arch,
mirrorURL
}; };
const nodeDistribution = (0, installer_factory_1.getNodejsDistribution)(nodejsInfo); const nodeDistribution = (0, installer_factory_1.getNodejsDistribution)(nodejsInfo);
yield nodeDistribution.setupNodeJs(); yield nodeDistribution.setupNodeJs();
@@ -100852,7 +100977,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unique = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0; exports.unique = exports.validateMirrorURL = exports.printEnvDetailsAndSetOutput = exports.getNodeVersionFromFile = void 0;
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514)); const exec = __importStar(__nccwpck_require__(1514));
const io = __importStar(__nccwpck_require__(7436)); const io = __importStar(__nccwpck_require__(7436));
@@ -100940,6 +101065,15 @@ function getToolVersion(tool, options) {
} }
}); });
} }
function validateMirrorURL(mirrorURL) {
if (mirrorURL === ' ' || mirrorURL.trim() === 'undefined') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
}
else {
return mirrorURL;
}
}
exports.validateMirrorURL = validateMirrorURL;
const unique = () => { const unique = () => {
const encountered = new Set(); const encountered = new Set();
return (value) => { return (value) => {

View File

@@ -104,6 +104,31 @@ export default abstract class BaseDistribution {
return response.result || []; return response.result || [];
} }
protected async getMirrorUrlVersions(): Promise<INodeVersion[]> {
const initialUrl = this.getDistributionUrl();
const dataUrl = `${initialUrl}/index.json`;
try {
const response = await this.httpClient.getJson<INodeVersion[]>(dataUrl);
return response.result || [];
} catch (err) {
if (
err instanceof Error &&
err.message.includes('getaddrinfo EAI_AGAIN')
) {
core.error(`Network error: Failed to resolve the server at ${dataUrl}.
Please check your DNS settings or verify that the URL is correct.`);
} else if (err instanceof hc.HttpClientError && err.statusCode === 404) {
core.error(`404 Error: Unable to find versions at ${dataUrl}.
Please verify that the mirror URL is valid.`);
} else {
core.error(`Failed to fetch Node.js versions from ${dataUrl}.
Please check the URL and try again.}`);
}
throw err;
}
}
protected getNodejsDistInfo(version: string) { protected getNodejsDistInfo(version: string) {
const osArch: string = this.translateArchToDistUrl(this.nodeInfo.arch); const osArch: string = this.translateArchToDistUrl(this.nodeInfo.arch);
version = semver.clean(version) || ''; version = semver.clean(version) || '';
@@ -128,6 +153,33 @@ export default abstract class BaseDistribution {
}; };
} }
protected getNodejsMirrorURLInfo(version: string) {
const mirrorURL = this.nodeInfo.mirrorURL;
const osArch: string = this.translateArchToDistUrl(this.nodeInfo.arch);
version = semver.clean(version) || '';
const fileName: string =
this.osPlat == 'win32'
? `node-v${version}-win-${osArch}`
: `node-v${version}-${this.osPlat}-${osArch}`;
const urlFileName: string =
this.osPlat == 'win32'
? this.nodeInfo.arch === 'arm64'
? `${fileName}.zip`
: `${fileName}.7z`
: `${fileName}.tar.gz`;
const url = `${mirrorURL}/v${version}/${urlFileName}`;
return <INodeVersionInfo>{
downloadUrl: url,
resolvedVersion: version,
arch: osArch,
fileName: fileName
};
}
protected async downloadNodejs(info: INodeVersionInfo) { protected async downloadNodejs(info: INodeVersionInfo) {
let downloadPath = ''; let downloadPath = '';
core.info( core.info(
@@ -143,9 +195,23 @@ export default abstract class BaseDistribution {
) { ) {
return await this.acquireWindowsNodeFromFallbackLocation( return await this.acquireWindowsNodeFromFallbackLocation(
info.resolvedVersion, info.resolvedVersion,
info.arch info.arch,
info.downloadUrl
); );
} }
// Handle network-related issues (e.g., DNS resolution failures)
if (
err instanceof Error &&
err.message.includes('getaddrinfo EAI_AGAIN')
) {
core.error(
`Network error: Failed to resolve the server at ${info.downloadUrl}.
This could be due to a DNS resolution issue. Please verify the URL or check your network connection.`
);
}
core.error(
`Download failed from ${info.downloadUrl}. Please check the URl and try again.`
);
throw err; throw err;
} }
@@ -166,9 +232,11 @@ export default abstract class BaseDistribution {
protected async acquireWindowsNodeFromFallbackLocation( protected async acquireWindowsNodeFromFallbackLocation(
version: string, version: string,
arch: string = os.arch() arch: string = os.arch(),
downloadUrl: string
): Promise<string> { ): Promise<string> {
const initialUrl = this.getDistributionUrl(); const initialUrl = this.getDistributionUrl();
core.info('url: ' + initialUrl);
const osArch: string = this.translateArchToDistUrl(arch); const osArch: string = this.translateArchToDistUrl(arch);
// Create temporary folder to download to // Create temporary folder to download to
@@ -185,6 +253,12 @@ export default abstract class BaseDistribution {
core.info(`Downloading only node binary from ${exeUrl}`); core.info(`Downloading only node binary from ${exeUrl}`);
if (downloadUrl != exeUrl) {
core.error(
'unable to download node binary with the provided URL. Please check and try again'
);
}
const exePath = await tc.downloadTool(exeUrl); const exePath = await tc.downloadTool(exeUrl);
await io.cp(exePath, path.join(tempDir, 'node.exe')); await io.cp(exePath, path.join(tempDir, 'node.exe'));
const libPath = await tc.downloadTool(libUrl); const libPath = await tc.downloadTool(libUrl);

View File

@@ -4,6 +4,7 @@ export interface NodeInputs {
auth?: string; auth?: string;
checkLatest: boolean; checkLatest: boolean;
stable: boolean; stable: boolean;
mirrorURL?: string;
} }
export interface INodeVersionInfo { export interface INodeVersionInfo {

View File

@@ -3,11 +3,16 @@ import {NodeInputs} from '../base-models';
export default class NightlyNodejs extends BasePrereleaseNodejs { export default class NightlyNodejs extends BasePrereleaseNodejs {
protected distribution = 'nightly'; protected distribution = 'nightly';
constructor(nodeInfo: NodeInputs) { constructor(nodeInfo: NodeInputs) {
super(nodeInfo); super(nodeInfo);
} }
protected getDistributionUrl(): string { protected getDistributionUrl(): string {
return 'https://nodejs.org/download/nightly'; if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
} else {
return 'https://nodejs.org/download/nightly';
}
} }
} }

View File

@@ -15,115 +15,134 @@ export default class OfficialBuilds extends BaseDistribution {
} }
public async setupNodeJs() { public async setupNodeJs() {
let manifest: tc.IToolRelease[] | undefined; if (this.nodeInfo.mirrorURL) {
let nodeJsVersions: INodeVersion[] | undefined; let downloadPath = '';
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);
if (this.isLtsAlias(this.nodeInfo.versionSpec)) { try {
core.info('Attempt to resolve LTS alias from manifest...'); core.info(`Attempting to download using mirror URL...`);
downloadPath = await this.downloadFromMirrorURL(); // Attempt to download from the mirror
core.info('downloadPath from downloadFromMirrorURL() ' + downloadPath);
if (downloadPath) {
const toolPath = downloadPath;
}
} catch (err) {
core.info((err as Error).message);
core.info('Download failed');
core.debug((err as Error).stack ?? 'empty stack');
}
} else {
core.info('No mirror URL found. Falling back to default setup...');
core.info('Setup Node.js');
let manifest: tc.IToolRelease[] | undefined;
let nodeJsVersions: INodeVersion[] | undefined;
const osArch = this.translateArchToDistUrl(this.nodeInfo.arch);
// No try-catch since it's not possible to resolve LTS alias without manifest if (this.isLtsAlias(this.nodeInfo.versionSpec)) {
manifest = await this.getManifest(); core.info('Attempt to resolve LTS alias from manifest...');
this.nodeInfo.versionSpec = this.resolveLtsAliasFromManifest( // No try-catch since it's not possible to resolve LTS alias without manifest
this.nodeInfo.versionSpec, manifest = await this.getManifest();
this.nodeInfo.stable,
manifest
);
}
if (this.isLatestSyntax(this.nodeInfo.versionSpec)) { this.nodeInfo.versionSpec = this.resolveLtsAliasFromManifest(
nodeJsVersions = await this.getNodeJsVersions(); this.nodeInfo.versionSpec,
const versions = this.filterVersions(nodeJsVersions); this.nodeInfo.stable,
this.nodeInfo.versionSpec = this.evaluateVersions(versions); manifest
core.info('getting latest node version...');
}
if (this.nodeInfo.checkLatest) {
core.info('Attempt to resolve the latest version from manifest...');
const resolvedVersion = await this.resolveVersionFromManifest(
this.nodeInfo.versionSpec,
this.nodeInfo.stable,
osArch,
manifest
);
if (resolvedVersion) {
this.nodeInfo.versionSpec = resolvedVersion;
core.info(`Resolved as '${resolvedVersion}'`);
} else {
core.info(
`Failed to resolve version ${this.nodeInfo.versionSpec} from manifest`
); );
} }
}
let toolPath = this.findVersionInHostedToolCacheDirectory(); if (this.isLatestSyntax(this.nodeInfo.versionSpec)) {
nodeJsVersions = await this.getNodeJsVersions();
const versions = this.filterVersions(nodeJsVersions);
this.nodeInfo.versionSpec = this.evaluateVersions(versions);
if (toolPath) { core.info('getting latest node version...');
core.info(`Found in cache @ ${toolPath}`); }
this.addToolPath(toolPath);
return;
}
let downloadPath = ''; if (this.nodeInfo.checkLatest) {
try { core.info('Attempt to resolve the latest version from manifest...');
core.info(`Attempting to download ${this.nodeInfo.versionSpec}...`); const resolvedVersion = await this.resolveVersionFromManifest(
this.nodeInfo.versionSpec,
const versionInfo = await this.getInfoFromManifest( this.nodeInfo.stable,
this.nodeInfo.versionSpec, osArch,
this.nodeInfo.stable, manifest
osArch,
manifest
);
if (versionInfo) {
core.info(
`Acquiring ${versionInfo.resolvedVersion} - ${versionInfo.arch} from ${versionInfo.downloadUrl}`
); );
downloadPath = await tc.downloadTool( if (resolvedVersion) {
versionInfo.downloadUrl, this.nodeInfo.versionSpec = resolvedVersion;
undefined, core.info(`Resolved as '${resolvedVersion}'`);
this.nodeInfo.auth } else {
); core.info(
`Failed to resolve version ${this.nodeInfo.versionSpec} from manifest`
if (downloadPath) {
toolPath = await this.extractArchive(
downloadPath,
versionInfo,
false
); );
} }
} else {
core.info(
'Not found in manifest. Falling back to download directly from Node'
);
} }
} catch (err) {
// Rate limit? let toolPath = this.findVersionInHostedToolCacheDirectory();
if (
err instanceof tc.HTTPError && if (toolPath) {
(err.httpStatusCode === 403 || err.httpStatusCode === 429) core.info(`Found in cache @ ${toolPath}`);
) { this.addToolPath(toolPath);
core.info( return;
`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`
);
} else {
core.info((err as Error).message);
} }
core.debug((err as Error).stack ?? 'empty stack');
core.info('Falling back to download directly from Node');
}
if (!toolPath) { let downloadPath = '';
toolPath = await this.downloadDirectlyFromNode(); try {
} core.info(`Attempting to download ${this.nodeInfo.versionSpec}...`);
if (this.osPlat != 'win32') { const versionInfo = await this.getInfoFromManifest(
toolPath = path.join(toolPath, 'bin'); this.nodeInfo.versionSpec,
} this.nodeInfo.stable,
osArch,
manifest
);
core.addPath(toolPath); if (versionInfo) {
core.info(
`Acquiring ${versionInfo.resolvedVersion} - ${versionInfo.arch} from ${versionInfo.downloadUrl}`
);
downloadPath = await tc.downloadTool(
versionInfo.downloadUrl,
undefined,
this.nodeInfo.auth
);
if (downloadPath) {
toolPath = await this.extractArchive(
downloadPath,
versionInfo,
false
);
}
} else {
core.info(
'Not found in manifest. Falling back to download directly from Node'
);
}
} catch (err) {
// Rate limit?
if (
err instanceof tc.HTTPError &&
(err.httpStatusCode === 403 || err.httpStatusCode === 429)
) {
core.info(
`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`
);
} else {
core.info((err as Error).message);
}
core.debug((err as Error).stack ?? 'empty stack');
core.info('Falling back to download directly from Node');
}
if (!toolPath) {
toolPath = await this.downloadDirectlyFromNode();
}
if (this.osPlat != 'win32') {
toolPath = path.join(toolPath, 'bin');
}
core.addPath(toolPath);
}
} }
protected addToolPath(toolPath: string) { protected addToolPath(toolPath: string) {
@@ -177,6 +196,9 @@ export default class OfficialBuilds extends BaseDistribution {
} }
protected getDistributionUrl(): string { protected getDistributionUrl(): string {
if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
}
return `https://nodejs.org/dist`; return `https://nodejs.org/dist`;
} }
@@ -291,4 +313,38 @@ export default class OfficialBuilds extends BaseDistribution {
private isLatestSyntax(versionSpec): boolean { private isLatestSyntax(versionSpec): boolean {
return ['current', 'latest', 'node'].includes(versionSpec); return ['current', 'latest', 'node'].includes(versionSpec);
} }
protected async downloadFromMirrorURL() {
const nodeJsVersions = await this.getMirrorUrlVersions();
const versions = this.filterVersions(nodeJsVersions);
const evaluatedVersion = this.evaluateVersions(versions);
if (!evaluatedVersion) {
throw new Error(
`Unable to find Node version '${this.nodeInfo.versionSpec}' for platform ${this.osPlat} and architecture ${this.nodeInfo.arch} from the provided mirror-url ${this.nodeInfo.mirrorURL}. Please check the mirror-url`
);
}
const toolName = this.getNodejsMirrorURLInfo(evaluatedVersion);
try {
const toolPath = await this.downloadNodejs(toolName);
return toolPath;
} catch (error) {
if (error instanceof tc.HTTPError && error.httpStatusCode === 404) {
core.error(
`Node version ${this.nodeInfo.versionSpec} for platform ${this.osPlat} and architecture ${this.nodeInfo.arch} was found but failed to download. ` +
'This usually happens when downloadable binaries are not fully updated at https://nodejs.org/. ' +
'To resolve this issue you may either fall back to the older version or try again later.'
);
} else {
// For any other error type, you can log the error message.
core.error(`An unexpected error occurred like url might not correct`);
}
throw error;
}
}
} }

View File

@@ -5,8 +5,11 @@ export default class RcBuild extends BaseDistribution {
constructor(nodeInfo: NodeInputs) { constructor(nodeInfo: NodeInputs) {
super(nodeInfo); super(nodeInfo);
} }
protected getDistributionUrl(): string {
getDistributionUrl(): string { if (this.nodeInfo.mirrorURL) {
return 'https://nodejs.org/download/rc'; return this.nodeInfo.mirrorURL;
} else {
return 'https://nodejs.org/download/rc';
}
} }
} }

View File

@@ -1,6 +1,5 @@
import BasePrereleaseNodejs from '../base-distribution-prerelease'; import BasePrereleaseNodejs from '../base-distribution-prerelease';
import {NodeInputs} from '../base-models'; import {NodeInputs} from '../base-models';
export default class CanaryBuild extends BasePrereleaseNodejs { export default class CanaryBuild extends BasePrereleaseNodejs {
protected distribution = 'v8-canary'; protected distribution = 'v8-canary';
constructor(nodeInfo: NodeInputs) { constructor(nodeInfo: NodeInputs) {
@@ -8,6 +7,10 @@ export default class CanaryBuild extends BasePrereleaseNodejs {
} }
protected getDistributionUrl(): string { protected getDistributionUrl(): string {
return 'https://nodejs.org/download/v8-canary'; if (this.nodeInfo.mirrorURL) {
return this.nodeInfo.mirrorURL;
} else {
return 'https://nodejs.org/download/v8-canary';
}
} }
} }

View File

@@ -7,7 +7,11 @@ import * as path from 'path';
import {restoreCache} from './cache-restore'; import {restoreCache} from './cache-restore';
import {isCacheFeatureAvailable} from './cache-utils'; import {isCacheFeatureAvailable} from './cache-utils';
import {getNodejsDistribution} from './distributions/installer-factory'; import {getNodejsDistribution} from './distributions/installer-factory';
import {getNodeVersionFromFile, printEnvDetailsAndSetOutput} from './util'; import {
getNodeVersionFromFile,
printEnvDetailsAndSetOutput,
validateMirrorURL
} from './util';
import {State} from './constants'; import {State} from './constants';
export async function run() { export async function run() {
@@ -33,6 +37,9 @@ export async function run() {
arch = os.arch(); arch = os.arch();
} }
const mirrorurl = core.getInput('mirror-url');
const mirrorURL = validateMirrorURL(mirrorurl);
if (version) { if (version) {
const token = core.getInput('token'); const token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`; const auth = !token ? undefined : `token ${token}`;
@@ -45,7 +52,8 @@ export async function run() {
checkLatest, checkLatest,
auth, auth,
stable, stable,
arch arch,
mirrorURL
}; };
const nodeDistribution = getNodejsDistribution(nodejsInfo); const nodeDistribution = getNodejsDistribution(nodejsInfo);
await nodeDistribution.setupNodeJs(); await nodeDistribution.setupNodeJs();

View File

@@ -97,7 +97,13 @@ async function getToolVersion(tool: string, options: string[]) {
return ''; return '';
} }
} }
export function validateMirrorURL(mirrorURL) {
if (mirrorURL === ' ' || mirrorURL.trim() === 'undefined') {
throw new Error('Mirror URL is empty. Please provide a valid mirror URL.');
} else {
return mirrorURL;
}
}
export const unique = () => { export const unique = () => {
const encountered = new Set(); const encountered = new Set();
return (value: unknown): boolean => { return (value: unknown): boolean => {