Skip to content

Commit faed857

Browse files
committed
feat(@angular/build): allow enabling Bazel sandbox plugin with esbuild
Setting the new `ENABLE_BAZEL_SANDBOX_PLUGIN` environment variable to `true` or `1` during a build with the `esbuild` based builder will now inject a special plugin to make `esbuild` compatible with Bazel builds in the output tree. When trying to integrate the `esbuild` based builder into Bazel with `rules_js` we found that it will incorrectly follow symlinks out of the sandbox. This is because Node.js based tooling runs in the output tree to support canonical JS project directory structures. The output tree will contain symlinks outside of the sandbox. Node tooling will generally follow these symlinks, which violates the rules of Bazel sandboxing. This can manifest in a wide variety of errors. One example we encountered with Angular compilation is that the symlinked browser entry point (e.g. `main.ts`) is outside of the range of `tsconfig.json` when the compiler follows the symlink. The plugin itself was originally written in https://github.com/aspect-build/rules_esbuild. The version container in this commit is a fork of https://github.com/aspect-build/rules_esbuild/blob/e4e49d3354cbf7087c47ac9c5f2e6fe7f5e398d3/esbuild/private/plugins/bazel-sandbox.js. I've adapted the JS file to TypeScript and made no further changes.
1 parent 69e1ad4 commit faed857

File tree

2 files changed

+210
-0
lines changed

2 files changed

+210
-0
lines changed

packages/angular/build/src/tools/esbuild/application-code-bundle.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { createAngularLocaleDataPlugin } from './i18n-locale-plugin';
3030
import type { LoadResultCache } from './load-result-cache';
3131
import { createLoaderImportAttributePlugin } from './loader-import-attribute-plugin';
3232
import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin';
33+
import { createBazelSandboxPlugin } from './sandbox-plugin-bazel';
3334
import { createServerBundleMetadata } from './server-bundle-metadata-plugin';
3435
import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin';
3536
import { SERVER_GENERATED_EXTERNALS, getFeatureSupport, isZonelessApp } from './utils';
@@ -607,6 +608,31 @@ function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): Bu
607608
}
608609
}
609610

