Skip to content

Multiple asset fixes for Vite and the application builder in watch mode #29274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 10, 2025
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
49 changes: 33 additions & 16 deletions packages/angular/build/src/builders/application/build-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { BuildOutputFileType } from '../../tools/esbuild/bundler-context';
import { ExecutionResult, RebuildState } from '../../tools/esbuild/bundler-execution-result';
import { shutdownSassWorkerPool } from '../../tools/esbuild/stylesheets/sass-language';
import { logMessages, withNoProgress, withSpinner } from '../../tools/esbuild/utils';
import { ChangedFiles } from '../../tools/esbuild/watcher';
import { shouldWatchRoot } from '../../utils/environment-options';
import { NormalizedCachedOptions } from '../../utils/normalize-cache';
import { NormalizedApplicationBuildOptions, NormalizedOutputOptions } from './options';
Expand Down Expand Up @@ -199,7 +200,8 @@ export async function* runEsBuildBuildAction(
for (const outputResult of emitOutputResults(
result,
outputOptions,
incrementalResults ? rebuildState.previousOutputInfo : undefined,
changes,
incrementalResults ? rebuildState : undefined,
)) {
yield outputResult;
}
Expand All @@ -224,7 +226,8 @@ function* emitOutputResults(
templateUpdates,
}: ExecutionResult,
outputOptions: NormalizedApplicationBuildOptions['outputOptions'],
previousOutputInfo?: ReadonlyMap<string, { hash: string; type: BuildOutputFileType }>,
changes?: ChangedFiles,
rebuildState?: RebuildState,
): Iterable<Result> {
if (errors.length > 0) {
yield {
Expand Down Expand Up @@ -255,7 +258,9 @@ function* emitOutputResults(
}

// Use an incremental result if previous output information is available
if (previousOutputInfo) {
if (rebuildState && changes) {
const { previousAssetsInfo, previousOutputInfo } = rebuildState;

const incrementalResult: IncrementalResult = {
kind: ResultKind.Incremental,
warnings: warnings as ResultMessage[],
Expand All @@ -273,7 +278,6 @@ function* emitOutputResults(

// Initially assume all previous output files have been removed
const removedOutputFiles = new Map(previousOutputInfo);

for (const file of outputFiles) {
removedOutputFiles.delete(file.path);

Expand Down Expand Up @@ -304,24 +308,37 @@ function* emitOutputResults(
}
}

// Include the removed output files
// Initially assume all previous assets files have been removed
const removedAssetFiles = new Map(previousAssetsInfo);
for (const { source, destination } of assetFiles) {
removedAssetFiles.delete(source);

if (!previousAssetsInfo.has(source)) {
incrementalResult.added.push(destination);
} else if (changes.modified.has(source)) {
incrementalResult.modified.push(destination);
} else {
continue;
}

incrementalResult.files[destination] = {
type: BuildOutputFileType.Browser,
inputPath: source,
origin: 'disk',
};
}

// Include the removed output and asset files
incrementalResult.removed.push(
...Array.from(removedOutputFiles, ([file, { type }]) => ({
path: file,
type,
})),
);

// Always consider asset files as added to ensure new/modified assets are available.
// TODO: Consider more comprehensive asset analysis.
for (const file of assetFiles) {
incrementalResult.added.push(file.destination);
incrementalResult.files[file.destination] = {
...Array.from(removedAssetFiles.values(), (file) => ({
path: file,
type: BuildOutputFileType.Browser,
inputPath: file.source,
origin: 'disk',
};
}
})),
);

yield incrementalResult;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,50 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {

expect(buildCount).toBe(2);
});

it('remove deleted asset from output', async () => {
await Promise.all([
harness.writeFile('public/asset-two.txt', 'bar'),
harness.writeFile('public/asset-one.txt', 'foo'),
]);

harness.useTarget('build', {
...BASE_OPTIONS,
assets: [
{
glob: '**/*',
input: 'public',
},
],
watch: true,
});

const buildCount = await harness
.execute({ outputLogsOnFailure: false })
.pipe(
timeout(BUILD_TIMEOUT),
concatMap(async ({ result }, index) => {
switch (index) {
case 0:
expect(result?.success).toBeTrue();
harness.expectFile('dist/browser/asset-one.txt').toExist();
harness.expectFile('dist/browser/asset-two.txt').toExist();

await harness.removeFile('public/asset-two.txt');
break;
case 1:
expect(result?.success).toBeTrue();
harness.expectFile('dist/browser/asset-one.txt').toExist();
harness.expectFile('dist/browser/asset-two.txt').toNotExist();
break;
}
}),
take(2),
count(),
)
.toPromise();

expect(buildCount).toBe(2);
});
});
});
52 changes: 41 additions & 11 deletions packages/angular/build/src/builders/dev-server/vite-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ interface OutputFileRecord {
type: BuildOutputFileType;
}

interface OutputAssetRecord {
source: string;
updated: boolean;
}

interface DevServerExternalResultMetadata extends Omit<ExternalResultMetadata, 'explicit'> {
explicitBrowser: string[];
explicitServer: string[];
Expand Down Expand Up @@ -168,7 +173,7 @@ export async function* serveWithVite(
let serverUrl: URL | undefined;
let hadError = false;
const generatedFiles = new Map<string, OutputFileRecord>();
const assetFiles = new Map<string, string>();
const assetFiles = new Map<string, OutputAssetRecord>();
const externalMetadata: DevServerExternalResultMetadata = {
implicitBrowser: [],
implicitServer: [],
Expand Down Expand Up @@ -229,19 +234,15 @@ export async function* serveWithVite(
assetFiles.clear();
componentStyles.clear();
generatedFiles.clear();
for (const entry of Object.entries(result.files)) {
const [outputPath, file] = entry;
if (file.origin === 'disk') {
assetFiles.set('/' + normalizePath(outputPath), normalizePath(file.inputPath));
continue;
}

for (const [outputPath, file] of Object.entries(result.files)) {
updateResultRecord(
outputPath,
file,
normalizePath,
htmlIndexPath,
generatedFiles,
assetFiles,
componentStyles,
// The initial build will not yet have a server setup
!server,
Expand All @@ -265,23 +266,27 @@ export async function* serveWithVite(
generatedFiles.delete(filePath);
assetFiles.delete(filePath);
}

for (const modified of result.modified) {
updateResultRecord(
modified,
result.files[modified],
normalizePath,
htmlIndexPath,
generatedFiles,
assetFiles,
componentStyles,
);
}

for (const added of result.added) {
updateResultRecord(
added,
result.files[added],
normalizePath,
htmlIndexPath,
generatedFiles,
assetFiles,
componentStyles,
);
}
Expand Down Expand Up @@ -352,12 +357,16 @@ export async function* serveWithVite(
if (server) {
// Update fs allow list to include any new assets from the build option.
server.config.server.fs.allow = [
...new Set([...server.config.server.fs.allow, ...assetFiles.values()]),
...new Set([
...server.config.server.fs.allow,
...[...assetFiles.values()].map(({ source }) => source),
]),
];

await handleUpdate(
normalizePath,
generatedFiles,
assetFiles,
server,
serverOptions,
context.logger,
Expand Down Expand Up @@ -471,15 +480,26 @@ export async function* serveWithVite(
async function handleUpdate(
normalizePath: (id: string) => string,
generatedFiles: Map<string, OutputFileRecord>,
assetFiles: Map<string, OutputAssetRecord>,
server: ViteDevServer,
serverOptions: NormalizedDevServerOptions,
logger: BuilderContext['logger'],
componentStyles: Map<string, ComponentStyleRecord>,
): Promise<void> {
const updatedFiles: string[] = [];
let destroyAngularServerAppCalled = false;

// Invalidate any updated asset
for (const [file, record] of assetFiles) {
if (!record.updated) {
continue;
}

record.updated = false;
updatedFiles.push(file);
}

// Invalidate any updated files
let destroyAngularServerAppCalled = false;
for (const [file, record] of generatedFiles) {
if (!record.updated) {
continue;
Expand Down Expand Up @@ -584,10 +604,16 @@ function updateResultRecord(
normalizePath: (id: string) => string,
htmlIndexPath: string,
generatedFiles: Map<string, OutputFileRecord>,
assetFiles: Map<string, OutputAssetRecord>,
componentStyles: Map<string, ComponentStyleRecord>,
initial = false,
): void {
if (file.origin === 'disk') {
assetFiles.set('/' + normalizePath(outputPath), {
source: normalizePath(file.inputPath),
updated: !initial,
});

return;
}

Expand Down Expand Up @@ -644,7 +670,7 @@ function updateResultRecord(
export async function setupServer(
serverOptions: NormalizedDevServerOptions,
outputFiles: Map<string, OutputFileRecord>,
assets: Map<string, string>,
assets: Map<string, OutputAssetRecord>,
preserveSymlinks: boolean | undefined,
externalMetadata: DevServerExternalResultMetadata,
ssrMode: ServerSsrMode,
Expand Down Expand Up @@ -743,7 +769,11 @@ export async function setupServer(
// The first two are required for Vite to function in prebundling mode (the default) and to load
// the Vite client-side code for browser reloading. These would be available by default but when
// the `allow` option is explicitly configured, they must be included manually.
allow: [cacheDir, join(serverOptions.workspaceRoot, 'node_modules'), ...assets.values()],
allow: [
cacheDir,
join(serverOptions.workspaceRoot, 'node_modules'),
...[...assets.values()].map(({ source }) => source),
],
},
// This is needed when `externalDependencies` is used to prevent Vite load errors.
// NOTE: If Vite adds direct support for externals, this can be removed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export interface RebuildState {
componentStyleBundler: ComponentStylesheetBundler;
codeBundleCache?: SourceFileCache;
fileChanges: ChangedFiles;
previousOutputInfo: Map<string, { hash: string; type: BuildOutputFileType }>;
previousOutputInfo: ReadonlyMap<string, { hash: string; type: BuildOutputFileType }>;
previousAssetsInfo: ReadonlyMap<string, string>;
templateUpdates?: Map<string, string>;
}

Expand Down Expand Up @@ -172,12 +173,15 @@ export class ExecutionResult {
previousOutputInfo: new Map(
this.outputFiles.map(({ path, hash, type }) => [path, { hash, type }]),
),
previousAssetsInfo: new Map(
this.assetFiles.map(({ source, destination }) => [source, destination]),
),
templateUpdates: this.templateUpdates,
};
}

findChangedFiles(
previousOutputHashes: Map<string, { hash: string; type: BuildOutputFileType }>,
previousOutputHashes: ReadonlyMap<string, { hash: string; type: BuildOutputFileType }>,
): Set<string> {
const changed = new Set<string>();
for (const file of this.outputFiles) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import { lookup as lookupMimeType } from 'mrmime';
import { extname } from 'node:path';
import type { Connect, ViteDevServer } from 'vite';
import { AngularMemoryOutputFiles, pathnameWithoutBasePath } from '../utils';
import { AngularMemoryOutputFiles, AngularOutputAssets, pathnameWithoutBasePath } from '../utils';

export interface ComponentStyleRecord {
rawContent: Uint8Array;
Expand All @@ -19,7 +19,7 @@ export interface ComponentStyleRecord {

export function createAngularAssetsMiddleware(
server: ViteDevServer,
assets: Map<string, string>,
assets: AngularOutputAssets,
outputFiles: AngularMemoryOutputFiles,
componentStyles: Map<string, ComponentStyleRecord>,
encapsulateStyle: (style: Uint8Array, componentId: string) => string,
Expand All @@ -36,16 +36,16 @@ export function createAngularAssetsMiddleware(
const pathnameHasTrailingSlash = pathname[pathname.length - 1] === '/';

// Rewrite all build assets to a vite raw fs URL
const assetSourcePath = assets.get(pathname);
if (assetSourcePath !== undefined) {
const asset = assets.get(pathname);
if (asset) {
// Workaround to disable Vite transformer middleware.
// See: https://github.com/vitejs/vite/blob/746a1daab0395f98f0afbdee8f364cb6cf2f3b3f/packages/vite/src/node/server/middlewares/transform.ts#L201 and
// https://github.com/vitejs/vite/blob/746a1daab0395f98f0afbdee8f364cb6cf2f3b3f/packages/vite/src/node/server/transformRequest.ts#L204-L206
req.headers.accept = 'text/html';

// The encoding needs to match what happens in the vite static middleware.
// ref: https://github.com/vitejs/vite/blob/d4f13bd81468961c8c926438e815ab6b1c82735e/packages/vite/src/node/server/middlewares/static.ts#L163
req.url = `${server.config.base}@fs/${encodeURI(assetSourcePath)}`;
req.url = `${server.config.base}@fs/${encodeURI(asset.source)}`;
next();

return;
Expand All @@ -61,7 +61,7 @@ export function createAngularAssetsMiddleware(
assets.get(pathname + '.html');

if (htmlAssetSourcePath) {
req.url = `${server.config.base}@fs/${encodeURI(htmlAssetSourcePath)}`;
req.url = `${server.config.base}@fs/${encodeURI(htmlAssetSourcePath.source)}`;
next();

return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
createAngularSsrExternalMiddleware,
createAngularSsrInternalMiddleware,
} from '../middlewares';
import { AngularMemoryOutputFiles } from '../utils';
import { AngularMemoryOutputFiles, AngularOutputAssets } from '../utils';

export enum ServerSsrMode {
/**
Expand Down Expand Up @@ -47,7 +47,7 @@ export enum ServerSsrMode {

interface AngularSetupMiddlewaresPluginOptions {
outputFiles: AngularMemoryOutputFiles;
assets: Map<string, string>;
assets: AngularOutputAssets;
extensionMiddleware?: Connect.NextHandleFunction[];
indexHtmlTransformer?: (content: string) => Promise<string>;
componentStyles: Map<string, ComponentStyleRecord>;
Expand Down
Loading
Loading