_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts_0_8699
/** * @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 ng from '@angular/compiler-cli'; import assert from 'node:assert'; import { relative } from 'node:path'; import ts from 'typescript'; import { profileAsync, profileSync } from '../../esbuild/profiling'; import { AngularHostOptions, createAngularCompilerHost, ensureSourceFileVersions, } from '../angular-host'; import { replaceBootstrap } from '../transformers/jit-bootstrap-transformer'; import { createWorkerTransformer } from '../transformers/web-worker-transformer'; import { AngularCompilation, DiagnosticModes, EmitFileResult } from './angular-compilation'; class AngularCompilationState { constructor( public readonly angularProgram: ng.NgtscProgram, public readonly compilerHost: ng.CompilerHost, public readonly typeScriptProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram, public readonly affectedFiles: ReadonlySet<ts.SourceFile>, public readonly templateDiagnosticsOptimization: ng.OptimizeFor, public readonly webWorkerTransform: ts.TransformerFactory<ts.SourceFile>, public readonly diagnosticCache = new WeakMap<ts.SourceFile, ts.Diagnostic[]>(), ) {} get angularCompiler() { return this.angularProgram.compiler; } } export class AotCompilation extends AngularCompilation { #state?: AngularCompilationState; async initialize( tsconfig: string, hostOptions: AngularHostOptions, compilerOptionsTransformer?: (compilerOptions: ng.CompilerOptions) => ng.CompilerOptions, ): Promise<{ affectedFiles: ReadonlySet<ts.SourceFile>; compilerOptions: ng.CompilerOptions; referencedFiles: readonly string[]; externalStylesheets?: ReadonlyMap<string, string>; templateUpdates?: ReadonlyMap<string, string>; }> { // Dynamically load the Angular compiler CLI package const { NgtscProgram, OptimizeFor } = await AngularCompilation.loadCompilerCli(); // Load the compiler configuration and transform as needed const { options: originalCompilerOptions, rootNames, errors: configurationDiagnostics, } = await this.loadConfiguration(tsconfig); const compilerOptions = compilerOptionsTransformer?.(originalCompilerOptions) ?? originalCompilerOptions; if (compilerOptions.externalRuntimeStyles) { hostOptions.externalStylesheets ??= new Map(); } // Create Angular compiler host const host = createAngularCompilerHost(ts, compilerOptions, hostOptions); // Create the Angular specific program that contains the Angular compiler const angularProgram = profileSync( 'NG_CREATE_PROGRAM', () => new NgtscProgram(rootNames, compilerOptions, host, this.#state?.angularProgram), ); const angularCompiler = angularProgram.compiler; const angularTypeScriptProgram = angularProgram.getTsProgram(); ensureSourceFileVersions(angularTypeScriptProgram); let oldProgram = this.#state?.typeScriptProgram; let usingBuildInfo = false; if (!oldProgram) { oldProgram = ts.readBuilderProgram(compilerOptions, host); usingBuildInfo = !!oldProgram; } const typeScriptProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram( angularTypeScriptProgram, host, oldProgram, configurationDiagnostics, ); await profileAsync('NG_ANALYZE_PROGRAM', () => angularCompiler.analyzeAsync()); let templateUpdates; if ( compilerOptions['_enableHmr'] && hostOptions.modifiedFiles && hasOnlyTemplates(hostOptions.modifiedFiles) ) { const componentNodes = [...hostOptions.modifiedFiles].flatMap((file) => [ ...angularCompiler.getComponentsWithTemplateFile(file), ]); for (const node of componentNodes) { if (!ts.isClassDeclaration(node)) { continue; } const componentFilename = node.getSourceFile().fileName; let relativePath = relative(host.getCurrentDirectory(), componentFilename); if (relativePath.startsWith('..')) { relativePath = componentFilename; } const updateId = encodeURIComponent( `${host.getCanonicalFileName(relativePath)}@${node.name?.text}`, ); const updateText = angularCompiler.emitHmrUpdateModule(node); if (updateText === null) { // Build is needed if a template cannot be updated templateUpdates = undefined; break; } templateUpdates ??= new Map<string, string>(); templateUpdates.set(updateId, updateText); } } const affectedFiles = profileSync('NG_FIND_AFFECTED', () => findAffectedFiles(typeScriptProgram, angularCompiler, usingBuildInfo), ); // Get all files referenced in the TypeScript/Angular program including component resources const referencedFiles = typeScriptProgram .getSourceFiles() .filter((sourceFile) => !angularCompiler.ignoreForEmit.has(sourceFile)) .flatMap((sourceFile) => { const resourceDependencies = angularCompiler.getResourceDependencies(sourceFile); // Also invalidate Angular diagnostics for a source file if component resources are modified if (this.#state && hostOptions.modifiedFiles?.size) { for (const resourceDependency of resourceDependencies) { if (hostOptions.modifiedFiles.has(resourceDependency)) { this.#state.diagnosticCache.delete(sourceFile); // Also mark as affected in case changed template affects diagnostics affectedFiles.add(sourceFile); } } } return [sourceFile.fileName, ...resourceDependencies]; }); this.#state = new AngularCompilationState( angularProgram, host, typeScriptProgram, affectedFiles, affectedFiles.size === 1 ? OptimizeFor.SingleFile : OptimizeFor.WholeProgram, createWorkerTransformer(hostOptions.processWebWorker.bind(hostOptions)), this.#state?.diagnosticCache, ); return { affectedFiles, compilerOptions, referencedFiles, externalStylesheets: hostOptions.externalStylesheets, templateUpdates, }; } *collectDiagnostics(modes: DiagnosticModes): Iterable<ts.Diagnostic> { assert(this.#state, 'Angular compilation must be initialized prior to collecting diagnostics.'); const { affectedFiles, angularCompiler, diagnosticCache, templateDiagnosticsOptimization, typeScriptProgram, } = this.#state; const syntactic = modes & DiagnosticModes.Syntactic; const semantic = modes & DiagnosticModes.Semantic; // Collect program level diagnostics if (modes & DiagnosticModes.Option) { yield* typeScriptProgram.getConfigFileParsingDiagnostics(); yield* angularCompiler.getOptionDiagnostics(); yield* typeScriptProgram.getOptionsDiagnostics(); } if (syntactic) { yield* typeScriptProgram.getGlobalDiagnostics(); } // Collect source file specific diagnostics for (const sourceFile of typeScriptProgram.getSourceFiles()) { if (angularCompiler.ignoreForDiagnostics.has(sourceFile)) { continue; } if (syntactic) { // TypeScript will use cached diagnostics for files that have not been // changed or affected for this build when using incremental building. yield* profileSync( 'NG_DIAGNOSTICS_SYNTACTIC', () => typeScriptProgram.getSyntacticDiagnostics(sourceFile), true, ); } if (!semantic) { continue; } yield* profileSync( 'NG_DIAGNOSTICS_SEMANTIC', () => typeScriptProgram.getSemanticDiagnostics(sourceFile), true, ); // Declaration files cannot have template diagnostics if (sourceFile.isDeclarationFile) { continue; } // Only request Angular template diagnostics for affected files to avoid // overhead of template diagnostics for unchanged files. if (affectedFiles.has(sourceFile)) { const angularDiagnostics = profileSync( 'NG_DIAGNOSTICS_TEMPLATE', () => angularCompiler.getDiagnosticsForFile(sourceFile, templateDiagnosticsOptimization), true, ); diagnosticCache.set(sourceFile, angularDiagnostics); yield* angularDiagnostics; } else { const angularDiagnostics = diagnosticCache.get(sourceFile); if (angularDiagnostics) { yield* angularDiagnostics; } } } }
{ "end_byte": 8699, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts" }
angular-cli/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts_8703_16007
emitAffectedFiles(): Iterable<EmitFileResult> { assert(this.#state, 'Angular compilation must be initialized prior to emitting files.'); const { affectedFiles, angularCompiler, compilerHost, typeScriptProgram, webWorkerTransform } = this.#state; const compilerOptions = typeScriptProgram.getCompilerOptions(); const buildInfoFilename = compilerOptions.tsBuildInfoFile ?? '.tsbuildinfo'; const useTypeScriptTranspilation = !compilerOptions.isolatedModules || !!compilerOptions.sourceMap || !!compilerOptions.inlineSourceMap; const emittedFiles = new Map<ts.SourceFile, EmitFileResult>(); const writeFileCallback: ts.WriteFileCallback = (filename, contents, _a, _b, sourceFiles) => { if (!sourceFiles?.length && filename.endsWith(buildInfoFilename)) { // Save builder info contents to specified location compilerHost.writeFile(filename, contents, false); return; } assert(sourceFiles?.length === 1, 'Invalid TypeScript program emit for ' + filename); const sourceFile = ts.getOriginalNode(sourceFiles[0], ts.isSourceFile); if (angularCompiler.ignoreForEmit.has(sourceFile)) { return; } angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile); emittedFiles.set(sourceFile, { filename: sourceFile.fileName, contents }); }; const transformers = angularCompiler.prepareEmit().transformers; transformers.before ??= []; transformers.before.push( replaceBootstrap(() => typeScriptProgram.getProgram().getTypeChecker()), ); transformers.before.push(webWorkerTransform); // Emit is handled in write file callback when using TypeScript if (useTypeScriptTranspilation) { // TypeScript will loop until there are no more affected files in the program while ( typeScriptProgram.emitNextAffectedFile( writeFileCallback, undefined, undefined, transformers, ) ) { /* empty */ } } else if (compilerOptions.tsBuildInfoFile) { // Manually get the builder state for the persistent cache // The TypeScript API currently embeds this behavior inside the program emit // via emitNextAffectedFile but that also applies all internal transforms. const programWithGetState = typeScriptProgram.getProgram() as ts.Program & { emitBuildInfo(writeFileCallback?: ts.WriteFileCallback): void; }; assert( typeof programWithGetState.emitBuildInfo === 'function', 'TypeScript program emitBuildInfo is missing.', ); programWithGetState.emitBuildInfo(); } // Angular may have files that must be emitted but TypeScript does not consider affected for (const sourceFile of typeScriptProgram.getSourceFiles()) { if (emittedFiles.has(sourceFile) || angularCompiler.ignoreForEmit.has(sourceFile)) { continue; } if (sourceFile.isDeclarationFile) { continue; } if ( angularCompiler.incrementalCompilation.safeToSkipEmit(sourceFile) && !affectedFiles.has(sourceFile) ) { continue; } if (useTypeScriptTranspilation) { typeScriptProgram.emit(sourceFile, writeFileCallback, undefined, undefined, transformers); continue; } // When not using TypeScript transpilation, directly apply only Angular specific transformations const transformResult = ts.transform( sourceFile, [ ...(transformers.before ?? []), ...(transformers.after ?? []), ] as ts.TransformerFactory<ts.SourceFile>[], compilerOptions, ); assert( transformResult.transformed.length === 1, 'TypeScript transforms should not produce multiple outputs for ' + sourceFile.fileName, ); let contents; if (sourceFile === transformResult.transformed[0]) { // Use original content if no changes were made contents = sourceFile.text; } else { // Otherwise, print the transformed source file const printer = ts.createPrinter(compilerOptions, transformResult); contents = printer.printFile(transformResult.transformed[0]); } angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile); emittedFiles.set(sourceFile, { filename: sourceFile.fileName, contents }); } return emittedFiles.values(); } } function findAffectedFiles( builder: ts.EmitAndSemanticDiagnosticsBuilderProgram, { ignoreForDiagnostics }: ng.NgtscProgram['compiler'], includeTTC: boolean, ): Set<ts.SourceFile> { const affectedFiles = new Set<ts.SourceFile>(); // eslint-disable-next-line no-constant-condition while (true) { const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, (sourceFile) => { // If the affected file is a TTC shim, add the shim's original source file. // This ensures that changes that affect TTC are typechecked even when the changes // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes. // For example, changing @Input property types of a directive used in another component's // template. // A TTC shim is a file that has been ignored for diagnostics and has a filename ending in `.ngtypecheck.ts`. if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) { // This file name conversion relies on internal compiler logic and should be converted // to an official method when available. 15 is length of `.ngtypecheck.ts` const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts'; const originalSourceFile = builder.getSourceFile(originalFilename); if (originalSourceFile) { affectedFiles.add(originalSourceFile); } return true; } return false; }); if (!result) { break; } affectedFiles.add(result.affected as ts.SourceFile); } // Add all files with associated template type checking files. // Stored TS build info does not have knowledge of the AOT compiler or the typechecking state of the templates. // To ensure that errors are reported correctly, all AOT component diagnostics need to be analyzed even if build // info is present. if (includeTTC) { for (const sourceFile of builder.getSourceFiles()) { if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) { // This file name conversion relies on internal compiler logic and should be converted // to an official method when available. 15 is length of `.ngtypecheck.ts` const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts'; const originalSourceFile = builder.getSourceFile(originalFilename); if (originalSourceFile) { affectedFiles.add(originalSourceFile); } } } } return affectedFiles; } function hasOnlyTemplates(modifiedFiles: Set<string>): boolean { for (const file of modifiedFiles) { const lowerFile = file.toLowerCase(); if (lowerFile.endsWith('.html') || lowerFile.endsWith('.svg')) { continue; } return false; } return true; }
{ "end_byte": 16007, "start_byte": 8703, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts" }
angular-cli/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts_0_3929
/** * @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 ng from '@angular/compiler-cli'; import type { PartialMessage } from 'esbuild'; import type ts from 'typescript'; import { loadEsmModule } from '../../../utils/load-esm'; import { convertTypeScriptDiagnostic } from '../../esbuild/angular/diagnostics'; import { profileAsync, profileSync } from '../../esbuild/profiling'; import type { AngularHostOptions } from '../angular-host'; export interface EmitFileResult { filename: string; contents: string; dependencies?: readonly string[]; } export enum DiagnosticModes { None = 0, Option = 1 << 0, Syntactic = 1 << 1, Semantic = 1 << 2, All = Option | Syntactic | Semantic, } export abstract class AngularCompilation { static #angularCompilerCliModule?: typeof ng; static #typescriptModule?: typeof ts; static async loadCompilerCli(): Promise<typeof ng> { // This uses a wrapped dynamic import to load `@angular/compiler-cli` which is ESM. // Once TypeScript provides support for retaining dynamic imports this workaround can be dropped. AngularCompilation.#angularCompilerCliModule ??= await loadEsmModule<typeof ng>('@angular/compiler-cli'); return AngularCompilation.#angularCompilerCliModule; } static async loadTypescript(): Promise<typeof ts> { AngularCompilation.#typescriptModule ??= await import('typescript'); return AngularCompilation.#typescriptModule; } protected async loadConfiguration(tsconfig: string): Promise<ng.CompilerOptions> { const { readConfiguration } = await AngularCompilation.loadCompilerCli(); return profileSync('NG_READ_CONFIG', () => readConfiguration(tsconfig, { // Angular specific configuration defaults and overrides to ensure a functioning compilation. suppressOutputPathCheck: true, outDir: undefined, sourceMap: false, declaration: false, declarationMap: false, allowEmptyCodegenFiles: false, annotationsAs: 'decorators', enableResourceInlining: false, supportTestBed: false, supportJitMode: false, }), ); } abstract initialize( tsconfig: string, hostOptions: AngularHostOptions, compilerOptionsTransformer?: (compilerOptions: ng.CompilerOptions) => ng.CompilerOptions, ): Promise<{ affectedFiles: ReadonlySet<ts.SourceFile>; compilerOptions: ng.CompilerOptions; referencedFiles: readonly string[]; externalStylesheets?: ReadonlyMap<string, string>; templateUpdates?: ReadonlyMap<string, string>; }>; abstract emitAffectedFiles(): Iterable<EmitFileResult> | Promise<Iterable<EmitFileResult>>; protected abstract collectDiagnostics( modes: DiagnosticModes, ): Iterable<ts.Diagnostic> | Promise<Iterable<ts.Diagnostic>>; async diagnoseFiles( modes = DiagnosticModes.All, ): Promise<{ errors?: PartialMessage[]; warnings?: PartialMessage[] }> { const result: { errors?: PartialMessage[]; warnings?: PartialMessage[] } = {}; // Avoid loading typescript until actually needed. // This allows for avoiding the load of typescript in the main thread when using the parallel compilation. const typescript = await AngularCompilation.loadTypescript(); await profileAsync('NG_DIAGNOSTICS_TOTAL', async () => { for (const diagnostic of await this.collectDiagnostics(modes)) { const message = convertTypeScriptDiagnostic(typescript, diagnostic); if (diagnostic.category === typescript.DiagnosticCategory.Error) { (result.errors ??= []).push(message); } else { (result.warnings ??= []).push(message); } } }); return result; } update?(files: Set<string>): Promise<void>; close?(): Promise<void>; }
{ "end_byte": 3929, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts" }
angular-cli/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts_0_5892
/** * @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 ng from '@angular/compiler-cli'; import assert from 'node:assert'; import ts from 'typescript'; import { loadEsmModule } from '../../../utils/load-esm'; import { profileSync } from '../../esbuild/profiling'; import { AngularHostOptions, createAngularCompilerHost } from '../angular-host'; import { createJitResourceTransformer } from '../transformers/jit-resource-transformer'; import { createWorkerTransformer } from '../transformers/web-worker-transformer'; import { AngularCompilation, DiagnosticModes, EmitFileResult } from './angular-compilation'; class JitCompilationState { constructor( public readonly compilerHost: ng.CompilerHost, public readonly typeScriptProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram, public readonly constructorParametersDownlevelTransform: ts.TransformerFactory<ts.SourceFile>, public readonly replaceResourcesTransform: ts.TransformerFactory<ts.SourceFile>, public readonly webWorkerTransform: ts.TransformerFactory<ts.SourceFile>, ) {} } export class JitCompilation extends AngularCompilation { #state?: JitCompilationState; async initialize( tsconfig: string, hostOptions: AngularHostOptions, compilerOptionsTransformer?: (compilerOptions: ng.CompilerOptions) => ng.CompilerOptions, ): Promise<{ affectedFiles: ReadonlySet<ts.SourceFile>; compilerOptions: ng.CompilerOptions; referencedFiles: readonly string[]; }> { // Dynamically load the Angular compiler CLI package const { constructorParametersDownlevelTransform } = await loadEsmModule< typeof import('@angular/compiler-cli/private/tooling') >('@angular/compiler-cli/private/tooling'); // Load the compiler configuration and transform as needed const { options: originalCompilerOptions, rootNames, errors: configurationDiagnostics, } = await this.loadConfiguration(tsconfig); const compilerOptions = compilerOptionsTransformer?.(originalCompilerOptions) ?? originalCompilerOptions; // Create Angular compiler host const host = createAngularCompilerHost(ts, compilerOptions, hostOptions); // Create the TypeScript Program const typeScriptProgram = profileSync('TS_CREATE_PROGRAM', () => ts.createEmitAndSemanticDiagnosticsBuilderProgram( rootNames, compilerOptions, host, this.#state?.typeScriptProgram ?? ts.readBuilderProgram(compilerOptions, host), configurationDiagnostics, ), ); const affectedFiles = profileSync('TS_FIND_AFFECTED', () => findAffectedFiles(typeScriptProgram), ); this.#state = new JitCompilationState( host, typeScriptProgram, constructorParametersDownlevelTransform(typeScriptProgram.getProgram()), createJitResourceTransformer(() => typeScriptProgram.getProgram().getTypeChecker()), createWorkerTransformer(hostOptions.processWebWorker.bind(hostOptions)), ); const referencedFiles = typeScriptProgram .getSourceFiles() .map((sourceFile) => sourceFile.fileName); return { affectedFiles, compilerOptions, referencedFiles }; } *collectDiagnostics(modes: DiagnosticModes): Iterable<ts.Diagnostic> { assert(this.#state, 'Compilation must be initialized prior to collecting diagnostics.'); const { typeScriptProgram } = this.#state; // Collect program level diagnostics if (modes & DiagnosticModes.Option) { yield* typeScriptProgram.getConfigFileParsingDiagnostics(); yield* typeScriptProgram.getOptionsDiagnostics(); } if (modes & DiagnosticModes.Syntactic) { yield* typeScriptProgram.getGlobalDiagnostics(); yield* profileSync('NG_DIAGNOSTICS_SYNTACTIC', () => typeScriptProgram.getSyntacticDiagnostics(), ); } if (modes & DiagnosticModes.Semantic) { yield* profileSync('NG_DIAGNOSTICS_SEMANTIC', () => typeScriptProgram.getSemanticDiagnostics(), ); } } emitAffectedFiles(): Iterable<EmitFileResult> { assert(this.#state, 'Compilation must be initialized prior to emitting files.'); const { compilerHost, typeScriptProgram, constructorParametersDownlevelTransform, replaceResourcesTransform, webWorkerTransform, } = this.#state; const buildInfoFilename = typeScriptProgram.getCompilerOptions().tsBuildInfoFile ?? '.tsbuildinfo'; const emittedFiles: EmitFileResult[] = []; const writeFileCallback: ts.WriteFileCallback = (filename, contents, _a, _b, sourceFiles) => { if (!sourceFiles?.length && filename.endsWith(buildInfoFilename)) { // Save builder info contents to specified location compilerHost.writeFile(filename, contents, false); return; } assert(sourceFiles?.length === 1, 'Invalid TypeScript program emit for ' + filename); emittedFiles.push({ filename: sourceFiles[0].fileName, contents }); }; const transformers = { before: [ replaceResourcesTransform, constructorParametersDownlevelTransform, webWorkerTransform, ], }; // TypeScript will loop until there are no more affected files in the program while ( typeScriptProgram.emitNextAffectedFile(writeFileCallback, undefined, undefined, transformers) ) { /* empty */ } return emittedFiles; } } function findAffectedFiles( builder: ts.EmitAndSemanticDiagnosticsBuilderProgram, ): Set<ts.SourceFile> { const affectedFiles = new Set<ts.SourceFile>(); let result; while ((result = builder.getSemanticDiagnosticsOfNextAffectedFile())) { affectedFiles.add(result.affected as ts.SourceFile); } return affectedFiles; }
{ "end_byte": 5892, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts" }
angular-cli/packages/angular/build/src/tools/angular/compilation/index.ts_0_389
/** * @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 { AngularCompilation, DiagnosticModes } from './angular-compilation'; export { createAngularCompilation } from './factory'; export { NoopCompilation } from './noop-compilation';
{ "end_byte": 389, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/index.ts" }
angular-cli/packages/angular/build/src/tools/angular/compilation/noop-compilation.ts_0_1340
/** * @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 ng from '@angular/compiler-cli'; import type ts from 'typescript'; import { AngularHostOptions } from '../angular-host'; import { AngularCompilation } from './angular-compilation'; export class NoopCompilation extends AngularCompilation { async initialize( tsconfig: string, hostOptions: AngularHostOptions, compilerOptionsTransformer?: (compilerOptions: ng.CompilerOptions) => ng.CompilerOptions, ): Promise<{ affectedFiles: ReadonlySet<ts.SourceFile>; compilerOptions: ng.CompilerOptions; referencedFiles: readonly string[]; }> { // Load the compiler configuration and transform as needed const { options: originalCompilerOptions } = await this.loadConfiguration(tsconfig); const compilerOptions = compilerOptionsTransformer?.(originalCompilerOptions) ?? originalCompilerOptions; return { affectedFiles: new Set(), compilerOptions, referencedFiles: [] }; } collectDiagnostics(): never { throw new Error('Not available when using noop compilation.'); } emitAffectedFiles(): never { throw new Error('Not available when using noop compilation.'); } }
{ "end_byte": 1340, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/noop-compilation.ts" }
angular-cli/packages/angular/build/src/tools/babel/typings.d.ts_0_632
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ declare module '@babel/helper-annotate-as-pure' { export default function annotateAsPure( pathOrNode: import('@babel/types').Node | { node: import('@babel/types').Node }, ): void; } declare module '@babel/helper-split-export-declaration' { export default function splitExportDeclaration( exportDeclaration: import('@babel/core').NodePath< import('@babel/types').ExportDefaultDeclaration >, ): void; }
{ "end_byte": 632, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/typings.d.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/elide-angular-metadata.ts_0_4229
/** * @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 { NodePath, PluginObj } from '@babel/core'; /** * The name of the Angular class metadata function created by the Angular compiler. */ const SET_CLASS_METADATA_NAME = 'ɵsetClassMetadata'; /** * Name of the asynchronous Angular class metadata function created by the Angular compiler. */ const SET_CLASS_METADATA_ASYNC_NAME = 'ɵsetClassMetadataAsync'; /** * Name of the function that sets debug information on classes. */ const SET_CLASS_DEBUG_INFO_NAME = 'ɵsetClassDebugInfo'; /** * Provides one or more keywords that if found within the content of a source file indicate * that this plugin should be used with a source file. * * @returns An a string iterable containing one or more keywords. */ export function getKeywords(): Iterable<string> { return Object.keys(angularMetadataFunctions); } /** * An object map of function names and related value checks for discovery of Angular generated * metadata calls. */ const angularMetadataFunctions: Record<string, (args: NodePath[]) => boolean> = { [SET_CLASS_METADATA_NAME]: isSetClassMetadataCall, [SET_CLASS_METADATA_ASYNC_NAME]: isSetClassMetadataAsyncCall, [SET_CLASS_DEBUG_INFO_NAME]: isSetClassDebugInfoCall, }; /** * A babel plugin factory function for eliding the Angular class metadata function (`ɵsetClassMetadata`). * * @returns A babel plugin object instance. */ export default function (): PluginObj { return { visitor: { CallExpression(path) { const callee = path.get('callee'); // The function being called must be the metadata function name let calleeName; if (callee.isMemberExpression()) { const calleeProperty = callee.get('property'); if (calleeProperty.isIdentifier()) { calleeName = calleeProperty.node.name; } } else if (callee.isIdentifier()) { calleeName = callee.node.name; } if (!calleeName) { return; } if ( Object.hasOwn(angularMetadataFunctions, calleeName) && angularMetadataFunctions[calleeName](path.get('arguments')) ) { // The metadata function is always emitted inside a function expression const parent = path.getFunctionParent(); if (parent && (parent.isFunctionExpression() || parent.isArrowFunctionExpression())) { // Replace the metadata function with `void 0` which is the equivalent return value // of the metadata function. path.replaceWith(path.scope.buildUndefinedNode()); } } }, }, }; } /** Determines if a function call is a call to `setClassMetadata`. */ function isSetClassMetadataCall(callArguments: NodePath[]): boolean { // `setClassMetadata` calls have to meet the following criteria: // * First must be an identifier // * Second must be an array literal return ( callArguments.length === 4 && callArguments[0].isIdentifier() && callArguments[1].isArrayExpression() ); } /** Determines if a function call is a call to `setClassMetadataAsync`. */ function isSetClassMetadataAsyncCall(callArguments: NodePath[]): boolean { // `setClassMetadataAsync` calls have to meet the following criteria: // * First argument must be an identifier. // * Second argument must be an inline function. // * Third argument must be an inline function. return ( callArguments.length === 3 && callArguments[0].isIdentifier() && isInlineFunction(callArguments[1]) && isInlineFunction(callArguments[2]) ); } /** Determines if a function call is a call to `setClassDebugInfo`. */ function isSetClassDebugInfoCall(callArguments: NodePath[]): boolean { return ( callArguments.length === 2 && callArguments[0].isIdentifier() && callArguments[1].isObjectExpression() ); } /** Determines if a node is an inline function expression. */ function isInlineFunction(path: NodePath): boolean { return path.isFunctionExpression() || path.isArrowFunctionExpression(); }
{ "end_byte": 4229, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/elide-angular-metadata.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions_spec.ts_0_4092
/** * @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 { transformSync } from '@babel/core'; // eslint-disable-next-line import/no-extraneous-dependencies import { format } from 'prettier'; import pureTopLevelPlugin from './pure-toplevel-functions'; function testCase({ input, expected, }: { input: string; expected: string; }): jasmine.ImplementationCallback { return async () => { const result = transformSync(input, { configFile: false, babelrc: false, compact: true, plugins: [pureTopLevelPlugin], }); if (!result?.code) { fail('Expected babel to return a transform result.'); } else { expect(await format(result.code, { parser: 'babel' })).toEqual( await format(expected, { parser: 'babel' }), ); } }; } function testCaseNoChange(input: string): jasmine.ImplementationCallback { return testCase({ input, expected: input }); } describe('pure-toplevel-functions Babel plugin', () => { it( 'annotates top-level new expressions', testCase({ input: 'var result = new SomeClass();', expected: 'var result = /*#__PURE__*/ new SomeClass();', }), ); it( 'annotates top-level function calls', testCase({ input: 'var result = someCall();', expected: 'var result = /*#__PURE__*/ someCall();', }), ); it( 'annotates top-level IIFE assignments with no arguments', testCase({ input: 'var SomeClass = (function () { function SomeClass() { } return SomeClass; })();', expected: 'var SomeClass = /*#__PURE__*/(function () { function SomeClass() { } return SomeClass; })();', }), ); it( 'annotates top-level arrow-function-based IIFE assignments with no arguments', testCase({ input: 'var SomeClass = (() => { function SomeClass() { } return SomeClass; })();', expected: 'var SomeClass = /*#__PURE__*/(() => { function SomeClass() { } return SomeClass; })();', }), ); it( 'does not annotate top-level IIFE assignments with arguments', testCaseNoChange( 'var SomeClass = (function () { function SomeClass() { } return SomeClass; })(abc);', ), ); it( 'does not annotate top-level arrow-function-based IIFE assignments with arguments', testCaseNoChange( 'var SomeClass = (() => { function SomeClass() { } return SomeClass; })(abc);', ), ); it( 'does not annotate call expressions inside function declarations', testCaseNoChange('function funcDecl() { const result = someFunction(); }'), ); it( 'does not annotate call expressions inside function expressions', testCaseNoChange('const foo = function funcDecl() { const result = someFunction(); }'), ); it( 'does not annotate call expressions inside function expressions', testCaseNoChange('const foo = () => { const result = someFunction(); }'), ); it( 'does not annotate new expressions inside function declarations', testCaseNoChange('function funcDecl() { const result = new SomeClass(); }'), ); it( 'does not annotate new expressions inside function expressions', testCaseNoChange('const foo = function funcDecl() { const result = new SomeClass(); }'), ); it( 'does not annotate new expressions inside function expressions', testCaseNoChange('const foo = () => { const result = new SomeClass(); }'), ); it( 'does not annotate TypeScript helper functions (tslib)', testCaseNoChange(` class LanguageState {} __decorate([ __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], LanguageState.prototype, "checkLanguage", null); `), ); it( 'does not annotate object literal methods', testCaseNoChange(` const literal = { method() { var newClazz = new Clazz(); } }; `), ); });
{ "end_byte": 4092, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums_spec.ts_0_1390
/** * @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 { transformSync } from '@babel/core'; // eslint-disable-next-line import/no-extraneous-dependencies import { format } from 'prettier'; import adjustTypeScriptEnums from './adjust-typescript-enums'; const NO_CHANGE = Symbol('NO_CHANGE'); function testCase({ input, expected, }: { input: string; expected: string | typeof NO_CHANGE; }): jasmine.ImplementationCallback { return async () => { const result = transformSync(input, { configFile: false, babelrc: false, plugins: [[adjustTypeScriptEnums]], }); if (!result?.code) { fail('Expected babel to return a transform result.'); } else { expect(await format(result.code, { parser: 'babel' })).toEqual( await format(expected === NO_CHANGE ? input : expected, { parser: 'babel' }), ); } }; } // The majority of these test cases are based off TypeScript emitted enum code for the FW's // `ChangedDetectionStrategy` enum. // https://github.com/angular/angular/blob/55d412c5b1b0ba9b03174f7ad9907961fcafa970/packages/core/src/change_detection/constants.ts#L18 // ``` // export enum ChangeDetectionStrategy { // OnPush = 0, // Default = 1, // } // ```
{ "end_byte": 1390, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums_spec.ts_1391_10334
describe('adjust-typescript-enums Babel plugin', () => { it( 'wraps unexported TypeScript enums', testCase({ input: ` var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); `, expected: ` var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; return ChangeDetectionStrategy; })(ChangeDetectionStrategy || {}); `, }), ); it( 'wraps exported TypeScript enums', testCase({ input: ` export var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); `, expected: ` export var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; return ChangeDetectionStrategy; })(ChangeDetectionStrategy || {}); `, }), ); // Even with recent improvements this case is and was never wrapped. However, it also was not broken // by the transformation. This test ensures that this older emitted enum form does not break with // any future changes. Over time this older form will be encountered less and less frequently. // In the future this test case could be considered for removal. it( 'does not wrap exported TypeScript enums from CommonJS (<5.1)', testCase({ input: ` var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy = exports.ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = {})); `, expected: NO_CHANGE, }), ); it( 'wraps exported TypeScript enums from CommonJS (5.1+)', testCase({ input: ` var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = ChangeDetectionStrategy = {})); `, expected: ` var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; return ChangeDetectionStrategy; })(ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = ChangeDetectionStrategy = {})); `, }), ); it( 'wraps TypeScript enums with custom numbering', testCase({ input: ` export var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 5] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 8] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); `, expected: ` export var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 5)] = "OnPush"; ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 8)] = "Default"; return ChangeDetectionStrategy; })(ChangeDetectionStrategy || {}); `, }), ); it( 'wraps string-based TypeScript enums', testCase({ input: ` var NotificationKind; (function (NotificationKind) { NotificationKind["NEXT"] = "N"; NotificationKind["ERROR"] = "E"; NotificationKind["COMPLETE"] = "C"; })(NotificationKind || (NotificationKind = {})); `, expected: ` var NotificationKind = /*#__PURE__*/ (function (NotificationKind) { NotificationKind["NEXT"] = "N"; NotificationKind["ERROR"] = "E"; NotificationKind["COMPLETE"] = "C"; return NotificationKind; })(NotificationKind || {}); `, }), ); it( 'wraps enums that were renamed due to scope hoisting', testCase({ input: ` var NotificationKind$1; (function (NotificationKind) { NotificationKind["NEXT"] = "N"; NotificationKind["ERROR"] = "E"; NotificationKind["COMPLETE"] = "C"; })(NotificationKind$1 || (NotificationKind$1 = {})); `, expected: ` var NotificationKind$1 = /*#__PURE__*/ (function (NotificationKind) { NotificationKind["NEXT"] = "N"; NotificationKind["ERROR"] = "E"; NotificationKind["COMPLETE"] = "C"; return NotificationKind; })(NotificationKind$1 || {}); `, }), ); it( 'maintains multi-line comments', testCase({ input: ` /** * Supported http methods. * @deprecated use @angular/common/http instead */ var RequestMethod; (function (RequestMethod) { RequestMethod[RequestMethod["Get"] = 0] = "Get"; RequestMethod[RequestMethod["Post"] = 1] = "Post"; RequestMethod[RequestMethod["Put"] = 2] = "Put"; RequestMethod[RequestMethod["Delete"] = 3] = "Delete"; RequestMethod[RequestMethod["Options"] = 4] = "Options"; RequestMethod[RequestMethod["Head"] = 5] = "Head"; RequestMethod[RequestMethod["Patch"] = 6] = "Patch"; })(RequestMethod || (RequestMethod = {})); `, expected: ` /** * Supported http methods. * @deprecated use @angular/common/http instead */ var RequestMethod = /*#__PURE__*/ (function (RequestMethod) { RequestMethod[(RequestMethod["Get"] = 0)] = "Get"; RequestMethod[(RequestMethod["Post"] = 1)] = "Post"; RequestMethod[(RequestMethod["Put"] = 2)] = "Put"; RequestMethod[(RequestMethod["Delete"] = 3)] = "Delete"; RequestMethod[(RequestMethod["Options"] = 4)] = "Options"; RequestMethod[(RequestMethod["Head"] = 5)] = "Head"; RequestMethod[(RequestMethod["Patch"] = 6)] = "Patch"; return RequestMethod; })(RequestMethod || {}); `, }), ); it( 'does not wrap TypeScript enums with side effect values', testCase({ input: ` export var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = console.log('foo'); ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); `, expected: NO_CHANGE, }), ); it( 'does not wrap object literals similar to TypeScript enums', testCase({ input: ` const RendererStyleFlags3 = { Important: 1, DashCase: 2, }; if (typeof RendererStyleFlags3 === 'object') { RendererStyleFlags3[RendererStyleFlags3.Important] = 'DashCase'; } RendererStyleFlags3[RendererStyleFlags3.Important] = 'Important'; `, expected: NO_CHANGE, }), ); it( 'wraps TypeScript enums', testCase({ input: ` var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); `, expected: ` var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; return ChangeDetectionStrategy; })(ChangeDetectionStrategy || {}); `, }), );
{ "end_byte": 10334, "start_byte": 1391, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums_spec.ts_10338_11214
it( 'should wrap TypeScript enums if the declaration identifier has been renamed to avoid collisions', testCase({ input: ` var ChangeDetectionStrategy$1; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy$1 || (ChangeDetectionStrategy$1 = {})); `, expected: ` var ChangeDetectionStrategy$1 = /*#__PURE__*/ (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; return ChangeDetectionStrategy; })(ChangeDetectionStrategy$1 || {}); `, }), ); });
{ "end_byte": 11214, "start_byte": 10338, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts_0_1098
/** * @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 { transformSync } from '@babel/core'; // eslint-disable-next-line import/no-extraneous-dependencies import { format } from 'prettier'; import adjustStaticClassMembers from './adjust-static-class-members'; const NO_CHANGE = Symbol('NO_CHANGE'); function testCase({ input, expected, options, }: { input: string; expected: string | typeof NO_CHANGE; options?: { wrapDecorators?: boolean }; }): jasmine.ImplementationCallback { return async () => { const result = transformSync(input, { configFile: false, babelrc: false, plugins: [[adjustStaticClassMembers, options]], }); if (!result?.code) { fail('Expected babel to return a transform result.'); } else { expect(await format(result.code, { parser: 'babel' })).toEqual( await format(expected === NO_CHANGE ? input : expected, { parser: 'babel' }), ); } }; }
{ "end_byte": 1098, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts_1100_9955
describe('adjust-static-class-members Babel plugin', () => { it( 'elides empty ctorParameters function expression static field', testCase({ input: ` export class SomeClass {} SomeClass.ctorParameters = function () { return []; }; `, expected: 'export class SomeClass {}', }), ); it( 'elides non-empty ctorParameters function expression static field', testCase({ input: ` export class SomeClass {} SomeClass.ctorParameters = function () { return [{type: Injector}]; }; `, expected: 'export class SomeClass {}', }), ); it( 'elides empty ctorParameters arrow expression static field', testCase({ input: ` export class SomeClass {} SomeClass.ctorParameters = () => []; `, expected: 'export class SomeClass {}', }), ); it( 'elides non-empty ctorParameters arrow expression static field', testCase({ input: ` export class SomeClass {} SomeClass.ctorParameters = () => [{type: Injector}]; `, expected: 'export class SomeClass {}', }), ); it( 'keeps ctorParameters static field without arrow/function expression', testCase({ input: ` export class SomeClass {} SomeClass.ctorParameters = 42; `, expected: ` export let SomeClass = /*#__PURE__*/ (() => { class SomeClass {} SomeClass.ctorParameters = 42; return SomeClass; })(); `, }), ); it( 'elides empty decorators static field with array literal', testCase({ input: ` export class SomeClass {} SomeClass.decorators = []; `, expected: 'export class SomeClass {}', }), ); it( 'elides non-empty decorators static field with array literal', testCase({ input: ` export class SomeClass {} SomeClass.decorators = [{ type: Injectable }]; `, expected: 'export class SomeClass {}', }), ); it( 'keeps decorators static field without array literal', testCase({ input: ` export class SomeClass {} SomeClass.decorators = 42; `, expected: ` export let SomeClass = /*#__PURE__*/ (() => { class SomeClass {} SomeClass.decorators = 42; return SomeClass; })(); `, }), ); it( 'elides empty propDecorators static field with object literal', testCase({ input: ` export class SomeClass {} SomeClass.propDecorators = {}; `, expected: 'export class SomeClass {}', }), ); it( 'elides non-empty propDecorators static field with object literal', testCase({ input: ` export class SomeClass {} SomeClass.propDecorators = { 'ngIf': [{ type: Input }] }; `, expected: 'export class SomeClass {}', }), ); it( 'keeps propDecorators static field without object literal', testCase({ input: ` export class SomeClass {} SomeClass.propDecorators = 42; `, expected: ` export let SomeClass = /*#__PURE__*/ (() => { class SomeClass {} SomeClass.propDecorators = 42; return SomeClass; })(); `, }), ); it( 'does not wrap default exported class with no connected siblings', testCase({ // NOTE: This could technically have no changes but the default export splitting detection // does not perform class property analysis currently. input: ` export default class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } `, expected: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } export { CustomComponentEffects as default }; `, }), ); it( 'does wrap not default exported class with only side effect fields', testCase({ input: ` export default class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); `, expected: NO_CHANGE, }), ); it( 'does not wrap class with only side effect fields', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); `, expected: NO_CHANGE, }), ); it( 'does not wrap class with only side effect native fields', testCase({ input: ` class CustomComponentEffects { static someFieldWithSideEffects = console.log('foo'); constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } `, expected: NO_CHANGE, }), ); it( 'does not wrap class with only instance native fields', testCase({ input: ` class CustomComponentEffects { someFieldWithSideEffects = console.log('foo'); constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } `, expected: NO_CHANGE, }), ); it( 'wraps class with pure annotated side effect fields (#__PURE__)', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); return CustomComponentEffects; })(); `, }), ); it( 'wraps class with pure annotated side effect native fields (#__PURE__)', testCase({ input: ` class CustomComponentEffects { static someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { static someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } return CustomComponentEffects; })(); `, }), ); it( 'wraps class with pure annotated side effect fields (@__PURE__)', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /*@__PURE__*/ console.log('foo'); `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /*@__PURE__*/ console.log('foo'); return CustomComponentEffects; })(); `, }), ); it( 'wraps class with pure annotated side effect fields (@pureOrBreakMyCode)', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /**@pureOrBreakMyCode*/ console.log('foo'); `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /**@pureOrBreakMyCode*/ console.log('foo'); return CustomComponentEffects; })(); `, }), );
{ "end_byte": 9955, "start_byte": 1100, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts_9959_19098
it( 'wraps class with closure pure annotated side effect fields', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /* @pureOrBreakMyCode */ console.log('foo'); `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = /* @pureOrBreakMyCode */ console.log('foo'); return CustomComponentEffects; })(); `, }), ); it( 'wraps exported class with a pure static field', testCase({ input: ` export class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; `, expected: ` export let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; return CustomComponentEffects; })(); `, }), ); it( 'wraps exported class with a pure native static field', testCase({ input: ` export class CustomComponentEffects { static someField = 42; constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } `, expected: ` export let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { static someField = 42; constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } return CustomComponentEffects; })(); `, }), ); it( 'wraps class with a basic literal static field', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; return CustomComponentEffects; })(); `, }), ); it( 'wraps class with a pure static field', testCase({ input: ` const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; class TemplateRef {} TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; `, expected: ` const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; let TemplateRef = /*#__PURE__*/ (() => { class TemplateRef {} TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; return TemplateRef; })(); `, }), ); it( 'wraps class with multiple pure static field', testCase({ input: ` const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; class TemplateRef {} TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; TemplateRef.someField = 42; `, expected: ` const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; let TemplateRef = /*#__PURE__*/ (() => { class TemplateRef {} TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; TemplateRef.someField = 42; return TemplateRef; })(); `, }), ); it( 'does not wrap class with only some pure static fields', testCase({ input: ` class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); `, expected: NO_CHANGE, }), ); it( 'does not wrap class with only pure native static fields and some side effect static fields', testCase({ input: ` class CustomComponentEffects { static someField = 42; constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); `, expected: NO_CHANGE, }), ); it( 'does not wrap class with only some pure native static fields', testCase({ input: ` class CustomComponentEffects { static someField = 42; static someFieldWithSideEffects = console.log('foo'); constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } `, expected: NO_CHANGE, }), ); it( 'does not wrap class with class decorators when wrapDecorators is false', testCase({ input: ` let SomeClass = class SomeClass { }; SomeClass = __decorate([ Dec() ], SomeClass); `, expected: NO_CHANGE, options: { wrapDecorators: false }, }), ); it( 'wraps class with Angular ɵfac static field (esbuild)', testCase({ input: ` var Comp2Component = class _Comp2Component { static { this.ɵfac = function Comp2Component_Factory(t) { return new (t || _Comp2Component)(); }; } }; `, expected: ` var Comp2Component = /*#__PURE__*/ (() => { let Comp2Component = class _Comp2Component { static { this.ɵfac = function Comp2Component_Factory(t) { return new (t || _Comp2Component)(); }; } }; return Comp2Component; })(); `, }), ); it( 'wraps class with class decorators when wrapDecorators is true (esbuild output)', testCase({ input: ` var ExampleClass = class { method() { } }; __decorate([ SomeDecorator() ], ExampleClass.prototype, "method", null); `, expected: ` var ExampleClass = /*#__PURE__*/ (() => { let ExampleClass = class { method() {} }; __decorate([SomeDecorator()], ExampleClass.prototype, "method", null); return ExampleClass; })(); `, options: { wrapDecorators: true }, }), ); it( 'wraps class with class decorators when wrapDecorators is true', testCase({ input: ` let SomeClass = class SomeClass { }; SomeClass = __decorate([ SomeDecorator() ], SomeClass); `, expected: ` let SomeClass = /*#__PURE__*/ (() => { let SomeClass = class SomeClass { }; SomeClass = __decorate([ SomeDecorator() ], SomeClass); return SomeClass; })(); `, options: { wrapDecorators: true }, }), ); it( 'does not wrap class with constructor decorators when wrapDecorators is false', testCase({ input: ` let SomeClass = class SomeClass { constructor(foo) { } }; SomeClass = __decorate([ __param(0, SomeDecorator) ], SomeClass); `, expected: NO_CHANGE, options: { wrapDecorators: false }, }), ); it( 'wraps class with constructor decorators when wrapDecorators is true', testCase({ input: ` let SomeClass = class SomeClass { constructor(foo) { } }; SomeClass = __decorate([ __param(0, SomeDecorator) ], SomeClass); `, expected: ` let SomeClass = /*#__PURE__*/ (() => { let SomeClass = class SomeClass { constructor(foo) { } }; SomeClass = __decorate([ __param(0, SomeDecorator) ], SomeClass); return SomeClass; })(); `, options: { wrapDecorators: true }, }), );
{ "end_byte": 19098, "start_byte": 9959, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts_19102_26148
'does not wrap class with field decorators when wrapDecorators is false', testCase({ input: ` class SomeClass { constructor() { this.foo = 42; } } __decorate([ SomeDecorator ], SomeClass.prototype, "foo", void 0); `, expected: NO_CHANGE, options: { wrapDecorators: false }, }), ); it( 'wraps class with field decorators when wrapDecorators is true', testCase({ input: ` class SomeClass { constructor() { this.foo = 42; } } __decorate([ SomeDecorator ], SomeClass.prototype, "foo", void 0); `, expected: ` let SomeClass = /*#__PURE__*/ (() => { class SomeClass { constructor() { this.foo = 42; } } __decorate([ SomeDecorator ], SomeClass.prototype, "foo", void 0); return SomeClass; })(); `, options: { wrapDecorators: true }, }), ); it( 'wraps class with Angular ɵfac static field', testCase({ input: ` class CommonModule { } CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; `, expected: ` let CommonModule = /*#__PURE__*/ (() => { class CommonModule { } CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; return CommonModule; })(); `, }), ); it( 'wraps class with Angular ɵfac static block (ES2022 + useDefineForClassFields: false)', testCase({ input: ` class CommonModule { static { this.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; } static { this.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); } } `, expected: ` let CommonModule = /*#__PURE__*/ (() => { class CommonModule { static { this.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; } static { this.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: CommonModule, }); } } return CommonModule; })(); `, }), ); it( 'does not wrap class with side effect full static block (ES2022 + useDefineForClassFields: false)', testCase({ input: ` class CommonModule { static { globalThis.bar = 1 } } `, expected: NO_CHANGE, }), ); it( 'wraps class with Angular ɵmod static field', testCase({ input: ` class CommonModule { } CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); `, expected: ` let CommonModule = /*#__PURE__*/ (() => { class CommonModule { } CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); return CommonModule; })(); `, }), ); it( 'wraps class with Angular ɵinj static field', testCase({ input: ` class CommonModule { } CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ] }); `, expected: ` let CommonModule = /*#__PURE__*/ (() => { class CommonModule { } CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ] }); return CommonModule; })(); `, }), ); it( 'wraps class with multiple Angular static fields', testCase({ input: ` class CommonModule { } CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ] }); `, expected: ` let CommonModule = /*#__PURE__*/ (() => { class CommonModule { } CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ]}); return CommonModule; })(); `, }), ); it( 'wraps class with multiple Angular native static fields', testCase({ input: ` class CommonModule { static ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; static ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); static ɵinj = ɵngcc0.ɵɵdefineInjector({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ] }); } `, expected: ` let CommonModule = /*#__PURE__*/ (() => { class CommonModule { static ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; static ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule, }); static ɵinj = ɵngcc0.ɵɵdefineInjector({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization, }, ], }); } return CommonModule; })(); `, }), ); it( 'wraps default exported class with pure static fields', testCase({ input: ` export default class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; `, expected: ` let CustomComponentEffects = /*#__PURE__*/ (() => { class CustomComponentEffects { constructor(_actions) { this._actions = _actions; this.doThis = this._actions; } } CustomComponentEffects.someField = 42; return CustomComponentEffects; })(); export { CustomComponentEffects as default }; `, }), ); });
{ "end_byte": 26148, "start_byte": 19102, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/types.d.ts_0_590
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ declare module 'istanbul-lib-instrument' { export interface Visitor { enter(path: import('@babel/core').NodePath<types.Program>): void; exit(path: import('@babel/core').NodePath<types.Program>): void; } export function programVisitor( types: typeof import('@babel/core').types, filePath?: string, options?: { inputSourceMap?: object | null }, ): Visitor; }
{ "end_byte": 590, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/types.d.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/add-code-coverage.ts_0_1268
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { NodePath, PluginObj, types } from '@babel/core'; import { Visitor, programVisitor } from 'istanbul-lib-instrument'; import assert from 'node:assert'; /** * A babel plugin factory function for adding istanbul instrumentation. * * @returns A babel plugin object instance. */ export default function (): PluginObj { const visitors = new WeakMap<NodePath, Visitor>(); return { visitor: { Program: { enter(path, state) { const visitor = programVisitor(types, state.filename, { // Babel returns a Converter object from the `convert-source-map` package inputSourceMap: (state.file.inputMap as undefined | { toObject(): object })?.toObject(), }); visitors.set(path, visitor); visitor.enter(path); }, exit(path) { const visitor = visitors.get(path); assert(visitor, 'Instrumentation visitor should always be present for program path.'); visitor.exit(path); visitors.delete(path); }, }, }, }; }
{ "end_byte": 1268, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/add-code-coverage.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions.ts_0_2173
/** * @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 { PluginObj } from '@babel/core'; import annotateAsPure from '@babel/helper-annotate-as-pure'; import * as tslib from 'tslib'; /** * A cached set of TypeScript helper function names used by the helper name matcher utility function. */ const tslibHelpers = new Set<string>(Object.keys(tslib).filter((h) => h.startsWith('__'))); /** * Determinates whether an identifier name matches one of the TypeScript helper function names. * * @param name The identifier name to check. * @returns True, if the name matches a TypeScript helper name; otherwise, false. */ function isTslibHelperName(name: string): boolean { const nameParts = name.split('$'); const originalName = nameParts[0]; if (nameParts.length > 2 || (nameParts.length === 2 && isNaN(+nameParts[1]))) { return false; } return tslibHelpers.has(originalName); } /** * A babel plugin factory function for adding the PURE annotation to top-level new and call expressions. * * @returns A babel plugin object instance. */ export default function (): PluginObj { return { visitor: { CallExpression(path) { // If the expression has a function parent, it is not top-level if (path.getFunctionParent()) { return; } const callee = path.get('callee'); if ( (callee.isFunctionExpression() || callee.isArrowFunctionExpression()) && path.node.arguments.length !== 0 ) { return; } // Do not annotate TypeScript helpers emitted by the TypeScript compiler. // TypeScript helpers are intended to cause side effects. if (callee.isIdentifier() && isTslibHelperName(callee.node.name)) { return; } annotateAsPure(path); }, NewExpression(path) { // If the expression has a function parent, it is not top-level if (!path.getFunctionParent()) { annotateAsPure(path); } }, }, }; }
{ "end_byte": 2173, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/elide-angular-metadata_spec.ts_0_6421
/** * @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 { transformSync } from '@babel/core'; // eslint-disable-next-line import/no-extraneous-dependencies import { format } from 'prettier'; import elideAngularMetadata from './elide-angular-metadata'; function testCase({ input, expected, }: { input: string; expected: string; }): jasmine.ImplementationCallback { return async () => { const result = transformSync(input, { configFile: false, babelrc: false, compact: true, plugins: [elideAngularMetadata], }); if (!result?.code) { fail('Expected babel to return a transform result.'); } else { expect(await format(result.code, { parser: 'babel' })).toEqual( await format(expected, { parser: 'babel' }), ); } }; } describe('elide-angular-metadata Babel plugin', () => { it( 'elides pure annotated ɵsetClassMetadata', testCase({ input: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (function () { i0.ɵsetClassMetadata(Clazz, [{ type: Component, args: [{ selector: 'app-lazy', template: 'very lazy', styles: [] }] }], null, null); })(); `, expected: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (function () { void 0 })(); `, }), ); it( 'elides JIT mode protected ɵsetClassMetadata', testCase({ input: ` import { Component } from '@angular/core'; export class SomeClass {} (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadata(SomeClass, [{ type: Component, args: [{ selector: 'app-lazy', template: 'very lazy', styles: [] }] }], null, null); })();`, expected: ` import { Component } from '@angular/core'; export class SomeClass {} (function () { (typeof ngJitMode === "undefined" || ngJitMode) && void 0 })();`, }), ); it( 'elides ɵsetClassMetadata inside an arrow-function-based IIFE', testCase({ input: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (() => { i0.ɵsetClassMetadata(Clazz, [{ type: Component, args: [{ selector: 'app-lazy', template: 'very lazy', styles: [] }] }], null, null); })(); `, expected: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (() => { void 0 })(); `, }), ); it( 'elides pure annotated ɵsetClassMetadataAsync', testCase({ input: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (function () { i0.ɵsetClassMetadataAsync(SomeClass, function () { return [import("./cmp-a").then(function (m) { return m.CmpA; })]; }, function (CmpA) { i0.ɵsetClassMetadata(SomeClass, [{ type: Component, args: [{ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: '{#defer}<cmp-a/>{/defer}', }] }], null, null); }); })(); `, expected: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (function () { void 0 })(); `, }), ); it( 'elides JIT mode protected ɵsetClassMetadataAsync', testCase({ input: ` import { Component } from '@angular/core'; export class SomeClass {} (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadataAsync(SomeClass, function () { return [import("./cmp-a").then(function (m) { return m.CmpA; })]; }, function (CmpA) { i0.ɵsetClassMetadata(SomeClass, [{ type: Component, args: [{ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: '{#defer}<cmp-a/>{/defer}', }] }], null, null); }); })(); `, expected: ` import { Component } from '@angular/core'; export class SomeClass {} (function () { (typeof ngJitMode === "undefined" || ngJitMode) && void 0 })(); `, }), ); it( 'elides arrow-function-based ɵsetClassMetadataAsync', testCase({ input: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (() => { i0.ɵsetClassMetadataAsync(SomeClass, () => [import("./cmp-a").then(m => m.CmpA)], (CmpA) => { i0.ɵsetClassMetadata(SomeClass, [{ type: Component, args: [{ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: '{#defer}<cmp-a/>{/defer}', }] }], null, null); }); })(); `, expected: ` import { Component } from '@angular/core'; export class SomeClass {} /*@__PURE__*/ (() => { void 0 })(); `, }), ); it( 'elides arrow-function-based ɵsetClassMetadataAsync', testCase({ input: ` import { Component } from '@angular/core'; class SomeClass {} (() => { (typeof ngDevMode === 'undefined' || ngDevMode) && i0.ɵsetClassDebugInfo(SomeClass, { className: 'SomeClass' }); })(); `, expected: ` import { Component } from "@angular/core"; class SomeClass {} (() => { (typeof ngDevMode === "undefined" || ngDevMode) && void 0; })(); `, }), ); });
{ "end_byte": 6421, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/elide-angular-metadata_spec.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums.ts_0_4239
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { NodePath, PluginObj, types } from '@babel/core'; import annotateAsPure from '@babel/helper-annotate-as-pure'; /** * Provides one or more keywords that if found within the content of a source file indicate * that this plugin should be used with a source file. * * @returns An a string iterable containing one or more keywords. */ export function getKeywords(): Iterable<string> { return ['var']; } /** * A babel plugin factory function for adjusting TypeScript emitted enums. * * @returns A babel plugin object instance. */ export default function (): PluginObj { return { visitor: { VariableDeclaration(path: NodePath<types.VariableDeclaration>) { const { parentPath, node } = path; if (node.kind !== 'var' || node.declarations.length !== 1) { return; } const declaration = path.get('declarations')[0]; if (declaration.node.init) { return; } const declarationId = declaration.node.id; if (!types.isIdentifier(declarationId)) { return; } const hasExport = parentPath.isExportNamedDeclaration() || parentPath.isExportDefaultDeclaration(); const origin = hasExport ? parentPath : path; const nextStatement = origin.getSibling(+(origin.key ?? 0) + 1); if (!nextStatement.isExpressionStatement()) { return; } const nextExpression = nextStatement.get('expression'); if (!nextExpression.isCallExpression() || nextExpression.node.arguments.length !== 1) { return; } const enumCallArgument = nextExpression.get('arguments')[0]; if (!enumCallArgument.isLogicalExpression({ operator: '||' })) { return; } const leftCallArgument = enumCallArgument.get('left'); const rightCallArgument = enumCallArgument.get('right'); // Check if identifiers match var declaration if ( !leftCallArgument.isIdentifier() || !nextExpression.scope.bindingIdentifierEquals( leftCallArgument.node.name, declarationId, ) || !rightCallArgument.isAssignmentExpression() ) { return; } const enumCallee = nextExpression.get('callee'); if (!enumCallee.isFunctionExpression() || enumCallee.node.params.length !== 1) { return; } const parameterId = enumCallee.get('params')[0]; if (!parameterId.isIdentifier()) { return; } // Check if all enum member values are pure. // If not, leave as-is due to potential side efects let hasElements = false; for (const enumStatement of enumCallee.get('body').get('body')) { if (!enumStatement.isExpressionStatement()) { return; } const enumValueAssignment = enumStatement.get('expression'); if ( !enumValueAssignment.isAssignmentExpression() || !enumValueAssignment.get('right').isPure() ) { return; } hasElements = true; } // If there are no enum elements then there is nothing to wrap if (!hasElements) { return; } // Update right-side of initializer call argument to remove redundant assignment if (rightCallArgument.get('left').isIdentifier()) { rightCallArgument.replaceWith(rightCallArgument.get('right')); } // Add a return statement to the enum initializer block enumCallee .get('body') .node.body.push(types.returnStatement(types.cloneNode(parameterId.node))); // Remove existing enum initializer const enumInitializer = nextExpression.node; nextExpression.remove(); annotateAsPure(enumInitializer); // Add the wrapped enum initializer directly to the variable declaration declaration.get('init').replaceWith(enumInitializer); }, }, }; }
{ "end_byte": 4239, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-typescript-enums.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/index.ts_0_511
/** * @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 { default as adjustStaticMembers } from './adjust-static-class-members'; export { default as adjustTypeScriptEnums } from './adjust-typescript-enums'; export { default as elideAngularMetadata } from './elide-angular-metadata'; export { default as markTopLevelPure } from './pure-toplevel-functions';
{ "end_byte": 511, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/index.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members.ts_0_7463
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { NodePath, PluginObj, PluginPass, types } from '@babel/core'; import annotateAsPure from '@babel/helper-annotate-as-pure'; import splitExportDeclaration from '@babel/helper-split-export-declaration'; /** * The name of the Typescript decorator helper function created by the TypeScript compiler. */ const TSLIB_DECORATE_HELPER_NAME = '__decorate'; /** * The set of Angular static fields that should always be wrapped. * These fields may appear to have side effects but are safe to remove if the associated class * is otherwise unused within the output. */ const angularStaticsToWrap = new Set([ 'ɵcmp', 'ɵdir', 'ɵfac', 'ɵinj', 'ɵmod', 'ɵpipe', 'ɵprov', 'INJECTOR_KEY', ]); /** * An object map of static fields and related value checks for discovery of Angular generated * JIT related static fields. */ const angularStaticsToElide: Record<string, (path: NodePath<types.Expression>) => boolean> = { 'ctorParameters'(path) { return path.isFunctionExpression() || path.isArrowFunctionExpression(); }, 'decorators'(path) { return path.isArrayExpression(); }, 'propDecorators'(path) { return path.isObjectExpression(); }, }; /** * Provides one or more keywords that if found within the content of a source file indicate * that this plugin should be used with a source file. * * @returns An a string iterable containing one or more keywords. */ export function getKeywords(): Iterable<string> { return ['class']; } /** * Determines whether a property and its initializer value can be safely wrapped in a pure * annotated IIFE. Values that may cause side effects are not considered safe to wrap. * Wrapping such values may cause runtime errors and/or incorrect runtime behavior. * * @param propertyName The name of the property to analyze. * @param assignmentValue The initializer value that will be assigned to the property. * @returns If the property can be safely wrapped, then true; otherwise, false. */ function canWrapProperty(propertyName: string, assignmentValue: NodePath): boolean { if (angularStaticsToWrap.has(propertyName)) { return true; } const { leadingComments } = assignmentValue.node as { leadingComments?: { value: string }[] }; if ( leadingComments?.some( // `@pureOrBreakMyCode` is used by closure and is present in Angular code ({ value }) => value.includes('@__PURE__') || value.includes('#__PURE__') || value.includes('@pureOrBreakMyCode'), ) ) { return true; } return assignmentValue.isPure(); } /** * Analyze the sibling nodes of a class to determine if any downlevel elements should be * wrapped in a pure annotated IIFE. Also determines if any elements have potential side * effects. * * @param origin The starting NodePath location for analyzing siblings. * @param classIdentifier The identifier node that represents the name of the class. * @param allowWrappingDecorators Whether to allow decorators to be wrapped. * @returns An object containing the results of the analysis. */ function analyzeClassSiblings( origin: NodePath, classIdentifier: types.Identifier, allowWrappingDecorators: boolean, ): { hasPotentialSideEffects: boolean; wrapStatementPaths: NodePath<types.Statement>[] } { const wrapStatementPaths: NodePath<types.Statement>[] = []; let hasPotentialSideEffects = false; for (let i = 1; ; ++i) { const nextStatement = origin.getSibling(+(origin.key ?? 0) + i); if (!nextStatement.isExpressionStatement()) { break; } // Valid sibling statements for class declarations are only assignment expressions // and TypeScript decorator helper call expressions const nextExpression = nextStatement.get('expression'); if (nextExpression.isCallExpression()) { if ( !types.isIdentifier(nextExpression.node.callee) || nextExpression.node.callee.name !== TSLIB_DECORATE_HELPER_NAME ) { break; } if (allowWrappingDecorators) { wrapStatementPaths.push(nextStatement); } else { // Statement cannot be safely wrapped which makes wrapping the class unneeded. // The statement will prevent even a wrapped class from being optimized away. hasPotentialSideEffects = true; } continue; } else if (!nextExpression.isAssignmentExpression()) { break; } // Valid assignment expressions should be member access expressions using the class // name as the object and an identifier as the property for static fields or only // the class name for decorators. const left = nextExpression.get('left'); if (left.isIdentifier()) { if ( !left.scope.bindingIdentifierEquals(left.node.name, classIdentifier) || !types.isCallExpression(nextExpression.node.right) || !types.isIdentifier(nextExpression.node.right.callee) || nextExpression.node.right.callee.name !== TSLIB_DECORATE_HELPER_NAME ) { break; } if (allowWrappingDecorators) { wrapStatementPaths.push(nextStatement); } else { // Statement cannot be safely wrapped which makes wrapping the class unneeded. // The statement will prevent even a wrapped class from being optimized away. hasPotentialSideEffects = true; } continue; } else if ( !left.isMemberExpression() || !types.isIdentifier(left.node.object) || !left.scope.bindingIdentifierEquals(left.node.object.name, classIdentifier) || !types.isIdentifier(left.node.property) ) { break; } const propertyName = left.node.property.name; const assignmentValue = nextExpression.get('right'); if (angularStaticsToElide[propertyName]?.(assignmentValue)) { nextStatement.remove(); --i; } else if (canWrapProperty(propertyName, assignmentValue)) { wrapStatementPaths.push(nextStatement); } else { // Statement cannot be safely wrapped which makes wrapping the class unneeded. // The statement will prevent even a wrapped class from being optimized away. hasPotentialSideEffects = true; } } return { hasPotentialSideEffects, wrapStatementPaths }; } /** * The set of classes already visited and analyzed during the plugin's execution. * This is used to prevent adjusted classes from being repeatedly analyzed which can lead * to an infinite loop. */ const visitedClasses = new WeakSet<types.Class>(); /** * A map of classes that have already been analyzed during the default export splitting step. * This is used to avoid analyzing a class declaration twice if it is a direct default export. */ const exportDefaultAnalysis = new WeakMap<types.Class, ReturnType<typeof analyzeClassSiblings>>(); /** * A babel plugin factory function for adjusting classes; primarily with Angular metadata. * The adjustments include wrapping classes with known safe or no side effects with pure * annotations to support dead code removal of unused classes. Angular compiler generated * metadata static fields not required in AOT mode are also elided to better support bundler- * level treeshaking. * * @returns A babel plugin object instance. */ // eslint-disable-next-line max-lines-per-function export
{ "end_byte": 7463, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members.ts" }
angular-cli/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members.ts_7464_14914
default function (): PluginObj { return { visitor: { // When a class is converted to a variable declaration, the default export must be moved // to a subsequent statement to prevent a JavaScript syntax error. ExportDefaultDeclaration(path: NodePath<types.ExportDefaultDeclaration>, state: PluginPass) { const declaration = path.get('declaration'); if (!declaration.isClassDeclaration() || !declaration.node.id) { return; } const { wrapDecorators } = state.opts as { wrapDecorators: boolean }; const analysis = analyzeClassSiblings(path, declaration.node.id, wrapDecorators); exportDefaultAnalysis.set(declaration.node, analysis); // Splitting the export declaration is not needed if the class will not be wrapped if (analysis.hasPotentialSideEffects) { return; } splitExportDeclaration(path); }, ClassDeclaration(path: NodePath<types.ClassDeclaration>, state: PluginPass) { const { node: classNode, parentPath } = path; const { wrapDecorators } = state.opts as { wrapDecorators: boolean }; // Skip if already visited or has no name if (visitedClasses.has(classNode) || !classNode.id) { return; } // Analyze sibling statements for elements of the class that were downleveled const origin = parentPath.isExportNamedDeclaration() ? parentPath : path; const { wrapStatementPaths, hasPotentialSideEffects } = exportDefaultAnalysis.get(classNode) ?? analyzeClassSiblings(origin, classNode.id, wrapDecorators); visitedClasses.add(classNode); // If no statements to wrap, check for static class properties. if ( hasPotentialSideEffects || (wrapStatementPaths.length === 0 && !analyzeClassStaticProperties(path).shouldWrap) ) { return; } const wrapStatementNodes: types.Statement[] = []; for (const statementPath of wrapStatementPaths) { wrapStatementNodes.push(statementPath.node); statementPath.remove(); } // Wrap class and safe static assignments in a pure annotated IIFE const container = types.arrowFunctionExpression( [], types.blockStatement([ classNode, ...wrapStatementNodes, types.returnStatement(types.cloneNode(classNode.id)), ]), ); const replacementInitializer = types.callExpression( types.parenthesizedExpression(container), [], ); annotateAsPure(replacementInitializer); // Replace class with IIFE wrapped class const declaration = types.variableDeclaration('let', [ types.variableDeclarator(types.cloneNode(classNode.id), replacementInitializer), ]); path.replaceWith(declaration); }, ClassExpression(path: NodePath<types.ClassExpression>, state: PluginPass) { const { node: classNode, parentPath } = path; const { wrapDecorators } = state.opts as { wrapDecorators: boolean }; if (visitedClasses.has(classNode)) { return; } if (!parentPath.isVariableDeclarator() || !types.isIdentifier(parentPath.node.id)) { return; } const origin = parentPath.parentPath; if (!origin.isVariableDeclaration() || origin.node.declarations.length !== 1) { return; } const { wrapStatementPaths, hasPotentialSideEffects } = analyzeClassSiblings( origin, parentPath.node.id, wrapDecorators, ); visitedClasses.add(classNode); // If no statements to wrap, check for static class properties. if ( hasPotentialSideEffects || (wrapStatementPaths.length === 0 && !analyzeClassStaticProperties(path).shouldWrap) ) { return; } const wrapStatementNodes: types.Statement[] = []; for (const statementPath of wrapStatementPaths) { wrapStatementNodes.push(statementPath.node); statementPath.remove(); } // Wrap class and safe static assignments in a pure annotated IIFE const container = types.arrowFunctionExpression( [], types.blockStatement([ types.variableDeclaration('let', [ types.variableDeclarator(types.cloneNode(parentPath.node.id), classNode), ]), ...wrapStatementNodes, types.returnStatement(types.cloneNode(parentPath.node.id)), ]), ); const replacementInitializer = types.callExpression( types.parenthesizedExpression(container), [], ); annotateAsPure(replacementInitializer); // Add the wrapped class directly to the variable declaration parentPath.get('init').replaceWith(replacementInitializer); }, }, }; } /** * Static class properties may be downleveled at later stages in the build pipeline * which results in additional function calls outside the class body. These calls * then cause the class to be referenced and not eligible for removal. Since it is * not known at this stage whether the class needs to be downleveled, the transform * wraps classes preemptively to allow for potential removal within the optimization stages. */ function analyzeClassStaticProperties( path: NodePath<types.ClassDeclaration | types.ClassExpression>, ): { shouldWrap: boolean } { let shouldWrap = false; for (const element of path.get('body').get('body')) { if (element.isClassProperty()) { // Only need to analyze static properties if (!element.node.static) { continue; } // Check for potential side effects. // These checks are conservative and could potentially be expanded in the future. const elementKey = element.get('key'); const elementValue = element.get('value'); if ( elementKey.isIdentifier() && (!elementValue.isExpression() || canWrapProperty(elementKey.node.name, elementValue)) ) { shouldWrap = true; } else { // Not safe to wrap shouldWrap = false; break; } } else if (element.isStaticBlock()) { // Only need to analyze static blocks const body = element.get('body'); if (Array.isArray(body) && body.length > 1) { // Not safe to wrap shouldWrap = false; break; } const expression = body.find((n) => n.isExpressionStatement()); const assignmentExpression = expression?.get('expression'); if (assignmentExpression?.isAssignmentExpression()) { const left = assignmentExpression.get('left'); if (!left.isMemberExpression()) { continue; } if (!left.get('object').isThisExpression()) { // Not safe to wrap shouldWrap = false; break; } const element = left.get('property'); const right = assignmentExpression.get('right'); if ( element.isIdentifier() && (!right.isExpression() || canWrapProperty(element.node.name, right)) ) { shouldWrap = true; } else { // Not safe to wrap shouldWrap = false; break; } } } } return { shouldWrap }; }
{ "end_byte": 14914, "start_byte": 7464, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/babel/plugins/adjust-static-class-members.ts" }
angular-cli/packages/angular/build/src/tools/vite/utils.ts_0_1026
/** * @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 { lookup as lookupMimeType } from 'mrmime'; import { extname } from 'node:path'; export type AngularMemoryOutputFiles = Map< string, { contents: Uint8Array; hash: string; servable: boolean } >; export function pathnameWithoutBasePath(url: string, basePath: string): string { const parsedUrl = new URL(url, 'http://localhost'); const pathname = decodeURIComponent(parsedUrl.pathname); // slice(basePath.length - 1) to retain the trailing slash return basePath !== '/' && pathname.startsWith(basePath) ? pathname.slice(basePath.length - 1) : pathname; } export function lookupMimeTypeFromRequest(url: string): string | undefined { const extension = extname(url.split('?')[0]); if (extension === '.ico') { return 'image/x-icon'; } return extension && lookupMimeType(extension); }
{ "end_byte": 1026, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/utils.ts" }
angular-cli/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts_0_3458
/** * @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 { Connect, Plugin } from 'vite'; import { angularHtmlFallbackMiddleware, createAngularAssetsMiddleware, createAngularComponentMiddleware, createAngularHeadersMiddleware, createAngularIndexHtmlMiddleware, createAngularSsrExternalMiddleware, createAngularSsrInternalMiddleware, } from '../middlewares'; import { AngularMemoryOutputFiles } from '../utils'; export enum ServerSsrMode { /** * No SSR */ NoSsr, /** * Internal server-side rendering (SSR) is handled through the built-in middleware. * * In this mode, the SSR process is managed internally by the dev-server's middleware. * The server automatically renders pages on the server without requiring external * middleware or additional configuration from the developer. */ InternalSsrMiddleware, /** * External server-side rendering (SSR) is handled by a custom middleware defined in server.ts. * * This mode allows developers to define custom SSR behavior by providing a middleware in the * `server.ts` file. It gives more flexibility for handling SSR, such as integrating with other * frameworks or customizing the rendering pipeline. */ ExternalSsrMiddleware, } interface AngularSetupMiddlewaresPluginOptions { outputFiles: AngularMemoryOutputFiles; assets: Map<string, string>; extensionMiddleware?: Connect.NextHandleFunction[]; indexHtmlTransformer?: (content: string) => Promise<string>; usedComponentStyles: Map<string, Set<string>>; templateUpdates: Map<string, string>; ssrMode: ServerSsrMode; } export function createAngularSetupMiddlewaresPlugin( options: AngularSetupMiddlewaresPluginOptions, ): Plugin { return { name: 'vite:angular-setup-middlewares', enforce: 'pre', configureServer(server) { const { indexHtmlTransformer, outputFiles, extensionMiddleware, assets, usedComponentStyles, templateUpdates, ssrMode, } = options; // Headers, assets and resources get handled first server.middlewares.use(createAngularHeadersMiddleware(server)); server.middlewares.use(createAngularComponentMiddleware(templateUpdates)); server.middlewares.use( createAngularAssetsMiddleware(server, assets, outputFiles, usedComponentStyles), ); extensionMiddleware?.forEach((middleware) => server.middlewares.use(middleware)); // Returning a function, installs middleware after the main transform middleware but // before the built-in HTML middleware // eslint-disable-next-line @typescript-eslint/no-misused-promises return async () => { if (ssrMode === ServerSsrMode.ExternalSsrMiddleware) { server.middlewares.use( await createAngularSsrExternalMiddleware(server, indexHtmlTransformer), ); return; } if (ssrMode === ServerSsrMode.InternalSsrMiddleware) { server.middlewares.use(createAngularSsrInternalMiddleware(server, indexHtmlTransformer)); } server.middlewares.use(angularHtmlFallbackMiddleware); server.middlewares.use( createAngularIndexHtmlMiddleware(server, outputFiles, indexHtmlTransformer), ); }; }, }; }
{ "end_byte": 3458, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts" }
angular-cli/packages/angular/build/src/tools/vite/plugins/i18n-locale-plugin.ts_0_1858
/** * @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 { Plugin } from 'vite'; /** * The base module location used to search for locale specific data. */ const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global'; /** * Creates a Vite plugin that resolves Angular locale data files from `@angular/common`. * * @returns A Vite plugin. */ export function createAngularLocaleDataPlugin(): Plugin { return { name: 'angular-locale-data', enforce: 'pre', async resolveId(source) { if (!source.startsWith('angular:locale/data:')) { return; } // Extract the locale from the path const originalLocale = source.split(':', 3)[2]; // Remove any private subtags since these will never match let partialLocale = originalLocale.replace(/-x(-[a-zA-Z0-9]{1,8})+$/, ''); let exact = true; while (partialLocale) { const potentialPath = `${LOCALE_DATA_BASE_MODULE}/${partialLocale}`; const result = await this.resolve(potentialPath); if (result) { if (!exact) { this.warn( `Locale data for '${originalLocale}' cannot be found. Using locale data for '${partialLocale}'.`, ); } return result; } // Remove the last subtag and try again with a less specific locale const parts = partialLocale.split('-'); partialLocale = parts.slice(0, -1).join('-'); exact = false; // The locales "en" and "en-US" are considered exact to retain existing behavior if (originalLocale === 'en-US' && partialLocale === 'en') { exact = true; } } return null; }, }; }
{ "end_byte": 1858, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/plugins/i18n-locale-plugin.ts" }
angular-cli/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts_0_1383
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import remapping, { SourceMapInput } from '@ampproject/remapping'; import type { Plugin } from 'vite'; import { loadEsmModule } from '../../../utils/load-esm'; export async function createAngularSsrTransformPlugin(workspaceRoot: string): Promise<Plugin> { const { normalizePath } = await loadEsmModule<typeof import('vite')>('vite'); return { name: 'vite:angular-ssr-transform', enforce: 'pre', async configureServer(server) { const originalssrTransform = server.ssrTransform; server.ssrTransform = async (code, map, url, originalCode) => { const result = await originalssrTransform(code, null, url, originalCode); if (!result || !result.map || !map) { return result; } const remappedMap = remapping( [result.map as SourceMapInput, map as SourceMapInput], () => null, ); // Set the sourcemap root to the workspace root. This is needed since we set a virtual path as root. remappedMap.sourceRoot = normalizePath(workspaceRoot) + '/'; return { ...result, map: remappedMap as (typeof result)['map'], }; }; }, }; }
{ "end_byte": 1383, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts" }
angular-cli/packages/angular/build/src/tools/vite/plugins/index.ts_0_579
/** * @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 { createAngularMemoryPlugin } from './angular-memory-plugin'; export { createAngularLocaleDataPlugin } from './i18n-locale-plugin'; export { createRemoveIdPrefixPlugin } from './id-prefix-plugin'; export { createAngularSetupMiddlewaresPlugin, ServerSsrMode } from './setup-middlewares-plugin'; export { createAngularSsrTransformPlugin } from './ssr-transform-plugin';
{ "end_byte": 579, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/plugins/index.ts" }
angular-cli/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin.ts_0_1847
/** * @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 { Plugin } from 'vite'; // NOTE: the implementation for this Vite plugin is roughly based on: // https://github.com/MilanKovacic/vite-plugin-externalize-dependencies const VITE_ID_PREFIX = '@id/'; const escapeRegexSpecialChars = (inputString: string): string => { return inputString.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }; export function createRemoveIdPrefixPlugin(externals: string[]): Plugin { return { name: 'angular-plugin-remove-id-prefix', apply: 'serve', configResolved: (resolvedConfig) => { // don't do anything when the list of externals is empty if (externals.length === 0) { return; } const escapedExternals = externals.map(escapeRegexSpecialChars); const prefixedExternalRegex = new RegExp( `${resolvedConfig.base}${VITE_ID_PREFIX}(${escapedExternals.join('|')})`, 'g', ); // @ts-expect-error: Property 'push' does not exist on type 'readonly Plugin<any>[]' // Reasoning: // since the /@id/ prefix is added by Vite's import-analysis plugin, // we must add our actual plugin dynamically, to ensure that it will run // AFTER the import-analysis. resolvedConfig.plugins.push({ name: 'angular-plugin-remove-id-prefix-transform', transform: (code: string) => { // don't do anything when code does not contain the Vite prefix if (!code.includes(VITE_ID_PREFIX)) { return code; } return code.replace(prefixedExternalRegex, (_, externalName) => externalName); }, }); }, }; }
{ "end_byte": 1847, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin.ts" }
angular-cli/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts_0_4203
/** * @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 'node:assert'; import { readFile } from 'node:fs/promises'; import { basename, dirname, join, relative } from 'node:path'; import type { Plugin } from 'vite'; import { loadEsmModule } from '../../../utils/load-esm'; import { AngularMemoryOutputFiles } from '../utils'; interface AngularMemoryPluginOptions { virtualProjectRoot: string; outputFiles: AngularMemoryOutputFiles; external?: string[]; } export async function createAngularMemoryPlugin( options: AngularMemoryPluginOptions, ): Promise<Plugin> { const { virtualProjectRoot, outputFiles, external } = options; const { normalizePath } = await loadEsmModule<typeof import('vite')>('vite'); // See: https://github.com/vitejs/vite/blob/a34a73a3ad8feeacc98632c0f4c643b6820bbfda/packages/vite/src/node/server/pluginContainer.ts#L331-L334 const defaultImporter = join(virtualProjectRoot, 'index.html'); return { name: 'vite:angular-memory', // Ensures plugin hooks run before built-in Vite hooks enforce: 'pre', async resolveId(source, importer) { // Prevent vite from resolving an explicit external dependency (`externalDependencies` option) if (external?.includes(source)) { // This is still not ideal since Vite will still transform the import specifier to // `/@id/${source}` but is currently closer to a raw external than a resolved file path. return source; } if (importer) { let normalizedSource: string | undefined; if (source[0] === '.' && normalizePath(importer).startsWith(virtualProjectRoot)) { // Remove query if present const [importerFile] = importer.split('?', 1); normalizedSource = join(dirname(relative(virtualProjectRoot, importerFile)), source); } else if (source[0] === '/' && importer === defaultImporter) { normalizedSource = basename(source); } if (normalizedSource) { source = '/' + normalizePath(normalizedSource); } } const [file] = source.split('?', 1); if (outputFiles.has(file)) { return join(virtualProjectRoot, source); } }, load(id) { const [file] = id.split('?', 1); const relativeFile = '/' + normalizePath(relative(virtualProjectRoot, file)); const codeContents = outputFiles.get(relativeFile)?.contents; if (codeContents === undefined) { return relativeFile.endsWith('/node_modules/vite/dist/client/client.mjs') ? loadViteClientCode(file) : undefined; } const code = Buffer.from(codeContents).toString('utf-8'); const mapContents = outputFiles.get(relativeFile + '.map')?.contents; return { // Remove source map URL comments from the code if a sourcemap is present. // Vite will inline and add an additional sourcemap URL for the sourcemap. code: mapContents ? code.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, '') : code, map: mapContents && Buffer.from(mapContents).toString('utf-8'), }; }, }; } /** * Reads the resolved Vite client code from disk and updates the content to remove * an unactionable suggestion to update the Vite configuration file to disable the * error overlay. The Vite configuration file is not present when used in the Angular * CLI. * @param file The absolute path to the Vite client code. * @returns */ async function loadViteClientCode(file: string): Promise<string> { const originalContents = await readFile(file, 'utf-8'); const updatedContents = originalContents.replace( `"You can also disable this overlay by setting ", h("code", { part: "config-option-name" }, "server.hmr.overlay"), " to ", h("code", { part: "config-option-value" }, "false"), " in ", h("code", { part: "config-file-name" }, hmrConfigName), "."`, '', ); assert(originalContents !== updatedContents, 'Failed to update Vite client error overlay text.'); return updatedContents; }
{ "end_byte": 4203, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/component-middleware.ts_0_1063
/** * @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 { Connect } from 'vite'; const ANGULAR_COMPONENT_PREFIX = '/@ng/component'; export function createAngularComponentMiddleware( templateUpdates: ReadonlyMap<string, string>, ): Connect.NextHandleFunction { return function angularComponentMiddleware(req, res, next) { if (req.url === undefined || res.writableEnded) { return; } if (!req.url.startsWith(ANGULAR_COMPONENT_PREFIX)) { next(); return; } const requestUrl = new URL(req.url, 'http://localhost'); const componentId = requestUrl.searchParams.get('c'); if (!componentId) { res.statusCode = 400; res.end(); return; } const updateCode = templateUpdates.get(componentId) ?? ''; res.setHeader('Content-Type', 'text/javascript'); res.setHeader('Cache-Control', 'no-cache'); res.end(updateCode); }; }
{ "end_byte": 1063, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/component-middleware.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/html-fallback-middleware.ts_0_1540
/** * @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 { ServerResponse } from 'node:http'; import type { Connect } from 'vite'; import { lookupMimeTypeFromRequest } from '../utils'; const ALLOWED_FALLBACK_METHODS = Object.freeze(['GET', 'HEAD']); export function angularHtmlFallbackMiddleware( req: Connect.IncomingMessage, _res: ServerResponse, next: Connect.NextFunction, ): void { // Similar to how it is handled in vite // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/htmlFallback.ts#L15C19-L15C45 if (!req.method || !ALLOWED_FALLBACK_METHODS.includes(req.method)) { // No fallback for unsupported request methods next(); return; } if (req.url) { const mimeType = lookupMimeTypeFromRequest(req.url); if (mimeType === 'text/html' || mimeType === 'application/xhtml+xml') { // eslint-disable-next-line no-console console.warn( `Request for HTML file "${req.url}" was received but no asset found. Asset may be missing from build.`, ); } else if (mimeType) { // No fallback for request of asset-like files next(); return; } } if ( !req.headers.accept || req.headers.accept.includes('text/html') || req.headers.accept.includes('text/*') || req.headers.accept.includes('*/*') ) { req.url = '/index.html'; } next(); }
{ "end_byte": 1540, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/html-fallback-middleware.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/index-html-middleware.ts_0_1547
/** * @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 { extname } from 'node:path'; import type { Connect, ViteDevServer } from 'vite'; import { AngularMemoryOutputFiles, pathnameWithoutBasePath } from '../utils'; export function createAngularIndexHtmlMiddleware( server: ViteDevServer, outputFiles: AngularMemoryOutputFiles, indexHtmlTransformer: ((content: string) => Promise<string>) | undefined, ): Connect.NextHandleFunction { return function angularIndexHtmlMiddleware(req, res, next) { if (!req.url) { next(); return; } // Parse the incoming request. // The base of the URL is unused but required to parse the URL. const pathname = pathnameWithoutBasePath(req.url, server.config.base); const extension = extname(pathname); if (extension !== '.html') { next(); return; } const rawHtml = outputFiles.get(pathname)?.contents; if (!rawHtml) { next(); return; } server .transformIndexHtml(req.url, Buffer.from(rawHtml).toString('utf-8')) .then(async (processedHtml) => { if (indexHtmlTransformer) { processedHtml = await indexHtmlTransformer(processedHtml); } res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'no-cache'); res.end(processedHtml); }) .catch((error) => next(error)); }; }
{ "end_byte": 1547, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/index-html-middleware.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts_0_6887
/** * @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 { lookup as lookupMimeType } from 'mrmime'; import { extname } from 'node:path'; import type { Connect, ViteDevServer } from 'vite'; import { loadEsmModule } from '../../../utils/load-esm'; import { AngularMemoryOutputFiles, pathnameWithoutBasePath } from '../utils'; export function createAngularAssetsMiddleware( server: ViteDevServer, assets: Map<string, string>, outputFiles: AngularMemoryOutputFiles, usedComponentStyles: Map<string, Set<string>>, ): Connect.NextHandleFunction { return function angularAssetsMiddleware(req, res, next) { if (req.url === undefined || res.writableEnded) { return; } // Parse the incoming request. // The base of the URL is unused but required to parse the URL. const pathname = pathnameWithoutBasePath(req.url, server.config.base); const extension = extname(pathname); const pathnameHasTrailingSlash = pathname[pathname.length - 1] === '/'; // Rewrite all build assets to a vite raw fs URL const assetSourcePath = assets.get(pathname); if (assetSourcePath !== undefined) { // Workaround to disable Vite transformer middleware. // See: https://github.com/vitejs/vite/blob/746a1daab0395f98f0afbdee8f364cb6cf2f3b3f/packages/vite/src/node/server/middlewares/transform.ts#L201 and // https://github.com/vitejs/vite/blob/746a1daab0395f98f0afbdee8f364cb6cf2f3b3f/packages/vite/src/node/server/transformRequest.ts#L204-L206 req.headers.accept = 'text/html'; // The encoding needs to match what happens in the vite static middleware. // ref: https://github.com/vitejs/vite/blob/d4f13bd81468961c8c926438e815ab6b1c82735e/packages/vite/src/node/server/middlewares/static.ts#L163 req.url = `${server.config.base}@fs/${encodeURI(assetSourcePath)}`; next(); return; } // HTML fallbacking // This matches what happens in the vite html fallback middleware. // ref: https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/htmlFallback.ts#L9 const htmlAssetSourcePath = pathnameHasTrailingSlash ? // Trailing slash check for `index.html`. assets.get(pathname + 'index.html') : // Non-trailing slash check for fallback `.html` assets.get(pathname + '.html'); if (htmlAssetSourcePath) { req.url = `${server.config.base}@fs/${encodeURI(htmlAssetSourcePath)}`; next(); return; } // Support HTTP HEAD requests for the virtual output files from the Angular build if (req.method === 'HEAD' && outputFiles.get(pathname)?.servable) { // While a GET will also generate content, the rest of the response is equivalent req.method = 'GET'; } // Resource files are handled directly. // Global stylesheets (CSS files) are currently considered resources to workaround // dev server sourcemap issues with stylesheets. if (extension !== '.js' && extension !== '.html') { const outputFile = outputFiles.get(pathname); if (outputFile?.servable) { const data = outputFile.contents; if (extension === '.css') { // Inject component ID for view encapsulation if requested const componentId = new URL(req.url, 'http://localhost').searchParams.get('ngcomp'); if (componentId !== null) { const etag = `W/"${outputFile.contents.byteLength}-${outputFile.hash}-${componentId}"`; if (req.headers['if-none-match'] === etag) { res.statusCode = 304; res.end(); return; } // Record the component style usage for HMR updates const usedIds = usedComponentStyles.get(pathname); if (usedIds === undefined) { usedComponentStyles.set(pathname, new Set([componentId])); } else { usedIds.add(componentId); } // Shim the stylesheet if a component ID is provided if (componentId.length > 0) { // Validate component ID if (/^[_.\-\p{Letter}\d]+-c\d+$/u.test(componentId)) { loadEsmModule<typeof import('@angular/compiler')>('@angular/compiler') .then((compilerModule) => { const encapsulatedData = compilerModule.encapsulateStyle( new TextDecoder().decode(data), componentId, ); res.setHeader('Content-Type', 'text/css'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('ETag', etag); res.end(encapsulatedData); }) .catch((e) => next(e)); return; } else { // eslint-disable-next-line no-console console.error('Invalid component stylesheet ID request: ' + componentId); } } } } // Avoid resending the content if it has not changed since last request const etag = `W/"${outputFile.contents.byteLength}-${outputFile.hash}"`; if (req.headers['if-none-match'] === etag) { res.statusCode = 304; res.end(); return; } const mimeType = lookupMimeType(extension); if (mimeType) { res.setHeader('Content-Type', mimeType); } res.setHeader('Cache-Control', 'no-cache'); res.setHeader('ETag', etag); res.end(data); return; } } // If the path has no trailing slash and it matches a servable directory redirect to the same path with slash. // This matches the default express static behaviour. // See: https://github.com/expressjs/serve-static/blob/89fc94567fae632718a2157206c52654680e9d01/index.js#L182 if (!pathnameHasTrailingSlash) { for (const assetPath of assets.keys()) { if (pathname === assetPath.substring(0, assetPath.lastIndexOf('/'))) { const { pathname, search, hash } = new URL(req.url, 'http://localhost'); const location = [pathname, '/', search, hash].join(''); res.statusCode = 301; res.setHeader('Content-Type', 'text/html'); res.setHeader('Location', location); res.end(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Redirecting</title> </head> <body> <pre>Redirecting to <a href="${location}">${location}</a></pre> </body> </html> `); return; } } } next(); }; }
{ "end_byte": 6887, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/headers-middleware.ts_0_1343
/** * @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 { ServerResponse } from 'node:http'; import type { Connect, ViteDevServer } from 'vite'; /** * Creates a middleware for adding custom headers. * * This middleware is responsible for setting HTTP headers as configured in the Vite server options. * If headers are defined in the server configuration, they are applied to the server response. * * @param server - The instance of `ViteDevServer` containing the configuration, including custom headers. * @returns A middleware function that processes the incoming request, sets headers if available, * and passes control to the next middleware in the chain. */ export function createAngularHeadersMiddleware(server: ViteDevServer): Connect.NextHandleFunction { return function angularHeadersMiddleware( _req: Connect.IncomingMessage, res: ServerResponse, next: Connect.NextFunction, ) { const headers = server.config.server.headers; if (!headers) { return next(); } for (const [name, value] of Object.entries(headers)) { if (value !== undefined) { res.setHeader(name, value); } } next(); }; }
{ "end_byte": 1343, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/headers-middleware.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts_0_5075
/** * @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 { AngularAppEngine as SSRAngularAppEngine, ɵgetOrCreateAngularServerApp as getOrCreateAngularServerApp, } from '@angular/ssr'; import type { ServerResponse } from 'node:http'; import type { Connect, ViteDevServer } from 'vite'; import { loadEsmModule } from '../../../utils/load-esm'; import { isSsrNodeRequestHandler, isSsrRequestHandler, } from '../../../utils/server-rendering/utils'; export function createAngularSsrInternalMiddleware( server: ViteDevServer, indexHtmlTransformer?: (content: string) => Promise<string>, ): Connect.NextHandleFunction { let cachedAngularServerApp: ReturnType<typeof getOrCreateAngularServerApp> | undefined; return function angularSsrMiddleware( req: Connect.IncomingMessage, res: ServerResponse, next: Connect.NextFunction, ) { if (req.url === undefined) { return next(); } (async () => { // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, // which must be processed by the runtime linker, even if they are not used. await loadEsmModule('@angular/compiler'); const { writeResponseToNodeResponse, createWebRequestFromNodeRequest } = await loadEsmModule<typeof import('@angular/ssr/node')>('@angular/ssr/node'); const { ɵgetOrCreateAngularServerApp } = (await server.ssrLoadModule('/main.server.mjs')) as { ɵgetOrCreateAngularServerApp: typeof getOrCreateAngularServerApp; }; const angularServerApp = ɵgetOrCreateAngularServerApp(); // Only Add the transform hook only if it's a different instance. if (cachedAngularServerApp !== angularServerApp) { angularServerApp.hooks.on('html:transform:pre', async ({ html, url }) => { const processedHtml = await server.transformIndexHtml(url.pathname, html); return indexHtmlTransformer?.(processedHtml) ?? processedHtml; }); cachedAngularServerApp = angularServerApp; } const webReq = new Request(createWebRequestFromNodeRequest(req), { signal: AbortSignal.timeout(30_000), }); const webRes = await angularServerApp.render(webReq); if (!webRes) { return next(); } return writeResponseToNodeResponse(webRes, res); })().catch(next); }; } export async function createAngularSsrExternalMiddleware( server: ViteDevServer, indexHtmlTransformer?: (content: string) => Promise<string>, ): Promise<Connect.NextHandleFunction> { let fallbackWarningShown = false; let cachedAngularAppEngine: typeof SSRAngularAppEngine | undefined; let angularSsrInternalMiddleware: | ReturnType<typeof createAngularSsrInternalMiddleware> | undefined; // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, // which must be processed by the runtime linker, even if they are not used. await loadEsmModule('@angular/compiler'); const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = await loadEsmModule<typeof import('@angular/ssr/node')>('@angular/ssr/node'); return function angularSsrExternalMiddleware( req: Connect.IncomingMessage, res: ServerResponse, next: Connect.NextFunction, ) { (async () => { const { reqHandler, AngularAppEngine } = (await server.ssrLoadModule('./server.mjs')) as { reqHandler?: unknown; AngularAppEngine: typeof SSRAngularAppEngine; }; if (!isSsrNodeRequestHandler(reqHandler) && !isSsrRequestHandler(reqHandler)) { if (!fallbackWarningShown) { // eslint-disable-next-line no-console console.warn( `The 'reqHandler' export in 'server.ts' is either undefined or does not provide a recognized request handler. ` + 'Using the internal SSR middleware instead.', ); fallbackWarningShown = true; } angularSsrInternalMiddleware ??= createAngularSsrInternalMiddleware( server, indexHtmlTransformer, ); angularSsrInternalMiddleware(req, res, next); return; } if (cachedAngularAppEngine !== AngularAppEngine) { AngularAppEngine.ɵhooks.on('html:transform:pre', async ({ html, url }) => { const processedHtml = await server.transformIndexHtml(url.pathname, html); return indexHtmlTransformer?.(processedHtml) ?? processedHtml; }); cachedAngularAppEngine = AngularAppEngine; } // Forward the request to the middleware in server.ts if (isSsrNodeRequestHandler(reqHandler)) { await reqHandler(req, res, next); } else { const webRes = await reqHandler(createWebRequestFromNodeRequest(req)); if (!webRes) { next(); return; } await writeResponseToNodeResponse(webRes, res); } })().catch(next); }; }
{ "end_byte": 5075, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts" }
angular-cli/packages/angular/build/src/tools/vite/middlewares/index.ts_0_683
/** * @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 { createAngularAssetsMiddleware } from './assets-middleware'; export { angularHtmlFallbackMiddleware } from './html-fallback-middleware'; export { createAngularIndexHtmlMiddleware } from './index-html-middleware'; export { createAngularSsrExternalMiddleware, createAngularSsrInternalMiddleware, } from './ssr-middleware'; export { createAngularHeadersMiddleware } from './headers-middleware'; export { createAngularComponentMiddleware } from './component-middleware';
{ "end_byte": 683, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/vite/middlewares/index.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/bundler-execution-result.ts_0_5921
/** * @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 { Message, PartialMessage } from 'esbuild'; import { normalize } from 'node:path'; import type { ChangedFiles } from '../../tools/esbuild/watcher'; import type { ComponentStylesheetBundler } from './angular/component-stylesheets'; import type { SourceFileCache } from './angular/source-file-cache'; import type { BuildOutputFile, BuildOutputFileType, BundlerContext } from './bundler-context'; import { createOutputFile } from './utils'; export interface BuildOutputAsset { source: string; destination: string; } export interface RebuildState { rebuildContexts: BundlerContext[]; componentStyleBundler: ComponentStylesheetBundler; codeBundleCache?: SourceFileCache; fileChanges: ChangedFiles; previousOutputHashes: Map<string, string>; } export interface ExternalResultMetadata { implicitBrowser: string[]; implicitServer: string[]; explicit: string[]; } export type PrerenderedRoutesRecord = Record<string, { headers?: Record<string, string> }>; /** * Represents the result of a single builder execute call. */ export class ExecutionResult { outputFiles: BuildOutputFile[] = []; assetFiles: BuildOutputAsset[] = []; errors: (Message | PartialMessage)[] = []; prerenderedRoutes: PrerenderedRoutesRecord = {}; warnings: (Message | PartialMessage)[] = []; logs: string[] = []; externalMetadata?: ExternalResultMetadata; extraWatchFiles: string[] = []; htmlIndexPath?: string; htmlBaseHref?: string; constructor( private rebuildContexts: BundlerContext[], private componentStyleBundler: ComponentStylesheetBundler, private codeBundleCache?: SourceFileCache, ) {} addOutputFile(path: string, content: string | Uint8Array, type: BuildOutputFileType): void { this.outputFiles.push(createOutputFile(path, content, type)); } addAssets(assets: BuildOutputAsset[]): void { this.assetFiles.push(...assets); } addLog(value: string): void { this.logs.push(value); } addError(error: PartialMessage | string): void { if (typeof error === 'string') { this.errors.push({ text: error, location: null }); } else { this.errors.push(error); } } addErrors(errors: (PartialMessage | string)[]): void { for (const error of errors) { this.addError(error); } } addPrerenderedRoutes(routes: PrerenderedRoutesRecord): void { Object.assign(this.prerenderedRoutes, routes); // Sort the prerendered routes. const sortedObj: PrerenderedRoutesRecord = {}; for (const key of Object.keys(this.prerenderedRoutes).sort()) { sortedObj[key] = this.prerenderedRoutes[key]; } this.prerenderedRoutes = sortedObj; } addWarning(error: PartialMessage | string): void { if (typeof error === 'string') { this.warnings.push({ text: error, location: null }); } else { this.warnings.push(error); } } addWarnings(errors: (PartialMessage | string)[]): void { for (const error of errors) { this.addWarning(error); } } /** * Add external JavaScript import metadata to the result. This is currently used * by the development server to optimize the prebundling process. * @param implicitBrowser External dependencies for the browser bundles due to the external packages option. * @param implicitServer External dependencies for the server bundles due to the external packages option. * @param explicit External dependencies due to explicit project configuration. */ setExternalMetadata( implicitBrowser: string[], implicitServer: string[], explicit: string[] | undefined, ): void { this.externalMetadata = { implicitBrowser, implicitServer, explicit: explicit ?? [] }; } get output() { return { success: this.errors.length === 0, }; } get outputWithFiles() { return { success: this.errors.length === 0, outputFiles: this.outputFiles, assetFiles: this.assetFiles, errors: this.errors, externalMetadata: this.externalMetadata, }; } get watchFiles() { // Bundler contexts internally normalize file dependencies const files = this.rebuildContexts.flatMap((context) => [...context.watchFiles]); if (this.codeBundleCache?.referencedFiles) { // These files originate from TS/NG and can have POSIX path separators even on Windows. // To ensure path comparisons are valid, all these paths must be normalized. files.push(...this.codeBundleCache.referencedFiles.map(normalize)); } if (this.codeBundleCache?.loadResultCache) { // Load result caches internally normalize file dependencies files.push(...this.codeBundleCache.loadResultCache.watchFiles); } return files.concat(this.extraWatchFiles); } createRebuildState(fileChanges: ChangedFiles): RebuildState { this.codeBundleCache?.invalidate([...fileChanges.modified, ...fileChanges.removed]); return { rebuildContexts: this.rebuildContexts, codeBundleCache: this.codeBundleCache, componentStyleBundler: this.componentStyleBundler, fileChanges, previousOutputHashes: new Map(this.outputFiles.map((file) => [file.path, file.hash])), }; } findChangedFiles(previousOutputHashes: Map<string, string>): Set<string> { const changed = new Set<string>(); for (const file of this.outputFiles) { const previousHash = previousOutputHashes.get(file.path); if (previousHash === undefined || previousHash !== file.hash) { changed.add(file.path); } } return changed; } async dispose(): Promise<void> { await Promise.allSettled(this.rebuildContexts.map((context) => context.dispose())); await this.componentStyleBundler.dispose(); } }
{ "end_byte": 5921, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/bundler-execution-result.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/profiling.ts_0_2276
/** * @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 { debugPerformance } from '../../utils/environment-options'; let cumulativeDurations: Map<string, number[]> | undefined; export function resetCumulativeDurations(): void { cumulativeDurations?.clear(); } export function logCumulativeDurations(): void { if (!debugPerformance || !cumulativeDurations) { return; } for (const [name, durations] of cumulativeDurations) { let total = 0; let min; let max; for (const duration of durations) { total += duration; if (min === undefined || duration < min) { min = duration; } if (max === undefined || duration > max) { max = duration; } } const average = total / durations.length; // eslint-disable-next-line no-console console.log( `DURATION[${name}]: ${total.toFixed(9)}s [count: ${durations.length}; avg: ${average.toFixed( 9, )}s; min: ${min?.toFixed(9)}s; max: ${max?.toFixed(9)}s]`, ); } } function recordDuration(name: string, startTime: bigint, cumulative?: boolean): void { const duration = Number(process.hrtime.bigint() - startTime) / 10 ** 9; if (cumulative) { cumulativeDurations ??= new Map<string, number[]>(); const durations = cumulativeDurations.get(name) ?? []; durations.push(duration); cumulativeDurations.set(name, durations); } else { // eslint-disable-next-line no-console console.log(`DURATION[${name}]: ${duration.toFixed(9)}s`); } } export async function profileAsync<T>( name: string, action: () => Promise<T>, cumulative?: boolean, ): Promise<T> { if (!debugPerformance) { return action(); } const startTime = process.hrtime.bigint(); try { return await action(); } finally { recordDuration(name, startTime, cumulative); } } export function profileSync<T>(name: string, action: () => T, cumulative?: boolean): T { if (!debugPerformance) { return action(); } const startTime = process.hrtime.bigint(); try { return action(); } finally { recordDuration(name, startTime, cumulative); } }
{ "end_byte": 2276, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/profiling.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/rxjs-esm-resolution-plugin.ts_0_1433
/** * @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 { Plugin } from 'esbuild'; const RXJS_ESM_RESOLUTION = Symbol('RXJS_ESM_RESOLUTION'); /** * Creates a plugin that forces ESM resolution of rxjs. * This is needed as when targeting node, the CJS version is used to the current package conditional exports. * @see: https://github.com/ReactiveX/rxjs/blob/2947583bb33e97f3db9e6d9f6cea70c62a173060/package.json#L19. * * NOTE: This can be removed when and if rxjs adds an import condition that allows ESM usage on Node.js. * * @returns An esbuild plugin. */ export function createRxjsEsmResolutionPlugin(): Plugin { return { name: 'angular-rxjs-resolution', setup(build) { build.onResolve({ filter: /^rxjs/ }, async (args) => { if (args.pluginData?.[RXJS_ESM_RESOLUTION]) { return null; } const { importer, kind, resolveDir, namespace, pluginData = {} } = args; pluginData[RXJS_ESM_RESOLUTION] = true; const result = await build.resolve(args.path, { importer, kind, namespace, pluginData, resolveDir, }); result.path = result.path.replace(/([\\/]dist[\\/])cjs([\\/])/, '$1esm$2'); return result; }); }, }; }
{ "end_byte": 1433, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/rxjs-esm-resolution-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/global-styles.ts_0_3277
/** * @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 'node:assert'; import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import { BundlerOptionsFactory } from './bundler-context'; import { createStylesheetBundleOptions } from './stylesheets/bundle-options'; import { createVirtualModulePlugin } from './virtual-module-plugin'; export function createGlobalStylesBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], initial: boolean, ): BundlerOptionsFactory | undefined { const { workspaceRoot, optimizationOptions, sourcemapOptions, outputNames, globalStyles, preserveSymlinks, externalDependencies, stylePreprocessorOptions, tailwindConfiguration, postcssConfiguration, cacheOptions, } = options; const namespace = 'angular:styles/global'; const entryPoints: Record<string, string> = {}; let found = false; for (const style of globalStyles) { if (style.initial === initial) { found = true; entryPoints[style.name] = `${namespace};${style.name}`; } } // Skip if there are no entry points for the style loading type if (found === false) { return; } return (loadCache) => { const buildOptions = createStylesheetBundleOptions( { workspaceRoot, optimization: !!optimizationOptions.styles.minify, inlineFonts: !!optimizationOptions.fonts.inline, sourcemap: !!sourcemapOptions.styles && (sourcemapOptions.hidden ? 'external' : true), preserveSymlinks, target, externalDependencies, outputNames: initial ? outputNames : { ...outputNames, bundles: '[name]', }, includePaths: stylePreprocessorOptions?.includePaths, // string[] | undefined' is not assignable to type '(Version | DeprecationOrId)[] | undefined'. // eslint-disable-next-line @typescript-eslint/no-explicit-any sass: stylePreprocessorOptions?.sass as any, tailwindConfiguration, postcssConfiguration, cacheOptions, }, loadCache, ); // Keep special CSS comments `/*! comment */` in place when `removeSpecialComments` is disabled. // These comments are special for a number of CSS tools such as Beasties and PurgeCSS. buildOptions.legalComments = optimizationOptions.styles?.removeSpecialComments ? 'none' : 'inline'; buildOptions.entryPoints = entryPoints; buildOptions.plugins.unshift( createVirtualModulePlugin({ namespace, transformPath: (path) => path.split(';', 2)[1], loadContent: (args) => { const files = globalStyles.find(({ name }) => name === args.path)?.files; assert(files, `global style name should always be found [${args.path}]`); return { contents: files.map((file) => `@import '${file.replace(/\\/g, '/')}';`).join('\n'), loader: 'css', resolveDir: workspaceRoot, }; }, }), ); return buildOptions; }; }
{ "end_byte": 3277, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/global-styles.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/server-bundle-metadata-plugin.ts_0_1276
/** * @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 { Plugin } from 'esbuild'; /** * Generates an esbuild plugin that appends metadata to the output bundle, * marking it with server-side rendering (SSR) details for Angular SSR scenarios. * * @param options Optional configuration object. * - `ssrEntryBundle`: If `true`, marks the bundle as an SSR entry point. * * @note We can't rely on `platform: node` or `platform: neutral`, as the latter * is used for non-SSR-related code too (e.g., global scripts). * @returns An esbuild plugin that injects SSR metadata into the build result's metafile. */ export function createServerBundleMetadata(options?: { ssrEntryBundle?: boolean }): Plugin { return { name: 'angular-server-bundle-metadata', setup(build) { build.onEnd((result) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const metafile = result.metafile as any; if (metafile) { metafile['ng-ssr-entry-bundle'] = !!options?.ssrEntryBundle; metafile['ng-platform-server'] = true; } }); }, }; }
{ "end_byte": 1276, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/server-bundle-metadata-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/compiler-plugin-options.ts_0_1350
/** * @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 { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import type { createCompilerPlugin } from './angular/compiler-plugin'; import { ComponentStylesheetBundler } from './angular/component-stylesheets'; import type { SourceFileCache } from './angular/source-file-cache'; type CreateCompilerPluginParameters = Parameters<typeof createCompilerPlugin>; export function createCompilerPluginOptions( options: NormalizedApplicationBuildOptions, sourceFileCache?: SourceFileCache, ): CreateCompilerPluginParameters[0] { const { sourcemapOptions, tsconfig, fileReplacements, advancedOptimizations, jit, externalRuntimeStyles, instrumentForCoverage, } = options; const incremental = !!options.watch; return { sourcemap: !!sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true), thirdPartySourcemaps: sourcemapOptions.vendor, tsconfig, jit, advancedOptimizations, fileReplacements, sourceFileCache, loadResultCache: sourceFileCache?.loadResultCache, incremental, externalRuntimeStyles, instrumentForCoverage, }; }
{ "end_byte": 1350, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/compiler-plugin-options.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/external-packages-plugin.ts_0_2906
/** * @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 { Plugin } from 'esbuild'; import { extname } from 'node:path'; const EXTERNAL_PACKAGE_RESOLUTION = Symbol('EXTERNAL_PACKAGE_RESOLUTION'); /** * Creates a plugin that marks any resolved path as external if it is within a node modules directory. * This is used instead of the esbuild `packages` option to avoid marking files that should be loaded * via customized loaders. This is necessary to prevent Vite development server pre-bundling errors. * * @returns An esbuild plugin. */ export function createExternalPackagesPlugin(options?: { exclude?: string[] }): Plugin { const exclusions = options?.exclude?.length ? new Set(options.exclude) : undefined; return { name: 'angular-external-packages', setup(build) { // Find all loader keys that are not using the 'file' loader. // The 'file' loader is automatically handled by Vite and does not need exclusion. const loaderOptionKeys = build.initialOptions.loader && Object.entries(build.initialOptions.loader) .filter(([, value]) => value !== 'file') .map(([key]) => key); // Safe to use native packages external option if no loader options or exclusions present if (!exclusions && !loaderOptionKeys?.length) { build.initialOptions.packages = 'external'; return; } const loaderFileExtensions = new Set(loaderOptionKeys); // Only attempt resolve of non-relative and non-absolute paths build.onResolve({ filter: /^[^./]/ }, async (args) => { if (args.pluginData?.[EXTERNAL_PACKAGE_RESOLUTION]) { return null; } if (exclusions?.has(args.path)) { return null; } const { importer, kind, resolveDir, namespace, pluginData = {} } = args; pluginData[EXTERNAL_PACKAGE_RESOLUTION] = true; const result = await build.resolve(args.path, { importer, kind, namespace, pluginData, resolveDir, }); // Return result if unable to resolve or explicitly marked external (externalDependencies option) if (!result.path || result.external) { return result; } // Allow customized loaders to run against configured paths regardless of location if (loaderFileExtensions.has(extname(result.path))) { return result; } // Mark paths from a node modules directory as external if (/[\\/]node_modules[\\/]/.test(result.path)) { return { path: args.path, external: true, }; } // Otherwise return original result return result; }); }, }; }
{ "end_byte": 2906, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/external-packages-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/load-result-cache.ts_0_2718
/** * @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 { OnLoadResult, PluginBuild } from 'esbuild'; import { normalize } from 'node:path'; export interface LoadResultCache { get(path: string): OnLoadResult | undefined; put(path: string, result: OnLoadResult): Promise<void>; readonly watchFiles: ReadonlyArray<string>; } export function createCachedLoad( cache: LoadResultCache | undefined, callback: Parameters<PluginBuild['onLoad']>[1], ): Parameters<PluginBuild['onLoad']>[1] { if (cache === undefined) { return callback; } return async (args) => { const loadCacheKey = `${args.namespace}:${args.path}`; let result: OnLoadResult | null | undefined = cache.get(loadCacheKey); if (result === undefined) { result = await callback(args); // Do not cache null or undefined if (result) { // Ensure requested path is included if it was a resolved file if (args.namespace === 'file') { result.watchFiles ??= []; result.watchFiles.push(args.path); } await cache.put(loadCacheKey, result); } } return result; }; } export class MemoryLoadResultCache implements LoadResultCache { #loadResults = new Map<string, OnLoadResult>(); #fileDependencies = new Map<string, Set<string>>(); get(path: string): OnLoadResult | undefined { return this.#loadResults.get(path); } async put(path: string, result: OnLoadResult): Promise<void> { this.#loadResults.set(path, result); if (result.watchFiles) { for (const watchFile of result.watchFiles) { // Normalize the watch file path to ensure OS consistent paths const normalizedWatchFile = normalize(watchFile); let affected = this.#fileDependencies.get(normalizedWatchFile); if (affected === undefined) { affected = new Set(); this.#fileDependencies.set(normalizedWatchFile, affected); } affected.add(path); } } } invalidate(path: string): boolean { const affectedPaths = this.#fileDependencies.get(path); let found = false; if (affectedPaths) { for (const affected of affectedPaths) { if (this.#loadResults.delete(affected)) { found = true; } } this.#fileDependencies.delete(path); } return found; } get watchFiles(): string[] { // this.#loadResults.keys() is not included here because the keys // are namespaced request paths and not disk-based file paths. return [...this.#fileDependencies.keys()]; } }
{ "end_byte": 2718, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/load-result-cache.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/javascript-transformer-worker.ts_0_6107
/** * @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 PluginItem, transformAsync } from '@babel/core'; import fs from 'node:fs'; import path from 'node:path'; import Piscina from 'piscina'; import { loadEsmModule } from '../../utils/load-esm'; interface JavaScriptTransformRequest { filename: string; data: string | Uint8Array; sourcemap: boolean; thirdPartySourcemaps: boolean; advancedOptimizations: boolean; skipLinker?: boolean; sideEffects?: boolean; jit: boolean; instrumentForCoverage?: boolean; } const textDecoder = new TextDecoder(); const textEncoder = new TextEncoder(); export default async function transformJavaScript( request: JavaScriptTransformRequest, ): Promise<unknown> { const { filename, data, ...options } = request; const textData = typeof data === 'string' ? data : textDecoder.decode(data); const transformedData = await transformWithBabel(filename, textData, options); // Transfer the data via `move` instead of cloning return Piscina.move(textEncoder.encode(transformedData)); } /** * Cached instance of the compiler-cli linker's createEs2015LinkerPlugin function. */ let linkerPluginCreator: | typeof import('@angular/compiler-cli/linker/babel').createEs2015LinkerPlugin | undefined; /** * Cached instance of the compiler-cli linker's needsLinking function. */ let needsLinking: typeof import('@angular/compiler-cli/linker').needsLinking | undefined; async function transformWithBabel( filename: string, data: string, options: Omit<JavaScriptTransformRequest, 'filename' | 'data'>, ): Promise<string> { const shouldLink = !options.skipLinker && (await requiresLinking(filename, data)); const useInputSourcemap = options.sourcemap && (!!options.thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename)); // @ts-expect-error Import attribute syntax plugin does not currently have type definitions const { default: importAttributePlugin } = await import('@babel/plugin-syntax-import-attributes'); const plugins: PluginItem[] = [importAttributePlugin]; if (options.instrumentForCoverage) { const { default: coveragePlugin } = await import('../babel/plugins/add-code-coverage.js'); plugins.push(coveragePlugin); } if (shouldLink) { // Lazy load the linker plugin only when linking is required const linkerPlugin = await createLinkerPlugin(options); plugins.push(linkerPlugin); } if (options.advancedOptimizations) { const sideEffectFree = options.sideEffects === false; const safeAngularPackage = sideEffectFree && /[\\/]node_modules[\\/]@angular[\\/]/.test(filename); const { adjustStaticMembers, adjustTypeScriptEnums, elideAngularMetadata, markTopLevelPure } = await import('../babel/plugins'); if (safeAngularPackage) { plugins.push(markTopLevelPure); } plugins.push(elideAngularMetadata, adjustTypeScriptEnums, [ adjustStaticMembers, { wrapDecorators: sideEffectFree }, ]); } // If no additional transformations are needed, return the data directly if (plugins.length === 0) { // Strip sourcemaps if they should not be used return useInputSourcemap ? data : data.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''); } const result = await transformAsync(data, { filename, inputSourceMap: (useInputSourcemap ? undefined : false) as undefined, sourceMaps: useInputSourcemap ? 'inline' : false, compact: false, configFile: false, babelrc: false, browserslistConfigFile: false, plugins, }); const outputCode = result?.code ?? data; // Strip sourcemaps if they should not be used. // Babel will keep the original comments even if sourcemaps are disabled. return useInputSourcemap ? outputCode : outputCode.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''); } async function requiresLinking(path: string, source: string): Promise<boolean> { // @angular/core and @angular/compiler will cause false positives // Also, TypeScript files do not require linking if (/[\\/]@angular[\\/](?:compiler|core)|\.tsx?$/.test(path)) { return false; } if (!needsLinking) { // Load ESM `@angular/compiler-cli/linker` using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. const linkerModule = await loadEsmModule<typeof import('@angular/compiler-cli/linker')>( '@angular/compiler-cli/linker', ); needsLinking = linkerModule.needsLinking; } return needsLinking(path, source); } async function createLinkerPlugin(options: Omit<JavaScriptTransformRequest, 'filename' | 'data'>) { linkerPluginCreator ??= ( await loadEsmModule<typeof import('@angular/compiler-cli/linker/babel')>( '@angular/compiler-cli/linker/babel', ) ).createEs2015LinkerPlugin; const linkerPlugin = linkerPluginCreator({ linkerJitMode: options.jit, // This is a workaround until https://github.com/angular/angular/issues/42769 is fixed. sourceMapping: false, logger: { level: 1, // Info level debug(...args: string[]) { // eslint-disable-next-line no-console console.debug(args); }, info(...args: string[]) { // eslint-disable-next-line no-console console.info(args); }, warn(...args: string[]) { // eslint-disable-next-line no-console console.warn(args); }, error(...args: string[]) { // eslint-disable-next-line no-console console.error(args); }, }, fileSystem: { resolve: path.resolve, exists: fs.existsSync, dirname: path.dirname, relative: path.relative, readFile: fs.readFileSync, // Node.JS types don't overlap the Compiler types. // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, }); return linkerPlugin; }
{ "end_byte": 6107, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/javascript-transformer-worker.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/watcher.ts_0_3268
/** * @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 WatchPack from 'watchpack'; export class ChangedFiles { readonly added = new Set<string>(); readonly modified = new Set<string>(); readonly removed = new Set<string>(); get all(): string[] { return [...this.added, ...this.modified, ...this.removed]; } toDebugString(): string { const content = { added: Array.from(this.added), modified: Array.from(this.modified), removed: Array.from(this.removed), }; return JSON.stringify(content, null, 2); } } export interface BuildWatcher extends AsyncIterableIterator<ChangedFiles> { add(paths: string | readonly string[]): void; remove(paths: string | readonly string[]): void; close(): Promise<void>; } export function createWatcher(options?: { polling?: boolean; interval?: number; ignored?: string[]; followSymlinks?: boolean; }): BuildWatcher { const watcher = new WatchPack({ poll: options?.polling ? options?.interval ?? true : false, ignored: options?.ignored, followSymlinks: options?.followSymlinks, aggregateTimeout: 250, }); const watchedFiles = new Set<string>(); const nextQueue: ((value?: ChangedFiles) => void)[] = []; let currentChangedFiles: ChangedFiles | undefined; watcher.on('aggregated', (changes, removals) => { const changedFiles = currentChangedFiles ?? new ChangedFiles(); for (const file of changes) { changedFiles.modified.add(file); } for (const file of removals) { changedFiles.removed.add(file); } const next = nextQueue.shift(); if (next) { currentChangedFiles = undefined; next(changedFiles); } else { currentChangedFiles = changedFiles; } }); return { [Symbol.asyncIterator]() { return this; }, async next() { if (currentChangedFiles && nextQueue.length === 0) { const result = { value: currentChangedFiles }; currentChangedFiles = undefined; return result; } return new Promise((resolve) => { nextQueue.push((value) => resolve(value ? { value } : { done: true, value })); }); }, add(paths) { const previousSize = watchedFiles.size; if (typeof paths === 'string') { watchedFiles.add(paths); } else { for (const file of paths) { watchedFiles.add(file); } } if (previousSize !== watchedFiles.size) { watcher.watch({ files: watchedFiles, }); } }, remove(paths) { const previousSize = watchedFiles.size; if (typeof paths === 'string') { watchedFiles.delete(paths); } else { for (const file of paths) { watchedFiles.delete(file); } } if (previousSize !== watchedFiles.size) { watcher.watch({ files: watchedFiles, }); } }, async close() { try { watcher.close(); } finally { let next; while ((next = nextQueue.shift()) !== undefined) { next(); } } }, }; }
{ "end_byte": 3268, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/watcher.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/lmdb-cache-store.ts_0_1323
/** * @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 { RootDatabase, open } from 'lmdb'; import { Cache, CacheStore } from './cache'; export class LmbdCacheStore implements CacheStore<unknown> { readonly #cacheFileUrl; #db: RootDatabase | undefined; constructor(readonly cachePath: string) { this.#cacheFileUrl = cachePath; } #ensureCacheFile(): RootDatabase { this.#db ??= open({ path: this.#cacheFileUrl, compression: true, }); return this.#db; } // eslint-disable-next-line @typescript-eslint/no-explicit-any async get(key: string): Promise<any> { const db = this.#ensureCacheFile(); const value = db.get(key); return value; } has(key: string): boolean { return this.#ensureCacheFile().doesExist(key); } async set(key: string, value: unknown): Promise<this> { const db = this.#ensureCacheFile(); await db.put(key, value); return this; } createCache<V = unknown>(namespace: string): Cache<V> { return new Cache(this, namespace); } async close() { try { await this.#db?.close(); } catch { // Failure to close should not be fatal } } }
{ "end_byte": 1323, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/lmdb-cache-store.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/wasm.d.ts_0_831
/** * @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 * TypeScript does not provide a separate lib for WASM types and the Node.js * types (`@types/node`) does not contain them either. This type definition * file provides type information for the subset of functionality required * by the Angular build process. Ideally this can be removed when the WASM * type situation has improved. */ declare namespace WebAssembly { class Module { constructor(data: Uint8Array); static imports(mod: Module): { module: string; name: string }[]; static exports(mode: Module): { name: string }[]; } function compile(data: Uint8Array): Promise<Module>; }
{ "end_byte": 831, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/wasm.d.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/i18n-inliner-worker.ts_0_6616
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import remapping, { SourceMapInput } from '@ampproject/remapping'; import { PluginObj, parseSync, transformFromAstAsync, types } from '@babel/core'; import assert from 'node:assert'; import { workerData } from 'node:worker_threads'; import { assertIsError } from '../../utils/error'; import { loadEsmModule } from '../../utils/load-esm'; /** * The options passed to the inliner for each file request */ interface InlineRequest { /** * The filename that should be processed. The data for the file is provided to the Worker * during Worker initialization. */ filename: string; /** * The locale specifier that should be used during the inlining process of the file. */ locale: string; /** * The translation messages for the locale that should be used during the inlining process of the file. */ translation?: Record<string, unknown>; } // Extract the application files and common options used for inline requests from the Worker context // TODO: Evaluate overall performance difference of passing translations here as well const { files, missingTranslation, shouldOptimize } = (workerData || {}) as { files: ReadonlyMap<string, Blob>; missingTranslation: 'error' | 'warning' | 'ignore'; shouldOptimize: boolean; }; /** * Inlines the provided locale and translation into a JavaScript file that contains `$localize` usage. * This function is the main entry for the Worker's action that is called by the worker pool. * * @param request An InlineRequest object representing the options for inlining * @returns An array containing the inlined file and optional map content. */ export default async function inlineLocale(request: InlineRequest) { const data = files.get(request.filename); assert(data !== undefined, `Invalid inline request for file '${request.filename}'.`); const code = await data.text(); const map = await files.get(request.filename + '.map')?.text(); const result = await transformWithBabel( code, map && (JSON.parse(map) as SourceMapInput), request, ); return { file: request.filename, code: result.code, map: result.map, messages: result.diagnostics.messages, }; } /** * A Type representing the localize tools module. */ 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> { // 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. localizeToolsModule ??= await loadEsmModule<LocalizeUtilityModule>('@angular/localize/tools'); return localizeToolsModule; } /** * Creates the needed Babel plugins to inline a given locale and translation for a JavaScript file. * @param locale A string containing the locale specifier to use. * @param translation A object record containing locale specific messages to use. * @returns An array of Babel plugins. */ async function createI18nPlugins(locale: string, translation: Record<string, unknown> | undefined) { const { Diagnostics, makeEs2015TranslatePlugin } = await loadLocalizeTools(); const plugins: PluginObj[] = []; const diagnostics = new Diagnostics(); plugins.push( // eslint-disable-next-line @typescript-eslint/no-explicit-any makeEs2015TranslatePlugin(diagnostics, (translation || {}) as any, { missingTranslation: translation === undefined ? 'ignore' : missingTranslation, }), ); // Create a plugin to replace the locale specifier constant inject by the build system with the actual specifier plugins.push({ visitor: { StringLiteral(path) { if (path.node.value === '___NG_LOCALE_INSERT___') { path.replaceWith(types.stringLiteral(locale)); } }, }, }); return { diagnostics, plugins }; } /** * Transforms a JavaScript file using Babel to inline the request locale and translation. * @param code A string containing the JavaScript code to transform. * @param map A sourcemap object for the provided JavaScript code. * @param options The inline request options to use. * @returns An object containing the code, map, and diagnostics from the transformation. */ async function transformWithBabel( code: string, map: SourceMapInput | undefined, options: InlineRequest, ) { let ast; try { ast = parseSync(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}"`); } const { diagnostics, plugins } = await createI18nPlugins(options.locale, options.translation); const transformResult = await transformFromAstAsync(ast, code, { filename: options.filename, // false is a valid value but not included in the type definition inputSourceMap: false as unknown as undefined, sourceMaps: !!map, compact: shouldOptimize, configFile: false, babelrc: false, browserslistConfigFile: false, plugins, }); if (!transformResult || !transformResult.code) { throw new Error(`Unknown error occurred processing bundle for "${options.filename}".`); } let outputMap; if (map && transformResult.map) { outputMap = remapping([transformResult.map as SourceMapInput, map], () => null); } return { code: transformResult.code, map: outputMap && JSON.stringify(outputMap), diagnostics }; }
{ "end_byte": 6616, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/i18n-inliner-worker.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/utils.ts_0_7341
/** * @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 { BuildOptions, Metafile, OutputFile, formatMessages } from 'esbuild'; import { Listr } from 'listr2'; import { createHash } from 'node:crypto'; import { basename, join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { brotliCompress } from 'node:zlib'; import { coerce } from 'semver'; import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import { OutputMode } from '../../builders/application/schema'; import { BudgetCalculatorResult } from '../../utils/bundle-calculator'; import { SERVER_APP_ENGINE_MANIFEST_FILENAME, SERVER_APP_MANIFEST_FILENAME, } from '../../utils/server-rendering/manifest'; import { BundleStats, generateEsbuildBuildStatsTable } from '../../utils/stats-table'; import { BuildOutputFile, BuildOutputFileType, InitialFileRecord } from './bundler-context'; import { BuildOutputAsset, ExecutionResult, PrerenderedRoutesRecord, } from './bundler-execution-result'; export function logBuildStats( metafile: Metafile, outputFiles: BuildOutputFile[], initial: Map<string, InitialFileRecord>, budgetFailures: BudgetCalculatorResult[] | undefined, colors: boolean, changedFiles?: Set<string>, estimatedTransferSizes?: Map<string, number>, ssrOutputEnabled?: boolean, verbose?: boolean, ): string { const browserStats: BundleStats[] = []; const serverStats: BundleStats[] = []; let unchangedCount = 0; let componentStyleChange = false; for (const { path: file, size, type } of outputFiles) { // Only display JavaScript and CSS files if (!/\.(?:css|m?js)$/.test(file)) { continue; } // Show only changed files if a changed list is provided if (changedFiles && !changedFiles.has(file)) { ++unchangedCount; continue; } const isPlatformServer = type === BuildOutputFileType.ServerApplication || type === BuildOutputFileType.ServerRoot; if (isPlatformServer && !ssrOutputEnabled) { // Only log server build stats when SSR is enabled. continue; } // Skip logging external component stylesheets used for HMR if (metafile.outputs[file] && 'ng-component' in metafile.outputs[file]) { componentStyleChange = true; continue; } const name = initial.get(file)?.name ?? getChunkNameFromMetafile(metafile, file); const stat: BundleStats = { initial: initial.has(file), stats: [file, name ?? '-', size, estimatedTransferSizes?.get(file) ?? '-'], }; if (isPlatformServer) { serverStats.push(stat); } else { browserStats.push(stat); } } if (browserStats.length > 0 || serverStats.length > 0) { const tableText = generateEsbuildBuildStatsTable( [browserStats, serverStats], colors, unchangedCount === 0, !!estimatedTransferSizes, budgetFailures, verbose, ); return tableText + '\n'; } else if (changedFiles !== undefined) { if (componentStyleChange) { return '\nComponent stylesheet(s) changed.\n'; } else { return '\nNo output file changes.\n'; } } if (unchangedCount > 0) { return `Unchanged output files: ${unchangedCount}`; } return ''; } export function getChunkNameFromMetafile(metafile: Metafile, file: string): string | undefined { if (metafile.outputs[file]?.entryPoint) { return getEntryPointName(metafile.outputs[file].entryPoint); } } export async function calculateEstimatedTransferSizes( outputFiles: OutputFile[], ): Promise<Map<string, number>> { const sizes = new Map<string, number>(); if (outputFiles.length <= 0) { return sizes; } return new Promise((resolve, reject) => { let completeCount = 0; for (const outputFile of outputFiles) { // Only calculate JavaScript and CSS files if (!outputFile.path.endsWith('.js') && !outputFile.path.endsWith('.css')) { ++completeCount; continue; } // Skip compressing small files which may end being larger once compressed and will most likely not be // compressed in actual transit. if (outputFile.contents.byteLength < 1024) { sizes.set(outputFile.path, outputFile.contents.byteLength); ++completeCount; continue; } // Directly use the async callback function to minimize the number of Promises that need to be created. brotliCompress(outputFile.contents, (error, result) => { if (error) { reject(error); return; } sizes.set(outputFile.path, result.byteLength); if (++completeCount >= outputFiles.length) { resolve(sizes); } }); } // Covers the case where no files need to be compressed if (completeCount >= outputFiles.length) { resolve(sizes); } }); } export async function withSpinner<T>(text: string, action: () => T | Promise<T>): Promise<T> { let result; const taskList = new Listr( [ { title: text, async task() { result = await action(); }, }, ], { rendererOptions: { clearOutput: true } }, ); await taskList.run(); return result as T; } export async function withNoProgress<T>(text: string, action: () => T | Promise<T>): Promise<T> { return action(); } /** * Generates a syntax feature object map for Angular applications based on a list of targets. * A full set of feature names can be found here: https://esbuild.github.io/api/#supported * @param target An array of browser/engine targets in the format accepted by the esbuild `target` option. * @param nativeAsyncAwait Indicate whether to support native async/await. * @returns An object that can be used with the esbuild build `supported` option. */ export function getFeatureSupport( target: string[], nativeAsyncAwait: boolean, ): BuildOptions['supported'] { return { // Native async/await is not supported with Zone.js. Disabling support here will cause // esbuild to downlevel async/await, async generators, and for await...of to a Zone.js supported form. 'async-await': nativeAsyncAwait, // V8 currently has a performance defect involving object spread operations that can cause signficant // degradation in runtime performance. By not supporting the language feature here, a downlevel form // will be used instead which provides a workaround for the performance issue. // For more details: https://bugs.chromium.org/p/v8/issues/detail?id=11536 'object-rest-spread': false, }; } const MAX_CONCURRENT_WRITES = 64; export async function emitFilesToDisk<T = BuildOutputAsset | BuildOutputFile>( files: T[], writeFileCallback: (file: T) => Promise<void>, ): Promise<void> { // Write files in groups of MAX_CONCURRENT_WRITES to avoid too many open files for (let fileIndex = 0; fileIndex < files.length; ) { const groupMax = Math.min(fileIndex + MAX_CONCURRENT_WRITES, files.length); const actions = []; while (fileIndex < groupMax) { actions.push(writeFileCallback(files[fileIndex++])); } await Promise.all(actions); } }
{ "end_byte": 7341, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/utils.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/utils.ts_7343_15188
export function createOutputFile( path: string, data: string | Uint8Array, type: BuildOutputFileType, ): BuildOutputFile { if (typeof data === 'string') { let cachedContents: Uint8Array | null = null; let cachedText: string | null = data; let cachedHash: string | null = null; return { path, type, get contents(): Uint8Array { cachedContents ??= new TextEncoder().encode(data); return cachedContents; }, set contents(value: Uint8Array) { cachedContents = value; cachedText = null; }, get text(): string { cachedText ??= new TextDecoder('utf-8').decode(this.contents); return cachedText; }, get size(): number { return this.contents.byteLength; }, get hash(): string { cachedHash ??= createHash('sha256') .update(cachedText ?? this.contents) .digest('hex'); return cachedHash; }, clone(): BuildOutputFile { return createOutputFile(this.path, cachedText ?? this.contents, this.type); }, }; } else { let cachedContents = data; let cachedText: string | null = null; let cachedHash: string | null = null; return { get contents(): Uint8Array { return cachedContents; }, set contents(value: Uint8Array) { cachedContents = value; cachedText = null; }, path, type, get size(): number { return this.contents.byteLength; }, get text(): string { cachedText ??= new TextDecoder('utf-8').decode(this.contents); return cachedText; }, get hash(): string { cachedHash ??= createHash('sha256').update(this.contents).digest('hex'); return cachedHash; }, clone(): BuildOutputFile { return createOutputFile(this.path, this.contents, this.type); }, }; } } export function convertOutputFile(file: OutputFile, type: BuildOutputFileType): BuildOutputFile { let { contents: cachedContents } = file; let cachedText: string | null = null; return { get contents(): Uint8Array { return cachedContents; }, set contents(value: Uint8Array) { cachedContents = value; cachedText = null; }, hash: file.hash, path: file.path, type, get size(): number { return this.contents.byteLength; }, get text(): string { cachedText ??= new TextDecoder('utf-8').decode(this.contents); return cachedText; }, clone(): BuildOutputFile { return convertOutputFile(this, this.type); }, }; } /** * Transform browserlists result to esbuild target. * @see https://esbuild.github.io/api/#target */ export function transformSupportedBrowsersToTargets(supportedBrowsers: string[]): string[] { const transformed: string[] = []; // https://esbuild.github.io/api/#target const esBuildSupportedBrowsers = new Set([ 'chrome', 'edge', 'firefox', 'ie', 'ios', 'node', 'opera', 'safari', ]); for (const browser of supportedBrowsers) { let [browserName, version] = browser.toLowerCase().split(' '); // browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios` if (browserName === 'ios_saf') { browserName = 'ios'; } // browserslist uses ranges `15.2-15.3` versions but only the lowest is required // to perform minimum supported feature checks. esbuild also expects a single version. [version] = version.split('-'); if (esBuildSupportedBrowsers.has(browserName)) { if (browserName === 'safari' && version === 'tp') { // esbuild only supports numeric versions so `TP` is converted to a high number (999) since // a Technology Preview (TP) of Safari is assumed to support all currently known features. version = '999'; } else if (!version.includes('.')) { // A lone major version is considered by esbuild to include all minor versions. However, // browserslist does not and is also inconsistent in its `.0` version naming. For example, // Safari 15.0 is named `safari 15` but Safari 16.0 is named `safari 16.0`. version += '.0'; } transformed.push(browserName + version); } } return transformed; } const SUPPORTED_NODE_VERSIONS = '0.0.0-ENGINES-NODE'; /** * Transform supported Node.js versions to esbuild target. * @see https://esbuild.github.io/api/#target */ export function getSupportedNodeTargets(): string[] { if (SUPPORTED_NODE_VERSIONS.charAt(0) === '0') { // Unlike `pkg_npm`, `ts_library` which is used to run unit tests does not support substitutions. return []; } return SUPPORTED_NODE_VERSIONS.split('||').map((v) => 'node' + coerce(v)?.version); } interface BuildManifest { errors: string[]; warnings: string[]; outputPaths: { root: URL; server?: URL | undefined; browser: URL; }; prerenderedRoutes: PrerenderedRoutesRecord; } export async function createJsonBuildManifest( result: ExecutionResult, normalizedOptions: NormalizedApplicationBuildOptions, ): Promise<string> { const { colors: color, outputOptions: { base, server, browser }, ssrOptions, outputMode, } = normalizedOptions; const { warnings, errors, prerenderedRoutes } = result; const manifest: BuildManifest = { errors: errors.length ? await formatMessages(errors, { kind: 'error', color }) : [], warnings: warnings.length ? await formatMessages(warnings, { kind: 'warning', color }) : [], outputPaths: { root: pathToFileURL(base), browser: pathToFileURL(join(base, browser)), server: outputMode !== OutputMode.Static && ssrOptions ? pathToFileURL(join(base, server)) : undefined, }, prerenderedRoutes, }; return JSON.stringify(manifest, undefined, 2); } export async function logMessages( logger: BuilderContext['logger'], executionResult: ExecutionResult, color?: boolean, jsonLogs?: boolean, ): Promise<void> { const { warnings, errors, logs } = executionResult; if (logs.length) { logger.info(logs.join('\n')); } if (jsonLogs) { return; } if (warnings.length) { logger.warn((await formatMessages(warnings, { kind: 'warning', color })).join('\n')); } if (errors.length) { logger.error((await formatMessages(errors, { kind: 'error', color })).join('\n')); } } /** * Ascertain whether the application operates without `zone.js`, we currently rely on the polyfills setting to determine its status. * If a file with an extension is provided or if `zone.js` is included in the polyfills, the application is deemed as not zoneless. * @param polyfills An array of polyfills * @returns true, when the application is considered as zoneless. */ export function isZonelessApp(polyfills: string[] | undefined): boolean { // TODO: Instead, we should rely on the presence of zone.js in the polyfills build metadata. return !polyfills?.some((p) => p === 'zone.js' || /\.[mc]?[jt]s$/.test(p)); } export function getEntryPointName(entryPoint: string): string { return basename(entryPoint) .replace(/(.*:)/, '') // global:bundle.css -> bundle.css .replace(/\.[cm]?[jt]s$/, '') .replace(/[\\/.]/g, '-'); } /** * A set of server-generated dependencies that are treated as external. * * These dependencies are marked as external because they are produced by a * separate bundling process and are not included in the primary bundle. This * ensures that these generated files are resolved from an external source rather * than being part of the main bundle. */ export const SERVER_GENERATED_EXTERNALS = new Set([ './polyfills.server.mjs', './' + SERVER_APP_MANIFEST_FILENAME, './' + SERVER_APP_ENGINE_MANIFEST_FILENAME, ]);
{ "end_byte": 15188, "start_byte": 7343, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/utils.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts_0_4893
/** * @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 { Plugin } from 'esbuild'; /** * The internal namespace used by generated locale import statements and Angular locale data plugin. */ export const LOCALE_DATA_NAMESPACE = 'angular:locale/data'; /** * The base module location used to search for locale specific data. */ export const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global'; /** * Creates an esbuild plugin that resolves Angular locale data files from `@angular/common`. * * @returns An esbuild plugin. */ export function createAngularLocaleDataPlugin(): Plugin { return { name: 'angular-locale-data', setup(build): void { // If packages are configured to be external then leave the original angular locale import path. // This happens when using the development server with caching enabled to allow Vite prebundling to work. // There currently is no option on the esbuild resolve function to resolve while disabling the option. To // workaround the inability to resolve the full locale location here, the Vite dev server prebundling also // contains a plugin to allow the locales to be correctly resolved when prebundling. // NOTE: If esbuild eventually allows controlling the external package options in a build.resolve call, this // workaround can be removed. if (build.initialOptions.packages === 'external') { return; } build.onResolve({ filter: /^angular:locale\/data:/ }, async ({ path }) => { // Extract the locale from the path const rawLocaleTag = path.split(':', 3)[2]; // Extract and normalize the base name of the raw locale tag let partialLocaleTag: string; try { const locale = new Intl.Locale(rawLocaleTag); partialLocaleTag = locale.baseName; } catch { return { path: rawLocaleTag, namespace: LOCALE_DATA_NAMESPACE, errors: [ { text: `Invalid or unsupported locale provided in configuration: "${rawLocaleTag}"`, }, ], }; } let exact = true; while (partialLocaleTag) { // Angular embeds the `en`/`en-US` locale into the framework and it does not need to be included again here. // The onLoad hook below for the locale data namespace has an `empty` loader that will prevent inclusion. // Angular does not contain exact locale data for `en-US` but `en` is equivalent. if (partialLocaleTag === 'en' || partialLocaleTag === 'en-US') { return { path: rawLocaleTag, namespace: LOCALE_DATA_NAMESPACE, }; } // Attempt to resolve the locale tag data within the Angular base module location const potentialPath = `${LOCALE_DATA_BASE_MODULE}/${partialLocaleTag}`; const result = await build.resolve(potentialPath, { kind: 'import-statement', resolveDir: build.initialOptions.absWorkingDir, }); if (result.path) { if (exact) { return result; } else { return { ...result, warnings: [ ...result.warnings, { location: null, text: `Locale data for '${rawLocaleTag}' cannot be found. Using locale data for '${partialLocaleTag}'.`, }, ], }; } } // Remove the last subtag and try again with a less specific locale. // Usually the match is exact so the string splitting here is not done until actually needed after the exact // match fails to resolve. const parts = partialLocaleTag.split('-'); partialLocaleTag = parts.slice(0, -1).join('-'); exact = false; } // Not found so issue a warning and use an empty loader. Framework built-in `en-US` data will be used. // This retains existing behavior as in the Webpack-based builder. return { path: rawLocaleTag, namespace: LOCALE_DATA_NAMESPACE, warnings: [ { location: null, text: `Locale data for '${rawLocaleTag}' cannot be found. No locale data will be included for this locale.`, }, ], }; }); // Locales that cannot be found will be loaded as empty content with a warning from the resolve step build.onLoad({ filter: /./, namespace: LOCALE_DATA_NAMESPACE }, () => ({ contents: '', loader: 'empty', })); }, }; }
{ "end_byte": 4893, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/global-scripts.ts_0_5061
/** * @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 MagicString, { Bundle } from 'magic-string'; import assert from 'node:assert'; import { readFile } from 'node:fs/promises'; import path from 'node:path'; import type { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import { assertIsError } from '../../utils/error'; import { BundlerOptionsFactory } from './bundler-context'; import { createCachedLoad } from './load-result-cache'; import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin'; import { createVirtualModulePlugin } from './virtual-module-plugin'; /** * Create an esbuild 'build' options object for all global scripts defined in the user provied * build options. * @param options The builder's user-provider normalized options. * @returns An esbuild BuildOptions object. */ export function createGlobalScriptsBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], initial: boolean, ): BundlerOptionsFactory | undefined { const { globalScripts, optimizationOptions, outputNames, preserveSymlinks, sourcemapOptions, jsonLogs, workspaceRoot, } = options; const namespace = 'angular:script/global'; const entryPoints: Record<string, string> = {}; let found = false; for (const script of globalScripts) { if (script.initial === initial) { found = true; entryPoints[script.name] = `${namespace}:${script.name}`; } } // Skip if there are no entry points for the style loading type if (found === false) { return; } return (loadCache) => { return { absWorkingDir: workspaceRoot, bundle: false, splitting: false, entryPoints, entryNames: initial ? outputNames.bundles : '[name]', assetNames: outputNames.media, mainFields: ['script', 'browser', 'main'], conditions: ['script', optimizationOptions.scripts ? 'production' : 'development'], resolveExtensions: ['.mjs', '.js', '.cjs'], logLevel: options.verbose && !jsonLogs ? 'debug' : 'silent', metafile: true, minify: optimizationOptions.scripts, outdir: workspaceRoot, sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true), write: false, platform: 'neutral', target, preserveSymlinks, plugins: [ createSourcemapIgnorelistPlugin(), createVirtualModulePlugin({ namespace, external: true, // Add the `js` extension here so that esbuild generates an output file with the extension transformPath: (path) => path.slice(namespace.length + 1) + '.js', loadContent: (args, build) => createCachedLoad(loadCache, async (args) => { const files = globalScripts.find( ({ name }) => name === args.path.slice(0, -3), )?.files; assert(files, `Invalid operation: global scripts name not found [${args.path}]`); // Global scripts are concatenated using magic-string instead of bundled via esbuild. const bundleContent = new Bundle(); const watchFiles = []; for (const filename of files) { let fileContent; try { // Attempt to read as a relative path from the workspace root const fullPath = path.join(workspaceRoot, filename); fileContent = await readFile(fullPath, 'utf-8'); watchFiles.push(fullPath); } catch (e) { assertIsError(e); if (e.code !== 'ENOENT') { throw e; } // If not found, attempt to resolve as a module specifier const resolveResult = await build.resolve(filename, { kind: 'entry-point', resolveDir: workspaceRoot, }); if (resolveResult.errors.length) { // Remove resolution failure notes about marking as external since it doesn't apply // to global scripts. resolveResult.errors.forEach((error) => (error.notes = [])); return { errors: resolveResult.errors, warnings: resolveResult.warnings, }; } watchFiles.push(resolveResult.path); fileContent = await readFile(resolveResult.path, 'utf-8'); } bundleContent.addSource(new MagicString(fileContent, { filename })); } return { contents: bundleContent.toString(), loader: 'js', watchFiles, }; }).call(build, args), }), ], }; }; }
{ "end_byte": 5061, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/global-scripts.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts_0_1163
/** * @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 { Loader, Plugin } from 'esbuild'; import { readFile } from 'node:fs/promises'; const SUPPORTED_LOADERS: Loader[] = ['binary', 'file', 'text']; export function createLoaderImportAttributePlugin(): Plugin { return { name: 'angular-loader-import-attributes', setup(build) { build.onLoad({ filter: /./ }, async (args) => { const loader = args.with['loader'] as Loader | undefined; if (!loader) { return undefined; } if (!SUPPORTED_LOADERS.includes(loader)) { return { errors: [ { text: 'Unsupported loader import attribute', notes: [ { text: 'Attribute value must be one of: ' + SUPPORTED_LOADERS.join(', ') }, ], }, ], }; } return { contents: await readFile(args.path), loader, }; }); }, }; }
{ "end_byte": 1163, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/budget-stats.ts_0_2404
/** * @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 { Metafile } from 'esbuild'; import type { BudgetStats } from '../../utils/bundle-calculator'; import { type BuildOutputFile, BuildOutputFileType, type InitialFileRecord, } from './bundler-context'; import { getChunkNameFromMetafile } from './utils'; /** * Generates a bundle budget calculator compatible stats object that provides * the necessary information for the Webpack-based bundle budget code to * interoperate with the esbuild-based builders. * @param metafile The esbuild metafile of a build to use. * @param initialFiles The records of all initial files of a build. * @returns A bundle budget compatible stats object. */ export function generateBudgetStats( metafile: Metafile, outputFiles: BuildOutputFile[], initialFiles: Map<string, InitialFileRecord>, ): BudgetStats { const stats: Required<BudgetStats> = { chunks: [], assets: [], }; for (const { path: file, size, type } of outputFiles) { if (!file.endsWith('.js') && !file.endsWith('.css')) { continue; } // Exclude server bundles if (type === BuildOutputFileType.ServerApplication || type === BuildOutputFileType.ServerRoot) { continue; } const initialRecord = initialFiles.get(file); const name = initialRecord?.name ?? getChunkNameFromMetafile(metafile, file); stats.chunks.push({ files: [file], initial: !!initialRecord, names: name ? [name] : undefined, }); stats.assets.push({ name: file, size, }); } // Add component styles from metafile // TODO: Provide this information directly from the AOT compiler for (const [file, entry] of Object.entries(metafile.outputs)) { if (!file.endsWith('.css')) { continue; } // 'ng-component' is set by the angular plugin's component stylesheet bundler // eslint-disable-next-line @typescript-eslint/no-explicit-any const componentStyle: boolean = (entry as any)['ng-component']; if (!componentStyle) { continue; } stats.assets.push({ // Component styles use the input file name: Object.keys(entry.inputs)[0], size: entry.bytes, componentStyle, }); } return stats; }
{ "end_byte": 2404, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/budget-stats.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/cache.ts_0_4022
/** * @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 * Provides infrastructure for common caching functionality within the build system. */ /** * A backing data store for one or more Cache instances. * The interface is intentionally designed to support using a JavaScript * Map instance as a potential cache store. */ export interface CacheStore<V> { /** * Returns the specified value from the cache store or `undefined` if not found. * @param key The key to retrieve from the store. */ get(key: string): V | undefined | Promise<V | undefined>; /** * Returns whether the provided key is present in the cache store. * @param key The key to check from the store. */ has(key: string): boolean | Promise<boolean>; /** * Adds a new value to the cache store if the key is not present. * Updates the value for the key if already present. * @param key The key to associate with the value in the cache store. * @param value The value to add to the cache store. */ set(key: string, value: V): this | Promise<this>; } /** * A cache object that allows accessing and storing key/value pairs in * an underlying CacheStore. This class is the primary method for consumers * to use a cache. */ export class Cache<V, S extends CacheStore<V> = CacheStore<V>> { constructor( protected readonly store: S, readonly namespace?: string, ) {} /** * Prefixes a key with the cache namespace if present. * @param key A key string to prefix. * @returns A prefixed key if a namespace is present. Otherwise the provided key. */ protected withNamespace(key: string): string { if (this.namespace) { return `${this.namespace}:${key}`; } return key; } /** * Gets the value associated with a provided key if available. * Otherwise, creates a value using the factory creator function, puts the value * in the cache, and returns the new value. * @param key A key associated with the value. * @param creator A factory function for the value if no value is present. * @returns A value associated with the provided key. */ async getOrCreate(key: string, creator: () => V | Promise<V>): Promise<V> { const namespacedKey = this.withNamespace(key); let value = await this.store.get(namespacedKey); if (value === undefined) { value = await creator(); await this.store.set(namespacedKey, value); } return value; } /** * Gets the value associated with a provided key if available. * @param key A key associated with the value. * @returns A value associated with the provided key if present. Otherwise, `undefined`. */ async get(key: string): Promise<V | undefined> { const value = await this.store.get(this.withNamespace(key)); return value; } /** * Puts a value in the cache and associates it with the provided key. * If the key is already present, the value is updated instead. * @param key A key associated with the value. * @param value A value to put in the cache. */ async put(key: string, value: V): Promise<void> { await this.store.set(this.withNamespace(key), value); } } /** * A lightweight in-memory cache implementation based on a JavaScript Map object. */ export class MemoryCache<V> extends Cache<V, Map<string, V>> { constructor() { super(new Map()); } /** * Removes all entries from the cache instance. */ clear() { this.store.clear(); } /** * Provides all the values currently present in the cache instance. * @returns An iterable of all values in the cache. */ values() { return this.store.values(); } /** * Provides all the keys/values currently present in the cache instance. * @returns An iterable of all key/value pairs in the cache. */ entries() { return this.store.entries(); } }
{ "end_byte": 4022, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/cache.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/i18n-inliner.ts_0_6062
/** * @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 'node:assert'; import { WorkerPool } from '../../utils/worker-pool'; import { BuildOutputFile, BuildOutputFileType } from './bundler-context'; import { createOutputFile } from './utils'; /** * A keyword used to indicate if a JavaScript file may require inlining of translations. * This keyword is used to avoid processing files that would not otherwise need i18n processing. */ const LOCALIZE_KEYWORD = '$localize'; /** * Inlining options that should apply to all transformed code. */ export interface I18nInlinerOptions { missingTranslation: 'error' | 'warning' | 'ignore'; outputFiles: BuildOutputFile[]; shouldOptimize?: boolean; } /** * A class that performs i18n translation inlining of JavaScript code. * A worker pool is used to distribute the transformation actions and allow * parallel processing. Inlining is only performed on code that contains the * localize function (`$localize`). */ export class I18nInliner { #workerPool: WorkerPool; readonly #localizeFiles: ReadonlyMap<string, Blob>; readonly #unmodifiedFiles: Array<BuildOutputFile>; readonly #fileToType = new Map<string, BuildOutputFileType>(); constructor(options: I18nInlinerOptions, maxThreads?: number) { this.#unmodifiedFiles = []; const files = new Map<string, Blob>(); const pendingMaps = []; for (const file of options.outputFiles) { if (file.type === BuildOutputFileType.Root || file.type === BuildOutputFileType.ServerRoot) { // Skip also the server entry-point. // Skip stats and similar files. continue; } this.#fileToType.set(file.path, file.type); if (file.path.endsWith('.js') || file.path.endsWith('.mjs')) { // Check if localizations are present const contentBuffer = Buffer.isBuffer(file.contents) ? file.contents : Buffer.from(file.contents.buffer, file.contents.byteOffset, file.contents.byteLength); const hasLocalize = contentBuffer.includes(LOCALIZE_KEYWORD); if (hasLocalize) { // A Blob is an immutable data structure that allows sharing the data between workers // without copying until the data is actually used within a Worker. This is useful here // since each file may not actually be processed in each Worker and the Blob avoids // unneeded repeat copying of potentially large JavaScript files. files.set(file.path, new Blob([file.contents])); continue; } } else if (file.path.endsWith('.js.map')) { // The related JS file may not have been checked yet. To ensure that map files are not // missed, store any pending map files and check them after all output files. pendingMaps.push(file); continue; } this.#unmodifiedFiles.push(file); } // Check if any pending map files should be processed by checking if the parent JS file is present for (const file of pendingMaps) { if (files.has(file.path.slice(0, -4))) { files.set(file.path, new Blob([file.contents])); } else { this.#unmodifiedFiles.push(file); } } this.#localizeFiles = files; this.#workerPool = new WorkerPool({ filename: require.resolve('./i18n-inliner-worker'), maxThreads, // Extract options to ensure only the named options are serialized and sent to the worker workerData: { missingTranslation: options.missingTranslation, shouldOptimize: options.shouldOptimize, files, }, }); } /** * Performs inlining of translations for the provided locale and translations. The files that * are processed originate from the files passed to the class constructor and filter by presence * of the localize function keyword. * @param locale The string representing the locale to inline. * @param translation The translation messages to use when inlining. * @returns A promise that resolves to an array of OutputFiles representing a translated result. */ async inlineForLocale( locale: string, translation: Record<string, unknown> | undefined, ): Promise<{ outputFiles: BuildOutputFile[]; errors: string[]; warnings: string[] }> { // Request inlining for each file that contains localize calls const requests = []; for (const filename of this.#localizeFiles.keys()) { if (filename.endsWith('.map')) { continue; } const fileRequest = this.#workerPool.run({ filename, locale, translation, }); requests.push(fileRequest); } // Wait for all file requests to complete const rawResults = await Promise.all(requests); // Convert raw results to output file objects and include all unmodified files const errors: string[] = []; const warnings: string[] = []; const outputFiles = [ ...rawResults.flatMap(({ file, code, map, messages }) => { const type = this.#fileToType.get(file); assert(type !== undefined, 'localized file should always have a type' + file); const resultFiles = [createOutputFile(file, code, type)]; if (map) { resultFiles.push(createOutputFile(file + '.map', map, type)); } for (const message of messages) { if (message.type === 'error') { errors.push(message.message); } else { warnings.push(message.message); } } return resultFiles; }), ...this.#unmodifiedFiles.map((file) => file.clone()), ]; return { outputFiles, errors, warnings, }; } /** * Stops all active transformation tasks and shuts down all workers. * @returns A void promise that resolves when closing is complete. */ close(): Promise<void> { return this.#workerPool.destroy(); } }
{ "end_byte": 6062, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/i18n-inliner.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/bundler-context.ts_0_6164
/** * @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 { BuildContext, BuildFailure, BuildOptions, BuildResult, Message, Metafile, OutputFile, build, context, } from 'esbuild'; import assert from 'node:assert'; import { basename, extname, join, relative } from 'node:path'; import { LoadResultCache, MemoryLoadResultCache } from './load-result-cache'; import { SERVER_GENERATED_EXTERNALS, convertOutputFile } from './utils'; export type BundleContextResult = | { errors: Message[]; warnings: Message[] } | { errors: undefined; warnings: Message[]; metafile: Metafile; outputFiles: BuildOutputFile[]; initialFiles: Map<string, InitialFileRecord>; externalImports: { server?: Set<string>; browser?: Set<string>; }; externalConfiguration?: string[]; }; export interface InitialFileRecord { entrypoint: boolean; name?: string; type: 'script' | 'style'; external?: boolean; serverFile: boolean; depth: number; } export enum BuildOutputFileType { Browser, Media, ServerApplication, ServerRoot, Root, } export interface BuildOutputFile extends OutputFile { type: BuildOutputFileType; readonly size: number; clone: () => BuildOutputFile; } export type BundlerOptionsFactory<T extends BuildOptions = BuildOptions> = ( loadCache: LoadResultCache | undefined, ) => T; /** * Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild. * @param value A potential esbuild BuildFailure error object. * @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`. */ function isEsBuildFailure(value: unknown): value is BuildFailure { return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value; } export class BundlerContext { #esbuildContext?: BuildContext<{ metafile: true; write: false }>; #esbuildOptions?: BuildOptions & { metafile: true; write: false }; #esbuildResult?: BundleContextResult; #optionsFactory: BundlerOptionsFactory<BuildOptions & { metafile: true; write: false }>; #shouldCacheResult: boolean; #loadCache?: MemoryLoadResultCache; readonly watchFiles = new Set<string>(); constructor( private workspaceRoot: string, private incremental: boolean, options: BuildOptions | BundlerOptionsFactory, private initialFilter?: (initial: Readonly<InitialFileRecord>) => boolean, ) { // To cache the results an option factory is needed to capture the full set of dependencies this.#shouldCacheResult = incremental && typeof options === 'function'; this.#optionsFactory = (...args) => { const baseOptions = typeof options === 'function' ? options(...args) : options; return { ...baseOptions, metafile: true, write: false, }; }; } static async bundleAll( contexts: Iterable<BundlerContext>, changedFiles?: Iterable<string>, ): Promise<BundleContextResult> { const individualResults = await Promise.all( [...contexts].map((context) => { if (changedFiles) { context.invalidate(changedFiles); } return context.bundle(); }), ); return BundlerContext.mergeResults(individualResults); } static mergeResults(results: BundleContextResult[]): BundleContextResult { // Return directly if only one result if (results.length === 1) { return results[0]; } let errors: Message[] | undefined; const warnings: Message[] = []; const metafile: Metafile = { inputs: {}, outputs: {} }; const initialFiles = new Map<string, InitialFileRecord>(); const externalImportsBrowser = new Set<string>(); const externalImportsServer = new Set<string>(); const outputFiles = []; let externalConfiguration; for (const result of results) { warnings.push(...result.warnings); if (result.errors) { errors ??= []; errors.push(...result.errors); continue; } // Combine metafiles used for the stats option as well as bundle budgets and console output if (result.metafile) { Object.assign(metafile.inputs, result.metafile.inputs); Object.assign(metafile.outputs, result.metafile.outputs); } result.initialFiles.forEach((value, key) => initialFiles.set(key, value)); outputFiles.push(...result.outputFiles); result.externalImports.browser?.forEach((value) => externalImportsBrowser.add(value)); result.externalImports.server?.forEach((value) => externalImportsServer.add(value)); if (result.externalConfiguration) { externalConfiguration ??= new Set<string>(); for (const value of result.externalConfiguration) { externalConfiguration.add(value); } } } if (errors !== undefined) { return { errors, warnings }; } return { errors, warnings, metafile, initialFiles, outputFiles, externalImports: { browser: externalImportsBrowser, server: externalImportsServer, }, externalConfiguration: externalConfiguration ? [...externalConfiguration] : undefined, }; } /** * Executes the esbuild build function and normalizes the build result in the event of a * build failure that results in no output being generated. * All builds use the `write` option with a value of `false` to allow for the output files * build result array to be populated. * * @returns If output files are generated, the full esbuild BuildResult; if not, the * warnings and errors for the attempted build. */ async bundle(): Promise<BundleContextResult> { // Return existing result if present if (this.#esbuildResult) { return this.#esbuildResult; } const result = await this.#performBundle(); if (this.#shouldCacheResult) { this.#esbuildResult = result; } return result; } // eslint-disable-next-line max-lines-per-function
{ "end_byte": 6164, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/bundler-context.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/bundler-context.ts_6167_15103
async #performBundle(): Promise<BundleContextResult> { // Create esbuild options if not present if (this.#esbuildOptions === undefined) { if (this.incremental) { this.#loadCache = new MemoryLoadResultCache(); } this.#esbuildOptions = this.#optionsFactory(this.#loadCache); } if (this.incremental) { this.watchFiles.clear(); } let result: BuildResult<{ metafile: true; write: false }>; try { if (this.#esbuildContext) { // Rebuild using the existing incremental build context result = await this.#esbuildContext.rebuild(); } else if (this.incremental) { // Create an incremental build context and perform the first build. // Context creation does not perform a build. this.#esbuildContext = await context(this.#esbuildOptions); result = await this.#esbuildContext.rebuild(); } else { // For non-incremental builds, perform a single build result = await build(this.#esbuildOptions); } } catch (failure) { // Build failures will throw an exception which contains errors/warnings if (isEsBuildFailure(failure)) { this.#addErrorsToWatch(failure); return failure; } else { throw failure; } } finally { if (this.incremental) { // When incremental always add any files from the load result cache if (this.#loadCache) { for (const file of this.#loadCache.watchFiles) { if (!isInternalAngularFile(file)) { // watch files are fully resolved paths this.watchFiles.add(file); } } } } } // Update files that should be watched. // While this should technically not be linked to incremental mode, incremental is only // currently enabled with watch mode where watch files are needed. if (this.incremental) { // Add input files except virtual angular files which do not exist on disk for (const input of Object.keys(result.metafile.inputs)) { if (!isInternalAngularFile(input)) { // input file paths are always relative to the workspace root this.watchFiles.add(join(this.workspaceRoot, input)); } } } // Return if the build encountered any errors if (result.errors.length) { this.#addErrorsToWatch(result); return { errors: result.errors, warnings: result.warnings, }; } const { 'ng-platform-server': isPlatformServer = false, 'ng-ssr-entry-bundle': isSsrEntryBundle = false, } = result.metafile as Metafile & { 'ng-platform-server'?: boolean; 'ng-ssr-entry-bundle'?: boolean; }; // Find all initial files const initialFiles = new Map<string, InitialFileRecord>(); for (const outputFile of result.outputFiles) { // Entries in the metafile are relative to the `absWorkingDir` option which is set to the workspaceRoot const relativeFilePath = relative(this.workspaceRoot, outputFile.path); const entryPoint = result.metafile.outputs[relativeFilePath]?.entryPoint; outputFile.path = relativeFilePath; if (entryPoint) { // The first part of the filename is the name of file (e.g., "polyfills" for "polyfills-7S5G3MDY.js") const name = basename(relativeFilePath).replace(/(?:-[\dA-Z]{8})?\.[a-z]{2,3}$/, ''); // Entry points are only styles or scripts const type = extname(relativeFilePath) === '.css' ? 'style' : 'script'; // Only entrypoints with an entry in the options are initial files. // Dynamic imports also have an entryPoint value in the meta file. if ((this.#esbuildOptions.entryPoints as Record<string, string>)?.[name]) { // An entryPoint value indicates an initial file const record: InitialFileRecord = { name, type, entrypoint: true, serverFile: isPlatformServer, depth: 0, }; if (!this.initialFilter || this.initialFilter(record)) { initialFiles.set(relativeFilePath, record); } } } } // Analyze for transitive initial files const entriesToAnalyze = [...initialFiles]; let currentEntry; while ((currentEntry = entriesToAnalyze.pop())) { const [entryPath, entryRecord] = currentEntry; for (const initialImport of result.metafile.outputs[entryPath].imports) { const existingRecord = initialFiles.get(initialImport.path); if (existingRecord) { // Store the smallest value depth if (existingRecord.depth > entryRecord.depth + 1) { existingRecord.depth = entryRecord.depth + 1; } continue; } if (initialImport.kind === 'import-statement' || initialImport.kind === 'import-rule') { const record: InitialFileRecord = { type: initialImport.kind === 'import-rule' ? 'style' : 'script', entrypoint: false, external: initialImport.external, serverFile: isPlatformServer, depth: entryRecord.depth + 1, }; if (!this.initialFilter || this.initialFilter(record)) { initialFiles.set(initialImport.path, record); } if (!initialImport.external) { entriesToAnalyze.push([initialImport.path, record]); } } } } // Collect all external package names const externalImports = new Set<string>(); for (const { imports } of Object.values(result.metafile.outputs)) { for (const importData of imports) { if ( !importData.external || SERVER_GENERATED_EXTERNALS.has(importData.path) || (importData.kind !== 'import-statement' && importData.kind !== 'dynamic-import' && importData.kind !== 'require-call') ) { continue; } externalImports.add(importData.path); } } assert(this.#esbuildOptions, 'esbuild options cannot be undefined.'); const outputFiles = result.outputFiles.map((file) => { let fileType: BuildOutputFileType; // All files that are not JS, CSS, WASM, or sourcemaps for them are considered media if (!/\.([cm]?js|css|wasm)(\.map)?$/i.test(file.path)) { fileType = BuildOutputFileType.Media; } else if (isPlatformServer) { fileType = isSsrEntryBundle ? BuildOutputFileType.ServerRoot : BuildOutputFileType.ServerApplication; } else { fileType = BuildOutputFileType.Browser; } return convertOutputFile(file, fileType); }); let externalConfiguration = this.#esbuildOptions.external; if (isPlatformServer && externalConfiguration) { externalConfiguration = externalConfiguration.filter( (dep) => !SERVER_GENERATED_EXTERNALS.has(dep), ); if (!externalConfiguration.length) { externalConfiguration = undefined; } } // Return the successful build results return { ...result, outputFiles, initialFiles, externalImports: { [isPlatformServer ? 'server' : 'browser']: externalImports, }, externalConfiguration, errors: undefined, }; } #addErrorsToWatch(result: BuildFailure | BuildResult): void { for (const error of result.errors) { let file = error.location?.file; if (file && !isInternalAngularFile(file)) { this.watchFiles.add(join(this.workspaceRoot, file)); } for (const note of error.notes) { file = note.location?.file; if (file && !isInternalAngularFile(file)) { this.watchFiles.add(join(this.workspaceRoot, file)); } } } } /** * Invalidate a stored bundler result based on the previous watch files * and a list of changed files. * The context must be created with incremental mode enabled for results * to be stored. * @returns True, if the result was invalidated; False, otherwise. */ invalidate(files: Iterable<string>): boolean { if (!this.incremental) { return false; } let invalid = false; for (const file of files) { if (this.#loadCache?.invalidate(file)) { invalid = true; continue; } invalid ||= this.watchFiles.has(file); } if (invalid) { this.#esbuildResult = undefined; } return invalid; } /** * Disposes incremental build resources present in the context. * * @returns A promise that resolves when disposal is complete. */ async dispose(): Promise<void> { try { this.#esbuildOptions = undefined; this.#esbuildResult = undefined; this.#loadCache = undefined; await this.#esbuildContext?.dispose(); } finally { this.#esbuildContext = undefined; } } }
{ "end_byte": 15103, "start_byte": 6167, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/bundler-context.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/bundler-context.ts_15105_15191
function isInternalAngularFile(file: string) { return file.startsWith('angular:'); }
{ "end_byte": 15191, "start_byte": 15105, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/bundler-context.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/index-html-generator.ts_0_4108
/** * @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 'node:assert'; import path from 'node:path'; import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import { IndexHtmlGenerator } from '../../utils/index-file/index-html-generator'; import { BuildOutputFile, BuildOutputFileType, InitialFileRecord } from './bundler-context'; /** * The maximum number of module preload link elements that should be added for * initial scripts. */ const MODULE_PRELOAD_MAX = 10; export async function generateIndexHtml( initialFiles: Map<string, InitialFileRecord>, outputFiles: BuildOutputFile[], buildOptions: NormalizedApplicationBuildOptions, lang?: string, ): Promise<{ csrContent: string; ssrContent?: string; warnings: string[]; errors: string[]; }> { // Analyze metafile for initial link-based hints. // Skip if the internal externalPackages option is enabled since this option requires // dev server cooperation to properly resolve and fetch imports. const hints = []; const { indexHtmlOptions, externalPackages, optimizationOptions, crossOrigin, subresourceIntegrity, baseHref, } = buildOptions; assert(indexHtmlOptions, 'indexHtmlOptions cannot be undefined.'); if (!externalPackages && indexHtmlOptions.preloadInitial) { const modulePreloads = []; for (const [key, value] of initialFiles) { if (value.entrypoint || value.serverFile) { // Entry points are already referenced in the HTML continue; } if (value.type === 'script') { modulePreloads.push({ url: key, mode: 'modulepreload' as const, depth: value.depth }); } else if (value.type === 'style') { // Provide an "as" value of "style" to ensure external URLs which may not have a // file extension are treated as stylesheets. hints.push({ url: key, mode: 'preload' as const, as: 'style' }); } } // Limit the number of module preloads with smallest depth given priority modulePreloads.sort((a, b) => a.depth - b.depth); hints.push(...modulePreloads.slice(0, MODULE_PRELOAD_MAX)); } /** Virtual output path to support reading in-memory files. */ const browserOutputFiles = outputFiles.filter(({ type }) => type === BuildOutputFileType.Browser); const virtualOutputPath = '/'; const readAsset = async function (filePath: string): Promise<string> { // Remove leading directory separator const relativefilePath = path.relative(virtualOutputPath, filePath); const file = browserOutputFiles.find((file) => file.path === relativefilePath); if (file) { return file.text; } throw new Error(`Output file does not exist: ${relativefilePath}`); }; // Read the Auto CSP options. const autoCsp = buildOptions.security?.autoCsp; const autoCspOptions = autoCsp === true ? { unsafeEval: false } : autoCsp ? { unsafeEval: !!autoCsp.unsafeEval } : undefined; // Create an index HTML generator that reads from the in-memory output files const indexHtmlGenerator = new IndexHtmlGenerator({ indexPath: indexHtmlOptions.input, entrypoints: indexHtmlOptions.insertionOrder, sri: subresourceIntegrity, optimization: optimizationOptions, crossOrigin: crossOrigin, deployUrl: buildOptions.publicPath, postTransform: indexHtmlOptions.transformer, generateDedicatedSSRContent: !!( buildOptions.ssrOptions || buildOptions.prerenderOptions || buildOptions.appShellOptions ), autoCsp: autoCspOptions, }); indexHtmlGenerator.readAsset = readAsset; return indexHtmlGenerator.process({ baseHref, lang, outputPath: virtualOutputPath, files: [...initialFiles] .filter(([, file]) => !file.serverFile) .map(([file, record]) => ({ name: record.name ?? '', file, extension: path.extname(file), })), hints, }); }
{ "end_byte": 4108, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/index-html-generator.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/commonjs-checker.ts_0_6123
/** * @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 { Metafile, PartialMessage } from 'esbuild'; /** * Checks the input files of a build to determine if any of the files included * in the build are not ESM. ESM files can be tree-shaken and otherwise optimized * in ways that CommonJS and other module formats cannot. The esbuild metafile * information is used as the basis for the analysis as it contains information * for each input file including its respective format. * * If any allowed dependencies are provided via the `allowedCommonJsDependencies` * parameter, both the direct import and any deep imports will be ignored and no * diagnostic will be generated. Use `'*'` as entry to skip the check. * * If a module has been issued a diagnostic message, then all descendant modules * will not be checked. This prevents a potential massive amount of inactionable * messages since the initial module import is the cause of the problem. * * @param metafile An esbuild metafile object to check. * @param allowedCommonJsDependencies An optional list of allowed dependencies. * @returns Zero or more diagnostic messages for any non-ESM modules. */ export function checkCommonJSModules( metafile: Metafile, allowedCommonJsDependencies?: string[], ): PartialMessage[] { const messages: PartialMessage[] = []; const allowedRequests = new Set(allowedCommonJsDependencies); if (allowedRequests.has('*')) { return messages; } // Ignore Angular locale definitions which are currently UMD allowedRequests.add('@angular/common/locales'); // Ignore zone.js due to it currently being built with a UMD like structure. // Once the build output is updated to be fully ESM, this can be removed. allowedRequests.add('zone.js'); // Used by '@angular/platform-server' and is in a seperate chunk that is unused when // using `provideHttpClient(withFetch())`. allowedRequests.add('xhr2'); // Packages used by @angular/ssr. // While beasties is ESM it has a number of direct and transtive CJS deps. allowedRequests.add('express'); allowedRequests.add('beasties'); // Find all entry points that contain code (JS/TS) const files: string[] = []; for (const { entryPoint } of Object.values(metafile.outputs)) { if (!entryPoint) { continue; } if (!isPathCode(entryPoint)) { continue; } files.push(entryPoint); } // Track seen files so they are only analyzed once. // Bundler runtime code is also ignored since it cannot be actionable. const seenFiles = new Set<string>(['<runtime>']); // Analyze the files present by walking the import graph let currentFile: string | undefined; while ((currentFile = files.shift())) { const input = metafile.inputs[currentFile]; for (const imported of input.imports) { // Ignore imports that were already seen or not originally in the code (bundler injected) if (!imported.original || seenFiles.has(imported.path)) { continue; } seenFiles.add(imported.path); // If the dependency is allowed ignore all other checks if (allowedRequests.has(imported.original)) { continue; } // Only check actual code files if (!isPathCode(imported.path)) { continue; } // Check if non-relative import is ESM format and issue a diagnostic if the file is not allowed if ( !isPotentialRelative(imported.original) && metafile.inputs[imported.path].format !== 'esm' ) { const request = imported.original; let notAllowed = true; if (allowedRequests.has(request)) { notAllowed = false; } else { // Check for deep imports of allowed requests for (const allowed of allowedRequests) { if (request.startsWith(allowed + '/')) { notAllowed = false; break; } } } if (notAllowed) { // Issue a diagnostic message for CommonJS module messages.push(createCommonJSModuleError(request, currentFile)); } // Skip all descendants since they are also most likely not ESM but solved by addressing this import continue; } // Add the path so that its imports can be checked files.push(imported.path); } } return messages; } /** * Determines if a file path has an extension that is a JavaScript or TypeScript * code file. * * @param name A path to check for code file extensions. * @returns True, if a code file path; false, otherwise. */ function isPathCode(name: string): boolean { return /\.[cm]?[jt]sx?$/.test(name); } /** * Test an import module specifier to determine if the string potentially references a relative file. * npm packages should not start with a period so if the first character is a period than it is not a * package. While this is sufficient for the use case in the CommmonJS checker, only checking the * first character does not definitely indicate the specifier is a relative path. * * @param specifier An import module specifier. * @returns True, if specifier is potentially relative; false, otherwise. */ function isPotentialRelative(specifier: string): boolean { return specifier[0] === '.'; } /** * Creates an esbuild diagnostic message for a given non-ESM module request. * * @param request The requested non-ESM module name. * @param importer The path of the file containing the import. * @returns A message representing the diagnostic. */ function createCommonJSModuleError(request: string, importer: string): PartialMessage { const error = { text: `Module '${request}' used by '${importer}' is not ESM`, notes: [ { text: 'CommonJS or AMD dependencies can cause optimization bailouts.\n' + 'For more information see: https://angular.dev/tools/cli/build#configuring-commonjs-dependencies', }, ], }; return error; }
{ "end_byte": 6123, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/commonjs-checker.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/sourcemap-ignorelist-plugin.ts_0_2947
/** * @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 { Plugin } from 'esbuild'; /** * The field identifier for the sourcemap Chrome Devtools ignore list extension. * * Following the naming conventions from https://sourcemaps.info/spec.html#h.ghqpj1ytqjbm */ const IGNORE_LIST_ID = 'x_google_ignoreList'; /** * The UTF-8 bytes for the node modules check text used to avoid unnecessary parsing * of a full source map if not present in the source map data. */ const NODE_MODULE_BYTES = Buffer.from('node_modules/', 'utf-8'); /** * Minimal sourcemap object required to create the ignore list. */ interface SourceMap { sources: string[]; [IGNORE_LIST_ID]?: number[]; } /** * Creates an esbuild plugin that updates generated sourcemaps to include the Chrome * DevTools ignore list extension. All source files that originate from a node modules * directory are added to the ignore list by this plugin. * * For more information, see https://developer.chrome.com/articles/x-google-ignore-list/ * @returns An esbuild plugin. */ export function createSourcemapIgnorelistPlugin(): Plugin { return { name: 'angular-sourcemap-ignorelist', setup(build): void { if (!build.initialOptions.sourcemap) { return; } build.onEnd((result) => { if (!result.outputFiles) { return; } for (const file of result.outputFiles) { // Only process sourcemap files if (!file.path.endsWith('.map')) { continue; } // Create a Buffer object that shares the memory of the output file contents const contents = Buffer.from( file.contents.buffer, file.contents.byteOffset, file.contents.byteLength, ); // Avoid parsing sourcemaps that have no node modules references if (!contents.includes(NODE_MODULE_BYTES)) { continue; } const map = JSON.parse(contents.toString('utf-8')) as SourceMap; const ignoreList = []; // Check and store the index of each source originating from a node modules directory for (let index = 0; index < map.sources.length; ++index) { const location = map.sources[index].indexOf('node_modules/'); if (location === 0 || (location > 0 && map.sources[index][location - 1] === '/')) { ignoreList.push(index); } } // Avoid regenerating the source map if nothing changed if (ignoreList.length === 0) { continue; } // Update the sourcemap in the output file map[IGNORE_LIST_ID] = ignoreList; file.contents = Buffer.from(JSON.stringify(map), 'utf-8'); } }); }, }; }
{ "end_byte": 2947, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/sourcemap-ignorelist-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/javascript-transformer.ts_0_6146
/** * @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 { createHash } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { WorkerPool } from '../../utils/worker-pool'; import { Cache } from './cache'; /** * Transformation options that should apply to all transformed files and data. */ export interface JavaScriptTransformerOptions { sourcemap: boolean; thirdPartySourcemaps?: boolean; advancedOptimizations?: boolean; jit?: boolean; } /** * A class that performs transformation of JavaScript files and raw data. * A worker pool is used to distribute the transformation actions and allow * parallel processing. Transformation behavior is based on the filename and * data. Transformations may include: async downleveling, Angular linking, * and advanced optimizations. */ export class JavaScriptTransformer { #workerPool: WorkerPool | undefined; #commonOptions: Required<JavaScriptTransformerOptions>; #fileCacheKeyBase: Uint8Array; constructor( options: JavaScriptTransformerOptions, readonly maxThreads: number, private readonly cache?: Cache<Uint8Array>, ) { // Extract options to ensure only the named options are serialized and sent to the worker const { sourcemap, thirdPartySourcemaps = false, advancedOptimizations = false, jit = false, } = options; this.#commonOptions = { sourcemap, thirdPartySourcemaps, advancedOptimizations, jit, }; this.#fileCacheKeyBase = Buffer.from(JSON.stringify(this.#commonOptions), 'utf-8'); } #ensureWorkerPool(): WorkerPool { this.#workerPool ??= new WorkerPool({ filename: require.resolve('./javascript-transformer-worker'), maxThreads: this.maxThreads, // Prevent passing `--import` (loader-hooks) from parent to child worker. execArgv: [], }); return this.#workerPool; } /** * Performs JavaScript transformations on a file from the filesystem. * If no transformations are required, the data for the original file will be returned. * @param filename The full path to the file. * @param skipLinker If true, bypass all Angular linker processing; if false, attempt linking. * @param sideEffects If false, and `advancedOptimizations` is enabled tslib decorators are wrapped. * @returns A promise that resolves to a UTF-8 encoded Uint8Array containing the result. */ async transformFile( filename: string, skipLinker?: boolean, sideEffects?: boolean, instrumentForCoverage?: boolean, ): Promise<Uint8Array> { const data = await readFile(filename); let result; let cacheKey; if (this.cache) { // Create a cache key from the file data and options that effect the output. // NOTE: If additional options are added, this may need to be updated. // TODO: Consider xxhash or similar instead of SHA256 const hash = createHash('sha256'); hash.update(`${!!skipLinker}--${!!sideEffects}`); hash.update(data); hash.update(this.#fileCacheKeyBase); cacheKey = hash.digest('hex'); try { result = await this.cache?.get(cacheKey); } catch { // Failure to get the value should not fail the transform } } if (result === undefined) { // If there is no cache or no cached entry, process the file result = (await this.#ensureWorkerPool().run( { filename, data, skipLinker, sideEffects, instrumentForCoverage, ...this.#commonOptions, }, { // The below is disable as with Yarn PNP this causes build failures with the below message // `Unable to deserialize cloned data`. transferList: process.versions.pnp ? undefined : [data.buffer], }, )) as Uint8Array; // If there is a cache then store the result if (this.cache && cacheKey) { try { await this.cache.put(cacheKey, result); } catch { // Failure to store the value in the cache should not fail the transform } } } return result; } /** * Performs JavaScript transformations on the provided data of a file. The file does not need * to exist on the filesystem. * @param filename The full path of the file represented by the data. * @param data The data of the file that should be transformed. * @param skipLinker If true, bypass all Angular linker processing; if false, attempt linking. * @param sideEffects If false, and `advancedOptimizations` is enabled tslib decorators are wrapped. * @returns A promise that resolves to a UTF-8 encoded Uint8Array containing the result. */ async transformData( filename: string, data: string, skipLinker: boolean, sideEffects?: boolean, instrumentForCoverage?: boolean, ): Promise<Uint8Array> { // Perform a quick test to determine if the data needs any transformations. // This allows directly returning the data without the worker communication overhead. if (skipLinker && !this.#commonOptions.advancedOptimizations && !instrumentForCoverage) { const keepSourcemap = this.#commonOptions.sourcemap && (!!this.#commonOptions.thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename)); return Buffer.from( keepSourcemap ? data : data.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''), 'utf-8', ); } return this.#ensureWorkerPool().run({ filename, data, skipLinker, sideEffects, instrumentForCoverage, ...this.#commonOptions, }); } /** * Stops all active transformation tasks and shuts down all workers. * @returns A void promise that resolves when closing is complete. */ async close(): Promise<void> { if (this.#workerPool) { try { await this.#workerPool.destroy(); } finally { this.#workerPool = undefined; } } } }
{ "end_byte": 6146, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/javascript-transformer.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/application-code-bundle.ts_0_8014
/** * @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 { BuildOptions, PartialMessage } from 'esbuild'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; import { extname, relative } from 'node:path'; import type { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import { ExperimentalPlatform } from '../../builders/application/schema'; import { allowMangle } from '../../utils/environment-options'; import { SERVER_APP_ENGINE_MANIFEST_FILENAME, SERVER_APP_MANIFEST_FILENAME, } from '../../utils/server-rendering/manifest'; import { createCompilerPlugin } from './angular/compiler-plugin'; import { ComponentStylesheetBundler } from './angular/component-stylesheets'; import { SourceFileCache } from './angular/source-file-cache'; import { BundlerOptionsFactory } from './bundler-context'; import { createCompilerPluginOptions } from './compiler-plugin-options'; import { createExternalPackagesPlugin } from './external-packages-plugin'; import { createAngularLocaleDataPlugin } from './i18n-locale-plugin'; import { createLoaderImportAttributePlugin } from './loader-import-attribute-plugin'; import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin'; import { createServerBundleMetadata } from './server-bundle-metadata-plugin'; import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin'; import { SERVER_GENERATED_EXTERNALS, getFeatureSupport, isZonelessApp } from './utils'; import { createVirtualModulePlugin } from './virtual-module-plugin'; import { createWasmPlugin } from './wasm-plugin'; export function createBrowserCodeBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], sourceFileCache: SourceFileCache, stylesheetBundler: ComponentStylesheetBundler, ): BuildOptions { const { entryPoints, outputNames, polyfills } = options; const pluginOptions = createCompilerPluginOptions(options, sourceFileCache); const zoneless = isZonelessApp(polyfills); const buildOptions: BuildOptions = { ...getEsBuildCommonOptions(options), platform: 'browser', // Note: `es2015` is needed for RxJS v6. If not specified, `module` would // match and the ES5 distribution would be bundled and ends up breaking at // runtime with the RxJS testing library. // More details: https://github.com/angular/angular-cli/issues/25405. mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'], entryNames: outputNames.bundles, entryPoints, target, supported: getFeatureSupport(target, zoneless), plugins: [ createLoaderImportAttributePlugin(), createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }), createSourcemapIgnorelistPlugin(), createCompilerPlugin( // JS/TS options pluginOptions, // Component stylesheet bundler stylesheetBundler, ), ], }; if (options.plugins) { buildOptions.plugins?.push(...options.plugins); } if (options.externalPackages) { // Package files affected by a customized loader should not be implicitly marked as external if ( options.loaderExtensions || options.plugins || typeof options.externalPackages === 'object' ) { // Plugin must be added after custom plugins to ensure any added loader options are considered buildOptions.plugins?.push( createExternalPackagesPlugin( options.externalPackages !== true ? options.externalPackages : undefined, ), ); } else { // Safe to use the packages external option directly buildOptions.packages = 'external'; } } return buildOptions; } export function createBrowserPolyfillBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], sourceFileCache: SourceFileCache, stylesheetBundler: ComponentStylesheetBundler, ): BuildOptions | BundlerOptionsFactory | undefined { const namespace = 'angular:polyfills'; const polyfillBundleOptions = getEsBuildCommonPolyfillsOptions( options, namespace, true, sourceFileCache, ); if (!polyfillBundleOptions) { return; } const { outputNames, polyfills } = options; const hasTypeScriptEntries = polyfills?.some((entry) => /\.[cm]?tsx?$/.test(entry)); const buildOptions: BuildOptions = { ...polyfillBundleOptions, platform: 'browser', // Note: `es2015` is needed for RxJS v6. If not specified, `module` would // match and the ES5 distribution would be bundled and ends up breaking at // runtime with the RxJS testing library. // More details: https://github.com/angular/angular-cli/issues/25405. mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'], entryNames: outputNames.bundles, target, entryPoints: { 'polyfills': namespace, }, }; // Only add the Angular TypeScript compiler if TypeScript files are provided in the polyfills if (hasTypeScriptEntries) { buildOptions.plugins ??= []; const pluginOptions = createCompilerPluginOptions( options, sourceFileCache, ); buildOptions.plugins.push( createCompilerPlugin( // JS/TS options { ...pluginOptions, noopTypeScriptCompilation: true }, // Component stylesheet options are unused for polyfills but required by the plugin stylesheetBundler, ), ); } // Use an options factory to allow fully incremental bundling when no TypeScript files are present. // The TypeScript compilation is not currently integrated into the bundler invalidation so // cannot be used with fully incremental bundling yet. return hasTypeScriptEntries ? buildOptions : () => buildOptions; } export function createServerPolyfillBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], sourceFileCache?: SourceFileCache, ): BundlerOptionsFactory | undefined { const serverPolyfills: string[] = []; const polyfillsFromConfig = new Set(options.polyfills); const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral; if (!isZonelessApp(options.polyfills)) { serverPolyfills.push(isNodePlatform ? 'zone.js/node' : 'zone.js'); } if ( polyfillsFromConfig.has('@angular/localize') || polyfillsFromConfig.has('@angular/localize/init') ) { serverPolyfills.push('@angular/localize/init'); } serverPolyfills.push('@angular/platform-server/init'); const namespace = 'angular:polyfills-server'; const polyfillBundleOptions = getEsBuildCommonPolyfillsOptions( { ...options, polyfills: serverPolyfills, }, namespace, false, sourceFileCache, ); if (!polyfillBundleOptions) { return; } const buildOptions: BuildOptions = { ...polyfillBundleOptions, platform: isNodePlatform ? 'node' : 'neutral', outExtension: { '.js': '.mjs' }, // Note: `es2015` is needed for RxJS v6. If not specified, `module` would // match and the ES5 distribution would be bundled and ends up breaking at // runtime with the RxJS testing library. // More details: https://github.com/angular/angular-cli/issues/25405. mainFields: ['es2020', 'es2015', 'module', 'main'], entryNames: '[name]', banner: isNodePlatform ? { js: [ // Note: Needed as esbuild does not provide require shims / proxy from ESModules. // See: https://github.com/evanw/esbuild/issues/1921. `import { createRequire } from 'node:module';`, `globalThis['require'] ??= createRequire(import.meta.url);`, ].join('\n'), } : undefined, target, entryPoints: { 'polyfills.server': namespace, }, }; buildOptions.plugins ??= []; buildOptions.plugins.push(createServerBundleMetadata()); return () => buildOptions; }
{ "end_byte": 8014, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/application-code-bundle.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/application-code-bundle.ts_8016_12696
export function createServerMainCodeBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], sourceFileCache: SourceFileCache, stylesheetBundler: ComponentStylesheetBundler, ): BuildOptions { const { serverEntryPoint: mainServerEntryPoint, workspaceRoot, outputMode, externalPackages, ssrOptions, polyfills, } = options; assert( mainServerEntryPoint, 'createServerCodeBundleOptions should not be called without a defined serverEntryPoint.', ); const pluginOptions = createCompilerPluginOptions(options, sourceFileCache); const mainServerNamespace = 'angular:main-server'; const mainServerInjectPolyfillsNamespace = 'angular:main-server-inject-polyfills'; const mainServerInjectManifestNamespace = 'angular:main-server-inject-manifest'; const zoneless = isZonelessApp(polyfills); const entryPoints: Record<string, string> = { 'main.server': mainServerNamespace, }; const ssrEntryPoint = ssrOptions?.entry; const isOldBehaviour = !outputMode; if (ssrEntryPoint && isOldBehaviour) { // Old behavior: 'server.ts' was bundled together with the SSR (Server-Side Rendering) code. // This approach combined server-side logic and rendering into a single bundle. entryPoints['server'] = ssrEntryPoint; } const buildOptions: BuildOptions = { ...getEsBuildServerCommonOptions(options), target, inject: [mainServerInjectPolyfillsNamespace, mainServerInjectManifestNamespace], entryPoints, supported: getFeatureSupport(target, zoneless), plugins: [ createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }), createSourcemapIgnorelistPlugin(), createCompilerPlugin( // JS/TS options { ...pluginOptions, noopTypeScriptCompilation: true }, // Component stylesheet bundler stylesheetBundler, ), ], }; buildOptions.plugins ??= []; if (externalPackages) { buildOptions.packages = 'external'; } else { buildOptions.plugins.push(createRxjsEsmResolutionPlugin()); } // Mark manifest and polyfills file as external as these are generated by a different bundle step. (buildOptions.external ??= []).push(...SERVER_GENERATED_EXTERNALS); const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral; if (!isNodePlatform) { // `@angular/platform-server` lazily depends on `xhr2` for XHR usage with the HTTP client. // Since `xhr2` has Node.js dependencies, it cannot be used when targeting non-Node.js platforms. // Note: The framework already issues a warning when using XHR with SSR. buildOptions.external.push('xhr2'); } buildOptions.plugins.push( createServerBundleMetadata(), createVirtualModulePlugin({ namespace: mainServerInjectPolyfillsNamespace, cache: sourceFileCache?.loadResultCache, loadContent: () => ({ contents: `import './polyfills.server.mjs';`, loader: 'js', resolveDir: workspaceRoot, }), }), createVirtualModulePlugin({ namespace: mainServerInjectManifestNamespace, cache: sourceFileCache?.loadResultCache, loadContent: async () => { const contents: string[] = [ // Configure `@angular/ssr` manifest. `import manifest from './${SERVER_APP_MANIFEST_FILENAME}';`, `import { ɵsetAngularAppManifest } from '@angular/ssr';`, `ɵsetAngularAppManifest(manifest);`, ]; return { contents: contents.join('\n'), loader: 'js', resolveDir: workspaceRoot, }; }, }), createVirtualModulePlugin({ namespace: mainServerNamespace, cache: sourceFileCache?.loadResultCache, loadContent: async () => { const mainServerEntryPointJsImport = entryFileToWorkspaceRelative( workspaceRoot, mainServerEntryPoint, ); const contents: string[] = [ // Re-export all symbols including default export from 'main.server.ts' `export { default } from '${mainServerEntryPointJsImport}';`, `export * from '${mainServerEntryPointJsImport}';`, // Add @angular/ssr exports `export { ɵdestroyAngularServerApp, ɵextractRoutesAndCreateRouteTree, ɵgetOrCreateAngularServerApp, } from '@angular/ssr';`, ]; return { contents: contents.join('\n'), loader: 'js', resolveDir: workspaceRoot, }; }, }), ); if (options.plugins) { buildOptions.plugins.push(...options.plugins); } return buildOptions; } exp
{ "end_byte": 12696, "start_byte": 8016, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/application-code-bundle.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/application-code-bundle.ts_12698_20749
t function createSsrEntryCodeBundleOptions( options: NormalizedApplicationBuildOptions, target: string[], sourceFileCache: SourceFileCache, stylesheetBundler: ComponentStylesheetBundler, ): BuildOptions { const { workspaceRoot, ssrOptions, externalPackages } = options; const serverEntryPoint = ssrOptions?.entry; assert( serverEntryPoint, 'createSsrEntryCodeBundleOptions should not be called without a defined serverEntryPoint.', ); const pluginOptions = createCompilerPluginOptions(options, sourceFileCache); const ssrEntryNamespace = 'angular:ssr-entry'; const ssrInjectManifestNamespace = 'angular:ssr-entry-inject-manifest'; const ssrInjectRequireNamespace = 'angular:ssr-entry-inject-require'; const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral; const inject: string[] = [ssrInjectManifestNamespace]; if (isNodePlatform) { inject.unshift(ssrInjectRequireNamespace); } const buildOptions: BuildOptions = { ...getEsBuildServerCommonOptions(options), target, entryPoints: { // TODO: consider renaming to index 'server': ssrEntryNamespace, }, supported: getFeatureSupport(target, true), plugins: [ createSourcemapIgnorelistPlugin(), createCompilerPlugin( // JS/TS options { ...pluginOptions, noopTypeScriptCompilation: true }, // Component stylesheet bundler stylesheetBundler, ), ], inject, }; buildOptions.plugins ??= []; if (externalPackages) { buildOptions.packages = 'external'; } else { buildOptions.plugins.push(createRxjsEsmResolutionPlugin()); } // Mark manifest file as external. As this will be generated later on. (buildOptions.external ??= []).push('*/main.server.mjs', ...SERVER_GENERATED_EXTERNALS); if (!isNodePlatform) { // `@angular/platform-server` lazily depends on `xhr2` for XHR usage with the HTTP client. // Since `xhr2` has Node.js dependencies, it cannot be used when targeting non-Node.js platforms. // Note: The framework already issues a warning when using XHR with SSR. buildOptions.external.push('xhr2'); } buildOptions.plugins.push( createServerBundleMetadata({ ssrEntryBundle: true }), createVirtualModulePlugin({ namespace: ssrInjectRequireNamespace, cache: sourceFileCache?.loadResultCache, loadContent: () => { const contents: string[] = [ // Note: Needed as esbuild does not provide require shims / proxy from ESModules. // See: https://github.com/evanw/esbuild/issues/1921. `import { createRequire } from 'node:module';`, `globalThis['require'] ??= createRequire(import.meta.url);`, ]; return { contents: contents.join('\n'), loader: 'js', resolveDir: workspaceRoot, }; }, }), createVirtualModulePlugin({ namespace: ssrInjectManifestNamespace, cache: sourceFileCache?.loadResultCache, loadContent: () => { const contents: string[] = [ // Configure `@angular/ssr` app engine manifest. `import manifest from './${SERVER_APP_ENGINE_MANIFEST_FILENAME}';`, `import { ɵsetAngularAppEngineManifest } from '@angular/ssr';`, `ɵsetAngularAppEngineManifest(manifest);`, ]; return { contents: contents.join('\n'), loader: 'js', resolveDir: workspaceRoot, }; }, }), createVirtualModulePlugin({ namespace: ssrEntryNamespace, cache: sourceFileCache?.loadResultCache, loadContent: () => { const serverEntryPointJsImport = entryFileToWorkspaceRelative( workspaceRoot, serverEntryPoint, ); const contents: string[] = [ // Re-export all symbols including default export `import * as server from '${serverEntryPointJsImport}';`, `export * from '${serverEntryPointJsImport}';`, // The below is needed to avoid // `Import "default" will always be undefined because there is no matching export` warning when no default is present. `const defaultExportName = 'default';`, `export default server[defaultExportName]`, // Add @angular/ssr exports `export { AngularAppEngine } from '@angular/ssr';`, ]; return { contents: contents.join('\n'), loader: 'js', resolveDir: workspaceRoot, }; }, }), ); if (options.plugins) { buildOptions.plugins.push(...options.plugins); } return buildOptions; } function getEsBuildServerCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions { const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral; return { ...getEsBuildCommonOptions(options), platform: isNodePlatform ? 'node' : 'neutral', outExtension: { '.js': '.mjs' }, // Note: `es2015` is needed for RxJS v6. If not specified, `module` would // match and the ES5 distribution would be bundled and ends up breaking at // runtime with the RxJS testing library. // More details: https://github.com/angular/angular-cli/issues/25405. mainFields: ['es2020', 'es2015', 'module', 'main'], entryNames: '[name]', }; } function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions { const { workspaceRoot, outExtension, optimizationOptions, sourcemapOptions, tsconfig, externalDependencies, outputNames, preserveSymlinks, jit, loaderExtensions, jsonLogs, i18nOptions, } = options; // Ensure unique hashes for i18n translation changes when using post-process inlining. // This hash value is added as a footer to each file and ensures that the output file names (with hashes) // change when translation files have changed. If this is not done the post processed files may have // different content but would retain identical production file names which would lead to browser caching problems. let footer; if (i18nOptions.shouldInline) { // Update file hashes to include translation file content const i18nHash = Object.values(i18nOptions.locales).reduce( (data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'), '', ); footer = { js: `/**i18n:${createHash('sha256').update(i18nHash).digest('hex')}*/` }; } return { absWorkingDir: workspaceRoot, format: 'esm', bundle: true, packages: 'bundle', assetNames: outputNames.media, conditions: [ 'es2020', 'es2015', 'module', optimizationOptions.scripts ? 'production' : 'development', ], resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'], metafile: true, legalComments: options.extractLicenses ? 'none' : 'eof', logLevel: options.verbose && !jsonLogs ? 'debug' : 'silent', minifyIdentifiers: optimizationOptions.scripts && allowMangle, minifySyntax: optimizationOptions.scripts, minifyWhitespace: optimizationOptions.scripts, pure: ['forwardRef'], outdir: workspaceRoot, outExtension: outExtension ? { '.js': `.${outExtension}` } : undefined, sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true), splitting: true, chunkNames: options.namedChunks ? '[name]-[hash]' : 'chunk-[hash]', tsconfig, external: externalDependencies ? [...externalDependencies] : undefined, write: false, preserveSymlinks, define: { ...options.define, // Only set to false when script optimizations are enabled. It should not be set to true because // Angular turns `ngDevMode` into an object for development debugging purposes when not defined // which a constant true value would break. ...(optimizationOptions.scripts ? { 'ngDevMode': 'false' } : undefined), 'ngJitMode': jit ? 'true' : 'false', }, loader: loaderExtensions, footer, }; } funct
{ "end_byte": 20749, "start_byte": 12698, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/application-code-bundle.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/application-code-bundle.ts_20751_24523
n getEsBuildCommonPolyfillsOptions( options: NormalizedApplicationBuildOptions, namespace: string, tryToResolvePolyfillsAsRelative: boolean, sourceFileCache: SourceFileCache | undefined, ): BuildOptions | undefined { const { jit, workspaceRoot, i18nOptions } = options; const buildOptions: BuildOptions = { ...getEsBuildCommonOptions(options), splitting: false, plugins: [createSourcemapIgnorelistPlugin()], }; let polyfills = options.polyfills ? [...options.polyfills] : []; // Angular JIT mode requires the runtime compiler if (jit) { polyfills.unshift('@angular/compiler'); } // Add Angular's global locale data if i18n options are present. // Locale data should go first so that project provided polyfill code can augment if needed. let needLocaleDataPlugin = false; if (i18nOptions.shouldInline) { // Remove localize polyfill as this is not needed for build time i18n. polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize')); // Add locale data for all active locales // TODO: Inject each individually within the inlining process itself for (const locale of i18nOptions.inlineLocales) { polyfills.unshift(`angular:locale/data:${locale}`); } needLocaleDataPlugin = true; } else if (i18nOptions.hasDefinedSourceLocale) { // When not inlining and a source local is present, use the source locale data directly polyfills.unshift(`angular:locale/data:${i18nOptions.sourceLocale}`); needLocaleDataPlugin = true; } if (needLocaleDataPlugin) { buildOptions.plugins?.push(createAngularLocaleDataPlugin()); } if (polyfills.length === 0) { return; } buildOptions.plugins?.push( createVirtualModulePlugin({ namespace, cache: sourceFileCache?.loadResultCache, loadContent: async (_, build) => { let polyfillPaths = polyfills; let warnings: PartialMessage[] | undefined; if (tryToResolvePolyfillsAsRelative) { polyfillPaths = await Promise.all( polyfills.map(async (path) => { if (path.startsWith('zone.js') || !extname(path)) { return path; } const potentialPathRelative = './' + path; const result = await build.resolve(potentialPathRelative, { kind: 'import-statement', resolveDir: workspaceRoot, }); return result.path ? potentialPathRelative : path; }), ); } // Generate module contents with an import statement per defined polyfill let contents = polyfillPaths .map((file) => `import '${file.replace(/\\/g, '/')}';`) .join('\n'); // The below should be done after loading `$localize` as otherwise the locale will be overridden. if (i18nOptions.shouldInline) { // When inlining, a placeholder is used to allow the post-processing step to inject the $localize locale identifier. contents += '(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n'; } else if (i18nOptions.hasDefinedSourceLocale) { // If not inlining translations and source locale is defined, inject the locale specifier. contents += `(globalThis.$localize ??= {}).locale = "${i18nOptions.sourceLocale}";\n`; } return { contents, loader: 'js', warnings, resolveDir: workspaceRoot, }; }, }), ); return buildOptions; } function entryFileToWorkspaceRelative(workspaceRoot: string, entryFile: string): string { return ( './' + relative(workspaceRoot, entryFile) .replace(/.[mc]?ts$/, '') .replace(/\\/g, '/') ); }
{ "end_byte": 24523, "start_byte": 20751, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/application-code-bundle.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/license-extractor.ts_0_6042
/** * @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 { Metafile } from 'esbuild'; import { readFile } from 'node:fs/promises'; import path from 'node:path'; /** * The path segment used to signify that a file is part of a package. */ const NODE_MODULE_SEGMENT = 'node_modules'; /** * String constant for the NPM recommended custom license wording. * * See: https://docs.npmjs.com/cli/v9/configuring-npm/package-json#license * * Example: * ``` * { * "license" : "SEE LICENSE IN <filename>" * } * ``` */ const CUSTOM_LICENSE_TEXT = 'SEE LICENSE IN '; /** * A list of commonly named license files found within packages. */ const LICENSE_FILES = ['LICENSE', 'LICENSE.txt', 'LICENSE.md']; /** * Header text that will be added to the top of the output license extraction file. */ const EXTRACTION_FILE_HEADER = ''; /** * The package entry separator to use within the output license extraction file. */ const EXTRACTION_FILE_SEPARATOR = '-'.repeat(80) + '\n'; /** * Extracts license information for each node module package included in the output * files of the built code. This includes JavaScript and CSS output files. The esbuild * metafile generated during the bundling steps is used as the source of information * regarding what input files where included and where they are located. A path segment * of `node_modules` is used to indicate that a file belongs to a package and its license * should be include in the output licenses file. * * The package name and license field are extracted from the `package.json` file for the * package. If a license file (e.g., `LICENSE`) is present in the root of the package, it * will also be included in the output licenses file. * * @param metafile An esbuild metafile object. * @param rootDirectory The root directory of the workspace. * @returns A string containing the content of the output licenses file. */ export async function extractLicenses(metafile: Metafile, rootDirectory: string) { let extractedLicenseContent = `${EXTRACTION_FILE_HEADER}\n${EXTRACTION_FILE_SEPARATOR}`; const seenPaths = new Set<string>(); const seenPackages = new Set<string>(); for (const entry of Object.values(metafile.outputs)) { for (const [inputPath, { bytesInOutput }] of Object.entries(entry.inputs)) { // Skip if not included in output if (bytesInOutput <= 0) { continue; } // Skip already processed paths if (seenPaths.has(inputPath)) { continue; } seenPaths.add(inputPath); // Skip non-package paths if (!inputPath.includes(NODE_MODULE_SEGMENT)) { continue; } // Extract the package name from the path let baseDirectory = path.join(rootDirectory, inputPath); let nameOrScope, nameOrFile; let found = false; while (baseDirectory !== path.dirname(baseDirectory)) { const segment = path.basename(baseDirectory); if (segment === NODE_MODULE_SEGMENT) { found = true; break; } nameOrFile = nameOrScope; nameOrScope = segment; baseDirectory = path.dirname(baseDirectory); } // Skip non-package path edge cases that are not caught in the includes check above if (!found || !nameOrScope) { continue; } const packageName = nameOrScope.startsWith('@') ? `${nameOrScope}/${nameOrFile}` : nameOrScope; const packageDirectory = path.join(baseDirectory, packageName); // Load the package's metadata to find the package's name, version, and license type const packageJsonPath = path.join(packageDirectory, 'package.json'); let packageJson; try { packageJson = JSON.parse(await readFile(packageJsonPath, 'utf-8')) as { name: string; version: string; // The object form is deprecated and should only be present in old packages license?: string | { type: string }; }; } catch { // Invalid package continue; } // Skip already processed packages const packageId = `${packageName}@${packageJson.version}`; if (seenPackages.has(packageId)) { continue; } seenPackages.add(packageId); // Attempt to find license text inside package let licenseText = ''; if ( typeof packageJson.license === 'string' && packageJson.license.toLowerCase().startsWith(CUSTOM_LICENSE_TEXT) ) { // Attempt to load the package's custom license let customLicensePath; const customLicenseFile = path.normalize( packageJson.license.slice(CUSTOM_LICENSE_TEXT.length + 1).trim(), ); if (customLicenseFile.startsWith('..') || path.isAbsolute(customLicenseFile)) { // Path is attempting to access files outside of the package // TODO: Issue warning? } else { customLicensePath = path.join(packageDirectory, customLicenseFile); try { licenseText = await readFile(customLicensePath, 'utf-8'); break; } catch {} } } else { // Search for a license file within the root of the package for (const potentialLicense of LICENSE_FILES) { const packageLicensePath = path.join(packageDirectory, potentialLicense); try { licenseText = await readFile(packageLicensePath, 'utf-8'); break; } catch {} } } // Generate the package's license entry in the output content extractedLicenseContent += `Package: ${packageJson.name}\n`; extractedLicenseContent += `License: ${JSON.stringify(packageJson.license, null, 2)}\n`; extractedLicenseContent += `\n${licenseText}\n`; extractedLicenseContent += EXTRACTION_FILE_SEPARATOR; } } return extractedLicenseContent; }
{ "end_byte": 6042, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/license-extractor.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/virtual-module-plugin.ts_0_2081
/** * @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 { OnLoadArgs, Plugin, PluginBuild } from 'esbuild'; import { LoadResultCache, createCachedLoad } from './load-result-cache'; /** * Options for the createVirtualModulePlugin * @see createVirtualModulePlugin */ export interface VirtualModulePluginOptions { /** Namespace. Example: `angular:polyfills`. */ namespace: string; /** If the generated module should be marked as external. */ external?: boolean; /** Method to transform the onResolve path. */ transformPath?: (path: string) => string; /** Method to provide the module content. */ loadContent: ( args: OnLoadArgs, build: PluginBuild, ) => ReturnType<Parameters<PluginBuild['onLoad']>[1]>; /** Restrict to only entry points. Defaults to `true`. */ entryPointOnly?: boolean; /** Load results cache. */ cache?: LoadResultCache; } /** * Creates an esbuild plugin that generated virtual modules. * * @returns An esbuild plugin. */ export function createVirtualModulePlugin(options: VirtualModulePluginOptions): Plugin { const { namespace, external, transformPath: pathTransformer, loadContent, cache, entryPointOnly = true, } = options; return { name: namespace.replace(/[/:]/g, '-'), setup(build): void { build.onResolve({ filter: new RegExp('^' + namespace) }, ({ kind, path }) => { if (entryPointOnly && kind !== 'entry-point') { return null; } return { path: pathTransformer?.(path) ?? path, namespace, }; }); if (external) { build.onResolve({ filter: /./, namespace }, ({ path }) => { return { path, external: true, }; }); } build.onLoad( { filter: /./, namespace }, createCachedLoad(cache, (args) => loadContent(args, build)), ); }, }; }
{ "end_byte": 2081, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/virtual-module-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/wasm-plugin.ts_0_8736
/** * @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 { Plugin, ResolveOptions } from 'esbuild'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; import { assertIsError } from '../../utils/error'; import { LoadResultCache, createCachedLoad } from './load-result-cache'; /** * Options for the Angular WASM esbuild plugin * @see createWasmPlugin */ export interface WasmPluginOptions { /** Allow generation of async (proposal compliant) WASM imports. This requires zoneless to enable async/await. */ allowAsync?: boolean; /** Load results cache. */ cache?: LoadResultCache; } const WASM_INIT_NAMESPACE = 'angular:wasm:init'; const WASM_CONTENTS_NAMESPACE = 'angular:wasm:contents'; const WASM_RESOLVE_SYMBOL = Symbol('WASM_RESOLVE_SYMBOL'); // See: https://github.com/tc39/proposal-regexp-unicode-property-escapes/blob/fe6d07fad74cd0192d154966baa1e95e7cda78a1/README.md#other-examples const ecmaIdentifierNameRegExp = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u; /** * Creates an esbuild plugin to use WASM files with import statements and expressions. * The default behavior follows the WebAssembly/ES mode integration proposal found at * https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration. * This behavior requires top-level await support which is only available in zoneless * Angular applications. * @returns An esbuild plugin. */ export function createWasmPlugin(options: WasmPluginOptions): Plugin { const { allowAsync = false, cache } = options; return { name: 'angular-wasm', setup(build): void { build.onResolve({ filter: /\.wasm$/ }, async (args) => { // Skip if already resolving the WASM file to avoid infinite resolution if (args.pluginData?.[WASM_RESOLVE_SYMBOL]) { return; } // Skip if not an import statement or expression if (args.kind !== 'import-statement' && args.kind !== 'dynamic-import') { return; } // When in the initialization namespace, the content has already been resolved // and only needs to be loaded for use with the initialization code. if (args.namespace === WASM_INIT_NAMESPACE) { return { namespace: WASM_CONTENTS_NAMESPACE, path: join(args.resolveDir, args.path), pluginData: args.pluginData, }; } // Skip if a custom loader is defined if (build.initialOptions.loader?.['.wasm'] || args.with['loader']) { return; } // Attempt full resolution of the WASM file const resolveOptions: ResolveOptions & { path?: string } = { ...args, pluginData: { [WASM_RESOLVE_SYMBOL]: true }, }; // The "path" property will cause an error if used in the resolve call delete resolveOptions.path; const result = await build.resolve(args.path, resolveOptions); // Skip if there are errors, is external, or another plugin resolves to a custom namespace if (result.errors.length > 0 || result.external || result.namespace !== 'file') { // Reuse already resolved result return result; } return { ...result, namespace: WASM_INIT_NAMESPACE, }; }); build.onLoad( { filter: /\.wasm$/, namespace: WASM_INIT_NAMESPACE }, createCachedLoad(cache, async (args) => { // Ensure async mode is supported if (!allowAsync) { return { errors: [ { text: 'WASM/ES module integration imports are not supported with Zone.js applications', notes: [ { text: 'Information about zoneless Angular applications can be found here: https://angular.dev/guide/experimental/zoneless', }, ], }, ], }; } const wasmContents = await readFile(args.path); // Inline WASM code less than 10kB const inlineWasm = wasmContents.byteLength < 10_000; // Add import of WASM contents let initContents = `import ${inlineWasm ? 'wasmData' : 'wasmPath'} from ${JSON.stringify(basename(args.path))}`; initContents += inlineWasm ? ' with { loader: "binary" };' : ';\n\n'; // Read from the file system when on Node.js (SSR) and not inline if (!inlineWasm && build.initialOptions.platform === 'node') { initContents += 'import { readFile } from "node:fs/promises";\n'; initContents += 'const wasmData = await readFile(new URL(wasmPath, import.meta.url));\n'; } // Create initialization function initContents += generateInitHelper( !inlineWasm && build.initialOptions.platform !== 'node', wasmContents, ); // Analyze WASM for imports and exports let importModuleNames, exportNames; try { const wasm = await WebAssembly.compile(wasmContents); importModuleNames = new Set( WebAssembly.Module.imports(wasm).map((value) => value.module), ); exportNames = WebAssembly.Module.exports(wasm).map((value) => value.name); } catch (error) { assertIsError(error); return { errors: [{ text: 'Unable to analyze WASM file', notes: [{ text: error.message }] }], }; } // Ensure export names are valid JavaScript identifiers const invalidExportNames = exportNames.filter( (name) => !ecmaIdentifierNameRegExp.test(name), ); if (invalidExportNames.length > 0) { return { errors: invalidExportNames.map((name) => ({ text: 'WASM export names must be valid JavaScript identifiers', notes: [ { text: `The export "${name}" is not valid. The WASM file should be updated to remove this error.`, }, ], })), }; } // Add import statements and setup import object initContents += 'const importObject = Object.create(null);\n'; let importIndex = 0; for (const moduleName of importModuleNames) { // Add a namespace import for each module name initContents += `import * as wasm_import_${++importIndex} from ${JSON.stringify(moduleName)};\n`; // Add the namespace object to the import object initContents += `importObject[${JSON.stringify(moduleName)}] = wasm_import_${importIndex};\n`; } // Instantiate the module initContents += 'const instance = await init(importObject);\n'; // Add exports const exportNameList = exportNames.join(', '); initContents += `const { ${exportNameList} } = instance.exports;\n`; initContents += `export { ${exportNameList} }\n`; return { contents: initContents, loader: 'js', resolveDir: dirname(args.path), pluginData: { wasmContents }, watchFiles: [args.path], }; }), ); build.onLoad({ filter: /\.wasm$/, namespace: WASM_CONTENTS_NAMESPACE }, async (args) => { const contents = args.pluginData.wasmContents ?? (await readFile(args.path)); let loader: 'binary' | 'file' = 'file'; if (args.with.loader) { assert( args.with.loader === 'binary' || args.with.loader === 'file', 'WASM loader type should only be binary or file.', ); loader = args.with.loader; } return { contents, loader, watchFiles: [args.path], }; }); }, }; } /** * Generates the string content of the WASM initialization helper function. * This function supports both file fetching and inline byte data depending on * the preferred option for the WASM file. When fetching, an integrity hash is * also generated and used with the fetch action. * * @param streaming Uses fetch and WebAssembly.instantiateStreaming. * @param wasmContents The binary contents to generate an integrity hash. * @returns A string containing the initialization function. */
{ "end_byte": 8736, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/wasm-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/wasm-plugin.ts_8737_9508
function generateInitHelper(streaming: boolean, wasmContents: Uint8Array) { let resultContents; if (streaming) { const fetchOptions = { integrity: 'sha256-' + createHash('sha-256').update(wasmContents).digest('base64'), }; const fetchContents = `fetch(new URL(wasmPath, import.meta.url), ${JSON.stringify(fetchOptions)})`; resultContents = `await WebAssembly.instantiateStreaming(${fetchContents}, imports)`; } else { resultContents = 'await WebAssembly.instantiate(wasmData, imports)'; } const contents = ` let mod; async function init(imports) { if (mod) { return await WebAssembly.instantiate(mod, imports); } const result = ${resultContents}; mod = result.module; return result.instance; } `; return contents; }
{ "end_byte": 9508, "start_byte": 8737, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/wasm-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts_0_5611
/** * @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 { BuildFailure, Loader, Metafile, OnStartResult, OutputFile, PartialMessage, Plugin, PluginBuild, } from 'esbuild'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; import * as path from 'node:path'; import { maxWorkers, useTypeChecking } from '../../../utils/environment-options'; import { AngularHostOptions } from '../../angular/angular-host'; import { AngularCompilation, DiagnosticModes, NoopCompilation, createAngularCompilation, } from '../../angular/compilation'; import { JavaScriptTransformer } from '../javascript-transformer'; import { LoadResultCache, createCachedLoad } from '../load-result-cache'; import { logCumulativeDurations, profileAsync, resetCumulativeDurations } from '../profiling'; import { SharedTSCompilationState, getSharedCompilationState } from './compilation-state'; import { ComponentStylesheetBundler } from './component-stylesheets'; import { FileReferenceTracker } from './file-reference-tracker'; import { setupJitPluginCallbacks } from './jit-plugin-callbacks'; import { SourceFileCache } from './source-file-cache'; export interface CompilerPluginOptions { sourcemap: boolean | 'external'; tsconfig: string; jit?: boolean; /** Skip TypeScript compilation setup. This is useful to re-use the TypeScript compilation from another plugin. */ noopTypeScriptCompilation?: boolean; advancedOptimizations?: boolean; thirdPartySourcemaps?: boolean; fileReplacements?: Record<string, string>; sourceFileCache?: SourceFileCache; loadResultCache?: LoadResultCache; incremental: boolean; externalRuntimeStyles?: boolean; instrumentForCoverage?: (request: string) => boolean; } // eslint-disable-next-line max-lines-per-function export function createCompilerPlugin( pluginOptions: CompilerPluginOptions, stylesheetBundler: ComponentStylesheetBundler, ): Plugin { return { name: 'angular-compiler', // eslint-disable-next-line max-lines-per-function async setup(build: PluginBuild): Promise<void> { let setupWarnings: PartialMessage[] | undefined = []; const preserveSymlinks = build.initialOptions.preserveSymlinks; // Initialize a worker pool for JavaScript transformations. // Webcontainers currently do not support this persistent cache store. let cacheStore: import('../lmdb-cache-store').LmbdCacheStore | undefined; if (pluginOptions.sourceFileCache?.persistentCachePath && !process.versions.webcontainer) { try { const { LmbdCacheStore } = await import('../lmdb-cache-store'); cacheStore = new LmbdCacheStore( path.join(pluginOptions.sourceFileCache.persistentCachePath, 'angular-compiler.db'), ); } catch (e) { setupWarnings.push({ text: 'Unable to initialize JavaScript cache storage.', location: null, notes: [ // Only show first line of lmdb load error which has platform support listed { text: (e as Error)?.message.split('\n')[0] ?? `${e}` }, { text: 'This will not affect the build output content but may result in slower builds.', }, ], }); } } const javascriptTransformer = new JavaScriptTransformer( { sourcemap: !!pluginOptions.sourcemap, thirdPartySourcemaps: pluginOptions.thirdPartySourcemaps, advancedOptimizations: pluginOptions.advancedOptimizations, jit: pluginOptions.jit, }, maxWorkers, cacheStore?.createCache('jstransformer'), ); // Setup defines based on the values used by the Angular compiler-cli build.initialOptions.define ??= {}; build.initialOptions.define['ngI18nClosureMode'] ??= 'false'; // The in-memory cache of TypeScript file outputs will be used during the build in `onLoad` callbacks for TS files. // A string value indicates direct TS/NG output and a Uint8Array indicates fully transformed code. const typeScriptFileCache = pluginOptions.sourceFileCache?.typeScriptFileCache ?? new Map<string, string | Uint8Array>(); // The resources from component stylesheets and web workers that will be added to the build results output files const additionalResults = new Map< string, { outputFiles?: OutputFile[]; metafile?: Metafile; errors?: PartialMessage[] } >(); // Create new reusable compilation for the appropriate mode based on the `jit` plugin option const compilation: AngularCompilation = pluginOptions.noopTypeScriptCompilation ? new NoopCompilation() : await createAngularCompilation(!!pluginOptions.jit); // Compilation is initially assumed to have errors until emitted let hasCompilationErrors = true; // Determines if TypeScript should process JavaScript files based on tsconfig `allowJs` option let shouldTsIgnoreJs = true; // Determines if transpilation should be handle by TypeScript or esbuild let useTypeScriptTranspilation = true; let sharedTSCompilationState: SharedTSCompilationState | undefined; // To fully invalidate files, track resource referenced files and their referencing source const referencedFileTracker = new FileReferenceTracker(); // eslint-disable-next-line max-lines-per-function
{ "end_byte": 5611, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts_5618_16574
build.onStart(async () => { sharedTSCompilationState = getSharedCompilationState(); if (!(compilation instanceof NoopCompilation)) { sharedTSCompilationState.markAsInProgress(); } const result: OnStartResult = { warnings: setupWarnings, }; // Reset debug performance tracking resetCumulativeDurations(); // Update the reference tracker and generate a full set of modified files for the // Angular compiler which does not have direct knowledge of transitive resource // dependencies or web worker processing. let modifiedFiles; let invalidatedStylesheetEntries; if ( pluginOptions.sourceFileCache?.modifiedFiles.size && referencedFileTracker && !pluginOptions.noopTypeScriptCompilation ) { // TODO: Differentiate between changed input files and stale output files modifiedFiles = referencedFileTracker.update(pluginOptions.sourceFileCache.modifiedFiles); pluginOptions.sourceFileCache.invalidate(modifiedFiles); invalidatedStylesheetEntries = stylesheetBundler.invalidate(modifiedFiles); } if ( !pluginOptions.noopTypeScriptCompilation && compilation.update && pluginOptions.sourceFileCache?.modifiedFiles.size ) { await compilation.update(modifiedFiles ?? pluginOptions.sourceFileCache.modifiedFiles); } // Create Angular compiler host options const hostOptions: AngularHostOptions = { fileReplacements: pluginOptions.fileReplacements, modifiedFiles, sourceFileCache: pluginOptions.sourceFileCache, async transformStylesheet(data, containingFile, stylesheetFile, order, className) { let stylesheetResult; // Stylesheet file only exists for external stylesheets if (stylesheetFile) { stylesheetResult = await stylesheetBundler.bundleFile(stylesheetFile); } else { stylesheetResult = await stylesheetBundler.bundleInline( data, containingFile, // Inline stylesheets from a template style element are always CSS; Otherwise, use default. containingFile.endsWith('.html') ? 'css' : undefined, // When external runtime styles are enabled, an identifier for the style that does not change // based on the content is required to avoid emitted JS code changes. Any JS code changes will // invalid the output and force a full page reload for HMR cases. The containing file and order // of the style within the containing file is used. pluginOptions.externalRuntimeStyles ? createHash('sha-256') .update(containingFile) .update((order ?? 0).toString()) .update(className ?? '') .digest('hex') : undefined, ); } const { contents, outputFiles, metafile, referencedFiles, errors, warnings } = stylesheetResult; if (errors) { (result.errors ??= []).push(...errors); } (result.warnings ??= []).push(...warnings); additionalResults.set(stylesheetFile ?? containingFile, { outputFiles, metafile, }); if (referencedFiles) { referencedFileTracker.add(containingFile, referencedFiles); if (stylesheetFile) { // Angular AOT compiler needs modified direct resource files to correctly invalidate its analysis referencedFileTracker.add(stylesheetFile, referencedFiles); } } return contents; }, processWebWorker(workerFile, containingFile) { const fullWorkerPath = path.join(path.dirname(containingFile), workerFile); // The synchronous API must be used due to the TypeScript compilation currently being // fully synchronous and this process callback being called from within a TypeScript // transformer. const workerResult = bundleWebWorker(build, pluginOptions, fullWorkerPath); (result.warnings ??= []).push(...workerResult.warnings); if (workerResult.errors.length > 0) { (result.errors ??= []).push(...workerResult.errors); // Track worker file errors to allow rebuilds on changes referencedFileTracker.add( containingFile, workerResult.errors .map((error) => error.location?.file) .filter((file): file is string => !!file) .map((file) => path.join(build.initialOptions.absWorkingDir ?? '', file)), ); additionalResults.set(fullWorkerPath, { errors: result.errors }); // Return the original path if the build failed return workerFile; } assert('outputFiles' in workerResult, 'Invalid web worker bundle result.'); additionalResults.set(fullWorkerPath, { outputFiles: workerResult.outputFiles, metafile: workerResult.metafile, }); referencedFileTracker.add( containingFile, Object.keys(workerResult.metafile.inputs).map((input) => path.join(build.initialOptions.absWorkingDir ?? '', input), ), ); // Return bundled worker file entry name to be used in the built output const workerCodeFile = workerResult.outputFiles.find((file) => /^worker-[A-Z0-9]{8}.[cm]?js$/.test(path.basename(file.path)), ); assert(workerCodeFile, 'Web Worker bundled code file should always be present.'); const workerCodePath = path.relative( build.initialOptions.outdir ?? '', workerCodeFile.path, ); return workerCodePath.replaceAll('\\', '/'); }, }; // Initialize the Angular compilation for the current build. // In watch mode, previous build state will be reused. let referencedFiles; let externalStylesheets; try { const initializationResult = await compilation.initialize( pluginOptions.tsconfig, hostOptions, createCompilerOptionsTransformer( setupWarnings, pluginOptions, preserveSymlinks, build.initialOptions.conditions, ), ); shouldTsIgnoreJs = !initializationResult.compilerOptions.allowJs; // Isolated modules option ensures safe non-TypeScript transpilation. // Typescript printing support for sourcemaps is not yet integrated. useTypeScriptTranspilation = !initializationResult.compilerOptions.isolatedModules || !!initializationResult.compilerOptions.sourceMap || !!initializationResult.compilerOptions.inlineSourceMap; referencedFiles = initializationResult.referencedFiles; externalStylesheets = initializationResult.externalStylesheets; } catch (error) { (result.errors ??= []).push({ text: 'Angular compilation initialization failed.', location: null, notes: [ { text: error instanceof Error ? (error.stack ?? error.message) : `${error}`, location: null, }, ], }); // Initialization failure prevents further compilation steps hasCompilationErrors = true; return result; } if (compilation instanceof NoopCompilation) { hasCompilationErrors = await sharedTSCompilationState.waitUntilReady; return result; } if (externalStylesheets) { // Process any new external stylesheets for (const [stylesheetFile, externalId] of externalStylesheets) { await bundleExternalStylesheet( stylesheetBundler, stylesheetFile, externalId, result, additionalResults, ); } // Process any updated stylesheets if (invalidatedStylesheetEntries) { for (const stylesheetFile of invalidatedStylesheetEntries) { // externalId is already linked in the bundler context so only enabling is required here await bundleExternalStylesheet( stylesheetBundler, stylesheetFile, true, result, additionalResults, ); } } } // Update TypeScript file output cache for all affected files try { await profileAsync('NG_EMIT_TS', async () => { for (const { filename, contents } of await compilation.emitAffectedFiles()) { typeScriptFileCache.set(path.normalize(filename), contents); } }); } catch (error) { (result.errors ??= []).push({ text: 'Angular compilation emit failed.', location: null, notes: [ { text: error instanceof Error ? (error.stack ?? error.message) : `${error}`, location: null, }, ], }); } const diagnostics = await compilation.diagnoseFiles( useTypeChecking ? DiagnosticModes.All : DiagnosticModes.All & ~DiagnosticModes.Semantic, ); if (diagnostics.errors?.length) { (result.errors ??= []).push(...diagnostics.errors); } if (diagnostics.warnings?.length) { (result.warnings ??= []).push(...diagnostics.warnings); } // Add errors from failed additional results. // This must be done after emit to capture latest web worker results. for (const { errors } of additionalResults.values()) { if (errors) { (result.errors ??= []).push(...errors); } } // Store referenced files for updated file watching if enabled if (pluginOptions.sourceFileCache) { pluginOptions.sourceFileCache.referencedFiles = [ ...referencedFiles, ...referencedFileTracker.referencedFiles, ]; } hasCompilationErrors = !!result.errors?.length; // Reset the setup warnings so that they are only shown during the first build. setupWarnings = undefined; sharedTSCompilationState.markAsReady(hasCompilationErrors); return result; });
{ "end_byte": 16574, "start_byte": 5618, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts_16582_22664
build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => { const request = path.normalize( pluginOptions.fileReplacements?.[path.normalize(args.path)] ?? args.path, ); const isJS = /\.[cm]?js$/.test(request); // Skip TS load attempt if JS TypeScript compilation not enabled and file is JS if (shouldTsIgnoreJs && isJS) { return undefined; } // The filename is currently used as a cache key. Since the cache is memory only, // the options cannot change and do not need to be represented in the key. If the // cache is later stored to disk, then the options that affect transform output // would need to be added to the key as well as a check for any change of content. let contents = typeScriptFileCache.get(request); if (contents === undefined) { // If the Angular compilation had errors the file may not have been emitted. // To avoid additional errors about missing files, return empty contents. if (hasCompilationErrors) { return { contents: '', loader: 'js' }; } // No TS result indicates the file is not part of the TypeScript program. // If allowJs is enabled and the file is JS then defer to the next load hook. if (!shouldTsIgnoreJs && isJS) { return undefined; } // Otherwise return an error return { errors: [ createMissingFileError(request, args.path, build.initialOptions.absWorkingDir ?? ''), ], }; } else if (typeof contents === 'string' && (useTypeScriptTranspilation || isJS)) { // A string indicates untransformed output from the TS/NG compiler. // This step is unneeded when using esbuild transpilation. const sideEffects = await hasSideEffects(request); const instrumentForCoverage = pluginOptions.instrumentForCoverage?.(request); contents = await javascriptTransformer.transformData( request, contents, true /* skipLinker */, sideEffects, instrumentForCoverage, ); // Store as the returned Uint8Array to allow caching the fully transformed code typeScriptFileCache.set(request, contents); } let loader: Loader; if (useTypeScriptTranspilation || isJS) { // TypeScript has transpiled to JS or is already JS loader = 'js'; } else if (request.at(-1) === 'x') { // TSX and TS have different syntax rules. Only set if input is a TSX file. loader = 'tsx'; } else { // Otherwise, directly bundle TS loader = 'ts'; } return { contents, loader, }; }); build.onLoad( { filter: /\.[cm]?js$/ }, createCachedLoad(pluginOptions.loadResultCache, async (args) => { return profileAsync( 'NG_EMIT_JS*', async () => { const sideEffects = await hasSideEffects(args.path); const contents = await javascriptTransformer.transformFile( args.path, pluginOptions.jit, sideEffects, ); return { contents, loader: 'js', }; }, true, ); }), ); // Setup bundling of component templates and stylesheets when in JIT mode if (pluginOptions.jit) { setupJitPluginCallbacks( build, stylesheetBundler, additionalResults, pluginOptions.loadResultCache, ); } build.onEnd((result) => { // Ensure other compilations are unblocked if the main compilation throws during start sharedTSCompilationState?.markAsReady(hasCompilationErrors); for (const { outputFiles, metafile } of additionalResults.values()) { // Add any additional output files to the main output files if (outputFiles?.length) { result.outputFiles?.push(...outputFiles); } // Combine additional metafiles with main metafile if (result.metafile && metafile) { // Append the existing object, by appending to it we prevent unnecessary new objections creations with spread // mitigating significant performance overhead for large apps. // See: https://bugs.chromium.org/p/v8/issues/detail?id=11536 Object.assign(result.metafile.inputs, metafile.inputs); Object.assign(result.metafile.outputs, metafile.outputs); } } logCumulativeDurations(); }); build.onDispose(() => { sharedTSCompilationState?.dispose(); void compilation.close?.(); void cacheStore?.close(); }); /** * Checks if the file has side-effects when `advancedOptimizations` is enabled. */ async function hasSideEffects(path: string): Promise<boolean | undefined> { if (!pluginOptions.advancedOptimizations) { return undefined; } const { sideEffects } = await build.resolve(path, { kind: 'import-statement', resolveDir: build.initialOptions.absWorkingDir ?? '', }); return sideEffects; } }, }; } async function bundleExternalStylesheet( stylesheetBundler: ComponentStylesheetBundler, stylesheetFile: string, externalId: string | boolean, result: OnStartResult, additionalResults: Map< string, { outputFiles?: OutputFile[]; metafile?: Metafile; errors?: PartialMessage[] } >, ) { const { outputFiles, metafile, errors, warnings } = await stylesheetBundler.bundleFile( stylesheetFile, externalId, ); if (errors) { (result.errors ??= []).push(...errors); } (result.warnings ??= []).push(...warnings); additionalResults.set(stylesheetFile, { outputFiles, metafile, }); }
{ "end_byte": 22664, "start_byte": 16582, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts_22666_27552
function createCompilerOptionsTransformer( setupWarnings: PartialMessage[] | undefined, pluginOptions: CompilerPluginOptions, preserveSymlinks: boolean | undefined, customConditions: string[] | undefined, ): Parameters<AngularCompilation['initialize']>[2] { return (compilerOptions) => { // target of 9 is ES2022 (using the number avoids an expensive import of typescript just for an enum) if (compilerOptions.target === undefined || compilerOptions.target < 9 /** ES2022 */) { // If 'useDefineForClassFields' is already defined in the users project leave the value as is. // Otherwise fallback to false due to https://github.com/microsoft/TypeScript/issues/45995 // which breaks the deprecated `@Effects` NGRX decorator and potentially other existing code as well. compilerOptions.target = 9 /** ES2022 */; compilerOptions.useDefineForClassFields ??= false; // Only add the warning on the initial build setupWarnings?.push({ text: `TypeScript compiler options 'target' and 'useDefineForClassFields' are set to 'ES2022' and ` + `'false' respectively by the Angular CLI.`, location: { file: pluginOptions.tsconfig }, notes: [ { text: 'To control ECMA version and features use the Browserslist configuration. ' + 'For more information, see https://angular.dev/tools/cli/build#configuring-browser-compatibility', }, ], }); } if (compilerOptions.compilationMode === 'partial') { setupWarnings?.push({ text: 'Angular partial compilation mode is not supported when building applications.', location: null, notes: [{ text: 'Full compilation mode will be used instead.' }], }); compilerOptions.compilationMode = 'full'; } // Enable incremental compilation by default if caching is enabled and incremental is not explicitly disabled if ( compilerOptions.incremental !== false && pluginOptions.sourceFileCache?.persistentCachePath ) { compilerOptions.incremental = true; // Set the build info file location to the configured cache directory compilerOptions.tsBuildInfoFile = path.join( pluginOptions.sourceFileCache?.persistentCachePath, '.tsbuildinfo', ); } else { compilerOptions.incremental = false; } if (compilerOptions.module === undefined || compilerOptions.module < 5 /** ES2015 */) { compilerOptions.module = 7; /** ES2022 */ setupWarnings?.push({ text: `TypeScript compiler options 'module' values 'CommonJS', 'UMD', 'System' and 'AMD' are not supported.`, location: null, notes: [{ text: `The 'module' option will be set to 'ES2022' instead.` }], }); } // Synchronize custom resolve conditions. // Set if using the supported bundler resolution mode (bundler is the default in new projects) if (compilerOptions.moduleResolution === 100 /* ModuleResolutionKind.Bundler */) { compilerOptions.customConditions = customConditions; } return { ...compilerOptions, noEmitOnError: false, inlineSources: !!pluginOptions.sourcemap, inlineSourceMap: !!pluginOptions.sourcemap, sourceMap: undefined, mapRoot: undefined, sourceRoot: undefined, preserveSymlinks, externalRuntimeStyles: pluginOptions.externalRuntimeStyles, }; }; } function bundleWebWorker( build: PluginBuild, pluginOptions: CompilerPluginOptions, workerFile: string, ) { try { return build.esbuild.buildSync({ ...build.initialOptions, platform: 'browser', write: false, bundle: true, metafile: true, format: 'esm', entryNames: 'worker-[hash]', entryPoints: [workerFile], sourcemap: pluginOptions.sourcemap, // Zone.js is not used in Web workers so no need to disable supported: undefined, // Plugins are not supported in sync esbuild calls plugins: undefined, }); } catch (error) { if (error && typeof error === 'object' && 'errors' in error && 'warnings' in error) { return error as BuildFailure; } throw error; } } function createMissingFileError(request: string, original: string, root: string): PartialMessage { const relativeRequest = path.relative(root, request); const error = { text: `File '${relativeRequest}' is missing from the TypeScript compilation.`, notes: [ { text: `Ensure the file is part of the TypeScript program via the 'files' or 'include' property.`, }, ], }; const relativeOriginal = path.relative(root, original); if (relativeRequest !== relativeOriginal) { error.notes.push({ text: `File is requested from a file replacement of '${relativeOriginal}'.`, }); } return error; }
{ "end_byte": 27552, "start_byte": 22666, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/compilation-state.ts_0_1332
/** * @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 class SharedTSCompilationState { #pendingCompilation = true; #resolveCompilationReady: ((value: boolean) => void) | undefined; #compilationReadyPromise: Promise<boolean> | undefined; #hasErrors = true; get waitUntilReady(): Promise<boolean> { if (!this.#pendingCompilation) { return Promise.resolve(this.#hasErrors); } this.#compilationReadyPromise ??= new Promise((resolve) => { this.#resolveCompilationReady = resolve; }); return this.#compilationReadyPromise; } markAsReady(hasErrors: boolean): void { this.#hasErrors = hasErrors; this.#resolveCompilationReady?.(hasErrors); this.#compilationReadyPromise = undefined; this.#pendingCompilation = false; } markAsInProgress(): void { this.#pendingCompilation = true; } dispose(): void { this.markAsReady(true); globalSharedCompilationState = undefined; } } let globalSharedCompilationState: SharedTSCompilationState | undefined; export function getSharedCompilationState(): SharedTSCompilationState { return (globalSharedCompilationState ??= new SharedTSCompilationState()); }
{ "end_byte": 1332, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/compilation-state.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/jit-plugin-callbacks.ts_0_5492
/** * @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 { Metafile, OutputFile, PluginBuild } from 'esbuild'; import { readFile } from 'node:fs/promises'; import { dirname, join, relative } from 'node:path'; import { JIT_NAMESPACE_REGEXP, JIT_STYLE_NAMESPACE, JIT_TEMPLATE_NAMESPACE, parseJitUri, } from '../../angular/uri'; import { LoadResultCache, createCachedLoad } from '../load-result-cache'; import { ComponentStylesheetBundler } from './component-stylesheets'; /** * Loads/extracts the contents from a load callback Angular JIT entry. * An Angular JIT entry represents either a file path for a component resource or base64 * encoded data for an inline component resource. * @param entry The value that represents content to load. * @param root The absolute path for the root of the build (typically the workspace root). * @param skipRead If true, do not attempt to read the file; if false, read file content from disk. * This option has no effect if the entry does not originate from a file. Defaults to false. * @returns An object containing the absolute path of the contents and optionally the actual contents. * For inline entries the contents will always be provided. */ async function loadEntry( entry: string, root: string, skipRead?: boolean, ): Promise<{ path: string; contents?: string }> { if (entry.startsWith('file:')) { const specifier = join(root, entry.slice(5)); return { path: specifier, contents: skipRead ? undefined : await readFile(specifier, 'utf-8'), }; } else if (entry.startsWith('inline:')) { const [importer, data] = entry.slice(7).split(';', 2); return { path: join(root, importer), contents: Buffer.from(data, 'base64').toString(), }; } else { throw new Error('Invalid data for Angular JIT entry.'); } } /** * Sets up esbuild resolve and load callbacks to support Angular JIT mode processing * for both Component stylesheets and templates. These callbacks work alongside the JIT * resource TypeScript transformer to convert and then bundle Component resources as * static imports. * @param build An esbuild {@link PluginBuild} instance used to add callbacks. * @param styleOptions The options to use when bundling stylesheets. * @param additionalResultFiles A Map where stylesheet resources will be added. */ export function setupJitPluginCallbacks( build: PluginBuild, stylesheetBundler: ComponentStylesheetBundler, additionalResultFiles: Map<string, { outputFiles?: OutputFile[]; metafile?: Metafile }>, loadCache?: LoadResultCache, ): void { const root = build.initialOptions.absWorkingDir ?? ''; // Add a resolve callback to capture and parse any JIT URIs that were added by the // JIT resource TypeScript transformer. // Resources originating from a file are resolved as relative from the containing file (importer). build.onResolve({ filter: JIT_NAMESPACE_REGEXP }, (args) => { const parsed = parseJitUri(args.path); if (!parsed) { return undefined; } const { namespace, origin, specifier } = parsed; if (origin === 'file') { return { // Use a relative path to prevent fully resolved paths in the metafile (JSON stats file). // This is only necessary for custom namespaces. esbuild will handle the file namespace. path: 'file:' + relative(root, join(dirname(args.importer), specifier)), namespace, }; } else { // Inline data may need the importer to resolve imports/references within the content const importer = relative(root, args.importer); return { path: `inline:${importer};${specifier}`, namespace, }; } }); // Add a load callback to handle Component stylesheets (both inline and external) build.onLoad( { filter: /./, namespace: JIT_STYLE_NAMESPACE }, createCachedLoad(loadCache, async (args) => { // skipRead is used here because the stylesheet bundling will read a file stylesheet // directly either via a preprocessor or esbuild itself. const entry = await loadEntry(args.path, root, true /* skipRead */); let stylesheetResult; // Stylesheet contents only exist for internal stylesheets if (entry.contents === undefined) { stylesheetResult = await stylesheetBundler.bundleFile(entry.path); } else { stylesheetResult = await stylesheetBundler.bundleInline(entry.contents, entry.path); } const { contents, outputFiles, errors, warnings, metafile, referencedFiles } = stylesheetResult; additionalResultFiles.set(entry.path, { outputFiles, metafile }); return { errors, warnings, contents, loader: 'text', watchFiles: referencedFiles && [...referencedFiles], }; }), ); // Add a load callback to handle Component templates // NOTE: While this callback supports both inline and external templates, the transformer // currently only supports generating URIs for external templates. build.onLoad( { filter: /./, namespace: JIT_TEMPLATE_NAMESPACE }, createCachedLoad(loadCache, async (args) => { const { contents, path } = await loadEntry(args.path, root); return { contents, loader: 'text', watchFiles: [path], }; }), ); }
{ "end_byte": 5492, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/jit-plugin-callbacks.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/source-file-cache.ts_0_1324
/** * @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 { platform } from 'node:os'; import * as path from 'node:path'; import type ts from 'typescript'; import { MemoryLoadResultCache } from '../load-result-cache'; const USING_WINDOWS = platform() === 'win32'; const WINDOWS_SEP_REGEXP = new RegExp(`\\${path.win32.sep}`, 'g'); export class SourceFileCache extends Map<string, ts.SourceFile> { readonly modifiedFiles = new Set<string>(); readonly typeScriptFileCache = new Map<string, string | Uint8Array>(); readonly loadResultCache = new MemoryLoadResultCache(); referencedFiles?: readonly string[]; constructor(readonly persistentCachePath?: string) { super(); } invalidate(files: Iterable<string>): void { if (files !== this.modifiedFiles) { this.modifiedFiles.clear(); } for (let file of files) { file = path.normalize(file); this.loadResultCache.invalidate(file); // Normalize separators to allow matching TypeScript Host paths if (USING_WINDOWS) { file = file.replace(WINDOWS_SEP_REGEXP, path.posix.sep); } this.delete(file); this.modifiedFiles.add(file); } } }
{ "end_byte": 1324, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/source-file-cache.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/diagnostics.ts_0_3264
/** * @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 { PartialMessage, PartialNote } from 'esbuild'; import { platform } from 'node:os'; import type ts from 'typescript'; /** * Converts TypeScript Diagnostic related information into an esbuild compatible note object. * Related information is a subset of a full TypeScript Diagnostic and also used for diagnostic * notes associated with the main Diagnostic. * @param info The TypeScript diagnostic relative information to convert. * @returns An esbuild diagnostic message as a PartialMessage object */ function convertTypeScriptDiagnosticInfo( typescript: typeof ts, info: ts.DiagnosticRelatedInformation, textPrefix?: string, ): PartialNote { const newLine = platform() === 'win32' ? '\r\n' : '\n'; let text = typescript.flattenDiagnosticMessageText(info.messageText, newLine); if (textPrefix) { text = textPrefix + text; } const note: PartialNote = { text }; if (info.file) { note.location = { file: info.file.fileName, length: info.length, }; // Calculate the line/column location and extract the full line text that has the diagnostic if (info.start) { const { line, character } = typescript.getLineAndCharacterOfPosition(info.file, info.start); note.location.line = line + 1; note.location.column = character; // The start position for the slice is the first character of the error line const lineStartPosition = typescript.getPositionOfLineAndCharacter(info.file, line, 0); // The end position for the slice is the first character of the next line or the length of // the entire file if the line is the last line of the file (getPositionOfLineAndCharacter // will error if a nonexistent line is passed). const { line: lastLineOfFile } = typescript.getLineAndCharacterOfPosition( info.file, info.file.text.length - 1, ); const lineEndPosition = line < lastLineOfFile ? typescript.getPositionOfLineAndCharacter(info.file, line + 1, 0) : info.file.text.length; note.location.lineText = info.file.text.slice(lineStartPosition, lineEndPosition).trimEnd(); } } return note; } /** * Converts a TypeScript Diagnostic message into an esbuild compatible message object. * @param diagnostic The TypeScript diagnostic to convert. * @returns An esbuild diagnostic message as a PartialMessage object */ export function convertTypeScriptDiagnostic( typescript: typeof ts, diagnostic: ts.Diagnostic, ): PartialMessage { let codePrefix = 'TS'; let code = `${diagnostic.code}`; if (diagnostic.source === 'ngtsc') { codePrefix = 'NG'; // Remove `-99` Angular prefix from diagnostic code code = code.slice(3); } const message: PartialMessage = convertTypeScriptDiagnosticInfo( typescript, diagnostic, `${codePrefix}${code}: `, ); if (diagnostic.relatedInformation?.length) { message.notes = diagnostic.relatedInformation.map((info) => convertTypeScriptDiagnosticInfo(typescript, info), ); } return message; }
{ "end_byte": 3264, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/diagnostics.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/file-reference-tracker.ts_0_2016
/** * @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 { normalize } from 'node:path'; export class FileReferenceTracker { #referencingFiles = new Map<string, Set<string>>(); get referencedFiles() { return this.#referencingFiles.keys(); } add(containingFile: string, referencedFiles: Iterable<string>): void { const normalizedContainingFile = normalize(containingFile); for (const file of referencedFiles) { const normalizedReferencedFile = normalize(file); if (normalizedReferencedFile === normalizedContainingFile) { // Containing file is already known to the AOT compiler continue; } const referencing = this.#referencingFiles.get(normalizedReferencedFile); if (referencing === undefined) { this.#referencingFiles.set(normalizedReferencedFile, new Set([normalizedContainingFile])); } else { referencing.add(normalizedContainingFile); } } } /** * * @param changed The set of changed files. */ update(changed: Set<string>): Set<string> { // Lazily initialized to avoid unneeded copying if there are no additions to return let allChangedFiles: Set<string> | undefined; // Add referencing files to fully notify the AOT compiler of required component updates for (const modifiedFile of changed) { const normalizedModifiedFile = normalize(modifiedFile); const referencing = this.#referencingFiles.get(normalizedModifiedFile); if (referencing) { allChangedFiles ??= new Set(changed); for (const referencingFile of referencing) { allChangedFiles.add(referencingFile); } // Cleanup the stale record which will be updated by new resource transforms this.#referencingFiles.delete(normalizedModifiedFile); } } return allChangedFiles ?? changed; } }
{ "end_byte": 2016, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/file-reference-tracker.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts_0_7841
/** * @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 { OutputFile } from 'esbuild'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; import path from 'node:path'; import { BuildOutputFileType, BundleContextResult, BundlerContext } from '../bundler-context'; import { MemoryCache } from '../cache'; import { BundleStylesheetOptions, createStylesheetBundleOptions, } from '../stylesheets/bundle-options'; /** * Bundles component stylesheets. A stylesheet can be either an inline stylesheet that * is contained within the Component's metadata definition or an external file referenced * from the Component's metadata definition. */ export class ComponentStylesheetBundler { readonly #fileContexts = new MemoryCache<BundlerContext>(); readonly #inlineContexts = new MemoryCache<BundlerContext>(); /** * * @param options An object containing the stylesheet bundling options. * @param cache A load result cache to use when bundling. */ constructor( private readonly options: BundleStylesheetOptions, private readonly defaultInlineLanguage: string, private readonly incremental: boolean, ) {} async bundleFile(entry: string, externalId?: string | boolean) { const bundlerContext = await this.#fileContexts.getOrCreate(entry, () => { return new BundlerContext(this.options.workspaceRoot, this.incremental, (loadCache) => { const buildOptions = createStylesheetBundleOptions(this.options, loadCache); if (externalId) { assert( typeof externalId === 'string', 'Initial external component stylesheets must have a string identifier', ); buildOptions.entryPoints = { [externalId]: entry }; buildOptions.entryNames = '[name]'; delete buildOptions.publicPath; } else { buildOptions.entryPoints = [entry]; } return buildOptions; }); }); return this.extractResult( await bundlerContext.bundle(), bundlerContext.watchFiles, !!externalId, ); } async bundleInline( data: string, filename: string, language = this.defaultInlineLanguage, externalId?: string, ) { // Use a hash of the inline stylesheet content to ensure a consistent identifier. External stylesheets will resolve // to the actual stylesheet file path. // TODO: Consider xxhash instead for hashing const id = createHash('sha256') .update(data) .update(externalId ?? '') .digest('hex'); const entry = [language, id, filename].join(';'); const bundlerContext = await this.#inlineContexts.getOrCreate(entry, () => { const namespace = 'angular:styles/component'; return new BundlerContext(this.options.workspaceRoot, this.incremental, (loadCache) => { const buildOptions = createStylesheetBundleOptions(this.options, loadCache, { [entry]: data, }); if (externalId) { buildOptions.entryPoints = { [externalId]: `${namespace};${entry}` }; buildOptions.entryNames = '[name]'; delete buildOptions.publicPath; } else { buildOptions.entryPoints = [`${namespace};${entry}`]; } buildOptions.plugins.push({ name: 'angular-component-styles', setup(build) { build.onResolve({ filter: /^angular:styles\/component;/ }, (args) => { if (args.kind !== 'entry-point') { return null; } return { path: entry, namespace, }; }); build.onLoad({ filter: /^css;/, namespace }, () => { return { contents: data, loader: 'css', resolveDir: path.dirname(filename), }; }); }, }); return buildOptions; }); }); // Extract the result of the bundling from the output files return this.extractResult( await bundlerContext.bundle(), bundlerContext.watchFiles, !!externalId, ); } /** * Invalidates both file and inline based component style bundling state for a set of modified files. * @param files The group of files that have been modified * @returns An array of file based stylesheet entries if any were invalidated; otherwise, undefined. */ invalidate(files: Iterable<string>): string[] | undefined { if (!this.incremental) { return; } const normalizedFiles = [...files].map(path.normalize); let entries: string[] | undefined; for (const [entry, bundler] of this.#fileContexts.entries()) { if (bundler.invalidate(normalizedFiles)) { entries ??= []; entries.push(entry); } } for (const bundler of this.#inlineContexts.values()) { bundler.invalidate(normalizedFiles); } return entries; } async dispose(): Promise<void> { const contexts = [...this.#fileContexts.values(), ...this.#inlineContexts.values()]; this.#fileContexts.clear(); this.#inlineContexts.clear(); await Promise.allSettled(contexts.map((context) => context.dispose())); } private extractResult( result: BundleContextResult, referencedFiles: Set<string> | undefined, external: boolean, ) { let contents = ''; let metafile; const outputFiles: OutputFile[] = []; if (!result.errors) { for (const outputFile of result.outputFiles) { const filename = path.basename(outputFile.path); if (outputFile.type === BuildOutputFileType.Media || filename.endsWith('.css.map')) { // The output files could also contain resources (images/fonts/etc.) that were referenced and the map files. // Clone the output file to avoid amending the original path which would causes problems during rebuild. const clonedOutputFile = outputFile.clone(); // Needed for Bazel as otherwise the files will not be written in the correct place, // this is because esbuild will resolve the output file from the outdir which is currently set to `workspaceRoot` twice, // once in the stylesheet and the other in the application code bundler. // Ex: `../../../../../app.component.css.map`. clonedOutputFile.path = path.join(this.options.workspaceRoot, outputFile.path); outputFiles.push(clonedOutputFile); } else if (filename.endsWith('.css')) { if (external) { const clonedOutputFile = outputFile.clone(); clonedOutputFile.path = path.join(this.options.workspaceRoot, outputFile.path); outputFiles.push(clonedOutputFile); contents = path.posix.join(this.options.publicPath ?? '', filename); } else { contents = outputFile.text; } } else { throw new Error( `Unexpected non CSS/Media file "${filename}" outputted during component stylesheet processing.`, ); } } metafile = result.metafile; // Remove entryPoint fields from outputs to prevent the internal component styles from being // treated as initial files. Also mark the entry as a component resource for stat reporting. Object.values(metafile.outputs).forEach((output) => { delete output.entryPoint; // eslint-disable-next-line @typescript-eslint/no-explicit-any (output as any)['ng-component'] = true; }); } return { errors: result.errors, warnings: result.warnings, contents, outputFiles, metafile, referencedFiles, }; } }
{ "end_byte": 7841, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts_0_3387
/** * @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 { BuildOptions, Plugin } from 'esbuild'; import path from 'node:path'; import { NormalizedCachedOptions } from '../../../utils/normalize-cache'; import { PostcssConfiguration } from '../../../utils/postcss-configuration'; import { LoadResultCache } from '../load-result-cache'; import { createCssInlineFontsPlugin } from './css-inline-fonts-plugin'; import { CssStylesheetLanguage } from './css-language'; import { createCssResourcePlugin } from './css-resource-plugin'; import { LessStylesheetLanguage } from './less-language'; import { SassStylesheetLanguage } from './sass-language'; import { StylesheetPluginFactory, StylesheetPluginsass } from './stylesheet-plugin-factory'; export interface BundleStylesheetOptions { workspaceRoot: string; optimization: boolean; inlineFonts: boolean; preserveSymlinks?: boolean; sourcemap: boolean | 'external' | 'inline' | 'linked'; outputNames: { bundles: string; media: string }; includePaths?: string[]; sass?: StylesheetPluginsass; externalDependencies?: string[]; target: string[]; tailwindConfiguration?: { file: string; package: string }; postcssConfiguration?: PostcssConfiguration; publicPath?: string; cacheOptions: NormalizedCachedOptions; } export function createStylesheetBundleOptions( options: BundleStylesheetOptions, cache?: LoadResultCache, inlineComponentData?: Record<string, string>, ): BuildOptions & { plugins: NonNullable<BuildOptions['plugins']> } { // Ensure preprocessor include paths are absolute based on the workspace root const includePaths = options.includePaths?.map((includePath) => path.resolve(options.workspaceRoot, includePath), ); const pluginFactory = new StylesheetPluginFactory( { sourcemap: !!options.sourcemap, includePaths, inlineComponentData, tailwindConfiguration: options.tailwindConfiguration, postcssConfiguration: options.postcssConfiguration, sass: options.sass, }, cache, ); const plugins: Plugin[] = [ pluginFactory.create(SassStylesheetLanguage), pluginFactory.create(LessStylesheetLanguage), pluginFactory.create(CssStylesheetLanguage), createCssResourcePlugin(cache), ]; if (options.inlineFonts) { plugins.unshift(createCssInlineFontsPlugin({ cache, cacheOptions: options.cacheOptions })); } return { absWorkingDir: options.workspaceRoot, bundle: true, entryNames: options.outputNames.bundles, assetNames: options.outputNames.media, logLevel: 'silent', minify: options.optimization, metafile: true, sourcemap: options.sourcemap, outdir: options.workspaceRoot, write: false, platform: 'browser', target: options.target, preserveSymlinks: options.preserveSymlinks, external: options.externalDependencies, publicPath: options.publicPath, conditions: ['style', 'sass', 'less', options.optimization ? 'production' : 'development'], mainFields: ['style', 'sass'], // Unlike JS, CSS does not have implicit file extensions in the general case. // Preprocessor specific behavior is handled in each stylesheet language plugin. resolveExtensions: [], plugins, }; }
{ "end_byte": 3387, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/sass-language.ts_0_8386
/** * @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 { OnLoadResult, PartialMessage, PartialNote, ResolveResult } from 'esbuild'; import { dirname, join, relative } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type { CanonicalizeContext, CompileResult, Exception, Syntax } from 'sass'; import type { SassWorkerImplementation } from '../../sass/sass-service'; import { MemoryCache } from '../cache'; import { StylesheetLanguage, StylesheetPluginOptions } from './stylesheet-plugin-factory'; let sassWorkerPool: SassWorkerImplementation | undefined; let sassWorkerPoolPromise: Promise<SassWorkerImplementation> | undefined; function isSassException(error: unknown): error is Exception { return !!error && typeof error === 'object' && 'sassMessage' in error; } export function shutdownSassWorkerPool(): void { if (sassWorkerPool) { void sassWorkerPool.close(); sassWorkerPool = undefined; } else if (sassWorkerPoolPromise) { void sassWorkerPoolPromise.then(shutdownSassWorkerPool); } sassWorkerPoolPromise = undefined; } export const SassStylesheetLanguage = Object.freeze<StylesheetLanguage>({ name: 'sass', componentFilter: /^s[ac]ss;/, fileFilter: /\.s[ac]ss$/, process(data, file, format, options, build) { const syntax = format === 'sass' ? 'indented' : 'scss'; const resolveUrl = async (url: string, options: CanonicalizeContext) => { let resolveDir = build.initialOptions.absWorkingDir; if (options.containingUrl) { resolveDir = dirname(fileURLToPath(options.containingUrl)); } const result = await build.resolve(url, { kind: 'import-rule', resolveDir, }); return result; }; return compileString(data, file, syntax, options, resolveUrl); }, }); function parsePackageName(url: string): { packageName: string; readonly pathSegments: string[] } { const parts = url.split('/'); const hasScope = parts.length >= 2 && parts[0].startsWith('@'); const [nameOrScope, nameOrFirstPath, ...pathPart] = parts; const packageName = hasScope ? `${nameOrScope}/${nameOrFirstPath}` : nameOrScope; return { packageName, get pathSegments() { return !hasScope && nameOrFirstPath ? [nameOrFirstPath, ...pathPart] : pathPart; }, }; } async function compileString( data: string, filePath: string, syntax: Syntax, options: StylesheetPluginOptions, resolveUrl: (url: string, options: CanonicalizeContext) => Promise<ResolveResult>, ): Promise<OnLoadResult> { // Lazily load Sass when a Sass file is found if (sassWorkerPool === undefined) { if (sassWorkerPoolPromise === undefined) { sassWorkerPoolPromise = import('../../sass/sass-service').then( (sassService) => new sassService.SassWorkerImplementation(true), ); } sassWorkerPool = await sassWorkerPoolPromise; } // Cache is currently local to individual compile requests. // Caching follows Sass behavior where a given url will always resolve to the same value // regardless of its importer's path. // A null value indicates that the cached resolution attempt failed to find a location and // later stage resolution should be attempted. This avoids potentially expensive repeat // failing resolution attempts. const resolutionCache = new MemoryCache<URL | null>(); const packageRootCache = new MemoryCache<string | null>(); const warnings: PartialMessage[] = []; const { silenceDeprecations, futureDeprecations, fatalDeprecations } = options.sass ?? {}; try { const { css, sourceMap, loadedUrls } = await sassWorkerPool.compileStringAsync(data, { url: pathToFileURL(filePath), style: 'expanded', syntax, loadPaths: options.includePaths, sourceMap: options.sourcemap, sourceMapIncludeSources: options.sourcemap, silenceDeprecations, fatalDeprecations, futureDeprecations, quietDeps: true, importers: [ { findFileUrl: (url, options) => resolutionCache.getOrCreate(url, async () => { const result = await resolveUrl(url, options); if (result.path) { return pathToFileURL(result.path); } // Check for package deep imports const { packageName, pathSegments } = parsePackageName(url); // Caching package root locations is particularly beneficial for `@material/*` packages // which extensively use deep imports. const packageRoot = await packageRootCache.getOrCreate(packageName, async () => { // Use the required presence of a package root `package.json` file to resolve the location const packageResult = await resolveUrl(packageName + '/package.json', options); return packageResult.path ? dirname(packageResult.path) : null; }); // Package not found could be because of an error or the specifier is intended to be found // via a later stage of the resolution process (`loadPaths`, etc.). // Errors are reported after the full completion of the resolution process. Exceptions for // not found packages should not be raised here. if (packageRoot) { return pathToFileURL(join(packageRoot, ...pathSegments)); } // Not found return null; }), }, ], logger: { warn: (text, { deprecation, stack, span }) => { const notes: PartialNote[] = []; if (deprecation) { notes.push({ text }); } if (stack && !span) { notes.push({ text: stack }); } warnings.push({ text: deprecation ? 'Deprecation' : text, location: span && { file: span.url && fileURLToPath(span.url), lineText: span.context, // Sass line numbers are 0-based while esbuild's are 1-based line: span.start.line + 1, column: span.start.column, }, notes, }); }, }, }); return { loader: 'css', contents: sourceMap ? `${css}\n${sourceMapToUrlComment(sourceMap, dirname(filePath))}` : css, watchFiles: loadedUrls.map((url) => fileURLToPath(url)), warnings, }; } catch (error) { if (isSassException(error)) { const fileWithError = error.span.url ? fileURLToPath(error.span.url) : undefined; const watchFiles = [filePath, ...extractFilesFromStack(error.sassStack)]; if (fileWithError) { watchFiles.push(fileWithError); } return { loader: 'css', errors: [ { text: error.message, }, ], warnings, watchFiles, }; } throw error; } } function sourceMapToUrlComment( sourceMap: Exclude<CompileResult['sourceMap'], undefined>, root: string, ): string { // Remove `file` protocol from all sourcemap sources and adjust to be relative to the input file. // This allows esbuild to correctly process the paths. sourceMap.sources = sourceMap.sources.map((source) => relative(root, fileURLToPath(source))); const urlSourceMap = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64'); return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${urlSourceMap} */`; } function* extractFilesFromStack(stack: string): Iterable<string> { const lines = stack.split('\n'); const cwd = process.cwd(); // Stack line has format of "<file> <location> <identifier>" for (const line of lines) { const segments = line.split(' '); if (segments.length < 3) { break; } // Extract path from stack line. // Paths may contain spaces. All segments before location are part of the file path. let path = ''; let index = 0; while (!segments[index].match(/\d+:\d+/)) { path += segments[index++]; } if (path) { // Stack paths from dart-sass are relative to the current working directory (not input file or workspace root) yield join(cwd, path); } } }
{ "end_byte": 8386, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/sass-language.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/css-inline-fonts-plugin.ts_0_2321
/** * @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 { Plugin, PluginBuild } from 'esbuild'; import { InlineFontsProcessor } from '../../../utils/index-file/inline-fonts'; import { NormalizedCachedOptions } from '../../../utils/normalize-cache'; import { LoadResultCache, createCachedLoad } from '../load-result-cache'; /** * Options for the createCssInlineFontsPlugin * @see createCssInlineFontsPlugin */ export interface CssInlineFontsPluginOptions { /** Disk cache normalized options */ cacheOptions?: NormalizedCachedOptions; /** Load results cache. */ cache?: LoadResultCache; } /** * Creates an esbuild {@link Plugin} that inlines fonts imported via import-rule. * within the build configuration. */ export function createCssInlineFontsPlugin({ cache, cacheOptions, }: CssInlineFontsPluginOptions): Plugin { return { name: 'angular-css-inline-fonts-plugin', setup(build: PluginBuild): void { const inlineFontsProcessor = new InlineFontsProcessor({ cache: cacheOptions, minify: false }); build.onResolve({ filter: /fonts\.googleapis\.com|use\.typekit\.net/ }, (args) => { // Only attempt to resolve import-rule tokens which only exist inside CSS. if (args.kind !== 'import-rule') { return null; } if (!inlineFontsProcessor.canInlineRequest(args.path)) { return null; } return { path: args.path, namespace: 'css-inline-fonts', }; }); build.onLoad( { filter: /./, namespace: 'css-inline-fonts' }, createCachedLoad(cache, async (args) => { try { return { contents: await inlineFontsProcessor.processURL(args.path), loader: 'css', }; } catch (error) { return { loader: 'css', errors: [ { text: `Failed to inline external stylesheet '${args.path}'.`, notes: error instanceof Error ? [{ text: error.toString() }] : undefined, }, ], }; } }), ); }, }; }
{ "end_byte": 2321, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/css-inline-fonts-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/css-resource-plugin.ts_0_4626
/** * @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 { Plugin, PluginBuild } from 'esbuild'; import { readFile } from 'node:fs/promises'; import { extname, join, relative } from 'node:path'; import { LoadResultCache, createCachedLoad } from '../load-result-cache'; const CSS_RESOURCE_NAMESPACE = 'angular:css-resource'; /** * Symbol marker used to indicate CSS resource resolution is being attempted. * This is used to prevent an infinite loop within the plugin's resolve hook. */ const CSS_RESOURCE_RESOLUTION = Symbol('CSS_RESOURCE_RESOLUTION'); /** * Creates an esbuild {@link Plugin} that loads all CSS url token references using the * built-in esbuild `file` loader. A plugin is used to allow for all file extensions * and types to be supported without needing to manually specify all extensions * within the build configuration. * * @returns An esbuild {@link Plugin} instance. */ export function createCssResourcePlugin(cache?: LoadResultCache): Plugin { return { name: 'angular-css-resource', setup(build: PluginBuild): void { build.onResolve({ filter: /.*/ }, async (args) => { const { importer, path, kind, resolveDir, namespace, pluginData = {} } = args; // Only attempt to resolve url tokens which only exist inside CSS. // Also, skip this plugin if already attempting to resolve the url-token. if (kind !== 'url-token' || pluginData[CSS_RESOURCE_RESOLUTION]) { return null; } let [containingDir, resourceUrl] = path.split('||file:', 2); if (resourceUrl === undefined) { // This can happen due to early exit checks in rebasing-importer // logic such as when the url is an external URL. resourceUrl = containingDir; containingDir = ''; } // If root-relative, absolute or protocol relative url, mark as external to leave the // path/URL in place. if (/^((?:\w+:)?\/\/|data:|chrome:|#|\/)/.test(resourceUrl)) { return { path: resourceUrl, external: true, }; } pluginData[CSS_RESOURCE_RESOLUTION] = true; const result = await build.resolve(resourceUrl, { importer, kind, namespace, pluginData, resolveDir: join(resolveDir, containingDir), }); if (result.errors.length) { const error = result.errors[0]; if (resourceUrl[0] === '~') { error.notes = [ { location: null, text: 'You can remove the tilde and use a relative path to reference it, which should remove this error.', }, ]; } else if (resourceUrl[0] === '^') { error.notes = [ { location: null, text: 'You can remove the caret and add the path to the `externalDependencies` build option,' + ' which should remove this error.', }, ]; } const extension = importer && extname(importer); if (extension !== '.css') { error.notes.push({ location: null, text: 'Preprocessor stylesheets may not show the exact file location of the error.', }); } } // Return results that are not files since these are most likely specific to another plugin // and cannot be loaded by this plugin. if (result.namespace !== 'file') { return result; } // All file results are considered CSS resources and will be loaded via the file loader return { ...result, // Use a relative path to prevent fully resolved paths in the metafile (JSON stats file). // This is only necessary for custom namespaces. esbuild will handle the file namespace. path: relative(build.initialOptions.absWorkingDir ?? '', result.path), namespace: CSS_RESOURCE_NAMESPACE, }; }); build.onLoad( { filter: /./, namespace: CSS_RESOURCE_NAMESPACE }, createCachedLoad(cache, async (args) => { const resourcePath = join(build.initialOptions.absWorkingDir ?? '', args.path); return { contents: await readFile(resourcePath), loader: 'file', watchFiles: [resourcePath], }; }), ); }, }; }
{ "end_byte": 4626, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/css-resource-plugin.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/css-language.ts_0_415
/** * @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 { StylesheetLanguage } from './stylesheet-plugin-factory'; export const CssStylesheetLanguage = Object.freeze<StylesheetLanguage>({ name: 'css', componentFilter: /^css;/, fileFilter: /\.css$/, });
{ "end_byte": 415, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/css-language.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts_0_5565
/** * @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 { Location, OnLoadResult, PluginBuild } from 'esbuild'; import { readFile } from 'node:fs/promises'; import { StylesheetLanguage, StylesheetPluginOptions } from './stylesheet-plugin-factory'; /** * The lazy-loaded instance of the less stylesheet preprocessor. * It is only imported and initialized if a less stylesheet is used. */ let lessPreprocessor: typeof import('less') | undefined; interface LessException extends Error { filename: string; line: number; column: number; extract?: string[]; } function isLessException(error: unknown): error is LessException { return !!error && typeof error === 'object' && 'column' in error; } export const LessStylesheetLanguage = Object.freeze<StylesheetLanguage>({ name: 'less', componentFilter: /^less;/, fileFilter: /\.less$/, process(data, file, _, options, build) { return compileString( data, file, options, build.resolve.bind(build), /* unsafeInlineJavaScript */ false, ); }, }); async function compileString( data: string, filename: string, options: StylesheetPluginOptions, resolver: PluginBuild['resolve'], unsafeInlineJavaScript: boolean, ): Promise<OnLoadResult> { try { lessPreprocessor ??= (await import('less')).default; } catch { return { errors: [ { text: 'Unable to load the "less" stylesheet preprocessor.', location: null, notes: [ { text: 'Ensure that the "less" Node.js package is installed within the project. ' + "If not present, installation via the project's package manager should resolve the error.", }, ], }, ], }; } const less = lessPreprocessor; const resolverPlugin: Less.Plugin = { install({ FileManager }, pluginManager): void { const resolverFileManager = new (class extends FileManager { override supportsSync(): boolean { return false; } override supports(): boolean { return true; } override async loadFile( filename: string, currentDirectory: string, options: Less.LoadFileOptions, environment: Less.Environment, ): Promise<Less.FileLoadResult> { // Attempt direct loading as a relative path to avoid resolution overhead try { return await super.loadFile(filename, currentDirectory, options, environment); } catch (error) { // Attempt a full resolution if not found const fullResult = await resolver(filename, { kind: 'import-rule', resolveDir: currentDirectory, }); if (fullResult.path) { return { filename: fullResult.path, contents: await readFile(fullResult.path, 'utf-8'), }; } // Otherwise error by throwing the failing direct result throw error; } } })(); pluginManager.addFileManager(resolverFileManager); }, }; try { const result = await less.render(data, { filename, paths: options.includePaths, plugins: [resolverPlugin], rewriteUrls: 'all', javascriptEnabled: unsafeInlineJavaScript, sourceMap: options.sourcemap ? { sourceMapFileInline: true, outputSourceFiles: true, } : undefined, } as Less.Options); return { contents: result.css, loader: 'css', watchFiles: [filename, ...result.imports], }; } catch (error) { if (isLessException(error)) { const location = convertExceptionLocation(error); // Retry with a warning for less files requiring the deprecated inline JavaScript option if (error.message.includes('Inline JavaScript is not enabled.')) { const withJsResult = await compileString( data, filename, options, resolver, /* unsafeInlineJavaScript */ true, ); withJsResult.warnings = [ { text: 'Deprecated inline execution of JavaScript has been enabled ("javascriptEnabled")', location, notes: [ { location: null, text: 'JavaScript found within less stylesheets may be executed at build time. [https://lesscss.org/usage/#less-options]', }, { location: null, text: 'Support for "javascriptEnabled" may be removed from the Angular CLI starting with Angular v19.', }, ], }, ]; return withJsResult; } return { errors: [ { text: error.message, location, }, ], loader: 'css', watchFiles: location.file ? [filename, location.file] : [filename], }; } throw error; } } function convertExceptionLocation(exception: LessException): Partial<Location> { return { file: exception.filename, line: exception.line, column: exception.column, // Middle element represents the line containing the exception lineText: exception.extract && exception.extract[Math.trunc(exception.extract.length / 2)], }; }
{ "end_byte": 5565, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts_0_8206
/** * @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 { OnLoadResult, Plugin, PluginBuild } from 'esbuild'; import glob from 'fast-glob'; import assert from 'node:assert'; import { readFile } from 'node:fs/promises'; import { extname } from 'node:path'; import type { Options } from 'sass'; import type { PostcssConfiguration } from '../../../utils/postcss-configuration'; import { LoadResultCache, createCachedLoad } from '../load-result-cache'; /** * Configuration options for handling Sass-specific deprecations in a stylesheet plugin. */ export type StylesheetPluginsass = Pick< Options<'async'>, 'futureDeprecations' | 'fatalDeprecations' | 'silenceDeprecations' >; /** * Convenience type for a postcss processor. */ type PostcssProcessor = import('postcss').Processor; /** * The lazy-loaded instance of the postcss stylesheet postprocessor. * It is only imported and initialized if postcss is needed. */ let postcss: (typeof import('postcss'))['default'] | undefined; /** * An object containing the plugin options to use when processing stylesheets. */ export interface StylesheetPluginOptions { /** * Controls the use and creation of sourcemaps when processing the stylesheets. * If true, sourcemap processing is enabled; if false, disabled. */ sourcemap: boolean; /** * An optional array of paths that will be searched for stylesheets if the default * resolution process for the stylesheet language does not succeed. */ includePaths?: string[]; /** * Optional component data for any inline styles from Component decorator `styles` fields. * The key is an internal angular resource URI and the value is the stylesheet content. */ inlineComponentData?: Record<string, string>; /** * Optional information used to load and configure Tailwind CSS. If present, the postcss * will be added to the stylesheet processing with the Tailwind plugin setup as provided * by the configuration file. */ tailwindConfiguration?: { file: string; package: string }; /** * Optional configuration object for custom postcss usage. If present, postcss will be * initialized and used for every stylesheet. This overrides the tailwind integration * and any tailwind usage must be manually configured in the custom postcss usage. */ postcssConfiguration?: PostcssConfiguration; /** * Optional Options for configuring Sass behavior. */ sass?: StylesheetPluginsass; } /** * An array of keywords that indicate Tailwind CSS processing is required for a stylesheet. * * Based on https://tailwindcss.com/docs/functions-and-directives */ const TAILWIND_KEYWORDS = [ '@tailwind', '@layer', '@apply', '@config', 'theme(', 'screen(', '@screen', // Undocumented in version 3, see: https://github.com/tailwindlabs/tailwindcss/discussions/7516. ]; export interface StylesheetLanguage { name: string; componentFilter: RegExp; fileFilter: RegExp; process?( data: string, file: string, format: string, options: StylesheetPluginOptions, build: PluginBuild, ): OnLoadResult | Promise<OnLoadResult>; } /** * Cached postcss instances that can be re-used between various StylesheetPluginFactory instances. */ const postcssProcessors = new Map<string, WeakRef<PostcssProcessor>>(); export class StylesheetPluginFactory { constructor( private readonly options: StylesheetPluginOptions, private readonly cache?: LoadResultCache, ) {} create(language: Readonly<StylesheetLanguage>): Plugin { const { cache, options, setupPostcss } = this; // Return a noop plugin if no load actions are required if (!language.process && !options.postcssConfiguration && !options.tailwindConfiguration) { return { name: 'angular-' + language.name, setup() {}, }; } return { name: 'angular-' + language.name, async setup(build) { // Setup postcss if needed let postcssProcessor: PostcssProcessor | undefined; build.onStart(async () => { try { postcssProcessor = await setupPostcss; } catch { return { errors: [ { text: 'Unable to load the "postcss" stylesheet processor.', location: null, notes: [ { text: 'Ensure that the "postcss" Node.js package is installed within the project. ' + "If not present, installation via the project's package manager should resolve the error.", }, ], }, ], }; } }); // Add a load callback to support inline Component styles build.onLoad( { filter: language.componentFilter, namespace: 'angular:styles/component' }, createCachedLoad(cache, (args) => { const data = options.inlineComponentData?.[args.path]; assert( typeof data === 'string', `component style name should always be found [${args.path}]`, ); const [format, , filename] = args.path.split(';', 3); return processStylesheet( language, data, filename, format, options, build, postcssProcessor, ); }), ); // Add a load callback to support files from disk build.onLoad( { filter: language.fileFilter, namespace: 'file' }, createCachedLoad(cache, async (args) => { const data = await readFile(args.path, 'utf-8'); return processStylesheet( language, data, args.path, extname(args.path).toLowerCase().slice(1), options, build, postcssProcessor, ); }), ); }, }; } private setupPostcssPromise: Promise<PostcssProcessor | undefined> | undefined; private get setupPostcss(): Promise<PostcssProcessor | undefined> { return (this.setupPostcssPromise ??= this.initPostcss()); } private initPostcssCallCount = 0; /** * This method should not be called directly. * Use {@link setupPostcss} instead. */ private async initPostcss(): Promise<PostcssProcessor | undefined> { assert.equal(++this.initPostcssCallCount, 1, '`initPostcss` was called more than once.'); const { options } = this; if (options.postcssConfiguration) { const postCssInstanceKey = JSON.stringify(options.postcssConfiguration); let postcssProcessor = postcssProcessors.get(postCssInstanceKey)?.deref(); if (!postcssProcessor) { postcss ??= (await import('postcss')).default; postcssProcessor = postcss(); for (const [pluginName, pluginOptions] of options.postcssConfiguration.plugins) { const { default: plugin } = await import(pluginName); if (typeof plugin !== 'function' || plugin.postcss !== true) { throw new Error(`Attempted to load invalid Postcss plugin: "${pluginName}"`); } postcssProcessor.use(plugin(pluginOptions)); } postcssProcessors.set(postCssInstanceKey, new WeakRef(postcssProcessor)); } return postcssProcessor; } else if (options.tailwindConfiguration) { const { package: tailwindPackage, file: config } = options.tailwindConfiguration; const postCssInstanceKey = tailwindPackage + ':' + config; let postcssProcessor = postcssProcessors.get(postCssInstanceKey)?.deref(); if (!postcssProcessor) { postcss ??= (await import('postcss')).default; const tailwind = await import(tailwindPackage); postcssProcessor = postcss().use(tailwind.default({ config })); postcssProcessors.set(postCssInstanceKey, new WeakRef(postcssProcessor)); } return postcssProcessor; } } }
{ "end_byte": 8206, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts" }
angular-cli/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts_8208_13639
async function processStylesheet( language: Readonly<StylesheetLanguage>, data: string, filename: string, format: string, options: StylesheetPluginOptions, build: PluginBuild, postcssProcessor: PostcssProcessor | undefined, ) { let result: OnLoadResult; // Process the input data if the language requires preprocessing if (language.process) { result = await language.process(data, filename, format, options, build); } else { result = { contents: data, loader: 'css', watchFiles: [filename], }; } // Return early if there are no contents to further process or there are errors if (!result.contents || result.errors?.length) { return result; } // Only use postcss if Tailwind processing is required or custom postcss is present. if (postcssProcessor && (options.postcssConfiguration || hasTailwindKeywords(result.contents))) { const postcssResult = await compileString( typeof result.contents === 'string' ? result.contents : Buffer.from(result.contents).toString('utf-8'), filename, postcssProcessor, options, ); // Merge results if (postcssResult.errors?.length) { delete result.contents; } if (result.warnings && postcssResult.warnings) { postcssResult.warnings.unshift(...result.warnings); } if (result.watchFiles && postcssResult.watchFiles) { postcssResult.watchFiles.unshift(...result.watchFiles); } if (result.watchDirs && postcssResult.watchDirs) { postcssResult.watchDirs.unshift(...result.watchDirs); } result = { ...result, ...postcssResult, }; } return result; } /** * Searches the provided contents for keywords that indicate Tailwind is used * within a stylesheet. * @param contents A string or Uint8Array containing UTF-8 text. * @returns True, if the contents contains tailwind keywords; False, otherwise. */ function hasTailwindKeywords(contents: string | Uint8Array): boolean { // TODO: use better search algorithm for keywords if (typeof contents === 'string') { return TAILWIND_KEYWORDS.some((keyword) => contents.includes(keyword)); } // Contents is a Uint8Array const data = contents instanceof Buffer ? contents : Buffer.from(contents); return TAILWIND_KEYWORDS.some((keyword) => data.includes(keyword)); } /** * Compiles the provided CSS stylesheet data using a provided postcss processor and provides an * esbuild load result that can be used directly by an esbuild Plugin. * @param data The stylesheet content to process. * @param filename The name of the file that contains the data. * @param postcssProcessor A postcss processor instance to use. * @param options The plugin options to control the processing. * @returns An esbuild OnLoaderResult object with the processed content, warnings, and/or errors. */ async function compileString( data: string, filename: string, postcssProcessor: import('postcss').Processor, options: StylesheetPluginOptions, ): Promise<OnLoadResult> { try { const postcssResult = await postcssProcessor.process(data, { from: filename, to: filename, map: options.sourcemap && { inline: true, sourcesContent: true, }, }); const loadResult: OnLoadResult = { contents: postcssResult.css, loader: 'css', }; const rawWarnings = postcssResult.warnings(); if (rawWarnings.length > 0) { const lineMappings = new Map<string, string[] | null>(); loadResult.warnings = rawWarnings.map((warning) => { const file = warning.node.source?.input.file; if (file === undefined) { return { text: warning.text }; } let lines = lineMappings.get(file); if (lines === undefined) { lines = warning.node.source?.input.css.split(/\r?\n/); lineMappings.set(file, lines ?? null); } return { text: warning.text, location: { file, line: warning.line, column: warning.column - 1, lineText: lines?.[warning.line - 1], }, }; }); } for (const resultMessage of postcssResult.messages) { if (resultMessage.type === 'dependency' && typeof resultMessage['file'] === 'string') { loadResult.watchFiles ??= []; loadResult.watchFiles.push(resultMessage['file']); } else if ( resultMessage.type === 'dir-dependency' && typeof resultMessage['dir'] === 'string' && typeof resultMessage['glob'] === 'string' ) { loadResult.watchFiles ??= []; const dependencies = await glob(resultMessage['glob'], { absolute: true, cwd: resultMessage['dir'], }); loadResult.watchFiles.push(...dependencies); } } return loadResult; } catch (error) { postcss ??= (await import('postcss')).default; if (error instanceof postcss.CssSyntaxError) { const lines = error.source?.split(/\r?\n/); return { errors: [ { text: error.reason, location: { file: error.file, line: error.line, column: error.column && error.column - 1, lineText: error.line === undefined ? undefined : lines?.[error.line - 1], }, }, ], }; } throw error; } }
{ "end_byte": 13639, "start_byte": 8208, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts" }
angular-cli/packages/angular/build/src/tools/sass/lexer.ts_0_5113
/** * @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: Combine everything into a single pass lexer /** * Determines if a unicode code point is a CSS whitespace character. * @param code The unicode code point to test. * @returns true, if the code point is CSS whitespace; false, otherwise. */ function isWhitespace(code: number): boolean { // Based on https://www.w3.org/TR/css-syntax-3/#whitespace switch (code) { case 0x0009: // tab case 0x0020: // space case 0x000a: // line feed case 0x000c: // form feed case 0x000d: // carriage return return true; default: return false; } } /** * Scans a CSS or Sass file and locates all valid url function values as defined by the * syntax specification. * @param contents A string containing a CSS or Sass file to scan. * @returns An iterable that yields each CSS url function value found. */ export function* findUrls( contents: string, ): Iterable<{ start: number; end: number; value: string }> { let pos = 0; let width = 1; let current = -1; const next = () => { pos += width; current = contents.codePointAt(pos) ?? -1; width = current > 0xffff ? 2 : 1; return current; }; // Based on https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token while ((pos = contents.indexOf('url(', pos)) !== -1) { width = 1; // Ensure whitespace, comma, or colon before `url(` if (pos > 0) { pos -= 2; next(); if (!isWhitespace(current) && current !== 0x002c && current !== 0x003a) { // Skip - not a url token pos += 3; continue; } pos += 1; } // Set to position of the ( pos += 3; // Consume all leading whitespace while (isWhitespace(next())) { /* empty */ } // Initialize URL state const url = { start: pos, end: -1, value: '' }; let complete = false; // If " or ', then consume the value as a string if (current === 0x0022 || current === 0x0027) { const ending = current; // Based on https://www.w3.org/TR/css-syntax-3/#consume-string-token while (!complete) { switch (next()) { case -1: // EOF return; case 0x000a: // line feed case 0x000c: // form feed case 0x000d: // carriage return // Invalid complete = true; break; case 0x005c: // \ -- character escape // If not EOF or newline, add the character after the escape switch (next()) { case -1: return; case 0x000a: // line feed case 0x000c: // form feed case 0x000d: // carriage return // Skip when inside a string break; default: // TODO: Handle hex escape codes url.value += String.fromCodePoint(current); break; } break; case ending: // Full string position should include the quotes for replacement url.end = pos + 1; complete = true; yield url; break; default: url.value += String.fromCodePoint(current); break; } } next(); continue; } // Based on https://www.w3.org/TR/css-syntax-3/#consume-url-token while (!complete) { switch (current) { case -1: // EOF return; case 0x0022: // " case 0x0027: // ' case 0x0028: // ( // Invalid complete = true; break; case 0x0029: // ) // URL is valid and complete url.end = pos; complete = true; break; case 0x005c: // \ -- character escape // If not EOF or newline, add the character after the escape switch (next()) { case -1: // EOF return; case 0x000a: // line feed case 0x000c: // form feed case 0x000d: // carriage return // Invalid complete = true; break; default: // TODO: Handle hex escape codes url.value += String.fromCodePoint(current); break; } break; default: if (isWhitespace(current)) { while (isWhitespace(next())) { /* empty */ } // Unescaped whitespace is only valid before the closing ) if (current === 0x0029) { // URL is valid url.end = pos; } complete = true; } else { // Add the character to the url value url.value += String.fromCodePoint(current); } break; } next(); } // An end position indicates a URL was found if (url.end !== -1) { yield url; } } }
{ "end_byte": 5113, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/lexer.ts" }
angular-cli/packages/angular/build/src/tools/sass/sass-service.ts_0_7719
/** * @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 'node:assert'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { MessageChannel } from 'node:worker_threads'; import type { CanonicalizeContext, CompileResult, Deprecation, Exception, FileImporter, Importer, NodePackageImporter, SourceSpan, StringOptions, } from 'sass'; import { maxWorkers } from '../../utils/environment-options'; import { WorkerPool } from '../../utils/worker-pool'; // Polyfill Symbol.dispose if not present // eslint-disable-next-line @typescript-eslint/no-explicit-any (Symbol as any).dispose ??= Symbol('Symbol Dispose'); /** * The maximum number of Workers that will be created to execute render requests. */ const MAX_RENDER_WORKERS = maxWorkers; /** * All available importer types. */ type Importers = | Importer<'sync'> | Importer<'async'> | FileImporter<'sync'> | FileImporter<'async'> | NodePackageImporter; export interface SerializableVersion { major: number; minor: number; patch: number; } export interface SerializableDeprecation extends Omit<Deprecation, 'obsoleteIn' | 'deprecatedIn'> { /** The version this deprecation first became active in. */ deprecatedIn: SerializableVersion | null; /** The version this deprecation became obsolete in. */ obsoleteIn: SerializableVersion | null; } export type SerializableWarningMessage = ( | { deprecation: true; deprecationType: SerializableDeprecation; } | { deprecation: false } ) & { message: string; span?: Omit<SourceSpan, 'url'> & { url?: string }; stack?: string; }; /** * A response from the Sass render Worker containing the result of the operation. */ interface RenderResponseMessage { error?: Exception; result?: Omit<CompileResult, 'loadedUrls'> & { loadedUrls: string[] }; warnings?: SerializableWarningMessage[]; } /** * A Sass renderer implementation that provides an interface that can be used by Webpack's * `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering * with the `dart-sass` package. The `dart-sass` synchronous render function is used within * the worker which can be up to two times faster than the asynchronous variant. */ export class SassWorkerImplementation { #workerPool: WorkerPool | undefined; constructor( private readonly rebase = false, readonly maxThreads = MAX_RENDER_WORKERS, ) {} #ensureWorkerPool(): WorkerPool { this.#workerPool ??= new WorkerPool({ filename: require.resolve('./worker'), maxThreads: this.maxThreads, }); return this.#workerPool; } /** * Provides information about the Sass implementation. * This mimics enough of the `dart-sass` value to be used with the `sass-loader`. */ get info(): string { return 'dart-sass\tworker'; } /** * The synchronous render function is not used by the `sass-loader`. */ compileString(): never { throw new Error('Sass compileString is not supported.'); } /** * Asynchronously request a Sass stylesheet to be renderered. * * @param source The contents to compile. * @param options The `dart-sass` options to use when rendering the stylesheet. */ async compileStringAsync( source: string, options: StringOptions<'async'>, ): Promise<CompileResult> { // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred. // If any additional function options are added in the future, they must be excluded as well. const { functions, importers, url, logger, ...serializableOptions } = options; // The CLI's configuration does not use or expose the ability to define custom Sass functions if (functions && Object.keys(functions).length > 0) { throw new Error('Sass custom functions are not supported.'); } using importerChannel = importers?.length ? this.#createImporterChannel(importers) : undefined; const response = (await this.#ensureWorkerPool().run( { source, importerChannel, hasLogger: !!logger, rebase: this.rebase, options: { ...serializableOptions, // URL is not serializable so to convert to string here and back to URL in the worker. url: url ? fileURLToPath(url) : undefined, }, }, { transferList: importerChannel ? [importerChannel.port] : undefined, }, )) as RenderResponseMessage; const { result, error, warnings } = response; if (warnings && logger?.warn) { for (const { message, span, ...options } of warnings) { logger.warn(message, { ...options, span: span && { ...span, url: span.url ? pathToFileURL(span.url) : undefined, }, }); } } if (error) { // Convert stringified url value required for cloning back to a URL object const url = error.span?.url as string | undefined; if (url) { error.span.url = pathToFileURL(url); } throw error; } assert(result, 'Sass render worker should always return a result or an error'); return { ...result, // URL is not serializable so in the worker we convert to string and here back to URL. loadedUrls: result.loadedUrls.map((p) => pathToFileURL(p)), }; } /** * Shutdown the Sass render worker. * Executing this method will stop any pending render requests. * @returns A void promise that resolves when closing is complete. */ async close(): Promise<void> { if (this.#workerPool) { try { await this.#workerPool.destroy(); } finally { this.#workerPool = undefined; } } } #createImporterChannel(importers: Iterable<Importers>) { const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel(); const importerSignal = new Int32Array(new SharedArrayBuffer(4)); mainImporterPort.on( 'message', ({ url, options }: { url: string; options: CanonicalizeContext }) => { this.processImporters(importers, url, { ...options, // URL is not serializable so in the worker we convert to string and here back to URL. containingUrl: options.containingUrl ? pathToFileURL(options.containingUrl as unknown as string) : null, }) .then((result) => { mainImporterPort.postMessage(result); }) .catch((error) => { mainImporterPort.postMessage(error); }) .finally(() => { Atomics.store(importerSignal, 0, 1); Atomics.notify(importerSignal, 0); }); }, ); mainImporterPort.unref(); return { port: workerImporterPort, signal: importerSignal, [Symbol.dispose]() { mainImporterPort.close(); }, }; } private async processImporters( importers: Iterable<Importers>, url: string, options: CanonicalizeContext, ): Promise<string | null> { for (const importer of importers) { if (!this.isFileImporter(importer)) { // Importer throw new Error('Only File Importers are supported.'); } // File importer (Can be sync or aync). const result = await importer.findFileUrl(url, options); if (result) { return fileURLToPath(result); } } return null; } private isFileImporter(value: Importers): value is FileImporter { return 'findFileUrl' in value; } }
{ "end_byte": 7719, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/sass-service.ts" }
angular-cli/packages/angular/build/src/tools/sass/rebasing-importer.ts_0_4904
/** * @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 { RawSourceMap } from '@ampproject/remapping'; import MagicString from 'magic-string'; import { readFileSync, readdirSync, statSync } from 'node:fs'; import { basename, dirname, extname, join, relative } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type { CanonicalizeContext, Importer, ImporterResult, Syntax } from 'sass'; import { assertIsError } from '../../utils/error'; import { findUrls } from './lexer'; /** * A preprocessed cache entry for the files and directories within a previously searched * directory when performing Sass import resolution. */ export interface DirectoryEntry { files: Set<string>; directories: Set<string>; } /** * A Sass Importer base class that provides the load logic to rebase all `url()` functions * within a stylesheet. The rebasing will ensure that the URLs in the output of the Sass compiler * reflect the final filesystem location of the output CSS file. * * This class provides the core of the rebasing functionality. To ensure that each file is processed * by this importer's load implementation, the Sass compiler requires the importer's canonicalize * function to return a non-null value with the resolved location of the requested stylesheet. * Concrete implementations of this class must provide this canonicalize functionality for rebasing * to be effective. */ abstract class UrlRebasingImporter implements Importer<'sync'> { /** * @param entryDirectory The directory of the entry stylesheet that was passed to the Sass compiler. * @param rebaseSourceMaps When provided, rebased files will have an intermediate sourcemap added to the Map * which can be used to generate a final sourcemap that contains original sources. */ constructor( private entryDirectory: string, private rebaseSourceMaps?: Map<string, RawSourceMap>, ) {} abstract canonicalize(url: string, options: { fromImport: boolean }): URL | null; load(canonicalUrl: URL): ImporterResult | null { const stylesheetPath = fileURLToPath(canonicalUrl); const stylesheetDirectory = dirname(stylesheetPath); let contents = readFileSync(stylesheetPath, 'utf-8'); // Rebase any URLs that are found let updatedContents; for (const { start, end, value } of findUrls(contents)) { // Skip if value is empty or Webpack-specific prefix if (value.length === 0 || value[0] === '~' || value[0] === '^') { continue; } // Skip if root-relative, absolute or protocol relative url if (/^((?:\w+:)?\/\/|data:|chrome:|\/)/.test(value)) { continue; } // Skip if a fragment identifier but not a Sass interpolation if (value[0] === '#' && value[1] !== '{') { continue; } // Skip if value is value contains a function call if (/#\{.+\(.+\)\}/.test(value)) { continue; } // Sass variable usage either starts with a `$` or contains a namespace and a `.$` const valueNormalized = value[0] === '$' || /^\w+\.\$/.test(value) ? `#{${value}}` : value; const rebasedPath = relative(this.entryDirectory, stylesheetDirectory); // Normalize path separators and escape characters // https://developer.mozilla.org/en-US/docs/Web/CSS/url#syntax const rebasedUrl = rebasedPath.replace(/\\/g, '/').replace(/[()\s'"]/g, '\\$&'); updatedContents ??= new MagicString(contents); // Always quote the URL to avoid potential downstream parsing problems updatedContents.update(start, end, `"${rebasedUrl}||file:${valueNormalized}"`); } if (updatedContents) { contents = updatedContents.toString(); if (this.rebaseSourceMaps) { // Generate an intermediate source map for the rebasing changes const map = updatedContents.generateMap({ hires: 'boundary', includeContent: true, source: canonicalUrl.href, }); this.rebaseSourceMaps.set(canonicalUrl.href, map as RawSourceMap); } } let syntax: Syntax | undefined; switch (extname(stylesheetPath).toLowerCase()) { case '.css': syntax = 'css'; break; case '.sass': syntax = 'indented'; break; default: syntax = 'scss'; break; } return { contents, syntax, sourceMapUrl: canonicalUrl, }; } } /** * Provides the Sass importer logic to resolve relative stylesheet imports via both import and use rules * and also rebase any `url()` function usage within those stylesheets. The rebasing will ensure that * the URLs in the output of the Sass compiler reflect the final filesystem location of the output CSS file. */
{ "end_byte": 4904, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/rebasing-importer.ts" }
angular-cli/packages/angular/build/src/tools/sass/rebasing-importer.ts_4905_13184
export class RelativeUrlRebasingImporter extends UrlRebasingImporter { constructor( entryDirectory: string, private directoryCache = new Map<string, DirectoryEntry>(), rebaseSourceMaps?: Map<string, RawSourceMap>, ) { super(entryDirectory, rebaseSourceMaps); } canonicalize(url: string, options: { fromImport: boolean }): URL | null { return this.resolveImport(url, options.fromImport, true); } /** * Attempts to resolve a provided URL to a stylesheet file using the Sass compiler's resolution algorithm. * Based on https://github.com/sass/dart-sass/blob/44d6bb6ac72fe6b93f5bfec371a1fffb18e6b76d/lib/src/importer/utils.dart * @param url The file protocol URL to resolve. * @param fromImport If true, URL was from an import rule; otherwise from a use rule. * @param checkDirectory If true, try checking for a directory with the base name containing an index file. * @returns A full resolved URL of the stylesheet file or `null` if not found. */ private resolveImport(url: string, fromImport: boolean, checkDirectory: boolean): URL | null { let stylesheetPath; try { stylesheetPath = fileURLToPath(url); } catch { // Only file protocol URLs are supported by this importer return null; } const directory = dirname(stylesheetPath); const extension = extname(stylesheetPath); const hasStyleExtension = extension === '.scss' || extension === '.sass' || extension === '.css'; // Remove the style extension if present to allow adding the `.import` suffix const filename = basename(stylesheetPath, hasStyleExtension ? extension : undefined); const importPotentials = new Set<string>(); const defaultPotentials = new Set<string>(); if (hasStyleExtension) { if (fromImport) { importPotentials.add(filename + '.import' + extension); importPotentials.add('_' + filename + '.import' + extension); } defaultPotentials.add(filename + extension); defaultPotentials.add('_' + filename + extension); } else { if (fromImport) { importPotentials.add(filename + '.import.scss'); importPotentials.add(filename + '.import.sass'); importPotentials.add(filename + '.import.css'); importPotentials.add('_' + filename + '.import.scss'); importPotentials.add('_' + filename + '.import.sass'); importPotentials.add('_' + filename + '.import.css'); } defaultPotentials.add(filename + '.scss'); defaultPotentials.add(filename + '.sass'); defaultPotentials.add(filename + '.css'); defaultPotentials.add('_' + filename + '.scss'); defaultPotentials.add('_' + filename + '.sass'); defaultPotentials.add('_' + filename + '.css'); } let foundDefaults; let foundImports; let hasPotentialIndex = false; let cachedEntries = this.directoryCache.get(directory); if (cachedEntries) { // If there is a preprocessed cache of the directory, perform an intersection of the potentials // and the directory files. const { files, directories } = cachedEntries; foundDefaults = [...defaultPotentials].filter((potential) => files.has(potential)); foundImports = [...importPotentials].filter((potential) => files.has(potential)); hasPotentialIndex = checkDirectory && !hasStyleExtension && directories.has(filename); } else { // If no preprocessed cache exists, get the entries from the file system and, while searching, // generate the cache for later requests. let entries; try { entries = readdirSync(directory, { withFileTypes: true }); } catch (error) { assertIsError(error); // If the containing directory does not exist return null to indicate it cannot be resolved if (error.code === 'ENOENT') { return null; } throw new Error(`Error reading directory ["${directory}"] while resolving Sass import`, { cause: error, }); } foundDefaults = []; foundImports = []; cachedEntries = { files: new Set<string>(), directories: new Set<string>() }; for (const entry of entries) { let isDirectory: boolean; let isFile: boolean; if (entry.isSymbolicLink()) { const stats = statSync(join(directory, entry.name)); isDirectory = stats.isDirectory(); isFile = stats.isFile(); } else { isDirectory = entry.isDirectory(); isFile = entry.isFile(); } if (isDirectory) { cachedEntries.directories.add(entry.name); // Record if the name should be checked as a directory with an index file if (checkDirectory && !hasStyleExtension && entry.name === filename) { hasPotentialIndex = true; } } if (!isFile) { continue; } cachedEntries.files.add(entry.name); if (importPotentials.has(entry.name)) { foundImports.push(entry.name); } if (defaultPotentials.has(entry.name)) { foundDefaults.push(entry.name); } } this.directoryCache.set(directory, cachedEntries); } // `foundImports` will only contain elements if `options.fromImport` is true const result = this.checkFound(foundImports) ?? this.checkFound(foundDefaults); if (result !== null) { return pathToFileURL(join(directory, result)); } if (hasPotentialIndex) { // Check for index files using filename as a directory return this.resolveImport(url + '/index', fromImport, false); } return null; } /** * Checks an array of potential stylesheet files to determine if there is a valid * stylesheet file. More than one discovered file may indicate an error. * @param found An array of discovered stylesheet files. * @returns A fully resolved path for a stylesheet file or `null` if not found. * @throws If there are ambiguous files discovered. */ private checkFound(found: string[]): string | null { if (found.length === 0) { // Not found return null; } // More than one found file may be an error if (found.length > 1) { // Presence of CSS files alongside a Sass file does not cause an error const foundWithoutCss = found.filter((element) => extname(element) !== '.css'); // If the length is zero then there are two or more css files // If the length is more than one than there are two or more sass/scss files if (foundWithoutCss.length !== 1) { throw new Error('Ambiguous import detected.'); } // Return the non-CSS file (sass/scss files have priority) // https://github.com/sass/dart-sass/blob/44d6bb6ac72fe6b93f5bfec371a1fffb18e6b76d/lib/src/importer/utils.dart#L44-L47 return foundWithoutCss[0]; } return found[0]; } } /** * Provides the Sass importer logic to resolve module (npm package) stylesheet imports via both import and * use rules and also rebase any `url()` function usage within those stylesheets. The rebasing will ensure that * the URLs in the output of the Sass compiler reflect the final filesystem location of the output CSS file. */ export class ModuleUrlRebasingImporter extends RelativeUrlRebasingImporter { constructor( entryDirectory: string, directoryCache: Map<string, DirectoryEntry>, rebaseSourceMaps: Map<string, RawSourceMap> | undefined, private finder: (specifier: string, options: CanonicalizeContext) => URL | null, ) { super(entryDirectory, directoryCache, rebaseSourceMaps); } override canonicalize(url: string, options: CanonicalizeContext): URL | null { if (url.startsWith('file://')) { return super.canonicalize(url, options); } let result = this.finder(url, options); result &&= super.canonicalize(result.href, options); return result; } } /** * Provides the Sass importer logic to resolve load paths located stylesheet imports via both import and * use rules and also rebase any `url()` function usage within those stylesheets. The rebasing will ensure that * the URLs in the output of the Sass compiler reflect the final filesystem location of the output CSS file. */
{ "end_byte": 13184, "start_byte": 4905, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/rebasing-importer.ts" }
angular-cli/packages/angular/build/src/tools/sass/rebasing-importer.ts_13185_14383
export class LoadPathsUrlRebasingImporter extends RelativeUrlRebasingImporter { constructor( entryDirectory: string, directoryCache: Map<string, DirectoryEntry>, rebaseSourceMaps: Map<string, RawSourceMap> | undefined, private loadPaths: Iterable<string>, ) { super(entryDirectory, directoryCache, rebaseSourceMaps); } override canonicalize(url: string, options: { fromImport: boolean }): URL | null { if (url.startsWith('file://')) { return super.canonicalize(url, options); } let result = null; for (const loadPath of this.loadPaths) { result = super.canonicalize(pathToFileURL(join(loadPath, url)).href, options); if (result !== null) { break; } } return result; } } /** * Workaround for Sass not calling instance methods with `this`. * The `canonicalize` and `load` methods will be bound to the class instance. * @param importer A Sass importer to bind. * @returns The bound Sass importer. */ export function sassBindWorkaround<T extends Importer>(importer: T): T { importer.canonicalize = importer.canonicalize.bind(importer); importer.load = importer.load.bind(importer); return importer; }
{ "end_byte": 14383, "start_byte": 13185, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/rebasing-importer.ts" }
angular-cli/packages/angular/build/src/tools/sass/lexer_spec.ts_0_912
/** * @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 { findUrls } from './lexer'; describe('Sass URL lexer', () => { it('should find url immediately after a colon, comma, or whitespace', () => { const input = `.c{property:url("first"),url("second"), url("third");}`; const result = [...findUrls(input)]; expect(result).toEqual([ { start: 16, end: 23, value: 'first' }, { start: 29, end: 37, value: 'second' }, { start: 44, end: 51, value: 'third' }, ]); }); it('should find full url with string containing url function', () => { const input = `.c{property:url("url('abc')");}`; const result = [...findUrls(input)]; expect(result).toEqual([{ start: 16, end: 28, value: `url('abc')` }]); }); });
{ "end_byte": 912, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/lexer_spec.ts" }
angular-cli/packages/angular/build/src/tools/sass/worker.ts_0_8674
/** * @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 mergeSourceMaps, { RawSourceMap } from '@ampproject/remapping'; import { dirname } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { MessagePort, receiveMessageOnPort } from 'node:worker_threads'; import { Deprecation, Exception, FileImporter, SourceSpan, StringOptions, compileString, } from 'sass'; import { DirectoryEntry, LoadPathsUrlRebasingImporter, ModuleUrlRebasingImporter, RelativeUrlRebasingImporter, sassBindWorkaround, } from './rebasing-importer'; import type { SerializableDeprecation, SerializableWarningMessage } from './sass-service'; /** * A request to render a Sass stylesheet using the supplied options. */ interface RenderRequestMessage { /** * The contents to compile. */ source: string; /** * The Sass options to provide to the `dart-sass` compile function. */ options: Omit<StringOptions<'sync'>, 'url'> & { url: string }; /** * Indicates the request has a custom importer function on the main thread. */ importerChannel?: { port: MessagePort; signal: Int32Array; }; /** * Indicates the request has a custom logger for warning messages. */ hasLogger: boolean; /** * Indicates paths within url() CSS functions should be rebased. */ rebase: boolean; } interface RenderResult { warnings: SerializableWarningMessage[] | undefined; result: { css: string; loadedUrls: string[]; sourceMap?: RawSourceMap; }; } interface RenderError { warnings: SerializableWarningMessage[] | undefined; error: { message: string; stack?: string; span?: Omit<SourceSpan, 'url'> & { url?: string }; sassMessage?: string; sassStack?: string; }; } export default async function renderSassStylesheet( request: RenderRequestMessage, ): Promise<RenderResult | RenderError> { const { importerChannel, hasLogger, source, options, rebase } = request; const entryDirectory = dirname(options.url); let warnings: SerializableWarningMessage[] | undefined; try { const directoryCache = new Map<string, DirectoryEntry>(); const rebaseSourceMaps = options.sourceMap ? new Map<string, RawSourceMap>() : undefined; if (importerChannel) { // When a custom importer function is present, the importer request must be proxied // back to the main thread where it can be executed. // This process must be synchronous from the perspective of dart-sass. The `Atomics` // functions combined with the shared memory `importSignal` and the Node.js // `receiveMessageOnPort` function are used to ensure synchronous behavior. const proxyImporter: FileImporter<'sync'> = { findFileUrl: (url, { fromImport, containingUrl }) => { Atomics.store(importerChannel.signal, 0, 0); importerChannel.port.postMessage({ url, options: { fromImport, containingUrl: containingUrl ? fileURLToPath(containingUrl) : null, }, }); // Wait for the main thread to set the signal to 1 and notify, which tells // us that a message can be received on the port. // If the main thread is fast, the signal will already be set to 1, and no // sleep/notify is necessary. // However, there can be a race condition here: // - the main thread sets the signal to 1, but does not get to the notify instruction yet // - the worker does not pause because the signal is set to 1 // - the worker very soon enters this method again // - this method sets the signal to 0 and sends the message // - the signal is 0 and so the `Atomics.wait` call blocks // - only now the main thread runs the `notify` from the first invocation, so the // worker continues. // - but there is no message yet in the port, because the thread should not have been // waken up yet. // To combat this, wait for a non-0 value _twice_. // Almost every time, this immediately continues with "not-equal", because // the signal is still set to 1, except during the race condition, when the second // wait will wait for the correct notify. Atomics.wait(importerChannel.signal, 0, 0); Atomics.wait(importerChannel.signal, 0, 0); const result = receiveMessageOnPort(importerChannel.port)?.message as string | null; return result ? pathToFileURL(result) : null; }, }; options.importers = [ rebase ? sassBindWorkaround( new ModuleUrlRebasingImporter( entryDirectory, directoryCache, rebaseSourceMaps, proxyImporter.findFileUrl, ), ) : proxyImporter, ]; } if (rebase && options.loadPaths?.length) { options.importers ??= []; options.importers.push( sassBindWorkaround( new LoadPathsUrlRebasingImporter( entryDirectory, directoryCache, rebaseSourceMaps, options.loadPaths, ), ), ); options.loadPaths = undefined; } let relativeImporter; if (rebase) { relativeImporter = sassBindWorkaround( new RelativeUrlRebasingImporter(entryDirectory, directoryCache, rebaseSourceMaps), ); } // The synchronous Sass render function can be up to two times faster than the async variant const result = compileString(source, { ...options, // URL is not serializable so to convert to string in the parent and back to URL here. url: pathToFileURL(options.url), // The `importer` option (singular) handles relative imports importer: relativeImporter, logger: hasLogger ? { warn(message, warnOptions) { warnings ??= []; warnings.push({ ...warnOptions, message, span: warnOptions.span && convertSourceSpan(warnOptions.span), ...convertDeprecation( warnOptions.deprecation, // eslint-disable-next-line @typescript-eslint/no-explicit-any (warnOptions as any).deprecationType, ), }); }, } : undefined, }); if (result.sourceMap && rebaseSourceMaps?.size) { // Merge the intermediate rebasing source maps into the final Sass generated source map. // Casting is required due to small but compatible differences in typings between the packages. result.sourceMap = mergeSourceMaps( result.sourceMap as unknown as RawSourceMap, // To prevent an infinite lookup loop, skip getting the source when the rebasing source map // is referencing its original self. (file, context) => (file !== context.importer ? rebaseSourceMaps.get(file) : null), ) as unknown as typeof result.sourceMap; } return { warnings, result: { ...result, sourceMap: result.sourceMap as unknown as RawSourceMap | undefined, // URL is not serializable so to convert to string here and back to URL in the parent. loadedUrls: result.loadedUrls.map((p) => fileURLToPath(p)), }, }; } catch (error) { // Needed because V8 will only serialize the message and stack properties of an Error instance. if (error instanceof Exception) { const { span, message, stack, sassMessage, sassStack } = error; return { warnings, error: { span: convertSourceSpan(span), message, stack, sassMessage, sassStack, }, }; } else if (error instanceof Error) { const { message, stack } = error; return { warnings, error: { message, stack } }; } else { return { warnings, error: { message: 'An unknown error has occurred.' }, }; } } } /** * Converts a Sass SourceSpan object into a serializable form. * The SourceSpan object contains a URL property which must be converted into a string. * Also, most of the interface's properties are get accessors and are not automatically * serialized when sent back from the worker. * * @param span The Sass SourceSpan object to convert. * @returns A serializable form of the SourceSpan object. */
{ "end_byte": 8674, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/worker.ts" }
angular-cli/packages/angular/build/src/tools/sass/worker.ts_8675_9906
function convertSourceSpan(span: SourceSpan): Omit<SourceSpan, 'url'> & { url?: string } { return { text: span.text, context: span.context, end: { column: span.end.column, offset: span.end.offset, line: span.end.line, }, start: { column: span.start.column, offset: span.start.offset, line: span.start.line, }, url: span.url ? fileURLToPath(span.url) : undefined, }; } function convertDeprecation( deprecation: boolean, deprecationType: Deprecation | undefined, ): { deprecation: false } | { deprecation: true; deprecationType: SerializableDeprecation } { if (!deprecation || !deprecationType) { return { deprecation: false }; } const { obsoleteIn, deprecatedIn, ...rest } = deprecationType; return { deprecation: true, deprecationType: { ...rest, obsoleteIn: obsoleteIn ? { major: obsoleteIn.major, minor: obsoleteIn.minor, patch: obsoleteIn.patch, } : null, deprecatedIn: deprecatedIn ? { major: deprecatedIn.major, minor: deprecatedIn.minor, patch: deprecatedIn.patch, } : null, }, }; }
{ "end_byte": 9906, "start_byte": 8675, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/sass/worker.ts" }