_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular-cli/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/karma.conf.js_0_1486 | /**
* @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
*/
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
customLaunchers: {
ChromeHeadlessCI: {
base: 'ChromeHeadless',
flags: [
'--disable-gpu',
...(process.env.CHROME_NO_SANDBOX === '1' ? ['--no-sandbox'] : []),
],
}
},
singleRun: false
});
};
| {
"end_byte": 1486,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/karma.conf.js"
} |
angular-cli/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/public-api.ts_0_313 | /**
* @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
*/
/*
* Public API Surface of lib
*/
export * from './lib/lib.service';
export * from './lib/lib.component';
| {
"end_byte": 313,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/public-api.ts"
} |
angular-cli/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.component.ts_0_380 | /**
* @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 { Component } from '@angular/core';
@Component({
selector: 'lib',
template: `
<p>
lib works!
</p>
`,
styles: []
})
export class LibComponent {
}
| {
"end_byte": 380,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.component.ts"
} |
angular-cli/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.service.spec.ts_0_560 | /**
* @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 { TestBed, inject } from '@angular/core/testing';
import { LibService } from './lib.service';
describe('LibService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [LibService]
});
});
it('should be created', inject([LibService], (service: LibService) => {
expect(service).toBeTruthy();
}));
});
| {
"end_byte": 560,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.service.spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.service.ts_0_357 | /**
* @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 { Injectable } from '@angular/core';
@Injectable()
export class LibService {
testEs2016() {
return ['foo', 'bar'].includes('foo');
}
}
| {
"end_byte": 357,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.service.ts"
} |
angular-cli/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.component.spec.ts_0_755 | /**
* @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 { ComponentFixture, TestBed } from '@angular/core/testing';
import { LibComponent } from './lib.component';
describe('LibComponent', () => {
let component: LibComponent;
let fixture: ComponentFixture<LibComponent>;
beforeEach(() => TestBed.configureTestingModule({
declarations: [LibComponent]
}));
beforeEach(() => {
fixture = TestBed.createComponent(LibComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"end_byte": 755,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/test/hello-world-lib/projects/lib/src/lib/lib.component.spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/plugins/karma.ts_0_274 | /**
* @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
*/
module.exports = require('../src/tools/webpack/plugins/karma/karma');
| {
"end_byte": 274,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/plugins/karma.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/index.ts_0_1721 | /**
* @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
*/
export * from './transforms';
export { CrossOrigin, OutputHashing, Type } from './builders/browser/schema';
export type {
AssetPattern,
AssetPatternClass as AssetPatternObject,
Budget,
FileReplacement,
OptimizationClass as OptimizationObject,
OptimizationUnion,
Schema as BrowserBuilderOptions,
SourceMapClass as SourceMapObject,
SourceMapUnion,
StylePreprocessorOptions,
} from './builders/browser/schema';
export {
buildWebpackBrowser as executeBrowserBuilder,
type BrowserBuilderOutput,
} from './builders/browser';
export { buildApplication, type ApplicationBuilderOptions } from '@angular/build';
export {
executeDevServerBuilder,
type DevServerBuilderOptions,
type DevServerBuilderOutput,
} from './builders/dev-server';
export {
execute as executeExtractI18nBuilder,
type ExtractI18nBuilderOptions,
} from './builders/extract-i18n';
export {
execute as executeKarmaBuilder,
type KarmaBuilderOptions,
type KarmaConfigOptions,
} from './builders/karma';
export {
execute as executeProtractorBuilder,
type ProtractorBuilderOptions,
} from './builders/protractor';
export {
execute as executeServerBuilder,
type ServerBuilderOptions,
type ServerBuilderOutput,
} from './builders/server';
export {
execute as executeSSRDevServerBuilder,
type SSRDevServerBuilderOptions,
type SSRDevServerBuilderOutput,
} from './builders/ssr-dev-server';
export {
execute as executeNgPackagrBuilder,
type NgPackagrBuilderOptions,
} from './builders/ng-packagr';
| {
"end_byte": 1721,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/index.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/transforms.ts_0_272 | /**
* @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
*/
export type ExecutionTransformer<T> = (input: T) => T | Promise<T>;
| {
"end_byte": 272,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/transforms.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/devtools-ignore-plugin.ts_0_2167 | /**
* @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 { Compilation, Compiler } from 'webpack';
// Following the naming conventions from
// https://sourcemaps.info/spec.html#h.ghqpj1ytqjbm
const IGNORE_LIST = 'x_google_ignoreList';
const PLUGIN_NAME = 'devtools-ignore-plugin';
interface SourceMap {
sources: string[];
[IGNORE_LIST]: number[];
}
/**
* This plugin adds a field to source maps that identifies which sources are
* vendored or runtime-injected (aka third-party) sources. These are consumed by
* Chrome DevTools to automatically ignore-list sources.
*/
export class DevToolsIgnorePlugin {
apply(compiler: Compiler) {
const { RawSource } = compiler.webpack.sources;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
additionalAssets: true,
},
(assets) => {
for (const [name, asset] of Object.entries(assets)) {
// Instead of using `asset.map()` to fetch the source maps from
// SourceMapSource assets, process them directly as a RawSource.
// This is because `.map()` is slow and can take several seconds.
if (!name.endsWith('.map')) {
// Ignore non source map files.
continue;
}
const mapContent = asset.source().toString();
if (!mapContent) {
continue;
}
const map = JSON.parse(mapContent) as SourceMap;
const ignoreList = [];
for (const [index, path] of map.sources.entries()) {
if (path.includes('/node_modules/') || path.startsWith('webpack/')) {
ignoreList.push(index);
}
}
map[IGNORE_LIST] = ignoreList;
compilation.updateAsset(name, new RawSource(JSON.stringify(map)));
}
},
);
});
}
}
| {
"end_byte": 2167,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/devtools-ignore-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/javascript-optimizer-plugin.ts_0_8639 | /**
* @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 { transformSupportedBrowsersToTargets } from '@angular/build/private';
import Piscina from 'piscina';
import type { Compiler, sources } from 'webpack';
import { maxWorkers } from '../../../utils/environment-options';
import { addError } from '../../../utils/webpack-diagnostics';
import { EsbuildExecutor } from './esbuild-executor';
import type { OptimizeRequestOptions } from './javascript-optimizer-worker';
/**
* The maximum number of Workers that will be created to execute optimize tasks.
*/
const MAX_OPTIMIZE_WORKERS = maxWorkers;
/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'angular-javascript-optimizer';
/**
* The options used to configure the {@link JavaScriptOptimizerPlugin}.
*/
export interface JavaScriptOptimizerOptions {
/**
* Enables advanced optimizations in the underlying JavaScript optimizers.
* This currently increases the `terser` passes to 2 and enables the `pure_getters`
* option for `terser`.
*/
advanced?: boolean;
/**
* An object record of string keys that will be replaced with their respective values when found
* within the code during optimization.
*/
define: Record<string, string | number | boolean>;
/**
* Enables the generation of a sourcemap during optimization.
* The output sourcemap will be a full sourcemap containing the merge of the input sourcemap and
* all intermediate sourcemaps.
*/
sourcemap?: boolean;
/**
* A list of supported browsers that is used for output code.
*/
supportedBrowsers?: string[];
/**
* Enables the retention of identifier names and ensures that function and class names are
* present in the output code.
*
* **Note**: in some cases symbols are still renamed to avoid collisions.
*/
keepIdentifierNames: boolean;
/**
* Enables the removal of all license comments from the output code.
*/
removeLicenses?: boolean;
}
/**
* A Webpack plugin that provides JavaScript optimization capabilities.
*
* The plugin uses both `esbuild` and `terser` to provide both fast and highly-optimized
* code output. `esbuild` is used as an initial pass to remove the majority of unused code
* as well as shorten identifiers. `terser` is then used as a secondary pass to apply
* optimizations not yet implemented by `esbuild`.
*/
export class JavaScriptOptimizerPlugin {
private targets: string[] | undefined;
constructor(private options: JavaScriptOptimizerOptions) {
if (options.supportedBrowsers) {
this.targets = transformSupportedBrowsersToTargets(options.supportedBrowsers);
}
}
apply(compiler: Compiler) {
const { OriginalSource, SourceMapSource } = compiler.webpack.sources;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const logger = compilation.getLogger('build-angular.JavaScriptOptimizerPlugin');
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
},
async (compilationAssets) => {
logger.time('optimize js assets');
const scriptsToOptimize = [];
const cache =
compilation.options.cache && compilation.getCache('JavaScriptOptimizerPlugin');
// Analyze the compilation assets for scripts that require optimization
for (const assetName of Object.keys(compilationAssets)) {
if (!assetName.endsWith('.js')) {
continue;
}
const scriptAsset = compilation.getAsset(assetName);
// Skip assets that have already been optimized or are verbatim copies (project assets)
if (!scriptAsset || scriptAsset.info.minimized || scriptAsset.info.copied) {
continue;
}
const { source: scriptAssetSource, name } = scriptAsset;
let cacheItem;
if (cache) {
const eTag = cache.getLazyHashedEtag(scriptAssetSource);
cacheItem = cache.getItemCache(name, eTag);
const cachedOutput = await cacheItem.getPromise<
{ source: sources.Source } | undefined
>();
if (cachedOutput) {
logger.debug(`${name} restored from cache`);
compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({
...assetInfo,
minimized: true,
}));
continue;
}
}
const { source, map } = scriptAssetSource.sourceAndMap();
scriptsToOptimize.push({
name: scriptAsset.name,
code: typeof source === 'string' ? source : source.toString(),
map,
cacheItem,
});
}
if (scriptsToOptimize.length === 0) {
return;
}
// Ensure all replacement values are strings which is the expected type for esbuild
let define: Record<string, string> | undefined;
if (this.options.define) {
define = {};
for (const [key, value] of Object.entries(this.options.define)) {
define[key] = String(value);
}
}
// Setup the options used by all worker tasks
const optimizeOptions: OptimizeRequestOptions = {
sourcemap: this.options.sourcemap,
define,
keepIdentifierNames: this.options.keepIdentifierNames,
target: this.targets,
removeLicenses: this.options.removeLicenses,
advanced: this.options.advanced,
// Perform a single native esbuild support check.
// This removes the need for each worker to perform the check which would
// otherwise require spawning a separate process per worker.
alwaysUseWasm: !(await EsbuildExecutor.hasNativeSupport()),
};
// Sort scripts so larger scripts start first - worker pool uses a FIFO queue
scriptsToOptimize.sort((a, b) => a.code.length - b.code.length);
// Initialize the task worker pool
const workerPath = require.resolve('./javascript-optimizer-worker');
const workerPool = new Piscina({
filename: workerPath,
maxThreads: MAX_OPTIMIZE_WORKERS,
recordTiming: false,
});
// Enqueue script optimization tasks and update compilation assets as the tasks complete
try {
const tasks = [];
for (const { name, code, map, cacheItem } of scriptsToOptimize) {
logger.time(`optimize asset: ${name}`);
tasks.push(
workerPool
.run({
asset: {
name,
code,
map,
},
options: optimizeOptions,
})
.then(
async ({ code, name, map, errors }) => {
if (errors?.length) {
for (const error of errors) {
addError(compilation, `Optimization error [${name}]: ${error}`);
}
return;
}
const optimizedAsset = map
? new SourceMapSource(code, name, map)
: new OriginalSource(code, name);
compilation.updateAsset(name, optimizedAsset, (assetInfo) => ({
...assetInfo,
minimized: true,
}));
logger.timeEnd(`optimize asset: ${name}`);
return cacheItem?.storePromise({
source: optimizedAsset,
});
},
(error) => {
addError(
compilation,
`Optimization error [${name}]: ${error.stack || error.message}`,
);
},
),
);
}
await Promise.all(tasks);
} finally {
void workerPool.destroy();
}
logger.timeEnd('optimize js assets');
},
);
});
}
}
| {
"end_byte": 8639,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/javascript-optimizer-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/esbuild-executor.ts_0_3911 | /**
* @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 type {
FormatMessagesOptions,
PartialMessage,
TransformOptions,
TransformResult,
} from 'esbuild';
/**
* Provides the ability to execute esbuild regardless of the current platform's support
* for using the native variant of esbuild. The native variant will be preferred (assuming
* the `alwaysUseWasm` constructor option is `false) due to its inherent performance advantages.
* At first use of esbuild, a supportability test will be automatically performed and the
* WASM-variant will be used if needed by the platform.
*/
export class EsbuildExecutor
implements Pick<typeof import('esbuild'), 'transform' | 'formatMessages'>
{
private esbuildTransform: this['transform'];
private esbuildFormatMessages: this['formatMessages'];
private initialized = false;
/**
* Constructs an instance of the `EsbuildExecutor` class.
*
* @param alwaysUseWasm If true, the WASM-variant will be preferred and no support test will be
* performed; if false (default), the native variant will be preferred.
*/
constructor(private alwaysUseWasm = false) {
this.esbuildTransform = this.esbuildFormatMessages = () => {
throw new Error('esbuild implementation missing');
};
}
/**
* Determines whether the native variant of esbuild can be used on the current platform.
*
* @returns A promise which resolves to `true`, if the native variant of esbuild is support or `false`, if the WASM variant is required.
*/
static async hasNativeSupport(): Promise<boolean> {
// Try to use native variant to ensure it is functional for the platform.
try {
const { formatMessages } = await import('esbuild');
await formatMessages([], { kind: 'error' });
return true;
} catch {
return false;
}
}
/**
* Initializes the esbuild transform and format messages functions.
*
* @returns A promise that fulfills when esbuild has been loaded and available for use.
*/
private async ensureEsbuild(): Promise<void> {
if (this.initialized) {
return;
}
// If the WASM variant was preferred at class construction or native is not supported, use WASM
if (this.alwaysUseWasm || !(await EsbuildExecutor.hasNativeSupport())) {
await this.useWasm();
this.initialized = true;
return;
}
try {
// Use the faster native variant if available.
const { transform, formatMessages } = await import('esbuild');
this.esbuildTransform = transform;
this.esbuildFormatMessages = formatMessages;
} catch {
// If the native variant is not installed then use the WASM-based variant
await this.useWasm();
}
this.initialized = true;
}
/**
* Transitions an executor instance to use the WASM-variant of esbuild.
*/
private async useWasm(): Promise<void> {
const { transform, formatMessages } = await import('esbuild-wasm');
this.esbuildTransform = transform;
this.esbuildFormatMessages = formatMessages;
// The ESBUILD_BINARY_PATH environment variable cannot exist when attempting to use the
// WASM variant. If it is then the binary located at the specified path will be used instead
// of the WASM variant.
delete process.env.ESBUILD_BINARY_PATH;
this.alwaysUseWasm = true;
}
async transform(
input: string | Uint8Array,
options?: TransformOptions,
): Promise<TransformResult> {
await this.ensureEsbuild();
return this.esbuildTransform(input, options);
}
async formatMessages(
messages: PartialMessage[],
options: FormatMessagesOptions,
): Promise<string[]> {
await this.ensureEsbuild();
return this.esbuildFormatMessages(messages, options);
}
}
| {
"end_byte": 3911,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/esbuild-executor.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/postcss-cli-resources.ts_0_5593 | /**
* @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 { interpolateName } from 'loader-utils';
import * as path from 'path';
import { Declaration, Plugin } from 'postcss';
import * as url from 'url';
import { assertIsError } from '../../../utils/error';
function wrapUrl(url: string): string {
let wrappedUrl;
const hasSingleQuotes = url.indexOf("'") >= 0;
if (hasSingleQuotes) {
wrappedUrl = `"${url}"`;
} else {
wrappedUrl = `'${url}'`;
}
return `url(${wrappedUrl})`;
}
export interface PostcssCliResourcesOptions {
baseHref?: string;
deployUrl?: string;
resourcesOutputPath?: string;
rebaseRootRelative?: boolean;
/** CSS is extracted to a `.css` or is embedded in a `.js` file. */
extracted?: boolean;
filename: (resourcePath: string) => string;
loader: import('webpack').LoaderContext<unknown>;
emitFile: boolean;
}
async function resolve(
file: string,
base: string,
resolver: (file: string, base: string) => Promise<string>,
): Promise<string> {
try {
return await resolver('./' + file, base);
} catch {
return resolver(file, base);
}
}
export const postcss = true;
export default function (options?: PostcssCliResourcesOptions): Plugin {
if (!options) {
throw new Error('No options were specified to "postcss-cli-resources".');
}
const {
deployUrl = '',
resourcesOutputPath = '',
filename,
loader,
emitFile,
extracted,
} = options;
const process = async (inputUrl: string, context: string, resourceCache: Map<string, string>) => {
// If root-relative, absolute or protocol relative url, leave as is
if (/^((?:\w+:)?\/\/|data:|chrome:|#)/.test(inputUrl)) {
return inputUrl;
}
if (/^\//.test(inputUrl)) {
return inputUrl;
}
// If starts with a caret, remove and return remainder
// this supports bypassing asset processing
if (inputUrl.startsWith('^')) {
return inputUrl.slice(1);
}
const cacheKey = path.resolve(context, inputUrl);
const cachedUrl = resourceCache.get(cacheKey);
if (cachedUrl) {
return cachedUrl;
}
if (inputUrl.startsWith('~')) {
inputUrl = inputUrl.slice(1);
}
const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/'));
const resolver = (file: string, base: string) =>
new Promise<string>((resolve, reject) => {
loader.resolve(base, decodeURI(file), (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result as string);
});
});
const result = await resolve(pathname as string, context, resolver);
return new Promise<string>((resolve, reject) => {
loader.fs.readFile(result, (err, content) => {
if (err) {
reject(err);
return;
}
let outputPath = interpolateName({ resourcePath: result }, filename(result), {
content,
context: loader.context || loader.rootContext,
}).replace(/\\|\//g, '-');
if (resourcesOutputPath) {
outputPath = path.posix.join(resourcesOutputPath, outputPath);
}
loader.addDependency(result);
if (emitFile) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
loader.emitFile(outputPath, content!, undefined, { sourceFilename: result });
}
let outputUrl = outputPath.replace(/\\/g, '/');
if (hash || search) {
outputUrl = url.format({ pathname: outputUrl, hash, search });
}
if (deployUrl && !extracted) {
outputUrl = url.resolve(deployUrl, outputUrl);
}
resourceCache.set(cacheKey, outputUrl);
resolve(outputUrl);
});
});
};
const resourceCache = new Map<string, string>();
const processed = Symbol('postcss-cli-resources');
return {
postcssPlugin: 'postcss-cli-resources',
async Declaration(decl) {
if (!decl.value.includes('url') || processed in decl) {
return;
}
const value = decl.value;
const urlRegex = /url(?:\(\s*(['"]?))(.*?)(?:\1\s*\))/g;
const segments: string[] = [];
let match;
let lastIndex = 0;
let modified = false;
// We want to load it relative to the file that imports
const inputFile = decl.source && decl.source.input.file;
const context = (inputFile && path.dirname(inputFile)) || loader.context;
while ((match = urlRegex.exec(value))) {
const originalUrl = match[2];
let processedUrl;
try {
processedUrl = await process(originalUrl, context, resourceCache);
} catch (err) {
assertIsError(err);
loader.emitError(decl.error(err.message, { word: originalUrl }));
continue;
}
if (lastIndex < match.index) {
segments.push(value.slice(lastIndex, match.index));
}
if (!processedUrl || originalUrl === processedUrl) {
segments.push(match[0]);
} else {
segments.push(wrapUrl(processedUrl));
modified = true;
}
lastIndex = match.index + match[0].length;
}
if (lastIndex < value.length) {
segments.push(value.slice(lastIndex));
}
if (modified) {
decl.value = segments.join('');
}
(decl as Declaration & { [processed]: boolean })[processed] = true;
},
};
}
| {
"end_byte": 5593,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/postcss-cli-resources.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/suppress-entry-chunks-webpack-plugin.ts_0_1666 | /**
* @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
*/
/**
* Remove .js files from entry points consisting entirely of stylesheets.
* To be used together with mini-css-extract-plugin.
*/
export class SuppressExtractedTextChunksWebpackPlugin {
apply(compiler: import('webpack').Compiler): void {
compiler.hooks.compilation.tap('SuppressExtractedTextChunks', (compilation) => {
compilation.hooks.chunkAsset.tap('SuppressExtractedTextChunks', (chunk, filename) => {
// Remove only JavaScript assets
if (!filename.endsWith('.js')) {
return;
}
// Only chunks with a css asset should have JavaScript assets removed
let hasCssFile = false;
for (const file of chunk.files) {
if (file.endsWith('.css')) {
hasCssFile = true;
break;
}
}
if (!hasCssFile) {
return;
}
// Only chunks with all CSS entry dependencies should have JavaScript assets removed
let cssOnly = false;
const entryModules = compilation.chunkGraph.getChunkEntryModulesIterable(chunk);
for (const module of entryModules) {
cssOnly = module.dependencies.every(
(dependency: {}) => dependency.constructor.name === 'CssDependency',
);
if (!cssOnly) {
break;
}
}
if (cssOnly) {
chunk.files.delete(filename);
compilation.deleteAsset(filename);
}
});
});
}
}
| {
"end_byte": 1666,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/suppress-entry-chunks-webpack-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/any-component-style-budget-checker.ts_0_2606 | /**
* @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 {
BudgetAsset,
BudgetEntry,
BudgetType,
ThresholdSeverity,
checkBudgets,
} from '@angular/build/private';
import * as path from 'path';
import { Compilation, Compiler } from 'webpack';
import { addError, addWarning } from '../../../utils/webpack-diagnostics';
const PLUGIN_NAME = 'AnyComponentStyleBudgetChecker';
/**
* Check budget sizes for component styles by emitting a warning or error if a
* budget is exceeded by a particular component's styles.
*/
export class AnyComponentStyleBudgetChecker {
private readonly budgets: BudgetEntry[];
constructor(budgets: BudgetEntry[]) {
this.budgets = budgets.filter((budget) => budget.type === BudgetType.AnyComponentStyle);
}
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_ANALYSE,
},
() => {
// No budgets.
if (this.budgets.length === 0) {
return;
}
// In AOT compilations component styles get processed in child compilations.
if (!compilation.compiler.parentCompilation) {
return;
}
const cssExtensions = ['.css', '.scss', '.less', '.sass'];
const componentStyles: BudgetAsset[] = Object.keys(compilation.assets)
.filter((name) => cssExtensions.includes(path.extname(name)))
.map((name) => ({
name,
size: compilation.assets[name].size(),
componentStyle: true,
}));
for (const { severity, message } of checkBudgets(
this.budgets,
{ chunks: [], assets: componentStyles },
true,
)) {
switch (severity) {
case ThresholdSeverity.Warning:
addWarning(compilation, message);
break;
case ThresholdSeverity.Error:
addError(compilation, message);
break;
default:
assertNever(severity);
}
}
},
);
});
}
}
function assertNever(input: never): never {
throw new Error(
`Unexpected call to assertNever() with input: ${JSON.stringify(
input,
null /* replacer */,
4 /* tabSize */,
)}`,
);
}
| {
"end_byte": 2606,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/any-component-style-budget-checker.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/styles-webpack-plugin.ts_0_2699 | /**
* @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 assert from 'assert';
import type { Compilation, Compiler } from 'webpack';
import { assertIsError } from '../../../utils/error';
import { addError } from '../../../utils/webpack-diagnostics';
export interface StylesWebpackPluginOptions {
preserveSymlinks?: boolean;
root: string;
entryPoints: Record<string, string[]>;
}
/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'styles-webpack-plugin';
export class StylesWebpackPlugin {
private compilation: Compilation | undefined;
constructor(private readonly options: StylesWebpackPluginOptions) {}
apply(compiler: Compiler): void {
const { entryPoints, preserveSymlinks, root } = this.options;
const resolver = compiler.resolverFactory.get('global-styles', {
conditionNames: ['sass', 'less', 'style'],
mainFields: ['sass', 'less', 'style', 'main', '...'],
extensions: ['.scss', '.sass', '.less', '.css'],
restrictions: [/\.((le|sa|sc|c)ss)$/i],
preferRelative: true,
useSyncFileSystemCalls: true,
symlinks: !preserveSymlinks,
fileSystem: compiler.inputFileSystem ?? undefined,
});
const webpackOptions = compiler.options;
compiler.hooks.environment.tap(PLUGIN_NAME, () => {
const entry =
typeof webpackOptions.entry === 'function' ? webpackOptions.entry() : webpackOptions.entry;
webpackOptions.entry = async () => {
const entrypoints = await entry;
for (const [bundleName, paths] of Object.entries(entryPoints)) {
entrypoints[bundleName] ??= {};
const entryImport = (entrypoints[bundleName].import ??= []);
for (const path of paths) {
try {
const resolvedPath = resolver.resolveSync({}, root, path);
if (resolvedPath) {
entryImport.push(`${resolvedPath}?ngGlobalStyle`);
} else {
assert(this.compilation, 'Compilation cannot be undefined.');
addError(this.compilation, `Cannot resolve '${path}'.`);
}
} catch (error) {
assert(this.compilation, 'Compilation cannot be undefined.');
assertIsError(error);
addError(this.compilation, error.message);
}
}
}
return entrypoints;
};
});
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
this.compilation = compilation;
});
}
}
| {
"end_byte": 2699,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/styles-webpack-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/css-optimizer-plugin.ts_0_5598 | /**
* @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 { transformSupportedBrowsersToTargets } from '@angular/build/private';
import type { Message, TransformResult } from 'esbuild';
import type { Compilation, Compiler, sources } from 'webpack';
import { addWarning } from '../../../utils/webpack-diagnostics';
import { EsbuildExecutor } from './esbuild-executor';
/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'angular-css-optimizer';
export interface CssOptimizerPluginOptions {
supportedBrowsers?: string[];
}
/**
* A Webpack plugin that provides CSS optimization capabilities.
*
* The plugin uses both `esbuild` to provide both fast and highly-optimized
* code output.
*/
export class CssOptimizerPlugin {
private targets: string[] | undefined;
private esbuild = new EsbuildExecutor();
constructor(options?: CssOptimizerPluginOptions) {
if (options?.supportedBrowsers) {
this.targets = transformSupportedBrowsersToTargets(options.supportedBrowsers);
}
}
apply(compiler: Compiler) {
const { OriginalSource, SourceMapSource } = compiler.webpack.sources;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const logger = compilation.getLogger('build-angular.CssOptimizerPlugin');
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
},
async (compilationAssets) => {
const cache = compilation.options.cache && compilation.getCache(PLUGIN_NAME);
logger.time('optimize css assets');
for (const assetName of Object.keys(compilationAssets)) {
if (!/\.(?:css|scss|sass|less)$/.test(assetName)) {
continue;
}
const asset = compilation.getAsset(assetName);
// Skip assets that have already been optimized or are verbatim copies (project assets)
if (!asset || asset.info.minimized || asset.info.copied) {
continue;
}
const { source: styleAssetSource, name } = asset;
let cacheItem;
if (cache) {
const eTag = cache.getLazyHashedEtag(styleAssetSource);
cacheItem = cache.getItemCache(name, eTag);
const cachedOutput = await cacheItem.getPromise<
{ source: sources.Source; warnings: Message[] } | undefined
>();
if (cachedOutput) {
logger.debug(`${name} restored from cache`);
await this.addWarnings(compilation, cachedOutput.warnings);
compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({
...assetInfo,
minimized: true,
}));
continue;
}
}
const { source, map: inputMap } = styleAssetSource.sourceAndMap();
const input = typeof source === 'string' ? source : source.toString();
const optimizeAssetLabel = `optimize asset: ${asset.name}`;
logger.time(optimizeAssetLabel);
const { code, warnings, map } = await this.optimize(
input,
asset.name,
inputMap,
this.targets,
);
logger.timeEnd(optimizeAssetLabel);
await this.addWarnings(compilation, warnings);
const optimizedAsset = map
? new SourceMapSource(code, name, map)
: new OriginalSource(code, name);
compilation.updateAsset(name, optimizedAsset, (assetInfo) => ({
...assetInfo,
minimized: true,
}));
await cacheItem?.storePromise({
source: optimizedAsset,
warnings,
});
}
logger.timeEnd('optimize css assets');
},
);
});
}
/**
* Optimizes a CSS asset using esbuild.
*
* @param input The CSS asset source content to optimize.
* @param name The name of the CSS asset. Used to generate source maps.
* @param inputMap Optionally specifies the CSS asset's original source map that will
* be merged with the intermediate optimized source map.
* @param target Optionally specifies the target browsers for the output code.
* @returns A promise resolving to the optimized CSS, source map, and any warnings.
*/
private optimize(
input: string,
name: string,
inputMap: object,
target: string[] | undefined,
): Promise<TransformResult> {
let sourceMapLine;
if (inputMap) {
// esbuild will automatically remap the sourcemap if provided
sourceMapLine = `\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(inputMap),
).toString('base64')} */`;
}
return this.esbuild.transform(sourceMapLine ? input + sourceMapLine : input, {
loader: 'css',
legalComments: 'inline',
minify: true,
sourcemap: !!inputMap && 'external',
sourcefile: name,
target,
});
}
private async addWarnings(compilation: Compilation, warnings: Message[]) {
if (warnings.length > 0) {
for (const warning of await this.esbuild.formatMessages(warnings, { kind: 'warning' })) {
addWarning(compilation, warning);
}
}
}
}
| {
"end_byte": 5598,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/css-optimizer-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/named-chunks-plugin.ts_0_2066 | /**
* @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 { AsyncDependenciesBlock, Chunk, Compiler, Template, dependencies } from 'webpack';
// `ImportDependency` is not part of Webpack's depenencies typings.
const ImportDependency: typeof dependencies.ModuleDependency = require('webpack/lib/dependencies/ImportDependency');
const PLUGIN_NAME = 'named-chunks-plugin';
/**
* Webpack will not populate the chunk `name` property unless `webpackChunkName` magic comment is used.
* This however will also effect the filename which is not desired when using `deterministic` chunkIds.
* This plugin will populate the chunk `name` which is mainly used so that users can set bundle budgets on lazy chunks.
*/
export class NamedChunksPlugin {
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.chunkAsset.tap(PLUGIN_NAME, (chunk) => {
if (chunk.name) {
return;
}
if ([...chunk.files.values()].every((f) => f.endsWith('.css'))) {
// If all chunk files are CSS files skip.
// This happens when using `import('./styles.css')` in a lazy loaded module.
return undefined;
}
const name = this.generateName(chunk);
if (name) {
chunk.name = name;
}
});
});
}
private generateName(chunk: Chunk): string | undefined {
for (const group of chunk.groupsIterable) {
const [block] = group.getBlocks();
if (!(block instanceof AsyncDependenciesBlock)) {
continue;
}
if (block.groupOptions.name) {
// Ignore groups which have been named already.
return undefined;
}
for (const dependency of block.dependencies) {
if (dependency instanceof ImportDependency) {
return Template.toPath(dependency.request);
}
}
}
return undefined;
}
}
| {
"end_byte": 2066,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/named-chunks-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/transfer-size-plugin.ts_0_2024 | /**
* @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 { promisify } from 'util';
import { Compiler } from 'webpack';
import { brotliCompress } from 'zlib';
import { addWarning } from '../../../utils/webpack-diagnostics';
const brotliCompressAsync = promisify(brotliCompress);
const PLUGIN_NAME = 'angular-transfer-size-estimator';
export class TransferSizePlugin {
constructor() {}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ANALYSE,
},
async (compilationAssets) => {
const actions = [];
for (const assetName of Object.keys(compilationAssets)) {
if (!assetName.endsWith('.js') && !assetName.endsWith('.css')) {
continue;
}
const scriptAsset = compilation.getAsset(assetName);
if (!scriptAsset || scriptAsset.source.size() <= 0) {
continue;
}
actions.push(
brotliCompressAsync(scriptAsset.source.source())
.then((result) => {
compilation.updateAsset(
assetName,
(s) => s,
(assetInfo) => ({
...assetInfo,
estimatedTransferSize: result.length,
}),
);
})
.catch((error) => {
addWarning(
compilation,
`Unable to calculate estimated transfer size for '${assetName}'. Reason: ${error.message}`,
);
}),
);
}
await Promise.all(actions);
},
);
});
}
}
| {
"end_byte": 2024,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/transfer-size-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/common-js-usage-warn-plugin.ts_0_5883 | /**
* @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 { isAbsolute } from 'path';
import { Compilation, Compiler, Dependency, Module, NormalModule } from 'webpack';
import { addWarning } from '../../../utils/webpack-diagnostics';
// Webpack doesn't export these so the deep imports can potentially break.
const AMDDefineDependency = require('webpack/lib/dependencies/AMDDefineDependency');
const CommonJsExportsDependency = require('webpack/lib/dependencies/CommonJsExportsDependency');
const CommonJsRequireDependency = require('webpack/lib/dependencies/CommonJsRequireDependency');
const CommonJsSelfReferenceDependency = require('webpack/lib/dependencies/CommonJsSelfReferenceDependency');
export interface CommonJsUsageWarnPluginOptions {
/** A list of CommonJS or AMD packages that are allowed to be used without a warning. Use `'*'` to allow all. */
allowedDependencies?: string[];
}
export class CommonJsUsageWarnPlugin {
private shownWarnings = new Set<string>();
private allowedDependencies: Set<string>;
constructor(private options: CommonJsUsageWarnPluginOptions = {}) {
this.allowedDependencies = new Set(this.options.allowedDependencies);
}
apply(compiler: Compiler) {
if (this.allowedDependencies.has('*')) {
return;
}
compiler.hooks.compilation.tap('CommonJsUsageWarnPlugin', (compilation) => {
compilation.hooks.finishModules.tap('CommonJsUsageWarnPlugin', (modules) => {
const mainEntry = compilation.entries.get('main');
if (!mainEntry) {
return;
}
const mainModules = new Set(
mainEntry.dependencies.map((dep) => compilation.moduleGraph.getModule(dep)),
);
for (const module of modules) {
const { dependencies, rawRequest } = module as NormalModule;
if (
!rawRequest ||
rawRequest.startsWith('.') ||
isAbsolute(rawRequest) ||
this.allowedDependencies.has(rawRequest) ||
this.allowedDependencies.has(this.rawRequestToPackageName(rawRequest)) ||
rawRequest.startsWith('@angular/common/locales/')
) {
/**
* Skip when:
* - module is absolute or relative.
* - module is allowed even if it's a CommonJS.
* - module is a locale imported from '@angular/common'.
*/
continue;
}
if (this.hasCommonJsDependencies(compilation, dependencies)) {
// Dependency is CommonsJS or AMD.
const issuer = getIssuer(compilation, module);
// Check if it's parent issuer is also a CommonJS dependency.
// In case it is skip as an warning will be show for the parent CommonJS dependency.
const parentDependencies = getIssuer(compilation, issuer)?.dependencies;
if (
parentDependencies &&
this.hasCommonJsDependencies(compilation, parentDependencies, true)
) {
continue;
}
// Find the main issuer (entry-point).
let mainIssuer = issuer;
let nextIssuer = getIssuer(compilation, mainIssuer);
while (nextIssuer) {
mainIssuer = nextIssuer;
nextIssuer = getIssuer(compilation, mainIssuer);
}
// Only show warnings for modules from main entrypoint.
// And if the issuer request is not from 'webpack-dev-server', as 'webpack-dev-server'
// will require CommonJS libraries for live reloading such as 'sockjs-node'.
if (mainIssuer && mainModules.has(mainIssuer)) {
const warning =
`${(issuer as NormalModule | null)?.userRequest} depends on '${rawRequest}'. ` +
'CommonJS or AMD dependencies can cause optimization bailouts.\n' +
'For more info see: https://angular.dev/tools/cli/build#configuring-commonjs-dependencies';
// Avoid showing the same warning multiple times when in 'watch' mode.
if (!this.shownWarnings.has(warning)) {
addWarning(compilation, warning);
this.shownWarnings.add(warning);
}
}
}
}
});
});
}
private hasCommonJsDependencies(
compilation: Compilation,
dependencies: Dependency[],
checkParentModules = false,
): boolean {
for (const dep of dependencies) {
if (
dep instanceof CommonJsRequireDependency ||
dep instanceof CommonJsExportsDependency ||
dep instanceof CommonJsSelfReferenceDependency ||
dep instanceof AMDDefineDependency
) {
return true;
}
if (checkParentModules) {
const module = getWebpackModule(compilation, dep);
if (module && this.hasCommonJsDependencies(compilation, module.dependencies)) {
return true;
}
}
}
return false;
}
private rawRequestToPackageName(rawRequest: string): string {
return rawRequest.startsWith('@')
? // Scoped request ex: @angular/common/locale/en -> @angular/common
rawRequest.split('/', 2).join('/')
: // Non-scoped request ex: lodash/isEmpty -> lodash
rawRequest.split('/', 1)[0];
}
}
function getIssuer(
compilation: Compilation,
module: Module | null | undefined,
): Module | null | undefined {
if (!module) {
return null;
}
return compilation.moduleGraph.getIssuer(module);
}
function getWebpackModule(
compilation: Compilation,
dependency: Dependency | null,
): Module | null | undefined {
if (!dependency) {
return null;
}
return compilation.moduleGraph.getModule(dependency);
}
| {
"end_byte": 5883,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/common-js-usage-warn-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/index-html-webpack-plugin.ts_0_3375 | /**
* @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 {
FileInfo,
IndexHtmlGenerator,
IndexHtmlGeneratorOptions,
IndexHtmlGeneratorProcessOptions,
} from '@angular/build/private';
import { basename, dirname, extname } from 'path';
import { Compilation, Compiler, sources } from 'webpack';
import { assertIsError } from '../../../utils/error';
import { addError, addWarning } from '../../../utils/webpack-diagnostics';
export interface IndexHtmlWebpackPluginOptions
extends IndexHtmlGeneratorOptions,
Omit<IndexHtmlGeneratorProcessOptions, 'files'> {}
const PLUGIN_NAME = 'index-html-webpack-plugin';
export class IndexHtmlWebpackPlugin extends IndexHtmlGenerator {
private _compilation: Compilation | undefined;
get compilation(): Compilation {
if (this._compilation) {
return this._compilation;
}
throw new Error('compilation is undefined.');
}
constructor(override readonly options: IndexHtmlWebpackPluginOptions) {
super(options);
}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
this._compilation = compilation;
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1,
},
callback,
);
});
const callback = async (assets: Record<string, unknown>) => {
const files: FileInfo[] = [];
try {
for (const chunk of this.compilation.chunks) {
for (const file of chunk.files) {
// https://github.com/webpack/webpack/blob/1f99ad6367f2b8a6ef17cce0e058f7a67fb7db18/lib/config/defaults.js#L1000
if (file.endsWith('.hot-update.js') || file.endsWith('.hot-update.mjs')) {
continue;
}
files.push({
name: chunk.name,
file,
extension: extname(file),
});
}
}
const {
csrContent: content,
warnings,
errors,
} = await this.process({
files,
outputPath: dirname(this.options.outputPath),
baseHref: this.options.baseHref,
lang: this.options.lang,
});
assets[this.options.outputPath] = new sources.RawSource(content);
warnings.forEach((msg) => addWarning(this.compilation, msg));
errors.forEach((msg) => addError(this.compilation, msg));
} catch (error) {
assertIsError(error);
addError(this.compilation, error.message);
}
};
}
override async readAsset(path: string): Promise<string> {
const data = this.compilation.assets[basename(path)].source();
return typeof data === 'string' ? data : data.toString();
}
protected override async readIndex(path: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
this.compilation.inputFileSystem.readFile(
path,
(err?: Error | null, data?: string | Buffer) => {
if (err) {
reject(err);
return;
}
this.compilation.fileDependencies.add(path);
resolve(data?.toString() ?? '');
},
);
});
}
}
| {
"end_byte": 3375,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/index-html-webpack-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/occurrences-plugin.ts_0_2948 | /**
* @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 { Compiler } from 'webpack';
const PLUGIN_NAME = 'angular-occurrences-plugin';
export interface OccurrencesPluginOptions {
aot?: boolean;
scriptsOptimization?: boolean;
}
export class OccurrencesPlugin {
constructor(private options: OccurrencesPluginOptions) {}
apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ANALYSE,
},
async (compilationAssets) => {
for (const assetName of Object.keys(compilationAssets)) {
if (!assetName.endsWith('.js')) {
continue;
}
const scriptAsset = compilation.getAsset(assetName);
if (!scriptAsset || scriptAsset.source.size() <= 0) {
continue;
}
const src = scriptAsset.source.source().toString('utf-8');
let ngComponentCount = 0;
if (!this.options.aot) {
// Count the number of `Component({` strings (case sensitive), which happens in __decorate().
ngComponentCount += this.countOccurrences(src, 'Component({');
}
if (this.options.scriptsOptimization) {
// for ascii_only true
ngComponentCount += this.countOccurrences(src, '.\\u0275cmp', false);
} else {
// For Ivy we just count ɵcmp.src
ngComponentCount += this.countOccurrences(src, '.ɵcmp', true);
}
compilation.updateAsset(
assetName,
(s) => s,
(assetInfo) => ({
...assetInfo,
ngComponentCount,
}),
);
}
},
);
});
}
private countOccurrences(source: string, match: string, wordBreak = false): number {
let count = 0;
// We condition here so branch prediction happens out of the loop, not in it.
if (wordBreak) {
const re = /\w/;
for (let pos = source.lastIndexOf(match); pos >= 0; pos = source.lastIndexOf(match, pos)) {
if (!(re.test(source[pos - 1] || '') || re.test(source[pos + match.length] || ''))) {
count++; // 1 match, AH! AH! AH! 2 matches, AH! AH! AH!
}
pos -= match.length;
if (pos < 0) {
break;
}
}
} else {
for (let pos = source.lastIndexOf(match); pos >= 0; pos = source.lastIndexOf(match, pos)) {
count++; // 1 match, AH! AH! AH! 2 matches, AH! AH! AH!
pos -= match.length;
if (pos < 0) {
break;
}
}
}
return count;
}
}
| {
"end_byte": 2948,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/occurrences-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/service-worker-plugin.ts_0_2237 | /**
* @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 { augmentAppWithServiceWorker } from '@angular/build/private';
import type { Compiler } from 'webpack';
export interface ServiceWorkerPluginOptions {
projectRoot: string;
root: string;
baseHref?: string;
ngswConfigPath?: string;
}
export class ServiceWorkerPlugin {
constructor(private readonly options: ServiceWorkerPluginOptions) {}
apply(compiler: Compiler) {
compiler.hooks.done.tapPromise('angular-service-worker', async (stats) => {
if (stats.hasErrors()) {
// Don't generate a service worker if the compilation has errors.
// When there are errors some files will not be emitted which would cause other errors down the line such as readdir failures.
return;
}
const { projectRoot, root, baseHref = '', ngswConfigPath } = this.options;
const { compilation } = stats;
// We use the output path from the compilation instead of build options since during
// localization the output path is modified to a temp directory.
// See: https://github.com/angular/angular-cli/blob/7e64b1537d54fadb650559214fbb12707324cd75/packages/angular_devkit/build_angular/src/utils/i18n-options.ts#L251-L252
const outputPath = compilation.outputOptions.path;
if (!outputPath) {
throw new Error('Compilation output path cannot be empty.');
}
try {
await augmentAppWithServiceWorker(
projectRoot,
root,
outputPath,
baseHref,
ngswConfigPath,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(compiler.inputFileSystem as any).promises,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(compiler.outputFileSystem as any).promises,
);
} catch (error) {
compilation.errors.push(
new compilation.compiler.webpack.WebpackError(
`Failed to generate service worker - ${error instanceof Error ? error.message : error}`,
),
);
}
});
}
}
| {
"end_byte": 2237,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/service-worker-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/remove-hash-plugin.ts_0_1097 | /**
* @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 { Compiler } from 'webpack';
import { HashFormat } from '../utils/helpers';
export interface RemoveHashPluginOptions {
chunkNames: string[];
hashFormat: HashFormat;
}
export class RemoveHashPlugin {
constructor(private options: RemoveHashPluginOptions) {}
apply(compiler: Compiler): void {
compiler.hooks.compilation.tap('remove-hash-plugin', (compilation) => {
const assetPath = (path: string, data: { chunk?: { name: string } }) => {
const chunkName = data.chunk?.name;
const { chunkNames, hashFormat } = this.options;
if (chunkName && chunkNames?.includes(chunkName)) {
// Replace hash formats with empty strings.
return path.replace(hashFormat.chunk, '').replace(hashFormat.extract, '');
}
return path;
};
compilation.hooks.assetPath.tap('remove-hash-plugin', assetPath);
});
}
}
| {
"end_byte": 1097,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/remove-hash-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/scripts-webpack-plugin.ts_0_6474 | /**
* @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 { interpolateName } from 'loader-utils';
import * as path from 'path';
import { Chunk, Compilation, Compiler, sources as webpackSources } from 'webpack';
import { assertIsError } from '../../../utils/error';
import { addError } from '../../../utils/webpack-diagnostics';
const Entrypoint = require('webpack/lib/Entrypoint');
/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'scripts-webpack-plugin';
export interface ScriptsWebpackPluginOptions {
name: string;
sourceMap?: boolean;
scripts: string[];
filename: string;
basePath: string;
}
interface ScriptOutput {
filename: string;
source: webpackSources.CachedSource;
}
function addDependencies(compilation: Compilation, scripts: string[]): void {
for (const script of scripts) {
compilation.fileDependencies.add(script);
}
}
export class ScriptsWebpackPlugin {
private _lastBuildTime?: number;
private _cachedOutput?: ScriptOutput;
constructor(private options: ScriptsWebpackPluginOptions) {}
async shouldSkip(compilation: Compilation, scripts: string[]): Promise<boolean> {
if (this._lastBuildTime == undefined) {
this._lastBuildTime = Date.now();
return false;
}
for (const script of scripts) {
const scriptTime = await new Promise<number | undefined>((resolve, reject) => {
compilation.fileSystemInfo.getFileTimestamp(script, (error, entry) => {
if (error) {
reject(error);
return;
}
resolve(entry && typeof entry !== 'string' ? entry.safeTime : undefined);
});
});
if (!scriptTime || scriptTime > this._lastBuildTime) {
this._lastBuildTime = Date.now();
return false;
}
}
return true;
}
private _insertOutput(
compilation: Compilation,
{ filename, source }: ScriptOutput,
cached = false,
) {
const chunk = new Chunk(this.options.name);
chunk.rendered = !cached;
chunk.id = this.options.name;
chunk.ids = [chunk.id];
chunk.files.add(filename);
const entrypoint = new Entrypoint(this.options.name);
entrypoint.pushChunk(chunk);
chunk.addGroup(entrypoint);
compilation.entrypoints.set(this.options.name, entrypoint);
compilation.chunks.add(chunk);
compilation.assets[filename] = source;
compilation.hooks.chunkAsset.call(chunk, filename);
}
apply(compiler: Compiler): void {
if (this.options.scripts.length === 0) {
return;
}
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
// Use the resolver from the compilation instead of compiler.
// Using the latter will causes a lot of `DescriptionFileUtils.loadDescriptionFile` calls.
// See: https://github.com/angular/angular-cli/issues/24634#issuecomment-1425782668
const resolver = compilation.resolverFactory.get('normal', {
preferRelative: true,
useSyncFileSystemCalls: true,
// Caching must be disabled because it causes the resolver to become async after a rebuild.
cache: false,
});
const scripts: string[] = [];
for (const script of this.options.scripts) {
try {
const resolvedPath = resolver.resolveSync({}, this.options.basePath, script);
if (resolvedPath) {
scripts.push(resolvedPath);
} else {
addError(compilation, `Cannot resolve '${script}'.`);
}
} catch (error) {
assertIsError(error);
addError(compilation, error.message);
}
}
compilation.hooks.additionalAssets.tapPromise(PLUGIN_NAME, async () => {
if (await this.shouldSkip(compilation, scripts)) {
if (this._cachedOutput) {
this._insertOutput(compilation, this._cachedOutput, true);
}
addDependencies(compilation, scripts);
return;
}
const sourceGetters = scripts.map((fullPath) => {
return new Promise<webpackSources.Source>((resolve, reject) => {
compilation.inputFileSystem.readFile(
fullPath,
(err?: Error | null, data?: string | Buffer) => {
if (err) {
reject(err);
return;
}
const content = data?.toString() ?? '';
let source;
if (this.options.sourceMap) {
// TODO: Look for source map file (for '.min' scripts, etc.)
let adjustedPath = fullPath;
if (this.options.basePath) {
adjustedPath = path.relative(this.options.basePath, fullPath);
}
source = new webpackSources.OriginalSource(content, adjustedPath);
} else {
source = new webpackSources.RawSource(content);
}
resolve(source);
},
);
});
});
const sources = await Promise.all(sourceGetters);
const concatSource = new webpackSources.ConcatSource();
sources.forEach((source) => {
concatSource.add(source);
concatSource.add('\n;');
});
const combinedSource = new webpackSources.CachedSource(concatSource);
const output = { filename: this.options.filename, source: combinedSource };
this._insertOutput(compilation, output);
this._cachedOutput = output;
addDependencies(compilation, scripts);
});
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
},
async () => {
const assetName = this.options.filename;
const asset = compilation.getAsset(assetName);
if (asset) {
const interpolatedFilename = interpolateName(
{ resourcePath: 'scripts.js' },
assetName,
{ content: asset.source.source() },
);
if (assetName !== interpolatedFilename) {
compilation.renameAsset(assetName, interpolatedFilename);
}
}
},
);
});
}
}
| {
"end_byte": 6474,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/scripts-webpack-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/javascript-optimizer-worker.ts_0_7261 | /**
* @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 remapping, { SourceMapInput } from '@ampproject/remapping';
import type { BuildFailure, TransformResult } from 'esbuild';
import { minify } from 'terser';
import { EsbuildExecutor } from './esbuild-executor';
/**
* The options to use when optimizing.
*/
export interface OptimizeRequestOptions {
/**
* Controls advanced optimizations.
* Currently these are only terser related:
* * terser compress passes are set to 2
* * terser pure_getters option is enabled
*/
advanced?: boolean;
/**
* Specifies the string tokens that should be replaced with a defined value.
*/
define?: Record<string, string>;
/**
* Controls whether class, function, and variable names should be left intact
* throughout the output code.
*/
keepIdentifierNames: boolean;
/**
* Controls whether license text is removed from the output code.
* Within the CLI, this option is linked to the license extraction functionality.
*/
removeLicenses?: boolean;
/**
* Controls whether source maps should be generated.
*/
sourcemap?: boolean;
/**
* Specifies the list of supported esbuild targets.
* @see: https://esbuild.github.io/api/#target
*/
target?: string[];
/**
* Controls whether esbuild should only use the WASM-variant instead of trying to
* use the native variant. Some platforms may not support the native-variant and
* this option allows one support test to be conducted prior to all the workers starting.
*/
alwaysUseWasm: boolean;
}
/**
* A request to optimize JavaScript using the supplied options.
*/
interface OptimizeRequest {
/**
* The options to use when optimizing.
*/
options: OptimizeRequestOptions;
/**
* The JavaScript asset to optimize.
*/
asset: {
/**
* The name of the JavaScript asset (typically the filename).
*/
name: string;
/**
* The source content of the JavaScript asset.
*/
code: string;
/**
* The source map of the JavaScript asset, if available.
* This map is merged with all intermediate source maps during optimization.
*/
map: SourceMapInput;
};
}
/**
* The cached esbuild executor.
* This will automatically use the native or WASM version based on platform and availability
* with the native version given priority due to its superior performance.
*/
let esbuild: EsbuildExecutor | undefined;
/**
* Handles optimization requests sent from the main thread via the `JavaScriptOptimizerPlugin`.
*/
export default async function ({ asset, options }: OptimizeRequest) {
// esbuild is used as a first pass
const esbuildResult = await optimizeWithEsbuild(asset.code, asset.name, options);
if (isEsBuildFailure(esbuildResult)) {
return {
name: asset.name,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
errors: await esbuild!.formatMessages(esbuildResult.errors, { kind: 'error' }),
};
}
// terser is used as a second pass
const terserResult = await optimizeWithTerser(
asset.name,
esbuildResult.code,
options.sourcemap,
options.advanced,
);
// Merge intermediate sourcemaps with input sourcemap if enabled
let fullSourcemap;
if (options.sourcemap) {
const partialSourcemaps = [];
if (esbuildResult.map) {
partialSourcemaps.unshift(JSON.parse(esbuildResult.map) as SourceMapInput);
}
if (terserResult.map) {
partialSourcemaps.unshift(terserResult.map as SourceMapInput);
}
if (asset.map) {
partialSourcemaps.push(asset.map);
}
fullSourcemap = remapping(partialSourcemaps, () => null);
}
return { name: asset.name, code: terserResult.code, map: fullSourcemap };
}
/**
* Optimizes a JavaScript asset using esbuild.
*
* @param content The JavaScript asset source content to optimize.
* @param name The name of the JavaScript asset. Used to generate source maps.
* @param options The optimization request options to apply to the content.
* @returns A promise that resolves with the optimized code, source map, and any warnings.
*/
async function optimizeWithEsbuild(
content: string,
name: string,
options: OptimizeRequest['options'],
): Promise<TransformResult | BuildFailure> {
if (!esbuild) {
esbuild = new EsbuildExecutor(options.alwaysUseWasm);
}
try {
return await esbuild.transform(content, {
minifyIdentifiers: !options.keepIdentifierNames,
minifySyntax: true,
// NOTE: Disabling whitespace ensures unused pure annotations are kept
minifyWhitespace: false,
pure: ['forwardRef'],
legalComments: options.removeLicenses ? 'none' : 'inline',
sourcefile: name,
sourcemap: options.sourcemap && 'external',
define: options.define,
target: options.target,
});
} catch (error) {
if (isEsBuildFailure(error)) {
return error;
}
throw error;
}
}
/**
* Optimizes a JavaScript asset using terser.
*
* @param name The name of the JavaScript asset. Used to generate source maps.
* @param code The JavaScript asset source content to optimize.
* @param sourcemaps If true, generate an output source map for the optimized code.
* @param advanced Controls advanced optimizations.
* @returns A promise that resolves with the optimized code and source map.
*/
async function optimizeWithTerser(
name: string,
code: string,
sourcemaps: boolean | undefined,
advanced: boolean | undefined,
): Promise<{ code: string; map?: object }> {
const result = await minify(
{ [name]: code },
{
compress: {
passes: advanced ? 2 : 1,
pure_getters: advanced,
},
// Set to ES2015 to prevent higher level features from being introduced when browserslist
// contains older browsers. The build system requires browsers to support ES2015 at a minimum.
ecma: 2015,
// esbuild in the first pass is used to minify identifiers instead of mangle here
mangle: false,
// esbuild in the first pass is used to minify function names
keep_fnames: true,
format: {
// ASCII output is enabled here as well to prevent terser from converting back to UTF-8
ascii_only: true,
wrap_func_args: false,
},
sourceMap:
sourcemaps &&
({
asObject: true,
// typings don't include asObject option
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any),
},
);
if (typeof result.code !== 'string') {
throw new Error('Terser failed for unknown reason.');
}
return { code: result.code, map: result.map as object };
}
/**
* Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild.
* @param value A potential esbuild BuildFailure error object.
* @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`.
*/
function isEsBuildFailure(value: unknown): value is BuildFailure {
return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value;
}
| {
"end_byte": 7261,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/javascript-optimizer-worker.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/watch-files-logs-plugin.ts_0_846 | /**
* @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 type { Compiler } from 'webpack';
const PLUGIN_NAME = 'angular.watch-files-logs-plugin';
export class WatchFilesLogsPlugin {
apply(compiler: Compiler) {
compiler.hooks.watchRun.tap(PLUGIN_NAME, ({ modifiedFiles, removedFiles }) => {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const logger = compilation.getLogger(PLUGIN_NAME);
if (modifiedFiles?.size) {
logger.log(`Modified files:\n${[...modifiedFiles].join('\n')}\n`);
}
if (removedFiles?.size) {
logger.log(`Removed files:\n${[...removedFiles].join('\n')}\n`);
}
});
});
}
}
| {
"end_byte": 846,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/watch-files-logs-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/typescript.ts_0_2371 | /**
* @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 type { CompilerOptions } from '@angular/compiler-cli';
import { AngularWebpackPlugin } from '@ngtools/webpack';
import { ScriptTarget } from 'typescript';
import { WebpackConfigOptions } from '../../../utils/build-options';
export function createIvyPlugin(
wco: WebpackConfigOptions,
aot: boolean,
tsconfig: string,
): AngularWebpackPlugin {
const { buildOptions, tsConfig } = wco;
const optimize = buildOptions.optimization.scripts;
const compilerOptions: CompilerOptions = {
sourceMap: buildOptions.sourceMap.scripts,
declaration: false,
declarationMap: false,
};
if (tsConfig.options.target === undefined || tsConfig.options.target < ScriptTarget.ES2022) {
compilerOptions.target = ScriptTarget.ES2022;
// If 'useDefineForClassFields' is already defined in the users project leave the value as is.
// Otherwise fallback to false due to https://github.com/microsoft/TypeScript/issues/45995
// which breaks the deprecated `@Effects` NGRX decorator and potentially other existing code as well.
compilerOptions.useDefineForClassFields ??= false;
wco.logger.warn(
'TypeScript compiler options "target" and "useDefineForClassFields" are set to "ES2022" and ' +
'"false" respectively by the Angular CLI. To control ECMA version and features use the Browserslist configuration. ' +
'For more information, see https://angular.dev/tools/cli/build#configuring-browser-compatibility\n' +
`NOTE: You can set the "target" to "ES2022" in the project's tsconfig to remove this warning.`,
);
}
if (buildOptions.preserveSymlinks !== undefined) {
compilerOptions.preserveSymlinks = buildOptions.preserveSymlinks;
}
const fileReplacements: Record<string, string> = {};
if (buildOptions.fileReplacements) {
for (const replacement of buildOptions.fileReplacements) {
fileReplacements[replacement.replace] = replacement.with;
}
}
return new AngularWebpackPlugin({
tsconfig,
compilerOptions,
fileReplacements,
jitMode: !aot,
emitNgModuleScope: !optimize,
inlineStyleFileExtension: buildOptions.inlineStyleLanguage ?? 'css',
});
}
| {
"end_byte": 2371,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/typescript.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/index.ts_0_1017 | /**
* @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
*/
// Exports the webpack plugins we use internally.
export { AnyComponentStyleBudgetChecker } from './any-component-style-budget-checker';
export { ScriptsWebpackPlugin, type ScriptsWebpackPluginOptions } from './scripts-webpack-plugin';
export { SuppressExtractedTextChunksWebpackPlugin } from './suppress-entry-chunks-webpack-plugin';
export { RemoveHashPlugin, type RemoveHashPluginOptions } from './remove-hash-plugin';
export { DedupeModuleResolvePlugin } from './dedupe-module-resolve-plugin';
export { CommonJsUsageWarnPlugin } from './common-js-usage-warn-plugin';
export { JsonStatsPlugin } from './json-stats-plugin';
export { JavaScriptOptimizerPlugin } from './javascript-optimizer-plugin';
export {
default as PostcssCliResources,
type PostcssCliResourcesOptions,
} from './postcss-cli-resources';
| {
"end_byte": 1017,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/index.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/builder-watch-plugin.ts_0_4156 | /**
* @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 { Compiler } from 'webpack';
export type BuilderWatcherCallback = (
events: Array<{ path: string; type: 'created' | 'modified' | 'deleted'; time?: number }>,
) => void;
export interface BuilderWatcherFactory {
watch(
files: Iterable<string>,
directories: Iterable<string>,
callback: BuilderWatcherCallback,
): { close(): void };
}
class TimeInfoMap extends Map<string, { safeTime: number; timestamp: number }> {
update(path: string, timestamp: number): void {
this.set(path, Object.freeze({ safeTime: timestamp, timestamp }));
}
toTimestamps(): Map<string, number> {
const timestamps = new Map<string, number>();
for (const [file, entry] of this) {
timestamps.set(file, entry.timestamp);
}
return timestamps;
}
}
// Extract watch related types from the Webpack compiler type since they are not directly exported
type WebpackWatchFileSystem = NonNullable<Compiler['watchFileSystem']>;
type WatchOptions = Parameters<WebpackWatchFileSystem['watch']>[4];
type WatchCallback = Parameters<WebpackWatchFileSystem['watch']>[5];
class BuilderWatchFileSystem implements WebpackWatchFileSystem {
constructor(
private readonly watcherFactory: BuilderWatcherFactory,
private readonly inputFileSystem: Compiler['inputFileSystem'],
) {}
watch(
files: Iterable<string>,
directories: Iterable<string>,
missing: Iterable<string>,
startTime: number,
_options: WatchOptions,
callback: WatchCallback,
callbackUndelayed?: (file: string, time: number) => void,
): ReturnType<WebpackWatchFileSystem['watch']> {
const watchedFiles = new Set(files);
const watchedDirectories = new Set(directories);
const watchedMissing = new Set(missing);
const timeInfo = new TimeInfoMap();
for (const file of files) {
timeInfo.update(file, startTime);
}
for (const directory of directories) {
timeInfo.update(directory, startTime);
}
const watcher = this.watcherFactory.watch(files, directories, (events) => {
if (events.length === 0) {
return;
}
if (callbackUndelayed) {
process.nextTick(() => callbackUndelayed(events[0].path, events[0].time ?? Date.now()));
}
process.nextTick(() => {
const removals = new Set<string>();
const fileChanges = new Set<string>();
const directoryChanges = new Set<string>();
const missingChanges = new Set<string>();
for (const event of events) {
this.inputFileSystem?.purge?.(event.path);
if (event.type === 'deleted') {
timeInfo.delete(event.path);
removals.add(event.path);
} else {
timeInfo.update(event.path, event.time ?? Date.now());
if (watchedFiles.has(event.path)) {
fileChanges.add(event.path);
} else if (watchedDirectories.has(event.path)) {
directoryChanges.add(event.path);
} else if (watchedMissing.has(event.path)) {
missingChanges.add(event.path);
}
}
}
const timeInfoMap = new Map(timeInfo);
callback(
null,
timeInfoMap,
timeInfoMap,
new Set([...fileChanges, ...directoryChanges, ...missingChanges]),
removals,
);
});
});
return {
close() {
watcher.close();
},
pause() {},
getFileTimeInfoEntries() {
return new Map(timeInfo);
},
getContextTimeInfoEntries() {
return new Map(timeInfo);
},
};
}
}
export class BuilderWatchPlugin {
constructor(private readonly watcherFactory: BuilderWatcherFactory) {}
apply(compiler: Compiler): void {
compiler.hooks.environment.tap('BuilderWatchPlugin', () => {
compiler.watchFileSystem = new BuilderWatchFileSystem(
this.watcherFactory,
compiler.inputFileSystem,
);
});
}
}
| {
"end_byte": 4156,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/builder-watch-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/json-stats-plugin.ts_0_1232 | /**
* @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 { createWriteStream } from 'node:fs';
import { mkdir } from 'node:fs/promises';
import { dirname } from 'node:path';
import { pipeline } from 'node:stream/promises';
import { Compiler } from 'webpack';
import { assertIsError } from '../../../utils/error';
import { addError } from '../../../utils/webpack-diagnostics';
export class JsonStatsPlugin {
constructor(private readonly statsOutputPath: string) {}
apply(compiler: Compiler) {
compiler.hooks.done.tapPromise('angular-json-stats', async (stats) => {
const { stringifyChunked } = await import('@discoveryjs/json-ext');
const data = stats.toJson('verbose');
try {
await mkdir(dirname(this.statsOutputPath), { recursive: true });
await pipeline(stringifyChunked(data), createWriteStream(this.statsOutputPath));
} catch (error) {
assertIsError(error);
addError(
stats.compilation,
`Unable to write stats file: ${error.message || 'unknown error'}`,
);
}
});
}
}
| {
"end_byte": 1232,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/json-stats-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/progress-plugin.ts_0_1214 | /**
* @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 { ProgressPlugin as WebpackProgressPlugin } from 'webpack';
import { Spinner } from '../../../utils/spinner';
export class ProgressPlugin extends WebpackProgressPlugin {
constructor(platform: 'server' | 'browser') {
const platformCapitalFirst = platform.replace(/^\w/, (s) => s.toUpperCase());
const spinner = new Spinner();
spinner.start(`Generating ${platform} application bundles (phase: setup)...`);
super({
handler: (percentage: number, message: string) => {
const phase = message ? ` (phase: ${message})` : '';
spinner.text = `Generating ${platform} application bundles${phase}...`;
switch (percentage) {
case 1:
if (spinner.isSpinning) {
spinner.succeed(`${platformCapitalFirst} application bundle generation complete.`);
}
break;
case 0:
if (!spinner.isSpinning) {
spinner.start();
}
break;
}
},
});
}
}
| {
"end_byte": 1214,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/progress-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/dedupe-module-resolve-plugin.ts_0_3260 | /**
* @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 { Compiler } from 'webpack';
import { addWarning } from '../../../utils/webpack-diagnostics';
interface ResourceData {
relativePath: string;
resource: string;
packageName?: string;
packageVersion?: string;
}
export interface DedupeModuleResolvePluginOptions {
verbose?: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getResourceData(resolveData: any): ResourceData {
const { descriptionFileData, relativePath } = resolveData.createData.resourceResolveData;
return {
packageName: descriptionFileData?.name,
packageVersion: descriptionFileData?.version,
relativePath,
resource: resolveData.createData.resource,
};
}
/**
* DedupeModuleResolvePlugin is a webpack plugin which dedupes modules with the same name and versions
* that are laid out in different parts of the node_modules tree.
*
* This is needed because Webpack relies on package managers to hoist modules and doesn't have any deduping logic.
*
* This is similar to how Webpack's 'NormalModuleReplacementPlugin' works
* @see https://github.com/webpack/webpack/blob/4a1f068828c2ab47537d8be30d542cd3a1076db4/lib/NormalModuleReplacementPlugin.js#L9
*/
export class DedupeModuleResolvePlugin {
modules = new Map<string, { request: string; resource: string }>();
constructor(private options?: DedupeModuleResolvePluginOptions) {}
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(
'DedupeModuleResolvePlugin',
(compilation, { normalModuleFactory }) => {
normalModuleFactory.hooks.afterResolve.tap('DedupeModuleResolvePlugin', (result) => {
if (!result) {
return;
}
const { packageName, packageVersion, relativePath, resource } = getResourceData(result);
// Empty name or versions are no valid primary entrypoints of a library
if (!packageName || !packageVersion) {
return;
}
const moduleId = packageName + '@' + packageVersion + ':' + relativePath;
const prevResolvedModule = this.modules.get(moduleId);
if (!prevResolvedModule) {
// This is the first time we visit this module.
this.modules.set(moduleId, {
resource,
request: result.request,
});
return;
}
const { resource: prevResource, request: prevRequest } = prevResolvedModule;
if (resource === prevResource) {
// No deduping needed.
// Current path and previously resolved path are the same.
return;
}
if (this.options?.verbose) {
addWarning(compilation, `[DedupeModuleResolvePlugin]: ${resource} -> ${prevResource}`);
}
// Alter current request with previously resolved module.
const createData = result.createData as { resource: string; userRequest: string };
createData.resource = prevResource;
createData.userRequest = prevRequest;
});
},
);
}
}
| {
"end_byte": 3260,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/dedupe-module-resolve-plugin.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/hmr/hmr-loader.ts_0_706 | /**
* @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 { join } from 'path';
export const HmrLoader = __filename;
const hmrAcceptPath = join(__dirname, './hmr-accept.js').replace(/\\/g, '/');
export default function localizeExtractLoader(
this: import('webpack').LoaderContext<{}>,
content: string,
map: Parameters<import('webpack').LoaderDefinitionFunction>[1],
) {
const source = `${content}
// HMR Accept Code
import ngHmrAccept from '${hmrAcceptPath}';
ngHmrAccept(module);
`;
this.callback(null, source, map);
return;
}
| {
"end_byte": 706,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/hmr/hmr-loader.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/hmr/hmr-accept.ts_0_6736 | /**
* @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
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import {
ApplicationRef,
PlatformRef,
Type,
isDevMode,
ɵresetCompiledComponents,
} from '@angular/core';
import { filter, take } from 'rxjs';
// For the time being we cannot use the DOM lib because it conflicts with @types/node,
// In future when we remove `yarn admin build` we should have this as a seperate compilation unit
// which includes DOM lib.
/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/no-explicit-any */
declare const ng: any;
declare const document: any;
declare const MutationObserver: any;
declare const KeyboardEvent: any;
declare const Event: any;
export default function (mod: any): void {
if (!mod['hot']) {
return;
}
if (!isDevMode()) {
console.error(
`[NG HMR] Cannot use HMR when Angular is running in production mode. To prevent production mode, do not call 'enableProdMode()'.`,
);
return;
}
mod['hot'].accept();
mod['hot'].dispose(() => {
if (typeof ng === 'undefined') {
console.warn(
`[NG HMR] Cannot find global 'ng'. Likely this is caused because scripts optimization is enabled.`,
);
return;
}
if (!ng.getInjector) {
// View Engine
return;
}
// Reset JIT compiled components cache
ɵresetCompiledComponents();
const appRoot = getAppRoot();
if (!appRoot) {
return;
}
const appRef = getApplicationRef(appRoot);
if (!appRef) {
return;
}
// Inputs that are hidden should be ignored
const oldInputs = document.querySelectorAll('input:not([type="hidden"]), textarea');
const oldOptions = document.querySelectorAll('option');
// Create new application
appRef.components.forEach((cp) => {
const element = cp.location.nativeElement;
const parentNode = element.parentNode;
parentNode.insertBefore(document.createElement(element.tagName), element);
parentNode.removeChild(element);
});
// Destroy old application, injectors, <style..., etc..
const platformRef = getPlatformRef(appRoot);
if (platformRef) {
platformRef.destroy();
}
// Restore all inputs and options
const bodyElement = document.body;
if (oldInputs.length + oldOptions.length === 0 || !bodyElement) {
return;
}
// Use a `MutationObserver` to wait until the app-root element has been bootstrapped.
// ie: when the ng-version attribute is added.
new MutationObserver((_mutationsList: any, observer: any) => {
observer.disconnect();
const newAppRoot = getAppRoot();
if (!newAppRoot) {
return;
}
const newAppRef = getApplicationRef(newAppRoot);
if (!newAppRef) {
return;
}
// Wait until the application isStable to restore the form values
newAppRef.isStable
.pipe(
filter((isStable) => !!isStable),
take(1),
)
.subscribe(() => restoreFormValues(oldInputs, oldOptions));
}).observe(bodyElement, {
attributes: true,
subtree: true,
attributeFilter: ['ng-version'],
});
});
}
function getAppRoot(): any {
const appRoot = document.querySelector('[ng-version]');
if (!appRoot) {
console.warn('[NG HMR] Cannot find the application root component.');
return undefined;
}
return appRoot;
}
function getToken<T>(appRoot: any, token: Type<T>): T | undefined {
return (typeof ng === 'object' && ng.getInjector(appRoot).get(token)) || undefined;
}
function getApplicationRef(appRoot: any): ApplicationRef | undefined {
const appRef = getToken(appRoot, ApplicationRef);
if (!appRef) {
console.warn(`[NG HMR] Cannot get 'ApplicationRef'.`);
return undefined;
}
return appRef;
}
function getPlatformRef(appRoot: any): PlatformRef | undefined {
const platformRef = getToken(appRoot, PlatformRef);
if (!platformRef) {
console.warn(`[NG HMR] Cannot get 'PlatformRef'.`);
return undefined;
}
return platformRef;
}
function dispatchEvents(element: any): void {
element.dispatchEvent(
new Event('input', {
bubbles: true,
cancelable: true,
}),
);
element.blur();
element.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }));
}
function restoreFormValues(oldInputs: any[], oldOptions: any[]): void {
// Restore input that are not hidden
const newInputs = document.querySelectorAll('input:not([type="hidden"]), textarea');
if (newInputs.length && newInputs.length === oldInputs.length) {
console.log('[NG HMR] Restoring input/textarea values.');
for (let index = 0; index < newInputs.length; index++) {
const newElement = newInputs[index];
const oldElement = oldInputs[index];
switch (oldElement.type) {
case 'button':
case 'image':
case 'submit':
case 'reset':
// These types don't need any value change.
continue;
case 'radio':
case 'checkbox':
newElement.checked = oldElement.checked;
break;
case 'color':
case 'date':
case 'datetime-local':
case 'email':
case 'hidden':
case 'month':
case 'number':
case 'password':
case 'range':
case 'search':
case 'tel':
case 'text':
case 'textarea':
case 'time':
case 'url':
case 'week':
newElement.value = oldElement.value;
break;
case 'file':
// Ignored due: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement':
// This input element accepts a filename, which may only be programmatically set to the empty string.
break;
default:
console.warn('[NG HMR] Unknown input type ' + oldElement.type + '.');
continue;
}
dispatchEvents(newElement);
}
} else if (oldInputs.length) {
console.warn('[NG HMR] Cannot restore input/textarea values.');
}
// Restore option
const newOptions = document.querySelectorAll('option');
if (newOptions.length && newOptions.length === oldOptions.length) {
console.log('[NG HMR] Restoring selected options.');
for (let index = 0; index < newOptions.length; index++) {
const newElement = newOptions[index];
newElement.selected = oldOptions[index].selected;
dispatchEvents(newElement);
}
} else if (oldOptions.length) {
console.warn('[NG HMR] Cannot restore selected options.');
}
}
| {
"end_byte": 6736,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/hmr/hmr-accept.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts_0_8036 | /**
* @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
*/
/* eslint-disable */
// TODO: cleanup this file, it's copied as is from Angular CLI.
import * as http from 'http';
import * as path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import { statsErrorsToString } from '../../utils/stats';
import { createConsoleLogger } from '@angular-devkit/core/node';
import { logging } from '@angular-devkit/core';
import { BuildOptions } from '../../../../utils/build-options';
import { normalizeSourceMaps } from '../../../../utils/index';
const KARMA_APPLICATION_PATH = '_karma_webpack_';
let blocked: any[] = [];
let isBlocked = false;
let webpackMiddleware: any;
let successCb: () => void;
let failureCb: () => void;
const init: any = (config: any, emitter: any) => {
if (!config.buildWebpack) {
throw new Error(
`The '@angular-devkit/build-angular/plugins/karma' karma plugin is meant to` +
` be used from within Angular CLI and will not work correctly outside of it.`,
);
}
const options = config.buildWebpack.options as BuildOptions;
const logger: logging.Logger = config.buildWebpack.logger || createConsoleLogger();
successCb = config.buildWebpack.successCb;
failureCb = config.buildWebpack.failureCb;
// Add a reporter that fixes sourcemap urls.
if (normalizeSourceMaps(options.sourceMap).scripts) {
config.reporters.unshift('@angular-devkit/build-angular--sourcemap-reporter');
// Code taken from https://github.com/tschaub/karma-source-map-support.
// We can't use it directly because we need to add it conditionally in this file, and karma
// frameworks cannot be added dynamically.
const smsPath = path.dirname(require.resolve('source-map-support'));
const ksmsPath = path.dirname(require.resolve('karma-source-map-support'));
config.files.unshift(
{
pattern: path.join(smsPath, 'browser-source-map-support.js'),
included: true,
served: true,
watched: false,
},
{ pattern: path.join(ksmsPath, 'client.js'), included: true, served: true, watched: false },
);
}
config.reporters.unshift('@angular-devkit/build-angular--event-reporter');
// When using code-coverage, auto-add karma-coverage.
if (
options.codeCoverage &&
!config.reporters.some((r: string) => r === 'coverage' || r === 'coverage-istanbul')
) {
config.reporters.push('coverage');
}
// Add webpack config.
const webpackConfig = config.buildWebpack.webpackConfig;
const webpackMiddlewareConfig = {
// Hide webpack output because its noisy.
stats: false,
publicPath: `/${KARMA_APPLICATION_PATH}/`,
};
// Use existing config if any.
config.webpack = { ...webpackConfig, ...config.webpack };
config.webpackMiddleware = { ...webpackMiddlewareConfig, ...config.webpackMiddleware };
// Our custom context and debug files list the webpack bundles directly instead of using
// the karma files array.
config.customContextFile = `${__dirname}/karma-context.html`;
config.customDebugFile = `${__dirname}/karma-debug.html`;
// Add the request blocker and the webpack server fallback.
config.beforeMiddleware = config.beforeMiddleware || [];
config.beforeMiddleware.push('@angular-devkit/build-angular--blocker');
config.middleware = config.middleware || [];
config.middleware.push('@angular-devkit/build-angular--fallback');
if (config.singleRun) {
// There's no option to turn off file watching in webpack-dev-server, but
// we can override the file watcher instead.
webpackConfig.plugins.unshift({
apply: (compiler: any) => {
compiler.hooks.afterEnvironment.tap('karma', () => {
compiler.watchFileSystem = { watch: () => {} };
});
},
});
}
// Files need to be served from a custom path for Karma.
webpackConfig.output.path = `/${KARMA_APPLICATION_PATH}/`;
webpackConfig.output.publicPath = `/${KARMA_APPLICATION_PATH}/`;
const compiler = webpack(webpackConfig, (error, stats) => {
if (error) {
throw error;
}
if (stats?.hasErrors()) {
// Only generate needed JSON stats and when needed.
const statsJson = stats?.toJson({
all: false,
children: true,
errors: true,
warnings: true,
});
logger.error(statsErrorsToString(statsJson, { colors: true }));
if (config.singleRun) {
// Notify potential listeners of the compile error.
emitter.emit('load_error');
}
// Finish Karma run early in case of compilation error.
emitter.emit('run_complete', [], { exitCode: 1 });
// Emit a failure build event if there are compilation errors.
failureCb();
}
});
function handler(callback?: () => void): void {
isBlocked = true;
callback?.();
}
compiler.hooks.invalid.tap('karma', () => handler());
compiler.hooks.watchRun.tapAsync('karma', (_: any, callback: () => void) => handler(callback));
compiler.hooks.run.tapAsync('karma', (_: any, callback: () => void) => handler(callback));
webpackMiddleware = webpackDevMiddleware(compiler, webpackMiddlewareConfig);
emitter.on('exit', (done: any) => {
webpackMiddleware.close();
compiler.close(() => done());
});
function unblock() {
isBlocked = false;
blocked.forEach((cb) => cb());
blocked = [];
}
let lastCompilationHash: string | undefined;
let isFirstRun = true;
return new Promise<void>((resolve) => {
compiler.hooks.done.tap('karma', (stats) => {
if (isFirstRun) {
// This is needed to block Karma from launching browsers before Webpack writes the assets in memory.
// See the below:
// https://github.com/karma-runner/karma-chrome-launcher/issues/154#issuecomment-986661937
// https://github.com/angular/angular-cli/issues/22495
isFirstRun = false;
resolve();
}
if (stats.hasErrors()) {
lastCompilationHash = undefined;
} else if (stats.hash != lastCompilationHash) {
// Refresh karma only when there are no webpack errors, and if the compilation changed.
lastCompilationHash = stats.hash;
emitter.refreshFiles();
}
unblock();
});
});
};
init.$inject = ['config', 'emitter'];
// Block requests until the Webpack compilation is done.
function requestBlocker() {
return function (_request: any, _response: any, next: () => void) {
if (isBlocked) {
blocked.push(next);
} else {
next();
}
};
}
// Copied from "karma-jasmine-diff-reporter" source code:
// In case, when multiple reporters are used in conjunction
// with initSourcemapReporter, they both will show repetitive log
// messages when displaying everything that supposed to write to terminal.
// So just suppress any logs from initSourcemapReporter by doing nothing on
// browser log, because it is an utility reporter,
// unless it's alone in the "reporters" option and base reporter is used.
function muteDuplicateReporterLogging(context: any, config: any) {
context.writeCommonMsg = () => {};
const reporterName = '@angular/cli';
const hasTrailingReporters = config.reporters.slice(-1).pop() !== reporterName;
if (hasTrailingReporters) {
context.writeCommonMsg = () => {};
}
}
// Emits builder events.
const eventReporter: any = function (this: any, baseReporterDecorator: any, config: any) {
baseReporterDecorator(this);
muteDuplicateReporterLogging(this, config);
this.onRunComplete = function (_browsers: any, results: any) {
if (results.exitCode === 0) {
successCb();
} else {
failureCb();
}
};
// avoid duplicate failure message
this.specFailure = () => {};
};
eventReporter.$inject = ['baseReporterDecorator', 'config'];
// Strip the server address and webpack scheme (webpack://) from error log. | {
"end_byte": 8036,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts_8037_10119 | const sourceMapReporter: any = function (this: any, baseReporterDecorator: any, config: any) {
baseReporterDecorator(this);
muteDuplicateReporterLogging(this, config);
const urlRegexp = /http:\/\/localhost:\d+\/_karma_webpack_\/(webpack:\/)?/gi;
this.onSpecComplete = function (_browser: any, result: any) {
if (!result.success) {
result.log = result.log.map((l: string) => l.replace(urlRegexp, ''));
}
};
// avoid duplicate complete message
this.onRunComplete = () => {};
// avoid duplicate failure message
this.specFailure = () => {};
};
sourceMapReporter.$inject = ['baseReporterDecorator', 'config'];
// When a request is not found in the karma server, try looking for it from the webpack server root.
function fallbackMiddleware() {
return function (request: http.IncomingMessage, response: http.ServerResponse, next: () => void) {
if (webpackMiddleware) {
if (request.url && !new RegExp(`\\/${KARMA_APPLICATION_PATH}\\/.*`).test(request.url)) {
request.url = '/' + KARMA_APPLICATION_PATH + request.url;
}
webpackMiddleware(request, response, () => {
const alwaysServe = [
`/${KARMA_APPLICATION_PATH}/runtime.js`,
`/${KARMA_APPLICATION_PATH}/polyfills.js`,
`/${KARMA_APPLICATION_PATH}/scripts.js`,
`/${KARMA_APPLICATION_PATH}/styles.css`,
`/${KARMA_APPLICATION_PATH}/vendor.js`,
];
if (request.url && alwaysServe.includes(request.url)) {
response.statusCode = 200;
response.end();
} else {
next();
}
});
} else {
next();
}
};
}
module.exports = {
'framework:@angular-devkit/build-angular': ['factory', init],
'reporter:@angular-devkit/build-angular--sourcemap-reporter': ['type', sourceMapReporter],
'reporter:@angular-devkit/build-angular--event-reporter': ['type', eventReporter],
'middleware:@angular-devkit/build-angular--blocker': ['factory', requestBlocker],
'middleware:@angular-devkit/build-angular--fallback': ['factory', fallbackMiddleware],
}; | {
"end_byte": 10119,
"start_byte": 8037,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-debug.html_0_1834 | <!DOCTYPE html>
<!--
This file is almost the same as context.html - loads all source files,
but its purpose is to be loaded in the main frame (not within an iframe),
just for immediate execution, without reporting to Karma server.
-->
<html>
<head>
%X_UA_COMPATIBLE%
<title>Karma DEBUG RUNNER</title>
<base href="/" />
<link href="favicon.ico" rel="icon" type="image/x-icon" />
<link rel="stylesheet" href="_karma_webpack_/styles.css" crossorigin="anonymous" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
</head>
<body>
<!-- The scripts need to be at the end of body, so that some test running frameworks
(Angular Scenario, for example) need the body to be loaded so that it can insert its magic
into it. If it is before body, then it fails to find the body and crashes and burns in an epic
manner. -->
<script src="context.js"></script>
<script src="debug.js"></script>
<script type="text/javascript">
// Configure our Karma
%CLIENT_CONFIG%
// All served files with the latest timestamps
%MAPPINGS%
</script>
<script src="_karma_webpack_/runtime.js" crossorigin="anonymous"></script>
<script src="_karma_webpack_/polyfills.js" crossorigin="anonymous"></script>
<!-- Dynamically replaced with <script> tags -->
%SCRIPTS%
<script src="_karma_webpack_/scripts.js" crossorigin="anonymous" defer></script>
<script src="_karma_webpack_/vendor.js" crossorigin="anonymous" type="module"></script>
<script src="_karma_webpack_/main.js" crossorigin="anonymous" type="module"></script>
<script type="module">
window.__karma__.loaded();
</script>
</body>
</html>
| {
"end_byte": 1834,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-debug.html"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-context.html_0_1678 | <!DOCTYPE html>
<!--
This is the execution context.
Loaded within the iframe.
Reloaded before every execution run.
-->
<html>
<head>
<title></title>
<base href="/" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="_karma_webpack_/styles.css" crossorigin="anonymous" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
</head>
<body>
<!-- The scripts need to be in the body DOM element, as some test running frameworks need the body
to have already been created so they can insert their magic into it. For example, if loaded
before body, Angular Scenario test framework fails to find the body and crashes and burns in
an epic manner. -->
<script src="context.js"></script>
<script type="text/javascript">
// Configure our Karma and set up bindings
%CLIENT_CONFIG%
window.__karma__.setupContext(window);
// All served files with the latest timestamps
%MAPPINGS%
</script>
<script src="_karma_webpack_/runtime.js" crossorigin="anonymous"></script>
<script src="_karma_webpack_/polyfills.js" crossorigin="anonymous"></script>
<!-- Dynamically replaced with <script> tags -->
%SCRIPTS%
<script src="_karma_webpack_/scripts.js" crossorigin="anonymous" defer></script>
<script src="_karma_webpack_/vendor.js" crossorigin="anonymous" type="module"></script>
<script src="_karma_webpack_/main.js" crossorigin="anonymous" type="module"></script>
<script type="module">
window.__karma__.loaded();
</script>
</body>
</html>
| {
"end_byte": 1678,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-context.html"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts_0_8020 | /**
* @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 type { ObjectPattern } from 'copy-webpack-plugin';
import { createHash } from 'crypto';
import glob from 'fast-glob';
import * as path from 'path';
import type { Configuration, WebpackOptionsNormalized } from 'webpack';
import {
AssetPatternClass,
OutputHashing,
ScriptElement,
StyleElement,
} from '../../../builders/browser/schema';
import { WebpackConfigOptions } from '../../../utils/build-options';
import { VERSION } from '../../../utils/package-version';
export interface HashFormat {
chunk: string;
extract: string;
file: string;
script: string;
}
export type WebpackStatsOptions = Exclude<Configuration['stats'], string | boolean | undefined>;
export function getOutputHashFormat(outputHashing = OutputHashing.None, length = 20): HashFormat {
const hashTemplate = `.[contenthash:${length}]`;
switch (outputHashing) {
case 'media':
return {
chunk: '',
extract: '',
file: hashTemplate,
script: '',
};
case 'bundles':
return {
chunk: hashTemplate,
extract: hashTemplate,
file: '',
script: hashTemplate,
};
case 'all':
return {
chunk: hashTemplate,
extract: hashTemplate,
file: hashTemplate,
script: hashTemplate,
};
case 'none':
default:
return {
chunk: '',
extract: '',
file: '',
script: '',
};
}
}
export type NormalizedEntryPoint = Required<Exclude<ScriptElement | StyleElement, string>>;
export function normalizeExtraEntryPoints(
extraEntryPoints: (ScriptElement | StyleElement)[],
defaultBundleName: string,
): NormalizedEntryPoint[] {
return extraEntryPoints.map((entry) => {
if (typeof entry === 'string') {
return { input: entry, inject: true, bundleName: defaultBundleName };
}
const { inject = true, ...newEntry } = entry;
let bundleName;
if (entry.bundleName) {
bundleName = entry.bundleName;
} else if (!inject) {
// Lazy entry points use the file name as bundle name.
bundleName = path.parse(entry.input).name;
} else {
bundleName = defaultBundleName;
}
return { ...newEntry, inject, bundleName };
});
}
export function assetNameTemplateFactory(hashFormat: HashFormat): (resourcePath: string) => string {
const visitedFiles = new Map<string, string>();
return (resourcePath: string) => {
if (hashFormat.file) {
// File names are hashed therefore we don't need to handle files with the same file name.
return `[name]${hashFormat.file}.[ext]`;
}
const filename = path.basename(resourcePath);
// Check if the file with the same name has already been processed.
const visited = visitedFiles.get(filename);
if (!visited) {
// Not visited.
visitedFiles.set(filename, resourcePath);
return filename;
} else if (visited === resourcePath) {
// Same file.
return filename;
}
// File has the same name but it's in a different location.
return '[path][name].[ext]';
};
}
export function getInstrumentationExcludedPaths(
root: string,
excludedPaths: string[],
): Set<string> {
const excluded = new Set<string>();
for (const excludeGlob of excludedPaths) {
const excludePath = excludeGlob[0] === '/' ? excludeGlob.slice(1) : excludeGlob;
glob.sync(excludePath, { cwd: root }).forEach((p) => excluded.add(path.join(root, p)));
}
return excluded;
}
export function normalizeGlobalStyles(styleEntrypoints: StyleElement[]): {
entryPoints: Record<string, string[]>;
noInjectNames: string[];
} {
const entryPoints: Record<string, string[]> = {};
const noInjectNames: string[] = [];
if (styleEntrypoints.length === 0) {
return { entryPoints, noInjectNames };
}
for (const style of normalizeExtraEntryPoints(styleEntrypoints, 'styles')) {
// Add style entry points.
entryPoints[style.bundleName] ??= [];
entryPoints[style.bundleName].push(style.input);
// Add non injected styles to the list.
if (!style.inject) {
noInjectNames.push(style.bundleName);
}
}
return { entryPoints, noInjectNames };
}
export function getCacheSettings(
wco: WebpackConfigOptions,
angularVersion: string,
): WebpackOptionsNormalized['cache'] {
const { enabled, path: cacheDirectory } = wco.buildOptions.cache;
if (enabled) {
return {
type: 'filesystem',
profile: wco.buildOptions.verbose,
cacheDirectory: path.join(cacheDirectory, 'angular-webpack'),
maxMemoryGenerations: 1,
// We use the versions and build options as the cache name. The Webpack configurations are too
// dynamic and shared among different build types: test, build and serve.
// None of which are "named".
name: createHash('sha1')
.update(angularVersion)
.update(VERSION)
.update(wco.projectRoot)
.update(JSON.stringify(wco.tsConfig))
.update(
JSON.stringify({
...wco.buildOptions,
// Needed because outputPath changes on every build when using i18n extraction
// https://github.com/angular/angular-cli/blob/736a5f89deaca85f487b78aec9ff66d4118ceb6a/packages/angular_devkit/build_angular/src/utils/i18n-options.ts#L264-L265
outputPath: undefined,
}),
)
.digest('hex'),
};
}
if (wco.buildOptions.watch) {
return {
type: 'memory',
maxGenerations: 1,
};
}
return false;
}
export function globalScriptsByBundleName(
scripts: ScriptElement[],
): { bundleName: string; inject: boolean; paths: string[] }[] {
return normalizeExtraEntryPoints(scripts, 'scripts').reduce(
(prev: { bundleName: string; paths: string[]; inject: boolean }[], curr) => {
const { bundleName, inject, input } = curr;
const existingEntry = prev.find((el) => el.bundleName === bundleName);
if (existingEntry) {
if (existingEntry.inject && !inject) {
// All entries have to be lazy for the bundle to be lazy.
throw new Error(`The ${bundleName} bundle is mixing injected and non-injected scripts.`);
}
existingEntry.paths.push(input);
} else {
prev.push({
bundleName,
inject,
paths: [input],
});
}
return prev;
},
[],
);
}
export function assetPatterns(root: string, assets: AssetPatternClass[]) {
return assets.map((asset: AssetPatternClass, index: number): ObjectPattern => {
// Resolve input paths relative to workspace root and add slash at the end.
// eslint-disable-next-line prefer-const
let { input, output = '', ignore = [], glob } = asset;
input = path.resolve(root, input).replace(/\\/g, '/');
input = input.endsWith('/') ? input : input + '/';
output = output.endsWith('/') ? output : output + '/';
if (output.startsWith('..')) {
throw new Error('An asset cannot be written to a location outside of the output path.');
}
return {
context: input,
// Now we remove starting slash to make Webpack place it from the output root.
to: output.replace(/^\//, ''),
from: glob,
noErrorOnMissing: true,
force: true,
globOptions: {
dot: true,
followSymbolicLinks: !!asset.followSymlinks,
ignore: [
'.gitkeep',
'**/.DS_Store',
'**/Thumbs.db',
// Negate patterns needs to be absolute because copy-webpack-plugin uses absolute globs which
// causes negate patterns not to match.
// See: https://github.com/webpack-contrib/copy-webpack-plugin/issues/498#issuecomment-639327909
...ignore,
].map((i) => path.posix.join(input, i)),
},
priority: index,
};
});
} | {
"end_byte": 8020,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts_8022_9751 | export function getStatsOptions(verbose = false): WebpackStatsOptions {
const webpackOutputOptions: WebpackStatsOptions = {
all: false, // Fallback value for stats options when an option is not defined. It has precedence over local webpack defaults.
colors: true,
hash: true, // required by custom stat output
timings: true, // required by custom stat output
chunks: true, // required by custom stat output
builtAt: true, // required by custom stat output
warnings: true,
errors: true,
assets: true, // required by custom stat output
cachedAssets: true, // required for bundle size calculators
// Needed for markAsyncChunksNonInitial.
ids: true,
entrypoints: true,
};
const verboseWebpackOutputOptions: WebpackStatsOptions = {
// The verbose output will most likely be piped to a file, so colors just mess it up.
colors: false,
usedExports: true,
optimizationBailout: true,
reasons: true,
children: true,
assets: true,
version: true,
chunkModules: true,
errorDetails: true,
errorStack: true,
moduleTrace: true,
logging: 'verbose',
modulesSpace: Infinity,
};
return verbose
? { ...webpackOutputOptions, ...verboseWebpackOutputOptions }
: webpackOutputOptions;
}
/**
* Checks if a specified package is installed in the given workspace.
*
* @param root - The root directory of the workspace.
* @param name - The name of the package to check for.
* @returns `true` if the package is installed, `false` otherwise.
*/
export function isPackageInstalled(root: string, name: string): boolean {
try {
require.resolve(name, { paths: [root] });
return true;
} catch {
return false;
}
} | {
"end_byte": 9751,
"start_byte": 8022,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts_0_7920 | /**
* @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 {
BudgetCalculatorResult,
BundleStats,
generateBuildStatsTable,
} from '@angular/build/private';
import { WebpackLoggingCallback } from '@angular-devkit/build-webpack';
import { logging } from '@angular-devkit/core';
import assert from 'node:assert';
import * as path from 'node:path';
import { Configuration, StatsCompilation } from 'webpack';
import { Schema as BrowserBuilderOptions } from '../../../builders/browser/schema';
import { normalizeOptimization } from '../../../utils';
import { colors as ansiColors } from '../../../utils/color';
import { markAsyncChunksNonInitial } from './async-chunks';
import { WebpackStatsOptions, getStatsOptions, normalizeExtraEntryPoints } from './helpers';
function getBuildDuration(webpackStats: StatsCompilation): number {
assert(webpackStats.builtAt, 'buildAt cannot be undefined');
assert(webpackStats.time, 'time cannot be undefined');
return Date.now() - webpackStats.builtAt + webpackStats.time;
}
function generateBundleStats(info: {
rawSize?: number;
estimatedTransferSize?: number;
files?: string[];
names?: string[];
initial?: boolean;
rendered?: boolean;
}): BundleStats {
const rawSize = typeof info.rawSize === 'number' ? info.rawSize : '-';
const estimatedTransferSize =
typeof info.estimatedTransferSize === 'number' ? info.estimatedTransferSize : '-';
const files =
info.files
?.filter((f) => !f.endsWith('.map'))
.map((f) => path.basename(f))
.join(', ') ?? '';
const names = info.names?.length ? info.names.join(', ') : '-';
const initial = !!info.initial;
return {
initial,
stats: [files, names, rawSize, estimatedTransferSize],
};
}
// We use this cache because we can have multiple builders running in the same process,
// where each builder has different output path.
// Ideally, we should create the logging callback as a factory, but that would need a refactoring.
const runsCache = new Set<string>();
function statsToString(
json: StatsCompilation,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
statsConfig: any,
budgetFailures?: BudgetCalculatorResult[],
): string {
if (!json.chunks?.length) {
return '';
}
const colors = statsConfig.colors;
const rs = (x: string) => (colors ? ansiColors.reset(x) : x);
const w = (x: string) => (colors ? ansiColors.bold.white(x) : x);
const changedChunksStats: BundleStats[] = [];
let unchangedChunkNumber = 0;
let hasEstimatedTransferSizes = false;
const isFirstRun = !runsCache.has(json.outputPath || '');
for (const chunk of json.chunks) {
// During first build we want to display unchanged chunks
// but unchanged cached chunks are always marked as not rendered.
if (!isFirstRun && !chunk.rendered) {
continue;
}
const assets = json.assets?.filter((asset) => chunk.files?.includes(asset.name));
let rawSize = 0;
let estimatedTransferSize;
if (assets) {
for (const asset of assets) {
if (asset.name.endsWith('.map')) {
continue;
}
rawSize += asset.size;
if (typeof asset.info.estimatedTransferSize === 'number') {
if (estimatedTransferSize === undefined) {
estimatedTransferSize = 0;
hasEstimatedTransferSizes = true;
}
estimatedTransferSize += asset.info.estimatedTransferSize;
}
}
}
changedChunksStats.push(generateBundleStats({ ...chunk, rawSize, estimatedTransferSize }));
}
unchangedChunkNumber = json.chunks.length - changedChunksStats.length;
runsCache.add(json.outputPath || '');
const statsTable = generateBuildStatsTable(
changedChunksStats,
colors,
unchangedChunkNumber === 0,
hasEstimatedTransferSizes,
budgetFailures,
);
// In some cases we do things outside of webpack context
// Such us index generation, service worker augmentation etc...
// This will correct the time and include these.
const time = getBuildDuration(json);
return rs(
`\n${statsTable}\n\n` +
(unchangedChunkNumber > 0 ? `${unchangedChunkNumber} unchanged chunks\n\n` : '') +
`Build at: ${w(new Date().toISOString())} - Hash: ${w(json.hash || '')} - Time: ${w('' + time)}ms`,
);
}
export function statsWarningsToString(
json: StatsCompilation,
statsConfig: WebpackStatsOptions,
): string {
const colors = statsConfig.colors;
const c = (x: string) => (colors ? ansiColors.reset.cyan(x) : x);
const y = (x: string) => (colors ? ansiColors.reset.yellow(x) : x);
const yb = (x: string) => (colors ? ansiColors.reset.yellowBright(x) : x);
const warnings = json.warnings ? [...json.warnings] : [];
if (json.children) {
warnings.push(...json.children.map((c) => c.warnings ?? []).reduce((a, b) => [...a, ...b], []));
}
let output = '';
for (const warning of warnings) {
if (typeof warning === 'string') {
output += yb(`Warning: ${warning}\n\n`);
} else {
let file = warning.file || warning.moduleName;
// Clean up warning paths
// Ex: ./src/app/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js....
// to ./src/app/styles.scss.webpack
if (file && !statsConfig.errorDetails) {
const webpackPathIndex = file.indexOf('.webpack[');
if (webpackPathIndex !== -1) {
file = file.substring(0, webpackPathIndex);
}
}
if (file) {
output += c(file);
if (warning.loc) {
output += ':' + yb(warning.loc);
}
output += ' - ';
}
if (!/^warning/i.test(warning.message)) {
output += y('Warning: ');
}
output += `${warning.message}\n\n`;
}
}
return output ? '\n' + output : output;
}
export function statsErrorsToString(
json: StatsCompilation,
statsConfig: WebpackStatsOptions,
): string {
const colors = statsConfig.colors;
const c = (x: string) => (colors ? ansiColors.reset.cyan(x) : x);
const yb = (x: string) => (colors ? ansiColors.reset.yellowBright(x) : x);
const r = (x: string) => (colors ? ansiColors.reset.redBright(x) : x);
const errors = json.errors ? [...json.errors] : [];
if (json.children) {
errors.push(...json.children.map((c) => c?.errors || []).reduce((a, b) => [...a, ...b], []));
}
let output = '';
for (const error of errors) {
if (typeof error === 'string') {
output += r(`Error: ${error}\n\n`);
} else {
let file = error.file || error.moduleName;
// Clean up error paths
// Ex: ./src/app/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js....
// to ./src/app/styles.scss.webpack
if (file && !statsConfig.errorDetails) {
const webpackPathIndex = file.indexOf('.webpack[');
if (webpackPathIndex !== -1) {
file = file.substring(0, webpackPathIndex);
}
}
if (file) {
output += c(file);
if (error.loc) {
output += ':' + yb(error.loc);
}
output += ' - ';
}
// In most cases webpack will add stack traces to error messages.
// This below cleans up the error from stacks.
// See: https://github.com/webpack/webpack/issues/15980
const index = error.message.search(/[\n\s]+at /);
const message =
statsConfig.errorStack || index === -1 ? error.message : error.message.substring(0, index);
if (!/^error/i.test(message)) {
output += r('Error: ');
}
output += `${message}\n\n`;
}
}
return output ? '\n' + output : output;
}
export function statsHasErrors(json: StatsCompilation): boolean {
return !!(json.errors?.length || json.children?.some((c) => c.errors?.length));
} | {
"end_byte": 7920,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts_7922_11186 | export function statsHasWarnings(json: StatsCompilation): boolean {
return !!(json.warnings?.length || json.children?.some((c) => c.warnings?.length));
}
export function createWebpackLoggingCallback(
options: BrowserBuilderOptions,
logger: logging.LoggerApi,
): WebpackLoggingCallback {
const { verbose = false, scripts = [], styles = [] } = options;
const extraEntryPoints = [
...normalizeExtraEntryPoints(styles, 'styles'),
...normalizeExtraEntryPoints(scripts, 'scripts'),
];
return (stats, config) => {
if (verbose && config.stats !== false) {
const statsOptions = config.stats === true ? undefined : config.stats;
logger.info(stats.toString(statsOptions));
}
const rawStats = stats.toJson(getStatsOptions(false));
const webpackStats = {
...rawStats,
chunks: markAsyncChunksNonInitial(rawStats, extraEntryPoints),
};
webpackStatsLogger(logger, webpackStats, config);
};
}
export interface BuildEventStats {
aot: boolean;
optimization: boolean;
allChunksCount: number;
lazyChunksCount: number;
initialChunksCount: number;
changedChunksCount?: number;
durationInMs: number;
cssSizeInBytes: number;
jsSizeInBytes: number;
ngComponentCount: number;
}
export function generateBuildEventStats(
webpackStats: StatsCompilation,
browserBuilderOptions: BrowserBuilderOptions,
): BuildEventStats {
const { chunks = [], assets = [] } = webpackStats;
let jsSizeInBytes = 0;
let cssSizeInBytes = 0;
let initialChunksCount = 0;
let ngComponentCount = 0;
let changedChunksCount = 0;
const allChunksCount = chunks.length;
const isFirstRun = !runsCache.has(webpackStats.outputPath || '');
const chunkFiles = new Set<string>();
for (const chunk of chunks) {
if (!isFirstRun && chunk.rendered) {
changedChunksCount++;
}
if (chunk.initial) {
initialChunksCount++;
}
for (const file of chunk.files ?? []) {
chunkFiles.add(file);
}
}
for (const asset of assets) {
if (asset.name.endsWith('.map') || !chunkFiles.has(asset.name)) {
continue;
}
if (asset.name.endsWith('.js')) {
jsSizeInBytes += asset.size;
ngComponentCount += asset.info.ngComponentCount ?? 0;
} else if (asset.name.endsWith('.css')) {
cssSizeInBytes += asset.size;
}
}
return {
optimization: !!normalizeOptimization(browserBuilderOptions.optimization).scripts,
aot: browserBuilderOptions.aot !== false,
allChunksCount,
lazyChunksCount: allChunksCount - initialChunksCount,
initialChunksCount,
changedChunksCount,
durationInMs: getBuildDuration(webpackStats),
cssSizeInBytes,
jsSizeInBytes,
ngComponentCount,
};
}
export function webpackStatsLogger(
logger: logging.LoggerApi,
json: StatsCompilation,
config: Configuration,
budgetFailures?: BudgetCalculatorResult[],
): void {
logger.info(statsToString(json, config.stats, budgetFailures));
if (typeof config.stats !== 'object') {
throw new Error('Invalid Webpack stats configuration.');
}
if (statsHasWarnings(json)) {
logger.warn(statsWarningsToString(json, config.stats));
}
if (statsHasErrors(json)) {
logger.error(statsErrorsToString(json, config.stats));
}
} | {
"end_byte": 11186,
"start_byte": 7922,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/utils/async-chunks.ts_0_2012 | /**
* @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 { StatsChunk, StatsCompilation } from 'webpack';
import { NormalizedEntryPoint } from './helpers';
/**
* Webpack stats may incorrectly mark extra entry points `initial` chunks, when
* they are actually loaded asynchronously and thus not in the main bundle. This
* function finds extra entry points in Webpack stats and corrects this value
* whereever necessary. Does not modify {@param webpackStats}.
*/
export function markAsyncChunksNonInitial(
webpackStats: StatsCompilation,
extraEntryPoints: NormalizedEntryPoint[],
): StatsChunk[] {
const { chunks = [], entrypoints: entryPoints = {} } = webpackStats;
// Find all Webpack chunk IDs not injected into the main bundle. We don't have
// to worry about transitive dependencies because extra entry points cannot be
// depended upon in Webpack, thus any extra entry point with `inject: false`,
// **cannot** be loaded in main bundle.
const asyncChunkIds = extraEntryPoints
.filter((entryPoint) => !entryPoint.inject && entryPoints[entryPoint.bundleName])
.flatMap((entryPoint) =>
entryPoints[entryPoint.bundleName].chunks?.filter((n) => n !== 'runtime'),
);
// Find chunks for each ID.
const asyncChunks = asyncChunkIds.map((chunkId) => {
const chunk = chunks.find((chunk) => chunk.id === chunkId);
if (!chunk) {
throw new Error(`Failed to find chunk (${chunkId}) in set:\n${JSON.stringify(chunks)}`);
}
return chunk;
});
// A chunk is considered `initial` only if Webpack already belives it to be initial
// and the application developer did not mark it async via an extra entry point.
return chunks.map((chunk) => {
return asyncChunks.find((asyncChunk) => asyncChunk === chunk)
? {
...chunk,
initial: false,
}
: chunk;
});
}
| {
"end_byte": 2012,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/utils/async-chunks.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/styles.ts_0_1140 | /**
* @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 { SassWorkerImplementation } from '@angular/build/private';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import * as path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type { FileImporter } from 'sass';
import type { Configuration, LoaderContext, RuleSetUseItem } from 'webpack';
import { WebpackConfigOptions } from '../../../utils/build-options';
import { findTailwindConfigurationFile } from '../../../utils/tailwind';
import {
AnyComponentStyleBudgetChecker,
PostcssCliResources,
RemoveHashPlugin,
SuppressExtractedTextChunksWebpackPlugin,
} from '../plugins';
import { CssOptimizerPlugin } from '../plugins/css-optimizer-plugin';
import { StylesWebpackPlugin } from '../plugins/styles-webpack-plugin';
import {
assetNameTemplateFactory,
getOutputHashFormat,
normalizeGlobalStyles,
} from '../utils/helpers';
// eslint-disable-next-line max-lines-per-function | {
"end_byte": 1140,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/styles.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/styles.ts_1141_9422 | export async function getStylesConfig(wco: WebpackConfigOptions): Promise<Configuration> {
const { root, buildOptions, logger, projectRoot } = wco;
const extraPlugins: Configuration['plugins'] = [];
extraPlugins.push(new AnyComponentStyleBudgetChecker(buildOptions.budgets));
const cssSourceMap = buildOptions.sourceMap.styles;
// Determine hashing format.
const hashFormat = getOutputHashFormat(buildOptions.outputHashing);
// use includePaths from appConfig
const includePaths =
buildOptions.stylePreprocessorOptions?.includePaths?.map((p) => path.resolve(root, p)) ?? [];
// Process global styles.
if (buildOptions.styles.length > 0) {
const { entryPoints, noInjectNames } = normalizeGlobalStyles(buildOptions.styles);
extraPlugins.push(
new StylesWebpackPlugin({
root,
entryPoints,
preserveSymlinks: buildOptions.preserveSymlinks,
}),
);
if (noInjectNames.length > 0) {
// Add plugin to remove hashes from lazy styles.
extraPlugins.push(new RemoveHashPlugin({ chunkNames: noInjectNames, hashFormat }));
}
}
const sassImplementation = new SassWorkerImplementation();
extraPlugins.push({
apply(compiler) {
compiler.hooks.shutdown.tap('sass-worker', () => {
void sassImplementation.close();
});
},
});
const assetNameTemplate = assetNameTemplateFactory(hashFormat);
const extraPostcssPlugins: import('postcss').Plugin[] = [];
// Attempt to setup Tailwind CSS
// Only load Tailwind CSS plugin if configuration file was found.
// This acts as a guard to ensure the project actually wants to use Tailwind CSS.
// The package may be unknowningly present due to a third-party transitive package dependency.
const tailwindConfigPath = await findTailwindConfigurationFile(root, projectRoot);
if (tailwindConfigPath) {
let tailwindPackagePath;
try {
tailwindPackagePath = require.resolve('tailwindcss', { paths: [root] });
} catch {
const relativeTailwindConfigPath = path.relative(root, tailwindConfigPath);
logger.warn(
`Tailwind CSS configuration file found (${relativeTailwindConfigPath})` +
` but the 'tailwindcss' package is not installed.` +
` To enable Tailwind CSS, please install the 'tailwindcss' package.`,
);
}
if (tailwindPackagePath) {
extraPostcssPlugins.push(require(tailwindPackagePath)({ config: tailwindConfigPath }));
}
}
const autoprefixer: typeof import('autoprefixer') = require('autoprefixer');
const postcssOptionsCreator = (inlineSourcemaps: boolean, extracted: boolean) => {
const optionGenerator = (loader: LoaderContext<unknown>) => ({
map: inlineSourcemaps
? {
inline: true,
annotation: false,
}
: undefined,
plugins: [
PostcssCliResources({
baseHref: buildOptions.baseHref,
deployUrl: buildOptions.deployUrl,
resourcesOutputPath: buildOptions.resourcesOutputPath,
loader,
filename: assetNameTemplate,
emitFile: buildOptions.platform !== 'server',
extracted,
}),
...extraPostcssPlugins,
autoprefixer({
ignoreUnknownVersions: true,
overrideBrowserslist: buildOptions.supportedBrowsers,
}),
],
});
// postcss-loader fails when trying to determine configuration files for data URIs
optionGenerator.config = false;
return optionGenerator;
};
let componentsSourceMap = !!cssSourceMap;
if (cssSourceMap) {
if (buildOptions.optimization.styles.minify) {
// Never use component css sourcemap when style optimizations are on.
// It will just increase bundle size without offering good debug experience.
logger.warn(
'Components styles sourcemaps are not generated when styles optimization is enabled.',
);
componentsSourceMap = false;
} else if (buildOptions.sourceMap.hidden) {
// Inline all sourcemap types except hidden ones, which are the same as no sourcemaps
// for component css.
logger.warn('Components styles sourcemaps are not generated when sourcemaps are hidden.');
componentsSourceMap = false;
}
}
// extract global css from js files into own css file.
extraPlugins.push(new MiniCssExtractPlugin({ filename: `[name]${hashFormat.extract}.css` }));
if (!buildOptions.hmr) {
// don't remove `.js` files for `.css` when we are using HMR these contain HMR accept codes.
// suppress empty .js files in css only entry points.
extraPlugins.push(new SuppressExtractedTextChunksWebpackPlugin());
}
const postCss = require('postcss');
const postCssLoaderPath = require.resolve('postcss-loader');
const componentStyleLoaders: RuleSetUseItem[] = [
{
loader: require.resolve('css-loader'),
options: {
url: false,
sourceMap: componentsSourceMap,
importLoaders: 1,
exportType: 'string',
esModule: false,
},
},
{
loader: postCssLoaderPath,
options: {
implementation: postCss,
postcssOptions: postcssOptionsCreator(componentsSourceMap, false),
},
},
];
const globalStyleLoaders: RuleSetUseItem[] = [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: require.resolve('css-loader'),
options: {
url: false,
sourceMap: !!cssSourceMap,
importLoaders: 1,
},
},
{
loader: postCssLoaderPath,
options: {
implementation: postCss,
postcssOptions: postcssOptionsCreator(false, true),
sourceMap: !!cssSourceMap,
},
},
];
const styleLanguages: {
extensions: string[];
use: RuleSetUseItem[];
}[] = [
{
extensions: ['css'],
use: [],
},
{
extensions: ['scss'],
use: [
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: cssSourceMap,
},
},
{
loader: require.resolve('sass-loader'),
options: getSassLoaderOptions(
root,
sassImplementation,
includePaths,
false,
!!buildOptions.verbose,
!!buildOptions.preserveSymlinks,
),
},
],
},
{
extensions: ['sass'],
use: [
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: cssSourceMap,
},
},
{
loader: require.resolve('sass-loader'),
options: getSassLoaderOptions(
root,
sassImplementation,
includePaths,
true,
!!buildOptions.verbose,
!!buildOptions.preserveSymlinks,
),
},
],
},
{
extensions: ['less'],
use: [
{
loader: require.resolve('less-loader'),
options: {
implementation: require('less'),
sourceMap: cssSourceMap,
lessOptions: {
javascriptEnabled: true,
paths: includePaths,
},
},
},
],
},
];
return {
module: {
rules: styleLanguages.map(({ extensions, use }) => ({
test: new RegExp(`\\.(?:${extensions.join('|')})$`, 'i'),
rules: [
// Setup processing rules for global and component styles
{
oneOf: [
// Global styles are only defined global styles
{
use: globalStyleLoaders,
resourceQuery: /\?ngGlobalStyle/,
},
// Component styles are all styles except defined global styles
{
use: componentStyleLoaders,
resourceQuery: /\?ngResource/,
},
],
},
{ use },
],
})),
},
optimization: {
minimizer: buildOptions.optimization.styles.minify
? [
new CssOptimizerPlugin({
supportedBrowsers: buildOptions.supportedBrowsers,
}),
]
: undefined,
},
plugins: extraPlugins,
};
} | {
"end_byte": 9422,
"start_byte": 1141,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/styles.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/styles.ts_9424_13018 | function getSassLoaderOptions(
root: string,
implementation: SassWorkerImplementation,
includePaths: string[],
indentedSyntax: boolean,
verbose: boolean,
preserveSymlinks: boolean,
): Record<string, unknown> {
return {
sourceMap: true,
api: 'modern',
implementation,
// Webpack importer is only implemented in the legacy API and we have our own custom Webpack importer.
// See: https://github.com/webpack-contrib/sass-loader/blob/997f3eb41d86dd00d5fa49c395a1aeb41573108c/src/utils.js#L642-L651
webpackImporter: false,
sassOptions: (loaderContext: LoaderContext<{}>) => ({
importers: [getSassResolutionImporter(loaderContext, root, preserveSymlinks)],
loadPaths: includePaths,
// Use expanded as otherwise sass will remove comments that are needed for autoprefixer
// Ex: /* autoprefixer grid: autoplace */
// See: https://github.com/webpack-contrib/sass-loader/blob/45ad0be17264ceada5f0b4fb87e9357abe85c4ff/src/getSassOptions.js#L68-L70
style: 'expanded',
// Silences compiler warnings from 3rd party stylesheets
quietDeps: !verbose,
verbose,
syntax: indentedSyntax ? 'indented' : 'scss',
sourceMapIncludeSources: true,
}),
};
}
function getSassResolutionImporter(
loaderContext: LoaderContext<{}>,
root: string,
preserveSymlinks: boolean,
): FileImporter<'async'> {
const commonResolverOptions: Parameters<(typeof loaderContext)['getResolve']>[0] = {
conditionNames: ['sass', 'style'],
mainFields: ['sass', 'style', 'main', '...'],
extensions: ['.scss', '.sass', '.css'],
restrictions: [/\.((sa|sc|c)ss)$/i],
preferRelative: true,
symlinks: !preserveSymlinks,
};
// Sass also supports import-only files. If you name a file <name>.import.scss, it will only be loaded for imports, not for @uses.
// See: https://sass-lang.com/documentation/at-rules/import#import-only-files
const resolveImport = loaderContext.getResolve({
...commonResolverOptions,
dependencyType: 'sass-import',
mainFiles: ['_index.import', '_index', 'index.import', 'index', '...'],
});
const resolveModule = loaderContext.getResolve({
...commonResolverOptions,
dependencyType: 'sass-module',
mainFiles: ['_index', 'index', '...'],
});
return {
findFileUrl: async (url, { fromImport, containingUrl }): Promise<URL | null> => {
if (url.charAt(0) === '.') {
// Let Sass handle relative imports.
return null;
}
let resolveDir = root;
if (containingUrl) {
resolveDir = path.dirname(fileURLToPath(containingUrl));
}
const resolve = fromImport ? resolveImport : resolveModule;
// Try to resolve from root of workspace
const result = await tryResolve(resolve, resolveDir, url);
return result ? pathToFileURL(result) : null;
},
};
}
async function tryResolve(
resolve: ReturnType<LoaderContext<{}>['getResolve']>,
root: string,
url: string,
): Promise<string | undefined> {
try {
return await resolve(root, url);
} catch {
// Try to resolve a partial file
// @use '@material/button/button' as mdc-button;
// `@material/button/button` -> `@material/button/_button`
const lastSlashIndex = url.lastIndexOf('/');
const underscoreIndex = lastSlashIndex + 1;
if (underscoreIndex > 0 && url.charAt(underscoreIndex) !== '_') {
const partialFileUrl = `${url.slice(0, underscoreIndex)}_${url.slice(underscoreIndex)}`;
return resolve(root, partialFileUrl).catch(() => undefined);
}
}
return undefined;
} | {
"end_byte": 13018,
"start_byte": 9424,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/styles.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/common.ts_0_1743 | /**
* @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 { AngularWebpackLoaderPath } from '@ngtools/webpack';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import * as path from 'path';
import {
Compiler,
Configuration,
ContextReplacementPlugin,
RuleSetRule,
SourceMapDevToolPlugin,
} from 'webpack';
import { SubresourceIntegrityPlugin } from 'webpack-subresource-integrity';
import { WebpackConfigOptions } from '../../../utils/build-options';
import { allowMangle } from '../../../utils/environment-options';
import { loadEsmModule } from '../../../utils/load-esm';
import { AngularBabelLoaderOptions } from '../../babel/webpack-loader';
import {
CommonJsUsageWarnPlugin,
DedupeModuleResolvePlugin,
JavaScriptOptimizerPlugin,
JsonStatsPlugin,
ScriptsWebpackPlugin,
} from '../plugins';
import { DevToolsIgnorePlugin } from '../plugins/devtools-ignore-plugin';
import { NamedChunksPlugin } from '../plugins/named-chunks-plugin';
import { OccurrencesPlugin } from '../plugins/occurrences-plugin';
import { ProgressPlugin } from '../plugins/progress-plugin';
import { TransferSizePlugin } from '../plugins/transfer-size-plugin';
import { createIvyPlugin } from '../plugins/typescript';
import { WatchFilesLogsPlugin } from '../plugins/watch-files-logs-plugin';
import {
assetPatterns,
getCacheSettings,
getInstrumentationExcludedPaths,
getOutputHashFormat,
getStatsOptions,
globalScriptsByBundleName,
isPackageInstalled,
} from '../utils/helpers';
const VENDORS_TEST = /[\\/]node_modules[\\/]/;
// eslint-disable-next-line max-lines-per-function | {
"end_byte": 1743,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/common.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/common.ts_1744_10110 | export async function getCommonConfig(wco: WebpackConfigOptions): Promise<Configuration> {
const { root, projectRoot, buildOptions, tsConfig, projectName, sourceRoot, tsConfigPath } = wco;
const {
cache,
codeCoverage,
crossOrigin = 'none',
platform = 'browser',
aot = true,
codeCoverageExclude = [],
main,
sourceMap: {
styles: stylesSourceMap,
scripts: scriptsSourceMap,
vendor: vendorSourceMap,
hidden: hiddenSourceMap,
},
optimization: { styles: stylesOptimization, scripts: scriptsOptimization },
commonChunk,
vendorChunk,
subresourceIntegrity,
verbose,
poll,
webWorkerTsConfig,
externalDependencies = [],
allowedCommonJsDependencies,
} = buildOptions;
const isPlatformServer = buildOptions.platform === 'server';
const extraPlugins: { apply(compiler: Compiler): void }[] = [];
const extraRules: RuleSetRule[] = [];
const entryPoints: Configuration['entry'] = {};
// Load ESM `@angular/compiler-cli` using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
const { VERSION: NG_VERSION } =
await loadEsmModule<typeof import('@angular/compiler-cli')>('@angular/compiler-cli');
const { GLOBAL_DEFS_FOR_TERSER, GLOBAL_DEFS_FOR_TERSER_WITH_AOT } = await loadEsmModule<
typeof import('@angular/compiler-cli/private/tooling')
>('@angular/compiler-cli/private/tooling');
// determine hashing format
const hashFormat = getOutputHashFormat(buildOptions.outputHashing);
if (buildOptions.progress) {
extraPlugins.push(new ProgressPlugin(platform));
}
const localizePackageInitEntryPoint = '@angular/localize/init';
const hasLocalizeType = tsConfig.options.types?.some(
(t) => t === '@angular/localize' || t === localizePackageInitEntryPoint,
);
if (hasLocalizeType) {
entryPoints['main'] = [localizePackageInitEntryPoint];
}
if (buildOptions.main) {
const mainPath = path.resolve(root, buildOptions.main);
if (Array.isArray(entryPoints['main'])) {
entryPoints['main'].push(mainPath);
} else {
entryPoints['main'] = [mainPath];
}
}
if (isPlatformServer) {
// Fixes Critical dependency: the request of a dependency is an expression
extraPlugins.push(new ContextReplacementPlugin(/@?hapi|express[\\/]/));
if (
isPackageInstalled(wco.root, '@angular/platform-server') &&
Array.isArray(entryPoints['main'])
) {
// This import must come before any imports (direct or transitive) that rely on DOM built-ins being
// available, such as `@angular/elements`.
entryPoints['main'].unshift('@angular/platform-server/init');
}
}
const polyfills = [...buildOptions.polyfills];
if (!aot) {
polyfills.push('@angular/compiler');
}
if (polyfills.length) {
// `zone.js/testing` is a **special** polyfill because when not imported in the main it fails with the below errors:
// `Error: Expected to be running in 'ProxyZone', but it was not found.`
// This was also the reason why previously it was imported in `test.ts` as the first module.
// From Jia li:
// This is because the jasmine functions such as beforeEach/it will not be patched by zone.js since
// jasmine will not be loaded yet, so the ProxyZone will not be there. We have to load zone-testing.js after
// jasmine is ready.
// We could force loading 'zone.js/testing' prior to jasmine by changing the order of scripts in 'karma-context.html'.
// But this has it's own problems as zone.js needs to be loaded prior to jasmine due to patching of timing functions
// See: https://github.com/jasmine/jasmine/issues/1944
// Thus the correct order is zone.js -> jasmine -> zone.js/testing.
const zoneTestingEntryPoint = 'zone.js/testing';
const polyfillsExludingZoneTesting = polyfills.filter((p) => p !== zoneTestingEntryPoint);
if (Array.isArray(entryPoints['polyfills'])) {
entryPoints['polyfills'].push(...polyfillsExludingZoneTesting);
} else {
entryPoints['polyfills'] = polyfillsExludingZoneTesting;
}
if (polyfillsExludingZoneTesting.length !== polyfills.length) {
if (Array.isArray(entryPoints['main'])) {
entryPoints['main'].unshift(zoneTestingEntryPoint);
} else {
entryPoints['main'] = [zoneTestingEntryPoint];
}
}
}
if (allowedCommonJsDependencies) {
// When this is not defined it means the builder doesn't support showing common js usages.
// When it does it will be an array.
extraPlugins.push(
new CommonJsUsageWarnPlugin({
allowedDependencies: allowedCommonJsDependencies,
}),
);
}
// process global scripts
// Add a new asset for each entry.
for (const { bundleName, inject, paths } of globalScriptsByBundleName(buildOptions.scripts)) {
// Lazy scripts don't get a hash, otherwise they can't be loaded by name.
const hash = inject ? hashFormat.script : '';
extraPlugins.push(
new ScriptsWebpackPlugin({
name: bundleName,
sourceMap: scriptsSourceMap,
scripts: paths,
filename: `${path.basename(bundleName)}${hash}.js`,
basePath: root,
}),
);
}
// process asset entries
if (buildOptions.assets.length) {
extraPlugins.push(
new CopyWebpackPlugin({
patterns: assetPatterns(root, buildOptions.assets),
}),
);
}
if (buildOptions.extractLicenses) {
const LicenseWebpackPlugin = require('license-webpack-plugin').LicenseWebpackPlugin;
extraPlugins.push(
new LicenseWebpackPlugin({
stats: {
warnings: false,
errors: false,
},
perChunkOutput: false,
outputFilename: '3rdpartylicenses.txt',
skipChildCompilers: true,
}),
);
}
if (scriptsSourceMap || stylesSourceMap) {
const include = [];
if (scriptsSourceMap) {
include.push(/js$/);
}
if (stylesSourceMap) {
include.push(/css$/);
}
extraPlugins.push(new DevToolsIgnorePlugin());
extraPlugins.push(
new SourceMapDevToolPlugin({
filename: '[file].map',
include,
// We want to set sourceRoot to `webpack:///` for non
// inline sourcemaps as otherwise paths to sourcemaps will be broken in browser
// `webpack:///` is needed for Visual Studio breakpoints to work properly as currently
// there is no way to set the 'webRoot'
sourceRoot: 'webpack:///',
moduleFilenameTemplate: '[resource-path]',
append: hiddenSourceMap ? false : undefined,
}),
);
}
if (verbose) {
extraPlugins.push(new WatchFilesLogsPlugin());
}
if (buildOptions.statsJson) {
extraPlugins.push(
new JsonStatsPlugin(path.resolve(root, buildOptions.outputPath, 'stats.json')),
);
}
if (subresourceIntegrity) {
extraPlugins.push(
new SubresourceIntegrityPlugin({
hashFuncNames: ['sha384'],
}),
);
}
if (scriptsSourceMap || stylesSourceMap) {
extraRules.push({
test: /\.[cm]?jsx?$/,
enforce: 'pre',
loader: require.resolve('source-map-loader'),
options: {
filterSourceMappingUrl: (_mapUri: string, resourcePath: string) => {
if (vendorSourceMap) {
// Consume all sourcemaps when vendor option is enabled.
return true;
}
// Don't consume sourcemaps in node_modules when vendor is disabled.
// But, do consume local libraries sourcemaps.
return !resourcePath.includes('node_modules');
},
},
});
}
if (main || polyfills) {
extraRules.push({
test: tsConfig.options.allowJs ? /\.[cm]?[tj]sx?$/ : /\.[cm]?tsx?$/,
loader: AngularWebpackLoaderPath,
// The below are known paths that are not part of the TypeScript compilation even when allowJs is enabled.
exclude: [
/[\\/]node_modules[/\\](?:css-loader|mini-css-extract-plugin|webpack-dev-server|webpack)[/\\]/,
],
});
extraPlugins.push(createIvyPlugin(wco, aot, tsConfigPath));
}
if (webWorkerTsConfig) {
extraPlugins.push(createIvyPlugin(wco, false, path.resolve(wco.root, webWorkerTsConfig)));
}
const extraMinimizers = []; | {
"end_byte": 10110,
"start_byte": 1744,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/common.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/common.ts_10113_17154 | if (scriptsOptimization) {
extraMinimizers.push(
new JavaScriptOptimizerPlugin({
define: buildOptions.aot ? GLOBAL_DEFS_FOR_TERSER_WITH_AOT : GLOBAL_DEFS_FOR_TERSER,
sourcemap: scriptsSourceMap,
supportedBrowsers: buildOptions.supportedBrowsers,
keepIdentifierNames: !allowMangle || isPlatformServer,
removeLicenses: buildOptions.extractLicenses,
advanced: buildOptions.buildOptimizer,
}),
);
}
if (platform === 'browser' && (scriptsOptimization || stylesOptimization.minify)) {
extraMinimizers.push(new TransferSizePlugin());
}
let crossOriginLoading: NonNullable<Configuration['output']>['crossOriginLoading'] = false;
if (subresourceIntegrity && crossOrigin === 'none') {
crossOriginLoading = 'anonymous';
} else if (crossOrigin !== 'none') {
crossOriginLoading = crossOrigin;
}
return {
mode: scriptsOptimization || stylesOptimization.minify ? 'production' : 'development',
devtool: false,
target: [isPlatformServer ? 'node' : 'web', 'es2015'],
profile: buildOptions.statsJson,
resolve: {
roots: [projectRoot],
extensions: ['.ts', '.tsx', '.mjs', '.js'],
symlinks: !buildOptions.preserveSymlinks,
modules: [tsConfig.options.baseUrl || projectRoot, 'node_modules'],
mainFields: isPlatformServer
? ['es2020', 'es2015', 'module', 'main']
: ['es2020', 'es2015', 'browser', 'module', 'main'],
conditionNames: ['es2020', 'es2015', '...'],
},
resolveLoader: {
symlinks: !buildOptions.preserveSymlinks,
},
context: root,
entry: entryPoints,
externals: externalDependencies,
output: {
uniqueName: projectName,
hashFunction: 'xxhash64', // todo: remove in webpack 6. This is part of `futureDefaults`.
clean: buildOptions.deleteOutputPath ?? true,
path: path.resolve(root, buildOptions.outputPath),
publicPath: buildOptions.deployUrl ?? '',
filename: `[name]${hashFormat.chunk}.js`,
chunkFilename: `[name]${hashFormat.chunk}.js`,
libraryTarget: isPlatformServer ? 'commonjs' : undefined,
crossOriginLoading,
trustedTypes: 'angular#bundler',
scriptType: 'module',
},
watch: buildOptions.watch,
watchOptions: {
poll,
// The below is needed as when preserveSymlinks is enabled we disable `resolve.symlinks`.
followSymlinks: buildOptions.preserveSymlinks,
ignored: poll === undefined ? undefined : '**/node_modules/**',
},
snapshot: {
module: {
// Use hash of content instead of timestamp because the timestamp of the symlink will be used
// instead of the referenced files which causes changes in symlinks not to be picked up.
hash: buildOptions.preserveSymlinks,
},
},
performance: {
hints: false,
},
ignoreWarnings: [
// https://github.com/webpack-contrib/source-map-loader/blob/b2de4249c7431dd8432da607e08f0f65e9d64219/src/index.js#L83
/Failed to parse source map from/,
// https://github.com/webpack-contrib/postcss-loader/blob/bd261875fdf9c596af4ffb3a1a73fe3c549befda/src/index.js#L153-L158
/Add postcss as project dependency/,
// esbuild will issue a warning, while still hoists the @charset at the very top.
// This is caused by a bug in css-loader https://github.com/webpack-contrib/css-loader/issues/1212
/"@charset" must be the first rule in the file/,
],
module: {
// Show an error for missing exports instead of a warning.
strictExportPresence: true,
parser: {
javascript: {
requireContext: false,
// Disable auto URL asset module creation. This doesn't effect `new Worker(new URL(...))`
// https://webpack.js.org/guides/asset-modules/#url-assets
url: false,
worker: !!webWorkerTsConfig,
},
},
rules: [
{
test: /\.?(svg|html)$/,
// Only process HTML and SVG which are known Angular component resources.
resourceQuery: /\?ngResource/,
type: 'asset/source',
},
{
// Mark files inside `rxjs/add` as containing side effects.
// If this is fixed upstream and the fixed version becomes the minimum
// supported version, this can be removed.
test: /[/\\]rxjs[/\\]add[/\\].+\.js$/,
sideEffects: true,
},
{
test: /\.[cm]?[tj]sx?$/,
// The below is needed due to a bug in `@babel/runtime`. See: https://github.com/babel/babel/issues/12824
resolve: { fullySpecified: false },
exclude: [
/[\\/]node_modules[/\\](?:core-js|@babel|tslib|web-animations-js|web-streams-polyfill|whatwg-url)[/\\]/,
],
use: [
{
loader: require.resolve('../../babel/webpack-loader'),
options: {
cacheDirectory: (cache.enabled && path.join(cache.path, 'babel-webpack')) || false,
aot: buildOptions.aot,
optimize: buildOptions.buildOptimizer,
supportedBrowsers: buildOptions.supportedBrowsers,
instrumentCode: codeCoverage
? {
includedBasePath: sourceRoot ?? projectRoot,
excludedPaths: getInstrumentationExcludedPaths(root, codeCoverageExclude),
}
: undefined,
} as AngularBabelLoaderOptions,
},
],
},
...extraRules,
],
},
experiments: {
backCompat: false,
syncWebAssembly: true,
asyncWebAssembly: true,
topLevelAwait: false,
},
infrastructureLogging: {
debug: verbose,
level: verbose ? 'verbose' : 'error',
},
stats: getStatsOptions(verbose),
cache: getCacheSettings(wco, NG_VERSION.full),
optimization: {
minimizer: extraMinimizers,
moduleIds: 'deterministic',
chunkIds: buildOptions.namedChunks ? 'named' : 'deterministic',
emitOnErrors: false,
runtimeChunk: isPlatformServer ? false : 'single',
splitChunks: {
maxAsyncRequests: Infinity,
cacheGroups: {
default: !!commonChunk && {
chunks: 'async',
minChunks: 2,
priority: 10,
},
common: !!commonChunk && {
name: 'common',
chunks: 'async',
minChunks: 2,
enforce: true,
priority: 5,
},
vendors: false,
defaultVendors: !!vendorChunk && {
name: 'vendor',
chunks: (chunk) => chunk.name === 'main',
enforce: true,
test: VENDORS_TEST,
},
},
},
},
plugins: [
new NamedChunksPlugin(),
new OccurrencesPlugin({
aot,
scriptsOptimization,
}),
new DedupeModuleResolvePlugin({ verbose }),
...extraPlugins,
],
node: false,
};
} | {
"end_byte": 17154,
"start_byte": 10113,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/common.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/index.ts_0_286 | /**
* @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
*/
export * from './common';
export * from './dev-server';
export * from './styles';
| {
"end_byte": 286,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/index.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/dev-server.ts_0_8244 | /**
* @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 { logging, tags } from '@angular-devkit/core';
import { existsSync, promises as fsPromises } from 'fs';
import { extname, posix, resolve } from 'path';
import { URL, pathToFileURL } from 'url';
import { Configuration, RuleSetRule } from 'webpack';
import type { Configuration as DevServerConfiguration } from 'webpack-dev-server';
import { WebpackConfigOptions, WebpackDevServerOptions } from '../../../utils/build-options';
import { assertIsError } from '../../../utils/error';
import { loadEsmModule } from '../../../utils/load-esm';
import { getIndexOutputFile } from '../../../utils/webpack-browser-config';
import { HmrLoader } from '../plugins/hmr/hmr-loader';
export async function getDevServerConfig(
wco: WebpackConfigOptions<WebpackDevServerOptions>,
): Promise<Configuration> {
const {
buildOptions: { host, port, index, headers, watch, hmr, main, liveReload, proxyConfig },
logger,
root,
} = wco;
const servePath = buildServePath(wco.buildOptions, logger);
const extraRules: RuleSetRule[] = [];
if (hmr) {
extraRules.push({
loader: HmrLoader,
include: [resolve(wco.root, main)],
});
}
const extraPlugins = [];
if (!watch) {
// There's no option to turn off file watching in webpack-dev-server, but
// we can override the file watcher instead.
extraPlugins.push({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
apply: (compiler: any) => {
compiler.hooks.afterEnvironment.tap('angular-cli', () => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
compiler.watchFileSystem = { watch: () => {} };
});
},
});
}
return {
plugins: extraPlugins,
module: {
rules: extraRules,
},
devServer: {
host,
port,
headers: {
'Access-Control-Allow-Origin': '*',
...headers,
},
historyApiFallback: !!index && {
index: posix.join(servePath, getIndexOutputFile(index)),
disableDotRule: true,
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
rewrites: [
{
from: new RegExp(`^(?!${servePath})/.*`),
to: (context) => context.parsedUrl.href,
},
],
},
// When setupExitSignals is enabled webpack-dev-server will shutdown gracefully which would
// require CTRL+C to be pressed multiple times to exit.
// See: https://github.com/webpack/webpack-dev-server/blob/c76b6d11a3821436c5e20207c8a38deb6ab7e33c/lib/Server.js#L1801-L1827
setupExitSignals: false,
compress: false,
static: false,
server: getServerConfig(root, wco.buildOptions),
allowedHosts: getAllowedHostsConfig(wco.buildOptions),
devMiddleware: {
publicPath: servePath,
stats: false,
},
liveReload,
hot: hmr && !liveReload ? 'only' : hmr,
proxy: await addProxyConfig(root, proxyConfig),
...getWebSocketSettings(wco.buildOptions, servePath),
},
};
}
/**
* Resolve and build a URL _path_ that will be the root of the server. This resolved base href and
* deploy URL from the browser options and returns a path from the root.
*/
export function buildServePath(
options: WebpackDevServerOptions,
logger: logging.LoggerApi,
): string {
let servePath = options.servePath;
if (servePath === undefined) {
const defaultPath = findDefaultServePath(options.baseHref, options.deployUrl);
if (defaultPath == null) {
logger.warn(tags.oneLine`
Warning: --deploy-url and/or --base-href contain unsupported values for ng serve. Default
serve path of '/' used. Use --serve-path to override.
`);
}
servePath = defaultPath || '';
}
if (servePath.endsWith('/')) {
servePath = servePath.slice(0, -1);
}
if (!servePath.startsWith('/')) {
servePath = `/${servePath}`;
}
return servePath;
}
/**
* Private method to enhance a webpack config with SSL configuration.
* @private
*/
function getServerConfig(
root: string,
options: WebpackDevServerOptions,
): DevServerConfiguration['server'] {
const { ssl, sslCert, sslKey } = options;
if (!ssl) {
return 'http';
}
return {
type: 'https',
options:
sslCert && sslKey
? {
key: resolve(root, sslKey),
cert: resolve(root, sslCert),
}
: undefined,
};
}
/**
* Private method to enhance a webpack config with Proxy configuration.
* @private
*/
async function addProxyConfig(
root: string,
proxyConfig: string | undefined,
): Promise<object[] | undefined> {
if (!proxyConfig) {
return undefined;
}
const proxyPath = resolve(root, proxyConfig);
if (!existsSync(proxyPath)) {
throw new Error(`Proxy configuration file ${proxyPath} does not exist.`);
}
let proxyConfiguration: Record<string, object> | object[];
switch (extname(proxyPath)) {
case '.json': {
const content = await fsPromises.readFile(proxyPath, 'utf-8');
const { parse, printParseErrorCode } = await import('jsonc-parser');
const parseErrors: import('jsonc-parser').ParseError[] = [];
proxyConfiguration = parse(content, parseErrors, { allowTrailingComma: true });
if (parseErrors.length > 0) {
let errorMessage = `Proxy configuration file ${proxyPath} contains parse errors:`;
for (const parseError of parseErrors) {
const { line, column } = getJsonErrorLineColumn(parseError.offset, content);
errorMessage += `\n[${line}, ${column}] ${printParseErrorCode(parseError.error)}`;
}
throw new Error(errorMessage);
}
break;
}
case '.mjs':
// Load the ESM configuration file using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
proxyConfiguration = (
await loadEsmModule<{ default: Record<string, object> | object[] }>(
pathToFileURL(proxyPath),
)
).default;
break;
case '.cjs':
proxyConfiguration = require(proxyPath);
break;
default:
// The file could be either CommonJS or ESM.
// CommonJS is tried first then ESM if loading fails.
try {
proxyConfiguration = require(proxyPath);
} catch (e) {
assertIsError(e);
if (e.code !== 'ERR_REQUIRE_ESM') {
throw e;
}
// Load the ESM configuration file using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
proxyConfiguration = (
await loadEsmModule<{ default: Record<string, object> | object[] }>(
pathToFileURL(proxyPath),
)
).default;
}
}
return normalizeProxyConfiguration(proxyConfiguration);
}
/**
* Calculates the line and column for an error offset in the content of a JSON file.
* @param location The offset error location from the beginning of the content.
* @param content The full content of the file containing the error.
* @returns An object containing the line and column
*/
function getJsonErrorLineColumn(offset: number, content: string) {
if (offset === 0) {
return { line: 1, column: 1 };
}
let line = 0;
let position = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
++line;
const nextNewline = content.indexOf('\n', position);
if (nextNewline === -1 || nextNewline > offset) {
break;
}
position = nextNewline + 1;
}
return { line, column: offset - position + 1 };
}
/**
* Find the default server path. We don't want to expose baseHref and deployUrl as arguments, only
* the browser options where needed. This method should stay private (people who want to resolve
* baseHref and deployUrl should use the buildServePath exported function.
* @private
*/ | {
"end_byte": 8244,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/dev-server.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/webpack/configs/dev-server.ts_8245_10943 | function findDefaultServePath(baseHref?: string, deployUrl?: string): string | null {
if (!baseHref && !deployUrl) {
return '';
}
if (/^(\w+:)?\/\//.test(baseHref || '') || /^(\w+:)?\/\//.test(deployUrl || '')) {
// If baseHref or deployUrl is absolute, unsupported by ng serve
return null;
}
// normalize baseHref
// for ng serve the starting base is always `/` so a relative
// and root relative value are identical
const baseHrefParts = (baseHref || '').split('/').filter((part) => part !== '');
if (baseHref && !baseHref.endsWith('/')) {
baseHrefParts.pop();
}
const normalizedBaseHref = baseHrefParts.length === 0 ? '/' : `/${baseHrefParts.join('/')}/`;
if (deployUrl && deployUrl[0] === '/') {
if (baseHref && baseHref[0] === '/' && normalizedBaseHref !== deployUrl) {
// If baseHref and deployUrl are root relative and not equivalent, unsupported by ng serve
return null;
}
return deployUrl;
}
// Join together baseHref and deployUrl
return `${normalizedBaseHref}${deployUrl || ''}`;
}
function getAllowedHostsConfig(
options: WebpackDevServerOptions,
): DevServerConfiguration['allowedHosts'] {
if (options.disableHostCheck) {
return 'all';
} else if (options.allowedHosts?.length) {
return options.allowedHosts;
}
return undefined;
}
function getWebSocketSettings(
options: WebpackDevServerOptions,
servePath: string,
): {
webSocketServer?: DevServerConfiguration['webSocketServer'];
client?: DevServerConfiguration['client'];
} {
const { hmr, liveReload } = options;
if (!hmr && !liveReload) {
return {
webSocketServer: false,
client: undefined,
};
}
const webSocketPath = posix.join(servePath, 'ng-cli-ws');
return {
webSocketServer: {
options: {
path: webSocketPath,
},
},
client: {
logging: 'info',
webSocketURL: getPublicHostOptions(options, webSocketPath),
overlay: {
errors: true,
warnings: false,
runtimeErrors: false,
},
},
};
}
function getPublicHostOptions(options: WebpackDevServerOptions, webSocketPath: string): string {
let publicHost: string | null | undefined = options.publicHost;
if (publicHost) {
const hostWithProtocol = !/^\w+:\/\//.test(publicHost) ? `https://${publicHost}` : publicHost;
publicHost = new URL(hostWithProtocol).host;
}
return `auto://${publicHost || '0.0.0.0:0'}${webSocketPath}`;
}
function normalizeProxyConfiguration(proxy: Record<string, object> | object[]): object[] {
return Array.isArray(proxy)
? proxy
: Object.entries(proxy).map(([context, value]) => ({ context: [context], ...value }));
} | {
"end_byte": 10943,
"start_byte": 8245,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/webpack/configs/dev-server.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/babel/babel-loader.d.ts_0_1280 | /**
* @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
*/
declare module 'babel-loader' {
type BabelLoaderCustomizer<T> = (babel: typeof import('@babel/core')) => {
customOptions?(
this: import('webpack').loader.LoaderContext,
loaderOptions: Record<string, unknown>,
loaderArguments: { source: string; map?: unknown },
): Promise<{ custom?: T; loader: Record<string, unknown> }>;
config?(
this: import('webpack').loader.LoaderContext,
configuration: import('@babel/core').PartialConfig,
loaderArguments: { source: string; map?: unknown; customOptions: T },
): import('@babel/core').TransformOptions;
result?(
this: import('webpack').loader.LoaderContext,
result: import('@babel/core').BabelFileResult,
context: {
source: string;
map?: unknown;
customOptions: T;
configuration: import('@babel/core').PartialConfig;
options: import('@babel/core').TransformOptions;
},
): import('@babel/core').BabelFileResult;
};
function custom<T>(customizer: BabelLoaderCustomizer<T>): import('webpack').loader.Loader;
}
| {
"end_byte": 1280,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/babel/babel-loader.d.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/babel/webpack-loader.ts_0_7920 | /**
* @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 { custom } from 'babel-loader';
import { loadEsmModule } from '../../utils/load-esm';
import { VERSION } from '../../utils/package-version';
import {
ApplicationPresetOptions,
I18nPluginCreators,
requiresLinking,
} from './presets/application';
interface AngularCustomOptions extends Omit<ApplicationPresetOptions, 'instrumentCode'> {
instrumentCode?: {
/** node_modules and test files are always excluded. */
excludedPaths: Set<string>;
includedBasePath: string;
};
}
export type AngularBabelLoaderOptions = AngularCustomOptions & Record<string, unknown>;
/**
* Cached instance of the compiler-cli linker's Babel plugin factory function.
*/
let linkerPluginCreator:
| typeof import('@angular/compiler-cli/linker/babel').createEs2015LinkerPlugin
| undefined;
/**
* Cached instance of the localize Babel plugins factory functions.
*/
let i18nPluginCreators: I18nPluginCreators | undefined;
// eslint-disable-next-line max-lines-per-function
export default custom<ApplicationPresetOptions>(() => {
const baseOptions = Object.freeze({
babelrc: false,
configFile: false,
compact: false,
cacheCompression: false,
sourceType: 'unambiguous',
inputSourceMap: false,
});
return {
async customOptions(options, { source, map }) {
const { i18n, aot, optimize, instrumentCode, supportedBrowsers, ...rawOptions } =
options as AngularBabelLoaderOptions;
// Must process file if plugins are added
let shouldProcess = Array.isArray(rawOptions.plugins) && rawOptions.plugins.length > 0;
const customOptions: ApplicationPresetOptions = {
forceAsyncTransformation: false,
angularLinker: undefined,
i18n: undefined,
instrumentCode: undefined,
supportedBrowsers,
};
// Analyze file for linking
if (await requiresLinking(this.resourcePath, source)) {
// Load ESM `@angular/compiler-cli/linker/babel` using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
linkerPluginCreator ??= (
await loadEsmModule<typeof import('@angular/compiler-cli/linker/babel')>(
'@angular/compiler-cli/linker/babel',
)
).createEs2015LinkerPlugin;
customOptions.angularLinker = {
shouldLink: true,
jitMode: aot !== true,
linkerPluginCreator,
};
shouldProcess = true;
}
// Application code (TS files) will only contain native async if target is ES2017+.
// However, third-party libraries can regardless of the target option.
// APF packages with code in [f]esm2015 directories is downlevelled to ES2015 and
// will not have native async.
customOptions.forceAsyncTransformation =
!/[\\/][_f]?esm2015[\\/]/.test(this.resourcePath) && source.includes('async');
shouldProcess ||=
customOptions.forceAsyncTransformation ||
customOptions.supportedBrowsers !== undefined ||
false;
// Analyze for i18n inlining
if (
i18n &&
!/[\\/]@angular[\\/](?:compiler|localize)/.test(this.resourcePath) &&
source.includes('$localize')
) {
// Load the i18n plugin creators from the new `@angular/localize/tools` entry point.
// This may fail during the transition to ESM due to the entry point not yet existing.
// During the transition, this will always attempt to load the entry point for each file.
// This will only occur during prerelease and will be automatically corrected once the new
// entry point exists.
if (i18nPluginCreators === undefined) {
// Load ESM `@angular/localize/tools` using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
i18nPluginCreators = await loadEsmModule<I18nPluginCreators>('@angular/localize/tools');
}
customOptions.i18n = {
...i18n,
pluginCreators: i18nPluginCreators,
};
// Add translation files as dependencies of the file to support rebuilds
// Except for `@angular/core` which needs locale injection but has no translations
if (
customOptions.i18n.translationFiles &&
!/[\\/]@angular[\\/]core/.test(this.resourcePath)
) {
for (const file of customOptions.i18n.translationFiles) {
this.addDependency(file);
}
}
shouldProcess = true;
}
if (optimize) {
const AngularPackage = /[\\/]node_modules[\\/]@angular[\\/]/.test(this.resourcePath);
const sideEffectFree = !!this._module?.factoryMeta?.sideEffectFree;
customOptions.optimize = {
// Angular packages provide additional tested side effects guarantees and can use
// otherwise unsafe optimizations. (@angular/platform-server/init) however has side-effects.
pureTopLevel: AngularPackage && sideEffectFree,
// JavaScript modules that are marked as side effect free are considered to have
// no decorators that contain non-local effects.
wrapDecorators: sideEffectFree,
};
shouldProcess = true;
}
if (
instrumentCode &&
!instrumentCode.excludedPaths.has(this.resourcePath) &&
!/\.(e2e|spec)\.tsx?$|[\\/]node_modules[\\/]/.test(this.resourcePath) &&
this.resourcePath.startsWith(instrumentCode.includedBasePath)
) {
// `babel-plugin-istanbul` has it's own includes but we do the below so that we avoid running the loader.
customOptions.instrumentCode = {
includedBasePath: instrumentCode.includedBasePath,
inputSourceMap: map,
};
shouldProcess = true;
}
// Add provided loader options to default base options
const loaderOptions: Record<string, unknown> = {
...baseOptions,
...rawOptions,
cacheIdentifier: JSON.stringify({
buildAngular: VERSION,
customOptions,
baseOptions,
rawOptions,
}),
};
// Skip babel processing if no actions are needed
if (!shouldProcess) {
// Force the current file to be ignored
loaderOptions.ignore = [() => true];
}
return { custom: customOptions, loader: loaderOptions };
},
config(configuration, { customOptions }) {
return {
...configuration.options,
// Using `false` disables babel from attempting to locate sourcemaps or process any inline maps.
// The babel types do not include the false option even though it is valid
// eslint-disable-next-line @typescript-eslint/no-explicit-any
inputSourceMap: configuration.options.inputSourceMap ?? (false as any),
presets: [
...(configuration.options.presets || []),
[
require('./presets/application').default,
{
...customOptions,
diagnosticReporter: (type, message) => {
switch (type) {
case 'error':
this.emitError(message);
break;
case 'info': // Webpack does not currently have an informational diagnostic
case 'warning':
this.emitWarning(message);
break;
}
},
} as ApplicationPresetOptions,
],
],
};
},
};
});
| {
"end_byte": 7920,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/babel/webpack-loader.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/babel/plugins/types.d.ts_0_590 | /**
* @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
*/
declare module 'istanbul-lib-instrument' {
export interface Visitor {
enter(path: import('@babel/core').NodePath<types.Program>): void;
exit(path: import('@babel/core').NodePath<types.Program>): void;
}
export function programVisitor(
types: typeof import('@babel/core').types,
filePath?: string,
options?: { inputSourceMap?: object | null },
): Visitor;
}
| {
"end_byte": 590,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/babel/plugins/types.d.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/babel/plugins/add-code-coverage.ts_0_1268 | /**
* @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 { NodePath, PluginObj, types } from '@babel/core';
import { Visitor, programVisitor } from 'istanbul-lib-instrument';
import assert from 'node:assert';
/**
* A babel plugin factory function for adding istanbul instrumentation.
*
* @returns A babel plugin object instance.
*/
export default function (): PluginObj {
const visitors = new WeakMap<NodePath, Visitor>();
return {
visitor: {
Program: {
enter(path, state) {
const visitor = programVisitor(types, state.filename, {
// Babel returns a Converter object from the `convert-source-map` package
inputSourceMap: (state.file.inputMap as undefined | { toObject(): object })?.toObject(),
});
visitors.set(path, visitor);
visitor.enter(path);
},
exit(path) {
const visitor = visitors.get(path);
assert(visitor, 'Instrumentation visitor should always be present for program path.');
visitor.exit(path);
visitors.delete(path);
},
},
},
};
}
| {
"end_byte": 1268,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/babel/plugins/add-code-coverage.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/tools/babel/presets/application.ts_0_8030 | /**
* @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 type { ɵParsedTranslation } from '@angular/localize';
import type {
DiagnosticHandlingStrategy,
Diagnostics,
makeEs2015TranslatePlugin,
makeLocalePlugin,
} from '@angular/localize/tools';
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import { loadEsmModule } from '../../../utils/load-esm';
/**
* Cached instance of the compiler-cli linker's needsLinking function.
*/
let needsLinking: typeof import('@angular/compiler-cli/linker').needsLinking | undefined;
export type DiagnosticReporter = (type: 'error' | 'warning' | 'info', message: string) => void;
/**
* An interface representing the factory functions for the `@angular/localize` translation Babel plugins.
* This must be provided for the ESM imports since dynamic imports are required to be asynchronous and
* Babel presets currently can only be synchronous.
*
*/
export interface I18nPluginCreators {
makeEs2015TranslatePlugin: typeof makeEs2015TranslatePlugin;
makeLocalePlugin: typeof makeLocalePlugin;
}
export interface ApplicationPresetOptions {
i18n?: {
locale: string;
missingTranslationBehavior?: 'error' | 'warning' | 'ignore';
translation?: Record<string, ɵParsedTranslation>;
translationFiles?: string[];
pluginCreators: I18nPluginCreators;
};
angularLinker?: {
shouldLink: boolean;
jitMode: boolean;
linkerPluginCreator: typeof import('@angular/compiler-cli/linker/babel').createEs2015LinkerPlugin;
};
forceAsyncTransformation?: boolean;
instrumentCode?: {
includedBasePath: string;
inputSourceMap: unknown;
};
optimize?: {
pureTopLevel: boolean;
wrapDecorators: boolean;
};
supportedBrowsers?: string[];
diagnosticReporter?: DiagnosticReporter;
}
// Extract Logger type from the linker function to avoid deep importing to access the type
type NgtscLogger = Parameters<
typeof import('@angular/compiler-cli/linker/babel').createEs2015LinkerPlugin
>[0]['logger'];
function createI18nDiagnostics(reporter: DiagnosticReporter | undefined): Diagnostics {
const diagnostics: Diagnostics = new (class {
readonly messages: Diagnostics['messages'] = [];
hasErrors = false;
add(type: DiagnosticHandlingStrategy, message: string): void {
if (type === 'ignore') {
return;
}
this.messages.push({ type, message });
this.hasErrors ||= type === 'error';
reporter?.(type, message);
}
error(message: string): void {
this.add('error', message);
}
warn(message: string): void {
this.add('warning', message);
}
merge(other: Diagnostics): void {
for (const diagnostic of other.messages) {
this.add(diagnostic.type, diagnostic.message);
}
}
formatDiagnostics(): never {
assert.fail(
'@angular/localize Diagnostics formatDiagnostics should not be called from within babel.',
);
}
})();
return diagnostics;
}
function createI18nPlugins(
locale: string,
translation: Record<string, ɵParsedTranslation> | undefined,
missingTranslationBehavior: 'error' | 'warning' | 'ignore',
diagnosticReporter: DiagnosticReporter | undefined,
pluginCreators: I18nPluginCreators,
) {
const diagnostics = createI18nDiagnostics(diagnosticReporter);
const plugins = [];
const { makeEs2015TranslatePlugin, makeLocalePlugin } = pluginCreators;
if (translation) {
plugins.push(
makeEs2015TranslatePlugin(diagnostics, translation, {
missingTranslation: missingTranslationBehavior,
}),
);
}
plugins.push(makeLocalePlugin(locale));
return plugins;
}
function createNgtscLogger(reporter: DiagnosticReporter | undefined): NgtscLogger {
return {
level: 1, // Info level
debug(...args: string[]) {},
info(...args: string[]) {
reporter?.('info', args.join());
},
warn(...args: string[]) {
reporter?.('warning', args.join());
},
error(...args: string[]) {
reporter?.('error', args.join());
},
};
}
export default function (api: unknown, options: ApplicationPresetOptions) {
const presets = [];
const plugins = [];
let needRuntimeTransform = false;
if (options.angularLinker?.shouldLink) {
plugins.push(
options.angularLinker.linkerPluginCreator({
linkerJitMode: options.angularLinker.jitMode,
// This is a workaround until https://github.com/angular/angular/issues/42769 is fixed.
sourceMapping: false,
logger: createNgtscLogger(options.diagnosticReporter),
fileSystem: {
resolve: path.resolve,
exists: fs.existsSync,
dirname: path.dirname,
relative: path.relative,
readFile: fs.readFileSync,
// Node.JS types don't overlap the Compiler types.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
}),
);
}
// Applications code ES version can be controlled using TypeScript's `target` option.
// However, this doesn't effect libraries and hence we use preset-env to downlevel ES features
// based on the supported browsers in browserslist.
if (options.supportedBrowsers) {
presets.push([
require('@babel/preset-env').default,
{
bugfixes: true,
modules: false,
targets: options.supportedBrowsers,
exclude: ['transform-typeof-symbol'],
},
]);
needRuntimeTransform = true;
}
if (options.i18n) {
const { locale, missingTranslationBehavior, pluginCreators, translation } = options.i18n;
const i18nPlugins = createI18nPlugins(
locale,
translation,
missingTranslationBehavior || 'ignore',
options.diagnosticReporter,
pluginCreators,
);
plugins.push(...i18nPlugins);
}
if (options.forceAsyncTransformation) {
// Always transform async/await to support Zone.js
plugins.push(
require('@babel/plugin-transform-async-to-generator').default,
require('@babel/plugin-transform-async-generator-functions').default,
);
needRuntimeTransform = true;
}
if (options.optimize) {
const {
adjustStaticMembers,
adjustTypeScriptEnums,
elideAngularMetadata,
markTopLevelPure,
} = require('@angular/build/private');
if (options.optimize.pureTopLevel) {
plugins.push(markTopLevelPure);
}
plugins.push(elideAngularMetadata, adjustTypeScriptEnums, [
adjustStaticMembers,
{ wrapDecorators: options.optimize.wrapDecorators },
]);
}
if (options.instrumentCode) {
plugins.push(require('../plugins/add-code-coverage').default);
}
if (needRuntimeTransform) {
// Babel equivalent to TypeScript's `importHelpers` option
plugins.push([
require('@babel/plugin-transform-runtime').default,
{
useESModules: true,
version: require('@babel/runtime/package.json').version,
absoluteRuntime: path.dirname(require.resolve('@babel/runtime/package.json')),
},
]);
}
return { presets, plugins };
}
export async function requiresLinking(path: string, source: string): Promise<boolean> {
// @angular/core and @angular/compiler will cause false positives
// Also, TypeScript files do not require linking
if (/[\\/]@angular[\\/](?:compiler|core)|\.tsx?$/.test(path)) {
return false;
}
if (!needsLinking) {
// Load ESM `@angular/compiler-cli/linker` using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
const linkerModule = await loadEsmModule<typeof import('@angular/compiler-cli/linker')>(
'@angular/compiler-cli/linker',
);
needsLinking = linkerModule.needsLinking;
}
return needsLinking(path, source);
}
| {
"end_byte": 8030,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/tools/babel/presets/application.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/webpack-server.ts_0_2600 | /**
* @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 {
IndexHtmlTransform,
assertCompatibleAngularVersion,
createTranslationLoader,
} from '@angular/build/private';
import { BuilderContext } from '@angular-devkit/architect';
import {
DevServerBuildOutput,
WebpackLoggingCallback,
runWebpackDevServer,
} from '@angular-devkit/build-webpack';
import { json, tags } from '@angular-devkit/core';
import * as path from 'path';
import { Observable, concatMap, from, switchMap } from 'rxjs';
import * as url from 'url';
import webpack from 'webpack';
import webpackDevServer from 'webpack-dev-server';
import { getCommonConfig, getDevServerConfig, getStylesConfig } from '../../tools/webpack/configs';
import { IndexHtmlWebpackPlugin } from '../../tools/webpack/plugins/index-html-webpack-plugin';
import { ServiceWorkerPlugin } from '../../tools/webpack/plugins/service-worker-plugin';
import {
BuildEventStats,
createWebpackLoggingCallback,
generateBuildEventStats,
} from '../../tools/webpack/utils/stats';
import { ExecutionTransformer } from '../../transforms';
import { normalizeOptimization } from '../../utils';
import { colors } from '../../utils/color';
import { I18nOptions, loadTranslations } from '../../utils/i18n-webpack';
import { loadEsmModule } from '../../utils/load-esm';
import { NormalizedCachedOptions } from '../../utils/normalize-cache';
import { generateEntryPoints } from '../../utils/package-chunk-sort';
import {
generateI18nBrowserWebpackConfigFromContext,
getIndexInputFile,
getIndexOutputFile,
} from '../../utils/webpack-browser-config';
import { addError, addWarning } from '../../utils/webpack-diagnostics';
import { Schema as BrowserBuilderSchema, OutputHashing } from '../browser/schema';
import { NormalizedDevServerOptions } from './options';
/**
* @experimental Direct usage of this type is considered experimental.
*/
export type DevServerBuilderOutput = DevServerBuildOutput & {
baseUrl: string;
stats: BuildEventStats;
};
/**
* Reusable implementation of the Angular Webpack development server builder.
* @param options Dev Server options.
* @param builderName The name of the builder used to build the application.
* @param context The build context.
* @param transforms A map of transforms that can be used to hook into some logic (such as
* transforming webpack configuration before passing it to webpack).
*/
// eslint-disable-next-line max-lines-per-function | {
"end_byte": 2600,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/webpack-server.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/webpack-server.ts_2601_9969 | export function serveWebpackBrowser(
options: NormalizedDevServerOptions,
builderName: string,
context: BuilderContext,
transforms: {
webpackConfiguration?: ExecutionTransformer<webpack.Configuration>;
logging?: WebpackLoggingCallback;
indexHtml?: IndexHtmlTransform;
} = {},
): Observable<DevServerBuilderOutput> {
// Check Angular version.
const { logger, workspaceRoot } = context;
assertCompatibleAngularVersion(workspaceRoot);
async function setup(): Promise<{
browserOptions: BrowserBuilderSchema;
webpackConfig: webpack.Configuration;
}> {
if (options.hmr) {
logger.warn(tags.stripIndents`NOTICE: Hot Module Replacement (HMR) is enabled for the dev server.
See https://webpack.js.org/guides/hot-module-replacement for information on working with HMR for Webpack.`);
}
// Get the browser configuration from the target name.
const rawBrowserOptions = await context.getTargetOptions(options.buildTarget);
if (rawBrowserOptions.outputHashing && rawBrowserOptions.outputHashing !== OutputHashing.None) {
// Disable output hashing for dev build as this can cause memory leaks
// See: https://github.com/webpack/webpack-dev-server/issues/377#issuecomment-241258405
rawBrowserOptions.outputHashing = OutputHashing.None;
logger.warn(`Warning: 'outputHashing' option is disabled when using the dev-server.`);
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const browserOptions = (await context.validateOptions(
{
...rawBrowserOptions,
watch: options.watch,
verbose: options.verbose,
// In dev server we should not have budgets because of extra libs such as socks-js
budgets: undefined,
} as json.JsonObject & BrowserBuilderSchema,
builderName,
)) as json.JsonObject & BrowserBuilderSchema;
const { styles, scripts } = normalizeOptimization(browserOptions.optimization);
if (scripts || styles.minify) {
logger.error(tags.stripIndents`
****************************************************************************************
This is a simple server for use in testing or debugging Angular applications locally.
It hasn't been reviewed for security issues.
DON'T USE IT FOR PRODUCTION!
****************************************************************************************
`);
}
const { config, i18n } = await generateI18nBrowserWebpackConfigFromContext(
browserOptions,
context,
(wco) => [getDevServerConfig(wco), getCommonConfig(wco), getStylesConfig(wco)],
options,
);
if (!config.devServer) {
throw new Error('Webpack Dev Server configuration was not set.');
}
let locale: string | undefined;
if (i18n.shouldInline) {
// Dev-server only supports one locale
locale = [...i18n.inlineLocales][0];
} else if (i18n.hasDefinedSourceLocale) {
// use source locale if not localizing
locale = i18n.sourceLocale;
}
let webpackConfig = config;
// If a locale is defined, setup localization
if (locale) {
if (i18n.inlineLocales.size > 1) {
throw new Error(
'The development server only supports localizing a single locale per build.',
);
}
await setupLocalize(
locale,
i18n,
browserOptions,
webpackConfig,
options.cacheOptions,
context,
);
}
if (transforms.webpackConfiguration) {
webpackConfig = await transforms.webpackConfiguration(webpackConfig);
}
webpackConfig.plugins ??= [];
if (browserOptions.index) {
const { scripts = [], styles = [], baseHref } = browserOptions;
const entrypoints = generateEntryPoints({
scripts,
styles,
// The below is needed as otherwise HMR for CSS will break.
// styles.js and runtime.js needs to be loaded as a non-module scripts as otherwise `document.currentScript` will be null.
// https://github.com/webpack-contrib/mini-css-extract-plugin/blob/90445dd1d81da0c10b9b0e8a17b417d0651816b8/src/hmr/hotModuleReplacement.js#L39
isHMREnabled: !!webpackConfig.devServer?.hot,
});
webpackConfig.plugins.push(
new IndexHtmlWebpackPlugin({
indexPath: path.resolve(workspaceRoot, getIndexInputFile(browserOptions.index)),
outputPath: getIndexOutputFile(browserOptions.index),
baseHref,
entrypoints,
deployUrl: browserOptions.deployUrl,
sri: browserOptions.subresourceIntegrity,
cache: options.cacheOptions,
postTransform: transforms.indexHtml,
optimization: normalizeOptimization(browserOptions.optimization),
crossOrigin: browserOptions.crossOrigin,
lang: locale,
}),
);
}
if (browserOptions.serviceWorker) {
webpackConfig.plugins.push(
new ServiceWorkerPlugin({
baseHref: browserOptions.baseHref,
root: context.workspaceRoot,
projectRoot: options.projectRoot,
ngswConfigPath: browserOptions.ngswConfigPath,
}),
);
}
return {
browserOptions,
webpackConfig,
};
}
return from(setup()).pipe(
switchMap(({ browserOptions, webpackConfig }) => {
return runWebpackDevServer(webpackConfig, context, {
logging: transforms.logging || createWebpackLoggingCallback(browserOptions, logger),
webpackFactory: require('webpack') as typeof webpack,
webpackDevServerFactory: require('webpack-dev-server') as typeof webpackDevServer,
}).pipe(
concatMap(async (buildEvent, index) => {
const webpackRawStats = buildEvent.webpackStats;
if (!webpackRawStats) {
throw new Error('Webpack stats build result is required.');
}
// Resolve serve address.
const publicPath = webpackConfig.devServer?.devMiddleware?.publicPath;
const serverAddress = url.format({
protocol: options.ssl ? 'https' : 'http',
hostname: options.host === '0.0.0.0' ? 'localhost' : options.host,
port: buildEvent.port,
pathname: typeof publicPath === 'string' ? publicPath : undefined,
});
if (index === 0) {
logger.info(
'\n' +
tags.oneLine`
**
Angular Live Development Server is listening on ${options.host}:${buildEvent.port},
open your browser on ${serverAddress}
**
` +
'\n',
);
if (options.open) {
const open = (await loadEsmModule<typeof import('open')>('open')).default;
await open(serverAddress);
}
}
if (buildEvent.success) {
logger.info(`\n${colors.greenBright(colors.symbols.check)} Compiled successfully.`);
} else {
logger.info(`\n${colors.redBright(colors.symbols.cross)} Failed to compile.`);
}
return {
...buildEvent,
baseUrl: serverAddress,
stats: generateBuildEventStats(webpackRawStats, browserOptions),
} as DevServerBuilderOutput;
}),
);
}),
);
} | {
"end_byte": 9969,
"start_byte": 2601,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/webpack-server.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/webpack-server.ts_9971_13364 | async function setupLocalize(
locale: string,
i18n: I18nOptions,
browserOptions: BrowserBuilderSchema,
webpackConfig: webpack.Configuration,
cacheOptions: NormalizedCachedOptions,
context: BuilderContext,
) {
const localeDescription = i18n.locales[locale];
// Modify main entrypoint to include locale data
if (
localeDescription?.dataPath &&
typeof webpackConfig.entry === 'object' &&
!Array.isArray(webpackConfig.entry) &&
webpackConfig.entry['main']
) {
if (Array.isArray(webpackConfig.entry['main'])) {
webpackConfig.entry['main'].unshift(localeDescription.dataPath);
} else {
webpackConfig.entry['main'] = [
localeDescription.dataPath,
webpackConfig.entry['main'] as string,
];
}
}
let missingTranslationBehavior = browserOptions.i18nMissingTranslation || 'ignore';
let translation = localeDescription?.translation || {};
if (locale === i18n.sourceLocale) {
missingTranslationBehavior = 'ignore';
translation = {};
}
const i18nLoaderOptions = {
locale,
missingTranslationBehavior,
translation: i18n.shouldInline ? translation : undefined,
translationFiles: localeDescription?.files.map((file) =>
path.resolve(context.workspaceRoot, file.path),
),
};
const i18nRule: webpack.RuleSetRule = {
test: /\.[cm]?[tj]sx?$/,
enforce: 'post',
use: [
{
loader: require.resolve('../../tools/babel/webpack-loader'),
options: {
cacheDirectory:
(cacheOptions.enabled && path.join(cacheOptions.path, 'babel-dev-server-i18n')) ||
false,
cacheIdentifier: JSON.stringify({
locale,
translationIntegrity: localeDescription?.files.map((file) => file.integrity),
}),
i18n: i18nLoaderOptions,
},
},
],
};
// Get the rules and ensure the Webpack configuration is setup properly
const rules = webpackConfig.module?.rules || [];
if (!webpackConfig.module) {
webpackConfig.module = { rules };
} else if (!webpackConfig.module.rules) {
webpackConfig.module.rules = rules;
}
rules.push(i18nRule);
// Add a plugin to reload translation files on rebuilds
const loader = await createTranslationLoader();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
webpackConfig.plugins!.push({
apply: (compiler: webpack.Compiler) => {
compiler.hooks.thisCompilation.tap('build-angular', (compilation) => {
if (i18n.shouldInline && i18nLoaderOptions.translation === undefined) {
// Reload translations
loadTranslations(
locale,
localeDescription,
context.workspaceRoot,
loader,
{
warn(message) {
addWarning(compilation, message);
},
error(message) {
addError(compilation, message);
},
},
undefined,
browserOptions.i18nDuplicateTranslation,
);
i18nLoaderOptions.translation = localeDescription.translation ?? {};
}
compilation.hooks.finishModules.tap('build-angular', () => {
// After loaders are finished, clear out the now unneeded translations
i18nLoaderOptions.translation = undefined;
});
});
},
});
} | {
"end_byte": 13364,
"start_byte": 9971,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/webpack-server.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/builder.ts_0_8048 | /**
* @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 type { DevServerBuilderOutput } from '@angular/build';
import { type IndexHtmlTransform, checkPort, purgeStaleBuildCache } from '@angular/build/private';
import type { BuilderContext } from '@angular-devkit/architect';
import type { Plugin } from 'esbuild';
import type http from 'node:http';
import { EMPTY, Observable, defer, switchMap } from 'rxjs';
import type { ExecutionTransformer } from '../../transforms';
import { normalizeOptions } from './options';
import type { Schema as DevServerBuilderOptions } from './schema';
/**
* A Builder that executes a development server based on the provided browser target option.
*
* Usage of the `transforms` and/or `extensions` parameters is NOT supported and may cause
* unexpected build output or build failures.
*
* @param options Dev Server options.
* @param context The build context.
* @param transforms A map of transforms that can be used to hook into some logic (such as
* transforming webpack configuration before passing it to webpack).
* @param extensions An optional object containing an array of build plugins (esbuild-based)
* and/or HTTP request middleware.
*
* @experimental Direct usage of this function is considered experimental.
*/
export function execute(
options: DevServerBuilderOptions,
context: BuilderContext,
transforms: {
webpackConfiguration?: ExecutionTransformer<import('webpack').Configuration>;
logging?: import('@angular-devkit/build-webpack').WebpackLoggingCallback;
indexHtml?: IndexHtmlTransform;
} = {},
extensions?: {
buildPlugins?: Plugin[];
middleware?: ((
req: http.IncomingMessage,
res: http.ServerResponse,
next: (err?: unknown) => void,
) => void)[];
builderSelector?: (info: BuilderSelectorInfo, logger: BuilderContext['logger']) => string;
},
): Observable<DevServerBuilderOutput> {
// Determine project name from builder context target
const projectName = context.target?.project;
if (!projectName) {
context.logger.error(`The "dev-server" builder requires a target to be specified.`);
return EMPTY;
}
return defer(() => initialize(options, projectName, context, extensions?.builderSelector)).pipe(
switchMap(({ builderName, normalizedOptions }) => {
// Use vite-based development server for esbuild-based builds
if (isEsbuildBased(builderName)) {
if (transforms?.logging || transforms?.webpackConfiguration) {
throw new Error(
`The "application" and "browser-esbuild" builders do not support Webpack transforms.`,
);
}
if (options.allowedHosts?.length) {
context.logger.warn(
`The "allowedHosts" option will not be used because it is not supported by the "${builderName}" builder.`,
);
}
if (options.publicHost) {
context.logger.warn(
`The "publicHost" option will not be used because it is not supported by the "${builderName}" builder.`,
);
}
if (options.disableHostCheck) {
context.logger.warn(
`The "disableHostCheck" option will not be used because it is not supported by the "${builderName}" builder.`,
);
}
return defer(() =>
Promise.all([import('@angular/build/private'), import('../browser-esbuild')]),
).pipe(
switchMap(([{ serveWithVite, buildApplicationInternal }, { convertBrowserOptions }]) =>
serveWithVite(
normalizedOptions,
builderName,
(options, context, codePlugins) => {
return builderName === '@angular-devkit/build-angular:browser-esbuild'
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
buildApplicationInternal(convertBrowserOptions(options as any), context, {
codePlugins,
})
: buildApplicationInternal(options, context, { codePlugins });
},
context,
transforms,
extensions,
),
),
);
}
// Warn if the initial options provided by the user enable prebundling with Webpack-based builders
if (options.prebundle) {
context.logger.warn(
`Prebundling has been configured but will not be used because it is not supported by the "${builderName}" builder.`,
);
}
if (extensions?.buildPlugins?.length) {
throw new Error('Only the "application" and "browser-esbuild" builders support plugins.');
}
if (extensions?.middleware?.length) {
throw new Error(
'Only the "application" and "browser-esbuild" builders support middleware.',
);
}
// Use Webpack for all other browser targets
return defer(() => import('./webpack-server')).pipe(
switchMap(({ serveWebpackBrowser }) =>
serveWebpackBrowser(normalizedOptions, builderName, context, transforms),
),
);
}),
);
}
async function initialize(
initialOptions: DevServerBuilderOptions,
projectName: string,
context: BuilderContext,
builderSelector = defaultBuilderSelector,
) {
// Purge old build disk cache.
await purgeStaleBuildCache(context);
const normalizedOptions = await normalizeOptions(context, projectName, initialOptions);
const builderName = builderSelector(
{
builderName: await context.getBuilderNameForTarget(normalizedOptions.buildTarget),
forceEsbuild: !!normalizedOptions.forceEsbuild,
},
context.logger,
);
if (
!normalizedOptions.disableHostCheck &&
!/^127\.\d+\.\d+\.\d+/g.test(normalizedOptions.host) &&
normalizedOptions.host !== 'localhost'
) {
context.logger.warn(`
Warning: This is a simple server for use in testing or debugging Angular applications
locally. It hasn't been reviewed for security issues.
Binding this server to an open connection can result in compromising your application or
computer. Using a different host than the one passed to the "--host" flag might result in
websocket connection issues. You might need to use "--disable-host-check" if that's the
case.
`);
}
if (normalizedOptions.disableHostCheck) {
context.logger.warn(
'Warning: Running a server with --disable-host-check is a security risk. ' +
'See https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a for more information.',
);
}
normalizedOptions.port = await checkPort(normalizedOptions.port, normalizedOptions.host);
return {
builderName,
normalizedOptions,
};
}
export function isEsbuildBased(
builderName: string,
): builderName is
| '@angular/build:application'
| '@angular-devkit/build-angular:application'
| '@angular-devkit/build-angular:browser-esbuild' {
if (
builderName === '@angular/build:application' ||
builderName === '@angular-devkit/build-angular:application' ||
builderName === '@angular-devkit/build-angular:browser-esbuild'
) {
return true;
}
return false;
}
interface BuilderSelectorInfo {
builderName: string;
forceEsbuild: boolean;
}
function defaultBuilderSelector(
info: BuilderSelectorInfo,
logger: BuilderContext['logger'],
): string {
if (isEsbuildBased(info.builderName)) {
return info.builderName;
}
if (info.forceEsbuild) {
if (!info.builderName.startsWith('@angular-devkit/build-angular:')) {
logger.warn(
'Warning: Forcing the use of the esbuild-based build system with third-party builders' +
' may cause unexpected behavior and/or build failures.',
);
}
// The compatibility builder should be used if esbuild is force enabled.
return '@angular-devkit/build-angular:browser-esbuild';
}
return info.builderName;
}
| {
"end_byte": 8048,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/builder.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/index.ts_0_699 | /**
* @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 { DevServerBuilderOutput } from '@angular/build';
import { createBuilder } from '@angular-devkit/architect';
import { execute } from './builder';
import { Schema as DevServerBuilderOptions } from './schema';
export {
type DevServerBuilderOptions,
type DevServerBuilderOutput,
execute as executeDevServerBuilder,
};
export default createBuilder<DevServerBuilderOptions, DevServerBuilderOutput>(execute);
// Temporary export to support specs
export { execute as executeDevServer };
| {
"end_byte": 699,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/index.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/options.ts_0_4388 | /**
* @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 { BuilderContext, targetFromTargetString } from '@angular-devkit/architect';
import path from 'node:path';
import { normalizeCacheOptions } from '../../utils/normalize-cache';
import { normalizeOptimization } from '../../utils/normalize-optimization';
import { isEsbuildBased } from './builder';
import { Schema as DevServerOptions } from './schema';
export type NormalizedDevServerOptions = Awaited<ReturnType<typeof normalizeOptions>>;
/**
* Normalize the user provided options by creating full paths for all path based options
* and converting multi-form options into a single form that can be directly used
* by the build process.
*
* @param context The context for current builder execution.
* @param projectName The name of the project for the current execution.
* @param options An object containing the options to use for the build.
* @returns An object containing normalized options required to perform the build.
*/
export async function normalizeOptions(
context: BuilderContext,
projectName: string,
options: DevServerOptions,
) {
const { workspaceRoot, logger } = context;
const projectMetadata = await context.getProjectMetadata(projectName);
const projectRoot = path.join(workspaceRoot, (projectMetadata.root as string | undefined) ?? '');
const cacheOptions = normalizeCacheOptions(projectMetadata, workspaceRoot);
// Target specifier defaults to the current project's build target using a development configuration
const buildTargetSpecifier = options.buildTarget ?? `::development`;
const buildTarget = targetFromTargetString(buildTargetSpecifier, projectName, 'build');
// Get the application builder options.
const browserBuilderName = await context.getBuilderNameForTarget(buildTarget);
const rawBuildOptions = await context.getTargetOptions(buildTarget);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buildOptions = (await context.validateOptions(rawBuildOptions, browserBuilderName)) as any;
const optimization = normalizeOptimization(buildOptions.optimization);
if (options.prebundle !== false && isEsbuildBased(browserBuilderName)) {
if (!cacheOptions.enabled) {
// Warn if the initial options provided by the user enable prebundling but caching is disabled
logger.warn(
'Prebundling has been configured but will not be used because caching has been disabled.',
);
} else if (optimization.scripts) {
// Warn if the initial options provided by the user enable prebundling but script optimization is enabled.
logger.warn(
'Prebundling has been configured but will not be used because scripts optimization is enabled.',
);
}
}
let inspect: false | { host?: string; port?: number } = false;
const inspectRaw = options.inspect;
if (inspectRaw === true || inspectRaw === '' || inspectRaw === 'true') {
inspect = {
host: undefined,
port: undefined,
};
} else if (typeof inspectRaw === 'string' && inspectRaw !== 'false') {
const port = +inspectRaw;
if (isFinite(port)) {
inspect = {
host: undefined,
port,
};
} else {
const [host, port] = inspectRaw.split(':');
inspect = {
host,
port: isNaN(+port) ? undefined : +port,
};
}
}
// Initial options to keep
const {
host,
port,
poll,
open,
verbose,
watch,
allowedHosts,
disableHostCheck,
liveReload,
hmr,
headers,
proxyConfig,
servePath,
publicHost,
ssl,
sslCert,
sslKey,
forceEsbuild,
prebundle,
} = options;
// Return all the normalized options
return {
buildTarget,
host: host ?? 'localhost',
port: port ?? 4200,
poll,
open,
verbose,
watch,
liveReload,
hmr,
headers,
workspaceRoot,
projectRoot,
cacheOptions,
allowedHosts,
disableHostCheck,
proxyConfig,
servePath,
publicHost,
ssl,
sslCert,
sslKey,
forceEsbuild,
// Prebundling defaults to true but requires caching to function
prebundle: cacheOptions.enabled && !optimization.scripts && (prebundle ?? true),
inspect,
};
}
| {
"end_byte": 4388,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/options.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts_0_3874 | /**
* @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 { Architect, BuilderRun } from '@angular-devkit/architect';
import { DevServerBuilderOutput } from '@angular-devkit/build-angular';
import { tags } from '@angular-devkit/core';
import { Agent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
import { createArchitect, host } from '../../../testing/test-utils';
describe('Dev Server Builder ssl', () => {
const target = { project: 'app', target: 'serve' };
let architect: Architect;
// We use runs like this to ensure it WILL stop the servers at the end of each tests.
let runs: BuilderRun[];
beforeEach(async () => {
await host.initialize().toPromise();
architect = (await createArchitect(host.root())).architect;
runs = [];
});
afterEach(async () => {
await host.restore().toPromise();
await Promise.all(runs.map((r) => r.stop()));
});
it('works', async () => {
const run = await architect.scheduleTarget(target, { ssl: true, port: 0 });
runs.push(run);
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
expect(output.baseUrl).toMatch(/^https:\/\/localhost:\d+\//);
// The self-signed certificate used by the dev server will cause fetch to fail
// unless reject unauthorized is disabled.
const originalDispatcher = getGlobalDispatcher();
setGlobalDispatcher(
new Agent({
connect: { rejectUnauthorized: false },
}),
);
try {
const response = await fetch(output.baseUrl);
expect(await response.text()).toContain('<title>HelloWorldApp</title>');
} finally {
setGlobalDispatcher(originalDispatcher);
}
});
it('supports key and cert', async () => {
host.writeMultipleFiles({
'ssl/server.key': tags.stripIndents`
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0+kOHdfpsPNUguCtai27DJ+DuOfVw4gw1P3BgYhNG8qoukaW
gdDLowj59+cXXgn9ZnQ8PdvZXhCEQcP3wjd1cBPuGQzO7BekoKEgzfGE/zjrrIeL
Q7tHYx9ddCPotQX4OJu4FZFJyS1Ar7zDDpQ9fSw6qmsXWN6I18fIGSVvbDbVB9rw
iAsLGe2jWadjXAjSqVOy6aT+CKJgnRnxudNZGP1LRC1YDRl/s7icCIh/9gEGfn7G
gwQQ9AM2p3JNjP2quclSjBvMv0uVj+yzL2bPGRz0hu90CDaIEU2FtBCse50/O75q
x0bQnPbuHKD3ajs0DfQYoAmFZGK078ZDl/VQxwIDAQABAoIBAEl17kXcNo/4GqDw
QE2hoslCdwhfnhQVn1AG09ESriBnRcylccF4308aaoVM4CXicqzUuJl9IEJimWav
B7GVRinfTtfyP71KiPCCSvv5sPBFDDYYGugVAS9UjTIYzLAMbLs7CDq5zglmnZkO
Z9QjAZnl/kRbsZFGO8wJ3s0Q1Cp/ygZcvFU331K2jHXW7B4YXiFOH/lBQrjdz0Gy
WBjX4zIdNWnwarvxu46IS/0z1P1YOHM8+B1Uv54MG94A6szBdd/Vp0cQRs78t/Cu
BQ1Rnuk16Pi+ieC5K04yUgeuNusYW0PWLtPX1nKNp9z46bmD1NHKAxaoDFXr7qP3
pZCaDMkCgYEA8mmTYrhXJTRIrOxoUwM1e3OZ0uOxVXJJ8HF6X8t+UO6dFxXB/JC9
ZBc+94cZQapaKFOeMmd/j3L2CQIjChk5yKV/G3Io+raxIoAAKPCkMF4NQQVvvNkS
CAGl61Qa78DoF5Habumz0AC1R9P877kNTC0aPSt4lhPWgfotbZNNMlMCgYEA38nM
s4a0pZseXPkuOtPYX/3Ms3E+d70XKSFuIMCHCg79YGsQ8h/9apYcPyeYkpQ0a4gs
I3IUqMaXC2OyqWA5LU1BZv51mXb6zcb2pokZfpiSWk+7sy5XjkE9EmQxp3xHfV3c
EO/DxHfWNvtMjESMbhu0yVzM2O/Aa53Tl9lqAT0CgYEA1dXBuHyqCtyTG08zO78B
55Ny5rAJ1zkI9jvz2hr0o0nJcvqzcyruliNXXRxkcCNoglg4nXfk81JSrGGhLSBR
c6hhdoF+mqKboLZO7c5Q14WvpWK5TVoiaMOja/J2DHYbhecYS2yGPH7TargaUBDq
JP9IPRtitOhs+Z0Jg7ZDi5cCgYAMb7B6gY/kbBxh2k8hYchyfS41AqQQD2gMFxmB
pHFcs7yM8SY97l0s4S6sq8ykyKupFiYtyhcv0elu7pltJDXJOLPbv2RVpPEHInlu
g8vw5xWrAydRK9Adza5RKVRBFHz8kIy8PDbK4kX7RDfay6xqKgv/7LJNk/VDhb/O
fnyPmQKBgQDg/o8Ubf/gxA9Husnuld4DBu3wwFhkMlWqyO9QH3cKgojQ2JGSrfDz
xHhetmhionEyzg0JCaMSpzgIHY+8o/NAwc++OjNHEoYp3XWM9GTp81ROMz6b83jV
biVR9N0MhONdwF6vtzDCcJxNIUe2p4lTvLf/Xd9jaQDNXe35Gxsdyg==
-----END RSA PRIVATE KEY-----
`, | {
"end_byte": 3874,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts_3881_6429 | 'ssl/server.crt': tags.stripIndents`
-----BEGIN CERTIFICATE-----
MIID5jCCAs6gAwIBAgIJAJOebwfGCm61MA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV
BAYTAlVTMRAwDgYDVQQIEwdHZW9yZ2lhMRAwDgYDVQQHEwdBdGxhbnRhMRAwDgYD
VQQKEwdBbmd1bGFyMRAwDgYDVQQLEwdBbmd1bGFyMB4XDTE2MTAwNDAxMDAyMVoX
DTI2MTAwMjAxMDAyMVowVTELMAkGA1UEBhMCVVMxEDAOBgNVBAgTB0dlb3JnaWEx
EDAOBgNVBAcTB0F0bGFudGExEDAOBgNVBAoTB0FuZ3VsYXIxEDAOBgNVBAsTB0Fu
Z3VsYXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDT6Q4d1+mw81SC
4K1qLbsMn4O459XDiDDU/cGBiE0byqi6RpaB0MujCPn35xdeCf1mdDw929leEIRB
w/fCN3VwE+4ZDM7sF6SgoSDN8YT/OOush4tDu0djH110I+i1Bfg4m7gVkUnJLUCv
vMMOlD19LDqqaxdY3ojXx8gZJW9sNtUH2vCICwsZ7aNZp2NcCNKpU7LppP4IomCd
GfG501kY/UtELVgNGX+zuJwIiH/2AQZ+fsaDBBD0Azanck2M/aq5yVKMG8y/S5WP
7LMvZs8ZHPSG73QINogRTYW0EKx7nT87vmrHRtCc9u4coPdqOzQN9BigCYVkYrTv
xkOX9VDHAgMBAAGjgbgwgbUwHQYDVR0OBBYEFG4VV6/aNLx/qFIS9MhAWuyeV5OX
MIGFBgNVHSMEfjB8gBRuFVev2jS8f6hSEvTIQFrsnleTl6FZpFcwVTELMAkGA1UE
BhMCVVMxEDAOBgNVBAgTB0dlb3JnaWExEDAOBgNVBAcTB0F0bGFudGExEDAOBgNV
BAoTB0FuZ3VsYXIxEDAOBgNVBAsTB0FuZ3VsYXKCCQCTnm8HxgputTAMBgNVHRME
BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQDO4jZT/oKVxaiWr+jV5TD+qwThl9zT
Uw/ZpFDkdbZdY/baCFaLCiJwkK9+puMOabLvm1VzcnHHWCoiUNbWpw8AOumLEnTv
ze/5OZXJ6XlA9kd9f3hDlN5zNB3S+Z2nKIrkPGfxQZ603QCbWaptip5dxgek6oDZ
YXVtnbOnPznRsG5jh07U49RO8CNebqZLzdRToLgObbqYlfRMcbUxCOHXjnB5wUlp
377Iivm4ldnCTvFOjEiDh+FByWL5xic7PjyJPZFMidiYTmsGilP9XTFC83CRZwz7
vW+RCSlU6x8Uejz98BPmASoqCuCTUeOo+2pFelFhX9NwR/Sb6b7ybdPv
-----END CERTIFICATE-----
`,
});
const overrides = {
ssl: true,
sslKey: 'ssl/server.key',
sslCert: 'ssl/server.crt',
port: 0,
};
const run = await architect.scheduleTarget(target, overrides);
runs.push(run);
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
expect(output.baseUrl).toMatch(/^https:\/\/localhost:\d+\//);
// The self-signed certificate used by the dev server will cause fetch to fail
// unless reject unauthorized is disabled.
const originalDispatcher = getGlobalDispatcher();
setGlobalDispatcher(
new Agent({
connect: { rejectUnauthorized: false },
}),
);
try {
const response = await fetch(output.baseUrl);
expect(await response.text()).toContain('<title>HelloWorldApp</title>');
} finally {
setGlobalDispatcher(originalDispatcher);
}
});
}); | {
"end_byte": 6429,
"start_byte": 3881,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts_0_3672 | /**
* @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 { Architect, BuilderRun } from '@angular-devkit/architect';
import { DevServerBuilderOutput } from '@angular-devkit/build-angular';
import { EmittedFiles } from '@angular-devkit/build-webpack';
import { normalize, virtualFs } from '@angular-devkit/core';
import { createArchitect, host } from '../../../testing/test-utils';
describe('Dev Server Builder', () => {
const target = { project: 'app', target: 'serve' };
let architect: Architect;
let runs: BuilderRun[] = [];
beforeEach(async () => {
await host.initialize().toPromise();
architect = (await createArchitect(host.root())).architect;
runs = [];
});
afterEach(async () => {
await host.restore().toPromise();
await Promise.all(runs.map((r) => r.stop()));
});
it(`doesn't serve files on the cwd directly`, async () => {
const run = await architect.scheduleTarget(target);
runs.push(run);
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
// When webpack-dev-server doesn't have `contentBase: false`, this will serve the repo README.
const response = await fetch(`http://localhost:${output.port}/README.md`, {
headers: {
'Accept': 'text/html',
},
});
const res = await response.text();
expect(res).not.toContain('This file is automatically generated during release.');
expect(res).toContain('<title>HelloWorldApp</title>');
});
it('should not generate sourcemaps when running prod build', async () => {
// Production builds have sourcemaps turned off.
const run = await architect.scheduleTarget(
{ ...target, configuration: 'production' },
{ port: 0 },
);
runs.push(run);
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
const hasSourceMaps =
output.emittedFiles && output.emittedFiles.some((f: EmittedFiles) => f.extension === '.map');
expect(hasSourceMaps).toBe(false, `Expected emitted files not to contain '.map' files.`);
});
it('serves custom headers', async () => {
const run = await architect.scheduleTarget(target, {
headers: { 'X-Header': 'Hello World' },
port: 0,
});
runs.push(run);
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
const response = await fetch(output.baseUrl);
expect(response.headers.get('X-Header')).toBe('Hello World');
});
it('uses source locale when not localizing', async () => {
const config = host.scopedSync().read(normalize('angular.json'));
const jsonConfig = JSON.parse(virtualFs.fileBufferToString(config));
const applicationProject = jsonConfig.projects.app;
applicationProject.i18n = { sourceLocale: 'fr' };
host.writeMultipleFiles({
'angular.json': JSON.stringify(jsonConfig),
});
const architect = (await createArchitect(host.root())).architect;
const run = await architect.scheduleTarget(target, { port: 0 });
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
const indexResponse = await fetch(output.baseUrl);
expect(await indexResponse.text()).toContain('lang="fr"');
const vendorResponse = await fetch(output.baseUrl + 'vendor.js');
const vendorText = await vendorResponse.text();
expect(vendorText).toContain('fr');
expect(vendorText).toContain('octobre');
await run.stop();
});
});
| {
"end_byte": 3672,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts_0_6329 | /**
* @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 { Architect, BuilderRun } from '@angular-devkit/architect';
// eslint-disable-next-line import/no-extraneous-dependencies
import puppeteer, { Browser, Page } from 'puppeteer';
import { debounceTime, switchMap, take } from 'rxjs';
import { createArchitect, host } from '../../../testing/test-utils';
/* eslint-disable @typescript-eslint/no-explicit-any */
declare const document: any;
declare const getComputedStyle: any;
/* eslint-enable @typescript-eslint/no-explicit-any */
describe('Dev Server Builder HMR', () => {
const target = { project: 'app', target: 'serve' };
const overrides = { hmr: true, watch: true, port: 0 };
let architect: Architect;
let browser: Browser;
let page: Page;
let logs: string[] = [];
let runs: BuilderRun[];
beforeAll(async () => {
browser = await puppeteer.launch({
// MacOSX users need to set the local binary manually because Chrome has lib files with
// spaces in them which Bazel does not support in runfiles
// See: https://github.com/angular/angular-cli/pull/17624
// eslint-disable-next-line max-len
// executablePath: '/Users/<USERNAME>/git/angular-cli/node_modules/puppeteer/.local-chromium/mac-800071/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
args: ['--no-sandbox', '--disable-gpu'],
});
});
afterAll(async () => {
await browser.close();
});
beforeEach(async () => {
await host.initialize().toPromise();
architect = (await createArchitect(host.root())).architect;
logs = [];
runs = [];
page = await browser.newPage();
page.on('console', (msg) => logs.push(msg.text()));
host.writeMultipleFiles({
'src/app/app.component.html': `
<p>{{title}}</p>
<input class="visible" type="text">
<input type="file">
<input type="hidden">
<select>
<option>one</option>
<option>two</option>
</select>
`,
});
});
afterEach(async () => {
await host.restore().toPromise();
await page.close();
await Promise.all(runs.map((r) => r.stop()));
});
it('works for CSS changes', async () => {
const run = await architect.scheduleTarget(target, overrides);
runs.push(run);
let buildCount = 0;
await run.output
.pipe(
debounceTime(1000),
switchMap(async (buildEvent) => {
expect(buildEvent.success).toBe(true);
const url = buildEvent.baseUrl as string;
switch (buildCount) {
case 0:
await page.goto(url);
expect(logs).toContain('[HMR] Waiting for update signal from WDS...');
host.writeMultipleFiles({
'src/styles.css': 'p { color: rgb(255, 255, 0) }',
});
break;
case 1:
expect(logs).toContain('[HMR] Updated modules:');
expect(logs).toContain(`[HMR] css reload %s ${url}styles.css`);
expect(logs).toContain('[HMR] App is up to date.');
const pTagColor = await page.evaluate(() => {
const el = document.querySelector('p');
return getComputedStyle(el).color;
});
expect(pTagColor).toBe('rgb(255, 255, 0)');
break;
}
logs = [];
buildCount++;
}),
take(2),
)
.toPromise();
});
it('works for TS changes', async () => {
const run = await architect.scheduleTarget(target, overrides);
runs.push(run);
let buildCount = 0;
await run.output
.pipe(
debounceTime(1000),
switchMap(async (buildEvent) => {
expect(buildEvent.success).toBe(true);
const url = buildEvent.baseUrl as string;
switch (buildCount) {
case 0:
await page.goto(url);
expect(logs).toContain('[HMR] Waiting for update signal from WDS...');
host.replaceInFile('src/app/app.component.ts', `'app'`, `'app-hmr'`);
break;
case 1:
expect(logs).toContain('[HMR] Updated modules:');
expect(logs).toContain('[HMR] App is up to date.');
const innerText = await page.evaluate(() => document.querySelector('p').innerText);
expect(innerText).toBe('app-hmr');
break;
}
logs = [];
buildCount++;
}),
take(2),
)
.toPromise();
});
it('restores input and select values', async () => {
const run = await architect.scheduleTarget(target, overrides);
runs.push(run);
let buildCount = 0;
await run.output
.pipe(
debounceTime(1000),
switchMap(async (buildEvent) => {
expect(buildEvent.success).toBe(true);
const url = buildEvent.baseUrl as string;
switch (buildCount) {
case 0:
await page.goto(url);
expect(logs).toContain('[HMR] Waiting for update signal from WDS...');
await page.evaluate(() => {
document.querySelector('input.visible').value = 'input value';
document.querySelector('select').value = 'two';
});
host.replaceInFile('src/app/app.component.ts', `'app'`, `'app-hmr'`);
break;
case 1:
expect(logs).toContain('[HMR] Updated modules:');
expect(logs).toContain('[HMR] App is up to date.');
expect(logs).toContain('[NG HMR] Restoring input/textarea values.');
expect(logs).toContain('[NG HMR] Restoring selected options.');
const inputValue = await page.evaluate(
() => document.querySelector('input.visible').value,
);
expect(inputValue).toBe('input value');
const selectValue = await page.evaluate(() => document.querySelector('select').value);
expect(selectValue).toBe('two');
break;
}
logs = [];
buildCount++;
}),
take(2),
)
.toPromise();
});
});
| {
"end_byte": 6329,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts_0_1787 | /**
* @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 { DevServerBuilderOutput } from '@angular-devkit/build-angular';
import { workspaces } from '@angular-devkit/core';
import { createArchitect, host } from '../../../testing/test-utils';
describe('Dev Server Builder index', () => {
const targetSpec = { project: 'app', target: 'serve' };
beforeEach(async () => host.initialize().toPromise());
afterEach(async () => host.restore().toPromise());
it('sets HTML lang attribute with the active locale', async () => {
const locale = 'fr';
const { workspace } = await workspaces.readWorkspace(
host.root(),
workspaces.createWorkspaceHost(host),
);
const app = workspace.projects.get('app');
if (!app) {
fail('Test application "app" not found.');
return;
}
app.extensions['i18n'] = {
locales: {
[locale]: [],
},
};
const target = app.targets.get('build');
if (!target) {
fail('Test application "app" target "build" not found.');
return;
}
if (!target.options) {
target.options = {};
}
target.options.localize = [locale];
await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host));
const architect = (await createArchitect(host.root())).architect;
const run = await architect.scheduleTarget(targetSpec, { port: 0 });
const output = (await run.result) as DevServerBuilderOutput;
expect(output.success).toBe(true);
const response = await fetch(output.baseUrl);
expect(await response.text()).toContain(`lang="${locale}"`);
await run.stop();
});
});
| {
"end_byte": 1787,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/jasmine-helpers.ts_0_1908 | /**
* @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 { BuilderHandlerFn } from '@angular-devkit/architect';
import { json } from '@angular-devkit/core';
import { readFileSync } from 'fs';
import { JasmineBuilderHarness } from '../../../testing';
import { host } from '../../../testing/test-utils';
import { setupApplicationTarget, setupBrowserTarget } from './setup';
const optionSchemaCache = new Map<string, json.schema.JsonSchema>();
export function describeServeBuilder<T>(
builderHandler: BuilderHandlerFn<T & json.JsonObject>,
options: { name?: string; schemaPath: string },
specDefinitions: ((
harness: JasmineBuilderHarness<T>,
setupTarget: typeof setupApplicationTarget,
isViteRun: true,
) => void) &
((
harness: JasmineBuilderHarness<T>,
setupTarget: typeof setupBrowserTarget,
isViteRun: false,
) => void),
): void {
let optionSchema = optionSchemaCache.get(options.schemaPath);
if (optionSchema === undefined) {
optionSchema = JSON.parse(readFileSync(options.schemaPath, 'utf8')) as json.schema.JsonSchema;
optionSchemaCache.set(options.schemaPath, optionSchema);
}
const harness = new JasmineBuilderHarness<T>(builderHandler, host, {
builderName: options.name,
optionSchema,
});
describe(options.name || builderHandler.name, () => {
for (const isViteRun of [true, false]) {
describe(isViteRun ? 'vite' : 'webpack-dev-server', () => {
beforeEach(() => host.initialize().toPromise());
afterEach(() => host.restore().toPromise());
if (isViteRun) {
specDefinitions(harness, setupApplicationTarget, true);
} else {
specDefinitions(harness, setupBrowserTarget, false);
}
});
}
});
}
| {
"end_byte": 1908,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/jasmine-helpers.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/setup.ts_0_4208 | /**
* @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 { json } from '@angular-devkit/core';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { BuilderHarness } from '../../../testing';
import { ApplicationBuilderOptions as AppilicationSchema, buildApplication } from '@angular/build';
import { buildWebpackBrowser } from '../../browser';
import { Schema as BrowserSchema } from '../../browser/schema';
import {
BASE_OPTIONS as BROWSER_BASE_OPTIONS,
BROWSER_BUILDER_INFO,
} from '../../browser/tests/setup';
import { Schema } from '../schema';
export { describeBuilder } from '../../../testing';
// TODO: Remove and use import after Vite-based dev server is moved to new package
export const APPLICATION_BUILDER_INFO = Object.freeze({
name: '@angular-devkit/build-angular:application',
schemaPath: path.join(
path.dirname(require.resolve('@angular/build/package.json')),
'src/builders/application/schema.json',
),
});
/**
* Contains all required application builder fields.
* Also disables progress reporting to minimize logging output.
*/
export const APPLICATION_BASE_OPTIONS = Object.freeze<AppilicationSchema>({
index: 'src/index.html',
browser: 'src/main.ts',
outputPath: 'dist',
tsConfig: 'src/tsconfig.app.json',
progress: false,
// Disable optimizations
optimization: false,
// Enable polling (if a test enables watch mode).
// This is a workaround for bazel isolation file watch not triggering in tests.
poll: 100,
});
export const DEV_SERVER_BUILDER_INFO = Object.freeze({
name: '@angular-devkit/build-angular:dev-server',
schemaPath: __dirname + '/../schema.json',
});
/**
* Contains all required dev-server builder fields.
* The port is also set to zero to ensure a free port is used for each test which
* supports parallel test execution.
*/
export const BASE_OPTIONS = Object.freeze<Schema>({
buildTarget: 'test:build',
port: 0,
// Watch is not supported for testing in vite as currently there is no teardown logic to stop the watchers.
watch: false,
});
/**
* Maximum time for single build/rebuild
* This accounts for CI variability.
*/
export const BUILD_TIMEOUT = 25_000;
/**
* Cached browser builder option schema
*/
let browserSchema: json.schema.JsonSchema | undefined;
/**
* Adds a `build` target to a builder test harness for the browser builder with the base options
* used by the browser builder tests.
*
* @param harness The builder harness to use when setting up the browser builder target
* @param extraOptions The additional options that should be used when executing the target.
*/
export function setupBrowserTarget<T>(
harness: BuilderHarness<T>,
extraOptions?: Partial<BrowserSchema>,
): void {
browserSchema ??= JSON.parse(
readFileSync(BROWSER_BUILDER_INFO.schemaPath, 'utf8'),
) as json.schema.JsonSchema;
harness.withBuilderTarget(
'build',
buildWebpackBrowser,
{
...BROWSER_BASE_OPTIONS,
...extraOptions,
},
{
builderName: BROWSER_BUILDER_INFO.name,
optionSchema: browserSchema,
},
);
}
/**
* Cached application builder option schema
*/
let applicationSchema: json.schema.JsonSchema | undefined;
/**
* Adds a `build` target to a builder test harness for the application builder with the base options
* used by the application builder tests.
*
* @param harness The builder harness to use when setting up the application builder target
* @param extraOptions The additional options that should be used when executing the target.
*/
export function setupApplicationTarget<T>(
harness: BuilderHarness<T>,
extraOptions?: Partial<AppilicationSchema>,
): void {
applicationSchema ??= JSON.parse(
readFileSync(APPLICATION_BUILDER_INFO.schemaPath, 'utf8'),
) as json.schema.JsonSchema;
harness.withBuilderTarget(
'build',
buildApplication,
{
...APPLICATION_BASE_OPTIONS,
...extraOptions,
},
{
builderName: APPLICATION_BUILDER_INFO.name,
optionSchema: applicationSchema,
},
);
}
| {
"end_byte": 4208,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/setup.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/execute-fetch.ts_0_1455 | /**
* @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 { lastValueFrom, mergeMap, take, timeout } from 'rxjs';
import { URL } from 'url';
import {
BuilderHarness,
BuilderHarnessExecutionOptions,
BuilderHarnessExecutionResult,
} from '../../../testing';
export async function executeOnceAndFetch<T>(
harness: BuilderHarness<T>,
url: string,
options?: Partial<BuilderHarnessExecutionOptions> & { request?: RequestInit },
): Promise<BuilderHarnessExecutionResult & { response?: Response; content?: string }> {
return lastValueFrom(
harness.execute().pipe(
timeout(30000),
mergeMap(async (executionResult) => {
let response = undefined;
let content = undefined;
if (executionResult.result?.success) {
let baseUrl = `${executionResult.result.baseUrl}`;
baseUrl = baseUrl[baseUrl.length - 1] === '/' ? baseUrl : `${baseUrl}/`;
const resolvedUrl = new URL(url, baseUrl);
const originalResponse = await fetch(resolvedUrl, options?.request);
response = originalResponse.clone();
// Ensure all data is available before stopping server
content = await originalResponse.text();
}
return { ...executionResult, response, content };
}),
take(1),
),
);
}
| {
"end_byte": 1455,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/execute-fetch.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve_service-worker_spec.ts_0_7449 | /**
* @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 { concatMap, count, take, timeout } from 'rxjs';
import { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup';
const manifest = {
index: '/index.html',
assetGroups: [
{
name: 'app',
installMode: 'prefetch',
resources: {
files: ['/favicon.ico', '/index.html'],
},
},
{
name: 'assets',
installMode: 'lazy',
updateMode: 'prefetch',
resources: {
files: [
'/media/**',
'/assets/**',
'/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)',
],
},
},
],
};
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
describe('Behavior: "dev-server builder serves service worker"', () => {
beforeEach(async () => {
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
await harness.writeFile('src/polyfills.ts', '');
harness.useProject('test', {
root: '.',
sourceRoot: 'src',
cli: {
cache: {
enabled: false,
},
},
i18n: {
sourceLocale: {
'code': 'fr',
},
},
});
});
it('works with service worker', async () => {
setupTarget(harness, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serviceWorker: (isViteRun ? 'ngsw-config.json' : true) as any,
resourcesOutputPath: isViteRun ? undefined : 'media',
assets: ['src/favicon.ico', 'src/assets'],
styles: ['src/styles.css'],
});
await harness.writeFiles({
'ngsw-config.json': JSON.stringify(manifest),
'src/assets/folder-asset.txt': 'folder-asset.txt',
'src/styles.css': `body { background: url(./spectrum.png); }`,
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/ngsw.json');
expect(result?.success).toBeTrue();
expect(await response?.json()).toEqual(
jasmine.objectContaining({
configVersion: 1,
index: '/index.html',
navigationUrls: [
{ positive: true, regex: '^\\/.*$' },
{ positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$' },
{ positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$' },
{ positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$' },
],
assetGroups: [
{
name: 'app',
installMode: 'prefetch',
updateMode: 'prefetch',
urls: ['/favicon.ico', '/index.html'],
cacheQueryOptions: {
ignoreVary: true,
},
patterns: [],
},
{
name: 'assets',
installMode: 'lazy',
updateMode: 'prefetch',
urls: ['/assets/folder-asset.txt', '/media/spectrum.png'],
cacheQueryOptions: {
ignoreVary: true,
},
patterns: [],
},
],
dataGroups: [],
hashTable: {
'/favicon.ico': '84161b857f5c547e3699ddfbffc6d8d737542e01',
'/assets/folder-asset.txt': '617f202968a6a81050aa617c2e28e1dca11ce8d4',
'/index.html': isViteRun
? 'e5b73e6798d2782bf59dd5272d254d5bde364695'
: '9d232e3e13b4605d197037224a2a6303dd337480',
'/media/spectrum.png': '8d048ece46c0f3af4b598a95fd8e4709b631c3c0',
},
}),
);
});
it('works with localize', async () => {
setupTarget(harness, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serviceWorker: (isViteRun ? 'ngsw-config.json' : true) as any,
resourcesOutputPath: isViteRun ? undefined : 'media',
assets: ['src/favicon.ico', 'src/assets'],
styles: ['src/styles.css'],
localize: ['fr'],
});
await harness.writeFiles({
'ngsw-config.json': JSON.stringify(manifest),
'src/assets/folder-asset.txt': 'folder-asset.txt',
'src/styles.css': `body { background: url(./spectrum.png); }`,
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/ngsw.json');
expect(result?.success).toBeTrue();
expect(await response?.json()).toBeDefined();
});
// TODO(fix-vite): currently this is broken in vite due to watcher never terminates.
(isViteRun ? xit : it)('works in watch mode', async () => {
setupTarget(harness, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serviceWorker: (isViteRun ? 'ngsw-config.json' : true) as any,
resourcesOutputPath: isViteRun ? undefined : 'media',
assets: ['src/favicon.ico', 'src/assets'],
styles: ['src/styles.css'],
});
await harness.writeFiles({
'ngsw-config.json': JSON.stringify(manifest),
'src/assets/folder-asset.txt': 'folder-asset.txt',
'src/styles.css': `body { background: url(./spectrum.png); }`,
});
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: true,
});
const buildCount = await harness
.execute()
.pipe(
timeout(BUILD_TIMEOUT),
concatMap(async ({ result }, index) => {
expect(result?.success).toBeTrue();
const response = await fetch(new URL('ngsw.json', `${result?.baseUrl}`));
const { hashTable } = (await response.json()) as { hashTable: object };
const hashTableEntries = Object.keys(hashTable);
switch (index) {
case 0:
expect(hashTableEntries).toEqual([
'/assets/folder-asset.txt',
'/favicon.ico',
'/index.html',
'/media/spectrum.png',
]);
await harness.writeFile(
'src/assets/folder-new-asset.txt',
harness.readFile('src/assets/folder-asset.txt'),
);
break;
case 1:
expect(hashTableEntries).toEqual([
'/assets/folder-asset.txt',
'/assets/folder-new-asset.txt',
'/favicon.ico',
'/index.html',
'/media/spectrum.png',
]);
break;
}
}),
take(2),
count(),
)
.toPromise();
expect(buildCount).toBe(2);
});
});
},
);
| {
"end_byte": 7449,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve_service-worker_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-deploy-url_spec.ts_0_1165 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import {
BASE_OPTIONS,
DEV_SERVER_BUILDER_INFO,
describeBuilder,
setupBrowserTarget,
} from '../setup';
describeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness) => {
describe('Behavior: "browser builder deployUrl"', () => {
beforeEach(() => {
setupBrowserTarget(harness, {
deployUrl: 'test/',
});
});
it('uses the deploy URL defined in the "browserTarget" options as the serve path', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, 'runtime.js');
expect(result?.success).toBeTrue();
expect(result?.baseUrl).toMatch(/\/test$/);
expect(response?.url).toMatch(/\/test\/runtime.js$/);
expect(await response?.text()).toContain('self["webpackChunktest"]');
});
});
});
| {
"end_byte": 1165,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-deploy-url_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-assets_spec.ts_0_3644 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isVite) => {
const javascriptFileContent =
"import {foo} from 'unresolved'; /* a comment */const foo = `bar`;\n\n\n";
describe('Behavior: "browser builder assets"', () => {
it('serves a project JavaScript asset unmodified', async () => {
await harness.writeFile('src/extra.js', javascriptFileContent);
setupTarget(harness, {
assets: ['src/extra.js'],
optimization: {
scripts: true,
},
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, 'extra.js');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain(javascriptFileContent);
});
it('serves a project TypeScript asset unmodified', async () => {
await harness.writeFile('src/extra.ts', javascriptFileContent);
setupTarget(harness, {
assets: ['src/extra.ts'],
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, 'extra.ts');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain(javascriptFileContent);
});
it('should return 404 for non existing assets', async () => {
setupTarget(harness, {
assets: [],
optimization: {
scripts: true,
},
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, 'does-not-exist.js');
expect(result?.success).toBeTrue();
expect(await response?.status).toBe(404);
});
it(`should return the asset that matches 'index.html' when path has a trailing '/'`, async () => {
await harness.writeFile(
'src/login/index.html',
'<html><body><h1>Login page</h1></body><html>',
);
setupTarget(harness, {
assets: ['src/login'],
optimization: {
scripts: true,
},
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, 'login/');
expect(result?.success).toBeTrue();
expect(await response?.status).toBe(200);
expect(await response?.text()).toContain('<h1>Login page</h1>');
});
(isVite ? it : xit)(
`should return the asset that matches '.html' when path has no trailing '/'`,
async () => {
await harness.writeFile(
'src/login/new.html',
'<html><body><h1>Login page</h1></body><html>',
);
setupTarget(harness, {
assets: ['src/login'],
optimization: {
scripts: true,
},
});
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, 'login/new');
expect(result?.success).toBeTrue();
expect(await response?.status).toBe(200);
expect(await response?.text()).toContain('<h1>Login page</h1>');
},
);
});
});
| {
"end_byte": 3644,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-assets_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build_localize_replaced_watch_spec.ts_0_2476 | /**
* @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
*/
/* eslint-disable max-len */
import { concatMap, count, take, timeout } from 'rxjs';
import { URL } from 'url';
import { executeDevServer } from '../../index';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xdescribe : describe)(
'Behavior: "i18n $localize calls are replaced during watching"',
() => {
beforeEach(() => {
harness.useProject('test', {
root: '.',
sourceRoot: 'src',
cli: {
cache: {
enabled: false,
},
},
i18n: {
sourceLocale: {
'code': 'fr',
},
},
});
setupTarget(harness, { localize: ['fr'] });
});
it('$localize are replaced in watch', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: true,
});
await harness.writeFile(
'src/app/app.component.html',
`
<p id="hello" i18n="An introduction header for this sample">Hello {{ title }}! </p>
`,
);
const buildCount = await harness
.execute()
.pipe(
timeout(BUILD_TIMEOUT * 2),
concatMap(async ({ result }, index) => {
expect(result?.success).toBe(true);
const response = await fetch(new URL('main.js', `${result?.baseUrl}`));
expect(await response?.text()).not.toContain('$localize`:');
switch (index) {
case 0: {
await harness.modifyFile('src/app/app.component.html', (content) =>
content.replace('introduction', 'intro'),
);
break;
}
}
}),
take(2),
count(),
)
.toPromise();
expect(buildCount).toBe(2);
});
},
);
},
);
| {
"end_byte": 2476,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build_localize_replaced_watch_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts_0_3491 | /**
* @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
*/
/* eslint-disable import/no-extraneous-dependencies */
import { tags } from '@angular-devkit/core';
import { createServer } from 'http';
import { createProxyServer } from 'http-proxy';
import { AddressInfo } from 'net';
import puppeteer, { Browser, Page } from 'puppeteer';
import { count, debounceTime, finalize, switchMap, take, timeout } from 'rxjs';
import { executeDevServer } from '../../index';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare const document: any;
interface ProxyInstance {
server: typeof createProxyServer extends () => infer R ? R : never;
url: string;
}
function findFreePort(): Promise<number> {
return new Promise<number>((resolve, reject) => {
const server = createServer();
server.once('listening', () => {
const port = (server.address() as AddressInfo).port;
server.close((e) => (e ? reject(e) : resolve(port)));
});
server.once('error', (e) => server.close(() => reject(e)));
server.listen();
});
}
async function createProxy(target: string, secure: boolean, ws = true): Promise<ProxyInstance> {
const proxyPort = await findFreePort();
const server = createProxyServer({
ws,
target,
secure,
ssl: secure && {
key: tags.stripIndents`
-----BEGIN RSA PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDEBRUsUz4rdcMt
CQGLvG3SzUinsmgdgOyTNQNA0eOMyRSrmS8L+F/kSLUnqqu4mzdeqDzo2Xj553jK
dRqMCRFGJuGnQ/VIbW2A+ywgrqILuDyF5i4PL1aQW4yJ7TnXfONKfpswQArlN6DF
gBYJtoJlf8XD1sOeJpsv/O46/ix/wngQ+GwQQ2cfqxQT0fE9SBCY23VNt3SPUJ3k
9etJMvJ9U9GHSb1CFdNQe7Gyx7xdKf1TazB27ElNZEg2aF99if47uRskYjvvFivy
7nxGx/ccIwjwNMpk29AsKG++0sn1yTK7tD5Px6aCSVK0BKbdXZS2euJor8hASGBJ
3GpVGJvdAgMBAAECggEAapYo8TVCdPdP7ckb4hPP0/R0MVu9aW2VNmZ5ImH+zar5
ZmWhQ20HF2bBupP/VB5yeTIaDLNUKO9Iqy4KBWNY1UCHKyC023FFPgFV+V98FctU
faqwGOmwtEZToRwxe48ZOISndhEc247oCPyg/x8SwIY9z0OUkwaDFBEAqWtUXxM3
/SPpCT5ilLgxnRgVB8Fj5Z0q7ThnxNVOmVC1OSIakEj46PzmMXn1pCKLOCUmAAOQ
BnrOZuty2b8b2M/GHsktLZwojQQJmArnIBymTXQTVhaGgKSyOv1qvHLp9L1OJf0/
Xm+/TqT6ztzhzlftcObdfQZZ5JuoEwlvyrsGFlA3MQKBgQDiQC3KYMG8ViJkWrv6
XNAFEoAjVEKrtirGWJ66YfQ9KSJ7Zttrd1Y1V1OLtq3z4YMH39wdQ8rOD+yR8mWV
6Tnsxma6yJXAH8uan8iVbxjIZKF1hnvNCxUoxYmWOmTLcEQMzmxvTzAiR+s6R6Uj
9LgGqppt30nM4wnOhOJU6UxqbwKBgQDdy03KidbPZuycJSy1C9AIt0jlrxDsYm+U
fZrB6mHEZcgoZS5GbLKinQCdGcgERa05BXvJmNbfZtT5a37YEnbjsTImIhDiBP5P
nW36/9a3Vg1svd1KP2206/Bh3gfZbgTsQg4YogXgjf0Uzuvw18btgTtLVpVyeuqz
TU3eeF30cwKBgQCN6lvOmapsDEs+T3uhqx4AUH53qp63PmjOSUAnANJGmsq6ROZV
HmHAy6nn9Qpf85BRHCXhZWiMoIhvc3As/EINNtWxS6hC/q6jqp4SvcD50cVFBroY
/16iWGXZCX+37A+DSOfTWgSDPEFcKRx41UOpStHbITgVgEPieo/NWxlHmQKBgQDX
JOLs2RB6V0ilnpnjdPXzvncD9fHgmwvJap24BPeZX3HtXViqD76oZsu1mNCg9EW3
zk3pnEyyoDlvSIreZerVq4kN3HWsCVP3Pqr0kz9g0CRtmy8RWr28hjHDfXD3xPUZ
iGnMEz7IOHOKv722/liFAprV1cNaLUmFbDNg3jmlaQKBgQDG5WwngPhOHmjTnSml
amfEz9a4yEhQqpqgVNW5wwoXOf6DbjL2m/maJh01giThj7inMcbpkZlIclxD0Eu6
Lof+ctCeqSAJvaVPmd+nv8Yp26zsF1yM8ax9xXjrIvv9fSbycNveGTDCsNNTiYoW
QyvMqmN1kGy20SZbQDD/fLfqBQ==
-----END RSA PRIVATE KEY-----
`, | {
"end_byte": 3491,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts_3498_6078 | cert: tags.stripIndents`
-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJALz8gD/gAt0OMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTgxMDIzMTgyMTQ5WhcNMTkxMDIzMTgyMTQ5WjBF
MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAxAUVLFM+K3XDLQkBi7xt0s1Ip7JoHYDskzUDQNHjjMkUq5kvC/hf5Ei1
J6qruJs3Xqg86Nl4+ed4ynUajAkRRibhp0P1SG1tgPssIK6iC7g8heYuDy9WkFuM
ie0513zjSn6bMEAK5TegxYAWCbaCZX/Fw9bDniabL/zuOv4sf8J4EPhsEENnH6sU
E9HxPUgQmNt1Tbd0j1Cd5PXrSTLyfVPRh0m9QhXTUHuxsse8XSn9U2swduxJTWRI
NmhffYn+O7kbJGI77xYr8u58Rsf3HCMI8DTKZNvQLChvvtLJ9ckyu7Q+T8emgklS
tASm3V2UtnriaK/IQEhgSdxqVRib3QIDAQABo1AwTjAdBgNVHQ4EFgQUDZBhVKdb
3BRhLIhuuE522Vsul0IwHwYDVR0jBBgwFoAUDZBhVKdb3BRhLIhuuE522Vsul0Iw
DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEABh9WWZwWLgb9/DcTxL72
6pI96t4jiF79Q+pPefkaIIi0mE6yodWrTAsBQu9I6bNRaEcCSoiXkP2bqskD/UGg
LwUFgSrDOAA3UjdHw3QU5g2NocduG7mcFwA40TB98sOsxsUyYlzSyWzoiQWwPYwb
hek1djuWkqPXsTjlj54PTPN/SjTFmo4p5Ip6nbRf2nOREl7v0rJpGbJvXiCMYyd+
Zv+j4mRjCGo8ysMR2HjCUGkYReLAgKyyz3M7i8vevJhKslyOmy6Txn4F0nPVumaU
DDIy4xXPW1STWfsmSYJfYW3wa0wk+pJQ3j2cTzkPQQ8gwpvM3U9DJl43uwb37v6I
7Q==
-----END CERTIFICATE-----
`,
},
}).listen(proxyPort);
return {
server,
url: `${secure ? 'https' : 'http'}://localhost:${proxyPort}`,
};
}
async function goToPageAndWaitForWS(page: Page, url: string): Promise<void> {
const baseUrl = url.replace(/^http/, 'ws');
const socksRequest =
baseUrl[baseUrl.length - 1] === '/' ? `${baseUrl}ng-cli-ws` : `${baseUrl}/ng-cli-ws`;
// Create a Chrome dev tools session so that we can capturing websocket request.
// https://github.com/puppeteer/puppeteer/issues/2974
// We do this, to ensure that we make the right request with the expected host, port etc...
const client = await page.target().createCDPSession();
await client.send('Network.enable');
await client.send('Page.enable');
await Promise.all([
new Promise<void>((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`A Websocket connected to ${socksRequest} was not established.`)),
2000,
);
client.on('Network.webSocketCreated', ({ url }) => {
if (url.startsWith(socksRequest)) {
clearTimeout(timeout);
resolve();
}
});
}),
page.goto(url),
]);
await client.detach();
} | {
"end_byte": 6078,
"start_byte": 3498,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts_6080_12248 | describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xdescribe : describe)(
'Behavior: "Dev-server builder live-reload with proxies"',
() => {
let browser: Browser;
let page: Page;
const SERVE_OPTIONS = Object.freeze({
...BASE_OPTIONS,
hmr: false,
watch: true,
liveReload: true,
});
beforeAll(async () => {
browser = await puppeteer.launch({
// MacOSX users need to set the local binary manually because Chrome has lib files with
// spaces in them which Bazel does not support in runfiles
// See: https://github.com/angular/angular-cli/pull/17624
// eslint-disable-next-line max-len
// executablePath: '/Users/<USERNAME>/git/angular-cli/node_modules/puppeteer/.local-chromium/mac-818858/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
ignoreHTTPSErrors: true,
args: ['--no-sandbox', '--disable-gpu'],
});
});
afterAll(async () => {
await browser.close();
});
beforeEach(async () => {
setupTarget(harness, {
polyfills: ['src/polyfills.ts'],
});
page = await browser.newPage();
});
afterEach(async () => {
await page.close();
});
it('works without proxy', async () => {
harness.useTarget('serve', {
...SERVE_OPTIONS,
});
await harness.writeFile('src/app/app.component.html', '<p>{{ title }}</p>');
const buildCount = await harness
.execute()
.pipe(
debounceTime(1000),
timeout(BUILD_TIMEOUT * 2),
switchMap(async ({ result }, index) => {
expect(result?.success).toBeTrue();
if (typeof result?.baseUrl !== 'string') {
throw new Error('Expected "baseUrl" to be a string.');
}
switch (index) {
case 0:
await goToPageAndWaitForWS(page, result.baseUrl);
await harness.modifyFile('src/app/app.component.ts', (content) =>
content.replace(`'app'`, `'app-live-reload'`),
);
break;
case 1:
const innerText = await page.evaluate(
() => document.querySelector('p').innerText,
);
expect(innerText).toBe('app-live-reload');
break;
}
}),
take(2),
count(),
)
.toPromise();
expect(buildCount).toBe(2);
});
it('works without http -> http proxy', async () => {
harness.useTarget('serve', {
...SERVE_OPTIONS,
});
await harness.writeFile('src/app/app.component.html', '<p>{{ title }}</p>');
let proxy: ProxyInstance | undefined;
const buildCount = await harness
.execute()
.pipe(
debounceTime(1000),
timeout(BUILD_TIMEOUT * 2),
switchMap(async ({ result }, index) => {
expect(result?.success).toBeTrue();
if (typeof result?.baseUrl !== 'string') {
throw new Error('Expected "baseUrl" to be a string.');
}
switch (index) {
case 0:
proxy = await createProxy(result.baseUrl, false);
await goToPageAndWaitForWS(page, proxy.url);
await harness.modifyFile('src/app/app.component.ts', (content) =>
content.replace(`'app'`, `'app-live-reload'`),
);
break;
case 1:
const innerText = await page.evaluate(
() => document.querySelector('p').innerText,
);
expect(innerText).toBe('app-live-reload');
break;
}
}),
take(2),
count(),
finalize(() => {
proxy?.server.close();
}),
)
.toPromise();
expect(buildCount).toBe(2);
});
it('works without https -> http proxy', async () => {
harness.useTarget('serve', {
...SERVE_OPTIONS,
});
await harness.writeFile('src/app/app.component.html', '<p>{{ title }}</p>');
let proxy: ProxyInstance | undefined;
const buildCount = await harness
.execute()
.pipe(
debounceTime(1000),
timeout(BUILD_TIMEOUT * 2),
switchMap(async ({ result }, index) => {
expect(result?.success).toBeTrue();
if (typeof result?.baseUrl !== 'string') {
throw new Error('Expected "baseUrl" to be a string.');
}
switch (index) {
case 0:
proxy = await createProxy(result.baseUrl, true);
await goToPageAndWaitForWS(page, proxy.url);
await harness.modifyFile('src/app/app.component.ts', (content) =>
content.replace(`'app'`, `'app-live-reload'`),
);
break;
case 1:
const innerText = await page.evaluate(
() => document.querySelector('p').innerText,
);
expect(innerText).toBe('app-live-reload');
break;
}
}),
take(2),
count(),
finalize(() => {
proxy?.server.close();
}),
)
.toPromise();
expect(buildCount).toBe(2);
});
},
);
},
); | {
"end_byte": 12248,
"start_byte": 6080,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-budgets_spec.ts_0_1208 | /**
* @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 { Type as BudgetType } from '../../../..';
import { executeDevServer } from '../../index';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xdescribe : describe)('Behavior: "browser builder budgets"', () => {
beforeEach(() => {
setupTarget(harness, {
// Add a budget error for any file over 100 bytes
budgets: [{ type: BudgetType.All, maximumError: '100b' }],
optimization: true,
});
});
it('should ignore budgets defined in the "buildTarget" options', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
});
});
},
);
| {
"end_byte": 1208,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-budgets_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build_translation_watch_spec.ts_0_3446 | /**
* @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
*/
/* eslint-disable max-len */
import { concatMap, count, take, timeout } from 'rxjs';
import { URL } from 'url';
import { executeDevServer } from '../../index';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xdescribe : describe)('Behavior: "i18n translation file watching"', () => {
beforeEach(() => {
harness.useProject('test', {
root: '.',
sourceRoot: 'src',
cli: {
cache: {
enabled: false,
},
},
i18n: {
locales: {
'fr': 'src/locales/messages.fr.xlf',
},
},
});
setupTarget(harness, { localize: ['fr'] });
});
it('watches i18n translation files by default', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: true,
});
await harness.writeFile(
'src/app/app.component.html',
`
<p id="hello" i18n="An introduction header for this sample">Hello {{ title }}! </p>
`,
);
await harness.writeFile('src/locales/messages.fr.xlf', TRANSLATION_FILE_CONTENT);
const buildCount = await harness
.execute()
.pipe(
timeout(BUILD_TIMEOUT),
concatMap(async ({ result }, index) => {
expect(result?.success).toBe(true);
const mainUrl = new URL('main.js', `${result?.baseUrl}`);
switch (index) {
case 0: {
const response = await fetch(mainUrl);
expect(await response?.text()).toContain('Bonjour');
await harness.modifyFile('src/locales/messages.fr.xlf', (content) =>
content.replace('Bonjour', 'Salut'),
);
break;
}
case 1: {
const response = await fetch(mainUrl);
expect(await response?.text()).toContain('Salut');
break;
}
}
}),
take(2),
count(),
)
.toPromise();
expect(buildCount).toBe(2);
});
});
},
);
const TRANSLATION_FILE_CONTENT = `
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file target-language="en-US" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="4286451273117902052" datatype="html">
<target>Bonjour <x id="INTERPOLATION" equiv-text="{{ title }}"/>! </target>
<context-group purpose="location">
<context context-type="targetfile">src/app/app.component.html</context>
<context context-type="linenumber">2,3</context>
</context-group>
<note priority="1" from="description">An introduction header for this sample</note>
</trans-unit>
</body>
</file>
</xliff>
`;
| {
"end_byte": 3446,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build_translation_watch_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-base-href_spec.ts_0_1677 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
describe('Behavior: "buildTarget baseHref"', () => {
beforeEach(async () => {
setupTarget(harness, {
baseHref: '/test/',
});
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', 'console.log("foo");');
});
it('uses the baseHref defined in the "buildTarget" options as the serve path', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/test/main.js');
expect(result?.success).toBeTrue();
const baseUrl = new URL(`${result?.baseUrl}/`);
expect(baseUrl.pathname).toBe('/test/');
expect(await response?.text()).toContain('console.log');
});
it('serves the application from baseHref location without trailing slash', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('<script src="main.js" type="module">');
});
});
});
| {
"end_byte": 1677,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-base-href_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-inline-critical-css_spec.ts_0_1401 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
describe('Behavior: "browser builder inline critical css"', () => {
beforeEach(async () => {
setupTarget(harness, {
optimization: {
styles: {
minify: true,
inlineCritical: true,
},
},
styles: ['src/styles.css'],
});
await harness.writeFiles({
'src/styles.css': 'body { color: #000 }',
});
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});
it('inlines critical css when enabled in the "buildTarget" options', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('body{color:#000}');
});
});
});
| {
"end_byte": 1401,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-inline-critical-css_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/proxy-config_spec.ts_0_8643 | /**
* @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 { createServer } from 'node:http';
import { BuilderHarness } from '../../../../testing';
import { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isVite) => {
describe('option: "proxyConfig"', () => {
beforeEach(async () => {
setupTarget(harness);
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});
it('proxies requests based on the `.json` proxy configuration file provided in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.json': `{ "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('proxies requests based on the `.json` (with comments) proxy configuration file provided in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.json': `
// JSON file with comments
{ "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }
`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('proxies requests based on the `.js` (CommonJS) proxy configuration file provided in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.js',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.js': `module.exports = { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('proxies requests based on the `.js` (ESM) proxy configuration file provided in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.js',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.js': `export default { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`,
'package.json': '{ "type": "module" }',
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('proxies requests based on the `.cjs` proxy configuration file provided in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.cjs',
});
const proxyServer = await createProxyServer();
try {
const proxyAddress = proxyServer.address;
await harness.writeFiles({
'proxy.config.cjs': `module.exports = { "/api/*": { "target": "http://127.0.0.1:${proxyAddress.port}" } }`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('proxies requests based on the `.mjs` proxy configuration file provided in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.mjs',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.mjs': `export default { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('supports the Webpack array form of the configuration file', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.json': `[ { "context": ["/api", "/abc"], "target": "http://127.0.0.1:${proxyServer.address.port}" } ]`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('throws an error when proxy configuration file cannot be found', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'INVALID.json',
});
const { result, error } = await harness.executeOnce({ outputLogsOnException: false });
expect(result).toBeUndefined();
expect(error).toEqual(
jasmine.objectContaining({
message: jasmine.stringMatching('INVALID\\.json does not exist'),
}),
);
});
it('throws an error when JSON proxy configuration file cannot be parsed', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
// Create a JSON file with a parse error (target property has no value)
await harness.writeFiles({
'proxy.config.json': `
// JSON file with comments
{ "/api/*": { "target": } }
`,
});
const { result, error } = await harness.executeOnce({ outputLogsOnException: false });
expect(result).toBeUndefined();
expect(error).toEqual(
jasmine.objectContaining({
message: jasmine.stringMatching('contains parse errors:\\n\\[3, 35\\] ValueExpected'),
}),
);
});
it('supports negation of globs', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.json': `
{ "!something/**/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }
`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
/**
* ****************************************************************************************************
* ********************************** Below only Vite specific tests **********************************
* ****************************************************************************************************
*/
if (isVite) {
viteOnlyTests(harness);
}
});
});
/**
* Creates an HTTP Server used for proxy testing that provides a `/test` endpoint
* that returns a 200 response with a body of `TEST_API_RETURN`. All other requests
* will return a 404 response.
*/ | {
"end_byte": 8643,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/proxy-config_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/proxy-config_spec.ts_8644_10620 | async function createProxyServer() {
const proxyServer = createServer((request, response) => {
if (request.url?.endsWith('/test')) {
response.writeHead(200);
response.end('TEST_API_RETURN');
} else {
response.writeHead(404);
response.end();
}
});
await new Promise<void>((resolve) => proxyServer.listen(0, '127.0.0.1', resolve));
return {
address: proxyServer.address() as import('net').AddressInfo,
close: () => new Promise<void>((resolve) => proxyServer.close(() => resolve())),
};
}
/**
* Vite specific tests
*/
function viteOnlyTests(harness: BuilderHarness<unknown>): void {
it('proxies support regexp as context', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.json': `
{ "^/api/.*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }
`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
it('proxies support negated regexp as context', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
proxyConfig: 'proxy.config.json',
});
const proxyServer = await createProxyServer();
try {
await harness.writeFiles({
'proxy.config.json': `
{ "^\\/(?!something).*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }
`,
});
const { result, response } = await executeOnceAndFetch(harness, '/api/test');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await proxyServer.close();
}
});
} | {
"end_byte": 10620,
"start_byte": 8644,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/proxy-config_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/port_spec.ts_0_3338 | /**
* @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 { URL } from 'url';
import { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
function getResultPort(result: Record<string, unknown> | undefined): string | undefined {
if (typeof result?.baseUrl !== 'string') {
fail(`Expected builder result with a string 'baseUrl' property. Received: ${result?.baseUrl}`);
return;
}
try {
return new URL(result.baseUrl).port;
} catch {
fail(`Expected a valid URL in builder result 'baseUrl' property. Received: ${result.baseUrl}`);
}
}
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
describe('option: "port"', () => {
beforeEach(async () => {
setupTarget(harness);
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});
it('uses default port (4200) when not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
// Base options set port to zero
port: undefined,
});
const { result, response, logs } = await executeOnceAndFetch(harness, '/');
expect(result?.success).toBeTrue();
expect(getResultPort(result)).toBe('4200');
expect(await response?.text()).toContain('<title>');
if (!isViteRun) {
expect(logs).toContain(
jasmine.objectContaining({
message: jasmine.stringMatching(/:4200/),
}),
);
}
});
it('uses a random free port when set to 0 (zero)', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
port: 0,
});
const { result, response, logs } = await executeOnceAndFetch(harness, '/');
expect(result?.success).toBeTrue();
const port = getResultPort(result);
expect(port).not.toBe('4200');
if (isViteRun) {
// Should not be default Vite port either
expect(port).not.toBe('5173');
}
expect(port).toMatch(/\d{4,6}/);
expect(await response?.text()).toContain('<title>');
if (!isViteRun) {
expect(logs).toContain(
jasmine.objectContaining({
message: jasmine.stringMatching(':' + port),
}),
);
}
});
it('uses specific port when a non-zero number is specified', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
port: 8000,
});
const { result, response, logs } = await executeOnceAndFetch(harness, '/');
expect(result?.success).toBeTrue();
expect(getResultPort(result)).toBe('8000');
expect(await response?.text()).toContain('<title>');
if (!isViteRun) {
expect(logs).toContain(
jasmine.objectContaining({
message: jasmine.stringMatching(':8000'),
}),
);
}
});
});
},
);
| {
"end_byte": 3338,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/port_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/prebundle_spec.ts_0_3413 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
// TODO: Temporarily disabled pending investigation into test-only Vite not stopping when caching is enabled
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// prebundling is not available in webpack
(isViteRun ? xdescribe : xdescribe)('option: "prebundle"', () => {
beforeEach(async () => {
setupTarget(harness);
harness.useProject('test', {
cli: {
cache: {
enabled: true,
},
},
});
// Application code is not needed for these tests
await harness.writeFile(
'src/main.ts',
`
import { VERSION as coreVersion } from '@angular/core';
import { VERSION as platformVersion } from '@angular/platform-browser';
console.log(coreVersion);
console.log(platformVersion);
`,
);
});
it('should prebundle dependencies when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, content } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(content).toContain('vite/deps/@angular_core.js');
expect(content).not.toContain('node_modules/@angular/core/');
});
it('should prebundle dependencies when option is set to true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
prebundle: true,
});
const { result, content } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(content).toContain('vite/deps/@angular_core.js');
expect(content).not.toContain('node_modules/@angular/core/');
});
it('should not prebundle dependencies when option is set to false', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
prebundle: false,
});
const { result, content } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(content).not.toContain('vite/deps/@angular_core.js');
expect(content).toContain('node_modules/@angular/core/');
});
it('should not prebundle specified dependency if added to exclude list', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
prebundle: { exclude: ['@angular/platform-browser'] },
});
const { result, content } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(content).toContain('vite/deps/@angular_core.js');
expect(content).not.toContain('node_modules/@angular/core/');
expect(content).not.toContain('vite/deps/@angular_platform-browser.js');
expect(content).toContain('node_modules/@angular/platform-browser/');
});
});
},
);
| {
"end_byte": 3413,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/prebundle_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/force-esbuild_spec.ts_0_2668 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
const ESBUILD_LOG_TEXT = 'Application bundle generation complete.';
const WEBPACK_LOG_TEXT = 'Compiled successfully.';
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
describe('option: "forceEsbuild"', () => {
beforeEach(async () => {
setupTarget(harness, {});
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', 'console.log("foo");');
});
it('should use build target specified build system when not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
forceEsbuild: undefined,
});
const { result, response, logs } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('console.log');
expect(logs).toContain(
jasmine.objectContaining({
message: jasmine.stringMatching(isViteRun ? ESBUILD_LOG_TEXT : WEBPACK_LOG_TEXT),
}),
);
});
it('should use build target specified build system when false', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
forceEsbuild: false,
});
const { result, response, logs } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('console.log');
expect(logs).toContain(
jasmine.objectContaining({
message: jasmine.stringMatching(isViteRun ? ESBUILD_LOG_TEXT : WEBPACK_LOG_TEXT),
}),
);
});
it('should always use the esbuild build system with Vite when true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
forceEsbuild: true,
});
const { result, response, logs } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('console.log');
expect(logs).toContain(
jasmine.objectContaining({ message: jasmine.stringMatching(ESBUILD_LOG_TEXT) }),
);
});
});
},
);
| {
"end_byte": 2668,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/force-esbuild_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/watch_spec.ts_0_3212 | /**
* @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 { TimeoutError, concatMap, count, take, timeout } from 'rxjs';
import { executeDevServer } from '../../index';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
describe('Option: "watch"', () => {
beforeEach(() => {
setupTarget(harness);
});
it('does not wait for file changes when false', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: false,
});
await harness
.execute()
.pipe(
timeout(BUILD_TIMEOUT),
concatMap(async ({ result }, index) => {
expect(result?.success).toBe(true);
switch (index) {
case 0:
await harness.modifyFile(
'src/main.ts',
(content) => content + 'console.log("abcd1234");',
);
break;
case 1:
fail('Expected files to not be watched.');
break;
}
}),
take(2),
)
.toPromise()
.catch((error) => {
// Timeout is expected if watching is disabled
if (error instanceof TimeoutError) {
return;
}
throw error;
});
});
it('watches for file changes when not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: undefined,
});
const buildCount = await harness
.execute()
.pipe(
timeout(BUILD_TIMEOUT),
concatMap(async ({ result }, index) => {
expect(result?.success).toBe(true);
switch (index) {
case 0:
await harness.modifyFile(
'src/main.ts',
(content) => content + 'console.log("abcd1234");',
);
break;
case 1:
break;
}
}),
take(2),
count(),
)
.toPromise();
expect(buildCount).toBe(2);
});
it('watches for file changes when true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
watch: true,
});
const buildCount = await harness
.execute()
.pipe(
timeout(BUILD_TIMEOUT),
concatMap(async ({ result }, index) => {
expect(result?.success).toBe(true);
switch (index) {
case 0:
await harness.modifyFile(
'src/main.ts',
(content) => content + 'console.log("abcd1234");',
);
break;
case 1:
break;
}
}),
take(2),
count(),
)
.toPromise();
expect(buildCount).toBe(2);
});
});
});
| {
"end_byte": 3212,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/watch_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/public-host_spec.ts_0_2254 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
const FETCH_HEADERS = Object.freeze({ host: 'example.com' });
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// This option is not used when using vite.
(isViteRun ? xdescribe : xdescribe)('option: "publicHost"', () => {
beforeEach(async () => {
setupTarget(harness);
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});
it('does not allow an invalid host when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
});
it('does not allow an invalid host when option is a different host', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
publicHost: 'example.net',
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
});
it('allows a host when option is set to used host', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
publicHost: 'example.com',
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('<title>');
});
});
},
);
| {
"end_byte": 2254,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/public-host_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/verbose_spec.ts_0_1815 | /**
* @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 { executeDevServer } from '../../index';
import {
BASE_OPTIONS,
DEV_SERVER_BUILDER_INFO,
describeBuilder,
setupBrowserTarget,
} from '../setup';
const VERBOSE_LOG_TEXT = /\[emitted\] \(name: main\)/;
describeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness) => {
describe('Option: "verbose"', () => {
beforeEach(() => {
setupBrowserTarget(harness);
});
it('shows verbose logs in console when true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
verbose: true,
});
const { result, logs } = await harness.executeOnce();
expect(result?.success).toBe(true);
expect(logs).toContain(
jasmine.objectContaining({ message: jasmine.stringMatching(VERBOSE_LOG_TEXT) }),
);
});
it('does not show verbose logs in console when false', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
verbose: false,
});
const { result, logs } = await harness.executeOnce();
expect(result?.success).toBe(true);
expect(logs).not.toContain(
jasmine.objectContaining({ message: jasmine.stringMatching(VERBOSE_LOG_TEXT) }),
);
});
it('does not show verbose logs in console when not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, logs } = await harness.executeOnce();
expect(result?.success).toBe(true);
expect(logs).not.toContain(
jasmine.objectContaining({ message: jasmine.stringMatching(VERBOSE_LOG_TEXT) }),
);
});
});
});
| {
"end_byte": 1815,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/verbose_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/allowed-hosts_spec.ts_0_2255 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
const FETCH_HEADERS = Object.freeze({ host: 'example.com' });
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xdescribe : xdescribe)('option: "allowedHosts"', () => {
beforeEach(async () => {
setupTarget(harness);
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});
it('does not allow an invalid host when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
});
it('does not allow an invalid host when option is an empty array', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: [],
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
});
it('allows a host when specified in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: ['example.com'],
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('<title>');
});
});
},
);
| {
"end_byte": 2255,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/allowed-hosts_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/disable-host-check_spec.ts_0_2232 | /**
* @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 { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
const FETCH_HEADERS = Object.freeze({ host: 'example.com' });
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
// This option is not used when using vite.
(isViteRun ? xdescribe : xdescribe)('option: "disableHostCheck"', () => {
beforeEach(async () => {
setupTarget(harness);
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});
it('does not allow an invalid host when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
});
it('does not allow an invalid host when option is false', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
disableHostCheck: false,
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toBe('Invalid Host header');
});
it('allows a host when option is true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
disableHostCheck: true,
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
request: { headers: FETCH_HEADERS },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('<title>');
});
});
},
);
| {
"end_byte": 2232,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/disable-host-check_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/serve-path_spec.ts_0_4053 | /**
* @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 { URL } from 'url';
import { executeDevServer } from '../../index';
import { executeOnceAndFetch } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
describeServeBuilder(
executeDevServer,
DEV_SERVER_BUILDER_INFO,
(harness, setupTarget, isViteRun) => {
describe('option: "servePath"', () => {
beforeEach(async () => {
setupTarget(harness, {
assets: ['src/assets'],
});
// Application code is not needed for these tests
await harness.writeFile('src/main.ts', 'console.log("foo");');
});
it('serves application at the root when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});
const { result, response } = await executeOnceAndFetch(harness, '/main.js');
expect(result?.success).toBeTrue();
const baseUrl = new URL(`${result?.baseUrl}`);
expect(baseUrl.pathname).toBe('/');
expect(await response?.text()).toContain('console.log');
});
it('serves application at specified path when option is used', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
servePath: 'test',
});
const { result, response } = await executeOnceAndFetch(harness, '/test/main.js');
expect(result?.success).toBeTrue();
const baseUrl = new URL(`${result?.baseUrl}/`);
expect(baseUrl.pathname).toBe('/test/');
expect(await response?.text()).toContain('console.log');
});
// TODO(fix-vite): currently this is broken in vite.
(isViteRun ? xit : it)('does not rewrite from root when option is used', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
servePath: 'test',
});
const { result, response } = await executeOnceAndFetch(harness, '/', {
// fallback processing requires an accept header
request: { headers: { accept: 'text/html' } },
});
expect(result?.success).toBeTrue();
expect(response?.status).toBe(404);
});
it('does not rewrite from path outside serve path when option is used', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
servePath: 'test',
});
const { result, response } = await executeOnceAndFetch(harness, '/api/', {
// fallback processing requires an accept header
request: { headers: { accept: 'text/html' } },
});
expect(result?.success).toBeTrue();
expect(response?.status).toBe(404);
});
it('rewrites from path inside serve path when option is used', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
servePath: 'test',
});
const { result, response } = await executeOnceAndFetch(harness, '/test/inside', {
// fallback processing requires an accept header
request: { headers: { accept: 'text/html' } },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('<title>');
});
it('serves assets at specified path when option is used', async () => {
await harness.writeFile('src/assets/test.txt', 'hello world!');
harness.useTarget('serve', {
...BASE_OPTIONS,
servePath: 'test',
});
const { result, response } = await executeOnceAndFetch(harness, '/test/assets/test.txt', {
// fallback processing requires an accept header
request: { headers: { accept: 'text/html' } },
});
expect(result?.success).toBeTrue();
expect(await response?.text()).toContain('hello world');
});
});
},
);
| {
"end_byte": 4053,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/dev-server/tests/options/serve-path_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/utils.ts_0_2299 | /**
* @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 { SpawnOptions, spawn } from 'child_process';
import { AddressInfo, createConnection, createServer } from 'net';
import { Observable, mergeMap, retryWhen, throwError, timer } from 'rxjs';
import treeKill from 'tree-kill';
export function getAvailablePort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = createServer();
server
.unref()
.on('error', reject)
.listen(0, () => {
const { port } = server.address() as AddressInfo;
server.close(() => resolve(port));
});
});
}
export function spawnAsObservable(
command: string,
args: string[] = [],
options: SpawnOptions = {},
): Observable<{ stdout?: string; stderr?: string }> {
return new Observable((obs) => {
const proc = spawn(command, args, options);
if (proc.stdout) {
proc.stdout.on('data', (data) => obs.next({ stdout: data.toString() }));
}
if (proc.stderr) {
proc.stderr.on('data', (data) => obs.next({ stderr: data.toString() }));
}
proc
.on('error', (err) => obs.error(err))
.on('close', (code) => {
if (code !== 0) {
obs.error(new Error(`${command} exited with ${code} code.`));
}
obs.complete();
});
return () => {
if (!proc.killed && proc.pid) {
treeKill(proc.pid, 'SIGTERM');
}
};
});
}
export function waitUntilServerIsListening(port: number, host?: string): Observable<undefined> {
const allowedErrorCodes = ['ECONNREFUSED', 'ECONNRESET'];
return new Observable<undefined>((obs) => {
const client = createConnection({ host, port }, () => {
obs.next(undefined);
obs.complete();
}).on('error', (err) => obs.error(err));
return () => {
if (!client.destroyed) {
client.destroy();
}
};
}).pipe(
retryWhen((err) =>
err.pipe(
mergeMap((error, attempts) => {
return attempts > 10 || !allowedErrorCodes.includes(error.code)
? throwError(error)
: timer(100 * (attempts * 1));
}),
),
),
);
}
| {
"end_byte": 2299,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/utils.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/index.ts_0_7101 | /**
* @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 { loadProxyConfiguration } from '@angular/build/private';
import {
BuilderContext,
BuilderOutput,
createBuilder,
targetFromTargetString,
} from '@angular-devkit/architect';
import { json, logging, tags } from '@angular-devkit/core';
import type {
BrowserSyncInstance,
Options as BrowserSyncOptions,
HttpsOptions,
MiddlewareHandler,
ProxyOptions,
} from 'browser-sync';
import { join, resolve as pathResolve } from 'path';
import {
EMPTY,
Observable,
catchError,
combineLatest,
concatMap,
debounce,
debounceTime,
delay,
finalize,
from,
ignoreElements,
map,
of,
startWith,
switchMap,
tap,
zip,
} from 'rxjs';
import * as url from 'url';
import { Schema } from './schema';
import { getAvailablePort, spawnAsObservable, waitUntilServerIsListening } from './utils';
/** Log messages to ignore and not rely to the logger */
const IGNORED_STDOUT_MESSAGES = [
'server listening on',
'Angular is running in development mode. Call enableProdMode() to enable production mode.',
];
export type SSRDevServerBuilderOptions = Schema & json.JsonObject;
export type SSRDevServerBuilderOutput = BuilderOutput & {
baseUrl?: string;
port?: string;
};
export function execute(
options: SSRDevServerBuilderOptions,
context: BuilderContext,
): Observable<SSRDevServerBuilderOutput> {
const browserTarget = targetFromTargetString(options.browserTarget);
const serverTarget = targetFromTargetString(options.serverTarget);
const getBaseUrl = (bs: BrowserSyncInstance) =>
`${bs.getOption('scheme')}://${bs.getOption('host')}:${bs.getOption('port')}`;
const browserTargetRun = context.scheduleTarget(browserTarget, {
watch: options.watch,
progress: options.progress,
verbose: options.verbose,
// Disable bundle budgets are these are not meant to be used with a dev-server as this will add extra JavaScript for live-reloading.
budgets: [],
} as json.JsonObject);
const serverTargetRun = context.scheduleTarget(serverTarget, {
watch: options.watch,
progress: options.progress,
verbose: options.verbose,
} as json.JsonObject);
let browserSync: typeof import('browser-sync');
try {
browserSync = require('browser-sync');
} catch {
return of({
success: false,
error:
'"browser-sync" is not installed, most likely you need to run `npm install browser-sync --save-dev` in your project.',
});
}
const bsInstance = browserSync.create();
context.logger.error(tags.stripIndents`
****************************************************************************************
This is a simple server for use in testing or debugging Angular applications locally.
It hasn't been reviewed for security issues.
DON'T USE IT FOR PRODUCTION!
****************************************************************************************
`);
return zip(browserTargetRun, serverTargetRun, getAvailablePort()).pipe(
switchMap(([br, sr, nodeServerPort]) => {
return combineLatest([br.output, sr.output]).pipe(
// This is needed so that if both server and browser emit close to each other
// we only emit once. This typically happens on the first build.
debounceTime(120),
switchMap(([b, s]) => {
if (!s.success || !b.success) {
return of([b, s]);
}
return startNodeServer(s, nodeServerPort, context.logger, !!options.inspect).pipe(
map(() => [b, s]),
catchError((err) => {
context.logger.error(`A server error has occurred.\n${mapErrorToMessage(err)}`);
return EMPTY;
}),
);
}),
map(
([b, s]) =>
[
{
success: b.success && s.success,
error: b.error || s.error,
},
nodeServerPort,
] as [SSRDevServerBuilderOutput, number],
),
tap(([builderOutput]) => {
if (builderOutput.success) {
context.logger.info('\nCompiled successfully.');
}
}),
debounce(([builderOutput]) =>
builderOutput.success && !options.inspect
? waitUntilServerIsListening(nodeServerPort)
: EMPTY,
),
finalize(() => {
void br.stop();
void sr.stop();
}),
);
}),
concatMap(([builderOutput, nodeServerPort]) => {
if (!builderOutput.success) {
return of(builderOutput);
}
if (bsInstance.active) {
bsInstance.reload();
return of(builderOutput);
} else {
return from(initBrowserSync(bsInstance, nodeServerPort, options, context)).pipe(
tap((bs) => {
const baseUrl = getBaseUrl(bs);
context.logger.info(tags.oneLine`
**
Angular Universal Live Development Server is listening on ${baseUrl},
open your browser on ${baseUrl}
**
`);
}),
map(() => builderOutput),
);
}
}),
map(
(builderOutput) =>
({
success: builderOutput.success,
error: builderOutput.error,
baseUrl: getBaseUrl(bsInstance),
port: bsInstance.getOption('port'),
}) as SSRDevServerBuilderOutput,
),
finalize(() => {
if (bsInstance) {
bsInstance.exit();
bsInstance.cleanup();
}
}),
catchError((error) =>
of({
success: false,
error: mapErrorToMessage(error),
}),
),
);
}
// Logs output to the terminal.
// Removes any trailing new lines from the output.
export function log(
{ stderr, stdout }: { stderr: string | undefined; stdout: string | undefined },
logger: logging.LoggerApi,
) {
if (stderr) {
// Strip the webpack scheme (webpack://) from error log.
logger.error(stderr.replace(/\n?$/, '').replace(/webpack:\/\//g, '.'));
}
if (stdout && !IGNORED_STDOUT_MESSAGES.some((x) => stdout.includes(x))) {
logger.info(stdout.replace(/\n?$/, ''));
}
}
function startNodeServer(
serverOutput: BuilderOutput,
port: number,
logger: logging.LoggerApi,
inspectMode = false,
): Observable<void> {
const outputPath = serverOutput.outputPath as string;
const path = join(outputPath, 'main.js');
const env = { ...process.env, PORT: '' + port };
const args = ['--enable-source-maps', `"${path}"`];
if (inspectMode) {
args.unshift('--inspect-brk');
}
return of(null).pipe(
delay(0), // Avoid EADDRINUSE error since it will cause the kill event to be finish.
switchMap(() => spawnAsObservable('node', args, { env, shell: true })),
tap((res) => log({ stderr: res.stderr, stdout: res.stdout }, logger)),
ignoreElements(),
// Emit a signal after the process has been started
startWith(undefined),
);
} | {
"end_byte": 7101,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/index.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/index.ts_7103_11618 | async function initBrowserSync(
browserSyncInstance: BrowserSyncInstance,
nodeServerPort: number,
options: SSRDevServerBuilderOptions,
context: BuilderContext,
): Promise<BrowserSyncInstance> {
if (browserSyncInstance.active) {
return browserSyncInstance;
}
const { port: browserSyncPort, open, host, publicHost, proxyConfig } = options;
const bsPort = browserSyncPort || (await getAvailablePort());
const bsOptions: BrowserSyncOptions = {
proxy: {
target: `localhost:${nodeServerPort}`,
proxyOptions: {
xfwd: true,
},
proxyRes: [
(proxyRes) => {
if ('headers' in proxyRes) {
proxyRes.headers['cache-control'] = undefined;
}
},
],
// proxyOptions is not in the typings
} as ProxyOptions & { proxyOptions: { xfwd: boolean } },
host,
port: bsPort,
ui: false,
server: false,
notify: false,
ghostMode: false,
logLevel: options.verbose ? 'debug' : 'silent',
open,
https: getSslConfig(context.workspaceRoot, options),
};
const publicHostNormalized =
publicHost && publicHost.endsWith('/')
? publicHost.substring(0, publicHost.length - 1)
: publicHost;
if (publicHostNormalized) {
const { protocol, hostname, port, pathname } = url.parse(publicHostNormalized);
const defaultSocketIoPath = '/browser-sync/socket.io';
const defaultNamespace = '/browser-sync';
const hasPathname = !!(pathname && pathname !== '/');
const namespace = hasPathname ? pathname + defaultNamespace : defaultNamespace;
const path = hasPathname ? pathname + defaultSocketIoPath : defaultSocketIoPath;
bsOptions.socket = {
namespace,
path,
domain: url.format({
protocol,
hostname,
port,
}),
};
// When having a pathname we also need to create a reverse proxy because socket.io
// will be listening on: 'http://localhost:4200/ssr/browser-sync/socket.io'
// However users will typically have a reverse proxy that will redirect all matching requests
// ex: http://testinghost.com/ssr -> http://localhost:4200 which will result in a 404.
if (hasPathname) {
const { createProxyMiddleware } = await import('http-proxy-middleware');
// Remove leading slash
bsOptions.scriptPath = (p) => p.substring(1);
bsOptions.middleware = [
createProxyMiddleware({
pathFilter: defaultSocketIoPath,
target: url.format({
protocol: 'http',
hostname: host,
port: bsPort,
pathname: path,
}),
ws: true,
logger: {
info: () => {},
warn: () => {},
error: () => {},
},
}),
];
}
}
if (proxyConfig) {
if (!bsOptions.middleware) {
bsOptions.middleware = [];
} else if (!Array.isArray(bsOptions.middleware)) {
bsOptions.middleware = [bsOptions.middleware];
}
bsOptions.middleware = [
...bsOptions.middleware,
...(await getProxyConfig(context.workspaceRoot, proxyConfig)),
];
}
return new Promise((resolve, reject) => {
browserSyncInstance.init(bsOptions, (error, bs) => {
if (error) {
reject(error);
} else {
resolve(bs);
}
});
});
}
function mapErrorToMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
return '';
}
function getSslConfig(
root: string,
options: SSRDevServerBuilderOptions,
): HttpsOptions | undefined | boolean {
const { ssl, sslCert, sslKey } = options;
if (ssl && sslCert && sslKey) {
return {
key: pathResolve(root, sslKey),
cert: pathResolve(root, sslCert),
};
}
return ssl;
}
async function getProxyConfig(root: string, proxyConfig: string): Promise<MiddlewareHandler[]> {
const proxy = await loadProxyConfiguration(root, proxyConfig);
if (!proxy) {
return [];
}
const { createProxyMiddleware } = await import('http-proxy-middleware');
return Object.entries(proxy).map(([key, context]) => {
const filterRegExp = new RegExp(key);
return createProxyMiddleware({
pathFilter: (pathname) => filterRegExp.test(pathname),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(context as any),
});
});
}
export default createBuilder<SSRDevServerBuilderOptions, BuilderOutput>(execute); | {
"end_byte": 11618,
"start_byte": 7103,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/index.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/specs/ssl_spec.ts_0_3073 | /**
* @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 { Architect } from '@angular-devkit/architect';
// eslint-disable-next-line import/no-extraneous-dependencies
import * as browserSync from 'browser-sync';
import { Agent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
import { createArchitect, host } from '../../../testing/test-utils';
import { SSRDevServerBuilderOutput } from '../index';
describe('Serve SSR Builder', () => {
const target = { project: 'app', target: 'serve-ssr' };
let architect: Architect;
beforeEach(async () => {
await host.initialize().toPromise();
architect = (await createArchitect(host.root())).architect;
host.writeMultipleFiles({
'src/main.server.ts': `
import 'zone.js/node';
import { CommonEngine } from '@angular/ssr/node';
import * as express from 'express';
import { resolve, join } from 'node:path';
import { AppServerModule } from './app/app.module.server';
export function app(): express.Express {
const server = express();
const distFolder = resolve(__dirname, '../dist');
const indexHtml = join(distFolder, 'index.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', distFolder);
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
server.get('*', (req, res, next) => {
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: req.originalUrl,
publicPath: distFolder,
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
app().listen(process.env['PORT']);
export * from './app/app.module.server';
`,
});
});
afterEach(async () => {
browserSync.reset();
await host.restore().toPromise();
});
it('works with SSL', async () => {
const run = await architect.scheduleTarget(target, { ssl: true, port: 0 });
const output = (await run.result) as SSRDevServerBuilderOutput;
expect(output.success).toBe(true);
expect(output.baseUrl).toBe(`https://localhost:${output.port}`);
// The self-signed certificate used by the dev server will cause fetch to fail
// unless reject unauthorized is disabled.
const originalDispatcher = getGlobalDispatcher();
setGlobalDispatcher(
new Agent({
connect: { rejectUnauthorized: false },
}),
);
try {
const response = await fetch(`https://localhost:${output.port}/index.html`);
expect(await response.text()).toContain('<title>HelloWorldApp</title>');
} finally {
setGlobalDispatcher(originalDispatcher);
}
await run.stop();
});
});
| {
"end_byte": 3073,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/specs/ssl_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/specs/proxy_spec.ts_0_3479 | /**
* @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 { Architect } from '@angular-devkit/architect';
// eslint-disable-next-line import/no-extraneous-dependencies
import * as browserSync from 'browser-sync';
import * as http from 'http';
import { createArchitect, host } from '../../../testing/test-utils';
import { SSRDevServerBuilderOutput } from '../index';
describe('Serve SSR Builder', () => {
const target = { project: 'app', target: 'serve-ssr' };
let architect: Architect;
beforeEach(async () => {
await host.initialize().toPromise();
architect = (await createArchitect(host.root())).architect;
host.writeMultipleFiles({
'src/main.server.ts': `
import 'zone.js/node';
import { CommonEngine } from '@angular/ssr/node';
import * as express from 'express';
import { resolve, join } from 'node:path';
import { AppServerModule } from './app/app.module.server';
export function app(): express.Express {
const server = express();
const distFolder = resolve(__dirname, '../dist');
const indexHtml = join(distFolder, 'index.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', distFolder);
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
server.get('*', (req, res, next) => {
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: req.originalUrl,
publicPath: distFolder,
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
app().listen(process.env['PORT']);
export * from './app/app.module.server';
`,
});
});
afterEach(async () => {
browserSync.reset();
await host.restore().toPromise();
});
it('proxies requests based on the proxy configuration file provided in the option', async () => {
const proxyServer = http.createServer((request, response) => {
if (request.url?.endsWith('/test')) {
response.writeHead(200);
response.end('TEST_API_RETURN');
} else {
response.writeHead(404);
response.end();
}
});
try {
await new Promise<void>((resolve) => proxyServer.listen(0, '127.0.0.1', resolve));
const proxyAddress = proxyServer.address() as import('net').AddressInfo;
host.writeMultipleFiles({
'proxy.config.json': `{ "/api/*": { "logLevel": "debug","target": "http://127.0.0.1:${proxyAddress.port}" } }`,
});
const run = await architect.scheduleTarget(target, {
port: 0,
proxyConfig: 'proxy.config.json',
});
const output = (await run.result) as SSRDevServerBuilderOutput;
expect(output.success).toBe(true);
expect(output.baseUrl).toBe(`http://localhost:${output.port}`);
const response = await fetch(`http://localhost:${output.port}/api/test`);
await run.stop();
expect(await response?.text()).toContain('TEST_API_RETURN');
} finally {
await new Promise<void>((resolve) => proxyServer.close(() => resolve()));
}
});
});
| {
"end_byte": 3479,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/specs/proxy_spec.ts"
} |
angular-cli/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/specs/works_spec.ts_0_2714 | /**
* @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 { Architect } from '@angular-devkit/architect';
// eslint-disable-next-line import/no-extraneous-dependencies
import * as browserSync from 'browser-sync';
import { createArchitect, host } from '../../../testing/test-utils';
import { SSRDevServerBuilderOutput } from '../index';
describe('Serve SSR Builder', () => {
const target = { project: 'app', target: 'serve-ssr' };
let architect: Architect;
beforeEach(async () => {
await host.initialize().toPromise();
architect = (await createArchitect(host.root())).architect;
host.writeMultipleFiles({
'src/main.server.ts': `
import 'zone.js/node';
import { CommonEngine } from '@angular/ssr/node';
import * as express from 'express';
import { resolve, join } from 'node:path';
import { AppServerModule } from './app/app.module.server';
export function app(): express.Express {
const server = express();
const distFolder = resolve(__dirname, '../dist');
const indexHtml = join(distFolder, 'index.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', distFolder);
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
server.get('*', (req, res, next) => {
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: req.originalUrl,
publicPath: distFolder,
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
app().listen(process.env['PORT']);
export * from './app/app.module.server';
`,
});
});
afterEach(async () => {
browserSync.reset();
await host.restore().toPromise();
});
it('works', async () => {
const run = await architect.scheduleTarget(target);
const output = await run.result;
expect(output.success).toBe(true);
const response = await fetch(`http://localhost:${output.port}/`);
await run.stop();
expect(await response.text()).toContain('<title>HelloWorldApp</title>');
});
it('works with port 0', async () => {
const run = await architect.scheduleTarget(target, { port: 0 });
const output = (await run.result) as SSRDevServerBuilderOutput;
await run.stop();
expect(output.success).toBe(true);
expect(output.baseUrl).not.toContain('4200');
});
});
| {
"end_byte": 2714,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ssr-dev-server/specs/works_spec.ts"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.