611+
// Inject the Bazel sandbox plugin only when specifically enabled to be fully backward compatible.
612+
// Most users will never need this and as such should not have it influence their builds.
613+
if (
614+
process.env.ENABLE_BAZEL_SANDBOX_PLUGIN === 'true' ||
615+
process.env.ENABLE_BAZEL_SANDBOX_PLUGIN === '1'
616+
) {
617+
const bindir = process.env.BAZEL_BINDIR;
618+
const execroot = process.env.JS_BINARY__EXECROOT;
619+
620+
let runfiles: string | undefined;
621+
// If requested, remap paths to the runfiles tree in the sandbox instead of the bindir
622+
// directly. This allows `js_binary` and `js_test` rules to invoke the Angular CLI against
623+
// their runfiles.
624+
if (
625+
process.env.BAZEL_SANDBOX_PLUGIN_REMAP_TO_RUNFILES === '1' ||
626+
process.env.BAZEL_SANDBOX_PLUGIN_REMAP_TO_RUNFILES === 'true'
627+
) {
628+
runfiles = process.env.JS_BINARY__RUNFILES;
629+
}
630+
631+
if (bindir && execroot) {
632+
plugins.push(createBazelSandboxPlugin({ bindir, execroot, runfiles }));
633+
}
634+
}
635+
610636
return {
611637
absWorkingDir: workspaceRoot,
612638
format: 'esm',
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
/**
10+
* Forked from https://github.com/aspect-build/rules_esbuild/blob/e4e49d3354cbf7087c47ac9c5f2e6fe7f5e398d3/esbuild/private/plugins/bazel-sandbox.js
11+
*/
12+
13+
import type { OnResolveResult, Plugin, PluginBuild, ResolveOptions } from 'esbuild';
14+
import { stat } from 'node:fs/promises';
15+
import path, { join } from 'node:path';
16+
17+
export interface CreateBazelSandboxPluginOptions {
18+
bindir: string;
19+
execroot: string;
20+
runfiles?: string;
21+
}
22+
23+
// Under Bazel, esbuild will follow symlinks out of the sandbox when the sandbox
24+
// is enabled. See https://github.com/aspect-build/rules_esbuild/issues/58. This
25+
// plugin using a separate resolver to detect if the the resolution has left the
26+
// execroot (which is the root of the sandbox when sandboxing is enabled) and
27+
// patches the resolution back into the sandbox.
28+
export function createBazelSandboxPlugin({
29+
bindir,
30+
execroot,
31+
runfiles,
32+
}: CreateBazelSandboxPluginOptions): Plugin {
33+
return {
34+
name: 'bazel-sandbox',
35+
setup(build) {
36+
build.onResolve({ filter: /./ }, async ({ path: importPath, ...otherOptions }) => {
37+
// NB: these lines are to prevent infinite recursion when we call `build.resolve`.
38+
if (otherOptions.pluginData) {
39+
if (otherOptions.pluginData.executedSandboxPlugin) {
40+
return;
41+
}
42+
} else {
43+
otherOptions.pluginData = {};
44+
}
45+
otherOptions.pluginData.executedSandboxPlugin = true;
46+
47+
return await resolveInExecroot({
48+
build,
49+
bindir,
50+
execroot,
51+
runfiles,
52+
importPath,
53+
otherOptions,
54+
});
55+
});
56+
},
57+
};
58+
}
59+
60+
interface ResolveInExecrootOptions {
61+
build: PluginBuild;
62+
bindir: string;
63+
execroot: string;
64+
runfiles?: string;
65+
importPath: string;
66+
otherOptions: ResolveOptions;
67+
}
68+
69+
const EXTERNAL_PREFIX = 'external/';
70+
71+
function removeExternalPathPrefix(filePath: string): string {
72+
// Normalize to relative path without leading slash.
73+
if (filePath.startsWith('/')) {
74+
filePath = filePath.substring(1);
75+
}
76+
// Remove the EXTERNAL_PREFIX if present.
77+
if (filePath.startsWith(EXTERNAL_PREFIX)) {
78+
filePath = filePath.substring(EXTERNAL_PREFIX.length);
79+
}
80+
81+
return filePath;
82+
}
83+
84+
async function resolveInExecroot({
85+
build,
86+
bindir,
87+
execroot,
88+
runfiles,
89+
importPath,
90+
otherOptions,
91+
}: ResolveInExecrootOptions): Promise<OnResolveResult> {
92+
const result = await build.resolve(importPath, otherOptions);
93+
94+
if (result.errors && result.errors.length) {
95+
// There was an error resolving, just return the error as-is.
96+
return result;
97+
}
98+
99+
if (
100+
!result.path.startsWith('.') &&
101+
!result.path.startsWith('/') &&
102+
!result.path.startsWith('\\')
103+
) {
104+
// Not a relative or absolute path. Likely a module resolution that is
105+
// marked "external"
106+
return result;
107+
}
108+
109+
// If esbuild attempts to leave the execroot, map the path back into the
110+
// execroot.
111+
if (!result.path.startsWith(execroot)) {
112+
// If it tried to leave bazel-bin, error out completely.
113+
if (!result.path.includes(bindir)) {
114+
throw new Error(
115+
`Error: esbuild resolved a path outside of BAZEL_BINDIR (${bindir}): ${result.path}`,
116+
);
117+
}
118+
// Get the path under the bindir for the file. This allows us to map into
119+
// the execroot or the runfiles directory (if present).
120+
// Example:
121+
// bindir = bazel-out/<arch>/bin
122+
// result.path = <base>/execroot/bazel-out/<arch>/bin/external/repo+/path/file.ts
123+
// binDirRelativePath = external/repo+/path/file.ts
124+
const binDirRelativePath = result.path.substring(
125+
result.path.indexOf(bindir) + bindir.length + 1,
126+
);
127+
// We usually remap into the bindir. However, when sources are provided
128+
// as `data` (runfiles), they will be in the runfiles root instead. The
129+
// runfiles path is absolute and under the bindir, so we don't need to
130+
// join anything to it. The execroot does not include the bindir, so there
131+
// we add it again after previously removing it from the result path.
132+
const remapBase = runfiles ?? path.join(execroot, bindir);
133+
// The path relative to the remapBase also differs between runfiles and
134+
// bindir, but only if the file is in an external repository. External
135+
// repositories appear under `external/repo+` in the bindir, whereas they
136+
// are directly under `repo+` in the runfiles tree. This difference needs
137+
// to be accounted for by removing a potential `external/` prefix when
138+
// mapping into runfiles.
139+
const remapBaseRelativePath = runfiles
140+
? removeExternalPathPrefix(binDirRelativePath)
141+
: binDirRelativePath;
142+
// Join the paths back together. The results will look slightly different
143+
// between runfiles and bindir, but this is intentional.
144+
// Source path:
145+
// <bin>/external/repo+/path/file.ts
146+
// Example in bindir:
147+
// <sandbox-bin>/external/repo+/path/file.ts
148+
// Example in runfiles:
149+
// <sandbox-bin>/path/bin.runfiles/repo+/path/file.ts
150+
const correctedPath = join(remapBase, remapBaseRelativePath);
151+
if (process.env.JS_BINARY__LOG_DEBUG) {
152+
// eslint-disable-next-line no-console
153+
console.error(
154+
`DEBUG: [bazel-sandbox] correcting resolution ${result.path} that left the sandbox to ${correctedPath}.`,
155+
);
156+
}
157+
result.path = correctedPath;
158+
159+
// Fall back to `.js` file if resolved `.ts` file does not exist in the
160+
// changed path.
161+
//
162+
// It's possible that a `.ts` file exists outside the sandbox and esbuild
163+
// resolves it. It is not guaranteed that the sandbox also contains the same
164+
// file. One example might be that the build depends on a compiled version
165+
// of the file and the sandbox will only contain the corresponding `.js` and
166+
// `.d.ts` files.
167+
if (result.path.endsWith('.ts')) {
168+
try {
169+
await stat(result.path);
170+
} catch (e: unknown) {
171+
const jsPath = result.path.slice(0, -3) + '.js';
172+
if (process.env.JS_BINARY__LOG_DEBUG) {
173+
// eslint-disable-next-line no-console
174+
console.error(
175+
`DEBUG: [bazel-sandbox] corrected resolution ${result.path} does not exist in the sandbox, trying ${jsPath}.`,
176+
);
177+
}
178+
result.path = jsPath;
179+
}
180+
}
181+
}
182+
183+
return result;
184+
}

0 commit comments

Comments
 (0)