_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/browser_builder.ts_0_6383
/** * @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 { purgeStaleBuildCache } from '@angular/build/private'; import { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import type { Config, ConfigOptions } from 'karma'; import * as path from 'path'; import { Observable, defaultIfEmpty, from, switchMap } from 'rxjs'; import { Configuration } from 'webpack'; import { getCommonConfig, getStylesConfig } from '../../tools/webpack/configs'; import { ExecutionTransformer } from '../../transforms'; import { generateBrowserWebpackConfigFromContext } from '../../utils/webpack-browser-config'; import { Schema as BrowserBuilderOptions, OutputHashing } from '../browser/schema'; import { FindTestsPlugin } from './find-tests-plugin'; import { Schema as KarmaBuilderOptions } from './schema'; export type KarmaConfigOptions = ConfigOptions & { buildWebpack?: unknown; configFile?: string; }; export function execute( options: KarmaBuilderOptions, context: BuilderContext, karmaOptions: KarmaConfigOptions, transforms: { webpackConfiguration?: ExecutionTransformer<Configuration>; // The karma options transform cannot be async without a refactor of the builder implementation karmaOptions?: (options: KarmaConfigOptions) => KarmaConfigOptions; } = {}, ): Observable<BuilderOutput> { return from(initializeBrowser(options, context)).pipe( switchMap(async ([karma, webpackConfig]) => { const projectName = context.target?.project; if (!projectName) { throw new Error(`The 'karma' builder requires a target to be specified.`); } const projectMetadata = await context.getProjectMetadata(projectName); const sourceRoot = (projectMetadata.sourceRoot ?? projectMetadata.root ?? '') as string; if (!options.main) { webpackConfig.entry ??= {}; if (typeof webpackConfig.entry === 'object' && !Array.isArray(webpackConfig.entry)) { if (Array.isArray(webpackConfig.entry['main'])) { webpackConfig.entry['main'].push(getBuiltInMainFile()); } else { webpackConfig.entry['main'] = [getBuiltInMainFile()]; } } } webpackConfig.plugins ??= []; webpackConfig.plugins.push( new FindTestsPlugin({ include: options.include, exclude: options.exclude, workspaceRoot: context.workspaceRoot, projectSourceRoot: path.join(context.workspaceRoot, sourceRoot), }), ); karmaOptions.buildWebpack = { options, webpackConfig, logger: context.logger, }; const parsedKarmaConfig = await karma.config.parseConfig( options.karmaConfig && path.resolve(context.workspaceRoot, options.karmaConfig), transforms.karmaOptions ? transforms.karmaOptions(karmaOptions) : karmaOptions, { promiseConfig: true, throwErrors: true }, ); return [karma, parsedKarmaConfig] as [typeof karma, KarmaConfigOptions]; }), switchMap( ([karma, karmaConfig]) => new Observable<BuilderOutput>((subscriber) => { // Pass onto Karma to emit BuildEvents. karmaConfig.buildWebpack ??= {}; if (typeof karmaConfig.buildWebpack === 'object') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (karmaConfig.buildWebpack as any).failureCb ??= () => subscriber.next({ success: false }); // eslint-disable-next-line @typescript-eslint/no-explicit-any (karmaConfig.buildWebpack as any).successCb ??= () => subscriber.next({ success: true }); } // Complete the observable once the Karma server returns. const karmaServer = new karma.Server(karmaConfig as Config, (exitCode) => { subscriber.next({ success: exitCode === 0 }); subscriber.complete(); }); const karmaStart = karmaServer.start(); // Cleanup, signal Karma to exit. return () => { void karmaStart.then(() => karmaServer.stop()); }; }), ), defaultIfEmpty({ success: false }), ); } async function initializeBrowser( options: KarmaBuilderOptions, context: BuilderContext, webpackConfigurationTransformer?: ExecutionTransformer<Configuration>, ): Promise<[typeof import('karma'), Configuration]> { // Purge old build disk cache. await purgeStaleBuildCache(context); const karma = await import('karma'); const { config } = await generateBrowserWebpackConfigFromContext( // only two properties are missing: // * `outputPath` which is fixed for tests // * `budgets` which might be incorrect due to extra dev libs { ...(options as unknown as BrowserBuilderOptions), outputPath: '', budgets: undefined, optimization: false, buildOptimizer: false, aot: false, vendorChunk: true, namedChunks: true, extractLicenses: false, outputHashing: OutputHashing.None, // The webpack tier owns the watch behavior so we want to force it in the config. // When not in watch mode, webpack-dev-middleware will call `compiler.watch` anyway. // https://github.com/webpack/webpack-dev-middleware/blob/698c9ae5e9bb9a013985add6189ff21c1a1ec185/src/index.js#L65 // https://github.com/webpack/webpack/blob/cde1b73e12eb8a77eb9ba42e7920c9ec5d29c2c9/lib/Compiler.js#L379-L388 watch: true, }, context, (wco) => [getCommonConfig(wco), getStylesConfig(wco)], ); return [karma, (await webpackConfigurationTransformer?.(config)) ?? config]; } function getBuiltInMainFile(): string { const content = Buffer.from( ` import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; // Initialize the Angular testing environment. getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { errorOnUnknownElements: true, errorOnUnknownProperties: true }); `, ).toString('base64'); return `ng-virtual-main.js!=!data:text/javascript;base64,${content}`; }
{ "commit_id": "b893a6ae9", "end_byte": 6383, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/browser_builder.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/find-tests-plugin.ts_0_2163
/** * @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 { pluginName } from 'mini-css-extract-plugin'; import type { Compilation, Compiler } from 'webpack'; import { findTests } from './find-tests'; /** * The name of the plugin provided to Webpack when tapping Webpack compiler hooks. */ const PLUGIN_NAME = 'angular-find-tests-plugin'; export interface FindTestsPluginOptions { include?: string[]; exclude?: string[]; workspaceRoot: string; projectSourceRoot: string; } export class FindTestsPlugin { private compilation: Compilation | undefined; constructor(private options: FindTestsPluginOptions) {} apply(compiler: Compiler): void { const { include = ['**/*.spec.ts'], exclude = [], projectSourceRoot, workspaceRoot, } = this.options; const webpackOptions = compiler.options; const entry = typeof webpackOptions.entry === 'function' ? webpackOptions.entry() : webpackOptions.entry; let originalImport: string[] | undefined; // Add tests files are part of the entry-point. webpackOptions.entry = async () => { const specFiles = await findTests(include, exclude, workspaceRoot, projectSourceRoot); const entrypoints = await entry; const entrypoint = entrypoints['main']; if (!entrypoint.import) { throw new Error(`Cannot find 'main' entrypoint.`); } if (specFiles.length) { originalImport ??= entrypoint.import; entrypoint.import = [...originalImport, ...specFiles]; } else { assert(this.compilation, 'Compilation cannot be undefined.'); this.compilation .getLogger(pluginName) .error(`Specified patterns: "${include.join(', ')}" did not match any spec files.`); } return entrypoints; }; compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { this.compilation = compilation; compilation.contextDependencies.add(projectSourceRoot); }); } }
{ "commit_id": "b893a6ae9", "end_byte": 2163, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/find-tests-plugin.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/index.ts_0_7237
/** * @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 { assertCompatibleAngularVersion } from '@angular/build/private'; import { BuilderContext, BuilderOutput, createBuilder, targetFromTargetString, } from '@angular-devkit/architect'; import { strings } from '@angular-devkit/core'; import type { ConfigOptions } from 'karma'; import { createRequire } from 'module'; import * as path from 'path'; import { Observable, from, mergeMap } from 'rxjs'; import { Configuration } from 'webpack'; import { ExecutionTransformer } from '../../transforms'; import { BuilderMode, Schema as KarmaBuilderOptions } from './schema'; export type KarmaConfigOptions = ConfigOptions & { buildWebpack?: unknown; configFile?: string; }; /** * @experimental Direct usage of this function is considered experimental. */ export function execute( options: KarmaBuilderOptions, context: BuilderContext, transforms: { webpackConfiguration?: ExecutionTransformer<Configuration>; // The karma options transform cannot be async without a refactor of the builder implementation karmaOptions?: (options: KarmaConfigOptions) => KarmaConfigOptions; } = {}, ): Observable<BuilderOutput> { // Check Angular version. assertCompatibleAngularVersion(context.workspaceRoot); return from(getExecuteWithBuilder(options, context)).pipe( mergeMap(([useEsbuild, executeWithBuilder]) => { const karmaOptions = getBaseKarmaOptions(options, context, useEsbuild); return executeWithBuilder.execute(options, context, karmaOptions, transforms); }), ); } function getBaseKarmaOptions( options: KarmaBuilderOptions, context: BuilderContext, useEsbuild: boolean, ): KarmaConfigOptions { let singleRun: boolean | undefined; if (options.watch !== undefined) { singleRun = !options.watch; } // Determine project name from builder context target const projectName = context.target?.project; if (!projectName) { throw new Error(`The 'karma' builder requires a target to be specified.`); } const karmaOptions: KarmaConfigOptions = options.karmaConfig ? {} : getBuiltInKarmaConfig(context.workspaceRoot, projectName, useEsbuild); karmaOptions.singleRun = singleRun; // Workaround https://github.com/angular/angular-cli/issues/28271, by clearing context by default // for single run executions. Not clearing context for multi-run (watched) builds allows the // Jasmine Spec Runner to be visible in the browser after test execution. karmaOptions.client ??= {}; karmaOptions.client.clearContext ??= singleRun ?? false; // `singleRun` defaults to `false` per Karma docs. // Convert browsers from a string to an array if (typeof options.browsers === 'string' && options.browsers) { karmaOptions.browsers = options.browsers.split(','); } else if (options.browsers === false) { karmaOptions.browsers = []; } if (options.reporters) { // Split along commas to make it more natural, and remove empty strings. const reporters = options.reporters .reduce<string[]>((acc, curr) => acc.concat(curr.split(',')), []) .filter((x) => !!x); if (reporters.length > 0) { karmaOptions.reporters = reporters; } } return karmaOptions; } function getBuiltInKarmaConfig( workspaceRoot: string, projectName: string, useEsbuild: boolean, ): ConfigOptions & Record<string, unknown> { let coverageFolderName = projectName.charAt(0) === '@' ? projectName.slice(1) : projectName; if (/[A-Z]/.test(coverageFolderName)) { coverageFolderName = strings.dasherize(coverageFolderName); } const workspaceRootRequire = createRequire(workspaceRoot + '/'); // Any changes to the config here need to be synced to: packages/schematics/angular/config/files/karma.conf.js.template return { basePath: '', frameworks: ['jasmine', ...(useEsbuild ? [] : ['@angular-devkit/build-angular'])], plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-jasmine-html-reporter', 'karma-coverage', ...(useEsbuild ? [] : ['@angular-devkit/build-angular/plugins/karma']), ].map((p) => workspaceRootRequire(p)), jasmineHtmlReporter: { suppressAll: true, // removes the duplicated traces }, coverageReporter: { dir: path.join(workspaceRoot, 'coverage', coverageFolderName), subdir: '.', reporters: [{ type: 'html' }, { type: 'text-summary' }], }, reporters: ['progress', 'kjhtml'], browsers: ['Chrome'], customLaunchers: { // Chrome configured to run in a bazel sandbox. // Disable the use of the gpu and `/dev/shm` because it causes Chrome to // crash on some environments. // See: // https://github.com/puppeteer/puppeteer/blob/v1.0.0/docs/troubleshooting.md#tips // https://stackoverflow.com/questions/50642308/webdriverexception-unknown-error-devtoolsactiveport-file-doesnt-exist-while-t ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'], }, }, restartOnFileChange: true, }; } export type { KarmaBuilderOptions }; export default createBuilder<Record<string, string> & KarmaBuilderOptions>(execute); async function getExecuteWithBuilder( options: KarmaBuilderOptions, context: BuilderContext, ): Promise<[boolean, typeof import('./application_builder') | typeof import('./browser_builder')]> { const useEsbuild = await checkForEsbuild(options, context); const executeWithBuilderModule = useEsbuild ? import('./application_builder') : import('./browser_builder'); return [useEsbuild, await executeWithBuilderModule]; } async function checkForEsbuild( options: KarmaBuilderOptions, context: BuilderContext, ): Promise<boolean> { if (options.builderMode !== BuilderMode.Detect) { return options.builderMode === BuilderMode.Application; } // Look up the current project's build target using a development configuration. const buildTargetSpecifier = `::development`; const buildTarget = targetFromTargetString( buildTargetSpecifier, context.target?.project, 'build', ); try { const developmentBuilderName = await context.getBuilderNameForTarget(buildTarget); return isEsbuildBased(developmentBuilderName); } catch (e) { if (!(e instanceof Error) || e.message !== 'Project target does not exist.') { throw e; } // If we can't find a development builder, we can't use 'detect'. throw new Error( 'Failed to detect the builder used by the application. Please set builderMode explicitly.', ); } } 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; }
{ "commit_id": "b893a6ae9", "end_byte": 7237, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/application_builder.ts_0_5603
/** * @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 { BuildOutputFileType } from '@angular/build'; import { ApplicationBuilderInternalOptions, ResultFile, ResultKind, buildApplicationInternal, emitFilesToDisk, } from '@angular/build/private'; import { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import { randomUUID } from 'crypto'; import glob from 'fast-glob'; import * as fs from 'fs/promises'; import type { Config, ConfigOptions, InlinePluginDef } from 'karma'; import * as path from 'path'; import { Observable, Subscriber, catchError, defaultIfEmpty, from, of, switchMap } from 'rxjs'; import { Configuration } from 'webpack'; import { ExecutionTransformer } from '../../transforms'; import { OutputHashing } from '../browser-esbuild/schema'; import { findTests } from './find-tests'; import { Schema as KarmaBuilderOptions } from './schema'; interface BuildOptions extends ApplicationBuilderInternalOptions { // We know that it's always a string since we set it. outputPath: string; } class ApplicationBuildError extends Error { constructor(message: string) { super(message); this.name = 'ApplicationBuildError'; } } function injectKarmaReporter( context: BuilderContext, buildOptions: BuildOptions, karmaConfig: Config & ConfigOptions, subscriber: Subscriber<BuilderOutput>, ) { const reporterName = 'angular-progress-notifier'; interface RunCompleteInfo { exitCode: number; } interface KarmaEmitter { refreshFiles(): void; } class ProgressNotifierReporter { static $inject = ['emitter']; constructor(private readonly emitter: KarmaEmitter) { this.startWatchingBuild(); } private startWatchingBuild() { void (async () => { for await (const buildOutput of buildApplicationInternal( { ...buildOptions, watch: true, }, context, )) { if (buildOutput.kind === ResultKind.Failure) { subscriber.next({ success: false, message: 'Build failed' }); } else if ( buildOutput.kind === ResultKind.Incremental || buildOutput.kind === ResultKind.Full ) { await writeTestFiles(buildOutput.files, buildOptions.outputPath); this.emitter.refreshFiles(); } } })(); } onRunComplete = function (_browsers: unknown, results: RunCompleteInfo) { if (results.exitCode === 0) { subscriber.next({ success: true }); } else { subscriber.next({ success: false }); } }; } karmaConfig.reporters ??= []; karmaConfig.reporters.push(reporterName); karmaConfig.plugins ??= []; karmaConfig.plugins.push({ [`reporter:${reporterName}`]: [ 'factory', Object.assign( (...args: ConstructorParameters<typeof ProgressNotifierReporter>) => new ProgressNotifierReporter(...args), ProgressNotifierReporter, ), ], }); } export function execute( options: KarmaBuilderOptions, context: BuilderContext, karmaOptions: ConfigOptions, transforms: { webpackConfiguration?: ExecutionTransformer<Configuration>; // The karma options transform cannot be async without a refactor of the builder implementation karmaOptions?: (options: ConfigOptions) => ConfigOptions; } = {}, ): Observable<BuilderOutput> { return from(initializeApplication(options, context, karmaOptions, transforms)).pipe( switchMap( ([karma, karmaConfig, buildOptions]) => new Observable<BuilderOutput>((subscriber) => { if (options.watch) { injectKarmaReporter(context, buildOptions, karmaConfig, subscriber); } // Complete the observable once the Karma server returns. const karmaServer = new karma.Server(karmaConfig as Config, (exitCode) => { subscriber.next({ success: exitCode === 0 }); subscriber.complete(); }); const karmaStart = karmaServer.start(); // Cleanup, signal Karma to exit. return () => { void karmaStart.then(() => karmaServer.stop()); }; }), ), catchError((err) => { if (err instanceof ApplicationBuildError) { return of({ success: false, message: err.message }); } throw err; }), defaultIfEmpty({ success: false }), ); } async function getProjectSourceRoot(context: BuilderContext): Promise<string> { // We have already validated that the project name is set before calling this function. const projectName = context.target?.project; if (!projectName) { return context.workspaceRoot; } const projectMetadata = await context.getProjectMetadata(projectName); const sourceRoot = (projectMetadata.sourceRoot ?? projectMetadata.root ?? '') as string; return path.join(context.workspaceRoot, sourceRoot); } function normalizePolyfills(polyfills: string | string[] | undefined): string[] { if (typeof polyfills === 'string') { return [polyfills]; } return polyfills ?? []; } async function collectEntrypoints( options: KarmaBuilderOptions, context: BuilderContext, projectSourceRoot: string, ): Promise<Set<string>> { // Glob for files to test. const testFiles = await findTests( options.include ?? [], options.exclude ?? [], context.workspaceRoot, projectSourceRoot, ); return new Set(testFiles); }
{ "commit_id": "b893a6ae9", "end_byte": 5603, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/application_builder.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/application_builder.ts_5605_12851
async function initializeApplication( options: KarmaBuilderOptions, context: BuilderContext, karmaOptions: ConfigOptions, transforms: { webpackConfiguration?: ExecutionTransformer<Configuration>; karmaOptions?: (options: ConfigOptions) => ConfigOptions; } = {}, ): Promise<[typeof import('karma'), Config & ConfigOptions, BuildOptions]> { if (transforms.webpackConfiguration) { context.logger.warn( `This build is using the application builder but transforms.webpackConfiguration was provided. The transform will be ignored.`, ); } const outputPath = path.join(context.workspaceRoot, 'dist/test-out', randomUUID()); const projectSourceRoot = await getProjectSourceRoot(context); const [karma, entryPoints] = await Promise.all([ import('karma'), collectEntrypoints(options, context, projectSourceRoot), fs.rm(outputPath, { recursive: true, force: true }), ]); let mainName = 'init_test_bed'; if (options.main) { entryPoints.add(options.main); mainName = path.basename(options.main, path.extname(options.main)); } else { entryPoints.add('@angular-devkit/build-angular/src/builders/karma/init_test_bed.js'); } const instrumentForCoverage = options.codeCoverage ? createInstrumentationFilter( projectSourceRoot, getInstrumentationExcludedPaths(context.workspaceRoot, options.codeCoverageExclude ?? []), ) : undefined; const buildOptions: BuildOptions = { entryPoints, tsConfig: options.tsConfig, outputPath, aot: false, index: false, outputHashing: OutputHashing.None, optimization: false, sourceMap: { scripts: true, styles: true, vendor: true, }, instrumentForCoverage, styles: options.styles, polyfills: normalizePolyfills(options.polyfills), webWorkerTsConfig: options.webWorkerTsConfig, }; // Build tests with `application` builder, using test files as entry points. const buildOutput = await first(buildApplicationInternal(buildOptions, context)); if (buildOutput.kind === ResultKind.Failure) { throw new ApplicationBuildError('Build failed'); } else if (buildOutput.kind !== ResultKind.Full) { throw new ApplicationBuildError( 'A full build result is required from the application builder.', ); } // Write test files await writeTestFiles(buildOutput.files, buildOptions.outputPath); karmaOptions.files ??= []; karmaOptions.files.push( // Serve polyfills first. { pattern: `${outputPath}/polyfills.js`, type: 'module' }, // Serve global setup script. { pattern: `${outputPath}/${mainName}.js`, type: 'module' }, // Serve all source maps. { pattern: `${outputPath}/*.map`, included: false }, ); if (hasChunkOrWorkerFiles(buildOutput.files)) { karmaOptions.files.push( // Allow loading of chunk-* files but don't include them all on load. { pattern: `${outputPath}/{chunk,worker}-*.js`, type: 'module', included: false }, ); } karmaOptions.files.push( // Serve remaining JS on page load, these are the test entrypoints. { pattern: `${outputPath}/*.js`, type: 'module' }, ); if (options.styles?.length) { // Serve CSS outputs on page load, these are the global styles. karmaOptions.files.push({ pattern: `${outputPath}/*.css`, type: 'css' }); } const parsedKarmaConfig: Config & ConfigOptions = await karma.config.parseConfig( options.karmaConfig && path.resolve(context.workspaceRoot, options.karmaConfig), transforms.karmaOptions ? transforms.karmaOptions(karmaOptions) : karmaOptions, { promiseConfig: true, throwErrors: true }, ); // Remove the webpack plugin/framework: // Alternative would be to make the Karma plugin "smart" but that's a tall order // with managing unneeded imports etc.. const pluginLengthBefore = (parsedKarmaConfig.plugins ?? []).length; parsedKarmaConfig.plugins = (parsedKarmaConfig.plugins ?? []).filter( (plugin: string | InlinePluginDef) => { if (typeof plugin === 'string') { return plugin !== 'framework:@angular-devkit/build-angular'; } return !plugin['framework:@angular-devkit/build-angular']; }, ); parsedKarmaConfig.frameworks = parsedKarmaConfig.frameworks?.filter( (framework: string) => framework !== '@angular-devkit/build-angular', ); const pluginLengthAfter = (parsedKarmaConfig.plugins ?? []).length; if (pluginLengthBefore !== pluginLengthAfter) { context.logger.warn( `Ignoring framework "@angular-devkit/build-angular" from karma config file because it's not compatible with the application builder.`, ); } // When using code-coverage, auto-add karma-coverage. // This was done as part of the karma plugin for webpack. if ( options.codeCoverage && !parsedKarmaConfig.reporters?.some((r: string) => r === 'coverage' || r === 'coverage-istanbul') ) { parsedKarmaConfig.reporters = (parsedKarmaConfig.reporters ?? []).concat(['coverage']); } return [karma, parsedKarmaConfig, buildOptions]; } function hasChunkOrWorkerFiles(files: Record<string, unknown>): boolean { return Object.keys(files).some((filename) => { return /(?:^|\/)(?:worker|chunk)[^/]+\.js$/.test(filename); }); } export async function writeTestFiles(files: Record<string, ResultFile>, testDir: string) { const directoryExists = new Set<string>(); // Writes the test related output files to disk and ensures the containing directories are present await emitFilesToDisk(Object.entries(files), async ([filePath, file]) => { if (file.type !== BuildOutputFileType.Browser && file.type !== BuildOutputFileType.Media) { return; } const fullFilePath = path.join(testDir, filePath); // Ensure output subdirectories exist const fileBasePath = path.dirname(fullFilePath); if (fileBasePath && !directoryExists.has(fileBasePath)) { await fs.mkdir(fileBasePath, { recursive: true }); directoryExists.add(fileBasePath); } if (file.origin === 'memory') { // Write file contents await fs.writeFile(fullFilePath, file.contents); } else { // Copy file contents await fs.copyFile(file.inputPath, fullFilePath, fs.constants.COPYFILE_FICLONE); } }); } /** Returns the first item yielded by the given generator and cancels the execution. */ async function first<T>(generator: AsyncIterable<T>): Promise<T> { for await (const value of generator) { return value; } throw new Error('Expected generator to emit at least once.'); } function createInstrumentationFilter(includedBasePath: string, excludedPaths: Set<string>) { return (request: string): boolean => { return ( !excludedPaths.has(request) && !/\.(e2e|spec)\.tsx?$|[\\/]node_modules[\\/]/.test(request) && request.startsWith(includedBasePath) ); }; } 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; }
{ "commit_id": "b893a6ae9", "end_byte": 12851, "start_byte": 5605, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/application_builder.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/setup.ts_0_5819
/** * @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 { BuilderMode, Schema } from '../schema'; import { BuilderHandlerFn } from '@angular-devkit/architect'; import { json } from '@angular-devkit/core'; import { ApplicationBuilderOptions as ApplicationSchema, buildApplication } from '@angular/build'; import * as path from 'node:path'; import { readFileSync } from 'node:fs'; import { JasmineBuilderHarness } from '../../../testing'; import { host } from '../../../testing/test-utils'; import { BuilderHarness } from '../../../testing'; 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'; export { describeBuilder } from '../../../testing'; export const KARMA_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:karma', schemaPath: __dirname + '/../schema.json', }); /** * Contains all required karma builder fields. * Also disables progress reporting to minimize logging output. */ export const BASE_OPTIONS = Object.freeze<Schema>({ polyfills: ['./src/polyfills', 'zone.js/testing'], tsConfig: 'src/tsconfig.spec.json', karmaConfig: 'karma.conf.js', browsers: 'ChromeHeadlessCI', progress: false, watch: false, builderMode: BuilderMode.Detect, }); const optionSchemaCache = new Map<string, json.schema.JsonSchema>(); function getCachedSchema(options: { schemaPath: string }): json.schema.JsonSchema { 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); } return optionSchema; } /** * 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 async function setupBrowserTarget<T>( harness: BuilderHarness<T>, extraOptions?: Partial<BrowserSchema>, ): Promise<void> { const browserSchema = getCachedSchema(BROWSER_BUILDER_INFO); harness.withBuilderTarget( 'build', buildWebpackBrowser, { ...BROWSER_BASE_OPTIONS, ...extraOptions, }, { builderName: BROWSER_BUILDER_INFO.name, optionSchema: browserSchema, }, ); } /** * Contains all required application builder fields. * Also disables progress reporting to minimize logging output. */ export const APPLICATION_BASE_OPTIONS = Object.freeze<ApplicationSchema>({ 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, }); // 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', ), }); /** * 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 async function setupApplicationTarget<T>( harness: BuilderHarness<T>, extraOptions?: Partial<ApplicationSchema>, ): Promise<void> { const applicationSchema = getCachedSchema(APPLICATION_BUILDER_INFO); harness.withBuilderTarget( 'build', buildApplication, { ...APPLICATION_BASE_OPTIONS, ...extraOptions, }, { builderName: APPLICATION_BUILDER_INFO.name, optionSchema: applicationSchema, }, ); // For application-builder based targets, the localize polyfill needs to be explicit. await harness.appendToFile('src/polyfills.ts', `import '@angular/localize/init';`); } /** Runs the test against both an application- and a browser-builder context. */ export function describeKarmaBuilder<T>( builderHandler: BuilderHandlerFn<T & json.JsonObject>, options: { name?: string; schemaPath: string }, specDefinitions: (( harness: JasmineBuilderHarness<T>, setupTarget: typeof setupApplicationTarget, isApplicationTarget: true, ) => void) & (( harness: JasmineBuilderHarness<T>, setupTarget: typeof setupBrowserTarget, isApplicationTarget: false, ) => void), ) { const optionSchema = getCachedSchema(options); const harness = new JasmineBuilderHarness<T>(builderHandler, host, { builderName: options.name, optionSchema, }); describe(options.name || builderHandler.name, () => { for (const isApplicationTarget of [true, false]) { describe(isApplicationTarget ? 'with application builder' : 'with browser builder', () => { beforeEach(() => host.initialize().toPromise()); afterEach(() => host.restore().toPromise()); if (isApplicationTarget) { specDefinitions(harness, setupApplicationTarget, true); } else { specDefinitions(harness, setupBrowserTarget, false); } }); } }); }
{ "commit_id": "b893a6ae9", "end_byte": 5819, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/setup.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/fake-async_spec.ts_0_2557
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "fakeAsync"', () => { beforeEach(async () => { await setupTarget(harness); }); it('loads zone.js/testing at the right time', async () => { await harness.writeFiles({ './src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, template: '<button (click)="changeMessage()" class="change">{{ message }}</button>', }) export class AppComponent { message = 'Initial'; changeMessage() { setTimeout(() => { this.message = 'Changed'; }, 1000); } }`, './src/app/app.component.spec.ts': ` import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ declarations: [AppComponent] })); it('allows terrible things that break the most basic assumptions', fakeAsync(() => { const fixture = TestBed.createComponent(AppComponent); const btn = fixture.debugElement .query(By.css('button.change')); fixture.detectChanges(); expect(btn.nativeElement.innerText).toBe('Initial'); btn.triggerEventHandler('click', null); // Pre-tick: Still the old value. fixture.detectChanges(); expect(btn.nativeElement.innerText).toBe('Initial'); tick(1500); fixture.detectChanges(); expect(btn.nativeElement.innerText).toBe('Changed'); })); });`, }); harness.useTarget('test', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2557, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/fake-async_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/rebuilds_spec.ts_0_2359
/** * @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, debounceTime, take, timeout } from 'rxjs'; import { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; import { BuilderOutput } from '@angular-devkit/architect'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget, isApplicationBuilder) => { describe('Behavior: "Rebuilds"', () => { beforeEach(async () => { await setupTarget(harness); }); it('recovers from compilation failures in watch mode', async () => { harness.useTarget('test', { ...BASE_OPTIONS, watch: true, }); const goodFile = await harness.readFile('src/app/app.component.spec.ts'); interface OutputCheck { (result: BuilderOutput | undefined): Promise<void>; } const expectedSequence: OutputCheck[] = [ async (result) => { // Karma run should succeed. // Add a compilation error. expect(result?.success).toBeTrue(); // Add an syntax error to a non-main file. await harness.appendToFile('src/app/app.component.spec.ts', `error`); }, async (result) => { expect(result?.success).toBeFalse(); await harness.writeFile('src/app/app.component.spec.ts', goodFile); }, async (result) => { expect(result?.success).toBeTrue(); }, ]; if (isApplicationBuilder) { expectedSequence.unshift(async (result) => { // This is the initial Karma run, it should succeed. // For simplicity, we trigger a run the first time we build in watch mode. expect(result?.success).toBeTrue(); }); } const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(60000), debounceTime(500), concatMap(async ({ result }, index) => { await expectedSequence[index](result); }), take(expectedSequence.length), count(), ) .toPromise(); expect(buildCount).toBe(expectedSequence.length); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2359, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/rebuilds_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/errors_spec.ts_0_907
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "Errors"', () => { beforeEach(async () => { await setupTarget(harness); }); it('should fail when there is a TypeScript error', async () => { harness.useTarget('test', { ...BASE_OPTIONS, }); await harness.appendToFile('src/app/app.component.spec.ts', `console.lo('foo')`); const { result } = await harness.executeOnce({ outputLogsOnFailure: false, }); expect(result?.success).toBeFalse(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 907, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/errors_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/module-cjs_spec.ts_0_997
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "module commonjs"', () => { beforeEach(async () => { await setupTarget(harness); }); it('should work when module is commonjs', async () => { harness.useTarget('test', { ...BASE_OPTIONS, }); await harness.modifyFile('src/tsconfig.spec.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.compilerOptions.module = 'commonjs'; return JSON.stringify(tsConfig); }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 997, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/module-cjs_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/code-coverage_spec.ts_0_3993
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { setTimeout } from 'node:timers/promises'; import { tags } from '@angular-devkit/core'; import { last, tap } from 'rxjs'; import { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; // In each of the test below we'll have to call setTimeout to wait for the coverage // analysis to be done. This is because karma-coverage performs the analysis // asynchronously but the promise that it returns is not awaited by Karma. // Coverage analysis begins when onRunComplete() is invoked, and output files // are subsequently written to disk. For more information, see // https://github.com/karma-runner/karma-coverage/blob/32acafa90ed621abd1df730edb44ae55a4009c2c/lib/reporter.js#L221 const coveragePath = 'coverage/lcov.info'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "codeCoverage"', () => { beforeEach(async () => { await setupTarget(harness); }); it('should generate coverage report when file was previously processed by Babel', async () => { // Force Babel transformation. await harness.appendToFile('src/app/app.component.ts', '// async'); harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).toExist(); }); it('should exit with non-zero code when coverage is below threshold', async () => { await harness.modifyFile('karma.conf.js', (content) => content.replace( 'coverageReporter: {', `coverageReporter: { check: { global: { statements: 100, lines: 100, branches: 100, functions: 100 } }, `, ), ); await harness.appendToFile( 'src/app/app.component.ts', ` export function nonCovered(): boolean { return true; } `, ); harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, }); await harness .execute() .pipe( // In incremental mode, karma-coverage does not have the ability to mark a // run as failed if code coverage does not pass. This is because it does // the coverage asynchoronously and Karma does not await the promise // returned by the plugin. // However the program must exit with non-zero exit code. // This is a more common use case of coverage testing and must be supported. last(), tap((buildEvent) => expect(buildEvent.result?.success).toBeFalse()), ) .toPromise(); }); it('should remapped instrumented code back to the original source', async () => { await harness.modifyFile('karma.conf.js', (content) => content.replace('lcov', 'html')); await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace( `title = 'app'`, tags.stripIndents` title = 'app'; async foo() { return 'foo'; } `, ); }); harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness .expectFile('coverage/app.component.ts.html') .content.toContain( '<span class="fstat-no" title="function not covered" >async </span>foo()', ); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 3993, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/behavior/code-coverage_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/assets_spec.ts_0_3779
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "assets"', () => { beforeEach(async () => { await setupTarget(harness); }); it('includes assets', async () => { await harness.writeFiles({ './src/string-file-asset.txt': 'string-file-asset.txt', './src/string-folder-asset/file.txt': 'string-folder-asset.txt', './src/glob-asset.txt': 'glob-asset.txt', './src/folder/folder-asset.txt': 'folder-asset.txt', './src/output-asset.txt': 'output-asset.txt', './src/app/app.module.ts': ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, './src/app/app.component.ts': ` import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', standalone: false, template: '<p *ngFor="let asset of assets">{{ asset.content }}</p>' }) export class AppComponent { public assets = [ { path: './string-file-asset.txt', content: '' }, { path: './string-folder-asset/file.txt', content: '' }, { path: './glob-asset.txt', content: '' }, { path: './folder/folder-asset.txt', content: '' }, { path: './output-folder/output-asset.txt', content: '' }, ]; constructor(private http: HttpClient) { this.assets.forEach(asset => http.get(asset.path, { responseType: 'text' }) .subscribe(res => asset.content = res)); } }`, './src/app/app.component.spec.ts': ` import { TestBed } from '@angular/core/testing'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ imports: [HttpClientModule], declarations: [AppComponent] })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); });`, }); harness.useTarget('test', { ...BASE_OPTIONS, assets: [ 'src/string-file-asset.txt', 'src/string-folder-asset', { glob: 'glob-asset.txt', input: 'src/', output: '/' }, { glob: 'output-asset.txt', input: 'src/', output: '/output-folder' }, { glob: '**/*', input: 'src/folder', output: '/folder' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 3779, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/main_spec.ts_0_1676
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "main"', () => { beforeEach(async () => { await setupTarget(harness); }); beforeEach(async () => { await harness.writeFiles({ 'src/magic.ts': `Object.assign(globalThis, {MAGIC_IS_REAL: true});`, 'src/magic.spec.ts': ` declare const MAGIC_IS_REAL: boolean; describe('Magic', () => { it('can be scientificially proven to be true', () => { expect(typeof MAGIC_IS_REAL).toBe('boolean'); }); });`, }); // Remove this test, we don't expect it to pass with our setup script. await harness.removeFile('src/app/app.component.spec.ts'); // Add src/magic.ts to tsconfig. interface TsConfig { files: string[]; } const tsConfig = JSON.parse(harness.readFile('src/tsconfig.spec.json')) as TsConfig; tsConfig.files.push('magic.ts'); await harness.writeFile('src/tsconfig.spec.json', JSON.stringify(tsConfig)); }); it('uses custom setup file', async () => { harness.useTarget('test', { ...BASE_OPTIONS, main: './src/magic.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 1676, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/main_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/builder-mode_spec.ts_0_2333
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; import { BuilderMode } from '../../schema'; const ESBUILD_LOG_TEXT = 'Application bundle generation complete.'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget, isApplicationTarget) => { describe('option: "builderMode"', () => { beforeEach(async () => { await setupTarget(harness); }); it('"application" always uses esbuild', async () => { harness.useTarget('test', { ...BASE_OPTIONS, // Must explicitly provide localize polyfill: polyfills: ['zone.js', '@angular/localize/init', 'zone.js/testing'], builderMode: BuilderMode.Application, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(ESBUILD_LOG_TEXT), }), ); }); it('"browser" always uses webpack', async () => { harness.useTarget('test', { ...BASE_OPTIONS, builderMode: BuilderMode.Browser, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining({ message: jasmine.stringMatching(ESBUILD_LOG_TEXT), }), ); }); it('"detect" follows configuration of the development builder', async () => { harness.useTarget('test', { ...BASE_OPTIONS, builderMode: BuilderMode.Detect, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); if (isApplicationTarget) { expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(ESBUILD_LOG_TEXT), }), ); } else { expect(logs).not.toContain( jasmine.objectContaining({ message: jasmine.stringMatching(ESBUILD_LOG_TEXT), }), ); } }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2333, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/builder-mode_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/web-worker-tsconfig_spec.ts_0_3836
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget, isApplicationBuilder) => { describe('Option: "webWorkerTsConfig"', () => { beforeEach(async () => { await setupTarget(harness); }); beforeEach(async () => { await harness.writeFiles({ 'src/tsconfig.worker.json': ` { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/worker", "lib": [ "es2018", "webworker" ], "types": [] }, "include": [ "**/*.worker.ts", ] }`, 'src/app/app.worker.ts': ` /// <reference lib="webworker" /> const prefix: string = 'Data: '; addEventListener('message', ({ data }) => { postMessage(prefix + data); }); `, 'src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, template: '' }) export class AppComponent { worker = new Worker(new URL('./app.worker', import.meta.url)); } `, './src/app/app.component.spec.ts': ` import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ declarations: [AppComponent] })); it('worker should be defined', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.worker).toBeDefined(); }); });`, }); }); // Web workers work with the application builder _without_ setting webWorkerTsConfig. if (isApplicationBuilder) { it(`should parse web workers when "webWorkerTsConfig" is not set or set to undefined.`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, webWorkerTsConfig: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); } else { it(`should not parse web workers when "webWorkerTsConfig" is not set or set to undefined.`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, webWorkerTsConfig: undefined, }); await harness.writeFile( './src/app/app.component.spec.ts', ` import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ declarations: [AppComponent] })); it('worker should throw', () => { expect(() => TestBed.createComponent(AppComponent)) .toThrowError(/Failed to construct 'Worker'/); }); });`, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); } it(`should parse web workers when "webWorkerTsConfig" is set.`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, webWorkerTsConfig: 'src/tsconfig.worker.json', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 3836, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/web-worker-tsconfig_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/code-coverage-exclude_spec.ts_0_2426
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { setTimeout } from 'node:timers/promises'; import { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; // In each of the test below we'll have to call setTimeout to wait for the coverage // analysis to be done. This is because karma-coverage performs the analysis // asynchronously but the promise that it returns is not awaited by Karma. // Coverage analysis begins when onRunComplete() is invoked, and output files // are subsequently written to disk. For more information, see // https://github.com/karma-runner/karma-coverage/blob/32acafa90ed621abd1df730edb44ae55a4009c2c/lib/reporter.js#L221 const coveragePath = 'coverage/lcov.info'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "codeCoverageExclude"', () => { beforeEach(async () => { await setupTarget(harness); }); it('should exclude file from coverage when set', async () => { harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, codeCoverageExclude: ['**/app.component.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).content.not.toContain('app.component.ts'); }); it('should exclude file from coverage when set when glob starts with a forward slash', async () => { harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, codeCoverageExclude: ['/**/app.component.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).content.not.toContain('app.component.ts'); }); it('should not exclude file from coverage when set', async () => { harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).content.toContain('app.component.ts'); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2426, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/code-coverage-exclude_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/styles_spec.ts_0_4690
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "styles"', () => { beforeEach(async () => { await setupTarget(harness); }); it(`processes 'styles.css' styles`, async () => { await harness.writeFiles({ 'src/styles.css': 'p {display: none}', 'src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, template: '<p>Hello World</p>' }) export class AppComponent { } `, 'src/app/app.component.spec.ts': ` import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ declarations: [AppComponent] })); it('should not contain text that is hidden via css', () => { const fixture = TestBed.createComponent(AppComponent); expect(fixture.nativeElement.innerText).not.toContain('Hello World'); }); });`, }); harness.useTarget('test', { ...BASE_OPTIONS, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it('processes style with bundleName', async () => { await harness.writeFiles({ 'src/dark-theme.css': '', 'src/app/app.module.ts': ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, 'src/app/app.component.ts': ` import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', standalone: false, template: '<p *ngFor="let asset of css">{{ asset.content }}</p>' }) export class AppComponent { public assets = [ { path: './dark-theme.css', content: '' }, ]; constructor(private http: HttpClient) { this.assets.forEach(asset => http.get(asset.path, { responseType: 'text' }) .subscribe(res => asset.content = res)); } }`, 'src/app/app.component.spec.ts': ` import { TestBed } from '@angular/core/testing'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ imports: [HttpClientModule], declarations: [AppComponent] })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); });`, }); harness.useTarget('test', { ...BASE_OPTIONS, styles: [ { inject: false, input: 'src/dark-theme.css', bundleName: 'dark-theme', }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it('fails and shows an error if style does not exist', async () => { harness.useTarget('test', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ level: 'error', message: jasmine.stringMatching( /(Can't|Could not) resolve ['"]src\/test-style-a.css['"]/, ), }), ); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 4690, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/code-coverage_spec.ts_0_3534
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { setTimeout } from 'node:timers/promises'; import { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; // In each of the test below we'll have to call setTimeout to wait for the coverage // analysis to be done. This is because karma-coverage performs the analysis // asynchronously but the promise that it returns is not awaited by Karma. // Coverage analysis begins when onRunComplete() is invoked, and output files // are subsequently written to disk. For more information, see // https://github.com/karma-runner/karma-coverage/blob/32acafa90ed621abd1df730edb44ae55a4009c2c/lib/reporter.js#L221 const coveragePath = 'coverage/lcov.info'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "codeCoverage"', () => { beforeEach(async () => { await setupTarget(harness); }); it('should generate coverage report when option is set to true', async () => { harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).toExist(); }); it('should not generate coverage report when option is set to false', async () => { harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).toNotExist(); }); it('should not generate coverage report when option is unset', async () => { harness.useTarget('test', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).toNotExist(); }); it(`should collect coverage from paths in 'sourceRoot'`, async () => { await harness.writeFiles({ './dist/my-lib/index.d.ts': ` export declare const title = 'app'; `, './dist/my-lib/index.js': ` export const title = 'app'; `, './src/app/app.component.ts': ` import { Component } from '@angular/core'; import { title } from 'my-lib'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = title; } `, }); await harness.modifyFile('tsconfig.json', (content) => content.replace( /"baseUrl": ".\/",/, ` "baseUrl": "./", "paths": { "my-lib": [ "./dist/my-lib" ] }, `, ), ); harness.useTarget('test', { ...BASE_OPTIONS, codeCoverage: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); await setTimeout(1000); harness.expectFile(coveragePath).content.not.toContain('my-lib'); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 3534, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/code-coverage_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/exclude_spec.ts_0_1986
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "exclude"', () => { beforeEach(async () => { await setupTarget(harness); }); beforeEach(async () => { await harness.writeFiles({ 'src/app/error.spec.ts': ` describe('Error spec', () => { it('should error', () => { expect(false).toBe(true); }); });`, }); }); it(`should not exclude any spec when exclude is not supplied`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeFalse(); }); it(`should exclude spec that matches the 'exclude' glob pattern`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, exclude: ['**/error.spec.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it(`should exclude spec that matches the 'exclude' pattern with a relative project root`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, exclude: ['src/app/error.spec.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it(`should exclude spec that matches the 'exclude' pattern prefixed with a slash`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, exclude: ['/src/app/error.spec.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 1986, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/exclude_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/tests/options/include_spec.ts_0_2835
/** * @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 { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "include"', () => { beforeEach(async () => { await setupTarget(harness); }); it(`should fail when includes doesn't match any files`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, include: ['abc.spec.ts', 'def.spec.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeFalse(); }); [ { test: 'relative path from workspace to spec', input: ['src/app/app.component.spec.ts'], }, { test: 'relative path from workspace to file', input: ['src/app/app.component.ts'], }, { test: 'relative path from project root to spec', input: ['app/services/test.service.spec.ts'], }, { test: 'relative path from project root to file', input: ['app/services/test.service.ts'], }, { test: 'relative path from workspace to directory', input: ['src/app/services'], }, { test: 'relative path from project root to directory', input: ['app/services'], }, { test: 'glob with spec suffix', input: ['**/*.pipe.spec.ts', '**/*.pipe.spec.ts', '**/*test.service.spec.ts'], }, { test: 'glob with forward slash and spec suffix', input: ['/**/*test.service.spec.ts'], }, ].forEach((options, index) => { it(`should work with ${options.test} (${index})`, async () => { await harness.writeFiles({ 'src/app/services/test.service.spec.ts': ` describe('TestService', () => { it('should succeed', () => { expect(true).toBe(true); }); });`, 'src/app/failing.service.spec.ts': ` describe('FailingService', () => { it('should be ignored', () => { expect(true).toBe(false); }); });`, 'src/app/property.pipe.spec.ts': ` describe('PropertyPipe', () => { it('should succeed', () => { expect(true).toBe(true); }); });`, }); harness.useTarget('test', { ...BASE_OPTIONS, include: options.input, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2835, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/tests/options/include_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts_0_6249
/** * @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'; import { normalize, virtualFs } from '@angular-devkit/core'; import { createArchitect, host } from '../../testing/test-utils'; describe('AppShell Builder', () => { const target = { project: 'app', target: 'app-shell' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); const appShellRouteFiles = { 'src/styles.css': ` p { color: #000 } `, 'src/app/app-shell/app-shell.component.html': ` <p> app-shell works! </p> `, 'src/app/app-shell/app-shell.component.ts': ` import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-app-shell', standalone: false, templateUrl: './app-shell.component.html', }) export class AppShellComponent implements OnInit { constructor() { } ngOnInit() { } } `, 'src/app/app.module.ts': ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { RouterModule } from '@angular/router'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, 'src/app/app.module.server.ts': ` import { NgModule } from '@angular/core'; import { ServerModule } from '@angular/platform-server'; import { AppModule } from './app.module'; import { AppComponent } from './app.component'; import { Routes, RouterModule } from '@angular/router'; import { AppShellComponent } from './app-shell/app-shell.component'; const routes: Routes = [ { path: 'shell', component: AppShellComponent }]; @NgModule({ imports: [ AppModule, ServerModule, RouterModule.forRoot(routes), ], bootstrap: [AppComponent], declarations: [AppShellComponent], }) export class AppServerModule {} `, 'src/main.ts': ` import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; document.addEventListener('DOMContentLoaded', () => { platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.log(err)); }); `, 'src/app/app-routing.module.ts': ` import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } `, 'src/app/app.component.html': ` <router-outlet></router-outlet> `, }; it('works (basic)', async () => { const run = await architect.scheduleTarget(target); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const fileName = 'dist/index.html'; const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toMatch('Welcome to app'); // TODO(alanagius): enable once integration of routes in complete. // expect(content).toMatch('ng-server-context="app-shell"'); }); it('works with route', async () => { host.writeMultipleFiles(appShellRouteFiles); const overrides = { route: 'shell' }; const run = await architect.scheduleTarget(target, overrides); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const fileName = 'dist/index.html'; const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('app-shell works!'); }); it('critical CSS is inlined', async () => { host.writeMultipleFiles(appShellRouteFiles); const overrides = { route: 'shell', browserTarget: 'app:build:production,inline-critical-css', }; const run = await architect.scheduleTarget(target, overrides); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const fileName = 'dist/index.html'; const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('app-shell works!'); expect(content).toContain('p{color:#000}'); expect(content).toMatch( /<link rel="stylesheet" href="styles\.[a-z0-9]+\.css" media="print" onload="this.media='all'">/, ); }); it('applies CSP nonce to critical CSS', async () => { host.writeMultipleFiles(appShellRouteFiles); host.replaceInFile('src/index.html', /<app-root/g, '<app-root ngCspNonce="{% nonce %}" '); const overrides = { route: 'shell', browserTarget: 'app:build:production,inline-critical-css', }; const run = await architect.scheduleTarget(target, overrides); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const fileName = 'dist/index.html'; const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('app-shell works!'); expect(content).toContain('<style nonce="{% nonce %}">p{color:#000}</style>'); expect(content).toContain('<style nonce="{% nonce %}" ng-app-id="ng">'); expect(content).toContain('<app-root ngcspnonce="{% nonce %}"'); expect(content).toContain('<script nonce="{% nonce %}">'); expect(content).toMatch( /<link rel="stylesheet" href="styles\.[a-z0-9]+\.css" media="print" ngCspMedia="all">/, ); }); });
{ "commit_id": "b893a6ae9", "end_byte": 6249, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/app-shell/index.ts_0_7189
/** * @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 { BuilderContext, BuilderOutput, createBuilder, targetFromTargetString, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; import * as fs from 'fs'; import * as path from 'path'; import Piscina from 'piscina'; import { normalizeOptimization } from '../../utils'; import { assertIsError } from '../../utils/error'; import { Spinner } from '../../utils/spinner'; import { BrowserBuilderOutput } from '../browser'; import { Schema as BrowserBuilderSchema } from '../browser/schema'; import { ServerBuilderOutput } from '../server'; import { Schema as BuildWebpackAppShellSchema } from './schema'; async function _renderUniversal( options: BuildWebpackAppShellSchema, context: BuilderContext, browserResult: BrowserBuilderOutput, serverResult: ServerBuilderOutput, spinner: Spinner, ): Promise<BrowserBuilderOutput> { // Get browser target options. const browserTarget = targetFromTargetString(options.browserTarget); const rawBrowserOptions = await context.getTargetOptions(browserTarget); const browserBuilderName = await context.getBuilderNameForTarget(browserTarget); const browserOptions = await context.validateOptions<JsonObject & BrowserBuilderSchema>( rawBrowserOptions, browserBuilderName, ); // Locate zone.js to load in the render worker const root = context.workspaceRoot; const zonePackage = require.resolve('zone.js', { paths: [root] }); const projectName = context.target && context.target.project; if (!projectName) { throw new Error('The builder requires a target.'); } const projectMetadata = await context.getProjectMetadata(projectName); const projectRoot = path.join(root, (projectMetadata.root as string | undefined) ?? ''); const { styles } = normalizeOptimization(browserOptions.optimization); let inlineCriticalCssProcessor; if (styles.inlineCritical) { const { InlineCriticalCssProcessor } = await import('@angular/build/private'); inlineCriticalCssProcessor = new InlineCriticalCssProcessor({ minify: styles.minify, deployUrl: browserOptions.deployUrl, }); } const renderWorker = new Piscina({ filename: require.resolve('./render-worker'), maxThreads: 1, workerData: { zonePackage }, recordTiming: false, }); try { for (const { path: outputPath, baseHref } of browserResult.outputs) { const localeDirectory = path.relative(browserResult.baseOutputPath, outputPath); const browserIndexOutputPath = path.join(outputPath, 'index.html'); const indexHtml = await fs.promises.readFile(browserIndexOutputPath, 'utf8'); const serverBundlePath = await _getServerModuleBundlePath( options, context, serverResult, localeDirectory, ); let html: string = await renderWorker.run({ serverBundlePath, document: indexHtml, url: options.route, }); // Overwrite the client index file. const outputIndexPath = options.outputIndexPath ? path.join(root, options.outputIndexPath) : browserIndexOutputPath; if (inlineCriticalCssProcessor) { const { content, warnings, errors } = await inlineCriticalCssProcessor.process(html, { outputPath, }); html = content; if (warnings.length || errors.length) { spinner.stop(); warnings.forEach((m) => context.logger.warn(m)); errors.forEach((m) => context.logger.error(m)); spinner.start(); } } await fs.promises.writeFile(outputIndexPath, html); if (browserOptions.serviceWorker) { await augmentAppWithServiceWorker( projectRoot, root, outputPath, baseHref ?? '/', browserOptions.ngswConfigPath, ); } } } finally { await renderWorker.destroy(); } return browserResult; } async function _getServerModuleBundlePath( options: BuildWebpackAppShellSchema, context: BuilderContext, serverResult: ServerBuilderOutput, browserLocaleDirectory: string, ) { if (options.appModuleBundle) { return path.join(context.workspaceRoot, options.appModuleBundle); } const { baseOutputPath = '' } = serverResult; const outputPath = path.join(baseOutputPath, browserLocaleDirectory); if (!fs.existsSync(outputPath)) { throw new Error(`Could not find server output directory: ${outputPath}.`); } const re = /^main\.(?:[a-zA-Z0-9]{16}\.)?js$/; const maybeMain = fs.readdirSync(outputPath).find((x) => re.test(x)); if (!maybeMain) { throw new Error('Could not find the main bundle.'); } return path.join(outputPath, maybeMain); } async function _appShellBuilder( options: BuildWebpackAppShellSchema, context: BuilderContext, ): Promise<BuilderOutput> { const browserTarget = targetFromTargetString(options.browserTarget); const serverTarget = targetFromTargetString(options.serverTarget); // Never run the browser target in watch mode. // If service worker is needed, it will be added in _renderUniversal(); const browserOptions = (await context.getTargetOptions(browserTarget)) as JsonObject & BrowserBuilderSchema; const optimization = normalizeOptimization(browserOptions.optimization); optimization.styles.inlineCritical = false; const browserTargetRun = await context.scheduleTarget(browserTarget, { watch: false, serviceWorker: false, optimization: optimization as unknown as JsonObject, }); if (browserTargetRun.info.builderName === '@angular-devkit/build-angular:application') { return { success: false, error: '"@angular-devkit/build-angular:application" has built-in app-shell generation capabilities. ' + 'The "appShell" option should be used instead.', }; } const serverTargetRun = await context.scheduleTarget(serverTarget, { watch: false, }); let spinner: Spinner | undefined; try { const [browserResult, serverResult] = await Promise.all([ browserTargetRun.result as Promise<BrowserBuilderOutput>, serverTargetRun.result as Promise<ServerBuilderOutput>, ]); if (browserResult.success === false || browserResult.baseOutputPath === undefined) { return browserResult; } else if (serverResult.success === false) { return serverResult; } spinner = new Spinner(); spinner.start('Generating application shell...'); const result = await _renderUniversal(options, context, browserResult, serverResult, spinner); spinner.succeed('Application shell generation complete.'); return result; } catch (err) { spinner?.fail('Application shell generation failed.'); assertIsError(err); return { success: false, error: err.message }; } finally { await Promise.all([browserTargetRun.stop(), serverTargetRun.stop()]); } } export default createBuilder(_appShellBuilder);
{ "commit_id": "b893a6ae9", "end_byte": 7189, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/app-shell/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/app-shell/render-worker.ts_0_4523
/** * @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 { ApplicationRef, StaticProvider, Type } from '@angular/core'; import type { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server'; import assert from 'node:assert'; import { workerData } from 'node:worker_threads'; /** * The fully resolved path to the zone.js package that will be loaded during worker initialization. * This is passed as workerData when setting up the worker via the `piscina` package. */ const { zonePackage } = workerData as { zonePackage: string; }; interface ServerBundleExports { /** An internal token that allows providing extra information about the server context. */ ɵSERVER_CONTEXT?: typeof ɵSERVER_CONTEXT; /** Render an NgModule application. */ renderModule?: typeof renderModule; /** NgModule to render. */ AppServerModule?: Type<unknown>; /** Method to render a standalone application. */ renderApplication?: typeof renderApplication; /** Standalone application bootstrapping function. */ default?: () => Promise<ApplicationRef>; } /** * A request to render a Server bundle generate by the universal server builder. */ interface RenderRequest { /** * The path to the server bundle that should be loaded and rendered. */ serverBundlePath: string; /** * The existing HTML document as a string that will be augmented with the rendered application. */ document: string; /** * An optional URL path that represents the Angular route that should be rendered. */ url: string; } /** * Renders an application based on a provided server bundle path, initial document, and optional URL route. * @param param0 A request to render a server bundle. * @returns A promise that resolves to the render HTML document for the application. */ async function render({ serverBundlePath, document, url }: RenderRequest): Promise<string> { const { ɵSERVER_CONTEXT, AppServerModule, renderModule, renderApplication, default: bootstrapAppFn, } = (await import(serverBundlePath)) as ServerBundleExports; assert(ɵSERVER_CONTEXT, `ɵSERVER_CONTEXT was not exported from: ${serverBundlePath}.`); const platformProviders: StaticProvider[] = [ { provide: ɵSERVER_CONTEXT, useValue: 'app-shell', }, ]; let renderAppPromise: Promise<string>; // Render platform server module if (isBootstrapFn(bootstrapAppFn)) { assert(renderApplication, `renderApplication was not exported from: ${serverBundlePath}.`); renderAppPromise = renderApplication(bootstrapAppFn, { document, url, platformProviders, }); } else { assert(renderModule, `renderModule was not exported from: ${serverBundlePath}.`); const moduleClass = bootstrapAppFn || AppServerModule; assert( moduleClass, `Neither an AppServerModule nor a bootstrapping function was exported from: ${serverBundlePath}.`, ); renderAppPromise = renderModule(moduleClass, { document, url, extraProviders: platformProviders, }); } // The below should really handled by the framework!!!. // See: https://github.com/angular/angular/issues/51549 let timer: NodeJS.Timeout; const renderingTimeout = new Promise<never>( (_, reject) => (timer = setTimeout( () => reject( new Error(`Page ${new URL(url, 'resolve://').pathname} did not render in 30 seconds.`), ), 30_000, )), ); return Promise.race([renderAppPromise, renderingTimeout]).finally(() => clearTimeout(timer)); } function isBootstrapFn(value: unknown): value is () => Promise<ApplicationRef> { // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property: return typeof value === 'function' && !('ɵmod' in value); } /** * Initializes the worker when it is first created by loading the Zone.js package * into the worker instance. * * @returns A promise resolving to the render function of the worker. */ async function initialize() { // Setup Zone.js await import(zonePackage); // Return the render function for use return render; } /** * The default export will be the promise returned by the initialize function. * This is awaited by piscina prior to using the Worker. */ export default initialize();
{ "commit_id": "b893a6ae9", "end_byte": 4523, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/app-shell/render-worker.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/prerender/routes-extractor-worker.ts_0_2541
/** * @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 { ApplicationRef, Type } from '@angular/core'; import type { ɵgetRoutesFromAngularRouterConfig } from '@angular/ssr'; import assert from 'node:assert'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { workerData } from 'node:worker_threads'; export interface RoutesExtractorWorkerData { zonePackage: string; indexFile: string; outputPath: string; serverBundlePath: string; } interface ServerBundleExports { /** NgModule to render. */ AppServerModule?: Type<unknown>; /** Standalone application bootstrapping function. */ default?: (() => Promise<ApplicationRef>) | Type<unknown>; /** Method to extract routes from the router config. */ ɵgetRoutesFromAngularRouterConfig: typeof ɵgetRoutesFromAngularRouterConfig; } const { zonePackage, serverBundlePath, outputPath, indexFile } = workerData as RoutesExtractorWorkerData; async function extract(): Promise<string[]> { const { AppServerModule, ɵgetRoutesFromAngularRouterConfig: getRoutesFromAngularRouterConfig, default: bootstrapAppFn, } = (await import(serverBundlePath)) as ServerBundleExports; const browserIndexInputPath = path.join(outputPath, indexFile); const document = await fs.promises.readFile(browserIndexInputPath, 'utf8'); const bootstrapAppFnOrModule = bootstrapAppFn || AppServerModule; assert( bootstrapAppFnOrModule, `The file "${serverBundlePath}" does not have a default export for an AppServerModule or a bootstrapping function.`, ); const routes: string[] = []; const { routes: extractRoutes } = await getRoutesFromAngularRouterConfig( bootstrapAppFnOrModule, document, new URL('http://localhost'), ); for (const { route, redirectTo } of extractRoutes) { if (redirectTo === undefined && !/[:*]/.test(route)) { routes.push(route); } } return routes; } /** * Initializes the worker when it is first created by loading the Zone.js package * into the worker instance. * * @returns A promise resolving to the extract function of the worker. */ async function initialize() { // Setup Zone.js await import(zonePackage); return extract; } /** * The default export will be the promise returned by the initialize function. * This is awaited by piscina prior to using the Worker. */ export default initialize();
{ "commit_id": "b893a6ae9", "end_byte": 2541, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/prerender/routes-extractor-worker.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/prerender/works_spec.ts_0_6893
/** * @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'; import { join, normalize, virtualFs } from '@angular-devkit/core'; import { createArchitect, host } from '../../testing/test-utils'; describe('Prerender Builder', () => { const target = { project: 'app', target: 'prerender' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; const routeFiles = { 'src/styles.css': ` p { color: #000 } `, 'src/app/foo/foo.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-foo', standalone: false, template: '<p>foo works!</p>', }) export class FooComponent {} `, 'src/app/app.module.ts': ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { FooComponent } from './foo/foo.component'; const routes: Routes = [ { path: 'foo', component: FooComponent }]; @NgModule({ declarations: [ AppComponent, FooComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes) ], bootstrap: [AppComponent] }) export class AppModule { } `, 'src/app/app.component.html': ` app is running! <router-outlet></router-outlet> `, }; host.writeMultipleFiles(routeFiles); }); afterEach(async () => host.restore().toPromise()); it('fails with error when no routes are provided', async () => { const run = await architect.scheduleTarget(target, { routes: [], discoverRoutes: false }); await run.stop(); await expectAsync(run.result).toBeRejectedWith( jasmine.objectContaining({ message: jasmine.stringMatching(/Could not find any routes to prerender/), }), ); }); it('should generate output for route when provided', async () => { const run = await architect.scheduleTarget(target, { routes: ['foo'] }); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const content = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/foo/index.html')), ); expect(content).toContain('foo works!'); expect(content).toContain('ng-server-context="ssg"'); }); it(`should generate routes and backup 'index.html' when route is ''`, async () => { const run = await architect.scheduleTarget(target, { routes: ['foo', ''] }); const output = await run.result; await run.stop(); expect(output.success).toBe(true); let content = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/foo/index.html')), ); expect(content).toContain('foo works!'); content = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/index.original.html')), ); expect(content).not.toContain('<router-outlet'); content = virtualFs.fileBufferToString(host.scopedSync().read(normalize('dist/index.html'))); expect(content).toContain('<router-outlet'); }); it('should generate output for routes when provided with a file', async () => { await host .write( join(host.root(), 'routes-file.txt'), virtualFs.stringToFileBuffer(['/foo', '/'].join('\n')), ) .toPromise(); const run = await architect.scheduleTarget(target, { routes: ['/foo', '/'], routesFile: './routes-file.txt', }); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const fooContent = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/foo/index.html')), ); const appContent = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/index.html')), ); expect(appContent).toContain('app is running!'); expect(appContent).toContain('ng-server-context="ssg"'); expect(fooContent).toContain('foo works!'); expect(fooContent).toContain('ng-server-context="ssg"'); }); it('should halt execution if a route file is given but does not exist.', async () => { const run = await architect.scheduleTarget(target, { routesFile: './nonexistent-file.txt', }); await run.stop(); await expectAsync(run.result).toBeRejectedWith( jasmine.objectContaining({ message: jasmine.stringMatching(/no such file or directory/) }), ); }); it('should guess routes to prerender when discoverRoutes is set to true.', async () => { const run = await architect.scheduleTarget(target, { routes: [''], discoverRoutes: true, }); const output = await run.result; const fooContent = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/foo/index.html')), ); const appContent = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/index.html')), ); await run.stop(); expect(output.success).toBe(true); expect(appContent).toContain('app is running!'); expect(appContent).toContain('ng-server-context="ssg"'); expect(fooContent).toContain('foo works!'); expect(fooContent).toContain('ng-server-context="ssg"'); }); it('should generate service-worker', async () => { const run = await architect.scheduleTarget(target, { routes: ['foo'], browserTarget: 'app:build:sw,production', }); const output = await run.result; await run.stop(); console.log(output.error); expect(output.success).toBe(true); expect(host.scopedSync().exists(normalize('dist/ngsw.json'))).toBeTrue(); }); it('should inline critical css for route', async () => { const run = await architect.scheduleTarget( { ...target, configuration: 'production' }, { routes: ['foo'] }, ); const output = await run.result; await run.stop(); expect(output.success).toBe(true); const content = virtualFs.fileBufferToString( host.scopedSync().read(normalize('dist/foo/index.html')), ); expect(content).toMatch( /<style>p{color:#000}<\/style><link rel="stylesheet" href="styles\.\w+\.css" media="print" onload="this\.media='all'">/, ); // Validate that beasties does not process already critical css inlined stylesheets. expect(content).not.toContain(`onload="this.media='print'">`); expect(content).not.toContain(`media="print"></noscript>`); }); });
{ "commit_id": "b893a6ae9", "end_byte": 6893, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/prerender/works_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/prerender/index.ts_0_9075
/** * @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 { BuilderContext, BuilderOutput, createBuilder, targetFromTargetString, } from '@angular-devkit/architect'; import * as fs from 'fs'; import { readFile } from 'node:fs/promises'; import ora from 'ora'; import * as path from 'path'; import Piscina from 'piscina'; import { normalizeOptimization } from '../../utils'; import { maxWorkers } from '../../utils/environment-options'; import { assertIsError } from '../../utils/error'; import { getIndexOutputFile } from '../../utils/webpack-browser-config'; import { BrowserBuilderOutput } from '../browser'; import { Schema as BrowserBuilderOptions } from '../browser/schema'; import { ServerBuilderOutput } from '../server'; import type { RenderOptions, RenderResult } from './render-worker'; import { RoutesExtractorWorkerData } from './routes-extractor-worker'; import { Schema } from './schema'; type PrerenderBuilderOptions = Schema; type PrerenderBuilderOutput = BuilderOutput; class RoutesSet extends Set<string> { override add(value: string): this { return super.add(value.charAt(0) === '/' ? value.slice(1) : value); } } async function getRoutes( indexFile: string, outputPath: string, serverBundlePath: string, options: PrerenderBuilderOptions, workspaceRoot: string, ): Promise<string[]> { const { routes: extraRoutes = [], routesFile, discoverRoutes } = options; const routes = new RoutesSet(extraRoutes); if (routesFile) { const routesFromFile = (await readFile(path.join(workspaceRoot, routesFile), 'utf8')).split( /\r?\n/, ); for (const route of routesFromFile) { routes.add(route); } } if (discoverRoutes) { const renderWorker = new Piscina({ filename: require.resolve('./routes-extractor-worker'), maxThreads: 1, workerData: { indexFile, outputPath, serverBundlePath, zonePackage: require.resolve('zone.js', { paths: [workspaceRoot] }), } as RoutesExtractorWorkerData, recordTiming: false, }); const extractedRoutes: string[] = await renderWorker .run({}) .finally(() => void renderWorker.destroy()); for (const route of extractedRoutes) { routes.add(route); } } if (routes.size === 0) { throw new Error('Could not find any routes to prerender.'); } return [...routes]; } /** * Schedules the server and browser builds and returns their results if both builds are successful. */ async function _scheduleBuilds( options: PrerenderBuilderOptions, context: BuilderContext, ): Promise< BuilderOutput & { serverResult?: ServerBuilderOutput; browserResult?: BrowserBuilderOutput; } > { const browserTarget = targetFromTargetString(options.browserTarget); const serverTarget = targetFromTargetString(options.serverTarget); const browserTargetRun = await context.scheduleTarget(browserTarget, { watch: false, serviceWorker: false, // todo: handle service worker augmentation }); if (browserTargetRun.info.builderName === '@angular-devkit/build-angular:application') { return { success: false, error: '"@angular-devkit/build-angular:application" has built-in prerendering capabilities. ' + 'The "prerender" option should be used instead.', }; } const serverTargetRun = await context.scheduleTarget(serverTarget, { watch: false, }); try { const [browserResult, serverResult] = await Promise.all([ browserTargetRun.result as unknown as BrowserBuilderOutput, serverTargetRun.result as unknown as ServerBuilderOutput, ]); const success = browserResult.success && serverResult.success && browserResult.baseOutputPath !== undefined; const error = browserResult.error || (serverResult.error as string); return { success, error, browserResult, serverResult }; } catch (e) { assertIsError(e); return { success: false, error: e.message }; } finally { await Promise.all([browserTargetRun.stop(), serverTargetRun.stop()]); } } /** * Renders each route and writes them to * <route>/index.html for each output path in the browser result. */ async function _renderUniversal( options: PrerenderBuilderOptions, context: BuilderContext, browserResult: BrowserBuilderOutput, serverResult: ServerBuilderOutput, browserOptions: BrowserBuilderOptions, ): Promise<PrerenderBuilderOutput> { const projectName = context.target && context.target.project; if (!projectName) { throw new Error('The builder requires a target.'); } const projectMetadata = await context.getProjectMetadata(projectName); const projectRoot = path.join( context.workspaceRoot, (projectMetadata.root as string | undefined) ?? '', ); // Users can specify a different base html file e.g. "src/home.html" const indexFile = getIndexOutputFile(browserOptions.index); const { styles: normalizedStylesOptimization } = normalizeOptimization( browserOptions.optimization, ); const zonePackage = require.resolve('zone.js', { paths: [context.workspaceRoot] }); const { baseOutputPath = '' } = serverResult; const worker = new Piscina({ filename: path.join(__dirname, 'render-worker.js'), maxThreads: maxWorkers, workerData: { zonePackage }, recordTiming: false, }); let routes: string[] | undefined; try { // We need to render the routes for each locale from the browser output. for (const { path: outputPath } of browserResult.outputs) { const localeDirectory = path.relative(browserResult.baseOutputPath, outputPath); const serverBundlePath = path.join(baseOutputPath, localeDirectory, 'main.js'); if (!fs.existsSync(serverBundlePath)) { throw new Error(`Could not find the main bundle: ${serverBundlePath}`); } routes ??= await getRoutes( indexFile, outputPath, serverBundlePath, options, context.workspaceRoot, ); const spinner = ora(`Prerendering ${routes.length} route(s) to ${outputPath}...`).start(); try { const results = (await Promise.all( routes.map((route) => { const options: RenderOptions = { indexFile, deployUrl: browserOptions.deployUrl || '', inlineCriticalCss: !!normalizedStylesOptimization.inlineCritical, minifyCss: !!normalizedStylesOptimization.minify, outputPath, route, serverBundlePath, }; return worker.run(options); }), )) as RenderResult[]; let numErrors = 0; for (const { errors, warnings } of results) { spinner.stop(); errors?.forEach((e) => context.logger.error(e)); warnings?.forEach((e) => context.logger.warn(e)); spinner.start(); numErrors += errors?.length ?? 0; } if (numErrors > 0) { throw Error(`Rendering failed with ${numErrors} worker errors.`); } } catch (error) { spinner.fail(`Prerendering routes to ${outputPath} failed.`); assertIsError(error); return { success: false, error: error.message }; } spinner.succeed(`Prerendering routes to ${outputPath} complete.`); if (browserOptions.serviceWorker) { spinner.start('Generating service worker...'); try { await augmentAppWithServiceWorker( projectRoot, context.workspaceRoot, outputPath, browserOptions.baseHref || '/', browserOptions.ngswConfigPath, ); } catch (error) { spinner.fail('Service worker generation failed.'); assertIsError(error); return { success: false, error: error.message }; } spinner.succeed('Service worker generation complete.'); } } } finally { void worker.destroy(); } return browserResult; } /** * Builds the browser and server, then renders each route in options.routes * and writes them to prerender/<route>/index.html for each output path in * the browser result. */ export async function execute( options: PrerenderBuilderOptions, context: BuilderContext, ): Promise<PrerenderBuilderOutput> { const browserTarget = targetFromTargetString(options.browserTarget); const browserOptions = (await context.getTargetOptions( browserTarget, )) as unknown as BrowserBuilderOptions; const result = await _scheduleBuilds(options, context); const { success, error, browserResult, serverResult } = result; if (!success || !browserResult || !serverResult) { return { success, error } as BuilderOutput; } return _renderUniversal(options, context, browserResult, serverResult, browserOptions); } export default createBuilder(execute);
{ "commit_id": "b893a6ae9", "end_byte": 9075, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/prerender/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/prerender/render-worker.ts_0_5136
/** * @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 { ApplicationRef, StaticProvider, Type } from '@angular/core'; import type { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server'; import assert from 'node:assert'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { workerData } from 'node:worker_threads'; export interface RenderOptions { indexFile: string; deployUrl: string; inlineCriticalCss: boolean; minifyCss: boolean; outputPath: string; serverBundlePath: string; route: string; } export interface RenderResult { errors?: string[]; warnings?: string[]; } interface ServerBundleExports { /** An internal token that allows providing extra information about the server context. */ ɵSERVER_CONTEXT?: typeof ɵSERVER_CONTEXT; /** Render an NgModule application. */ renderModule?: typeof renderModule; /** NgModule to render. */ AppServerModule?: Type<unknown>; /** Method to render a standalone application. */ renderApplication?: typeof renderApplication; /** Standalone application bootstrapping function. */ default?: (() => Promise<ApplicationRef>) | Type<unknown>; } /** * The fully resolved path to the zone.js package that will be loaded during worker initialization. * This is passed as workerData when setting up the worker via the `piscina` package. */ const { zonePackage } = workerData as { zonePackage: string; }; /** * Renders each route in routes and writes them to <outputPath>/<route>/index.html. */ async function render({ indexFile, deployUrl, minifyCss, outputPath, serverBundlePath, route, inlineCriticalCss, }: RenderOptions): Promise<RenderResult> { const result = {} as RenderResult; const browserIndexOutputPath = path.join(outputPath, indexFile); const outputFolderPath = path.join(outputPath, route); const outputIndexPath = path.join(outputFolderPath, 'index.html'); const { ɵSERVER_CONTEXT, AppServerModule, renderModule, renderApplication, default: bootstrapAppFn, } = (await import(serverBundlePath)) as ServerBundleExports; assert(ɵSERVER_CONTEXT, `ɵSERVER_CONTEXT was not exported from: ${serverBundlePath}.`); const indexBaseName = fs.existsSync(path.join(outputPath, 'index.original.html')) ? 'index.original.html' : indexFile; const browserIndexInputPath = path.join(outputPath, indexBaseName); const document = await fs.promises.readFile(browserIndexInputPath, 'utf8'); const platformProviders: StaticProvider[] = [ { provide: ɵSERVER_CONTEXT, useValue: 'ssg', }, ]; let html: string; // Render platform server module if (isBootstrapFn(bootstrapAppFn)) { assert(renderApplication, `renderApplication was not exported from: ${serverBundlePath}.`); html = await renderApplication(bootstrapAppFn, { document, url: route, platformProviders, }); } else { assert(renderModule, `renderModule was not exported from: ${serverBundlePath}.`); const moduleClass = bootstrapAppFn || AppServerModule; assert( moduleClass, `Neither an AppServerModule nor a bootstrapping function was exported from: ${serverBundlePath}.`, ); html = await renderModule(moduleClass, { document, url: route, extraProviders: platformProviders, }); } if (inlineCriticalCss) { const { InlineCriticalCssProcessor } = await import('@angular/build/private'); const inlineCriticalCssProcessor = new InlineCriticalCssProcessor({ deployUrl: deployUrl, minify: minifyCss, }); const { content, warnings, errors } = await inlineCriticalCssProcessor.process(html, { outputPath, }); result.errors = errors; result.warnings = warnings; html = content; } // This case happens when we are prerendering "/". if (browserIndexOutputPath === outputIndexPath) { const browserIndexOutputPathOriginal = path.join(outputPath, 'index.original.html'); fs.renameSync(browserIndexOutputPath, browserIndexOutputPathOriginal); } fs.mkdirSync(outputFolderPath, { recursive: true }); fs.writeFileSync(outputIndexPath, html); return result; } function isBootstrapFn(value: unknown): value is () => Promise<ApplicationRef> { // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property: return typeof value === 'function' && !('ɵmod' in value); } /** * Initializes the worker when it is first created by loading the Zone.js package * into the worker instance. * * @returns A promise resolving to the render function of the worker. */ async function initialize() { // Setup Zone.js await import(zonePackage); // Return the render function for use return render; } /** * The default export will be the promise returned by the initialize function. * This is awaited by piscina prior to using the Worker. */ export default initialize();
{ "commit_id": "b893a6ae9", "end_byte": 5136, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/prerender/render-worker.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/index.ts_0_2658
/** * @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 ApplicationBuilderOptions, buildApplication } from '@angular/build'; import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import type { Plugin } from 'esbuild'; import type { Schema as BrowserBuilderOptions } from './schema'; export type { BrowserBuilderOptions }; type OutputPathClass = Exclude<ApplicationBuilderOptions['outputPath'], string | undefined>; /** * Main execution function for the esbuild-based application builder. * The options are compatible with the Webpack-based builder. * @param userOptions The browser builder options to use when setting up the application build * @param context The Architect builder context object * @returns An async iterable with the builder result output */ export async function* buildEsbuildBrowser( userOptions: BrowserBuilderOptions, context: BuilderContext, infrastructureSettings?: { write?: boolean; }, plugins?: Plugin[], ): AsyncIterable<BuilderOutput> { // Warn about any unsupported options if (userOptions['vendorChunk']) { context.logger.warn( `The 'vendorChunk' option is not used by this builder and will be ignored.`, ); } if (userOptions['commonChunk'] === false) { context.logger.warn( `The 'commonChunk' option is always enabled by this builder and will be ignored.`, ); } if (userOptions['webWorkerTsConfig']) { context.logger.warn(`The 'webWorkerTsConfig' option is not yet supported by this builder.`); } // Convert browser builder options to application builder options const normalizedOptions = convertBrowserOptions(userOptions); // Execute the application builder yield* buildApplication(normalizedOptions, context, { codePlugins: plugins }); } export function convertBrowserOptions( options: BrowserBuilderOptions, ): Omit<ApplicationBuilderOptions, 'outputPath'> & { outputPath: OutputPathClass } { const { main: browser, outputPath, ngswConfigPath, serviceWorker, polyfills, resourcesOutputPath, ...otherOptions } = options; return { browser, serviceWorker: serviceWorker ? ngswConfigPath : false, polyfills: typeof polyfills === 'string' ? [polyfills] : polyfills, outputPath: { base: outputPath, browser: '', server: '', media: resourcesOutputPath ?? 'media', }, ...otherOptions, }; } export default createBuilder<BrowserBuilderOptions>(buildEsbuildBrowser);
{ "commit_id": "b893a6ae9", "end_byte": 2658, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/setup.ts_0_834
/** * @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 { Schema } from '../schema'; export { describeBuilder } from '../../../testing'; export const BROWSER_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:browser-esbuild', schemaPath: __dirname + '/../schema.json', }); /** * Contains all required browser builder fields. * Also disables progress reporting to minimize logging output. */ export const BASE_OPTIONS = Object.freeze<Schema>({ index: 'src/index.html', main: 'src/main.ts', outputPath: 'dist', tsConfig: 'src/tsconfig.app.json', progress: false, // Disable optimizations optimization: false, buildOptimizer: false, });
{ "commit_id": "b893a6ae9", "end_byte": 834, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/setup.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/assets_spec.ts_0_3988
/** * @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 { buildEsbuildBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildEsbuildBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "assets"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); it('supports an empty array value', async () => { harness.useTarget('build', { ...BASE_OPTIONS, assets: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('supports mixing shorthand and longhand syntax', async () => { await harness.writeFile('src/files/test.svg', '<svg></svg>'); await harness.writeFile('src/files/another.file', 'asset file'); await harness.writeFile('src/extra.file', 'extra file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/extra.file', { glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.file').content.toBe('extra file'); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); describe('shorthand syntax', () => { it('copies a single asset', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('copies multiple assets', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/test.svg', 'src/another.file'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies an asset with directory and maintains directory in output', async () => { await harness.writeFile('src/subdirectory/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/subdirectory/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('does not fail if asset does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').toNotExist(); }); it('fail if asset path is not within project source root', async () => { await harness.writeFile('test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['test.svg'], }); const { error } = await harness.executeOnce({ outputLogsOnException: false }); expect(error?.message).toMatch('path must start with the project source root'); harness.expectFile('dist/test.svg').toNotExist(); }); });
{ "commit_id": "b893a6ae9", "end_byte": 3988, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/assets_spec.ts_3994_12715
describe('longhand syntax', () => { it('copies a single asset', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('copies multiple assets as separate entries', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [ { glob: 'test.svg', input: 'src', output: '.' }, { glob: 'another.file', input: 'src', output: '.' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a single entry glob pattern', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '{test.svg,another.file}', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a wildcard glob pattern', async () => { await harness.writeFile('src/files/test.svg', '<svg></svg>'); await harness.writeFile('src/files/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a recursive wildcard glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); }); it('automatically ignores "." prefixed files when using wildcard glob pattern', async () => { await harness.writeFile('src/files/.gitkeep', ''); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/.gitkeep').toNotExist(); }); it('supports ignoring a specific file when using a glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['another.file'] }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').toNotExist(); harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); }); it('supports ignoring with a glob pattern when using a glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['**/*.file'] }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').toNotExist(); harness.expectFile('dist/nested/extra.file').toNotExist(); }); it('copies an asset with directory and maintains directory in output', async () => { await harness.writeFile('src/subdirectory/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'subdirectory/test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('does not fail if asset does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').toNotExist(); }); it('uses project output path when output option is empty string', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('uses project output path when output option is "."', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('uses project output path when output option is "/"', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '/' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('creates a project output sub-path when output option path does not exist', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: 'subdirectory' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('fails if output option is not within project output path', async () => { await harness.writeFile('test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '..' }], }); const { error } = await harness.executeOnce({ outputLogsOnException: false }); expect(error?.message).toMatch( 'An asset cannot be written to a location outside of the output path', ); harness.expectFile('dist/test.svg').toNotExist(); }); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 12715, "start_byte": 3994, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/main_spec.ts_0_2761
/** * @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 { buildEsbuildBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildEsbuildBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "main"', () => { it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/main.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').toExist(); harness.expectFile('dist/index.html').toExist(); }); it('uses a provided JavaScript file', async () => { await harness.writeFile('src/main.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/main.js', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').toExist(); harness.expectFile('dist/index.html').toExist(); harness.expectFile('dist/main.js').content.toContain('console.log("main")'); }); it('fails and shows an error when file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/missing.ts', }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Could not resolve "') }), ); harness.expectFile('dist/main.js').toNotExist(); harness.expectFile('dist/index.html').toNotExist(); }); it('throws an error when given an empty string', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: '', }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error?.message).toContain('cannot be an empty string'); }); it('resolves an absolute path as relative inside the workspace root', async () => { await harness.writeFile('file.mjs', `console.log('Hello!');`); harness.useTarget('build', { ...BASE_OPTIONS, main: '/file.mjs', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Always uses the name `main.js` for the `main` option. harness.expectFile('dist/main.js').toExist(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2761, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/main_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/deploy-url_spec.ts_0_2934
/** * @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 { buildEsbuildBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildEsbuildBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "deployUrl"', () => { beforeEach(async () => { // Add a global stylesheet to test link elements await harness.writeFile('src/styles.css', '/* Global styles */'); // Reduce the input index HTML to a single line to simplify comparing await harness.writeFile( 'src/index.html', '<html><head><base href="/"></head><body><app-root></app-root></body></html>', ); }); it('should update script src and link href attributes when option is set to relative URL', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], deployUrl: 'deployUrl/', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toEqual( `<html><head><base href="/"><link rel="stylesheet" href="deployUrl/styles.css"></head>` + `<body><app-root></app-root>` + `<script src="deployUrl/main.js" type="module"></script></body></html>`, ); }); it('should update script src and link href attributes when option is set to absolute URL', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], deployUrl: 'https://example.com/some/path/', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toEqual( `<html><head><base href="/"><link rel="stylesheet" href="https://example.com/some/path/styles.css"></head>` + `<body><app-root></app-root>` + `<script src="https://example.com/some/path/main.js" type="module"></script></body></html>`, ); }); it('should update resources component stylesheets to reference deployURL', async () => { await harness.writeFile('src/app/test.svg', '<svg></svg>'); await harness.writeFile( 'src/app/app.component.css', `* { background-image: url('./test.svg'); }`, ); harness.useTarget('build', { ...BASE_OPTIONS, deployUrl: 'https://example.com/some/path/', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/main.js') .content.toContain('background-image: url("https://example.com/some/path/media/test.svg")'); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 2934, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/deploy-url_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/delete-output-path_spec.ts_0_1781
/** * @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 { buildEsbuildBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildEsbuildBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "deleteOutputPath"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); // Add file in output await harness.writeFile('dist/dummy.txt', ''); }); it(`should delete the output files when 'deleteOutputPath' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/dummy.txt').toNotExist(); }); it(`should delete the output files when 'deleteOutputPath' is not set`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/dummy.txt').toNotExist(); }); it(`should not delete the output files when 'deleteOutputPath' is false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/dummy.txt').toExist(); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 1781, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser-esbuild/tests/options/delete-output-path_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/protractor/works_spec.ts_0_4356
/** * @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'; import { JsonObject, normalize } from '@angular-devkit/core'; import { createArchitect, host, protractorTargetSpec } from '../../testing/test-utils'; describe('Protractor Builder', () => { let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(() => host.restore().toPromise()); it('executes tests with automatic dev server usage', async () => { const run = await architect.scheduleTarget(protractorTargetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); it('fails with no devServerTarget and no standalone server', async () => { const overrides = { devServerTarget: undefined } as unknown as JsonObject; const run = await architect.scheduleTarget(protractorTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); await run.stop(); }); it('overrides protractor specs', async () => { host .scopedSync() .rename(normalize('./e2e/app.e2e-spec.ts'), normalize('./e2e/renamed-app.e2e.spec.ts')); const overrides = { specs: ['./e2e/renamed-app.e2e.spec.ts'] }; const run = await architect.scheduleTarget(protractorTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); it('overrides protractor suites', async () => { host .scopedSync() .rename(normalize('./e2e/app.e2e-spec.ts'), normalize('./e2e/renamed-app.e2e-spec.ts')); // Suites block needs to be added in the protractor.conf.js file to test suites host.replaceInFile( 'protractor.conf.js', `allScriptsTimeout: 11000,`, ` allScriptsTimeout: 11000, suites: { app: './e2e/app.e2e-spec.ts' }, `, ); const overrides = { suite: 'app' }; const run = await architect.scheduleTarget(protractorTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); it('supports automatic port assignment (port = 0)', async () => { const overrides = { port: 0 }; const run = await architect.scheduleTarget(protractorTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); it('supports dev server builder with browser builder base HREF option', async () => { host.replaceInFile( 'angular.json', '"main": "src/main.ts",', '"main": "src/main.ts", "baseHref": "/base/",', ); // Need to reset architect to use the modified config architect = (await createArchitect(host.root())).architect; const run = await architect.scheduleTarget(protractorTargetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); it('supports running tests by pattern', async () => { host.writeMultipleFiles({ 'e2e/app.e2e-spec.ts': ` it('should succeed', () => expect(true).toBeTruthy()); it('should fail', () => expect(false).toBeTruthy()); `, }); const overrides = { grep: 'succeed' }; const run = await architect.scheduleTarget(protractorTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); it('supports running tests excluding a pattern', async () => { host.writeMultipleFiles({ 'e2e/app.e2e-spec.ts': ` it('should succeed', () => expect(true).toBeTruthy()); it('should fail', () => expect(false).toBeTruthy()); `, }); const overrides = { grep: 'fail', invertGrep: true }; const run = await architect.scheduleTarget(protractorTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); });
{ "commit_id": "b893a6ae9", "end_byte": 4356, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/protractor/works_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/protractor/index.ts_0_5790
/** * @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, BuilderOutput, createBuilder, targetFromTargetString, } from '@angular-devkit/architect'; import { json, tags } from '@angular-devkit/core'; import { resolve } from 'path'; import * as url from 'url'; import { runModuleAsObservableFork } from '../../utils'; import { assertIsError } from '../../utils/error'; import { DevServerBuilderOptions } from '../dev-server/index'; import { Schema as ProtractorBuilderOptions } from './schema'; interface JasmineNodeOpts { jasmineNodeOpts: { grep?: string; invertGrep?: boolean; }; } function runProtractor(root: string, options: ProtractorBuilderOptions): Promise<BuilderOutput> { const additionalProtractorConfig: Partial<ProtractorBuilderOptions> & Partial<JasmineNodeOpts> = { baseUrl: options.baseUrl, specs: options.specs && options.specs.length ? options.specs : undefined, suite: options.suite, jasmineNodeOpts: { grep: options.grep, invertGrep: options.invertGrep, }, }; // TODO: Protractor manages process.exit itself, so this target will allways quit the // process. To work around this we run it in a subprocess. // https://github.com/angular/protractor/issues/4160 return runModuleAsObservableFork(root, 'protractor/built/launcher', 'init', [ resolve(root, options.protractorConfig), additionalProtractorConfig, ]).toPromise() as Promise<BuilderOutput>; } async function updateWebdriver() { // The webdriver-manager update command can only be accessed via a deep import. const webdriverDeepImport = 'webdriver-manager/built/lib/cmds/update'; let path; try { const protractorPath = require.resolve('protractor'); path = require.resolve(webdriverDeepImport, { paths: [protractorPath] }); } catch (error) { assertIsError(error); if (error.code !== 'MODULE_NOT_FOUND') { throw error; } } if (!path) { throw new Error(tags.stripIndents` Cannot automatically find webdriver-manager to update. Update webdriver-manager manually and run 'ng e2e --no-webdriver-update' instead. `); } const webdriverUpdate = await import(path); // const webdriverUpdate = await import(path) as typeof import ('webdriver-manager/built/lib/cmds/update'); // run `webdriver-manager update --standalone false --gecko false --quiet` // if you change this, update the command comment in prev line return webdriverUpdate.program.run({ standalone: false, gecko: false, quiet: true, } as unknown as JSON); } export type { ProtractorBuilderOptions }; /** * @experimental Direct usage of this function is considered experimental. */ export async function execute( options: ProtractorBuilderOptions, context: BuilderContext, ): Promise<BuilderOutput> { context.logger.warn( 'Protractor has reached end-of-life and is no longer supported by the Angular team. The `protractor` builder will be removed in a future Angular major version. For additional information and alternatives, please see https://blog.angular.dev/protractor-deprecation-update-august-2023-2beac7402ce0.', ); // ensure that only one of these options is used if (options.devServerTarget && options.baseUrl) { throw new Error(tags.stripIndents` The 'baseUrl' option cannot be used with 'devServerTarget'. When present, 'devServerTarget' will be used to automatically setup 'baseUrl' for Protractor. `); } if (options.webdriverUpdate) { await updateWebdriver(); } let baseUrl = options.baseUrl; let server; try { if (options.devServerTarget) { const target = targetFromTargetString(options.devServerTarget); const serverOptions = await context.getTargetOptions(target); const overrides = { watch: false, liveReload: false, } as DevServerBuilderOptions & json.JsonObject; if (options.host !== undefined) { overrides.host = options.host; } else if (typeof serverOptions.host === 'string') { options.host = serverOptions.host; } else { options.host = overrides.host = 'localhost'; } if (options.port !== undefined) { overrides.port = options.port; } else if (typeof serverOptions.port === 'number') { options.port = serverOptions.port; } server = await context.scheduleTarget(target, overrides); const result = await server.result; if (!result.success) { return { success: false }; } if (typeof serverOptions.publicHost === 'string') { let publicHost = serverOptions.publicHost; if (!/^\w+:\/\//.test(publicHost)) { publicHost = `${serverOptions.ssl ? 'https' : 'http'}://${publicHost}`; } const clientUrl = url.parse(publicHost); baseUrl = url.format(clientUrl); } else if (typeof result.baseUrl === 'string') { baseUrl = result.baseUrl; } else if (typeof result.port === 'number') { baseUrl = url.format({ protocol: serverOptions.ssl ? 'https' : 'http', hostname: options.host, port: result.port.toString(), }); } } // Like the baseUrl in protractor config file when using the API we need to add // a trailing slash when provide to the baseUrl. if (baseUrl && !baseUrl.endsWith('/')) { baseUrl += '/'; } return await runProtractor(context.workspaceRoot, { ...options, baseUrl }); } catch { return { success: false }; } finally { await server?.stop(); } } export default createBuilder<ProtractorBuilderOptions>(execute);
{ "commit_id": "b893a6ae9", "end_byte": 5790, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/protractor/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/ng-packagr/works_spec.ts_0_3480
/** * @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'; import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; import { TestProjectHost, TestingArchitectHost } from '@angular-devkit/architect/testing'; import { getSystemPath, join, normalize, schema, virtualFs, workspaces, } from '@angular-devkit/core'; import { debounceTime, map, take, tap } from 'rxjs'; // Default timeout for large specs is 2.5 minutes. jasmine.DEFAULT_TIMEOUT_INTERVAL = 150000; describe('NgPackagr Builder', () => { const workspaceRoot = join(normalize(__dirname), `../../../test/hello-world-lib/`); const host = new TestProjectHost(workspaceRoot); let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); const registry = new schema.CoreSchemaRegistry(); registry.addPostTransform(schema.transforms.addUndefinedDefaults); const workspaceSysPath = getSystemPath(host.root()); const { workspace } = await workspaces.readWorkspace( workspaceSysPath, workspaces.createWorkspaceHost(host), ); const architectHost = new TestingArchitectHost( workspaceSysPath, workspaceSysPath, new WorkspaceNodeModulesArchitectHost(workspace, workspaceSysPath), ); architect = new Architect(architectHost, registry); }); afterEach(() => host.restore().toPromise()); it('builds and packages a library', async () => { const run = await architect.scheduleTarget({ project: 'lib', target: 'build' }); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(normalize('./dist/lib/fesm2022/lib.mjs'))).toBe(true); const content = virtualFs.fileBufferToString( host.scopedSync().read(normalize('./dist/lib/fesm2022/lib.mjs')), ); expect(content).toContain('lib works'); expect(content).toContain('ɵcmp'); }); it('rebuilds on TS file changes', async () => { const goldenValueFiles: { [path: string]: string } = { 'projects/lib/src/lib/lib.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'lib', template: 'lib update works!' }) export class LibComponent { } `, }; const run = await architect.scheduleTarget( { project: 'lib', target: 'build' }, { watch: true }, ); let buildNumber = 0; await run.output .pipe( tap((buildEvent) => expect(buildEvent.success).toBe(true)), debounceTime(1000), map(() => { const fileName = './dist/lib/fesm2022/lib.mjs'; const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); return content; }), tap((content) => { buildNumber += 1; switch (buildNumber) { case 1: expect(content).toMatch(/lib works/); host.writeMultipleFiles(goldenValueFiles); break; case 2: expect(content).toMatch(/lib update works/); break; default: break; } }), take(2), ) .toPromise(); await run.stop(); }); });
{ "commit_id": "b893a6ae9", "end_byte": 3480, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ng-packagr/works_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/ng-packagr/index.ts_0_2231
/** * @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 { purgeStaleBuildCache } from '@angular/build/private'; import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import type { NgPackagrOptions } from 'ng-packagr'; import { join, resolve } from 'node:path'; import { Observable, catchError, from, map, of, switchMap } from 'rxjs'; import { normalizeCacheOptions } from '../../utils/normalize-cache'; import { Schema as NgPackagrBuilderOptions } from './schema'; /** * @experimental Direct usage of this function is considered experimental. */ export function execute( options: NgPackagrBuilderOptions, context: BuilderContext, ): Observable<BuilderOutput> { return from( (async () => { // Purge old build disk cache. await purgeStaleBuildCache(context); const root = context.workspaceRoot; const packager = (await import('ng-packagr')).ngPackagr(); packager.forProject(resolve(root, options.project)); if (options.tsConfig) { packager.withTsConfig(resolve(root, options.tsConfig)); } const projectName = context.target?.project; if (!projectName) { throw new Error('The builder requires a target.'); } const metadata = await context.getProjectMetadata(projectName); const { enabled: cacheEnabled, path: cacheDirectory } = normalizeCacheOptions( metadata, context.workspaceRoot, ); const ngPackagrOptions: NgPackagrOptions = { cacheEnabled, poll: options.poll, cacheDirectory: join(cacheDirectory, 'ng-packagr'), }; return { packager, ngPackagrOptions }; })(), ).pipe( switchMap(({ packager, ngPackagrOptions }) => options.watch ? packager.watch(ngPackagrOptions) : packager.build(ngPackagrOptions), ), map(() => ({ success: true })), catchError((err) => of({ success: false, error: err.message })), ); } export type { NgPackagrBuilderOptions }; export default createBuilder<Record<string, string> & NgPackagrBuilderOptions>(execute);
{ "commit_id": "b893a6ae9", "end_byte": 2231, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/ng-packagr/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/jest/init-test-bed.mjs_0_815
/** * @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 */ // TODO(dgp1130): These imports likely don't resolve in stricter package environments like `pnpm`, since they are resolved relative to // `@angular-devkit/build-angular` rather than the user's workspace. Should look into virtual modules to support those use cases. import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { errorOnUnknownElements: true, errorOnUnknownProperties: true, });
{ "commit_id": "b893a6ae9", "end_byte": 815, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/jest/init-test-bed.mjs" }
angular-cli/packages/angular_devkit/build_angular/src/builders/jest/jest-global.mjs_0_858
/** * @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 */ /** * @fileoverview Zone.js requires the `jest` global to be initialized in order to know that it must patch the environment to support Jest * execution. When running ESM code, Jest does _not_ inject the global `jest` symbol, so Zone.js would not normally know it is running * within Jest as users are supposed to import from `@jest/globals` or use `import.meta.jest`. Zone.js is not currently aware of this, so we * manually set this global to get Zone.js to run correctly. * * TODO(dgp1130): Update Zone.js to directly support Jest ESM executions so we can drop this. */ // eslint-disable-next-line no-undef globalThis.jest = import.meta.jest;
{ "commit_id": "b893a6ae9", "end_byte": 858, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/jest/jest-global.mjs" }
angular-cli/packages/angular_devkit/build_angular/src/builders/jest/jest.config.mjs_0_396
/** * @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 */ // Empty config file, everything is specified via CLI options right now. // This file is used just so Jest doesn't accidentally inherit a custom user-specified Jest config. export default {};
{ "commit_id": "b893a6ae9", "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/jest/jest.config.mjs" }
angular-cli/packages/angular_devkit/build_angular/src/builders/jest/index.ts_0_8881
/** * @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 { ResultKind, buildApplicationInternal } from '@angular/build/private'; import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import { execFile as execFileCb } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import * as fs from 'node:fs/promises'; import * as path from 'node:path'; import { promisify } from 'node:util'; import { colors } from '../../utils/color'; import { findTestFiles } from '../../utils/test-files'; import { OutputHashing } from '../browser-esbuild/schema'; import { writeTestFiles } from '../web-test-runner/write-test-files'; import { normalizeOptions } from './options'; import { Schema as JestBuilderSchema } from './schema'; const execFile = promisify(execFileCb); /** Main execution function for the Jest builder. */ export default createBuilder( async (schema: JestBuilderSchema, context: BuilderContext): Promise<BuilderOutput> => { context.logger.warn( 'NOTE: The Jest builder is currently EXPERIMENTAL and not ready for production use.', ); const options = normalizeOptions(schema); const testOut = path.join(context.workspaceRoot, 'dist/test-out', randomUUID()); // TODO(dgp1130): Hide in temp directory. // Verify Jest installation and get the path to it's binary. // We need to `node_modules/.bin/jest`, but there is no means to resolve that directly. Fortunately Jest's `package.json` exports the // same file at `bin/jest`, so we can just resolve that instead. const jest = resolveModule('jest/bin/jest'); if (!jest) { return { success: false, // TODO(dgp1130): Display a more accurate message for non-NPM users. error: 'Jest is not installed, most likely you need to run `npm install jest --save-dev` in your project.', }; } // Verify that JSDom is installed in the project. const environment = resolveModule('jest-environment-jsdom'); if (!environment) { return { success: false, // TODO(dgp1130): Display a more accurate message for non-NPM users. error: '`jest-environment-jsdom` is not installed. Install it with `npm install jest-environment-jsdom --save-dev`.', }; } const [testFiles, customConfig] = await Promise.all([ findTestFiles(options.include, options.exclude, context.workspaceRoot), findCustomJestConfig(context.workspaceRoot), ]); // Warn if a custom Jest configuration is found. We won't use it, so if a developer is trying to use a custom config, this hopefully // makes a better experience than silently ignoring the configuration. // Ideally, this would be a hard error. However a Jest config could exist for testing other files in the workspace outside of Angular // CLI, so we likely can't produce a hard error in this situation without an opt-out. if (customConfig) { context.logger.warn( 'A custom Jest config was found, but this is not supported by `@angular-devkit/build-angular:jest` and will be' + ` ignored: ${customConfig}. This is an experiment to see if completely abstracting away Jest's configuration is viable. Please` + ` consider if your use case can be met without directly modifying the Jest config. If this is a major obstacle for your use` + ` case, please post it in this issue so we can collect feedback and evaluate: https://github.com/angular/angular-cli/issues/25434.`, ); } // Build all the test files. const jestGlobal = path.join(__dirname, 'jest-global.mjs'); const initTestBed = path.join(__dirname, 'init-test-bed.mjs'); const buildResult = await first( buildApplicationInternal( { // Build all the test files and also the `jest-global` and `init-test-bed` scripts. entryPoints: new Set([...testFiles, jestGlobal, initTestBed]), tsConfig: options.tsConfig, polyfills: options.polyfills ?? ['zone.js', 'zone.js/testing'], outputPath: testOut, aot: false, index: false, outputHashing: OutputHashing.None, outExtension: 'mjs', // Force native ESM. optimization: false, sourceMap: { scripts: true, styles: false, vendor: false, }, }, context, ), ); if (buildResult.kind === ResultKind.Failure) { return { success: false }; } else if (buildResult.kind !== ResultKind.Full) { return { success: false, error: 'A full build result is required from the application builder.', }; } // Write test files await writeTestFiles(buildResult.files, testOut); // Execute Jest on the built output directory. const jestProc = execFile(process.execPath, [ '--experimental-vm-modules', jest, `--rootDir="${testOut}"`, `--config=${path.join(__dirname, 'jest.config.mjs')}`, '--testEnvironment=jsdom', // TODO(dgp1130): Enable cache once we have a mechanism for properly clearing / disabling it. '--no-cache', // Run basically all files in the output directory, any excluded files were already dropped by the build. `--testMatch="<rootDir>/**/*.mjs"`, // Load polyfills and initialize the environment before executing each test file. // IMPORTANT: Order matters here. // First, we execute `jest-global.mjs` to initialize the `jest` global variable. // Second, we execute user polyfills, including `zone.js` and `zone.js/testing`. This is dependent on the Jest global so it can patch // the environment for fake async to work correctly. // Third, we initialize `TestBed`. This is dependent on fake async being set up correctly beforehand. `--setupFilesAfterEnv="<rootDir>/jest-global.mjs"`, ...(options.polyfills ? [`--setupFilesAfterEnv="<rootDir>/polyfills.mjs"`] : []), `--setupFilesAfterEnv="<rootDir>/init-test-bed.mjs"`, // Don't run any infrastructure files as tests, they are manually loaded where needed. `--testPathIgnorePatterns="<rootDir>/jest-global\\.mjs"`, ...(options.polyfills ? [`--testPathIgnorePatterns="<rootDir>/polyfills\\.mjs"`] : []), `--testPathIgnorePatterns="<rootDir>/init-test-bed\\.mjs"`, // Skip shared chunks, as they are not entry points to tests. `--testPathIgnorePatterns="<rootDir>/chunk-.*\\.mjs"`, // Optionally enable color. ...(colors.enabled ? ['--colors'] : []), ]); // Stream test output to the terminal. jestProc.child.stdout?.on('data', (chunk) => { context.logger.info(chunk); }); jestProc.child.stderr?.on('data', (chunk) => { // Write to stderr directly instead of `context.logger.error(chunk)` because the logger will overwrite Jest's coloring information. process.stderr.write(chunk); }); try { await jestProc; } catch (error) { // No need to propagate error message, already piped to terminal output. // TODO(dgp1130): Handle process spawning failures. return { success: false }; } return { success: true }; }, ); /** Returns the first item yielded by the given generator and cancels the execution. */ async function first<T>(generator: AsyncIterable<T>): Promise<T> { for await (const value of generator) { return value; } throw new Error('Expected generator to emit at least once.'); } /** Safely resolves the given Node module string. */ function resolveModule(module: string): string | undefined { try { return require.resolve(module); } catch { return undefined; } } /** Returns whether or not the provided directory includes a Jest configuration file. */ async function findCustomJestConfig(dir: string): Promise<string | undefined> { const entries = await fs.readdir(dir, { withFileTypes: true }); // Jest supports many file extensions (`js`, `ts`, `cjs`, `cts`, `json`, etc.) Just look // for anything with that prefix. const config = entries.find((entry) => entry.isFile() && entry.name.startsWith('jest.config.')); if (config) { return path.join(dir, config.name); } // Jest also supports a `jest` key in `package.json`, look for a config there. const packageJsonPath = path.join(dir, 'package.json'); let packageJson: string | undefined; try { packageJson = await fs.readFile(packageJsonPath, 'utf8'); } catch { return undefined; // No package.json, therefore no Jest configuration in it. } const json = JSON.parse(packageJson) as { jest?: unknown }; if ('jest' in json) { return packageJsonPath; } return undefined; }
{ "commit_id": "b893a6ae9", "end_byte": 8881, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/jest/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/jest/options.ts_0_1045
/** * @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 { Schema as JestBuilderSchema } from './schema'; /** * Options supported for the Jest builder. The schema is an approximate * representation of the options type, but this is a more precise version. */ export type JestBuilderOptions = JestBuilderSchema & { include: string[]; exclude: string[]; }; /** * Normalizes input options validated by the schema to a more precise and useful * options type in {@link JestBuilderOptions}. */ export function normalizeOptions(schema: JestBuilderSchema): JestBuilderOptions { return { // Options with default values can't actually be null, even if the types say so. /* eslint-disable @typescript-eslint/no-non-null-assertion */ include: schema.include!, exclude: schema.exclude!, /* eslint-enable @typescript-eslint/no-non-null-assertion */ ...schema, }; }
{ "commit_id": "b893a6ae9", "end_byte": 1045, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/jest/options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/jest/tests/options.ts_0_446
/** * @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 { JestBuilderOptions } from '../options'; /** Default options to use for most tests. */ export const BASE_OPTIONS = Object.freeze<JestBuilderOptions>({ include: ['**/*.spec.ts'], exclude: [], tsConfig: 'tsconfig.spec.json', });
{ "commit_id": "b893a6ae9", "end_byte": 446, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/jest/tests/options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/webpack-diagnostics.ts_0_576
/** * @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 { Compilation } from 'webpack'; export function addWarning(compilation: Compilation, message: string): void { compilation.warnings.push(new compilation.compiler.webpack.WebpackError(message)); } export function addError(compilation: Compilation, message: string): void { compilation.errors.push(new compilation.compiler.webpack.WebpackError(message)); }
{ "commit_id": "b893a6ae9", "end_byte": 576, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/webpack-diagnostics.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/package-version.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 */ export const VERSION: string = require('../../package.json').version;
{ "commit_id": "b893a6ae9", "end_byte": 274, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/package-version.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/spinner.ts_0_1284
/** * @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 ora from 'ora'; import { colors } from './color'; import { isTTY } from './tty'; export class Spinner { private readonly spinner: ora.Ora; /** When false, only fail messages will be displayed. */ enabled = true; readonly #isTTY = isTTY(); constructor(text?: string) { this.spinner = ora({ text: text === undefined ? undefined : text + '\n', // The below 2 options are needed because otherwise CTRL+C will be delayed // when the underlying process is sync. hideCursor: false, discardStdin: false, isEnabled: this.#isTTY, }); } set text(text: string) { this.spinner.text = text; } get isSpinning(): boolean { return this.spinner.isSpinning || !this.#isTTY; } succeed(text?: string): void { if (this.enabled) { this.spinner.succeed(text); } } fail(text?: string): void { this.spinner.fail(text && colors.redBright(text)); } stop(): void { this.spinner.stop(); } start(text?: string): void { if (this.enabled) { this.spinner.start(text); } } }
{ "commit_id": "b893a6ae9", "end_byte": 1284, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/spinner.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-polyfills.ts_0_727
/** * @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 { existsSync } from 'fs'; import { resolve } from 'path'; export function normalizePolyfills( polyfills: string[] | string | undefined, root: string, ): string[] { if (!polyfills) { return []; } const polyfillsList = Array.isArray(polyfills) ? polyfills : [polyfills]; return polyfillsList.map((p) => { const resolvedPath = resolve(root, p); // If file doesn't exist, let the bundle resolve it using node module resolution. return existsSync(resolvedPath) ? resolvedPath : p; }); }
{ "commit_id": "b893a6ae9", "end_byte": 727, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-polyfills.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/url_spec.ts_0_979
/** * @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 { urlJoin } from './url'; describe('urlJoin', () => { it('should work with absolute url with trailing slash', () => { expect(urlJoin('http://foo.com/', '/one/')).toBe('http://foo.com/one/'); }); it('should work with absolute url without trailing slash', () => { expect(urlJoin('http://foo.com', '/one')).toBe('http://foo.com/one'); }); it('should work with absolute url without slashes', () => { expect(urlJoin('http://foo.com', 'one', 'two')).toBe('http://foo.com/one/two'); }); it('should work with relative url without slashes', () => { expect(urlJoin('one', 'two', 'three')).toBe('one/two/three'); }); it('should keep trailing slash if empty path is provided', () => { expect(urlJoin('one/', '')).toBe('one/'); }); });
{ "commit_id": "b893a6ae9", "end_byte": 979, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/url_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/i18n-webpack.ts_0_4783
/** * @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 I18nOptions, createI18nOptions, createTranslationLoader, loadTranslations, } from '@angular/build/private'; import { BuilderContext } from '@angular-devkit/architect'; import fs from 'node:fs'; import { createRequire } from 'node:module'; import os from 'node:os'; import path from 'node:path'; import { Schema as BrowserBuilderSchema } from '../builders/browser/schema'; import { Schema as ServerBuilderSchema } from '../builders/server/schema'; import { readTsconfig } from '../utils/read-tsconfig'; /** * The base module location used to search for locale specific data. */ const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global'; // Re-export for use within Webpack related builders export { I18nOptions, loadTranslations }; export async function configureI18nBuild<T extends BrowserBuilderSchema | ServerBuilderSchema>( context: BuilderContext, options: T, ): Promise<{ buildOptions: T; i18n: I18nOptions; }> { if (!context.target) { throw new Error('The builder requires a target.'); } const buildOptions = { ...options }; const tsConfig = await readTsconfig(buildOptions.tsConfig, context.workspaceRoot); const metadata = await context.getProjectMetadata(context.target); const i18n = createI18nOptions(metadata, buildOptions.localize); // No additional processing needed if no inlining requested and no source locale defined. if (!i18n.shouldInline && !i18n.hasDefinedSourceLocale) { return { buildOptions, i18n }; } const projectRoot = path.join(context.workspaceRoot, (metadata.root as string) || ''); // The trailing slash is required to signal that the path is a directory and not a file. const projectRequire = createRequire(projectRoot + '/'); const localeResolver = (locale: string) => projectRequire.resolve(path.join(LOCALE_DATA_BASE_MODULE, locale)); // Load locale data and translations (if present) let loader; const usedFormats = new Set<string>(); for (const [locale, desc] of Object.entries(i18n.locales)) { if (!i18n.inlineLocales.has(locale) && locale !== i18n.sourceLocale) { continue; } let localeDataPath = findLocaleDataPath(locale, localeResolver); if (!localeDataPath) { const [first] = locale.split('-'); if (first) { localeDataPath = findLocaleDataPath(first.toLowerCase(), localeResolver); if (localeDataPath) { context.logger.warn( `Locale data for '${locale}' cannot be found. Using locale data for '${first}'.`, ); } } } if (!localeDataPath) { context.logger.warn( `Locale data for '${locale}' cannot be found. No locale data will be included for this locale.`, ); } else { desc.dataPath = localeDataPath; } if (!desc.files.length) { continue; } loader ??= await createTranslationLoader(); loadTranslations( locale, desc, context.workspaceRoot, loader, { warn(message) { context.logger.warn(message); }, error(message) { throw new Error(message); }, }, usedFormats, buildOptions.i18nDuplicateTranslation, ); if (usedFormats.size > 1 && tsConfig.options.enableI18nLegacyMessageIdFormat !== false) { // This limitation is only for legacy message id support (defaults to true as of 9.0) throw new Error( 'Localization currently only supports using one type of translation file format for the entire application.', ); } } // If inlining store the output in a temporary location to facilitate post-processing if (i18n.shouldInline) { // TODO: we should likely save these in the .angular directory in the next major version. // We'd need to do a migration to add the temp directory to gitignore. const tempPath = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'angular-cli-i18n-')); buildOptions.outputPath = tempPath; process.on('exit', () => { try { fs.rmSync(tempPath, { force: true, recursive: true, maxRetries: 3 }); } catch {} }); } return { buildOptions, i18n }; } function findLocaleDataPath(locale: string, resolver: (locale: string) => string): string | null { // Remove private use subtags const scrubbedLocale = locale.replace(/-x(-[a-zA-Z0-9]{1,8})+$/, ''); try { return resolver(scrubbedLocale); } catch { // fallback to known existing en-US locale data as of 14.0 return scrubbedLocale === 'en-US' ? findLocaleDataPath('en', resolver) : null; } }
{ "commit_id": "b893a6ae9", "end_byte": 4783, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/i18n-webpack.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/environment-options.ts_0_3137
/** * @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 { availableParallelism } from 'node:os'; function isDisabled(variable: string): boolean { return variable === '0' || variable.toLowerCase() === 'false'; } function isEnabled(variable: string): boolean { return variable === '1' || variable.toLowerCase() === 'true'; } function isPresent(variable: string | undefined): variable is string { return typeof variable === 'string' && variable !== ''; } // Optimization and mangling const debugOptimizeVariable = process.env['NG_BUILD_DEBUG_OPTIMIZE']; const debugOptimize = (() => { if (!isPresent(debugOptimizeVariable) || isDisabled(debugOptimizeVariable)) { return { mangle: true, minify: true, beautify: false, }; } const debugValue = { mangle: false, minify: false, beautify: true, }; if (isEnabled(debugOptimizeVariable)) { return debugValue; } for (const part of debugOptimizeVariable.split(',')) { switch (part.trim().toLowerCase()) { case 'mangle': debugValue.mangle = true; break; case 'minify': debugValue.minify = true; break; case 'beautify': debugValue.beautify = true; break; } } return debugValue; })(); const mangleVariable = process.env['NG_BUILD_MANGLE']; export const allowMangle = isPresent(mangleVariable) ? !isDisabled(mangleVariable) : debugOptimize.mangle; export const shouldBeautify = debugOptimize.beautify; export const allowMinify = debugOptimize.minify; /** * Some environments, like CircleCI which use Docker report a number of CPUs by the host and not the count of available. * This cause `Error: Call retries were exceeded` errors when trying to use them. * * @see https://github.com/nodejs/node/issues/28762 * @see https://github.com/webpack-contrib/terser-webpack-plugin/issues/143 * @see https://ithub.com/angular/angular-cli/issues/16860#issuecomment-588828079 * */ const maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS']; export const maxWorkers = isPresent(maxWorkersVariable) ? +maxWorkersVariable : Math.min(4, Math.max(availableParallelism() - 1, 1)); const parallelTsVariable = process.env['NG_BUILD_PARALLEL_TS']; export const useParallelTs = !isPresent(parallelTsVariable) || !isDisabled(parallelTsVariable); const debugPerfVariable = process.env['NG_BUILD_DEBUG_PERF']; export const debugPerformance = isPresent(debugPerfVariable) && isEnabled(debugPerfVariable); const watchRootVariable = process.env['NG_BUILD_WATCH_ROOT']; export const shouldWatchRoot = isPresent(watchRootVariable) && isEnabled(watchRootVariable); const typeCheckingVariable = process.env['NG_BUILD_TYPE_CHECK']; export const useTypeChecking = !isPresent(typeCheckingVariable) || !isDisabled(typeCheckingVariable); const buildLogsJsonVariable = process.env['NG_BUILD_LOGS_JSON']; export const useJSONBuildLogs = isPresent(buildLogsJsonVariable) && isEnabled(buildLogsJsonVariable);
{ "commit_id": "b893a6ae9", "end_byte": 3137, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/environment-options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/bundle-inline-options.ts_0_391
/** * @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 interface InlineOptions { filename: string; code: string; map?: string; outputPath: string; missingTranslation?: 'warning' | 'error' | 'ignore'; setLocale?: boolean; }
{ "commit_id": "b893a6ae9", "end_byte": 391, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/bundle-inline-options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/read-tsconfig.ts_0_1407
/** * @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 { ParsedConfiguration } from '@angular/compiler-cli'; import * as path from 'path'; import { loadEsmModule } from './load-esm'; /** * Reads and parses a given TsConfig file. * * @param tsconfigPath - An absolute or relative path from 'workspaceRoot' of the tsconfig file. * @param workspaceRoot - workspaceRoot root location when provided * it will resolve 'tsconfigPath' from this path. */ export async function readTsconfig( tsconfigPath: string, workspaceRoot?: string, ): Promise<ParsedConfiguration> { const tsConfigFullPath = workspaceRoot ? path.resolve(workspaceRoot, tsconfigPath) : tsconfigPath; // 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 { formatDiagnostics, readConfiguration } = await loadEsmModule<typeof import('@angular/compiler-cli')>('@angular/compiler-cli'); const configResult = readConfiguration(tsConfigFullPath); if (configResult.errors && configResult.errors.length) { throw new Error(formatDiagnostics(configResult.errors)); } return configResult; }
{ "commit_id": "b893a6ae9", "end_byte": 1407, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/read-tsconfig.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-file-replacements.ts_0_1892
/** * @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 { existsSync } from 'fs'; import * as path from 'path'; import { FileReplacement } from '../builders/browser/schema'; export class MissingFileReplacementException extends Error { constructor(path: string) { super(`The ${path} path in file replacements does not exist.`); } } export interface NormalizedFileReplacement { replace: string; with: string; } export function normalizeFileReplacements( fileReplacements: FileReplacement[], workspaceRoot: string, ): NormalizedFileReplacement[] { if (fileReplacements.length === 0) { return []; } const normalizedReplacement = fileReplacements.map((replacement) => normalizeFileReplacement(replacement, workspaceRoot), ); for (const { replace, with: replacementWith } of normalizedReplacement) { if (!existsSync(replacementWith)) { throw new MissingFileReplacementException(replacementWith); } if (!existsSync(replace)) { throw new MissingFileReplacementException(replace); } } return normalizedReplacement; } function normalizeFileReplacement( fileReplacement: FileReplacement, root: string, ): NormalizedFileReplacement { let replacePath: string; let withPath: string; if (fileReplacement.src && fileReplacement.replaceWith) { replacePath = fileReplacement.src; withPath = fileReplacement.replaceWith; } else if (fileReplacement.replace && fileReplacement.with) { replacePath = fileReplacement.replace; withPath = fileReplacement.with; } else { throw new Error(`Invalid file replacement: ${JSON.stringify(fileReplacement)}`); } return { replace: path.join(root, replacePath), with: path.join(root, withPath), }; }
{ "commit_id": "b893a6ae9", "end_byte": 1892, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-file-replacements.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-source-maps.ts_0_749
/** * @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 { SourceMapClass, SourceMapUnion } from '../builders/browser/schema'; export function normalizeSourceMaps(sourceMap: SourceMapUnion): SourceMapClass { const scripts = typeof sourceMap === 'object' ? sourceMap.scripts : sourceMap; const styles = typeof sourceMap === 'object' ? sourceMap.styles : sourceMap; const hidden = (typeof sourceMap === 'object' && sourceMap.hidden) || false; const vendor = (typeof sourceMap === 'object' && sourceMap.vendor) || false; return { vendor, hidden, scripts, styles, }; }
{ "commit_id": "b893a6ae9", "end_byte": 749, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-source-maps.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/run-module-as-observable-fork.ts_0_2558
/** * @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 { BuilderOutput } from '@angular-devkit/architect'; import { ForkOptions, fork } from 'child_process'; import { resolve } from 'path'; import { Observable } from 'rxjs'; import treeKill from 'tree-kill'; export function runModuleAsObservableFork( cwd: string, modulePath: string, exportName: string | undefined, // eslint-disable-next-line @typescript-eslint/no-explicit-any args: any[], ): Observable<BuilderOutput> { return new Observable((obs) => { const workerPath: string = resolve(__dirname, './run-module-worker.js'); const debugArgRegex = /--inspect(?:-brk|-port)?|--debug(?:-brk|-port)/; const execArgv = process.execArgv.filter((arg) => { // Remove debug args. // Workaround for https://github.com/nodejs/node/issues/9435 return !debugArgRegex.test(arg); }); const forkOptions: ForkOptions = { cwd, execArgv, }; // TODO: support passing in a logger to use as stdio streams // if (logger) { // (forkOptions as any).stdio = [ // 'ignore', // logger.info, // make it a stream // logger.error, // make it a stream // ]; // } const forkedProcess = fork(workerPath, undefined, forkOptions); // Cleanup. const killForkedProcess = () => { if (forkedProcess && forkedProcess.pid) { treeKill(forkedProcess.pid, 'SIGTERM'); } }; // Handle child process exit. const handleChildProcessExit = (code?: number) => { killForkedProcess(); if (code && code !== 0) { obs.error(); } obs.next({ success: true }); obs.complete(); }; forkedProcess.once('exit', handleChildProcessExit); forkedProcess.once('SIGINT', handleChildProcessExit); forkedProcess.once('uncaughtException', handleChildProcessExit); // Handle parent process exit. const handleParentProcessExit = () => { killForkedProcess(); }; process.once('exit', handleParentProcessExit); process.once('SIGINT', handleParentProcessExit); process.once('uncaughtException', handleParentProcessExit); // Run module. forkedProcess.send({ hash: '5d4b9a5c0a4e0f9977598437b0e85bcc', modulePath, exportName, args, }); // Teardown logic. When unsubscribing, kill the forked process. return killForkedProcess; }); }
{ "commit_id": "b893a6ae9", "end_byte": 2558, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/run-module-as-observable-fork.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/tailwind.ts_0_1062
/** * @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 { readdir } from 'node:fs/promises'; import { join } from 'node:path'; const tailwindConfigFiles: string[] = [ 'tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.mjs', 'tailwind.config.ts', ]; export async function findTailwindConfigurationFile( workspaceRoot: string, projectRoot: string, ): Promise<string | undefined> { const dirEntries = [projectRoot, workspaceRoot].map((root) => readdir(root, { withFileTypes: false }).then((entries) => ({ root, files: new Set(entries), })), ); // A configuration file can exist in the project or workspace root for (const { root, files } of await Promise.all(dirEntries)) { for (const potentialConfig of tailwindConfigFiles) { if (files.has(potentialConfig)) { return join(root, potentialConfig); } } } return undefined; }
{ "commit_id": "b893a6ae9", "end_byte": 1062, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/tailwind.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/url.ts_0_485
/** * @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 function urlJoin(...parts: string[]): string { const [p, ...rest] = parts; // Remove trailing slash from first part // Join all parts with `/` // Dedupe double slashes from path names return p.replace(/\/$/, '') + ('/' + rest.join('/')).replace(/\/\/+/g, '/'); }
{ "commit_id": "b893a6ae9", "end_byte": 485, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/url.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-optimization.ts_0_1307
/** * @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 { FontsClass, OptimizationClass, OptimizationUnion, StylesClass, } from '../builders/browser/schema'; export type NormalizedOptimizationOptions = Required< Omit<OptimizationClass, 'fonts' | 'styles'> > & { fonts: FontsClass; styles: StylesClass; }; export function normalizeOptimization( optimization: OptimizationUnion = true, ): NormalizedOptimizationOptions { if (typeof optimization === 'object') { const styleOptimization = !!optimization.styles; return { scripts: !!optimization.scripts, styles: typeof optimization.styles === 'object' ? optimization.styles : { minify: styleOptimization, inlineCritical: styleOptimization, }, fonts: typeof optimization.fonts === 'object' ? optimization.fonts : { inline: !!optimization.fonts, }, }; } return { scripts: optimization, styles: { minify: optimization, inlineCritical: optimization, }, fonts: { inline: optimization, }, }; }
{ "commit_id": "b893a6ae9", "end_byte": 1307, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-optimization.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/action-executor.ts_0_1942
/** * @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 Piscina from 'piscina'; import { InlineOptions } from './bundle-inline-options'; import { maxWorkers } from './environment-options'; import { I18nOptions } from './i18n-webpack'; const workerFile = require.resolve('./process-bundle'); export class BundleActionExecutor { private workerPool?: Piscina; constructor(private workerOptions: { i18n: I18nOptions }) {} private ensureWorkerPool(): Piscina { if (this.workerPool) { return this.workerPool; } this.workerPool = new Piscina({ filename: workerFile, name: 'inlineLocales', workerData: this.workerOptions, maxThreads: maxWorkers, recordTiming: false, }); return this.workerPool; } async inline( action: InlineOptions, ): Promise<{ file: string; diagnostics: { type: string; message: string }[]; count: number }> { return this.ensureWorkerPool().run(action, { name: 'inlineLocales' }); } inlineAll(actions: Iterable<InlineOptions>) { return BundleActionExecutor.executeAll(actions, (action) => this.inline(action)); } private static async *executeAll<I, O>( actions: Iterable<I>, executor: (action: I) => Promise<O>, ): AsyncIterable<O> { const executions = new Map<Promise<O>, Promise<[Promise<O>, O]>>(); for (const action of actions) { const execution = executor(action); executions.set( execution, execution.then((result) => [execution, result]), ); } while (executions.size > 0) { const [execution, result] = await Promise.race(executions.values()); executions.delete(execution); yield result; } } stop(): void { if (this.workerPool) { void this.workerPool.destroy(); } } }
{ "commit_id": "b893a6ae9", "end_byte": 1942, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/action-executor.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/output-paths.ts_0_821
/** * @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 { existsSync, mkdirSync } from 'fs'; import { join } from 'path'; import { I18nOptions } from './i18n-webpack'; export function ensureOutputPaths(baseOutputPath: string, i18n: I18nOptions): Map<string, string> { const outputPaths: [string, string][] = i18n.shouldInline ? [...i18n.inlineLocales].map((l) => [ l, i18n.flatOutput ? baseOutputPath : join(baseOutputPath, l), ]) : [['', baseOutputPath]]; for (const [, outputPath] of outputPaths) { if (!existsSync(outputPath)) { mkdirSync(outputPath, { recursive: true }); } } return new Map(outputPaths); }
{ "commit_id": "b893a6ae9", "end_byte": 821, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/output-paths.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/test-files_spec.ts_0_5110
/** * @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 realGlob from 'fast-glob'; import { promises as fs } from 'fs'; import * as path from 'path'; import { findTestFiles } from './test-files'; describe('test-files', () => { describe('findTestFiles()', () => { let tempDir!: string; beforeEach(async () => { tempDir = await fs.mkdtemp('angular-cli-jest-builder-test-files-'); }); afterEach(async () => { await fs.rm(tempDir, { recursive: true }); }); it('returns all the test files in the project', async () => { await fs.writeFile(path.join(tempDir, 'foo.spec.ts'), ''); await fs.mkdir(path.join(tempDir, 'nested')); await fs.writeFile(path.join(tempDir, 'nested', 'bar.spec.ts'), ''); const testFiles = await findTestFiles( ['**/*.spec.ts'] /* include */, [] /* exclude */, tempDir, ); expect(testFiles).toEqual(new Set(['foo.spec.ts', path.join('nested', 'bar.spec.ts')])); }); it('excludes `node_modules/` and files from input options', async () => { await fs.writeFile(path.join(tempDir, 'foo.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'bar.ignored.spec.ts'), ''); await fs.mkdir(path.join(tempDir, 'node_modules', 'dep'), { recursive: true }); await fs.writeFile(path.join(tempDir, 'node_modules', 'dep', 'baz.spec.ts'), ''); const testFiles = await findTestFiles( ['**/*.spec.ts'] /* include */, ['**/*.ignored.spec.ts'] /* exclude */, tempDir, ); expect(testFiles).toEqual(new Set(['foo.spec.ts'])); }); it('finds files in multiple globs', async () => { await fs.writeFile(path.join(tempDir, 'foo.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'bar.test.ts'), ''); await fs.writeFile(path.join(tempDir, 'foo.ignored.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'bar.ignored.test.ts'), ''); await fs.mkdir(path.join(tempDir, 'node_modules', 'dep'), { recursive: true }); await fs.writeFile(path.join(tempDir, 'node_modules', 'dep', 'baz.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'node_modules', 'dep', 'baz.test.ts'), ''); const testFiles = await findTestFiles( ['**/*.spec.ts', '**/*.test.ts'] /* include */, // Exclude should be applied to all `glob()` executions. ['**/*.ignored.*.ts'] /* exclude */, tempDir, ); expect(testFiles).toEqual(new Set(['foo.spec.ts', 'bar.test.ts'])); }); it('is constrained to the workspace root', async () => { await fs.mkdir(path.join(tempDir, 'nested')); await fs.writeFile(path.join(tempDir, 'foo.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'nested', 'bar.spec.ts'), ''); const testFiles = await findTestFiles( ['**/*.spec.ts'] /* include */, [] /* exclude */, path.join(tempDir, 'nested'), ); expect(testFiles).toEqual(new Set(['bar.spec.ts'])); }); it('throws if any `glob` invocation fails', async () => { const err = new Error('Eww, I stepped in a glob.'); const glob = jasmine .createSpy('glob', realGlob) .and.returnValues( Promise.resolve(['foo.spec.ts']), Promise.reject(err), Promise.resolve(['bar.test.ts']), ); await expectAsync( findTestFiles( ['*.spec.ts', '*.stuff.ts', '*.test.ts'] /* include */, [] /* exclude */, tempDir, // eslint-disable-next-line @typescript-eslint/no-explicit-any glob as any, ), ).toBeRejectedWith(err); }); it('disables brace expansion', async () => { await fs.writeFile(path.join(tempDir, 'foo.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'bar.spec.ts'), ''); const testFiles = await findTestFiles( ['{foo,bar}.spec.ts'] /* include */, [] /* exclude */, tempDir, ); expect(testFiles).toEqual(new Set()); }); it('disables `extglob` features', async () => { await fs.writeFile(path.join(tempDir, 'foo.spec.ts'), ''); await fs.writeFile(path.join(tempDir, 'bar.spec.ts'), ''); const testFiles = await findTestFiles( ['+(foo|bar).spec.ts'] /* include */, [] /* exclude */, tempDir, ); expect(testFiles).toEqual(new Set()); }); it('ignores directories', async () => { await fs.mkdir(path.join(tempDir, 'foo.spec.ts')); await fs.mkdir(path.join(tempDir, 'bar.spec.ts')); await fs.writeFile(path.join(tempDir, 'bar.spec.ts', 'baz.spec.ts'), ''); const testFiles = await findTestFiles( ['**/*.spec.ts'] /* include */, [] /* exclude */, tempDir, ); expect(testFiles).toEqual(new Set([path.join('bar.spec.ts', 'baz.spec.ts')])); }); }); });
{ "commit_id": "b893a6ae9", "end_byte": 5110, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/test-files_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/build-options.ts_0_2573
/** * @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 { ParsedConfiguration } from '@angular/compiler-cli'; import { logging } from '@angular-devkit/core'; import { AssetPatternClass, Budget, CrossOrigin, I18NTranslation, IndexUnion, InlineStyleLanguage, Localize, OutputHashing, ScriptElement, SourceMapClass, StyleElement, } from '../builders/browser/schema'; import { Schema as DevServerSchema } from '../builders/dev-server/schema'; import { NormalizedCachedOptions } from './normalize-cache'; import { NormalizedFileReplacement } from './normalize-file-replacements'; import { NormalizedOptimizationOptions } from './normalize-optimization'; export interface BuildOptions { optimization: NormalizedOptimizationOptions; environment?: string; outputPath: string; resourcesOutputPath?: string; aot?: boolean; sourceMap: SourceMapClass; vendorChunk?: boolean; commonChunk?: boolean; baseHref?: string; deployUrl?: string; verbose?: boolean; progress?: boolean; localize?: Localize; i18nMissingTranslation?: I18NTranslation; externalDependencies?: string[]; watch?: boolean; outputHashing?: OutputHashing; poll?: number; index?: IndexUnion; deleteOutputPath?: boolean; preserveSymlinks?: boolean; extractLicenses?: boolean; buildOptimizer?: boolean; namedChunks?: boolean; crossOrigin?: CrossOrigin; subresourceIntegrity?: boolean; serviceWorker?: boolean; webWorkerTsConfig?: string; statsJson: boolean; hmr?: boolean; main: string; polyfills: string[]; budgets: Budget[]; assets: AssetPatternClass[]; scripts: ScriptElement[]; styles: StyleElement[]; stylePreprocessorOptions?: { includePaths: string[] }; platform?: 'browser' | 'server'; fileReplacements: NormalizedFileReplacement[]; inlineStyleLanguage?: InlineStyleLanguage; allowedCommonJsDependencies?: string[]; cache: NormalizedCachedOptions; codeCoverage?: boolean; codeCoverageExclude?: string[]; supportedBrowsers?: string[]; } export interface WebpackDevServerOptions extends BuildOptions, Omit<DevServerSchema, 'optimization' | 'sourceMap' | 'buildTarget' | 'browserTarget'> {} export interface WebpackConfigOptions<T = BuildOptions> { root: string; logger: logging.Logger; projectRoot: string; sourceRoot?: string; buildOptions: T; tsConfig: ParsedConfiguration; tsConfigPath: string; projectName: string; }
{ "commit_id": "b893a6ae9", "end_byte": 2573, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/build-options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/run-module-worker.js_0_592
/** * @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 */ process.on('message', (message) => { // Only process messages with the hash in 'run-module-as-observable-fork.ts'. if (message.hash === '5d4b9a5c0a4e0f9977598437b0e85bcc') { const requiredModule = require(message.modulePath); if (message.exportName) { requiredModule[message.exportName](...message.args); } else { requiredModule(...message.args); } } });
{ "commit_id": "b893a6ae9", "end_byte": 592, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/run-module-worker.js" }
angular-cli/packages/angular_devkit/build_angular/src/utils/process-bundle.ts_0_6931
/** * @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 from '@ampproject/remapping'; import { NodePath, ParseResult, parseSync, template as templateBuilder, transformAsync, transformFromAstSync, traverse, types, } from '@babel/core'; import * as fs from 'fs/promises'; import * as path from 'path'; import { workerData } from 'worker_threads'; import { InlineOptions } from './bundle-inline-options'; import { allowMinify, shouldBeautify } from './environment-options'; import { assertIsError } from './error'; import { I18nOptions } from './i18n-webpack'; import { loadEsmModule } from './load-esm'; // Extract Sourcemap input type from the remapping function since it is not currently exported type SourceMapInput = Exclude<Parameters<typeof remapping>[0], unknown[]>; // Lazy loaded webpack-sources object // Webpack is only imported if needed during the processing let webpackSources: typeof import('webpack').sources | undefined; const { i18n } = (workerData || {}) as { i18n?: I18nOptions }; /** * Internal flag to enable the direct usage of the `@angular/localize` translation plugins. * Their usage is currently several times slower than the string manipulation method. * Future work to optimize the plugins should enable plugin usage as the default. */ const USE_LOCALIZE_PLUGINS = false; type LocalizeUtilityModule = typeof import('@angular/localize/tools'); /** * Cached instance of the `@angular/localize/tools` module. * This is used to remove the need to repeatedly import the module per file translation. */ let localizeToolsModule: LocalizeUtilityModule | undefined; /** * Attempts to load the `@angular/localize/tools` module containing the functionality to * perform the file translations. * This module must be dynamically loaded as it is an ESM module and this file is CommonJS. */ async function loadLocalizeTools(): Promise<LocalizeUtilityModule> { if (localizeToolsModule !== undefined) { return localizeToolsModule; } // 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. return loadEsmModule('@angular/localize/tools'); } async function createI18nPlugins( locale: string, translation: unknown | undefined, missingTranslation: 'error' | 'warning' | 'ignore', shouldInline: boolean, localeDataContent?: string, ) { const { Diagnostics, makeEs2015TranslatePlugin, makeLocalePlugin } = await loadLocalizeTools(); const plugins = []; const diagnostics = new Diagnostics(); if (shouldInline) { plugins.push( // eslint-disable-next-line @typescript-eslint/no-explicit-any makeEs2015TranslatePlugin(diagnostics, (translation || {}) as any, { missingTranslation: translation === undefined ? 'ignore' : missingTranslation, }), ); } plugins.push(makeLocalePlugin(locale)); if (localeDataContent) { plugins.push({ visitor: { Program(path: NodePath<types.Program>) { path.unshiftContainer('body', templateBuilder.ast(localeDataContent)); }, }, }); } return { diagnostics, plugins }; } interface LocalizePosition { start: number; end: number; messageParts: TemplateStringsArray; expressions: types.Expression[]; } const localizeName = '$localize'; export async function inlineLocales(options: InlineOptions) { if (!i18n || i18n.inlineLocales.size === 0) { return { file: options.filename, diagnostics: [], count: 0 }; } if (i18n.flatOutput && i18n.inlineLocales.size > 1) { throw new Error('Flat output is only supported when inlining one locale.'); } const hasLocalizeName = options.code.includes(localizeName); if (!hasLocalizeName && !options.setLocale) { return inlineCopyOnly(options); } await loadLocalizeTools(); let ast: ParseResult | undefined | null; try { ast = parseSync(options.code, { babelrc: false, configFile: false, sourceType: 'unambiguous', filename: options.filename, }); } catch (error) { assertIsError(error); // Make the error more readable. // Same errors will contain the full content of the file as the error message // Which makes it hard to find the actual error message. const index = error.message.indexOf(')\n'); const msg = index !== -1 ? error.message.slice(0, index + 1) : error.message; throw new Error(`${msg}\nAn error occurred inlining file "${options.filename}"`); } if (!ast) { throw new Error(`Unknown error occurred inlining file "${options.filename}"`); } if (!USE_LOCALIZE_PLUGINS) { return inlineLocalesDirect(ast, options); } const diagnostics = []; for (const locale of i18n.inlineLocales) { const isSourceLocale = locale === i18n.sourceLocale; // eslint-disable-next-line @typescript-eslint/no-explicit-any const translations: any = isSourceLocale ? {} : i18n.locales[locale].translation || {}; let localeDataContent; if (options.setLocale) { // If locale data is provided, load it and prepend to file const localeDataPath = i18n.locales[locale]?.dataPath; if (localeDataPath) { localeDataContent = await loadLocaleData(localeDataPath, true); } } const { diagnostics: localeDiagnostics, plugins } = await createI18nPlugins( locale, translations, isSourceLocale ? 'ignore' : options.missingTranslation || 'warning', true, localeDataContent, ); const transformResult = transformFromAstSync(ast, options.code, { filename: options.filename, // using false ensures that babel will NOT search and process sourcemap comments (large memory usage) // The types do not include the false option even though it is valid // eslint-disable-next-line @typescript-eslint/no-explicit-any inputSourceMap: false as any, babelrc: false, configFile: false, plugins, compact: !shouldBeautify, sourceMaps: !!options.map, }); diagnostics.push(...localeDiagnostics.messages); if (!transformResult || !transformResult.code) { throw new Error(`Unknown error occurred processing bundle for "${options.filename}".`); } const outputPath = path.join( options.outputPath, i18n.flatOutput ? '' : locale, options.filename, ); await fs.writeFile(outputPath, transformResult.code); if (options.map && transformResult.map) { const outputMap = remapping([transformResult.map as SourceMapInput, options.map], () => null); await fs.writeFile(outputPath + '.map', JSON.stringify(outputMap)); } } return { file: options.filename, diagnostics }; }
{ "commit_id": "b893a6ae9", "end_byte": 6931, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/process-bundle.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/process-bundle.ts_6933_13284
async function inlineLocalesDirect(ast: ParseResult, options: InlineOptions) { if (!i18n || i18n.inlineLocales.size === 0) { return { file: options.filename, diagnostics: [], count: 0 }; } const { default: generate } = await import('@babel/generator'); const localizeDiag = await loadLocalizeTools(); const diagnostics = new localizeDiag.Diagnostics(); const positions = findLocalizePositions(ast, options, localizeDiag); if (positions.length === 0 && !options.setLocale) { return inlineCopyOnly(options); } const inputMap = !!options.map && (JSON.parse(options.map) as { sourceRoot?: string }); // Cleanup source root otherwise it will be added to each source entry const mapSourceRoot = inputMap && inputMap.sourceRoot; if (inputMap) { delete inputMap.sourceRoot; } // Load Webpack only when needed if (webpackSources === undefined) { webpackSources = (await import('webpack')).sources; } const { ConcatSource, OriginalSource, ReplaceSource, SourceMapSource } = webpackSources; for (const locale of i18n.inlineLocales) { const content = new ReplaceSource( inputMap ? new SourceMapSource(options.code, options.filename, inputMap) : new OriginalSource(options.code, options.filename), ); const isSourceLocale = locale === i18n.sourceLocale; // eslint-disable-next-line @typescript-eslint/no-explicit-any const translations: any = isSourceLocale ? {} : i18n.locales[locale].translation || {}; for (const position of positions) { const translated = localizeDiag.translate( diagnostics, translations, position.messageParts, position.expressions, isSourceLocale ? 'ignore' : options.missingTranslation || 'warning', ); const expression = localizeDiag.buildLocalizeReplacement(translated[0], translated[1]); const { code } = generate(expression); content.replace(position.start, position.end - 1, code); } let outputSource: import('webpack').sources.Source = content; if (options.setLocale) { const setLocaleText = `globalThis.$localize=Object.assign(globalThis.$localize || {},{locale:"${locale}"});\n`; // If locale data is provided, load it and prepend to file let localeDataSource; const localeDataPath = i18n.locales[locale] && i18n.locales[locale].dataPath; if (localeDataPath) { const localeDataContent = await loadLocaleData(localeDataPath, true); localeDataSource = new OriginalSource(localeDataContent, path.basename(localeDataPath)); } outputSource = localeDataSource ? // The semicolon ensures that there is no syntax error between statements new ConcatSource(setLocaleText, localeDataSource, ';\n', content) : new ConcatSource(setLocaleText, content); } const { source: outputCode, map: outputMap } = outputSource.sourceAndMap() as { source: string; map: { file: string; sourceRoot?: string }; }; const outputPath = path.join( options.outputPath, i18n.flatOutput ? '' : locale, options.filename, ); await fs.writeFile(outputPath, outputCode); if (inputMap && outputMap) { outputMap.file = options.filename; if (mapSourceRoot) { outputMap.sourceRoot = mapSourceRoot; } await fs.writeFile(outputPath + '.map', JSON.stringify(outputMap)); } } return { file: options.filename, diagnostics: diagnostics.messages, count: positions.length }; } async function inlineCopyOnly(options: InlineOptions) { if (!i18n) { throw new Error('i18n options are missing'); } for (const locale of i18n.inlineLocales) { const outputPath = path.join( options.outputPath, i18n.flatOutput ? '' : locale, options.filename, ); await fs.writeFile(outputPath, options.code); if (options.map) { await fs.writeFile(outputPath + '.map', options.map); } } return { file: options.filename, diagnostics: [], count: 0 }; } function findLocalizePositions( ast: ParseResult, options: InlineOptions, utils: LocalizeUtilityModule, ): LocalizePosition[] { const positions: LocalizePosition[] = []; // Workaround to ensure a path hub is present for traversal const { File } = require('@babel/core'); const file = new File({}, { code: options.code, ast }); traverse(file.ast, { TaggedTemplateExpression(path) { if (types.isIdentifier(path.node.tag) && path.node.tag.name === localizeName) { const [messageParts, expressions] = unwrapTemplateLiteral(path, utils); positions.push({ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion start: path.node.start!, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion end: path.node.end!, messageParts, expressions, }); } }, }); return positions; } function unwrapTemplateLiteral( path: NodePath<types.TaggedTemplateExpression>, utils: LocalizeUtilityModule, ): [TemplateStringsArray, types.Expression[]] { const [messageParts] = utils.unwrapMessagePartsFromTemplateLiteral( path.get('quasi').get('quasis'), ); const [expressions] = utils.unwrapExpressionsFromTemplateLiteral(path.get('quasi')); return [messageParts, expressions]; } async function loadLocaleData(path: string, optimize: boolean): Promise<string> { // The path is validated during option processing before the build starts const content = await fs.readFile(path, 'utf8'); // Downlevel and optimize the data const transformResult = await transformAsync(content, { filename: path, // The types do not include the false option even though it is valid // eslint-disable-next-line @typescript-eslint/no-explicit-any inputSourceMap: false as any, babelrc: false, configFile: false, presets: [ [ require.resolve('@babel/preset-env'), { bugfixes: true, targets: { esmodules: true }, }, ], ], minified: allowMinify && optimize, compact: !shouldBeautify && optimize, comments: !optimize, }); if (!transformResult || !transformResult.code) { throw new Error(`Unknown error occurred processing bundle for "${path}".`); } return transformResult.code; }
{ "commit_id": "b893a6ae9", "end_byte": 13284, "start_byte": 6933, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/process-bundle.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/package-chunk-sort.ts_0_1575
/** * @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 { ScriptElement, StyleElement } from '../builders/browser/schema'; import { normalizeExtraEntryPoints } from '../tools/webpack/utils/helpers'; export type EntryPointsType = [name: string, isModule: boolean]; export function generateEntryPoints(options: { styles: StyleElement[]; scripts: ScriptElement[]; isHMREnabled?: boolean; }): EntryPointsType[] { // Add all styles/scripts, except lazy-loaded ones. const extraEntryPoints = ( extraEntryPoints: (ScriptElement | StyleElement)[], defaultBundleName: string, ) => { const entryPoints = normalizeExtraEntryPoints(extraEntryPoints, defaultBundleName) .filter((entry) => entry.inject) .map((entry) => entry.bundleName); // remove duplicates return [...new Set(entryPoints)].map<EntryPointsType>((f) => [f, false]); }; const entryPoints: EntryPointsType[] = [ ['runtime', !options.isHMREnabled], ['polyfills', true], ...extraEntryPoints(options.styles, 'styles'), ...extraEntryPoints(options.scripts, 'scripts'), ['vendor', true], ['main', true], ]; const duplicates = entryPoints.filter( ([name]) => entryPoints[0].indexOf(name) !== entryPoints[0].lastIndexOf(name), ); if (duplicates.length > 0) { throw new Error(`Multiple bundles have been named the same: '${duplicates.join(`', '`)}'.`); } return entryPoints; }
{ "commit_id": "b893a6ae9", "end_byte": 1575, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/package-chunk-sort.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-cache.ts_0_1796
/** * @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, resolve } from 'node:path'; /** Version placeholder is replaced during the build process with actual package version */ const VERSION = '0.0.0-PLACEHOLDER'; export interface NormalizedCachedOptions { /** Whether disk cache is enabled. */ enabled: boolean; /** Disk cache path. Example: `/.angular/cache/v12.0.0`. */ path: string; /** Disk cache base path. Example: `/.angular/cache`. */ basePath: string; } interface CacheMetadata { enabled?: boolean; environment?: 'local' | 'ci' | 'all'; path?: string; } function hasCacheMetadata(value: unknown): value is { cli: { cache: CacheMetadata } } { return ( !!value && typeof value === 'object' && 'cli' in value && !!value['cli'] && typeof value['cli'] === 'object' && 'cache' in value['cli'] ); } export function normalizeCacheOptions( projectMetadata: unknown, worspaceRoot: string, ): NormalizedCachedOptions { const cacheMetadata = hasCacheMetadata(projectMetadata) ? projectMetadata.cli.cache : {}; const { enabled = true, environment = 'local', path = '.angular/cache' } = cacheMetadata; const isCI = process.env['CI'] === '1' || process.env['CI']?.toLowerCase() === 'true'; let cacheEnabled = enabled; if (cacheEnabled) { switch (environment) { case 'ci': cacheEnabled = isCI; break; case 'local': cacheEnabled = !isCI; break; } } const cacheBasePath = resolve(worspaceRoot, path); return { enabled: cacheEnabled, basePath: cacheBasePath, path: join(cacheBasePath, VERSION), }; }
{ "commit_id": "b893a6ae9", "end_byte": 1796, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-cache.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/index.ts_0_612
/** * @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 './default-progress'; export { deleteOutputDir, loadProxyConfiguration } from '@angular/build/private'; export * from './run-module-as-observable-fork'; export * from './normalize-file-replacements'; export * from './normalize-asset-patterns'; export * from './normalize-source-maps'; export * from './normalize-optimization'; export * from './normalize-builder-schema'; export * from './url';
{ "commit_id": "b893a6ae9", "end_byte": 612, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/error.ts_0_597
/** * @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'; export function assertIsError(value: unknown): asserts value is Error & { code?: string } { const isError = value instanceof Error || // The following is needing to identify errors coming from RxJs. (typeof value === 'object' && value && 'name' in value && 'message' in value); assert(isError, 'catch clause variable is not an Error instance'); }
{ "commit_id": "b893a6ae9", "end_byte": 597, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/error.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/color.ts_0_1267
/** * @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 * as ansiColors from 'ansi-colors'; import { WriteStream } from 'node:tty'; function supportColor(): boolean { if (process.env.FORCE_COLOR !== undefined) { // 2 colors: FORCE_COLOR = 0 (Disables colors), depth 1 // 16 colors: FORCE_COLOR = 1, depth 4 // 256 colors: FORCE_COLOR = 2, depth 8 // 16,777,216 colors: FORCE_COLOR = 3, depth 16 // See: https://nodejs.org/dist/latest-v12.x/docs/api/tty.html#tty_writestream_getcolordepth_env // and https://github.com/nodejs/node/blob/b9f36062d7b5c5039498e98d2f2c180dca2a7065/lib/internal/tty.js#L106; switch (process.env.FORCE_COLOR) { case '': case 'true': case '1': case '2': case '3': return true; default: return false; } } if (process.stdout instanceof WriteStream) { return process.stdout.hasColors(); } return false; } // Create a separate instance to prevent unintended global changes to the color configuration const colors = ansiColors.create(); colors.enabled = supportColor(); export { colors };
{ "commit_id": "b893a6ae9", "end_byte": 1267, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/color.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/tty.ts_0_674
/** * @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 */ function _isTruthy(value: undefined | string): boolean { // Returns true if value is a string that is anything but 0 or false. return value !== undefined && value !== '0' && value.toUpperCase() !== 'FALSE'; } export function isTTY(): boolean { // If we force TTY, we always return true. const force = process.env['NG_FORCE_TTY']; if (force !== undefined) { return _isTruthy(force); } return !!process.stdout.isTTY && !_isTruthy(process.env['CI']); }
{ "commit_id": "b893a6ae9", "end_byte": 674, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/tty.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-builder-schema.ts_0_2853
/** * @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 { getSupportedBrowsers } from '@angular/build/private'; import { json, logging } from '@angular-devkit/core'; import { AssetPatternClass, Schema as BrowserBuilderSchema, SourceMapClass, } from '../builders/browser/schema'; import { BuildOptions } from './build-options'; import { normalizeAssetPatterns } from './normalize-asset-patterns'; import { normalizeCacheOptions } from './normalize-cache'; import { NormalizedFileReplacement, normalizeFileReplacements, } from './normalize-file-replacements'; import { NormalizedOptimizationOptions, normalizeOptimization } from './normalize-optimization'; import { normalizePolyfills } from './normalize-polyfills'; import { normalizeSourceMaps } from './normalize-source-maps'; /** * A normalized browser builder schema. */ export type NormalizedBrowserBuilderSchema = BrowserBuilderSchema & BuildOptions & { sourceMap: SourceMapClass; assets: AssetPatternClass[]; fileReplacements: NormalizedFileReplacement[]; optimization: NormalizedOptimizationOptions; polyfills: string[]; }; export function normalizeBrowserSchema( workspaceRoot: string, projectRoot: string, projectSourceRoot: string | undefined, options: BrowserBuilderSchema, metadata: json.JsonObject, logger: logging.LoggerApi, ): NormalizedBrowserBuilderSchema { return { ...options, cache: normalizeCacheOptions(metadata, workspaceRoot), assets: normalizeAssetPatterns( options.assets || [], workspaceRoot, projectRoot, projectSourceRoot, ), fileReplacements: normalizeFileReplacements(options.fileReplacements || [], workspaceRoot), optimization: normalizeOptimization(options.optimization), sourceMap: normalizeSourceMaps(options.sourceMap || false), polyfills: normalizePolyfills(options.polyfills, workspaceRoot), preserveSymlinks: options.preserveSymlinks === undefined ? process.execArgv.includes('--preserve-symlinks') : options.preserveSymlinks, statsJson: options.statsJson || false, budgets: options.budgets || [], scripts: options.scripts || [], styles: options.styles || [], stylePreprocessorOptions: { includePaths: (options.stylePreprocessorOptions && options.stylePreprocessorOptions.includePaths) || [], }, // Using just `--poll` will result in a value of 0 which is very likely not the intention // A value of 0 is falsy and will disable polling rather then enable // 500 ms is a sensible default in this case poll: options.poll === 0 ? 500 : options.poll, supportedBrowsers: getSupportedBrowsers(projectRoot, logger), }; }
{ "commit_id": "b893a6ae9", "end_byte": 2853, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-builder-schema.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/copy-assets.ts_0_1772
/** * @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 glob from 'fast-glob'; import fs from 'node:fs'; import path from 'node:path'; export async function copyAssets( entries: { glob: string; ignore?: string[]; input: string; output: string; flatten?: boolean; followSymlinks?: boolean; }[], basePaths: Iterable<string>, root: string, changed?: Set<string>, ) { const defaultIgnore = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db']; const outputFiles: { source: string; destination: string }[] = []; for (const entry of entries) { const cwd = path.resolve(root, entry.input); const files = await glob(entry.glob, { cwd, dot: true, ignore: entry.ignore ? defaultIgnore.concat(entry.ignore) : defaultIgnore, followSymbolicLinks: entry.followSymlinks, }); const directoryExists = new Set<string>(); for (const file of files) { const src = path.join(cwd, file); if (changed && !changed.has(src)) { continue; } const filePath = entry.flatten ? path.basename(file) : file; outputFiles.push({ source: src, destination: path.join(entry.output, filePath) }); for (const base of basePaths) { const dest = path.join(base, entry.output, filePath); const dir = path.dirname(dest); if (!directoryExists.has(dir)) { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } directoryExists.add(dir); } fs.copyFileSync(src, dest, fs.constants.COPYFILE_FICLONE); } } } return outputFiles; }
{ "commit_id": "b893a6ae9", "end_byte": 1772, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/copy-assets.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/default-progress.ts_0_378
/** * @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 function defaultProgress(progress: boolean | undefined): boolean { if (progress === undefined) { return process.stdout.isTTY === true; } return progress; }
{ "commit_id": "b893a6ae9", "end_byte": 378, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/default-progress.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/load-esm.ts_0_1203
/** * @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 */ /** * Lazily compiled dynamic import loader function. */ let load: (<T>(modulePath: string | URL) => Promise<T>) | undefined; /** * This uses a dynamic import to load a module which may be ESM. * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript * will currently, unconditionally downlevel dynamic import into a require call. * require calls cannot load ESM code and will result in a runtime error. To workaround * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. * Once TypeScript provides support for keeping the dynamic import this workaround can * be dropped. * * @param modulePath The path of the module to load. * @returns A Promise that resolves to the dynamically imported module. */ export function loadEsmModule<T>(modulePath: string | URL): Promise<T> { load ??= new Function('modulePath', `return import(modulePath);`) as Exclude< typeof load, undefined >; return load(modulePath); }
{ "commit_id": "b893a6ae9", "end_byte": 1203, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/load-esm.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/webpack-browser-config.ts_0_6305
/** * @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 } from '@angular-devkit/architect'; import * as path from 'path'; import { Configuration, javascript } from 'webpack'; import { merge as webpackMerge } from 'webpack-merge'; import { Schema as BrowserBuilderSchema } from '../builders/browser/schema'; import { BuilderWatchPlugin, BuilderWatcherFactory, } from '../tools/webpack/plugins/builder-watch-plugin'; import { NormalizedBrowserBuilderSchema, defaultProgress, normalizeBrowserSchema } from '../utils'; import { WebpackConfigOptions } from '../utils/build-options'; import { readTsconfig } from '../utils/read-tsconfig'; import { I18nOptions, configureI18nBuild } from './i18n-webpack'; export type BrowserWebpackConfigOptions = WebpackConfigOptions<NormalizedBrowserBuilderSchema>; export type WebpackPartialGenerator = ( configurationOptions: BrowserWebpackConfigOptions, ) => (Promise<Configuration> | Configuration)[]; export async function generateWebpackConfig( workspaceRoot: string, projectRoot: string, sourceRoot: string | undefined, projectName: string, options: NormalizedBrowserBuilderSchema, webpackPartialGenerator: WebpackPartialGenerator, logger: BuilderContext['logger'], extraBuildOptions: Partial<NormalizedBrowserBuilderSchema>, ): Promise<Configuration> { // Ensure Build Optimizer is only used with AOT. if (options.buildOptimizer && !options.aot) { throw new Error(`The 'buildOptimizer' option cannot be used without 'aot'.`); } const tsConfigPath = path.resolve(workspaceRoot, options.tsConfig); const tsConfig = await readTsconfig(tsConfigPath); const buildOptions: NormalizedBrowserBuilderSchema = { ...options, ...extraBuildOptions }; const wco: BrowserWebpackConfigOptions = { root: workspaceRoot, logger: logger.createChild('webpackConfigOptions'), projectRoot, sourceRoot, buildOptions, tsConfig, tsConfigPath, projectName, }; wco.buildOptions.progress = defaultProgress(wco.buildOptions.progress); const partials = await Promise.all(webpackPartialGenerator(wco)); const webpackConfig = webpackMerge(partials); return webpackConfig; } export async function generateI18nBrowserWebpackConfigFromContext( options: BrowserBuilderSchema, context: BuilderContext, webpackPartialGenerator: WebpackPartialGenerator, extraBuildOptions: Partial<NormalizedBrowserBuilderSchema> = {}, ): Promise<{ config: Configuration; projectRoot: string; projectSourceRoot?: string; i18n: I18nOptions; }> { const { buildOptions, i18n } = await configureI18nBuild(context, options); const result = await generateBrowserWebpackConfigFromContext( buildOptions, context, (wco) => { return webpackPartialGenerator(wco); }, extraBuildOptions, ); const config = result.config; if (i18n.shouldInline) { // Remove localize "polyfill" if in AOT mode if (buildOptions.aot) { if (!config.resolve) { config.resolve = {}; } if (Array.isArray(config.resolve.alias)) { config.resolve.alias.push({ name: '@angular/localize/init', alias: false, }); } else { if (!config.resolve.alias) { config.resolve.alias = {}; } config.resolve.alias['@angular/localize/init'] = false; } } // Update file hashes to include translation file content const i18nHash = Object.values(i18n.locales).reduce( (data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'), '', ); config.plugins ??= []; config.plugins.push({ apply(compiler) { compiler.hooks.compilation.tap('build-angular', (compilation) => { javascript.JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap( 'build-angular', (_, hash) => { hash.update('$localize' + i18nHash); }, ); }); }, }); } return { ...result, i18n }; } export async function generateBrowserWebpackConfigFromContext( options: BrowserBuilderSchema, context: BuilderContext, webpackPartialGenerator: WebpackPartialGenerator, extraBuildOptions: Partial<NormalizedBrowserBuilderSchema> = {}, ): Promise<{ config: Configuration; projectRoot: string; projectSourceRoot?: string }> { const projectName = context.target && context.target.project; if (!projectName) { throw new Error('The builder requires a target.'); } const workspaceRoot = context.workspaceRoot; const projectMetadata = await context.getProjectMetadata(projectName); const projectRoot = path.join(workspaceRoot, (projectMetadata.root as string | undefined) ?? ''); const sourceRoot = projectMetadata.sourceRoot as string | undefined; const projectSourceRoot = sourceRoot ? path.join(workspaceRoot, sourceRoot) : undefined; const normalizedOptions = normalizeBrowserSchema( workspaceRoot, projectRoot, projectSourceRoot, options, projectMetadata, context.logger, ); const config = await generateWebpackConfig( workspaceRoot, projectRoot, projectSourceRoot, projectName, normalizedOptions, webpackPartialGenerator, context.logger, extraBuildOptions, ); // If builder watch support is present in the context, add watch plugin // This is internal only and currently only used for testing const watcherFactory = ( context as { watcherFactory?: BuilderWatcherFactory; } ).watcherFactory; if (watcherFactory) { if (!config.plugins) { config.plugins = []; } config.plugins.push(new BuilderWatchPlugin(watcherFactory)); } return { config, projectRoot, projectSourceRoot, }; } export function getIndexOutputFile(index: BrowserBuilderSchema['index']): string { if (typeof index === 'string') { return path.basename(index); } else { return index.output || 'index.html'; } } export function getIndexInputFile(index: BrowserBuilderSchema['index']): string { if (typeof index === 'string') { return index; } else { return index.input; } }
{ "commit_id": "b893a6ae9", "end_byte": 6305, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/webpack-browser-config.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/test-files.ts_0_1225
/** * @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 fastGlob, { Options as GlobOptions } from 'fast-glob'; /** * Finds all test files in the project. * * @param options The builder options describing where to find tests. * @param workspaceRoot The path to the root directory of the workspace. * @param glob A promisified implementation of the `glob` module. Only intended for * testing purposes. * @returns A set of all test files in the project. */ export async function findTestFiles( include: string[], exclude: string[], workspaceRoot: string, glob: typeof fastGlob = fastGlob, ): Promise<Set<string>> { const globOptions: GlobOptions = { cwd: workspaceRoot, ignore: ['node_modules/**'].concat(exclude), braceExpansion: false, // Do not expand `a{b,c}` to `ab,ac`. extglob: false, // Disable "extglob" patterns. }; const included = await Promise.all(include.map((pattern) => glob(pattern, globOptions))); // Flatten and deduplicate any files found in multiple include patterns. return new Set(included.flat()); }
{ "commit_id": "b893a6ae9", "end_byte": 1225, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/test-files.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts_0_3866
/** * @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 } from '@angular-devkit/architect'; import { EmittedFiles } from '@angular-devkit/build-webpack'; import * as fs from 'fs'; import * as path from 'path'; import { BundleActionExecutor } from './action-executor'; import { InlineOptions } from './bundle-inline-options'; import { copyAssets } from './copy-assets'; import { assertIsError } from './error'; import { I18nOptions } from './i18n-webpack'; import { Spinner } from './spinner'; function emittedFilesToInlineOptions( emittedFiles: EmittedFiles[], scriptsEntryPointName: string[], emittedPath: string, outputPath: string, missingTranslation: 'error' | 'warning' | 'ignore' | undefined, context: BuilderContext, ): { options: InlineOptions[]; originalFiles: string[] } { const options: InlineOptions[] = []; const originalFiles: string[] = []; for (const emittedFile of emittedFiles) { if ( emittedFile.asset || emittedFile.extension !== '.js' || (emittedFile.name && scriptsEntryPointName.includes(emittedFile.name)) ) { continue; } const originalPath = path.join(emittedPath, emittedFile.file); const action: InlineOptions = { filename: emittedFile.file, code: fs.readFileSync(originalPath, 'utf8'), outputPath, missingTranslation, setLocale: emittedFile.name === 'main', }; originalFiles.push(originalPath); try { const originalMapPath = originalPath + '.map'; action.map = fs.readFileSync(originalMapPath, 'utf8'); originalFiles.push(originalMapPath); } catch (err) { assertIsError(err); if (err.code !== 'ENOENT') { throw err; } } context.logger.debug(`i18n file queued for processing: ${action.filename}`); options.push(action); } return { options, originalFiles }; } export async function i18nInlineEmittedFiles( context: BuilderContext, emittedFiles: EmittedFiles[], i18n: I18nOptions, baseOutputPath: string, outputPaths: string[], scriptsEntryPointName: string[], emittedPath: string, missingTranslation: 'error' | 'warning' | 'ignore' | undefined, ): Promise<boolean> { const executor = new BundleActionExecutor({ i18n }); let hasErrors = false; const spinner = new Spinner(); spinner.start('Generating localized bundles...'); try { const { options, originalFiles: processedFiles } = emittedFilesToInlineOptions( emittedFiles, scriptsEntryPointName, emittedPath, baseOutputPath, missingTranslation, context, ); for await (const result of executor.inlineAll(options)) { context.logger.debug(`i18n file processed: ${result.file}`); for (const diagnostic of result.diagnostics) { spinner.stop(); if (diagnostic.type === 'error') { hasErrors = true; context.logger.error(diagnostic.message); } else { context.logger.warn(diagnostic.message); } spinner.start(); } } // Copy any non-processed files into the output locations await copyAssets( [ { glob: '**/*', input: emittedPath, output: '', ignore: [...processedFiles].map((f) => path.relative(emittedPath, f)), }, ], outputPaths, '', ); } catch (err) { assertIsError(err); spinner.fail('Localized bundle generation failed: ' + err.message); return false; } finally { executor.stop(); } if (hasErrors) { spinner.fail('Localized bundle generation failed.'); } else { spinner.succeed('Localized bundle generation complete.'); } return !hasErrors; }
{ "commit_id": "b893a6ae9", "end_byte": 3866, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts" }
angular-cli/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns.ts_0_2656
/** * @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 { statSync } from 'fs'; import assert from 'node:assert'; import * as path from 'path'; import { AssetPattern, AssetPatternClass } from '../builders/browser/schema'; export class MissingAssetSourceRootException extends Error { constructor(path: string) { super(`The ${path} asset path must start with the project source root.`); } } export function normalizeAssetPatterns( assetPatterns: AssetPattern[], workspaceRoot: string, projectRoot: string, projectSourceRoot: string | undefined, ): (AssetPatternClass & { output: string })[] { if (assetPatterns.length === 0) { return []; } // When sourceRoot is not available, we default to ${projectRoot}/src. const sourceRoot = projectSourceRoot || path.join(projectRoot, 'src'); const resolvedSourceRoot = path.resolve(workspaceRoot, sourceRoot); return assetPatterns.map((assetPattern) => { // Normalize string asset patterns to objects. if (typeof assetPattern === 'string') { const assetPath = path.normalize(assetPattern); const resolvedAssetPath = path.resolve(workspaceRoot, assetPath); // Check if the string asset is within sourceRoot. if (!resolvedAssetPath.startsWith(resolvedSourceRoot)) { throw new MissingAssetSourceRootException(assetPattern); } let glob: string, input: string; let isDirectory = false; try { isDirectory = statSync(resolvedAssetPath).isDirectory(); } catch { isDirectory = true; } if (isDirectory) { // Folders get a recursive star glob. glob = '**/*'; // Input directory is their original path. input = assetPath; } else { // Files are their own glob. glob = path.basename(assetPath); // Input directory is their original dirname. input = path.dirname(assetPath); } // Output directory for both is the relative path from source root to input. const output = path.relative(resolvedSourceRoot, path.resolve(workspaceRoot, input)); assetPattern = { glob, input, output }; } else { assetPattern.output = path.join('.', assetPattern.output ?? ''); } assert(assetPattern.output !== undefined); if (assetPattern.output.startsWith('..')) { throw new Error('An asset cannot be written to a location outside of the output path.'); } return assetPattern as AssetPatternClass & { output: string }; }); }
{ "commit_id": "b893a6ae9", "end_byte": 2656, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns.ts" }
angular-cli/packages/angular_devkit/build_angular/src/testing/test-utils.ts_0_264
/** * @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 '../../../../../modules/testing/builder/src';
{ "commit_id": "b893a6ae9", "end_byte": 264, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/testing/test-utils.ts" }
angular-cli/packages/angular_devkit/build_angular/src/testing/index.ts_0_379
/** * @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 */ // TODO: Consider using package.json imports field instead of relative path // after the switch to rules_js. export * from '../../../../../modules/testing/builder/src';
{ "commit_id": "b893a6ae9", "end_byte": 379, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/testing/index.ts" }
angular-cli/packages/angular_devkit/architect_cli/README.md_0_563
# Architect CLI This package contains the executable for running an [Architect Builder](/packages/angular_devkit/architect/README.md). # Usage ``` architect [project][:target][:configuration] [options, ...] Run a project target. If project/target/configuration are not specified, the workspace defaults will be used. Options: --help Show available options for project target. Shows this message instead when ran without the run argument. Any additional option is passed the target, overriding existing options. ```
{ "commit_id": "b893a6ae9", "end_byte": 563, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect_cli/README.md" }
angular-cli/packages/angular_devkit/architect_cli/BUILD.bazel_0_1289
load("//tools:defaults.bzl", "pkg_npm", "ts_library") # Copyright Google Inc. 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 licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "architect_cli", package_name = "@angular-devkit/architect-cli", srcs = [ "bin/architect.ts", ] + glob(["src/**/*.ts"]), module_name = "@angular-devkit/architect-cli", deps = [ "//packages/angular_devkit/architect", "//packages/angular_devkit/architect/node", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "@npm//@types/node", "@npm//@types/progress", "@npm//@types/yargs-parser", "@npm//ansi-colors", ], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/architect:package.json", "//packages/angular_devkit/core:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":architect_cli", ":license", ], )
{ "commit_id": "b893a6ae9", "end_byte": 1289, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect_cli/BUILD.bazel" }
angular-cli/packages/angular_devkit/architect_cli/bin/architect.ts_0_7445
#!/usr/bin/env node /** * @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, BuilderInfo, BuilderProgressState, Target } from '@angular-devkit/architect'; import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; import { JsonValue, json, logging, schema, tags, workspaces } from '@angular-devkit/core'; import { NodeJsSyncHost, createConsoleLogger } from '@angular-devkit/core/node'; import * as ansiColors from 'ansi-colors'; import { existsSync } from 'fs'; import * as path from 'path'; import yargsParser, { camelCase, decamelize } from 'yargs-parser'; import { MultiProgressBar } from '../src/progress'; function findUp(names: string | string[], from: string) { if (!Array.isArray(names)) { names = [names]; } const root = path.parse(from).root; let currentDir = from; while (currentDir && currentDir !== root) { for (const name of names) { const p = path.join(currentDir, name); if (existsSync(p)) { return p; } } currentDir = path.dirname(currentDir); } return null; } /** * Show usage of the CLI tool, and exit the process. */ function usage(logger: logging.Logger, exitCode = 0): never { logger.info(tags.stripIndent` architect [project][:target][:configuration] [options, ...] Run a project target. If project/target/configuration are not specified, the workspace defaults will be used. Options: --help Show available options for project target. Shows this message instead when ran without the run argument. Any additional option is passed the target, overriding existing options. `); return process.exit(exitCode); } function _targetStringFromTarget({ project, target, configuration }: Target) { return `${project}:${target}${configuration !== undefined ? ':' + configuration : ''}`; } interface BarInfo { status?: string; builder: BuilderInfo; target?: Target; } // Create a separate instance to prevent unintended global changes to the color configuration const colors = ansiColors.create(); async function _executeTarget( parentLogger: logging.Logger, workspace: workspaces.WorkspaceDefinition, root: string, argv: ReturnType<typeof yargsParser>, registry: schema.SchemaRegistry, ) { const architectHost = new WorkspaceNodeModulesArchitectHost(workspace, root); const architect = new Architect(architectHost, registry); // Split a target into its parts. const { _: [targetStr = ''], help, ...options } = argv; const [project, target, configuration] = targetStr.toString().split(':'); const targetSpec = { project, target, configuration }; const logger = new logging.Logger('jobs'); const logs: logging.LogEntry[] = []; logger.subscribe((entry) => logs.push({ ...entry, message: `${entry.name}: ` + entry.message })); // Camelize options as yargs will return the object in kebab-case when camel casing is disabled. const camelCasedOptions: json.JsonObject = {}; for (const [key, value] of Object.entries(options)) { if (/[A-Z]/.test(key)) { throw new Error(`Unknown argument ${key}. Did you mean ${decamelize(key)}?`); } camelCasedOptions[camelCase(key)] = value as JsonValue; } const run = await architect.scheduleTarget(targetSpec, camelCasedOptions, { logger }); const bars = new MultiProgressBar<number, BarInfo>(':name :bar (:current/:total) :status'); run.progress.subscribe((update) => { const data = bars.get(update.id) || { id: update.id, builder: update.builder, target: update.target, status: update.status || '', name: ( (update.target ? _targetStringFromTarget(update.target) : update.builder.name) + ' '.repeat(80) ).substring(0, 40), }; if (update.status !== undefined) { data.status = update.status; } switch (update.state) { case BuilderProgressState.Error: data.status = 'Error: ' + update.error; bars.update(update.id, data); break; case BuilderProgressState.Stopped: data.status = 'Done.'; bars.complete(update.id); bars.update(update.id, data, update.total, update.total); break; case BuilderProgressState.Waiting: bars.update(update.id, data); break; case BuilderProgressState.Running: bars.update(update.id, data, update.current, update.total); break; } bars.render(); }); // Wait for full completion of the builder. try { const result = await run.lastOutput; if (result.success) { parentLogger.info(colors.green('SUCCESS')); } else { parentLogger.info(colors.red('FAILURE')); } parentLogger.info('Result: ' + JSON.stringify({ ...result, info: undefined }, null, 4)); parentLogger.info('\nLogs:'); logs.forEach((l) => parentLogger.next(l)); logs.splice(0); await run.stop(); bars.terminate(); return result.success ? 0 : 1; } catch (err) { parentLogger.info(colors.red('ERROR')); parentLogger.info('\nLogs:'); logs.forEach((l) => parentLogger.next(l)); parentLogger.fatal('Exception:'); parentLogger.fatal((err instanceof Error && err.stack) || `${err}`); return 2; } } async function main(args: string[]): Promise<number> { /** Parse the command line. */ const argv = yargsParser(args, { boolean: ['help'], configuration: { 'dot-notation': false, 'boolean-negation': true, 'strip-aliased': true, 'camel-case-expansion': false, }, }); /** Create the DevKit Logger used through the CLI. */ const logger = createConsoleLogger(argv['verbose'], process.stdout, process.stderr, { info: (s) => s, debug: (s) => s, warn: (s) => colors.bold.yellow(s), error: (s) => colors.bold.red(s), fatal: (s) => colors.bold.red(s), }); // Check the target. const targetStr = argv._[0] || ''; if (!targetStr || argv.help) { // Show architect usage if there's no target. usage(logger); } // Load workspace configuration file. const currentPath = process.cwd(); const configFileNames = ['angular.json', '.angular.json', 'workspace.json', '.workspace.json']; const configFilePath = findUp(configFileNames, currentPath); if (!configFilePath) { logger.fatal( `Workspace configuration file (${configFileNames.join(', ')}) cannot be found in ` + `'${currentPath}' or in parent directories.`, ); return 3; } const root = path.dirname(configFilePath); const registry = new schema.CoreSchemaRegistry(); registry.addPostTransform(schema.transforms.addUndefinedDefaults); // Show usage of deprecated options registry.useXDeprecatedProvider((msg) => logger.warn(msg)); const { workspace } = await workspaces.readWorkspace( configFilePath, workspaces.createWorkspaceHost(new NodeJsSyncHost()), ); // Clear the console. process.stdout.write('\u001Bc'); return await _executeTarget(logger, workspace, root, argv, registry); } main(process.argv.slice(2)).then( (code) => { process.exit(code); }, (err) => { // eslint-disable-next-line no-console console.error('Error: ' + err.stack || err.message || err); process.exit(-1); }, );
{ "commit_id": "b893a6ae9", "end_byte": 7445, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect_cli/bin/architect.ts" }
angular-cli/packages/angular_devkit/architect_cli/src/progress.ts_0_2388
/** * @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 ProgressBar from 'progress'; import * as readline from 'readline'; export class MultiProgressBar<Key, T> { private _bars = new Map<Key, { data: T; bar: ProgressBar }>(); constructor( private _status: string, private _stream = process.stderr, ) {} private _add(id: Key, data: T): { data: T; bar: ProgressBar } { const width = Math.min(80, this._stream.columns || 80); const value = { data, bar: new ProgressBar(this._status, { renderThrottle: 0, clear: true, total: 1, width: width, complete: '#', incomplete: '.', stream: this._stream, }), }; this._bars.set(id, value); readline.moveCursor(this._stream, 0, 1); return value; } complete(id: Key) { const maybeBar = this._bars.get(id); if (maybeBar) { maybeBar.bar.complete = true; } } add(id: Key, data: T) { this._add(id, data); } get(key: Key): T | undefined { const maybeValue = this._bars.get(key); return maybeValue && maybeValue.data; } has(key: Key) { return this._bars.has(key); } update(key: Key, data: T, current?: number, total?: number) { let maybeBar = this._bars.get(key); if (!maybeBar) { maybeBar = this._add(key, data); } maybeBar.data = data; if (total !== undefined) { maybeBar.bar.total = total; } if (current !== undefined) { maybeBar.bar.curr = Math.max(0, Math.min(current, maybeBar.bar.total)); } } render(max = Infinity, sort?: (a: T, b: T) => number) { const stream = this._stream; readline.moveCursor(stream, 0, -this._bars.size); readline.cursorTo(stream, 0); let values: Iterable<{ data: T; bar: ProgressBar }> = this._bars.values(); if (sort) { values = [...values].sort((a, b) => sort(a.data, b.data)); } for (const { data, bar } of values) { if (max-- == 0) { return; } bar.render(data); readline.moveCursor(stream, 0, 1); readline.cursorTo(stream, 0); } } terminate() { for (const { bar } of this._bars.values()) { bar.terminate(); } this._bars.clear(); } }
{ "commit_id": "b893a6ae9", "end_byte": 2388, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect_cli/src/progress.ts" }
angular-cli/packages/angular_devkit/architect/README.md_0_28
# Angular Build Facade WIP
{ "commit_id": "b893a6ae9", "end_byte": 28, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/README.md" }
angular-cli/packages/angular_devkit/architect/BUILD.bazel_0_3266
# Copyright Google Inc. 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 load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test_npm_package") load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") load("//tools:ts_json_schema.bzl", "ts_json_schema") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) # @external_begin ts_json_schema( name = "builder_input_schema", src = "src/input-schema.json", ) ts_json_schema( name = "builder_output_schema", src = "src/output-schema.json", ) ts_json_schema( name = "builder_builders_schema", src = "src/builders-schema.json", ) ts_json_schema( name = "progress_schema", src = "src/progress-schema.json", ) ts_json_schema( name = "operator_schema", src = "builders/operator-schema.json", ) # @external_end ts_library( name = "architect", package_name = "@angular-devkit/architect", srcs = glob( include = [ "src/**/*.ts", "builders/*.ts", ], exclude = ["**/*_spec.ts"], ) + [ # These files are generated from the JSON schema "//packages/angular_devkit/architect:src/input-schema.ts", "//packages/angular_devkit/architect:src/output-schema.ts", "//packages/angular_devkit/architect:src/builders-schema.ts", "//packages/angular_devkit/architect:src/progress-schema.ts", "//packages/angular_devkit/architect:builders/operator-schema.ts", ], data = glob( include = ["**/*.json"], exclude = [ # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ), module_name = "@angular-devkit/architect", module_root = "src/index.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "@npm//@types/node", "@npm//rxjs", ], ) ts_library( name = "architect_test_lib", testonly = True, srcs = glob(["src/**/*_spec.ts"]), deps = [ ":architect", "//packages/angular_devkit/architect/testing", "//packages/angular_devkit/core", "@npm//rxjs", ], ) jasmine_node_test( name = "architect_test", srcs = [":architect_test_lib"], ) # @external_begin genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/core:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":architect", ":license", "//packages/angular_devkit/architect/node", "//packages/angular_devkit/architect/testing", ], ) api_golden_test_npm_package( name = "architect_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular_cli/goldens/public-api/angular_devkit/architect", npm_package = "angular_cli/packages/angular_devkit/architect/npm_package", ) # @external_end
{ "commit_id": "b893a6ae9", "end_byte": 3266, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/BUILD.bazel" }
angular-cli/packages/angular_devkit/architect/builders/false.ts_0_347
/** * @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 { createBuilder } from '../src'; export default createBuilder(() => ({ success: false, error: 'False builder always errors.', }));
{ "commit_id": "b893a6ae9", "end_byte": 347, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/builders/false.ts" }
angular-cli/packages/angular_devkit/architect/builders/all-of.ts_0_2060
/** * @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 { EMPTY, from, map, mergeMap, of } from 'rxjs'; import { BuilderOutput, BuilderRun, createBuilder } from '../src'; import { Schema as OperatorSchema } from './operator-schema'; export default createBuilder<json.JsonObject & OperatorSchema>((options, context) => { const allRuns: Promise<[number, BuilderRun]>[] = []; context.reportProgress( 0, (options.targets ? options.targets.length : 0) + (options.builders ? options.builders.length : 0), ); if (options.targets) { allRuns.push( ...options.targets.map(({ target: targetStr, overrides }, i) => { const [project, target, configuration] = targetStr.split(/:/g, 3); return context .scheduleTarget({ project, target, configuration }, overrides || {}) .then((run) => [i, run] as [number, BuilderRun]); }), ); } if (options.builders) { allRuns.push( ...options.builders.map(({ builder, options }, i) => { return context .scheduleBuilder(builder, options || {}) .then((run) => [i, run] as [number, BuilderRun]); }), ); } const allResults: (BuilderOutput | null)[] = allRuns.map(() => null); let n = 0; context.reportProgress(n++, allRuns.length); return from(allRuns).pipe( mergeMap((runPromise) => from(runPromise)), mergeMap(([i, run]) => run.output.pipe(map((output) => [i, output] as [number, BuilderOutput])), ), mergeMap(([i, output]) => { allResults[i] = output; context.reportProgress(n++, allRuns.length); if (allResults.some((x) => x === null)) { // Some builders aren't done running yet. return EMPTY; } else { return of({ success: allResults.every((x) => (x ? x.success : false)), }); } }), ); });
{ "commit_id": "b893a6ae9", "end_byte": 2060, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/builders/all-of.ts" }
angular-cli/packages/angular_devkit/architect/builders/concat.ts_0_1848
/** * @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 { concatMap, first, from, last, map, of, switchMap } from 'rxjs'; import { BuilderOutput, BuilderRun, createBuilder } from '../src'; import { Schema as OperatorSchema } from './operator-schema'; export default createBuilder<json.JsonObject & OperatorSchema>((options, context) => { const allRuns: (() => Promise<BuilderRun>)[] = []; context.reportProgress( 0, (options.targets ? options.targets.length : 0) + (options.builders ? options.builders.length : 0), ); if (options.targets) { allRuns.push( ...options.targets.map(({ target: targetStr, overrides }) => { const [project, target, configuration] = targetStr.split(/:/g, 3); return () => context.scheduleTarget({ project, target, configuration }, overrides || {}); }), ); } if (options.builders) { allRuns.push( ...options.builders.map(({ builder, options }) => { return () => context.scheduleBuilder(builder, options || {}); }), ); } let stop: BuilderOutput | null = null; let i = 0; context.reportProgress(i++, allRuns.length); return from(allRuns).pipe( concatMap((fn) => stop ? of(null) : from(fn()).pipe(switchMap((run) => (run === null ? of(null) : run.output.pipe(first())))), ), map((output) => { context.reportProgress(i++, allRuns.length); if (output === null || stop !== null) { return stop || { success: false }; } else if (output.success === false) { return (stop = output); } else { return output; } }), last(), ); });
{ "commit_id": "b893a6ae9", "end_byte": 1848, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/builders/concat.ts" }
angular-cli/packages/angular_devkit/architect/builders/true.ts_0_302
/** * @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 { createBuilder } from '../src'; export default createBuilder(() => ({ success: true }));
{ "commit_id": "b893a6ae9", "end_byte": 302, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/builders/true.ts" }
angular-cli/packages/angular_devkit/architect/testing/test-project-host.ts_0_4953
/** * @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 { Path, PathFragment, basename, dirname, join, normalize, relative, virtualFs, } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { Stats } from 'fs'; import { EMPTY, Observable, concatMap, delay, finalize, from, map, mergeMap, of, retry, tap, } from 'rxjs'; /** * @deprecated */ export class TestProjectHost extends NodeJsSyncHost { private _currentRoot: Path | null = null; private _scopedSyncHost: virtualFs.SyncDelegateHost<Stats> | null = null; constructor(protected _templateRoot: Path) { super(); } root(): Path { if (this._currentRoot === null) { throw new Error('TestProjectHost must be initialized before being used.'); } return this._currentRoot; } scopedSync(): virtualFs.SyncDelegateHost<Stats> { if (this._currentRoot === null || this._scopedSyncHost === null) { throw new Error('TestProjectHost must be initialized before being used.'); } return this._scopedSyncHost; } initialize(): Observable<void> { const recursiveList = (path: Path): Observable<Path> => this.list(path).pipe( // Emit each fragment individually. concatMap((fragments) => from(fragments)), // Join the path with fragment. map((fragment) => join(path, fragment)), // Emit directory content paths instead of the directory path. mergeMap((path) => this.isDirectory(path).pipe( concatMap((isDir) => (isDir ? recursiveList(path) : of(path))), ), ), ); // Find a unique folder that we can write to use as current root. return this.findUniqueFolderPath().pipe( // Save the path and create a scoped host for it. tap((newFolderPath) => { this._currentRoot = newFolderPath; this._scopedSyncHost = new virtualFs.SyncDelegateHost( new virtualFs.ScopedHost(this, this.root()), ); }), // List all files in root. concatMap(() => recursiveList(this._templateRoot)), // Copy them over to the current root. concatMap((from) => { const to = join(this.root(), relative(this._templateRoot, from)); return this.read(from).pipe(concatMap((buffer) => this.write(to, buffer))); }), map(() => {}), ); } restore(): Observable<void> { if (this._currentRoot === null) { return EMPTY; } // Delete the current root and clear the variables. // Wait 50ms and retry up to 10 times, to give time for file locks to clear. return this.exists(this.root()).pipe( delay(50), concatMap((exists) => (exists ? this.delete(this.root()) : EMPTY)), retry(10), finalize(() => { this._currentRoot = null; this._scopedSyncHost = null; }), ); } writeMultipleFiles(files: { [path: string]: string | ArrayBufferLike | Buffer }): void { Object.keys(files).forEach((fileName) => { let content = files[fileName]; if (typeof content == 'string') { content = virtualFs.stringToFileBuffer(content); } else if (content instanceof Buffer) { content = content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength); } this.scopedSync().write(normalize(fileName), content); }); } replaceInFile(path: string, match: RegExp | string, replacement: string) { const content = virtualFs.fileBufferToString(this.scopedSync().read(normalize(path))); this.scopedSync().write( normalize(path), virtualFs.stringToFileBuffer(content.replace(match, replacement)), ); } appendToFile(path: string, str: string) { const content = virtualFs.fileBufferToString(this.scopedSync().read(normalize(path))); this.scopedSync().write(normalize(path), virtualFs.stringToFileBuffer(content.concat(str))); } fileMatchExists(dir: string, regex: RegExp): PathFragment | undefined { const [fileName] = this.scopedSync() .list(normalize(dir)) .filter((name) => name.match(regex)); return fileName || undefined; } copyFile(from: string, to: string) { const content = this.scopedSync().read(normalize(from)); this.scopedSync().write(normalize(to), content); } private findUniqueFolderPath(): Observable<Path> { // 11 character alphanumeric string. const randomString = Math.random().toString(36).slice(2); const newFolderName = `test-project-host-${basename(this._templateRoot)}-${randomString}`; const newFolderPath = join(dirname(this._templateRoot), newFolderName); return this.exists(newFolderPath).pipe( concatMap((exists) => (exists ? this.findUniqueFolderPath() : of(newFolderPath))), ); } }
{ "commit_id": "b893a6ae9", "end_byte": 4953, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/testing/test-project-host.ts" }
angular-cli/packages/angular_devkit/architect/testing/testing-architect-host.ts_0_4421
/** * @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 { BuilderInfo, Target, targetStringFromTarget } from '../src'; import { ArchitectHost, Builder } from '../src/internal'; export class TestingArchitectHost implements ArchitectHost { private _builderImportMap = new Map<string, Builder>(); private _builderMap = new Map<string, BuilderInfo>(); private _targetMap = new Map<string, { builderName: string; options: json.JsonObject }>(); /** * Can provide a backend host, in case of integration tests. * @param workspaceRoot The workspace root to use. * @param currentDirectory The current directory to use. * @param _backendHost A host to defer calls that aren't resolved here. */ constructor( public workspaceRoot = '', public currentDirectory = workspaceRoot, private _backendHost: ArchitectHost | null = null, ) {} addBuilder( builderName: string, builder: Builder, description = 'Testing only builder.', optionSchema: json.schema.JsonSchema = { type: 'object' }, ) { this._builderImportMap.set(builderName, builder); this._builderMap.set(builderName, { builderName, description, optionSchema }); } async addBuilderFromPackage(packageName: string) { const packageJson = await import(packageName + '/package.json'); if (!('builders' in packageJson)) { throw new Error('Invalid package.json, builders key not found.'); } if (!packageJson.name) { throw new Error('Invalid package name'); } const builderJsonPath = packageName + '/' + packageJson['builders']; const builderJson = await import(builderJsonPath); const builders = builderJson['builders']; if (!builders) { throw new Error('Invalid builders.json, builders key not found.'); } for (const builderName of Object.keys(builders)) { const b = builders[builderName]; // TODO: remove this check as v1 is not supported anymore. if (!b.implementation) { continue; } const handler = (await import(builderJsonPath + '/../' + b.implementation)).default; const optionsSchema = await import(builderJsonPath + '/../' + b.schema); this.addBuilder(`${packageJson.name}:${builderName}`, handler, b.description, optionsSchema); } } addTarget(target: Target, builderName: string, options: json.JsonObject = {}) { this._targetMap.set(targetStringFromTarget(target), { builderName, options }); } async getBuilderNameForTarget(target: Target): Promise<string | null> { const name = targetStringFromTarget(target); const maybeTarget = this._targetMap.get(name); if (!maybeTarget) { return this._backendHost && this._backendHost.getBuilderNameForTarget(target); } return maybeTarget.builderName; } /** * Resolve a builder. This needs to return a string which will be used in a dynamic `import()` * clause. This should throw if no builder can be found. The dynamic import will throw if * it is unsupported. * @param builderName The name of the builder to be used. * @returns All the info needed for the builder itself. */ async resolveBuilder(builderName: string): Promise<BuilderInfo | null> { return ( this._builderMap.get(builderName) || (this._backendHost && this._backendHost.resolveBuilder(builderName)) ); } async getCurrentDirectory(): Promise<string> { return this.currentDirectory; } async getWorkspaceRoot(): Promise<string> { return this.workspaceRoot; } async getOptionsForTarget(target: Target): Promise<json.JsonObject | null> { const name = targetStringFromTarget(target); const maybeTarget = this._targetMap.get(name); if (!maybeTarget) { return this._backendHost && this._backendHost.getOptionsForTarget(target); } return maybeTarget.options; } async getProjectMetadata(target: Target | string): Promise<json.JsonObject | null> { return this._backendHost && this._backendHost.getProjectMetadata(target as string); } async loadBuilder(info: BuilderInfo): Promise<Builder | null> { return ( this._builderImportMap.get(info.builderName) || (this._backendHost && this._backendHost.loadBuilder(info)) ); } }
{ "commit_id": "b893a6ae9", "end_byte": 4421, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/testing/testing-architect-host.ts" }
angular-cli/packages/angular_devkit/architect/testing/BUILD.bazel_0_723
# Copyright Google Inc. 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 load("//tools:defaults.bzl", "ts_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( include = ["**/*.ts"], exclude = ["**/*_spec.ts"], ), module_name = "@angular-devkit/architect/testing", module_root = "index.d.ts", deps = [ "//packages/angular_devkit/architect", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "@npm//@types/node", "@npm//rxjs", ], )
{ "commit_id": "b893a6ae9", "end_byte": 723, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/testing/BUILD.bazel" }
angular-cli/packages/angular_devkit/architect/testing/index.ts_0_283
/** * @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 './testing-architect-host'; export * from './test-project-host';
{ "commit_id": "b893a6ae9", "end_byte": 283, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/testing/index.ts" }
angular-cli/packages/angular_devkit/architect/node/BUILD.bazel_0_1175
# Copyright Google Inc. 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 load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "ts_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "node", srcs = glob( include = ["**/*.ts"], exclude = ["**/*_spec.ts"], ), module_name = "@angular-devkit/architect/node", module_root = "index.d.ts", deps = [ "//packages/angular_devkit/architect", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "@npm//@types/node", "@npm//rxjs", ], ) ts_library( name = "node_test_lib", testonly = True, srcs = glob( include = [ "**/*_spec.ts", ], ), deps = [ ":node", "//packages/angular_devkit/architect", "//tests/angular_devkit/architect/node/jobs:jobs_test_lib", "@npm//rxjs", ], ) jasmine_node_test( name = "node_test", srcs = [":node_test_lib"], )
{ "commit_id": "b893a6ae9", "end_byte": 1175, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/BUILD.bazel" }
angular-cli/packages/angular_devkit/architect/node/index.ts_0_315
/** * @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 * as jobs from './jobs/job-registry'; export * from './node-modules-architect-host'; export { jobs };
{ "commit_id": "b893a6ae9", "end_byte": 315, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/index.ts" }
angular-cli/packages/angular_devkit/architect/node/node-modules-architect-host.ts_0_1921
/** * @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, workspaces } from '@angular-devkit/core'; import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import * as path from 'node:path'; import { pathToFileURL } from 'node:url'; import { deserialize, serialize } from 'node:v8'; import { BuilderInfo } from '../src'; import { Schema as BuilderSchema } from '../src/builders-schema'; import { Target } from '../src/input-schema'; import { ArchitectHost, Builder, BuilderSymbol } from '../src/internal'; // TODO_ESM: Update to use import.meta.url const localRequire = createRequire(__filename); export type NodeModulesBuilderInfo = BuilderInfo & { import: string; }; function clone(obj: unknown): unknown { try { return deserialize(serialize(obj)); } catch { return JSON.parse(JSON.stringify(obj)) as unknown; } } export interface WorkspaceHost { getBuilderName(project: string, target: string): Promise<string>; getMetadata(project: string): Promise<json.JsonObject>; getOptions(project: string, target: string, configuration?: string): Promise<json.JsonObject>; hasTarget(project: string, target: string): Promise<boolean>; getDefaultConfigurationName(project: string, target: string): Promise<string | undefined>; } function findProjectTarget( workspace: workspaces.WorkspaceDefinition, project: string, target: string, ): workspaces.TargetDefinition { const projectDefinition = workspace.projects.get(project); if (!projectDefinition) { throw new Error(`Project "${project}" does not exist.`); } const targetDefinition = projectDefinition.targets.get(target); if (!targetDefinition) { throw new Error('Project target does not exist.'); } return targetDefinition; }
{ "commit_id": "b893a6ae9", "end_byte": 1921, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/node-modules-architect-host.ts" }
angular-cli/packages/angular_devkit/architect/node/node-modules-architect-host.ts_1923_10668
export class WorkspaceNodeModulesArchitectHost implements ArchitectHost<NodeModulesBuilderInfo> { private workspaceHost: WorkspaceHost; constructor(workspaceHost: WorkspaceHost, _root: string); constructor(workspace: workspaces.WorkspaceDefinition, _root: string); constructor( workspaceOrHost: workspaces.WorkspaceDefinition | WorkspaceHost, protected _root: string, ) { if ('getBuilderName' in workspaceOrHost) { this.workspaceHost = workspaceOrHost; } else { this.workspaceHost = { async getBuilderName(project, target) { const targetDefinition = findProjectTarget(workspaceOrHost, project, target); return targetDefinition.builder; }, async getOptions(project, target, configuration) { const targetDefinition = findProjectTarget(workspaceOrHost, project, target); if (configuration === undefined) { return (targetDefinition.options ?? {}) as json.JsonObject; } if (!targetDefinition.configurations?.[configuration]) { throw new Error(`Configuration '${configuration}' is not set in the workspace.`); } return (targetDefinition.configurations?.[configuration] ?? {}) as json.JsonObject; }, async getMetadata(project) { const projectDefinition = workspaceOrHost.projects.get(project); if (!projectDefinition) { throw new Error(`Project "${project}" does not exist.`); } return { root: projectDefinition.root, sourceRoot: projectDefinition.sourceRoot, prefix: projectDefinition.prefix, ...(clone(workspaceOrHost.extensions) as {}), ...(clone(projectDefinition.extensions) as {}), } as unknown as json.JsonObject; }, async hasTarget(project, target) { return !!workspaceOrHost.projects.get(project)?.targets.has(target); }, async getDefaultConfigurationName(project, target) { return workspaceOrHost.projects.get(project)?.targets.get(target)?.defaultConfiguration; }, }; } } async getBuilderNameForTarget(target: Target) { return this.workspaceHost.getBuilderName(target.project, target.target); } /** * Resolve a builder. This needs to be a string which will be used in a dynamic `import()` * clause. This should throw if no builder can be found. The dynamic import will throw if * it is unsupported. * @param builderStr The name of the builder to be used. * @returns All the info needed for the builder itself. */ resolveBuilder( builderStr: string, basePath = this._root, seenBuilders?: Set<string>, ): Promise<NodeModulesBuilderInfo> { if (seenBuilders?.has(builderStr)) { throw new Error( 'Circular builder alias references detected: ' + [...seenBuilders, builderStr], ); } const [packageName, builderName] = builderStr.split(':', 2); if (!builderName) { throw new Error('No builder name specified.'); } // Resolve and load the builders manifest from the package's `builders` field, if present const packageJsonPath = localRequire.resolve(packageName + '/package.json', { paths: [basePath], }); const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as { builders?: string }; const buildersManifestRawPath = packageJson['builders']; if (!buildersManifestRawPath) { throw new Error(`Package ${JSON.stringify(packageName)} has no builders defined.`); } let buildersManifestPath = path.normalize(buildersManifestRawPath); if (path.isAbsolute(buildersManifestRawPath) || buildersManifestRawPath.startsWith('..')) { throw new Error( `Package "${packageName}" has an invalid builders manifest path: "${buildersManifestRawPath}"`, ); } buildersManifestPath = path.join(path.dirname(packageJsonPath), buildersManifestPath); const buildersManifest = JSON.parse( readFileSync(buildersManifestPath, 'utf-8'), ) as BuilderSchema; const buildersManifestDirectory = path.dirname(buildersManifestPath); // Attempt to locate an entry for the specified builder by name const builder = buildersManifest.builders?.[builderName]; if (!builder) { throw new Error(`Cannot find builder ${JSON.stringify(builderStr)}.`); } // Resolve alias reference if entry is a string if (typeof builder === 'string') { return this.resolveBuilder( builder, path.dirname(packageJsonPath), (seenBuilders ?? new Set()).add(builderStr), ); } // Determine builder implementation path (relative within package only) const implementationPath = builder.implementation && path.normalize(builder.implementation); if (!implementationPath) { throw new Error('Could not find the implementation for builder ' + builderStr); } if (path.isAbsolute(implementationPath) || implementationPath.startsWith('..')) { throw new Error( `Package "${packageName}" has an invalid builder implementation path: "${builderName}" --> "${builder.implementation}"`, ); } // Determine builder option schema path (relative within package only) const schemaPath = builder.schema && path.normalize(builder.schema); if (!schemaPath) { throw new Error('Could not find the schema for builder ' + builderStr); } if (path.isAbsolute(schemaPath) || schemaPath.startsWith('..')) { throw new Error( `Package "${packageName}" has an invalid builder implementation path: "${builderName}" --> "${builder.schema}"`, ); } const schemaText = readFileSync(path.join(buildersManifestDirectory, schemaPath), 'utf-8'); return Promise.resolve({ name: builderStr, builderName, description: builder['description'], optionSchema: JSON.parse(schemaText) as json.schema.JsonSchema, import: path.join(buildersManifestDirectory, implementationPath), }); } async getCurrentDirectory() { return process.cwd(); } async getWorkspaceRoot() { return this._root; } async getOptionsForTarget(target: Target): Promise<json.JsonObject | null> { if (!(await this.workspaceHost.hasTarget(target.project, target.target))) { return null; } let options = await this.workspaceHost.getOptions(target.project, target.target); const targetConfiguration = target.configuration || (await this.workspaceHost.getDefaultConfigurationName(target.project, target.target)); if (targetConfiguration) { const configurations = targetConfiguration.split(',').map((c) => c.trim()); for (const configuration of configurations) { options = { ...options, ...(await this.workspaceHost.getOptions(target.project, target.target, configuration)), }; } } return clone(options) as json.JsonObject; } async getProjectMetadata(target: Target | string): Promise<json.JsonObject | null> { const projectName = typeof target === 'string' ? target : target.project; const metadata = this.workspaceHost.getMetadata(projectName); return metadata; } async loadBuilder(info: NodeModulesBuilderInfo): Promise<Builder> { const builder = await getBuilder(info.import); if (builder[BuilderSymbol]) { return builder; } // Default handling code is for old builders that incorrectly export `default` with non-ESM module if (builder?.default[BuilderSymbol]) { return builder.default; } throw new Error('Builder is not a builder'); } } /** * Lazily compiled dynamic import loader function. */ let load: (<T>(modulePath: string | URL) => Promise<T>) | undefined; /** * This uses a dynamic import to load a module which may be ESM. * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript * will currently, unconditionally downlevel dynamic import into a require call. * require calls cannot load ESM code and will result in a runtime error. To workaround * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. * Once TypeScript provides support for keeping the dynamic import this workaround can * be dropped. * * @param modulePath The path of the module to load. * @returns A Promise that resolves to the dynamically imported module. */ export function loadEsmModule<T>(modulePath: string | URL): Promise<T> { load ??= new Function('modulePath', `return import(modulePath);`) as Exclude< typeof load, undefined >; return load(modulePath); } // eslint-disable-next-line @typescript-eslint/no-explicit-any
{ "commit_id": "b893a6ae9", "end_byte": 10668, "start_byte": 1923, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/node/node-modules-architect-host.ts" }