Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,18 @@ rules_ts_ext.deps(
use_repo(rules_ts_ext, "npm_typescript")

node = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node")
node.toolchain(node_version_from_nvmrc = "//:.nvmrc")
node.toolchain(
node_repositories = {
"24.11.0-darwin_arm64": ("node-v24.11.0-darwin-arm64.tar.gz", "node-v24.11.0-darwin-arm64", "0be2ab2816a4fa02d1acff014a434f29f56d8d956f5af6a98b70ced6c5f4d201"),
"24.11.0-darwin_amd64": ("node-v24.11.0-darwin-x64.tar.gz", "node-v24.11.0-darwin-x64", "3884671e87f46f773832d98a0a6cabcc5ec4f637084f0f3515b69e66ea27f2f1"),
"24.11.0-linux_arm64": ("node-v24.11.0-linux-arm64.tar.xz", "node-v24.11.0-linux-arm64", "33a6673b2c7bffeae9deec7f9f8b31aad9119b08f13d49b2ca3ee3bebfe8260f"),
"24.11.0-linux_ppc64le": ("node-v24.11.0-linux-ppc64le.tar.xz", "node-v24.11.0-linux-ppc64le", "5e9fd1936c08ad6bf0cc69266af3f9815b598ff63419640da8379f7bd9afe9f5"),
"24.11.0-linux_s390x": ("node-v24.11.0-linux-s390x.tar.xz", "node-v24.11.0-linux-s390x", "8c7eca962686b98c0c5eaf46d96f24cd6d0e2f950954051027899c6b57bc7680"),
"24.11.0-linux_amd64": ("node-v24.11.0-linux-x64.tar.xz", "node-v24.11.0-linux-x64", "46da9a098973ab7ba4fca76945581ecb2eaf468de347173897044382f10e0a0a"),
"24.11.0-windows_amd64": ("node-v24.11.0-win-x64.zip", "node-v24.11.0-win-x64", "1054540bce22b54ec7e50ebc078ec5d090700a77657607a58f6a64df21f49fdd"),
},
node_version = "24.11.0",
Copy link
Contributor Author

@alan-agius4 alan-agius4 Jan 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using node_version_from_nvmrc in dev-infra causes build failures because pnpm ng-dev sync-module-bazel executes inside Bazel. To prevent errors during syncing, we must ensure the Node.js toolchain is correctly configured before actually syncing. Thus, we update the node_version with that inside the .nvmrc during syncing.

)
use_repo(node, "nodejs_toolchains")

rules_angular = use_extension("@rules_angular//setup:extensions.bzl", "rules_angular")
Expand All @@ -68,7 +79,8 @@ use_repo(rules_angular, rules_angular_configurable_deps = "dev_infra_rules_angul
pnpm = use_extension("@aspect_rules_js//npm:extensions.bzl", "pnpm")
pnpm.pnpm(
name = "pnpm",
pnpm_version = "10.16.1",
pnpm_version = "10.27.0",
pnpm_version_integrity = "sha512-ctaZ2haxF5wUup5k3HHJpAmIy9xlwmTLDkidt96RfyDc9NZNhyNiXylpulLUt+KhFwaC2awqXcrqq3MrfhbwSg==",
)
use_repo(pnpm, "pnpm")

Expand Down
338 changes: 309 additions & 29 deletions MODULE.bazel.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions ng-dev/misc/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ ts_project(
deps = [
"//ng-dev:node_modules/@types/node",
"//ng-dev:node_modules/@types/yargs",
"//ng-dev/format",
"//ng-dev/release/build",
"//ng-dev/release/config",
"//ng-dev/utils",
Expand Down
2 changes: 2 additions & 0 deletions ng-dev/misc/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/
import {Argv} from 'yargs';

import {SyncModuleBazelModule} from './sync-module-bazel/cli.js';
import {BuildAndLinkCommandModule} from './build-and-link/cli.js';
import {GeneratedFilesModule} from './generated-files/cli.js';
import {GeneratedNodeJsToolchainModule} from './generate-nodejs-toolchain/cli.js';
Expand All @@ -16,6 +17,7 @@ export function buildMiscParser(localYargs: Argv) {
return localYargs
.help()
.strict()
.command(SyncModuleBazelModule)
.command(BuildAndLinkCommandModule)
.command(GeneratedFilesModule)
.command(GeneratedNodeJsToolchainModule);
Expand Down
74 changes: 74 additions & 0 deletions ng-dev/misc/sync-module-bazel/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @license
* Copyright Google LLC
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {Argv, CommandModule} from 'yargs';
import {readFileSync, writeFileSync} from 'node:fs';
import {join} from 'node:path';
import {determineRepoBaseDirFromCwd} from '../../utils/repo-directory';
import {PackageJson, syncNodeJs, syncPnpm, syncTypeScript} from './sync-module-bazel';
import {ChildProcess} from '../../utils/child-process';
import {formatFiles} from '../../format/format';

async function builder(argv: Argv) {
return argv;
}

async function handler() {
const rootDir = determineRepoBaseDirFromCwd();
const packageJsonPath = join(rootDir, 'package.json');
const moduleBazelPath = join(rootDir, 'MODULE.bazel');
const nvmrcPath = join(rootDir, '.nvmrc');

// Read package.json
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as PackageJson;
const pnpmVersion = packageJson.engines?.pnpm;
const tsVersion = packageJson.dependencies?.typescript || packageJson.devDependencies?.typescript;

// Read .nvmrc
let nvmrcVersion: string | undefined;
try {
nvmrcVersion = readFileSync(nvmrcPath, 'utf8').trim().replace(/^v/, '');
} catch {
// .nvmrc is optional.
}

if (!pnpmVersion) {
throw new Error('Could find engines.pnpm in package.json');
}

if (!tsVersion) {
throw new Error('Could not find typescript in dependencies or devDependencies in package.json');
}

// Read MODULE.bazel
const originalBazelContent = readFileSync(moduleBazelPath, 'utf8');
let moduleBazelContent = originalBazelContent;

moduleBazelContent = await syncPnpm(moduleBazelContent, pnpmVersion);
moduleBazelContent = await syncTypeScript(moduleBazelContent, tsVersion);
moduleBazelContent = await syncNodeJs(moduleBazelContent, nvmrcVersion);

if (originalBazelContent !== moduleBazelContent) {
writeFileSync(moduleBazelPath, moduleBazelContent);

await formatFiles(['MODULE.bazel']);

ChildProcess.spawnSync('pnpm', ['bazel', 'mod', 'deps', '--lockfile_mode=update'], {
suppressErrorOnFailingExitCode: true,
});
}
}

/** CLI command module. */
export const SyncModuleBazelModule: CommandModule = {
builder,
handler,
command: 'sync-module-bazel',
describe:
'Sync node.js, pnpm and typescript versions in MODULE.bazel with package.json and .nvmrc.',
};
239 changes: 239 additions & 0 deletions ng-dev/misc/sync-module-bazel/sync-module-bazel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
/**
* @license
* Copyright Google LLC
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {Log} from '../../utils/logging';

export interface PackageJson {
engines?: {
pnpm?: string;
node?: string;
};
dependencies?: {
typescript?: string;
};
devDependencies?: {
typescript?: string;
};
}

interface RepositoryInfo {
filename: string;
sha: string;
type: string;
}

const REPOSITORY_TYPES: Record<string, string> = {
'darwin-arm64.tar.gz': 'darwin_arm64',
'darwin-x64.tar.gz': 'darwin_amd64',
'linux-x64.tar.xz': 'linux_amd64',
'linux-arm64.tar.xz': 'linux_arm64',
'linux-s390x.tar.xz': 'linux_s390x',
'win-x64.zip': 'windows_amd64',
'linux-ppc64le.tar.xz': 'linux_ppc64le',
};

/** RegExp that matches the pnpm version assignment in MODULE.bazel. */
const PNPM_VERSION_REGEXP = /pnpm_version(?:_from)? = ".*?"/;
/** RegExp that matches the pnpm integrity assignment in MODULE.bazel. */
const PNPM_INTEGRITY_REGEXP = /pnpm_version_integrity = ".*?"/;
/** RegExp that matches the TypeScript version assignment in MODULE.bazel. */
const TS_VERSION_REGEXP = /ts_version(?:_from)? = ".*?"/;
/** RegExp that matches the TypeScript integrity assignment in MODULE.bazel. */
const TS_INTEGRITY_REGEXP = /ts_integrity = ".*?"/;
/** RegExp that matches the Node.js version assignment in MODULE.bazel. */
const NODE_VERSION_REGEXP = /node_version = "(.*?)"/;
/** RegExp that matches the Node.js repositories assignment in MODULE.bazel. */
const NODE_REPOSITORIES_REGEXP = /node_repositories = \{[\s\S]*?\}/;

/** Fetches the integrity for a given package version from the npm registry. */
async function getNpmPackageIntegrity(pkg: string, version: string): Promise<string> {
const response = await fetch(`https://registry.npmjs.org/${pkg}/${version}`);
if (!response.ok) {
throw new Error(`Failed to request ${pkg}@${version}: ${response.statusText}`);
}

const {dist} = (await response.json()) as {dist: {integrity: string}};

return dist.integrity;
}

/** Fetches the repository information for a given Node.js version. */
async function getNodeJsRepositories(version: string): Promise<RepositoryInfo[]> {
const response = await fetch(`https://nodejs.org/dist/v${version}/SHASUMS256.txt`);
if (!response.ok) {
throw new Error(`Failed to get SHASUMS for Node.js v${version}: ${response.statusText}`);
}
const text = await response.text();

return text
.split('\n')
.filter(Boolean)
.map((line: string): RepositoryInfo | undefined => {
const [sha, filename] = line.trim().split(/\s+/);
if (!filename) return undefined;

const fileTypeSuffix = filename.replace(/^node-v[\d.]+-/, '');
const type = REPOSITORY_TYPES[fileTypeSuffix];

return type ? {filename, sha, type} : undefined;
})
.filter((repo): repo is RepositoryInfo => repo !== undefined);
}

/** Updates the version and integrity in the MODULE.bazel content for PNPM/TS. */
function updateVersionAndIntegrity(
content: string,
version: string,
integrity: string,
versionRegExp: RegExp,
integrityRegExp: RegExp,
versionKey: string,
integrityKey: string,
): string {
const newVal = `${versionKey} = "${version}"`;
const result = content.replace(versionRegExp, newVal);

return integrityRegExp.test(result)
? result.replace(integrityRegExp, `${integrityKey} = "${integrity}"`)
: result.replace(newVal, `${newVal},\n ${integrityKey} = "${integrity}"`);
}

/**
* Processes a `node.toolchain` block args string and updates it with
* the correct versions and repositories.
*/
async function processNodeToolchainArgs(
args: string,
nvmrcVersion: string | undefined,
): Promise<string> {
const useVersionFromNvm = args.includes('node_version_from_nvmrc');
const versionMatch = args.match(NODE_VERSION_REGEXP);
let effectiveVersion = versionMatch?.[1];

if (useVersionFromNvm) {
if (!nvmrcVersion) {
throw new Error('node_version_from_nvmrc used but .nvmrc not found');
}

effectiveVersion = nvmrcVersion;
} else if (effectiveVersion && effectiveVersion !== nvmrcVersion) {
args = args.replace(NODE_VERSION_REGEXP, `node_version = "${nvmrcVersion}"`);
effectiveVersion = nvmrcVersion;
}
if (!effectiveVersion) {
return args;
}

Log.info(`Resolving Node.js repositories for v${effectiveVersion}...`);
const repositories = await getNodeJsRepositories(effectiveVersion);
const lines = repositories.map(({filename, sha, type}) => {
const strippedFilename = filename.replace(/(\.tar)?\.[^.]+$/, '');

return ` "${effectiveVersion}-${type}": ("${filename}", "${strippedFilename}", "${sha}"),`;
});

const reposDict = `{\n${lines.join('\n')}\n }`;

if (NODE_REPOSITORIES_REGEXP.test(args)) {
return args.replace(NODE_REPOSITORIES_REGEXP, `node_repositories = ${reposDict}`);
}

const separator = args.trim().endsWith(',') ? '' : ',';
return `${args.trim()}${separator}\n node_repositories = ${reposDict}\n`;
}

/** Synchronizes the PNPM version and integrity in MODULE.bazel. */
export async function syncPnpm(content: string, version: string): Promise<string> {
if (!PNPM_VERSION_REGEXP.test(content)) {
return content;
}

Log.info(`Resolving integrity for pnpm@${version}...`);
const pnpmIntegrity = await getNpmPackageIntegrity('pnpm', version);

return updateVersionAndIntegrity(
content,
version,
pnpmIntegrity,
PNPM_VERSION_REGEXP,
PNPM_INTEGRITY_REGEXP,
'pnpm_version',
'pnpm_version_integrity',
);
}

/** Synchronizes the TypeScript version and integrity in MODULE.bazel. */
export async function syncTypeScript(content: string, version: string): Promise<string> {
if (!TS_VERSION_REGEXP.test(content)) {
return content;
}

Log.info(`Resolving integrity for typescript@${version}...`);
const tsIntegrity = await getNpmPackageIntegrity('typescript', version);

return updateVersionAndIntegrity(
content,
version,
tsIntegrity,
TS_VERSION_REGEXP,
TS_INTEGRITY_REGEXP,
'ts_version',
'ts_integrity',
);
}

/** Finds the index of the closing parenthesis for a balanced block. */
function findClosedParenIndex(content: string, startIndex: number): number {
let balance = 1;

for (let i = startIndex + 1; i < content.length; i++) {
if (content[i] === '(') {
balance++;
} else if (content[i] === ')') {
balance--;
}

if (balance === 0) {
return i;
}
}

return -1;
}

/** Synchronizes the Node.js toolchain versions and repositories in MODULE.bazel. */
export async function syncNodeJs(
content: string,
nvmrcVersion: string | undefined,
): Promise<string> {
const parts: string[] = [];
let lastIndex = 0;
let startIndex = 0;

while ((startIndex = content.indexOf('node.toolchain(', startIndex)) !== -1) {
const openParenIndex = startIndex + 'node.toolchain('.length - 1;
const endIndex = findClosedParenIndex(content, openParenIndex);

if (endIndex === -1) {
break;
}

parts.push(content.slice(lastIndex, startIndex));

const args = content.slice(openParenIndex + 1, endIndex);
const updatedArgs = await processNodeToolchainArgs(args, nvmrcVersion);
parts.push(`node.toolchain(${updatedArgs})`);

lastIndex = endIndex + 1;
startIndex = lastIndex;
}

parts.push(content.slice(lastIndex));

return parts.join('');
}
17 changes: 16 additions & 1 deletion renovate-presets/default.json5
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
// Workaround for https://github.com/renovatebot/renovate/issues/25557
{
postUpgradeTasks: {
matchManagers: ['bazel', 'bazel-module', 'bazelisk'],
commands: [
'bash -c "git restore .npmrc || true"', // If `.npmrc` doesn't exist, avoid a hard error.
'bazel mod deps --lockfile_mode=update',
Expand All @@ -55,7 +56,21 @@
// run when in the same branch there are mixtures of update types by different managers.
executionMode: 'update',
},
matchManagers: ['bazel', 'bazel-module', 'bazelisk'],
},

// Enable 'postUpdateTasks' for changes that effect the typescript and pnpm versions.
// This is to ensure that the `MODULE.bazel` is updated with the correct versions.
{
matchManagers: ['npm', 'nvm'],
matchDepNames: ['pnpm', 'typescript', 'node'],
postUpgradeTasks: {
commands: [
'bash -c "git restore .npmrc || true"', // If `.npmrc` doesn't exist, avoid a hard error.
'pnpm install --frozen-lockfile',
'bash -c "pnpm ng-dev misc sync-module-bazel || true"', // If `ng-dev` doesn't exist, avoid a hard error.
],
executionMode: 'branch',
},
},

// Rule to require manual approval for NPM updates on branches other than 'main'.
Expand Down
Loading
Loading