Skip to content
Closed
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
1 change: 1 addition & 0 deletions goldens/public-api/angular/build/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export type DevServerBuilderOptions = {
host?: string;
inspect?: Inspect;
liveReload?: boolean;
manualRebuild?: boolean;
open?: boolean;
poll?: number;
port?: number;
Expand Down
55 changes: 54 additions & 1 deletion packages/angular/build/src/builders/application/build-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '../../tools/esbuild/stylesheets/sass-language';
import { logMessages, withNoProgress, withSpinner } from '../../tools/esbuild/utils';
import { initializeHash } from '../../utils/hash';
import type { ManualRebuildController, ManualRebuildResult } from '../../utils/manual-rebuild';
import { NormalizedCachedOptions } from '../../utils/normalize-cache';
import { ChangedFiles } from '../../utils/watcher';
import { NormalizedApplicationBuildOptions, NormalizedOutputOptions } from './options';
Expand Down Expand Up @@ -50,6 +51,7 @@ export async function* runEsBuildBuildAction(
colors?: boolean;
jsonLogs?: boolean;
incrementalResults?: boolean;
manualRebuild?: ManualRebuildController;
},
): AsyncIterable<Result> {
const {
Expand All @@ -67,6 +69,7 @@ export async function* runEsBuildBuildAction(
colors,
jsonLogs,
incrementalResults,
manualRebuild,
} = options;

await initializeHash();
Expand Down Expand Up @@ -95,6 +98,11 @@ export async function* runEsBuildBuildAction(
if (watch) {
if (progress) {
logger.info('Watch mode enabled. Watching for file changes...');
if (manualRebuild) {
logger.info(
'Manual rebuild mode enabled. File changes will be rebuilt only when a rebuild is requested.',
);
}
}

// Setup a watcher
Expand Down Expand Up @@ -140,8 +148,29 @@ export async function* runEsBuildBuildAction(

// Wait for changes and rebuild as needed
const currentWatchFiles = new Set(result.watchFiles);
let rebuilds: AsyncIterable<{
changes: ChangedFiles;
requests?: ((result: ManualRebuildResult) => void)[];
}>;
if (manualRebuild) {
const { waitForManualRebuilds } = await import('../../utils/manual-rebuild');
rebuilds = waitForManualRebuilds(watcher, manualRebuild, {
onChangesPending: () => {
if (progress) {
logger.info('File changes detected. Waiting for a rebuild request...');
}
},
});
} else {
rebuilds = mapChanges(watcher);
}

// Manual rebuild requests for the rebuild in progress. These are resolved as cancelled if the
// loop exits before the rebuild completes (e.g., abort signal, build error, or consumer exit).
let activeRequests: ((result: ManualRebuildResult) => void)[] | undefined;
try {
for await (const changes of watcher) {
for await (const { changes, requests } of rebuilds) {
activeRequests = requests;
if (options.signal?.aborted) {
break;
}
Comment thread
DingWeizhe marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -202,15 +231,39 @@ export async function* runEsBuildBuildAction(

// Clear initial build errors flag if no errors are now present
hasInitialErrors &&= result.errors.length > 0;

// Notify any manual rebuild requesters now that all results have been emitted
if (requests?.length) {
const status = result.errors.length > 0 ? 'failure' : 'success';
for (const resolve of requests) {
resolve({ status });
}
}
activeRequests = undefined;
}
Comment thread
DingWeizhe marked this conversation as resolved.
Resolved
} finally {
if (activeRequests) {
for (const resolve of activeRequests) {
resolve({ status: 'cancelled' });
}
}
manualRebuild?.close();
Comment thread
DingWeizhe marked this conversation as resolved.
Resolved

// Stop the watcher and cleanup incremental rebuild state
await Promise.allSettled([watcher.close(), result.dispose()]);

shutdownSassWorkerPool();
}
}

async function* mapChanges(
watcher: AsyncIterable<ChangedFiles>,
): AsyncIterable<{ changes: ChangedFiles }> {
for await (const changes of watcher) {
yield { changes };
}
}

function* emitOutputResults(
{
outputFiles,
Expand Down
1 change: 1 addition & 0 deletions packages/angular/build/src/builders/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ export async function* buildApplicationInternal(
colors: normalizedOptions.colors,
jsonLogs: normalizedOptions.jsonLogs,
incrementalResults: normalizedOptions.incrementalResults,
manualRebuild: normalizedOptions.manualRebuild,
logger,
signal,
},
Expand Down
9 changes: 9 additions & 0 deletions packages/angular/build/src/builders/application/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { supportColor } from '../../utils/color';
import { useJSONBuildLogs, usePartialSsrBuild } from '../../utils/environment-options';
import { I18nOptions, createI18nOptions } from '../../utils/i18n-options';
import { IndexHtmlTransform } from '../../utils/index-file/index-html-generator';
import type { ManualRebuildController } from '../../utils/manual-rebuild';
import { normalizeCacheOptions } from '../../utils/normalize-cache';
import { canonicalizePath } from '../../utils/path';
import {
Expand Down Expand Up @@ -114,6 +115,13 @@ interface InternalOptions {
*/
incrementalResults?: boolean;

/**
* When provided, file changes detected in watch mode do not automatically trigger a rebuild.
* Instead, accumulated changes are rebuilt incrementally only when a rebuild is requested
* via the controller. This option also requires watch to be enabled to have an effect.
*/
manualRebuild?: ManualRebuildController;

/**
* Enables instrumentation to collect code coverage data for specific files.
*
Expand Down Expand Up @@ -560,6 +568,7 @@ export async function normalizeOptions(
security,
templateUpdates: !!options.templateUpdates,
incrementalResults: !!options.incrementalResults,
manualRebuild: options.manualRebuild,
customConditions: options.conditions,
frameworkVersion: await findFrameworkVersion(projectRoot),
};
Expand Down
5 changes: 4 additions & 1 deletion packages/angular/build/src/builders/dev-server/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ import { Schema as DevServerOptions } from './schema';

export type NormalizedDevServerOptions = Omit<
Awaited<ReturnType<typeof normalizeOptions>>,
'strictPort'
'strictPort' | 'manualRebuild'
> & {
strictPort?: boolean;
manualRebuild?: boolean;
};

/**
Expand Down Expand Up @@ -115,6 +116,7 @@ export async function normalizeOptions(
verbose,
define,
watch,
manualRebuild,
liveReload,
hmr,
headers,
Expand All @@ -138,6 +140,7 @@ export async function normalizeOptions(
verbose,
define,
watch,
manualRebuild: !!manualRebuild,
liveReload: !!liveReload,
hmr: hmr ?? !!liveReload,
headers,
Expand Down
5 changes: 5 additions & 0 deletions packages/angular/build/src/builders/dev-server/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@
"type": "number",
"description": "Enable and define the file watching poll time period in milliseconds."
},
"manualRebuild": {
"type": "boolean",
"description": "Rebuild only when explicitly requested instead of on every file change. File changes are still tracked while in watch mode, and all pending changes are rebuilt incrementally when a `POST` request is sent to the `/__ng_rebuild` endpoint of the development server or the `b` key is pressed in the terminal. This option has no effect when 'watch' is disabled.",
"default": false
},
"inspect": {
"default": false,
"description": "Activate debugging inspector. This option only has an effect when 'SSR' or 'SSG' are enabled.",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { setTimeout } from 'node:timers/promises';
import { executeDevServer } from '../../index';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';

const REBUILD_PATH = '__ng_rebuild';

describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
describe('Option: "manualRebuild"', () => {
beforeEach(() => {
setupTarget(harness);
});

it('only rebuilds file changes when a rebuild is requested', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: true,
manualRebuild: true,
});

let baseUrl = '';
let rebuildResponse: Promise<Response> | undefined;

await harness.executeWithCases([
async ({ result }) => {
expect(result?.success).toBeTrue();
baseUrl = result?.baseUrl as string;

// Nothing pending so a request should not rebuild
const noChangesResponse = await fetch(new URL(REBUILD_PATH, baseUrl), {
method: 'POST',
});
expect(noChangesResponse.status).toBe(200);
expect(await noChangesResponse.json()).toEqual({ status: 'no-changes' });

await harness.modifyFile(
'src/main.ts',
(content) => content + 'console.log("abcd1234");',
);

// Give the file watcher enough time to detect the change. No rebuild should occur.
await setTimeout(1500);
const before = await fetch(new URL('main.js', baseUrl));
expect(await before.text()).not.toContain('abcd1234');

// Request a rebuild. The response is sent once the rebuild completes.
rebuildResponse = fetch(new URL(REBUILD_PATH, baseUrl), { method: 'POST' });
},
async ({ result }) => {
expect(result?.success).toBeTrue();

const response = await rebuildResponse;
expect(response?.status).toBe(200);
expect(await response?.json()).toEqual({ status: 'success' });

const after = await fetch(new URL('main.js', baseUrl));
expect(await after.text()).toContain('abcd1234');
},
]);
});

it('rejects non-POST and cross-origin rebuild requests', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: true,
manualRebuild: true,
});

await harness.executeWithCases([
async ({ result }) => {
expect(result?.success).toBeTrue();
const url = new URL(REBUILD_PATH, result?.baseUrl as string);

const getResponse = await fetch(url);
expect(getResponse.status).toBe(405);

const crossOriginResponse = await fetch(url, {
method: 'POST',
headers: { origin: 'http://example.com' },
});
expect(crossOriginResponse.status).toBe(403);
},
]);
});
});
});
73 changes: 58 additions & 15 deletions packages/angular/build/src/builders/dev-server/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ import { join } from 'node:path';
import type * as Vite from 'vite' with {
'resolution-mode': 'import',
};
import type { ComponentStyleRecord } from '../../../tools/vite/middlewares';
import {
type ComponentStyleRecord,
REBUILD_ROUTE,
createAngularRebuildMiddleware,
} from '../../../tools/vite/middlewares';
import { ServerSsrMode } from '../../../tools/vite/plugins';
import { updateExternalMetadata } from '../../../tools/vite/utils';
import { normalizeSourceMaps } from '../../../utils';
import { useComponentStyleHmr, useComponentTemplateHmr } from '../../../utils/environment-options';
import { ManualRebuildController } from '../../../utils/manual-rebuild';
import { Result, ResultKind } from '../../application/results';
import { OutputHashing } from '../../application/schema';
import {
Expand Down Expand Up @@ -181,6 +186,18 @@ export async function* serveWithVite(
browserOptions.templateUpdates = componentsHmrCanBeUsed && useComponentTemplateHmr;
browserOptions.incrementalResults = true;

// Setup manual rebuild support which requires watch mode to be enabled
let manualRebuild: ManualRebuildController | undefined;
if (serverOptions.manualRebuild) {
if (browserOptions.watch) {
manualRebuild = browserOptions.manualRebuild = new ManualRebuildController();
} else {
context.logger.warn(
`The 'manualRebuild' option has no effect because the 'watch' option is disabled.`,
);
}
}

// Setup the prebundling transformer that will be shared across Vite prebundling requests
const prebundleTransformer = new JavaScriptTransformer(
// Always enable JIT linking to support applications built with and without AOT.
Expand Down Expand Up @@ -434,7 +451,9 @@ export async function* serveWithVite(
'ngJitMode': browserOptions.aot ? 'false' : 'true',
'ngHmrMode': browserOptions.templateUpdates ? 'true' : 'false',
},
extensions?.middleware,
manualRebuild
? [createAngularRebuildMiddleware(manualRebuild), ...(extensions?.middleware ?? [])]
: extensions?.middleware,
transformers?.indexHtml,
thirdPartySourcemaps,
);
Expand Down Expand Up @@ -503,21 +522,45 @@ export async function* serveWithVite(
// log connection information
server.printUrls();

if (manualRebuild && serverUrl) {
context.logger.info(
`Manual rebuild mode enabled. Send a POST request to ${new URL(REBUILD_ROUTE, serverUrl)}` +
` or press "b" to rebuild pending changes.`,
);
}

const customShortcuts: Vite.CLIShortcut<Vite.ViteDevServer>[] = [
{
key: 'r',
description: 'force reload browser',
action(server) {
componentStyles.forEach((record) => record.used?.clear());
server.ws.send({
type: 'full-reload',
path: '*',
});
},
},
];

if (manualRebuild) {
const controller = manualRebuild;
customShortcuts.push({
key: 'b',
description: 'rebuild pending changes',
action() {
void controller.requestRebuild().then(({ status }) => {
if (status === 'no-changes') {
context.logger.info('No pending changes to rebuild.');
}
});
},
});
}

server.bindCLIShortcuts({
print: true,
customShortcuts: [
{
key: 'r',
description: 'force reload browser',
action(server) {
componentStyles.forEach((record) => record.used?.clear());
server.ws.send({
type: 'full-reload',
path: '*',
});
},
},
],
customShortcuts,
});
}

Expand Down
Loading
Loading