_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/ngtools/webpack/src/ivy/host.ts_0_8869
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/unbound-method */ import type { CompilerHost } from '@angular/compiler-cli'; import { createHash } from 'crypto'; import * as path from 'path'; import * as ts from 'typescript'; import { WebpackResourceLoader } from '../resource_loader'; import { normalizePath } from './paths'; export function augmentHostWithResources( host: ts.CompilerHost, resourceLoader: WebpackResourceLoader, options: { directTemplateLoading?: boolean; inlineStyleFileExtension?: string; } = {}, ) { const resourceHost = host as CompilerHost; resourceHost.readResource = function (fileName: string) { const filePath = normalizePath(fileName); if ( options.directTemplateLoading && (filePath.endsWith('.html') || filePath.endsWith('.svg')) ) { const content = this.readFile(filePath); if (content === undefined) { throw new Error('Unable to locate component resource: ' + fileName); } resourceLoader.setAffectedResources(filePath, [filePath]); return content; } else { return resourceLoader.get(filePath); } }; resourceHost.resourceNameToFileName = function (resourceName: string, containingFile: string) { return path.join(path.dirname(containingFile), resourceName); }; resourceHost.getModifiedResourceFiles = function () { return resourceLoader.getModifiedResourceFiles(); }; resourceHost.transformResource = async function (data, context) { // Only inline style resources are supported currently if (context.resourceFile || context.type !== 'style') { return null; } if (options.inlineStyleFileExtension) { const content = await resourceLoader.process( data, options.inlineStyleFileExtension, context.type, context.containingFile, ); return { content }; } return null; }; } function augmentResolveModuleNames( host: ts.CompilerHost, resolvedModuleModifier: ( resolvedModule: ts.ResolvedModule | undefined, moduleName: string, ) => ts.ResolvedModule | undefined, moduleResolutionCache?: ts.ModuleResolutionCache, ): void { if (host.resolveModuleNames) { const baseResolveModuleNames = host.resolveModuleNames; host.resolveModuleNames = function (moduleNames: string[], ...parameters) { return moduleNames.map((name) => { const result = baseResolveModuleNames.call(host, [name], ...parameters); return resolvedModuleModifier(result[0], name); }); }; } else { host.resolveModuleNames = function ( moduleNames: string[], containingFile: string, _reusedNames: string[] | undefined, redirectedReference: ts.ResolvedProjectReference | undefined, options: ts.CompilerOptions, ) { return moduleNames.map((name) => { const result = ts.resolveModuleName( name, containingFile, options, host, moduleResolutionCache, redirectedReference, ).resolvedModule; return resolvedModuleModifier(result, name); }); }; } } /** * Augments a TypeScript Compiler Host's resolveModuleNames function to collect dependencies * of the containing file passed to the resolveModuleNames function. This process assumes * that consumers of the Compiler Host will only call resolveModuleNames with modules that are * actually present in a containing file. * This process is a workaround for gathering a TypeScript SourceFile's dependencies as there * is no currently exposed public method to do so. A BuilderProgram does have a `getAllDependencies` * function. However, that function returns all transitive dependencies as well which can cause * excessive Webpack rebuilds. * * @param host The CompilerHost to augment. * @param dependencies A Map which will be used to store file dependencies. * @param moduleResolutionCache An optional resolution cache to use when the host resolves a module. */ export function augmentHostWithDependencyCollection( host: ts.CompilerHost, dependencies: Map<string, Set<string>>, moduleResolutionCache?: ts.ModuleResolutionCache, ): void { if (host.resolveModuleNames) { const baseResolveModuleNames = host.resolveModuleNames; host.resolveModuleNames = function ( moduleNames: string[], containingFile: string, ...parameters ) { const results = baseResolveModuleNames.call(host, moduleNames, containingFile, ...parameters); const containingFilePath = normalizePath(containingFile); for (const result of results) { if (result) { const containingFileDependencies = dependencies.get(containingFilePath); if (containingFileDependencies) { containingFileDependencies.add(result.resolvedFileName); } else { dependencies.set(containingFilePath, new Set([result.resolvedFileName])); } } } return results; }; } else { host.resolveModuleNames = function ( moduleNames: string[], containingFile: string, _reusedNames: string[] | undefined, redirectedReference: ts.ResolvedProjectReference | undefined, options: ts.CompilerOptions, ) { return moduleNames.map((name) => { const result = ts.resolveModuleName( name, containingFile, options, host, moduleResolutionCache, redirectedReference, ).resolvedModule; if (result) { const containingFilePath = normalizePath(containingFile); const containingFileDependencies = dependencies.get(containingFilePath); if (containingFileDependencies) { containingFileDependencies.add(result.resolvedFileName); } else { dependencies.set(containingFilePath, new Set([result.resolvedFileName])); } } return result; }); }; } } export function augmentHostWithReplacements( host: ts.CompilerHost, replacements: Record<string, string>, moduleResolutionCache?: ts.ModuleResolutionCache, ): void { if (Object.keys(replacements).length === 0) { return; } const normalizedReplacements: Record<string, string> = {}; for (const [key, value] of Object.entries(replacements)) { normalizedReplacements[normalizePath(key)] = normalizePath(value); } const tryReplace = (resolvedModule: ts.ResolvedModule | undefined) => { const replacement = resolvedModule && normalizedReplacements[resolvedModule.resolvedFileName]; if (replacement) { return { resolvedFileName: replacement, isExternalLibraryImport: /[/\\]node_modules[/\\]/.test(replacement), }; } else { return resolvedModule; } }; augmentResolveModuleNames(host, tryReplace, moduleResolutionCache); } export function augmentHostWithSubstitutions( host: ts.CompilerHost, substitutions: Record<string, string>, ): void { const regexSubstitutions: [RegExp, string][] = []; for (const [key, value] of Object.entries(substitutions)) { regexSubstitutions.push([new RegExp(`\\b${key}\\b`, 'g'), value]); } if (regexSubstitutions.length === 0) { return; } const baseReadFile = host.readFile; host.readFile = function (...parameters) { let file: string | undefined = baseReadFile.call(host, ...parameters); if (file) { for (const entry of regexSubstitutions) { file = file.replace(entry[0], entry[1]); } } return file; }; } export function augmentProgramWithVersioning(program: ts.Program): void { const baseGetSourceFiles = program.getSourceFiles; program.getSourceFiles = function (...parameters) { const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles( ...parameters, ); for (const file of files) { if (file.version === undefined) { file.version = createHash('sha256').update(file.text).digest('hex'); } } return files; }; } export function augmentHostWithCaching( host: ts.CompilerHost, cache: Map<string, ts.SourceFile>, ): void { const baseGetSourceFile = host.getSourceFile; host.getSourceFile = function ( fileName, languageVersion, onError, shouldCreateNewSourceFile, ...parameters ) { if (!shouldCreateNewSourceFile && cache.has(fileName)) { return cache.get(fileName); } const file = baseGetSourceFile.call( host, fileName, languageVersion, onError, true, ...parameters, ); if (file) { cache.set(fileName, file); } return file; }; }
{ "end_byte": 8869, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/host.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/index.ts_0_414
/** * @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 { angularWebpackLoader as default } from './loader'; export { type AngularWebpackPluginOptions, AngularWebpackPlugin, imageDomains } from './plugin'; export const AngularWebpackLoaderPath = __filename;
{ "end_byte": 414, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/index.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/paths.ts_0_1031
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as nodePath from 'path'; const normalizationCache = new Map<string, string>(); export function normalizePath(path: string): string { let result = normalizationCache.get(path); if (result === undefined) { result = nodePath.win32.normalize(path).replace(/\\/g, nodePath.posix.sep); normalizationCache.set(path, result); } return result; } const externalizationCache = new Map<string, string>(); function externalizeForWindows(path: string): string { let result = externalizationCache.get(path); if (result === undefined) { result = nodePath.win32.normalize(path); externalizationCache.set(path, result); } return result; } export const externalizePath = (() => { if (process.platform !== 'win32') { return (path: string) => path; } return externalizeForWindows; })();
{ "end_byte": 1031, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/paths.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/system.ts_0_2678
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as ts from 'typescript'; import { Compiler } from 'webpack'; import { externalizePath } from './paths'; export type InputFileSystem = NonNullable<Compiler['inputFileSystem']>; export interface InputFileSystemSync extends InputFileSystem { readFileSync: NonNullable<InputFileSystem['readFileSync']>; statSync: NonNullable<InputFileSystem['statSync']>; } function shouldNotWrite(): never { throw new Error('Webpack TypeScript System should not write.'); } export function createWebpackSystem( input: InputFileSystemSync, currentDirectory: string, ): ts.System { // Webpack's CachedInputFileSystem uses the default directory separator in the paths it uses // for keys to its cache. If the keys do not match then the file watcher will not purge outdated // files and cause stale data to be used in the next rebuild. TypeScript always uses a `/` (POSIX) // directory separator internally which is also supported with Windows system APIs. However, // if file operations are performed with the non-default directory separator, the Webpack cache // will contain a key that will not be purged. `externalizePath` ensures the paths are as expected. const system: ts.System = { ...ts.sys, readFile(path: string) { let data; try { data = input.readFileSync(externalizePath(path)); } catch { return undefined; } // Strip BOM if present let start = 0; if (data.length > 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) { start = 3; } return data.toString('utf8', start); }, getFileSize(path: string) { try { return input.statSync(externalizePath(path)).size; } catch { return 0; } }, fileExists(path: string) { try { return input.statSync(externalizePath(path)).isFile(); } catch { return false; } }, directoryExists(path: string) { try { return input.statSync(externalizePath(path)).isDirectory(); } catch { return false; } }, getModifiedTime(path: string) { try { return input.statSync(externalizePath(path)).mtime; } catch { return undefined; } }, getCurrentDirectory() { return currentDirectory; }, writeFile: shouldNotWrite, createDirectory: shouldNotWrite, deleteFile: shouldNotWrite, setModifiedTime: shouldNotWrite, }; return system; }
{ "end_byte": 2678, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/system.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/transformation.ts_0_5392
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as ts from 'typescript'; import { elideImports } from '../transformers/elide_imports'; import { findImageDomains } from '../transformers/find_image_domains'; import { removeIvyJitSupportCalls } from '../transformers/remove-ivy-jit-support-calls'; import { replaceResources } from '../transformers/replace_resources'; export function createAotTransformers( builder: ts.BuilderProgram, options: { emitClassMetadata?: boolean; emitNgModuleScope?: boolean; emitSetClassDebugInfo?: boolean; }, imageDomains: Set<string>, ): ts.CustomTransformers { const getTypeChecker = () => builder.getProgram().getTypeChecker(); const transformers: ts.CustomTransformers = { before: [findImageDomains(imageDomains), replaceBootstrap(getTypeChecker)], after: [], }; const removeClassMetadata = !options.emitClassMetadata; const removeNgModuleScope = !options.emitNgModuleScope; const removeSetClassDebugInfo = !options.emitSetClassDebugInfo; if (removeClassMetadata || removeNgModuleScope || removeSetClassDebugInfo) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion transformers.before!.push( removeIvyJitSupportCalls( removeClassMetadata, removeNgModuleScope, removeSetClassDebugInfo, getTypeChecker, ), ); } return transformers; } export function createJitTransformers( builder: ts.BuilderProgram, compilerCli: typeof import('@angular/compiler-cli/private/tooling'), options: { inlineStyleFileExtension?: string; }, ): ts.CustomTransformers { const getTypeChecker = () => builder.getProgram().getTypeChecker(); return { before: [ replaceResources(() => true, getTypeChecker, options.inlineStyleFileExtension), compilerCli.constructorParametersDownlevelTransform(builder.getProgram()), ], }; } export function mergeTransformers( first: ts.CustomTransformers, second: ts.CustomTransformers, ): ts.CustomTransformers { const result: ts.CustomTransformers = {}; if (first.before || second.before) { result.before = [...(first.before || []), ...(second.before || [])]; } if (first.after || second.after) { result.after = [...(first.after || []), ...(second.after || [])]; } if (first.afterDeclarations || second.afterDeclarations) { result.afterDeclarations = [ ...(first.afterDeclarations || []), ...(second.afterDeclarations || []), ]; } return result; } /** * The name of the Angular platform that should be replaced within * bootstrap call expressions to support AOT. */ const PLATFORM_BROWSER_DYNAMIC_NAME = 'platformBrowserDynamic'; export function replaceBootstrap( getTypeChecker: () => ts.TypeChecker, ): ts.TransformerFactory<ts.SourceFile> { return (context: ts.TransformationContext) => { let bootstrapImport: ts.ImportDeclaration | undefined; let bootstrapNamespace: ts.Identifier | undefined; const replacedNodes: ts.Node[] = []; const nodeFactory = context.factory; const visitNode: ts.Visitor = (node: ts.Node) => { if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) { const target = node.expression; if (target.text === PLATFORM_BROWSER_DYNAMIC_NAME) { if (!bootstrapNamespace) { bootstrapNamespace = nodeFactory.createUniqueName('__NgCli_bootstrap_'); bootstrapImport = nodeFactory.createImportDeclaration( undefined, nodeFactory.createImportClause( false, undefined, nodeFactory.createNamespaceImport(bootstrapNamespace), ), nodeFactory.createStringLiteral('@angular/platform-browser'), ); } replacedNodes.push(target); return nodeFactory.updateCallExpression( node, nodeFactory.createPropertyAccessExpression(bootstrapNamespace, 'platformBrowser'), node.typeArguments, node.arguments, ); } } return ts.visitEachChild(node, visitNode, context); }; return (sourceFile: ts.SourceFile) => { if (!sourceFile.text.includes(PLATFORM_BROWSER_DYNAMIC_NAME)) { return sourceFile; } let updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context); if (bootstrapImport) { // Remove any unused platform browser dynamic imports const removals = elideImports( updatedSourceFile, replacedNodes, getTypeChecker, context.getCompilerOptions(), ); if (removals.size > 0) { updatedSourceFile = ts.visitEachChild( updatedSourceFile, (node) => (removals.has(node) ? undefined : node), context, ); } // Add new platform browser import return nodeFactory.updateSourceFile( updatedSourceFile, ts.setTextRange( nodeFactory.createNodeArray([bootstrapImport, ...updatedSourceFile.statements]), sourceFile.statements, ), ); } else { return updatedSourceFile; } }; }; }
{ "end_byte": 5392, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/transformation.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls.ts_0_3979
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as ts from 'typescript'; import { elideImports } from './elide_imports'; export function removeIvyJitSupportCalls( classMetadata: boolean, ngModuleScope: boolean, debugInfo: boolean, getTypeChecker: () => ts.TypeChecker, ): ts.TransformerFactory<ts.SourceFile> { return (context: ts.TransformationContext) => { const removedNodes: ts.Node[] = []; const visitNode: ts.Visitor = (node: ts.Node) => { const innerExpression = ts.isExpressionStatement(node) ? getIifeExpression(node) : null; if (innerExpression) { if ( ngModuleScope && ts.isBinaryExpression(innerExpression) && isIvyPrivateCallExpression(innerExpression.right, 'ɵɵsetNgModuleScope') ) { removedNodes.push(innerExpression); return undefined; } if (classMetadata) { const expression = ts.isBinaryExpression(innerExpression) ? innerExpression.right : innerExpression; if ( isIvyPrivateCallExpression(expression, 'ɵsetClassMetadata') || isIvyPrivateCallExpression(expression, 'ɵsetClassMetadataAsync') ) { removedNodes.push(innerExpression); return undefined; } } if ( debugInfo && ts.isBinaryExpression(innerExpression) && isIvyPrivateCallExpression(innerExpression.right, 'ɵsetClassDebugInfo') ) { removedNodes.push(innerExpression); return undefined; } } return ts.visitEachChild(node, visitNode, context); }; return (sourceFile: ts.SourceFile) => { let updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context); if (removedNodes.length > 0) { // Remove any unused imports const importRemovals = elideImports( updatedSourceFile, removedNodes, getTypeChecker, context.getCompilerOptions(), ); if (importRemovals.size > 0) { updatedSourceFile = ts.visitEachChild( updatedSourceFile, function visitForRemoval(node): ts.Node | undefined { return importRemovals.has(node) ? undefined : ts.visitEachChild(node, visitForRemoval, context); }, context, ); } } return updatedSourceFile; }; }; } // Each Ivy private call expression is inside an IIFE function getIifeExpression(exprStmt: ts.ExpressionStatement): null | ts.Expression { const expression = exprStmt.expression; if (!expression || !ts.isCallExpression(expression) || expression.arguments.length !== 0) { return null; } const parenExpr = expression; if (!ts.isParenthesizedExpression(parenExpr.expression)) { return null; } const funExpr = parenExpr.expression.expression; if (!ts.isFunctionExpression(funExpr) && !ts.isArrowFunction(funExpr)) { return null; } if (!ts.isBlock(funExpr.body)) { return funExpr.body; } const innerStmts = funExpr.body.statements; if (innerStmts.length !== 1) { return null; } const innerExprStmt = innerStmts[0]; if (!ts.isExpressionStatement(innerExprStmt)) { return null; } return innerExprStmt.expression; } function isIvyPrivateCallExpression(expression: ts.Expression, name: string) { // Now we're in the IIFE and have the inner expression statement. We can check if it matches // a private Ivy call. if (!ts.isCallExpression(expression)) { return false; } const propAccExpr = expression.expression; if (!ts.isPropertyAccessExpression(propAccExpr)) { return false; } if (propAccExpr.name.text !== name) { return false; } return true; }
{ "end_byte": 3979, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/find_image_domains_spec.ts_0_8468
/** * @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 { tags } from '@angular-devkit/core'; import * as ts from 'typescript'; import { findImageDomains } from './find_image_domains'; import { createTypescriptContext, transformTypescript } from './spec_helpers'; function findDomains( input: string, importHelpers = true, module: ts.ModuleKind = ts.ModuleKind.ES2020, ) { const { program, compilerHost } = createTypescriptContext(input, undefined, undefined, { importHelpers, module, }); const domains = new Set<string>(); const transformer = findImageDomains(domains); transformTypescript(input, [transformer], program, compilerHost); return domains; } function inputTemplateAppModule(provider: string) { /* eslint-disable max-len */ return tags.stripIndent` export class AppModule { static ɵfac = function AppModule_Factory(t) { return new (t || AppModule)(); }; static ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); static ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ providers: [ ${provider} ], imports: [BrowserModule] }); } (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent ], imports: [ BrowserModule, NgOptimizedImage ], providers: [ ${provider} ], bootstrap: [AppComponent] }] }], null, null); })(); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent], imports: [BrowserModule, NgOptimizedImage] }); })(); `; } function inputTemplateComponent(provider: string) { /* eslint-disable max-len */ return tags.stripIndent` export class AppComponent { title = 'angular-cli-testbed'; static ɵfac = function AppComponent_Factory(t) { return new (t || AppComponent)(); }; static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: AppComponent, selectors: [["app-root"]], standalone: true, features: [i0.ɵɵProvidersFeature([ ${provider} ]), i0.ɵɵStandaloneFeature], decls: 2, vars: 0, template: function AppComponent_Template(rf, ctx) { if (rf & 1) { i0.ɵɵelementStart(0, "div"); i0.ɵɵtext(1, "Hello world"); i0.ɵɵelementEnd(); } } }); } (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(AppComponent, [{ type: Component, args: [{ selector: 'app-root', imports: [NgOptimizedImage, NgSwitchCase, NgSwitchDefault, NgSwitch], standalone: true, providers: [ ${provider} ], template: "<div>Hello world</div>\n\n" }] }], null, null); })(); `; } function runSharedTests(template: (povider: string) => string) { it('should find a domain when a built-in loader is used with a string-literal-like argument', () => { // Intentionally inconsistent use of quote styles in this data structure: const builtInLoaders: Array<[string, string]> = [ ['provideCloudflareLoader("www.cloudflaredomain.com")', 'www.cloudflaredomain.com'], [ "provideCloudinaryLoader('https://www.cloudinarydomain.net')", 'https://www.cloudinarydomain.net', ], ['provideImageKitLoader("www.imageKitdomain.com")', 'www.imageKitdomain.com'], ['provideImgixLoader(`www.imgixdomain.com/images/`)', 'www.imgixdomain.com/images/'], ]; for (const loader of builtInLoaders) { const input = template(loader[0]); const result = Array.from(findDomains(input)); expect(result.length).toBe(1); expect(result[0]).toBe(loader[1]); } }); it('should find a domain in a custom loader function with a template literal', () => { const customLoader = tags.stripIndent` { provide: IMAGE_LOADER, useValue: (config: ImageLoaderConfig) => { return ${'`https://customLoaderTemplate.com/images?src=${config.src}&width=${config.width}`'}; }, },`; const input = template(customLoader); const result = Array.from(findDomains(input)); expect(result.length).toBe(1); expect(result[0]).toBe('https://customLoaderTemplate.com/'); }); it('should find a domain when provider is alongside other providers', () => { const customLoader = tags.stripIndent` { provide: SOME_OTHER_PROVIDER, useValue: (config: ImageLoaderConfig) => { return "https://notacustomloaderstring.com/images?src=" + config.src + "&width=" + config.width; }, }, provideNotARealLoader("https://www.foo.com"), { provide: IMAGE_LOADER, useValue: (config: ImageLoaderConfig) => { return ${'`https://customloadertemplate.com/images?src=${config.src}&width=${config.width}`'}; }, }, { provide: YET_ANOTHER_PROVIDER, useValue: (config: ImageLoaderConfig) => { return ${'`https://notacustomloadertemplate.com/images?src=${config.src}&width=${config.width}`'}; }, },`; const input = template(customLoader); const result = Array.from(findDomains(input)); expect(result.length).toBe(1); expect(result[0]).toBe('https://customloadertemplate.com/'); }); } describe('@ngtools/webpack transformers', () => { describe('find_image_domains (app module)', () => { runSharedTests(inputTemplateAppModule); runSharedTests(inputTemplateComponent); it('should not find a domain when a built-in loader is used with a variable', () => { const input = inputTemplateAppModule(`provideCloudflareLoader(myImageCDN)`); const result = Array.from(findDomains(input)); expect(result.length).toBe(0); }); it('should not find a domain when a built-in loader is used with an expression', () => { const input = inputTemplateAppModule( `provideCloudflareLoader("https://www." + (dev ? "dev." : "") + "cloudinarydomain.net")`, ); const result = Array.from(findDomains(input)); expect(result.length).toBe(0); }); it('should not find a domain when a built-in loader is used with a template literal', () => { const input = inputTemplateAppModule( 'provideCloudflareLoader(`https://www.${dev ? "dev." : ""}cloudinarydomain.net`)', ); const result = Array.from(findDomains(input)); expect(result.length).toBe(0); }); it('should not find a domain in a function that is not a built-in loader', () => { const input = inputTemplateAppModule('provideNotARealLoader("https://www.foo.com")'); const result = Array.from(findDomains(input)); expect(result.length).toBe(0); }); it('should find a domain in a custom loader function with string concatenation', () => { const customLoader = tags.stripIndent` { provide: IMAGE_LOADER, useValue: (config: ImageLoaderConfig) => { return "https://customLoaderString.com/images?src=" + config.src + "&width=" + config.width; }, },`; const input = inputTemplateAppModule(customLoader); const result = Array.from(findDomains(input)); expect(result.length).toBe(1); expect(result[0]).toBe('https://customLoaderString.com/'); }); it('should not find a domain if not an IMAGE_LOADER provider', () => { const customLoader = tags.stripIndent` { provide: SOME_OTHER_PROVIDER, useValue: (config: ImageLoaderConfig) => { return "https://customLoaderString.com/images?src=" + config.src + "&width=" + config.width; }, },`; const input = inputTemplateAppModule(customLoader); const result = Array.from(findDomains(input)); expect(result.length).toBe(0); }); }); });
{ "end_byte": 8468, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/find_image_domains_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts_0_899
/** * @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 { tags } from '@angular-devkit/core'; import * as ts from 'typescript'; import { replaceResources } from './replace_resources'; import { createTypescriptContext, transformTypescript } from './spec_helpers'; function transform( input: string, shouldTransform = true, importHelpers = true, module: ts.ModuleKind = ts.ModuleKind.ES2020, ) { const { program, compilerHost } = createTypescriptContext(input, undefined, undefined, { importHelpers, module, }); const getTypeChecker = () => program.getTypeChecker(); const transformer = replaceResources(() => shouldTransform, getTypeChecker); return transformTypescript(input, [transformer], program, compilerHost); }
{ "end_byte": 899, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts_901_10209
describe('@ngtools/webpack transformers', () => { /* eslint-disable max-len */ describe('find_resources', () => { it('should replace resources', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', './app.component.2.css'] }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import __NG_CLI_RESOURCE__2 from "./app.component.2.css?ngResource"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: [__NG_CLI_RESOURCE__1, __NG_CLI_RESOURCE__2] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should replace resources with `require()` when module is CommonJs', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', './app.component.2.css'] }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AppComponent = void 0; const tslib_1 = require("tslib"); const core_1 = require("@angular/core"); let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; exports.AppComponent = AppComponent; exports.AppComponent = AppComponent = tslib_1.__decorate([ (0, core_1.Component)({ selector: 'app-root', template: require("./app.component.html?ngResource"), styles: [require("./app.component.css?ngResource"), require("./app.component.2.css?ngResource")] }) ], AppComponent); `; const result = transform(input, true, true, ts.ModuleKind.CommonJS); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should should support svg as templates', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.svg' }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.svg?ngResource"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0 }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should merge styleUrls with styles', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styles: ['a { color: red }'], styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: ["a { color: red }", __NG_CLI_RESOURCE__1] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should replace resources with backticks', () => { const input = ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: \`./app.component.html\`, styleUrls: [\`./app.component.css\`, \`./app.component.2.css\`] }) export class AppComponent { title = 'app'; } `; const output = ` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import __NG_CLI_RESOURCE__2 from "./app.component.2.css?ngResource"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: [__NG_CLI_RESOURCE__1, __NG_CLI_RESOURCE__2] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should replace resources if Component decorator is aliased', () => { const input = tags.stripIndent` import { Component as NgComponent } from '@angular/core'; @NgComponent({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', './app.component.2.css'] }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import __NG_CLI_RESOURCE__2 from "./app.component.2.css?ngResource"; import { Component as NgComponent } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ NgComponent({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: [__NG_CLI_RESOURCE__1, __NG_CLI_RESOURCE__2] }) ], AppComponent); export { AppComponent }; `; const { program } = createTypescriptContext(input); const getTypeChecker = () => program.getTypeChecker(); const transformer = replaceResources(() => true, getTypeChecker); const result = transformTypescript(input, [transformer]); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should replace resources if Angular Core import is namespaced', () => { const input = tags.stripIndent` import * as ng from '@angular/core'; @ng.Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', './app.component.2.css'] }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import __NG_CLI_RESOURCE__2 from "./app.component.2.css?ngResource"; import * as ng from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ ng.Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: [__NG_CLI_RESOURCE__1, __NG_CLI_RESOURCE__2] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); });
{ "end_byte": 10209, "start_byte": 901, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts_10215_15375
it('should replace resources specified as string literals', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styles: 'h2 {font-size: 10px}', styleUrl: './app.component.css' }) export class AppComponent { title = 'app'; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: ["h2 {font-size: 10px}", __NG_CLI_RESOURCE__1] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not replace resources if not in Component decorator', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { obj = [ { 'labels': 'Content', 'templateUrl': 'content.html' } ]; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import __NG_CLI_RESOURCE__0 from "./app.component.html?ngResource"; import __NG_CLI_RESOURCE__1 from "./app.component.css?ngResource"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.obj = [ { 'labels': 'Content', 'templateUrl': 'content.html' } ]; } }; AppComponent = __decorate([ Component({ selector: 'app-root', template: __NG_CLI_RESOURCE__0, styles: [__NG_CLI_RESOURCE__1] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not replace resources if not in an NG Component decorator', () => { const input = tags.stripIndent` import { Component } from 'foo'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { obj = [ { 'labels': 'Content', 'templateUrl': 'content.html' } ]; } `; const output = tags.stripIndent` import { __decorate } from "tslib"; import { Component } from 'foo'; let AppComponent = class AppComponent { constructor() { this.obj = [ { 'labels': 'Content', 'templateUrl': 'content.html' } ]; } }; AppComponent = __decorate([ Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) ], AppComponent); export { AppComponent }; `; const result = transform(input); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not replace resources if shouldTransform returns false', () => { const input = tags.stripIndent` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', './app.component.2.css'] }) export class AppComponent { title = 'app'; } `; const output = ` import { __decorate } from "tslib"; import { Component } from '@angular/core'; let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; AppComponent = __decorate([ Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', './app.component.2.css'] }) ], AppComponent); export { AppComponent }; `; const result = transform(input, false); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); }); });
{ "end_byte": 15375, "start_byte": 10215, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts_0_438
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable max-len */ import { tags } from '@angular-devkit/core'; import * as ts from 'typescript'; import { elideImports } from './elide_imports'; import { createTypescriptContext, transformTypescript } from './spec_helpers';
{ "end_byte": 438, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts_440_9834
describe('@ngtools/webpack transformers', () => { describe('elide_imports', () => { const dummyNode = `const remove = ''`; // Transformer that removes the last node and then elides unused imports const transformer = (program: ts.Program) => { return (context: ts.TransformationContext) => { return (sourceFile: ts.SourceFile) => { const lastNode = sourceFile.statements[sourceFile.statements.length - 1]; const updatedSourceFile = context.factory.updateSourceFile( sourceFile, ts.setTextRange( context.factory.createNodeArray(sourceFile.statements.slice(0, -1)), sourceFile.statements, ), ); const importRemovals = elideImports( updatedSourceFile, [lastNode], () => program.getTypeChecker(), context.getCompilerOptions(), ); if (importRemovals.size > 0) { return ts.visitEachChild( updatedSourceFile, function visitForRemoval(node): ts.Node | undefined { return importRemovals.has(node) ? undefined : ts.visitEachChild(node, visitForRemoval, context); }, context, ); } return updatedSourceFile; }; }; }; const additionalFiles: Record<string, string> = { 'const.ts': ` export const animations = []; export const promise = () => null; export const take = () => null; export default promise; `, 'decorator.ts': ` export function Decorator(value?: any): any { return function (): any { }; } `, 'service.ts': ` export class Service { } export class Service2 { } `, 'type.ts': ` export interface OnChanges { ngOnChanges(changes: SimpleChanges): void; } export interface SimpleChanges { [propName: string]: unknown; } `, 'jsx.ts': ` export function createElement() {} `, }; it('should remove unused imports', () => { const input = tags.stripIndent` import { promise } from './const'; import { take } from './const'; const unused = promise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual('export {};'); }); it('should remove unused aliased imports', () => { const input = tags.stripIndent` import { promise as fromPromise } from './const'; const unused = fromPromise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual('export {};'); }); it('should retain used aliased imports', () => { const input = tags.stripIndent` import { promise as fromPromise } from './const'; const used = fromPromise; ${dummyNode} `; const output = tags.stripIndent` import { promise as fromPromise } from './const'; const used = fromPromise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should retain used namespaced imports', () => { const input = tags.stripIndent` import * as namespaced from './const'; const used = namespaced; ${dummyNode} `; const output = tags.stripIndent` import * as namespaced from './const'; const used = namespaced; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should drop unused namespaced imports', () => { const input = tags.stripIndent` import * as namespaced from './const'; const used = namespaced; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual('export {};'); }); it('should drop unused imports in export specifier', () => { const input = tags.stripIndent` import { promise as fromPromise } from './const'; export { fromPromise }; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual('export {};'); }); it('should retain used imports in export specifier', () => { const input = tags.stripIndent` import { promise as fromPromise } from './const'; export { fromPromise }; ${dummyNode} `; const output = tags.stripIndent` import { promise as fromPromise } from './const'; export { fromPromise }; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should drop unused in shorthand property assignment', () => { const input = tags.stripIndent` import { promise as fromPromise } from './const'; const unused = { fromPromise }; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual('export {};'); }); it('should retain used imports in shorthand property assignment', () => { const input = tags.stripIndent` import { promise as fromPromise } from './const'; const used = { fromPromise }; ${dummyNode} `; const output = tags.stripIndent` import { promise as fromPromise } from './const'; const used = { fromPromise }; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should drop unused default import', () => { const input = tags.stripIndent` import defaultPromise from './const'; const unused = defaultPromise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual('export {};'); }); it('should retain used default import', () => { const input = tags.stripIndent` import defaultPromise from './const'; const used = defaultPromise; ${dummyNode} `; const output = tags.stripIndent` import defaultPromise from './const'; const used = defaultPromise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should only drop unused default imports when named and default (1)', () => { const input = tags.stripIndent` import promise, { promise as fromPromise } from './const'; const used = fromPromise; const unused = promise; `; const output = tags.stripIndent` import { promise as fromPromise } from './const'; const used = fromPromise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should only drop unused named imports when named and default (2)', () => { const input = tags.stripIndent` import promise, { promise as fromPromise, take } from './const'; const used = fromPromise; const unused = promise; `; const output = tags.stripIndent` import { promise as fromPromise } from './const'; const used = fromPromise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); });
{ "end_byte": 9834, "start_byte": 440, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts_9840_15481
it('should only drop default imports when having named and default (3)', () => { const input = tags.stripIndent` import promise, { promise as fromPromise } from './const'; const used = promise; const unused = fromPromise; `; const output = tags.stripIndent` import promise from './const'; const used = promise; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should retain import clause', () => { const input = tags.stripIndent` import './const'; ${dummyNode} `; const output = tags.stripIndent` import './const'; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it(`should remove import for 'ExpressionWithTypeArguments' implements token`, () => { const input = tags.stripIndent` import { Bar, Buz, Unused } from './bar'; export class Foo extends Bar implements Buz { } ${dummyNode} `; const output = tags.stripIndent` import { Bar } from './bar'; export class Foo extends Bar { } `; const { program, compilerHost } = createTypescriptContext(input); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); describe('should elide imports decorator type references when emitDecoratorMetadata is false', () => { const extraCompilerOptions: ts.CompilerOptions = { emitDecoratorMetadata: false, experimentalDecorators: true, }; it('should remove ctor parameter type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; @Decorator() export class Foo { constructor(param: Service) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate } from "tslib"; import { Decorator } from './decorator'; let Foo = class Foo { constructor(param) { } }; Foo = __decorate([ Decorator() ], Foo); export { Foo }; `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove ctor parameter type reference and unused named import from same declaration', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service, Service2 as ServiceUnused } from './service'; @Decorator() export class Foo { constructor(param: Service) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate } from "tslib"; import { Decorator } from './decorator'; let Foo = class Foo { constructor(param) { } }; Foo = __decorate([ Decorator() ], Foo); export { Foo }; `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); }); it('keeps jsxFactory imports when configured', () => { const extraCompilerOptions: ts.CompilerOptions = { jsxFactory: 'createElement', experimentalDecorators: true, jsx: ts.JsxEmit.React, }; const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; import { createElement } from './jsx'; const test = <p>123</p>; @Decorator() export class Foo { constructor(param: Service) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate } from "tslib"; import { Decorator } from './decorator'; import { createElement } from './jsx'; const test = createElement("p", null, "123"); let Foo = class Foo { constructor(param) { } }; Foo = __decorate([ Decorator() ], Foo); export { Foo }; `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, true, ); const result = transformTypescript(undefined, [transformer(program)], program, compilerHost); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); describe('should not elide imports decorator type references when emitDecoratorMetadata is true',
{ "end_byte": 15481, "start_byte": 9840, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts_15482_25271
() => { const extraCompilerOptions: ts.CompilerOptions = { emitDecoratorMetadata: true, experimentalDecorators: true, }; it('should elide type only named imports', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { type OnChanges, type SimpleChanges } from './type'; @Decorator() export class Foo implements OnChanges { ngOnChanges(changes: SimpleChanges) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate } from "tslib"; import { Decorator } from './decorator'; let Foo = class Foo { ngOnChanges(changes) { } }; Foo = __decorate([ Decorator() ], Foo); export { Foo }; `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not remove ctor parameter type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; @Decorator() export class Foo { constructor(param: Service) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; let Foo = class Foo { constructor(param) { } }; Foo = __decorate([ Decorator(), __metadata("design:paramtypes", [Service]) ], Foo); export { Foo }; `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not remove property declaration parameter type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { @Decorator() foo: Service; } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { } __decorate([ Decorator(), __metadata("design:type", Service) ], Foo.prototype, "foo", void 0); `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not remove set accessor parameter type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { _foo: Service; @Decorator() set name(f: Service) { this._foo = f; } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { set name(f) { this._foo = f; } } __decorate([ Decorator(), __metadata("design:type", Service), __metadata("design:paramtypes", [Service]) ], Foo.prototype, "name", null); `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not remove get accessor parameter type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { _foo: Service; @Decorator() get name(): Service { return this._foo; } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { get name() { return this._foo; } } __decorate([ Decorator(), __metadata("design:type", Service), __metadata("design:paramtypes", []) ], Foo.prototype, "name", null); `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not remove decorated method return type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { @Decorator() name(): Service { return undefined; } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { name() { return undefined; } } __decorate([ Decorator(), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Service) ], Foo.prototype, "name", null); `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should not remove decorated method parameter type reference', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { @Decorator() name(f: Service) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; export class Foo { name(f) { } } __decorate([ Decorator(), __metadata("design:type", Function), __metadata("design:paramtypes", [Service]), __metadata("design:returntype", void 0) ], Foo.prototype, "name", null); `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove type-only imports', () => { const input = tags.stripIndent` import { Decorator } from './decorator'; import { Service } from './service'; import type { OnChanges, SimpleChanges } from './type'; @Decorator() class Foo implements OnChanges { constructor(param: Service) { } ngOnChanges(changes: SimpleChanges) { } } ${dummyNode} `; const output = tags.stripIndent` import { __decorate, __metadata } from "tslib"; import { Decorator } from './decorator'; import { Service } from './service'; let Foo = class Foo { constructor(param) { } ngOnChanges(changes) { } }; Foo = __decorate([ Decorator(), __metadata("design:paramtypes", [Service]) ], Foo); `; const { program, compilerHost } = createTypescriptContext( input, additionalFiles, true, extraCompilerOptions, ); const result = transformTypescript( undefined, [transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); });
{ "end_byte": 25271, "start_byte": 15482, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts_25279_26765
describe('NGTSC - ShorthandPropertyAssignment to PropertyAssignment', () => { const transformShorthandPropertyAssignment = ( context: ts.TransformationContext, ): ts.Transformer<ts.SourceFile> => { const visit: ts.Visitor = (node) => { if (ts.isShorthandPropertyAssignment(node)) { return ts.factory.createPropertyAssignment(node.name, node.name); } return ts.visitEachChild(node, (child) => visit(child), context); }; return (node) => ts.visitNode(node, visit) as ts.SourceFile; }; it('should not elide import when ShorthandPropertyAssignment is transformed to PropertyAssignment', () => { const input = tags.stripIndent` import { animations } from './const'; const used = { animations } ${dummyNode} `; const output = tags.stripIndent` import { animations } from './const'; const used = { animations: animations }; `; const { program, compilerHost } = createTypescriptContext(input, additionalFiles); const result = transformTypescript( undefined, [transformShorthandPropertyAssignment, transformer(program)], program, compilerHost, ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); }); }); }); });
{ "end_byte": 26765, "start_byte": 25279, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/elide_imports_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/elide_imports.ts_0_4792
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as ts from 'typescript'; // Remove imports for which all identifiers have been removed. // Needs type checker, and works even if it's not the first transformer. // Works by removing imports for symbols whose identifiers have all been removed. // Doesn't use the `symbol.declarations` because that previous transforms might have removed nodes // but the type checker doesn't know. // See https://github.com/Microsoft/TypeScript/issues/17552 for more information. export function elideImports( sourceFile: ts.SourceFile, removedNodes: ts.Node[], getTypeChecker: () => ts.TypeChecker, compilerOptions: ts.CompilerOptions, ): Set<ts.Node> { const importNodeRemovals = new Set<ts.Node>(); if (removedNodes.length === 0) { return importNodeRemovals; } const typeChecker = getTypeChecker(); // Collect all imports and used identifiers const usedSymbols = new Set<ts.Symbol>(); const imports: ts.ImportDeclaration[] = []; ts.forEachChild(sourceFile, function visit(node) { // Skip removed nodes. if (removedNodes.includes(node)) { return; } // Consider types for 'implements' as unused. // A HeritageClause token can also be an 'AbstractKeyword' // which in that case we should not elide the import. if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) { return; } // Record import and skip if (ts.isImportDeclaration(node)) { if (!node.importClause?.isTypeOnly) { imports.push(node); } return; } // Type reference imports do not need to be emitted when emitDecoratorMetadata is disabled. if (ts.isTypeReferenceNode(node) && !compilerOptions.emitDecoratorMetadata) { return; } let symbol: ts.Symbol | undefined; switch (node.kind) { case ts.SyntaxKind.Identifier: if (node.parent && ts.isShorthandPropertyAssignment(node.parent)) { const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(node.parent); if (shorthandSymbol) { symbol = shorthandSymbol; } } else { symbol = typeChecker.getSymbolAtLocation(node); } break; case ts.SyntaxKind.ExportSpecifier: symbol = typeChecker.getExportSpecifierLocalTargetSymbol(node as ts.ExportSpecifier); break; case ts.SyntaxKind.ShorthandPropertyAssignment: symbol = typeChecker.getShorthandAssignmentValueSymbol(node); break; } if (symbol) { usedSymbols.add(symbol); } ts.forEachChild(node, visit); }); if (imports.length === 0) { return importNodeRemovals; } const isUnused = (node: ts.Identifier) => { // Do not remove JSX factory imports if (node.text === compilerOptions.jsxFactory) { return false; } const symbol = typeChecker.getSymbolAtLocation(node); return symbol && !usedSymbols.has(symbol); }; for (const node of imports) { if (!node.importClause) { // "import 'abc';" continue; } const namedBindings = node.importClause.namedBindings; if (namedBindings && ts.isNamespaceImport(namedBindings)) { // "import * as XYZ from 'abc';" if (isUnused(namedBindings.name)) { importNodeRemovals.add(node); } } else { const specifierNodeRemovals = []; let clausesCount = 0; // "import { XYZ, ... } from 'abc';" if (namedBindings && ts.isNamedImports(namedBindings)) { let removedClausesCount = 0; clausesCount += namedBindings.elements.length; for (const specifier of namedBindings.elements) { if (specifier.isTypeOnly || isUnused(specifier.name)) { removedClausesCount++; // in case we don't have any more namedImports we should remove the parent ie the {} const nodeToRemove = clausesCount === removedClausesCount ? specifier.parent : specifier; specifierNodeRemovals.push(nodeToRemove); } } } // "import XYZ from 'abc';" if (node.importClause.name) { clausesCount++; if (node.importClause.isTypeOnly || isUnused(node.importClause.name)) { specifierNodeRemovals.push(node.importClause.name); } } if (specifierNodeRemovals.length === clausesCount) { importNodeRemovals.add(node); } else { for (const specifierNodeRemoval of specifierNodeRemovals) { importNodeRemovals.add(specifierNodeRemoval); } } } } return importNodeRemovals; }
{ "end_byte": 4792, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/elide_imports.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/find_image_domains.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 ts from 'typescript'; const BUILTIN_LOADERS = new Set([ 'provideCloudflareLoader', 'provideCloudinaryLoader', 'provideImageKitLoader', 'provideImgixLoader', ]); const URL_REGEX = /(https?:\/\/[^/]*)\//g; export function findImageDomains(imageDomains: Set<string>): ts.TransformerFactory<ts.SourceFile> { return (context: ts.TransformationContext) => { return (sourceFile: ts.SourceFile) => { const isBuiltinImageLoader = (node: ts.CallExpression): boolean => { return BUILTIN_LOADERS.has(node.expression.getText()); }; const findDomainString = (node: ts.Node) => { if ( ts.isStringLiteral(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node) ) { const domain = node.text.match(URL_REGEX); if (domain && domain[0]) { imageDomains.add(domain[0]); return node; } } ts.visitEachChild(node, findDomainString, context); return node; }; function isImageProviderKey(property: ts.ObjectLiteralElementLike): boolean { return ( ts.isPropertyAssignment(property) && property.name.getText() === 'provide' && property.initializer.getText() === 'IMAGE_LOADER' ); } function isImageProviderValue(property: ts.ObjectLiteralElementLike): boolean { return ts.isPropertyAssignment(property) && property.name.getText() === 'useValue'; } function checkForDomain(node: ts.ObjectLiteralExpression) { if (node.properties.find(isImageProviderKey)) { const value = node.properties.find(isImageProviderValue); if (value && ts.isPropertyAssignment(value)) { if ( ts.isArrowFunction(value.initializer) || ts.isFunctionExpression(value.initializer) ) { ts.visitEachChild(node, findDomainString, context); } } } } function findImageLoaders(node: ts.Node) { if (ts.isCallExpression(node)) { if (isBuiltinImageLoader(node)) { const firstArg = node.arguments[0]; if (ts.isStringLiteralLike(firstArg)) { imageDomains.add(firstArg.text); } } } else if (ts.isObjectLiteralExpression(node)) { checkForDomain(node); } return node; } function findProvidersAssignment(node: ts.Node) { if (ts.isPropertyAssignment(node)) { if (ts.isIdentifier(node.name) && node.name.escapedText === 'providers') { ts.visitEachChild(node.initializer, findImageLoaders, context); } } return node; } function findFeaturesAssignment(node: ts.Node) { if (ts.isPropertyAssignment(node)) { if ( ts.isIdentifier(node.name) && node.name.escapedText === 'features' && ts.isArrayLiteralExpression(node.initializer) ) { const providerElement = node.initializer.elements.find(isProvidersFeatureElement); if ( providerElement && ts.isCallExpression(providerElement) && providerElement.arguments[0] ) { ts.visitEachChild(providerElement.arguments[0], findImageLoaders, context); } } } return node; } function isProvidersFeatureElement(node: ts.Node): boolean { return ( ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText === 'i0' && ts.isIdentifier(node.expression.name) && node.expression.name.escapedText === 'ɵɵProvidersFeature' ); } function findPropertyDeclaration(node: ts.Node) { if ( ts.isPropertyDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && ts.isCallExpression(node.initializer) && node.initializer.arguments[0] ) { if (node.name.escapedText === 'ɵinj') { ts.visitEachChild(node.initializer.arguments[0], findProvidersAssignment, context); } else if (node.name.escapedText === 'ɵcmp') { ts.visitEachChild(node.initializer.arguments[0], findFeaturesAssignment, context); } } return node; } function findClassDeclaration(node: ts.Node) { if (ts.isClassDeclaration(node)) { ts.visitEachChild(node, findPropertyDeclaration, context); } return node; } ts.visitEachChild(sourceFile, findClassDeclaration, context); return sourceFile; }; }; }
{ "end_byte": 5075, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/find_image_domains.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls_spec.ts_0_7575
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable max-len */ import { tags } from '@angular-devkit/core'; import * as ts from 'typescript'; import { removeIvyJitSupportCalls } from './remove-ivy-jit-support-calls'; import { createTypescriptContext, transformTypescript } from './spec_helpers'; function transform( input: string, transformerFactory: ( getTypeChecker: () => ts.TypeChecker, ) => ts.TransformerFactory<ts.SourceFile>, ) { const { program, compilerHost } = createTypescriptContext(input); const getTypeChecker = () => program.getTypeChecker(); const transformer = transformerFactory(getTypeChecker); return transformTypescript(input, [transformer], program, compilerHost); } const input = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent, ExampleComponent], imports: [BrowserModule, AppRoutingModule] }); })(); /*@__PURE__*/ (function () { i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent, ExampleComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }] }], null, null); })(); `; const inputNoPure = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent, ExampleComponent], imports: [BrowserModule, AppRoutingModule] }); })(); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent, ExampleComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }] }], null, null); })(); `; const inputArrowFnWithBody = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (() => { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent, ExampleComponent], imports: [BrowserModule, AppRoutingModule] }); })(); (() => { i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent, ExampleComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }] }], null, null); })(); `; const inputArrowFnWithImplicitReturn = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (() => (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent, ExampleComponent], imports: [BrowserModule, AppRoutingModule] }))(); (() => i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent, ExampleComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }] }], null, null))(); `; const inputAsync = tags.stripIndent` export class TestCmp { } TestCmp.ɵfac = function TestCmp_Factory(t) { return new (t || TestCmp)(); }; TestCmp.ɵcmp = i0.ɵɵdefineComponent({ type: TestCmp, selectors: [["test-cmp"]], standalone: true, features: [i0.ɵɵStandaloneFeature], decls: 3, vars: 0, template: function TestCmp_Template(rf, ctx) { }, encapsulation: 2 }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadataAsync(TestCmp, function () { return [import("./cmp-a").then(function (m) { return m.CmpA; })]; }, function (CmpA) { i0.ɵsetClassMetadata(TestCmp, [{ type: Component, args: [{ selector: 'test-cmp', standalone: true, imports: [CmpA], template: '{#defer}<cmp-a />{/defer}', }] }], null, null); }); })(); `; const inputAsyncArrowFn = tags.stripIndent` export class TestCmp { } TestCmp.ɵfac = function TestCmp_Factory(t) { return new (t || TestCmp)(); }; TestCmp.ɵcmp = i0.ɵɵdefineComponent({ type: TestCmp, selectors: [["test-cmp"]], standalone: true, features: [i0.ɵɵStandaloneFeature], decls: 3, vars: 0, template: function TestCmp_Template(rf, ctx) { }, encapsulation: 2 }); (() => { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadataAsync(TestCmp, () => [import("./cmp-a").then((m) => m.CmpA)], (CmpA) => { i0.ɵsetClassMetadata(TestCmp, [{ type: Component, args: [{ selector: 'test-cmp', standalone: true, imports: [CmpA], template: '{#defer}<cmp-a />{/defer}', }] }], null, null); }); })(); `; const inputDebugInfo = tags.stripIndent` import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class TestCmp { } TestCmp.ɵfac = function TestCmp_Factory(t) { return new (t || TestCmp)(); }; TestCmp.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: TestCmp, selectors: [["test-cmp"]], decls: 0, vars: 0, template: function TestCmp_Template(rf, ctx) { }, encapsulation: 2 }); (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(TestCmp, { className: "TestCmp" }); })(); `; describe('@ngtools/webpack transformers', () => { describe('rem
{ "end_byte": 7575, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls_spec.ts_7575_17246
ove-ivy-dev-calls', () => { it('should allow removing only set class metadata with pure annotation', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent, ExampleComponent], imports: [BrowserModule, AppRoutingModule] }); })(); `; const result = transform(input, (getTypeChecker) => removeIvyJitSupportCalls(true, false, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should allow removing only set class metadata', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(AppModule, { declarations: [AppComponent, ExampleComponent], imports: [BrowserModule, AppRoutingModule] }); })(); `; const result = transform(inputNoPure, (getTypeChecker) => removeIvyJitSupportCalls(true, false, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should allow removing only ng module scope with pure annotation', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); /*@__PURE__*/ (function () { i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent, ExampleComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }] }], null, null); })(); `; const result = transform(input, (getTypeChecker) => removeIvyJitSupportCalls(false, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should allow removing only ng module scope', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadata(AppModule, [{ type: NgModule, args: [{ declarations: [ AppComponent, ExampleComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }] }], null, null); })(); `; const result = transform(inputNoPure, (getTypeChecker) => removeIvyJitSupportCalls(false, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should allow removing both set class metadata and ng module scope with pure annotation', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); `; const result = transform(input, (getTypeChecker) => removeIvyJitSupportCalls(true, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should allow removing both set class metadata and ng module scope', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); `; const result = transform(inputNoPure, (getTypeChecker) => removeIvyJitSupportCalls(true, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should allow removing neither set class metadata nor ng module scope with pure annotation', () => { const result = transform(input, (getTypeChecker) => removeIvyJitSupportCalls(false, false, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${input}`); }); it('should allow removing neither set class metadata nor ng module scope', () => { const result = transform(inputNoPure, (getTypeChecker) => removeIvyJitSupportCalls(false, false, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${inputNoPure}`); }); it('should strip unused imports when removing set class metadata and ng module scope with pure annotation', () => { const imports = tags.stripIndent` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ExampleComponent } from './example/example.component'; import * as i0 from "@angular/core"; `; const output = tags.stripIndent` import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import * as i0 from "@angular/core"; export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); `; const result = transform(imports + input, (getTypeChecker) => removeIvyJitSupportCalls(true, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should strip unused imports when removing set class metadata and ng module scope', () => { const imports = tags.stripIndent` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ExampleComponent } from './example/example.component'; import * as i0 from "@angular/core"; `; const output = tags.stripIndent` import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import * as i0 from "@angular/core"; export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); `; const result = transform(imports + inputNoPure, (getTypeChecker) => removeIvyJitSupportCalls(true, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove setClassMetadata and setNgModuleScope calls inside arrow-function-based IIFEs that have
{ "end_byte": 17246, "start_byte": 7575, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls_spec.ts_17252_20983
s', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); `; const result = transform(inputArrowFnWithBody, (getTypeChecker) => removeIvyJitSupportCalls(true, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove setClassMetadata and setNgModuleScope calls inside arrow-function-based IIFEs that have an implicit return', () => { const output = tags.stripIndent` export class AppModule { } AppModule.ɵmod = i0.ɵɵdefineNgModule({ type: AppModule, bootstrap: [AppComponent] }); AppModule.ɵinj = i0.ɵɵdefineInjector({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ BrowserModule, AppRoutingModule ]] }); `; const result = transform(inputArrowFnWithImplicitReturn, (getTypeChecker) => removeIvyJitSupportCalls(true, true, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove setClassMetadataAsync calls', () => { const output = tags.stripIndent` export class TestCmp { } TestCmp.ɵfac = function TestCmp_Factory(t) { return new (t || TestCmp)(); }; TestCmp.ɵcmp = i0.ɵɵdefineComponent({ type: TestCmp, selectors: [["test-cmp"]], standalone: true, features: [i0.ɵɵStandaloneFeature], decls: 3, vars: 0, template: function TestCmp_Template(rf, ctx) { }, encapsulation: 2 }); `; const result = transform(inputAsync, (getTypeChecker) => removeIvyJitSupportCalls(true, false, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove arrow-function-based setClassMetadataAsync calls', () => { const output = tags.stripIndent` export class TestCmp { } TestCmp.ɵfac = function TestCmp_Factory(t) { return new (t || TestCmp)(); }; TestCmp.ɵcmp = i0.ɵɵdefineComponent({ type: TestCmp, selectors: [["test-cmp"]], standalone: true, features: [i0.ɵɵStandaloneFeature], decls: 3, vars: 0, template: function TestCmp_Template(rf, ctx) { }, encapsulation: 2 }); `; const result = transform(inputAsyncArrowFn, (getTypeChecker) => removeIvyJitSupportCalls(true, false, false, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); it('should remove setClassDebugInfo calls', () => { const output = tags.stripIndent` import * as i0 from "@angular/core"; export class TestCmp { } TestCmp.ɵfac = function TestCmp_Factory(t) { return new (t || TestCmp)(); }; TestCmp.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: TestCmp, selectors: [["test-cmp"]], decls: 0, vars: 0, template: function TestCmp_Template(rf, ctx) { }, encapsulation: 2 }); `; const result = transform(inputDebugInfo, (getTypeChecker) => removeIvyJitSupportCalls(true, false, true, getTypeChecker), ); expect(tags.oneLine`${result}`).toEqual(tags.oneLine`${output}`); }); }); });
{ "end_byte": 20983, "start_byte": 17252, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/remove-ivy-jit-support-calls_spec.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/index.ts_0_274
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './elide_imports'; export * from './replace_resources';
{ "end_byte": 274, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/index.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/replace_resources.ts_0_8997
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as ts from 'typescript'; import { InlineAngularResourceLoaderPath } from '../loaders/inline-resource'; export const NG_COMPONENT_RESOURCE_QUERY = 'ngResource'; export function replaceResources( shouldTransform: (fileName: string) => boolean, getTypeChecker: () => ts.TypeChecker, inlineStyleFileExtension?: string, ): ts.TransformerFactory<ts.SourceFile> { return (context: ts.TransformationContext) => { const typeChecker = getTypeChecker(); const resourceImportDeclarations: ts.ImportDeclaration[] = []; const moduleKind = context.getCompilerOptions().module; const nodeFactory = context.factory; const visitNode: ts.Visitor = (node: ts.Node) => { if (ts.isClassDeclaration(node)) { const decorators = ts.getDecorators(node); if (!decorators || decorators.length === 0) { return node; } return nodeFactory.updateClassDeclaration( node, [ ...decorators.map((current) => visitDecorator( nodeFactory, current, typeChecker, resourceImportDeclarations, moduleKind, inlineStyleFileExtension, ), ), ...(ts.getModifiers(node) ?? []), ], node.name, node.typeParameters, node.heritageClauses, node.members, ); } return ts.visitEachChild(node, visitNode, context); }; return (sourceFile: ts.SourceFile) => { if (!shouldTransform(sourceFile.fileName)) { return sourceFile; } const updatedSourceFile = ts.visitNode(sourceFile, visitNode) as ts.SourceFile; if (resourceImportDeclarations.length) { // Add resource imports return context.factory.updateSourceFile( updatedSourceFile, ts.setTextRange( context.factory.createNodeArray([ ...resourceImportDeclarations, ...updatedSourceFile.statements, ]), updatedSourceFile.statements, ), ); } return updatedSourceFile; }; }; } function visitDecorator( nodeFactory: ts.NodeFactory, node: ts.Decorator, typeChecker: ts.TypeChecker, resourceImportDeclarations: ts.ImportDeclaration[], moduleKind?: ts.ModuleKind, inlineStyleFileExtension?: string, ): ts.Decorator { if (!isComponentDecorator(node, typeChecker)) { return node; } if (!ts.isCallExpression(node.expression)) { return node; } const decoratorFactory = node.expression; const args = decoratorFactory.arguments; if (args.length !== 1 || !ts.isObjectLiteralExpression(args[0])) { // Unsupported component metadata return node; } const objectExpression = args[0]; const styleReplacements: ts.Expression[] = []; // visit all properties let properties = ts.visitNodes(objectExpression.properties, (node) => ts.isObjectLiteralElementLike(node) ? visitComponentMetadata( nodeFactory, node, styleReplacements, resourceImportDeclarations, moduleKind, inlineStyleFileExtension, ) : node, ) as ts.NodeArray<ts.ObjectLiteralElementLike>; // replace properties with updated properties if (styleReplacements.length > 0) { const styleProperty = nodeFactory.createPropertyAssignment( nodeFactory.createIdentifier('styles'), nodeFactory.createArrayLiteralExpression(styleReplacements), ); properties = nodeFactory.createNodeArray([...properties, styleProperty]); } return nodeFactory.updateDecorator( node, nodeFactory.updateCallExpression( decoratorFactory, decoratorFactory.expression, decoratorFactory.typeArguments, [nodeFactory.updateObjectLiteralExpression(objectExpression, properties)], ), ); } function visitComponentMetadata( nodeFactory: ts.NodeFactory, node: ts.ObjectLiteralElementLike, styleReplacements: ts.Expression[], resourceImportDeclarations: ts.ImportDeclaration[], moduleKind: ts.ModuleKind = ts.ModuleKind.ES2015, inlineStyleFileExtension?: string, ): ts.ObjectLiteralElementLike | undefined { if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) { return node; } const name = node.name.text; switch (name) { case 'moduleId': return undefined; case 'templateUrl': { const url = getResourceUrl(node.initializer); if (!url) { return node; } const importName = createResourceImport( nodeFactory, url, resourceImportDeclarations, moduleKind, ); if (!importName) { return node; } return nodeFactory.updatePropertyAssignment( node, nodeFactory.createIdentifier('template'), importName, ); } case 'styles': case 'styleUrl': case 'styleUrls': { const isInlineStyle = name === 'styles'; let styles: Iterable<ts.Expression>; if (ts.isStringLiteralLike(node.initializer)) { styles = [ transformInlineStyleLiteral( node.initializer, nodeFactory, isInlineStyle, inlineStyleFileExtension, resourceImportDeclarations, moduleKind, ) as ts.StringLiteralLike, ]; } else if (ts.isArrayLiteralExpression(node.initializer)) { styles = ts.visitNodes(node.initializer.elements, (node) => transformInlineStyleLiteral( node, nodeFactory, isInlineStyle, inlineStyleFileExtension, resourceImportDeclarations, moduleKind, ), ) as ts.NodeArray<ts.Expression>; } else { return node; } // Styles should be placed first if (isInlineStyle) { styleReplacements.unshift(...styles); } else { styleReplacements.push(...styles); } return undefined; } default: return node; } } function transformInlineStyleLiteral( node: ts.Node, nodeFactory: ts.NodeFactory, isInlineStyle: boolean, inlineStyleFileExtension: string | undefined, resourceImportDeclarations: ts.ImportDeclaration[], moduleKind: ts.ModuleKind, ) { if (!ts.isStringLiteralLike(node)) { return node; } // Don't transform empty strings as PostCSS will choke on them. No work to do anyways. if (node.text === '') { return node; } if (!isInlineStyle) { const url = getResourceUrl(node); return url ? createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind) : node; } if (!inlineStyleFileExtension) { return nodeFactory.createStringLiteral(node.text); } const data = Buffer.from(node.text).toString('base64'); const containingFile = node.getSourceFile().fileName; // app.component.ts.css?ngResource!=!@ngtools/webpack/src/loaders/inline-resource.js?data=...!app.component.ts const url = `${containingFile}.${inlineStyleFileExtension}?${NG_COMPONENT_RESOURCE_QUERY}` + `!=!${InlineAngularResourceLoaderPath}?data=${encodeURIComponent(data)}!${containingFile}`; return createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind); } export function getResourceUrl(node: ts.Node): string | null { // only analyze strings if (!ts.isStringLiteralLike(node)) { return null; } return `${/^\.?\.\//.test(node.text) ? '' : './'}${node.text}?${NG_COMPONENT_RESOURCE_QUERY}`; } function isComponentDecorator(node: ts.Node, typeChecker: ts.TypeChecker): node is ts.Decorator { if (!ts.isDecorator(node)) { return false; } const origin = getDecoratorOrigin(node, typeChecker); if (origin && origin.module === '@angular/core' && origin.name === 'Component') { return true; } return false; } function createResourceImport( nodeFactory: ts.NodeFactory, url: string, resourceImportDeclarations: ts.ImportDeclaration[], moduleKind: ts.ModuleKind, ): ts.Identifier | ts.Expression { const urlLiteral = nodeFactory.createStringLiteral(url); if (moduleKind < ts.ModuleKind.ES2015) { return nodeFactory.createCallExpression( nodeFactory.createIdentifier('require'), [], [urlLiteral], ); } else { const importName = nodeFactory.createIdentifier( `__NG_CLI_RESOURCE__${resourceImportDeclarations.length}`, ); resourceImportDeclarations.push( nodeFactory.createImportDeclaration( undefined, nodeFactory.createImportClause(false, importName, undefined), urlLiteral, ), ); return importName; } } interface DecoratorOrigin { name: string; module: string; }
{ "end_byte": 8997, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/replace_resources.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/replace_resources.ts_8999_10531
function getDecoratorOrigin( decorator: ts.Decorator, typeChecker: ts.TypeChecker, ): DecoratorOrigin | null { if (!ts.isCallExpression(decorator.expression)) { return null; } let identifier: ts.Node; let name = ''; if (ts.isPropertyAccessExpression(decorator.expression.expression)) { identifier = decorator.expression.expression.expression; name = decorator.expression.expression.name.text; } else if (ts.isIdentifier(decorator.expression.expression)) { identifier = decorator.expression.expression; } else { return null; } // NOTE: resolver.getReferencedImportDeclaration would work as well but is internal const symbol = typeChecker.getSymbolAtLocation(identifier); if (symbol && symbol.declarations && symbol.declarations.length > 0) { const declaration = symbol.declarations[0]; let module: string; if (ts.isImportSpecifier(declaration)) { name = (declaration.propertyName || declaration.name).text; module = (declaration.parent.parent.parent.moduleSpecifier as ts.Identifier).text; } else if (ts.isNamespaceImport(declaration)) { // Use the name from the decorator namespace property access module = (declaration.parent.parent.moduleSpecifier as ts.Identifier).text; } else if (ts.isImportClause(declaration)) { name = (declaration.name as ts.Identifier).text; module = (declaration.parent.moduleSpecifier as ts.Identifier).text; } else { return null; } return { name, module }; } return null; }
{ "end_byte": 10531, "start_byte": 8999, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/replace_resources.ts" }
angular-cli/packages/ngtools/webpack/src/transformers/spec_helpers.ts_0_3124
/** * @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 { basename } from 'path'; import * as ts from 'typescript'; // Test transform helpers. const basefileName = 'test-file.ts'; export function createTypescriptContext( content: string, additionalFiles?: Record<string, string>, useLibs = false, extraCompilerOptions: ts.CompilerOptions = {}, jsxFile = false, ) { const fileName = basefileName + (jsxFile ? 'x' : ''); // Set compiler options. const compilerOptions: ts.CompilerOptions = { noEmitOnError: useLibs, allowJs: true, newLine: ts.NewLineKind.LineFeed, moduleResolution: ts.ModuleResolutionKind.Node10, module: ts.ModuleKind.ES2020, target: ts.ScriptTarget.ES2020, skipLibCheck: true, sourceMap: false, importHelpers: true, experimentalDecorators: true, types: [], ...extraCompilerOptions, }; // Create compiler host. const compilerHost = ts.createCompilerHost(compilerOptions, true); const baseFileExists = compilerHost.fileExists; compilerHost.fileExists = function (compilerFileName: string) { return ( compilerFileName === fileName || !!additionalFiles?.[basename(compilerFileName)] || baseFileExists(compilerFileName) ); }; const baseReadFile = compilerHost.readFile; compilerHost.readFile = function (compilerFileName: string) { if (compilerFileName === fileName) { return content; } else if (additionalFiles?.[basename(compilerFileName)]) { return additionalFiles[basename(compilerFileName)]; } else { return baseReadFile(compilerFileName); } }; // Create the TypeScript program. const program = ts.createProgram([fileName], compilerOptions, compilerHost); return { compilerHost, program }; } export function transformTypescript( content: string | undefined, transformers: ts.TransformerFactory<ts.SourceFile>[], program?: ts.Program, compilerHost?: ts.CompilerHost, ): string | undefined { // Use given context or create a new one. if (content !== undefined) { const typescriptContext = createTypescriptContext(content); if (!program) { program = typescriptContext.program; } if (!compilerHost) { compilerHost = typescriptContext.compilerHost; } } else if (!program || !compilerHost) { throw new Error('transformTypescript needs either `content` or a `program` and `compilerHost'); } const outputFileName = basefileName.replace(/\.tsx?$/, '.js'); let outputContent; // Emit. const { emitSkipped, diagnostics } = program.emit( undefined, (filename, data) => { if (filename === outputFileName) { outputContent = data; } }, undefined, undefined, { before: transformers }, ); // Throw error with diagnostics if emit wasn't successfull. if (emitSkipped) { throw new Error(ts.formatDiagnostics(diagnostics, compilerHost)); } // Return the transpiled js. return outputContent; }
{ "end_byte": 3124, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/transformers/spec_helpers.ts" }
angular-cli/packages/ngtools/webpack/src/loaders/inline-resource.ts_0_925
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { Compilation, LoaderContext } from 'webpack'; export const InlineAngularResourceLoaderPath = __filename; export const InlineAngularResourceSymbol = Symbol('@ngtools/webpack[angular-resource]'); export interface CompilationWithInlineAngularResource extends Compilation { [InlineAngularResourceSymbol]: string; } export default function (this: LoaderContext<{ data?: string }>) { const callback = this.async(); const { data } = this.getOptions(); if (data) { callback(undefined, Buffer.from(data, 'base64').toString()); } else { const content = (this._compilation as CompilationWithInlineAngularResource)[ InlineAngularResourceSymbol ]; callback(undefined, content); } }
{ "end_byte": 925, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/loaders/inline-resource.ts" }
angular-cli/packages/schematics/angular/no_typescript_runtime_dep_spec.js_0_1150
/** * @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 */ const fs = require('fs'); const path = require('path'); const pkg = path.dirname(require.resolve(__filename)); describe('@schematics/angular javascript code', () => { fs.readdirSync(pkg).forEach((d) => { const dir = path.join(pkg, d); if (!fs.statSync(dir).isDirectory()) return; it(`${d} has no typescript dependency`, () => { function check(subdir) { fs.readdirSync(subdir).forEach((f) => { const file = path.join(subdir, f); if (fs.statSync(file).isDirectory()) { check(file); } else if (file.endsWith('.js')) { const content = fs.readFileSync(file, { encoding: 'utf-8' }); if ( content.includes(`require("typescript")`) || content.includes(`require('typescript')`) ) { fail(`${file} has a typescript import`); } } }); } check(dir); }); }); });
{ "end_byte": 1150, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/no_typescript_runtime_dep_spec.js" }
angular-cli/packages/schematics/angular/README.md_0_2886
# @schematics/angular This package contains a collection of [schematics](/packages/angular_devkit/schematics/README.md) for generating an Angular application. ## Schematics | Name | Description | | -------------- | ----------------------------------------------------------------------------------------------------- | | app-shell | Generates an app shell for running a server-side version of an app | | application | Generates a new basic app definition in the "projects" subfolder of the workspace | | class | Creates a new, generic class definition in the given project | | component | Creates a new, generic component definition in the given project | | directive | Creates a new, generic directive definition in the given project | | enum | Generates a new, generic enum definition in the given project | | guard | Generates a new, generic route guard definition in the given project | | interceptor | Creates a new, generic interceptor definition in the given project | | interface | Creates a new, generic interface definition in the given project | | library | Creates a new, generic library project in the current workspace | | module | Creates a new, generic NgModule definition in the given project | | ng-new | Creates a new project by combining the workspace and application schematics | | pipe | Creates a new, generic pipe definition in the given project | | resolver | Creates a new, generic resolver definition in the given project | | service | Creates a new, generic service definition in the given project | | service-worker | Pass this schematic to the "run" command to create a service worker | | web-worker | Creates a new, generic web worker definition in the given project | | workspace | Initializes an empty workspace and adds the necessary dependencies required by an Angular application | ## Disclaimer While the schematics when executed via the Angular CLI and their associated options are considered stable, the programmatic APIs are not considered officially supported and are not subject to the breaking change guarantees of SemVer.
{ "end_byte": 2886, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/README.md" }
angular-cli/packages/schematics/angular/BUILD.bazel_0_4568
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") load("//tools:ts_json_schema.bzl", "ts_json_schema") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) # Create a list of Tuple("path/file.json", "path_file") to be used as rules ALL_SCHEMA_TARGETS = [ ( x, x.replace("/", "_").replace("-", "_").replace(".json", ""), ) for x in glob( include = ["*/schema.json"], exclude = [ # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ) ] # Create all the targets. [ ts_json_schema( name = name, src = src, ) for (src, name) in ALL_SCHEMA_TARGETS ] ts_library( name = "angular", package_name = "@schematics/angular", srcs = glob( include = ["**/*.ts"], exclude = [ "**/*_spec.ts", # Also exclude templated files. "*/files/**/*.ts", "*/other-files/**/*.ts", "*/implements-files/**/*", "*/type-files/**/*", "*/functional-files/**/*", "*/class-files/**/*", # Exclude test helpers. "utility/test/**/*.ts", # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ) + [ "//packages/schematics/angular:" + src.replace(".json", ".ts") for (src, _) in ALL_SCHEMA_TARGETS ], data = [ "collection.json", "migrations/migration-collection.json", "package.json", "utility/latest-versions/package.json", ] + glob( include = [ "*/schema.json", "*/files/**/*", "*/other-files/**/*", "*/implements-files/**/*", "*/type-files/**/*", "*/functional-files/**/*", "*/class-files/**/*", ], exclude = [ # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ), module_name = "@schematics/angular", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/schematics/angular/third_party/github.com/Microsoft/TypeScript", "@npm//@types/node", "@npm//browserslist", "@npm//jsonc-parser", ], ) jasmine_node_test( name = "no_typescript_runtime_dep_test", srcs = ["no_typescript_runtime_dep_spec.js"], deps = [ ":angular", "@npm//jasmine", ], ) ts_library( name = "angular_test_lib", testonly = True, srcs = glob( include = [ "**/*_spec.ts", "utility/test/**/*.ts", ], exclude = [ # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", ], ), # @external_begin deps = [ ":angular", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node/testing", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/testing", "//packages/schematics/angular/third_party/github.com/Microsoft/TypeScript", "@npm//jsonc-parser", ], # @external_end ) jasmine_node_test( name = "angular_test", srcs = [":angular_test_lib"], deps = [ "//packages/schematics/angular/third_party/github.com/Microsoft/TypeScript", "@npm//jasmine", "@npm//source-map", ], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular_devkit/schematics:package.json", "//packages/angular_devkit/core:package.json", ], tags = ["release-package"], deps = [ ":README.md", ":angular", ":license", ":migrations/migration-collection.json", ":utility/latest-versions/package.json", "//packages/schematics/angular/third_party/github.com/Microsoft/TypeScript:LICENSE", ], )
{ "end_byte": 4568, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/BUILD.bazel" }
angular-cli/packages/schematics/angular/migrations/update-ssr-imports/migration.ts_0_2768
/** * @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 { DirEntry, Rule, UpdateRecorder } from '@angular-devkit/schematics'; import * as ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; function* visit(directory: DirEntry): IterableIterator<ts.SourceFile> { for (const path of directory.subfiles) { if (path.endsWith('.ts') && !path.endsWith('.d.ts')) { const entry = directory.file(path); if (entry) { const content = entry.content; if (content.includes('CommonEngine') && !content.includes('@angular/ssr/node')) { const source = ts.createSourceFile( entry.path, content.toString().replace(/^\uFEFF/, ''), ts.ScriptTarget.Latest, true, ); yield source; } } } } for (const path of directory.subdirs) { if (path === 'node_modules' || path.startsWith('.')) { continue; } yield* visit(directory.dir(path)); } } /** * Schematics rule that identifies and updates import declarations in TypeScript files. * Specifically, it modifies imports of '@angular/ssr' by appending '/node' if the * `CommonEngine` is used from the old entry point. * */ export default function (): Rule { return (tree) => { for (const sourceFile of visit(tree.root)) { let recorder: UpdateRecorder | undefined; const allImportDeclarations = sourceFile.statements.filter((n) => ts.isImportDeclaration(n)); if (allImportDeclarations.length === 0) { continue; } const ssrImports = allImportDeclarations.filter( (n) => ts.isStringLiteral(n.moduleSpecifier) && n.moduleSpecifier.text === '@angular/ssr', ); for (const ssrImport of ssrImports) { const ssrNamedBinding = getNamedImports(ssrImport); if (ssrNamedBinding) { const isUsingOldEntryPoint = ssrNamedBinding.elements.some((e) => e.name.text.startsWith('CommonEngine'), ); if (!isUsingOldEntryPoint) { continue; } recorder ??= tree.beginUpdate(sourceFile.fileName); recorder.insertRight(ssrImport.moduleSpecifier.getEnd() - 1, '/node'); } } if (recorder) { tree.commitUpdate(recorder); } } }; } function getNamedImports( importDeclaration: ts.ImportDeclaration | undefined, ): ts.NamedImports | undefined { const namedBindings = importDeclaration?.importClause?.namedBindings; if (namedBindings && ts.isNamedImports(namedBindings)) { return namedBindings; } return undefined; }
{ "end_byte": 2768, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/update-ssr-imports/migration.ts" }
angular-cli/packages/schematics/angular/migrations/update-ssr-imports/migration_spec.ts_0_2219
/** * @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 { tags } from '@angular-devkit/core'; import { EmptyTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; describe('CommonEngine migration', () => { const schematicRunner = new SchematicTestRunner( 'migrations', require.resolve('../migration-collection.json'), ); let tree: UnitTestTree; beforeEach(() => { tree = new UnitTestTree(new EmptyTree()); }); function runMigration(): Promise<UnitTestTree> { return schematicRunner.runSchematic('update-ssr-imports', {}, tree); } it(`should replace 'CommonEngine*' imports from '@angular/ssr' to '@angular/ssr/node'`, async () => { tree.create( '/index.ts', tags.stripIndents` import { CommonEngine } from '@angular/ssr'; import type { CommonEngineOptions, CommonEngineRenderOptions } from '@angular/ssr'; `, ); const newTree = await runMigration(); expect(newTree.readContent('/index.ts')).toBe(tags.stripIndents` import { CommonEngine } from '@angular/ssr/node'; import type { CommonEngineOptions, CommonEngineRenderOptions } from '@angular/ssr/node'; `); }); it(`should not replace 'CommonEngine*' imports from '@angular/ssr/node'`, async () => { const input = tags.stripIndents` import { CommonEngine } from '@angular/ssr/node'; import type { CommonEngineOptions, CommonEngineRenderOptions } from '@angular/ssr/node'; `; tree.create('/index.ts', input); const newTree = await runMigration(); expect(newTree.readContent('/index.ts')).toBe(input); }); it(`should not replace 'CommonEngine*' imports from other package`, async () => { const input = tags.stripIndents` import { CommonEngine } from 'unknown'; import type { CommonEngineOptions, CommonEngineRenderOptions } from 'unknown'; `; tree.create('/index.ts', input); const newTree = await runMigration(); expect(newTree.readContent('/index.ts')).toBe(input); }); });
{ "end_byte": 2219, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/update-ssr-imports/migration_spec.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/migration.ts_0_4898
/** * @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 { DirEntry, Rule, SchematicContext, SchematicsException, Tree, chain, externalSchematic, } from '@angular-devkit/schematics'; import { basename, dirname, extname, join } from 'node:path/posix'; import { removePackageJsonDependency } from '../../utility/dependencies'; import { DependencyType, ExistingBehavior, InstallBehavior, addDependency, } from '../../utility/dependency'; import { JSONFile } from '../../utility/json-file'; import { latestVersions } from '../../utility/latest-versions'; import { TargetDefinition, WorkspaceDefinition, allTargetOptions, allWorkspaceTargets, updateWorkspace, } from '../../utility/workspace'; import { Builders, ProjectType } from '../../utility/workspace-models'; import { findImports } from './css-import-lexer'; function* updateBuildTarget( projectName: string, buildTarget: TargetDefinition, serverTarget: TargetDefinition | undefined, tree: Tree, context: SchematicContext, ): Iterable<Rule> { // Update builder target and options buildTarget.builder = Builders.Application; for (const [, options] of allTargetOptions(buildTarget, false)) { if (options['index'] === '') { options['index'] = false; } // Rename and transform options options['browser'] = options['main']; if (serverTarget && typeof options['browser'] === 'string') { options['server'] = dirname(options['browser']) + '/main.server.ts'; } options['serviceWorker'] = options['ngswConfigPath'] ?? options['serviceWorker']; if (typeof options['polyfills'] === 'string') { options['polyfills'] = [options['polyfills']]; } let outputPath = options['outputPath']; if (typeof outputPath === 'string') { if (!/\/browser\/?$/.test(outputPath)) { // TODO: add prompt. context.logger.warn( `The output location of the browser build has been updated from "${outputPath}" to ` + `"${join(outputPath, 'browser')}". ` + 'You might need to adjust your deployment pipeline or, as an alternative, ' + 'set outputPath.browser to "" in order to maintain the previous functionality.', ); } else { outputPath = outputPath.replace(/\/browser\/?$/, ''); } options['outputPath'] = { base: outputPath, }; if (typeof options['resourcesOutputPath'] === 'string') { const media = options['resourcesOutputPath'].replaceAll('/', ''); if (media && media !== 'media') { options['outputPath'] = { base: outputPath, media, }; } } } // Delete removed options delete options['vendorChunk']; delete options['commonChunk']; delete options['resourcesOutputPath']; delete options['buildOptimizer']; delete options['main']; delete options['ngswConfigPath']; } // Merge browser and server tsconfig if (serverTarget) { const browserTsConfig = buildTarget.options?.tsConfig; const serverTsConfig = serverTarget.options?.tsConfig; if (typeof browserTsConfig !== 'string') { throw new SchematicsException( `Cannot update project "${projectName}" to use the application builder` + ` as the browser tsconfig cannot be located.`, ); } if (typeof serverTsConfig !== 'string') { throw new SchematicsException( `Cannot update project "${projectName}" to use the application builder` + ` as the server tsconfig cannot be located.`, ); } const browserJson = new JSONFile(tree, browserTsConfig); const serverJson = new JSONFile(tree, serverTsConfig); const filesPath = ['files']; const files = new Set([ ...((browserJson.get(filesPath) as string[] | undefined) ?? []), ...((serverJson.get(filesPath) as string[] | undefined) ?? []), ]); // Server file will be added later by the means of the ssr schematic. files.delete('server.ts'); browserJson.modify(filesPath, Array.from(files)); const typesPath = ['compilerOptions', 'types']; browserJson.modify( typesPath, Array.from( new Set([ ...((browserJson.get(typesPath) as string[] | undefined) ?? []), ...((serverJson.get(typesPath) as string[] | undefined) ?? []), ]), ), ); // Delete server tsconfig yield deleteFile(serverTsConfig); } // Update server file const ssrMainFile = serverTarget?.options?.['main']; if (typeof ssrMainFile === 'string') { yield deleteFile(ssrMainFile); yield externalSchematic('@schematics/angular', 'ssr', { project: projectName, skipInstall: true, }); } }
{ "end_byte": 4898, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/migration.ts_4900_12885
function updateProjects(tree: Tree, context: SchematicContext) { return updateWorkspace((workspace) => { const rules: Rule[] = []; for (const [name, project] of workspace.projects) { if (project.extensions.projectType !== ProjectType.Application) { // Only interested in application projects since these changes only effects application builders continue; } const buildTarget = project.targets.get('build'); if (!buildTarget || buildTarget.builder === Builders.Application) { continue; } if ( buildTarget.builder !== Builders.BrowserEsbuild && buildTarget.builder !== Builders.Browser ) { context.logger.error( `Cannot update project "${name}" to use the application builder.` + ` Only "${Builders.BrowserEsbuild}" and "${Builders.Browser}" can be automatically migrated.`, ); continue; } const serverTarget = project.targets.get('server'); rules.push(...updateBuildTarget(name, buildTarget, serverTarget, tree, context)); // Delete all redundant targets for (const [key, target] of project.targets) { switch (target.builder) { case Builders.Server: case Builders.Prerender: case Builders.AppShell: case Builders.SsrDevServer: project.targets.delete(key); break; } } // Update CSS/Sass import specifiers const projectSourceRoot = join(project.root, project.sourceRoot ?? 'src'); updateStyleImports(tree, projectSourceRoot, buildTarget); } // Check for @angular-devkit/build-angular Webpack usage let hasAngularDevkitUsage = false; for (const [, target] of allWorkspaceTargets(workspace)) { switch (target.builder) { case Builders.Application: case Builders.DevServer: case Builders.ExtractI18n: // Ignore application, dev server, and i18n extraction for devkit usage check. // Both will be replaced if no other usage is found. continue; } if (target.builder.startsWith('@angular-devkit/build-angular:')) { hasAngularDevkitUsage = true; break; } } // Use @angular/build directly if there is no devkit package usage if (!hasAngularDevkitUsage) { for (const [, target] of allWorkspaceTargets(workspace)) { switch (target.builder) { case Builders.Application: target.builder = '@angular/build:application'; break; case Builders.DevServer: target.builder = '@angular/build:dev-server'; break; case Builders.ExtractI18n: target.builder = '@angular/build:extract-i18n'; break; } } // Add direct @angular/build dependencies and remove @angular-devkit/build-angular rules.push( addDependency('@angular/build', latestVersions.DevkitBuildAngular, { type: DependencyType.Dev, // Always is set here since removePackageJsonDependency below does not automatically // trigger the package manager execution. install: InstallBehavior.Always, existing: ExistingBehavior.Replace, }), ); removePackageJsonDependency(tree, '@angular-devkit/build-angular'); // Add less dependency if any projects contain a Less stylesheet file. // This check does not consider Node.js packages due to the performance // cost of searching such a large directory structure. A build time error // will provide instructions to install the package in this case. if (hasLessStylesheets(tree)) { rules.push( addDependency('less', latestVersions['less'], { type: DependencyType.Dev, existing: ExistingBehavior.Skip, }), ); } // Add postcss dependency if any projects have a custom postcss configuration file. // The build system only supports files in a project root or workspace root with // names of either 'postcss.config.json' or '.postcssrc.json'. if (hasPostcssConfiguration(tree, workspace)) { rules.push( addDependency('postcss', latestVersions['postcss'], { type: DependencyType.Dev, existing: ExistingBehavior.Replace, }), ); } } return chain(rules); }); } /** * Searches the schematic tree for files that have a `.less` extension. * * @param tree A Schematics tree instance to search * @returns true if Less stylesheet files are found; otherwise, false */ function hasLessStylesheets(tree: Tree) { const directories = [tree.getDir('/')]; let current; while ((current = directories.pop())) { for (const path of current.subfiles) { if (path.endsWith('.less')) { return true; } } for (const path of current.subdirs) { if (path === 'node_modules' || path.startsWith('.')) { continue; } directories.push(current.dir(path)); } } } /** * Searches for a Postcss configuration file within the workspace root * or any of the project roots. * * @param tree A Schematics tree instance to search * @param workspace A Workspace to check for projects * @returns true, if a Postcss configuration file is found; otherwise, false */ function hasPostcssConfiguration(tree: Tree, workspace: WorkspaceDefinition) { // Add workspace root const searchDirectories = ['']; // Add each project root for (const { root } of workspace.projects.values()) { if (root) { searchDirectories.push(root); } } return searchDirectories.some( (dir) => tree.exists(join(dir, 'postcss.config.json')) || tree.exists(join(dir, '.postcssrc.json')), ); } function* visit( directory: DirEntry, ): IterableIterator<[fileName: string, contents: string, sass: boolean]> { for (const path of directory.subfiles) { const sass = path.endsWith('.scss'); if (path.endsWith('.css') || sass) { const entry = directory.file(path); if (entry) { const content = entry.content; yield [entry.path, content.toString(), sass]; } } } for (const path of directory.subdirs) { if (path === 'node_modules' || path.startsWith('.')) { continue; } yield* visit(directory.dir(path)); } } // Based on https://github.com/sass/dart-sass/blob/44d6bb6ac72fe6b93f5bfec371a1fffb18e6b76d/lib/src/importer/utils.dart function* potentialSassImports( specifier: string, base: string, fromImport: boolean, ): Iterable<string> { const directory = join(base, dirname(specifier)); const extension = extname(specifier); const hasStyleExtension = extension === '.scss' || extension === '.sass' || extension === '.css'; // Remove the style extension if present to allow adding the `.import` suffix const filename = basename(specifier, hasStyleExtension ? extension : undefined); if (hasStyleExtension) { if (fromImport) { yield join(directory, filename + '.import' + extension); yield join(directory, '_' + filename + '.import' + extension); } yield join(directory, filename + extension); yield join(directory, '_' + filename + extension); } else { if (fromImport) { yield join(directory, filename + '.import.scss'); yield join(directory, filename + '.import.sass'); yield join(directory, filename + '.import.css'); yield join(directory, '_' + filename + '.import.scss'); yield join(directory, '_' + filename + '.import.sass'); yield join(directory, '_' + filename + '.import.css'); } yield join(directory, filename + '.scss'); yield join(directory, filename + '.sass'); yield join(directory, filename + '.css'); yield join(directory, '_' + filename + '.scss'); yield join(directory, '_' + filename + '.sass'); yield join(directory, '_' + filename + '.css'); } }
{ "end_byte": 12885, "start_byte": 4900, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/migration.ts_12887_15446
function updateStyleImports(tree: Tree, projectSourceRoot: string, buildTarget: TargetDefinition) { const external = new Set<string>(); let needWorkspaceIncludePath = false; for (const file of visit(tree.getDir(projectSourceRoot))) { const [path, content, sass] = file; const relativeBase = dirname(path); let updater; for (const { start, specifier, fromUse } of findImports(content, sass)) { if (specifier[0] === '~') { updater ??= tree.beginUpdate(path); // start position includes the opening quote updater.remove(start + 1, 1); } else if (specifier[0] === '^') { updater ??= tree.beginUpdate(path); // start position includes the opening quote updater.remove(start + 1, 1); // Add to externalDependencies external.add(specifier.slice(1)); } else if ( sass && [...potentialSassImports(specifier, relativeBase, !fromUse)].every( (v) => !tree.exists(v), ) && [...potentialSassImports(specifier, '/', !fromUse)].some((v) => tree.exists(v)) ) { needWorkspaceIncludePath = true; } } if (updater) { tree.commitUpdate(updater); } } if (needWorkspaceIncludePath) { buildTarget.options ??= {}; buildTarget.options['stylePreprocessorOptions'] ??= {}; ((buildTarget.options['stylePreprocessorOptions'] as { includePaths?: string[] })[ 'includePaths' ] ??= []).push('.'); } if (external.size > 0) { buildTarget.options ??= {}; ((buildTarget.options['externalDependencies'] as string[] | undefined) ??= []).push( ...external, ); } } function deleteFile(path: string): Rule { return (tree) => { tree.delete(path); }; } function updateJsonFile(path: string, updater: (json: JSONFile) => void): Rule { return (tree) => { updater(new JSONFile(tree, path)); }; } /** * Migration main entrypoint */ export default function (): Rule { return chain([ updateProjects, // Delete package.json helper scripts updateJsonFile('package.json', (pkgJson) => ['build:ssr', 'dev:ssr', 'serve:ssr', 'prerender'].forEach((s) => pkgJson.remove(['scripts', s]), ), ), // Update main tsconfig updateJsonFile('tsconfig.json', (rootJson) => { rootJson.modify(['compilerOptions', 'esModuleInterop'], true); rootJson.modify(['compilerOptions', 'downlevelIteration'], undefined); rootJson.modify(['compilerOptions', 'allowSyntheticDefaultImports'], undefined); }), ]); }
{ "end_byte": 15446, "start_byte": 12887, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/css-import-lexer.ts_0_3829
/** * @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 */ /** * 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 import/use directive 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 directive value found. */ export function* findImports( contents: string, sass: boolean, ): Iterable<{ start: number; end: number; specifier: string; fromUse?: boolean }> { yield* find(contents, '@import '); if (sass) { for (const result of find(contents, '@use ')) { yield { ...result, fromUse: true }; } } } /** * Scans a CSS or Sass file and locates all valid function/directive values as defined by the * syntax specification. * @param contents A string containing a CSS or Sass file to scan. * @param prefix The prefix to start a valid segment. * @returns An iterable that yields each CSS url function value found. */ function* find( contents: string, prefix: string, ): Iterable<{ start: number; end: number; specifier: 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(prefix, pos)) !== -1) { // Set to position of the last character in prefix pos += prefix.length - 1; width = 1; // Consume all leading whitespace while (isWhitespace(next())) { /* empty */ } // Initialize URL state const url = { start: pos, end: -1, specifier: '' }; 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.specifier += 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.specifier += String.fromCodePoint(current); break; } } next(); continue; } } }
{ "end_byte": 3829, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/css-import-lexer.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/migration_spec.ts_0_1299
/** * @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 { EmptyTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Builders, ProjectType, WorkspaceSchema } from '../../utility/workspace-models'; function createWorkSpaceConfig(tree: UnitTestTree) { const angularConfig: WorkspaceSchema = { version: 1, projects: { app: { root: '/project/app', sourceRoot: 'src', projectType: ProjectType.Application, prefix: 'app', architect: { build: { builder: Builders.Browser, options: { tsConfig: 'src/tsconfig.app.json', main: 'src/main.ts', polyfills: 'src/polyfills.ts', outputPath: 'dist/project', resourcesOutputPath: '/resources', }, }, }, }, }, }; tree.create('/angular.json', JSON.stringify(angularConfig, undefined, 2)); tree.create('/tsconfig.json', JSON.stringify({}, undefined, 2)); tree.create('/package.json', JSON.stringify({}, undefined, 2)); }
{ "end_byte": 1299, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration_spec.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/migration_spec.ts_1301_9260
describe(`Migration to use the application builder`, () => { const schematicName = 'use-application-builder'; const schematicRunner = new SchematicTestRunner( 'migrations', require.resolve('../migration-collection.json'), ); let tree: UnitTestTree; beforeEach(() => { tree = new UnitTestTree(new EmptyTree()); createWorkSpaceConfig(tree); }); it(`should replace 'outputPath' to string if 'resourcesOutputPath' is set to 'media'`, async () => { // Replace resourcesOutputPath tree.overwrite('angular.json', tree.readContent('angular.json').replace('/resources', 'media')); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { outputPath, resourcesOutputPath } = app.architect['build'].options; expect(outputPath).toEqual({ base: 'dist/project', }); expect(resourcesOutputPath).toBeUndefined(); }); it(`should set 'outputPath.media' if 'resourcesOutputPath' is set and is not 'media'`, async () => { const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { outputPath, resourcesOutputPath } = app.architect['build'].options; expect(outputPath).toEqual({ base: 'dist/project', media: 'resources', }); expect(resourcesOutputPath).toBeUndefined(); }); it(`should remove 'browser' portion from 'outputPath'`, async () => { // Replace outputPath tree.overwrite( 'angular.json', tree.readContent('angular.json').replace('dist/project/', 'dist/project/browser/'), ); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { outputPath } = app.architect['build'].options; expect(outputPath).toEqual({ base: 'dist/project', media: 'resources', }); }); it('should remove tilde prefix from CSS @import specifiers', async () => { // Replace outputPath tree.create( '/project/app/src/styles.css', '@import "~@angular/material";\n@import "./abc.css"\n', ); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.css'); expect(content).toEqual('@import "@angular/material";\n@import "./abc.css"\n'); }); it('should remove caret prefix from CSS @import specifiers and as external dependency', async () => { // Replace outputPath tree.create( '/project/app/src/styles.css', '@import "^@angular/material";\n@import "./abc.css"\n', ); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.css'); expect(content).toEqual('@import "@angular/material";\n@import "./abc.css"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { externalDependencies } = app.architect['build'].options; expect(externalDependencies).toEqual(['@angular/material']); }); it('should remove tilde prefix from SCSS @import specifiers', async () => { // Replace outputPath tree.create('/project/app/src/styles.scss', '@import "~@angular/material";\n@import "./abc"\n'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@import "@angular/material";\n@import "./abc"\n'); }); it('should remove tilde prefix from SCSS @use specifiers', async () => { // Replace outputPath tree.create('/project/app/src/styles.scss', '@use "~@angular/material";\n@import "./abc"\n'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@use "@angular/material";\n@import "./abc"\n'); }); it('should remove caret prefix from SCSS @import specifiers and as external dependency', async () => { // Replace outputPath tree.create('/project/app/src/styles.scss', '@import "^@angular/material";\n@import "./abc"\n'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@import "@angular/material";\n@import "./abc"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { externalDependencies } = app.architect['build'].options; expect(externalDependencies).toEqual(['@angular/material']); }); it('should remove caret prefix from SCSS @use specifiers and as external dependency', async () => { // Replace outputPath tree.create('/project/app/src/styles.scss', '@use "^@angular/material";\n@import "./abc"\n'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@use "@angular/material";\n@import "./abc"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { externalDependencies } = app.architect['build'].options; expect(externalDependencies).toEqual(['@angular/material']); }); it('should add SCSS workspace include path for root referenced @import specifiers', async () => { // Replace outputPath tree.create( '/project/app/src/styles.scss', '@use "@angular/material";\n@import "some/path/abc"\n', ); tree.create('/some/path/abc.scss', ''); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@use "@angular/material";\n@import "some/path/abc"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { stylePreprocessorOptions } = app.architect['build'].options; expect(stylePreprocessorOptions).toEqual({ includePaths: ['.'] }); }); it('should add SCSS workspace include path for root referenced @use specifiers', async () => { // Replace outputPath tree.create( '/project/app/src/styles.scss', '@use "@angular/material";\n@use "some/path/abc"\n', ); tree.create('/some/path/abc.scss', ''); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@use "@angular/material";\n@use "some/path/abc"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { stylePreprocessorOptions } = app.architect['build'].options; expect(stylePreprocessorOptions).toEqual({ includePaths: ['.'] }); }); it('should not add SCSS workspace include path for root referenced @import specifiers with ".import" local file', async () => { // Replace outputPath tree.create( '/project/app/src/styles.scss', '@use "@angular/material";\n@import "some/path/abc"\n', ); tree.create('/some/path/abc.scss', ''); tree.create('/project/app/src/some/path/abc.import.scss', ''); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@use "@angular/material";\n@import "some/path/abc"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { stylePreprocessorOptions } = app.architect['build'].options; expect(stylePreprocessorOptions).toBeUndefined(); });
{ "end_byte": 9260, "start_byte": 1301, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration_spec.ts" }
angular-cli/packages/schematics/angular/migrations/use-application-builder/migration_spec.ts_9264_12438
it('should add SCSS workspace include path for root referenced @use specifiers with ".import" local file', async () => { // Replace outputPath tree.create( '/project/app/src/styles.scss', '@use "@angular/material";\n@use "some/path/abc"\n', ); tree.create('/some/path/abc.scss', ''); tree.create('/project/app/src/some/path/abc.import.scss', ''); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const content = newTree.readText('/project/app/src/styles.scss'); expect(content).toEqual('@use "@angular/material";\n@use "some/path/abc"\n'); const { projects: { app }, } = JSON.parse(newTree.readContent('/angular.json')); const { stylePreprocessorOptions } = app.architect['build'].options; expect(stylePreprocessorOptions).toEqual({ includePaths: ['.'] }); }); it('should add "less" dependency when converting to "@angular/build" and a ".less" file is present', async () => { tree.create('/project/app/src/styles.less', ''); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { devDependencies } = JSON.parse(newTree.readContent('/package.json')); expect(devDependencies['less']).toBeDefined(); }); it('should not add "less" dependency when converting to "@angular/build" and a ".less" file is not present', async () => { const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { devDependencies } = JSON.parse(newTree.readContent('/package.json')); expect(devDependencies['less']).toBeUndefined(); }); it('should add "postcss" dependency when converting to "@angular/build" and postcss.config.json is present', async () => { tree.create('postcss.config.json', '{}'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { devDependencies } = JSON.parse(newTree.readContent('/package.json')); expect(devDependencies['postcss']).toBeDefined(); }); it('should add "postcss" dependency when converting to "@angular/build" and .postcssrc.json is present', async () => { tree.create('.postcssrc.json', '{}'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { devDependencies } = JSON.parse(newTree.readContent('/package.json')); expect(devDependencies['postcss']).toBeDefined(); }); it('should add "postcss" dependency when converting to "@angular/build" and .postcssrc.json is present in project', async () => { tree.create('/project/app/.postcssrc.json', '{}'); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { devDependencies } = JSON.parse(newTree.readContent('/package.json')); expect(devDependencies['postcss']).toBeDefined(); }); it('should not add "postcss" dependency when converting to "@angular/build" and a Postcss configuration is not present', async () => { const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { devDependencies } = JSON.parse(newTree.readContent('/package.json')); expect(devDependencies['postcss']).toBeUndefined(); }); });
{ "end_byte": 12438, "start_byte": 9264, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/use-application-builder/migration_spec.ts" }
angular-cli/packages/schematics/angular/migrations/update-workspace-config/migration.ts_0_3279
/** * @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 { Rule } from '@angular-devkit/schematics'; import { allTargetOptions, updateWorkspace } from '../../utility/workspace'; import { Builders, ProjectType } from '../../utility/workspace-models'; /** * Main entry point for the migration rule. * * This schematic migration performs updates to the Angular workspace configuration * to ensure that application projects are properly configured with polyfills * required for internationalization (`localize`). * * It specifically targets application projects that use either the `application` * or `browser-esbuild` builders. * * The migration process involves: * * 1. Iterating over all projects in the workspace. * 2. Checking each project to determine if it is an application-type project. * 3. For each application project, examining the associated build targets. * 4. If a build target's `localize` option is enabled but the polyfill * `@angular/localize/init` is missing from the `polyfills` array, the polyfill * is automatically added to ensure proper internationalization support. * * Additionally, this migration updates projects that use the `dev-server` or `extract-i18n` * builders to ensure that deprecated `browserTarget` options are migrated to the * newer `buildTarget` field. * */ export default function (): Rule { return updateWorkspace((workspace) => { for (const project of workspace.projects.values()) { if (project.extensions.projectType !== ProjectType.Application) { continue; } for (const target of project.targets.values()) { if (target.builder === Builders.DevServer || target.builder === Builders.ExtractI18n) { // Migrate `browserTarget` to `buildTarget` for (const [, options] of allTargetOptions(target, false)) { if (options['browserTarget'] && !options['buildTarget']) { options['buildTarget'] = options['browserTarget']; } delete options['browserTarget']; } } // Check if the target uses application-related builders if ( target.builder !== Builders.BuildApplication && target.builder !== Builders.Application && target.builder !== Builders.BrowserEsbuild ) { continue; } // Check if polyfills include '@angular/localize/init' const polyfills = target.options?.['polyfills']; if ( Array.isArray(polyfills) && polyfills.some( (polyfill) => typeof polyfill === 'string' && polyfill.startsWith('@angular/localize'), ) ) { // Skip if the polyfill is already present continue; } // Add '@angular/localize/init' polyfill if localize option is enabled for (const [, options] of allTargetOptions(target, false)) { if (options['localize']) { target.options ??= {}; ((target.options['polyfills'] ??= []) as string[]).push('@angular/localize/init'); break; } } } } }); }
{ "end_byte": 3279, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/update-workspace-config/migration.ts" }
angular-cli/packages/schematics/angular/migrations/update-workspace-config/migration_spec.ts_0_3271
/** * @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 { EmptyTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { ProjectType } from '../../utility/workspace-models'; function createWorkSpaceConfig(tree: UnitTestTree) { const angularConfig = { version: 1, projects: { app: { root: '/project/app', sourceRoot: '/project/app/src', projectType: ProjectType.Application, prefix: 'app', architect: { build: { builder: '@angular/build:application', options: { localize: true, polyfills: [], }, }, }, }, }, }; tree.create('/angular.json', JSON.stringify(angularConfig, undefined, 2)); } describe(`Migration to update the workspace configuration`, () => { const schematicName = 'update-workspace-config'; const schematicRunner = new SchematicTestRunner( 'migrations', require.resolve('../migration-collection.json'), ); let tree: UnitTestTree; beforeEach(() => { tree = new UnitTestTree(new EmptyTree()); createWorkSpaceConfig(tree); }); it(`should add '@angular/localize/init' to polyfills if localize is enabled`, async () => { const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { projects: { app }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } = newTree.readJson('/angular.json') as any; expect(app.architect.build.options.polyfills).toContain('@angular/localize/init'); }); it(`should not add '@angular/localize/init' to polyfills if it already exists`, async () => { // Add '@angular/localize/init' manually // eslint-disable-next-line @typescript-eslint/no-explicit-any const config = tree.readJson('/angular.json') as any; config.projects.app.architect.build.options.polyfills.push('@angular/localize/init'); tree.overwrite('/angular.json', JSON.stringify(config, undefined, 2)); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { projects: { app }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } = newTree.readJson('/angular.json') as any; const polyfills = app.architect.build.options.polyfills; expect(polyfills.filter((p: string) => p === '@angular/localize/init').length).toBe(1); }); it(`should not add polyfills if localize is not enabled`, async () => { // Disable 'localize' const config = JSON.parse(tree.readContent('/angular.json')); config.projects.app.architect.build.options.localize = false; tree.overwrite('/angular.json', JSON.stringify(config, undefined, 2)); const newTree = await schematicRunner.runSchematic(schematicName, {}, tree); const { projects: { app }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } = newTree.readJson('/angular.json') as any; expect(app.architect.build.options.polyfills).not.toContain('@angular/localize/init'); }); });
{ "end_byte": 3271, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/migrations/update-workspace-config/migration_spec.ts" }
angular-cli/packages/schematics/angular/interface/index.ts_0_536
/** * @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 { Rule } from '@angular-devkit/schematics'; import { generateFromFiles } from '../utility/generate-from-files'; import { Schema as InterfaceOptions } from './schema'; export default function (options: InterfaceOptions): Rule { options.type = options.type ? `.${options.type}` : ''; return generateFromFiles(options); }
{ "end_byte": 536, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interface/index.ts" }
angular-cli/packages/schematics/angular/interface/index_spec.ts_0_2520
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as InterfaceOptions } from './schema'; describe('Interface Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: InterfaceOptions = { name: 'foo', prefix: '', type: '', project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create one file', async () => { const tree = await schematicRunner.runSchematic('interface', defaultOptions, appTree); expect(tree.files).toContain('/projects/bar/src/app/foo.ts'); }); it('should create an interface named "Foo"', async () => { const tree = await schematicRunner.runSchematic('interface', defaultOptions, appTree); const fileContent = tree.readContent('/projects/bar/src/app/foo.ts'); expect(fileContent).toMatch(/export interface Foo/); }); it('should put type in the file name', async () => { const options = { ...defaultOptions, type: 'model' }; const tree = await schematicRunner.runSchematic('interface', options, appTree); expect(tree.files).toContain('/projects/bar/src/app/foo.model.ts'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('interface', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo.ts'); }); });
{ "end_byte": 2520, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interface/index_spec.ts" }
angular-cli/packages/schematics/angular/interface/files/__name@dasherize____type__.ts.template_0_56
export interface <%= prefix %><%= classify(name) %> { }
{ "end_byte": 56, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/interface/files/__name@dasherize____type__.ts.template" }
angular-cli/packages/schematics/angular/pipe/index.ts_0_1597
/** * @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 { Rule, Tree, apply, applyTemplates, chain, filter, mergeWith, move, noop, strings, url, } from '@angular-devkit/schematics'; import { addDeclarationToNgModule } from '../utility/add-declaration-to-ng-module'; import { findModuleFromOptions } from '../utility/find-module'; import { parseName } from '../utility/parse-name'; import { validateClassName } from '../utility/validation'; import { createDefaultPath } from '../utility/workspace'; import { Schema as PipeOptions } from './schema'; export default function (options: PipeOptions): Rule { return async (host: Tree) => { options.path ??= await createDefaultPath(host, options.project); options.module = findModuleFromOptions(host, options); const parsedPath = parseName(options.path, options.name); options.name = parsedPath.name; options.path = parsedPath.path; validateClassName(strings.classify(options.name)); const templateSource = apply(url('./files'), [ options.skipTests ? filter((path) => !path.endsWith('.spec.ts.template')) : noop(), applyTemplates({ ...strings, 'if-flat': (s: string) => (options.flat ? '' : s), ...options, }), move(parsedPath.path), ]); return chain([ addDeclarationToNgModule({ type: 'pipe', ...options, }), mergeWith(templateSource), ]); }; }
{ "end_byte": 1597, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/pipe/index.ts" }
angular-cli/packages/schematics/angular/pipe/index_spec.ts_0_7478
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { createAppModule, getFileContent } from '../utility/test'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as PipeOptions } from './schema'; describe('Pipe Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: PipeOptions = { name: 'foo', module: undefined, export: false, flat: true, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; const defaultNonStandaloneOptions: PipeOptions = { ...defaultOptions, standalone: false }; describe('standalone=false', () => { beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic( 'application', { ...appOptions, standalone: false }, appTree, ); }); it('should create a pipe', async () => { const tree = await schematicRunner.runSchematic('pipe', defaultNonStandaloneOptions, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo.pipe.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo.pipe.ts'); const moduleContent = getFileContent(tree, '/projects/bar/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo.pipe'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooPipe\r?\n/m); const fileContent = tree.readContent('/projects/bar/src/app/foo.pipe.ts'); expect(fileContent).toContain('transform(value: unknown, ...args: unknown[])'); }); it('should import into a specified module', async () => { const options = { ...defaultNonStandaloneOptions, module: 'app.module.ts' }; const tree = await schematicRunner.runSchematic('pipe', options, appTree); const appModule = getFileContent(tree, '/projects/bar/src/app/app.module.ts'); expect(appModule).toMatch(/import { FooPipe } from '.\/foo.pipe'/); }); it('should fail if specified module does not exist', async () => { const options = { ...defaultNonStandaloneOptions, module: '/projects/bar/src/app/app.moduleXXX.ts', }; await expectAsync(schematicRunner.runSchematic('pipe', options, appTree)).toBeRejected(); }); it('should handle a path in the name and module options', async () => { appTree = await schematicRunner.runSchematic( 'module', { name: 'admin/module', project: 'bar' }, appTree, ); const options = { ...defaultNonStandaloneOptions, module: 'admin/module' }; appTree = await schematicRunner.runSchematic('pipe', options, appTree); const content = appTree.readContent('/projects/bar/src/app/admin/module/module.module.ts'); expect(content).toMatch(/import { FooPipe } from '\.\.\/\.\.\/foo.pipe'/); }); it('should export the pipe', async () => { const options = { ...defaultNonStandaloneOptions, export: true }; const tree = await schematicRunner.runSchematic('pipe', options, appTree); const appModuleContent = getFileContent(tree, '/projects/bar/src/app/app.module.ts'); expect(appModuleContent).toMatch(/exports: \[\n(\s*) {2}FooPipe\n\1\]/); }); it('should respect the flat flag', async () => { const options = { ...defaultNonStandaloneOptions, flat: false }; const tree = await schematicRunner.runSchematic('pipe', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.pipe.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.pipe.ts'); const moduleContent = getFileContent(tree, '/projects/bar/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.pipe'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooPipe\r?\n/m); }); it('should use the module flag even if the module is a routing module', async () => { const routingFileName = 'app-routing.module.ts'; const routingModulePath = `/projects/bar/src/app/${routingFileName}`; const newTree = createAppModule(appTree, routingModulePath); const options = { ...defaultNonStandaloneOptions, module: routingFileName }; const tree = await schematicRunner.runSchematic('pipe', options, newTree); const content = getFileContent(tree, routingModulePath); expect(content).toMatch(/import { FooPipe } from '.\/foo.pipe/); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); // should fail without a module in that dir await expectAsync( schematicRunner.runSchematic('pipe', defaultNonStandaloneOptions, appTree), ).toBeRejected(); // move the module appTree.rename( '/projects/bar/src/app/app.module.ts', '/projects/bar/custom/app/app.module.ts', ); appTree = await schematicRunner.runSchematic('pipe', defaultNonStandaloneOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo.pipe.ts'); }); }); describe('standalone=true', () => { beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', { ...appOptions }, appTree); }); it('should create a standalone pipe', async () => { const tree = await schematicRunner.runSchematic('pipe', defaultOptions, appTree); const moduleContent = tree.readContent('/projects/bar/src/app/app.module.ts'); const pipeContent = tree.readContent('/projects/bar/src/app/foo.pipe.ts'); expect(pipeContent).not.toContain('standalone'); expect(pipeContent).toContain('class FooPipe'); expect(moduleContent).not.toContain('FooPipe'); }); it('should respect the skipTests flag', async () => { const options = { ...defaultOptions, skipTests: true }; const tree = await schematicRunner.runSchematic('pipe', options, appTree); const files = tree.files; expect(files).not.toContain('/projects/bar/src/app/foo.pipe.spec.ts'); expect(files).toContain('/projects/bar/src/app/foo.pipe.ts'); }); it('should error when class name contains invalid characters', async () => { const options = { ...defaultOptions, name: '1Clazz' }; await expectAsync( schematicRunner.runSchematic('pipe', options, appTree), ).toBeRejectedWithError('Class name "1Clazz" is invalid.'); }); }); });
{ "end_byte": 7478, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/pipe/index_spec.ts" }
angular-cli/packages/schematics/angular/pipe/files/__name@dasherize@if-flat__/__name@dasherize__.pipe.spec.ts.template_0_248
import { <%= classify(name) %>Pipe } from './<%= dasherize(name) %>.pipe'; describe('<%= classify(name) %>Pipe', () => { it('create an instance', () => { const pipe = new <%= classify(name) %>Pipe(); expect(pipe).toBeTruthy(); }); });
{ "end_byte": 248, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/pipe/files/__name@dasherize@if-flat__/__name@dasherize__.pipe.spec.ts.template" }
angular-cli/packages/schematics/angular/pipe/files/__name@dasherize@if-flat__/__name@dasherize__.pipe.ts.template_0_295
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: '<%= camelize(name) %>'<% if(!standalone) {%>, standalone: false<%}%> }) export class <%= classify(name) %>Pipe implements PipeTransform { transform(value: unknown, ...args: unknown[]): unknown { return null; } }
{ "end_byte": 295, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/pipe/files/__name@dasherize@if-flat__/__name@dasherize__.pipe.ts.template" }
angular-cli/packages/schematics/angular/config/index.ts_0_2951
/** * @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 { Rule, SchematicsException, apply, applyTemplates, filter, mergeWith, move, strings, url, } from '@angular-devkit/schematics'; import { AngularBuilder, readWorkspace, updateWorkspace } from '@schematics/angular/utility'; import { posix as path } from 'path'; import { relativePathToWorkspaceRoot } from '../utility/paths'; import { Schema as ConfigOptions, Type as ConfigType } from './schema'; export default function (options: ConfigOptions): Rule { switch (options.type) { case ConfigType.Karma: return addKarmaConfig(options); case ConfigType.Browserslist: return addBrowserslistConfig(options); default: throw new SchematicsException(`"${options.type}" is an unknown configuration file type.`); } } function addBrowserslistConfig(options: ConfigOptions): Rule { return async (host) => { const workspace = await readWorkspace(host); const project = workspace.projects.get(options.project); if (!project) { throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`); } return mergeWith( apply(url('./files'), [ filter((p) => p.endsWith('.browserslistrc.template')), applyTemplates({}), move(project.root), ]), ); }; } function addKarmaConfig(options: ConfigOptions): Rule { return updateWorkspace((workspace) => { const project = workspace.projects.get(options.project); if (!project) { throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`); } const testTarget = project.targets.get('test'); if (!testTarget) { throw new SchematicsException( `No "test" target found for project "${options.project}".` + ' A "test" target is required to generate a karma configuration.', ); } if (testTarget.builder !== AngularBuilder.Karma) { throw new SchematicsException( `Cannot add a karma configuration as builder for "test" target in project does not use "${AngularBuilder.Karma}".`, ); } testTarget.options ??= {}; testTarget.options.karmaConfig = path.join(project.root, 'karma.conf.js'); // If scoped project (i.e. "@foo/bar"), convert dir to "foo/bar". let folderName = options.project.startsWith('@') ? options.project.slice(1) : options.project; if (/[A-Z]/.test(folderName)) { folderName = strings.dasherize(folderName); } return mergeWith( apply(url('./files'), [ filter((p) => p.endsWith('karma.conf.js.template')), applyTemplates({ relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(project.root), folderName, }), move(project.root), ]), ); }); }
{ "end_byte": 2951, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/config/index.ts" }
angular-cli/packages/schematics/angular/config/index_spec.ts_0_2681
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ConfigOptions, Type as ConfigType } from './schema'; describe('Config Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '15.0.0', }; const defaultAppOptions: ApplicationOptions = { name: 'foo', inlineStyle: true, inlineTemplate: true, routing: false, skipPackageJson: false, }; let applicationTree: UnitTestTree; function runConfigSchematic(type: ConfigType): Promise<UnitTestTree> { return schematicRunner.runSchematic<ConfigOptions>( 'config', { project: 'foo', type, }, applicationTree, ); } beforeEach(async () => { const workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions); applicationTree = await schematicRunner.runSchematic( 'application', defaultAppOptions, workspaceTree, ); }); describe(`when 'type' is 'karma'`, () => { it('should create a karma.conf.js file', async () => { const tree = await runConfigSchematic(ConfigType.Karma); expect(tree.exists('projects/foo/karma.conf.js')).toBeTrue(); }); it('should set the right coverage folder', async () => { const tree = await runConfigSchematic(ConfigType.Karma); const karmaConf = tree.readText('projects/foo/karma.conf.js'); expect(karmaConf).toContain(`dir: require('path').join(__dirname, '../../coverage/foo')`); }); it(`should set 'karmaConfig' in test builder`, async () => { const tree = await runConfigSchematic(ConfigType.Karma); const config = JSON.parse(tree.readContent('/angular.json')); const prj = config.projects.foo; const { karmaConfig } = prj.architect.test.options; expect(karmaConfig).toBe('projects/foo/karma.conf.js'); }); }); describe(`when 'type' is 'browserslist'`, () => { it('should create a .browserslistrc file', async () => { const tree = await runConfigSchematic(ConfigType.Browserslist); expect(tree.exists('projects/foo/.browserslistrc')).toBeTrue(); }); }); });
{ "end_byte": 2681, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/config/index_spec.ts" }
angular-cli/packages/schematics/angular/config/files/karma.conf.js.template_0_1278
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { jasmine: { // you can add configuration options for Jasmine here // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html // for example, you can disable the random execution with `random: false` // or set a specific seed with `seed: 4321` }, }, jasmineHtmlReporter: { suppressAll: true // removes the duplicated traces }, coverageReporter: { dir: require('path').join(__dirname, '<%= relativePathToWorkspaceRoot %>/coverage/<%= folderName %>'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, reporters: ['progress', 'kjhtml'], browsers: ['Chrome'], restartOnFileChange: true }); };
{ "end_byte": 1278, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/config/files/karma.conf.js.template" }
angular-cli/packages/schematics/angular/environments/index.ts_0_5327
/** * @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 { Rule, SchematicsException, chain } from '@angular-devkit/schematics'; import { AngularBuilder, TargetDefinition, updateWorkspace } from '@schematics/angular/utility'; import { posix as path } from 'path'; import { Schema as EnvironmentOptions } from './schema'; const ENVIRONMENTS_DIRECTORY = 'environments'; const ENVIRONMENT_FILE_CONTENT = 'export const environment = {};\n'; export default function (options: EnvironmentOptions): Rule { return updateWorkspace((workspace) => { const project = workspace.projects.get(options.project); if (!project) { throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`); } const type = project.extensions['projectType']; if (type !== 'application') { return log( 'error', 'Only application project types are support by this schematic.' + type ? ` Project "${options.project}" has a "projectType" of "${type}".` : ` Project "${options.project}" has no "projectType" defined.`, ); } const buildTarget = project.targets.get('build'); if (!buildTarget) { return log( 'error', `No "build" target found for project "${options.project}".` + ' A "build" target is required to generate environment files.', ); } const serverTarget = project.targets.get('server'); const sourceRoot = project.sourceRoot ?? path.join(project.root, 'src'); // The generator needs to be iterated prior to returning to ensure all workspace changes that occur // within the generator are present for `updateWorkspace` when it writes the workspace file. return chain([ ...generateConfigurationEnvironments(buildTarget, serverTarget, sourceRoot, options.project), ]); }); } function createIfMissing(path: string): Rule { return (tree, context) => { if (tree.exists(path)) { context.logger.info(`Skipping creation of already existing environment file "${path}".`); } else { tree.create(path, ENVIRONMENT_FILE_CONTENT); } }; } function log(type: 'info' | 'warn' | 'error', text: string): Rule { return (_, context) => context.logger[type](text); } function* generateConfigurationEnvironments( buildTarget: TargetDefinition, serverTarget: TargetDefinition | undefined, sourceRoot: string, projectName: string, ): Iterable<Rule> { if ( buildTarget.builder !== AngularBuilder.Browser && buildTarget.builder !== AngularBuilder.BrowserEsbuild && buildTarget.builder !== AngularBuilder.Application ) { yield log( 'warn', `"build" target found for project "${projectName}" has a third-party builder "${buildTarget.builder}".` + ' The generated project options may not be compatible with this builder.', ); } if (serverTarget && serverTarget.builder !== AngularBuilder.Server) { yield log( 'warn', `"server" target found for project "${projectName}" has a third-party builder "${buildTarget.builder}".` + ' The generated project options may not be compatible with this builder.', ); } // Create default environment file const defaultFilePath = path.join(sourceRoot, ENVIRONMENTS_DIRECTORY, 'environment.ts'); yield createIfMissing(defaultFilePath); const configurationEntries = [ ...Object.entries(buildTarget.configurations ?? {}), ...Object.entries(serverTarget?.configurations ?? {}), ]; const addedFiles = new Set<string>(); for (const [name, configurationOptions] of configurationEntries) { if (!configurationOptions) { // Invalid configuration continue; } // Default configuration will use the default environment file if (name === buildTarget.defaultConfiguration) { continue; } const configurationFilePath = path.join( sourceRoot, ENVIRONMENTS_DIRECTORY, `environment.${name}.ts`, ); // Add file replacement option entry for the configuration environment file const replacements = (configurationOptions['fileReplacements'] ??= []) as { replace: string; with: string; }[]; const existing = replacements.find((value) => value.replace === defaultFilePath); if (existing) { if (existing.with === configurationFilePath) { yield log( 'info', `Skipping addition of already existing file replacements option for "${defaultFilePath}" to "${configurationFilePath}".`, ); } else { yield log( 'warn', `Configuration "${name}" has a file replacements option for "${defaultFilePath}" but with a different replacement.` + ` Expected "${configurationFilePath}" but found "${existing.with}". This may result in unexpected build behavior.`, ); } } else { replacements.push({ replace: defaultFilePath, with: configurationFilePath }); } // Create configuration specific environment file if not already added if (!addedFiles.has(configurationFilePath)) { addedFiles.add(configurationFilePath); yield createIfMissing(configurationFilePath); } } }
{ "end_byte": 5327, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/environments/index.ts" }
angular-cli/packages/schematics/angular/environments/index_spec.ts_0_6612
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Builders } from '../utility/workspace-models'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as EnvironmentOptions } from './schema'; describe('Environments Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '15.0.0', }; const defaultOptions: EnvironmentOptions = { project: 'foo', }; const defaultAppOptions: ApplicationOptions = { name: 'foo', inlineStyle: true, inlineTemplate: true, routing: false, skipPackageJson: false, minimal: true, }; let applicationTree: UnitTestTree; function runEnvironmentsSchematic(): Promise<UnitTestTree> { return schematicRunner.runSchematic('environments', defaultOptions, applicationTree); } function convertBuilderToLegacyBrowser(): void { const config = JSON.parse(applicationTree.readContent('/angular.json')); const build = config.projects.foo.architect.build; build.builder = Builders.Browser; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; applicationTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2)); } beforeEach(async () => { const workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions); applicationTree = await schematicRunner.runSchematic( 'application', defaultAppOptions, workspaceTree, ); }); it('should create a default environment typescript file', async () => { const tree = await runEnvironmentsSchematic(); expect(tree.readText('projects/foo/src/environments/environment.ts')).toEqual( 'export const environment = {};\n', ); }); it('should create a development configuration environment typescript file', async () => { const tree = await runEnvironmentsSchematic(); expect(tree.readText('projects/foo/src/environments/environment.development.ts')).toEqual( 'export const environment = {};\n', ); }); it('should create environment typescript files for additional configurations', async () => { const initialWorkspace = JSON.parse(applicationTree.readContent('/angular.json')); initialWorkspace.projects.foo.architect.build.configurations.staging = {}; applicationTree.overwrite('/angular.json', JSON.stringify(initialWorkspace)); const tree = await runEnvironmentsSchematic(); expect(tree.readText('projects/foo/src/environments/environment.development.ts')).toEqual( 'export const environment = {};\n', ); expect(tree.readText('projects/foo/src/environments/environment.staging.ts')).toEqual( 'export const environment = {};\n', ); }); it('should update the angular.json file replacements option for the development configuration', async () => { const tree = await runEnvironmentsSchematic(); const workspace = JSON.parse(tree.readContent('/angular.json')); const developmentConfiguration = workspace.projects.foo.architect.build.configurations.development; expect(developmentConfiguration).toEqual( jasmine.objectContaining({ fileReplacements: [ { replace: 'projects/foo/src/environments/environment.ts', with: 'projects/foo/src/environments/environment.development.ts', }, ], }), ); }); it('should update the angular.json file replacements option for additional configurations', async () => { const initialWorkspace = JSON.parse(applicationTree.readContent('/angular.json')); initialWorkspace.projects.foo.architect.build.configurations.staging = {}; applicationTree.overwrite('/angular.json', JSON.stringify(initialWorkspace)); const tree = await runEnvironmentsSchematic(); const workspace = JSON.parse(tree.readContent('/angular.json')); const developmentConfiguration = workspace.projects.foo.architect.build.configurations.development; expect(developmentConfiguration).toEqual( jasmine.objectContaining({ fileReplacements: [ { replace: 'projects/foo/src/environments/environment.ts', with: 'projects/foo/src/environments/environment.development.ts', }, ], }), ); const stagingConfiguration = workspace.projects.foo.architect.build.configurations.staging; expect(stagingConfiguration).toEqual( jasmine.objectContaining({ fileReplacements: [ { replace: 'projects/foo/src/environments/environment.ts', with: 'projects/foo/src/environments/environment.staging.ts', }, ], }), ); }); it('should update the angular.json file replacements option for server configurations', async () => { convertBuilderToLegacyBrowser(); await schematicRunner.runSchematic( 'server', { project: 'foo', skipInstall: true }, applicationTree, ); const tree = await runEnvironmentsSchematic(); const workspace = JSON.parse(tree.readContent('/angular.json')); const developmentConfiguration = workspace.projects.foo.architect.build.configurations.development; expect(developmentConfiguration).toEqual( jasmine.objectContaining({ fileReplacements: [ { replace: 'projects/foo/src/environments/environment.ts', with: 'projects/foo/src/environments/environment.development.ts', }, ], }), ); const serverDevelopmentConfiguration = workspace.projects.foo.architect.server.configurations.development; expect(serverDevelopmentConfiguration).toEqual( jasmine.objectContaining({ fileReplacements: [ { replace: 'projects/foo/src/environments/environment.ts', with: 'projects/foo/src/environments/environment.development.ts', }, ], }), ); }); });
{ "end_byte": 6612, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/environments/index_spec.ts" }
angular-cli/packages/schematics/angular/module/index.ts_0_5755
/** * @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 { Rule, Tree, apply, applyTemplates, chain, filter, mergeWith, move, noop, schematic, strings, url, } from '@angular-devkit/schematics'; import { join } from 'node:path/posix'; import { Schema as ComponentOptions } from '../component/schema'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { addImportToModule, addRouteDeclarationToModule } from '../utility/ast-utils'; import { InsertChange } from '../utility/change'; import { MODULE_EXT, ROUTING_MODULE_EXT, buildRelativePath, findModuleFromOptions, } from '../utility/find-module'; import { parseName } from '../utility/parse-name'; import { validateClassName } from '../utility/validation'; import { createDefaultPath } from '../utility/workspace'; import { Schema as ModuleOptions, RoutingScope } from './schema'; function buildRelativeModulePath(options: ModuleOptions, modulePath: string): string { const importModulePath = join( options.path ?? '', options.flat ? '' : strings.dasherize(options.name), strings.dasherize(options.name) + '.module', ); return buildRelativePath(modulePath, importModulePath); } function addImportToNgModule(options: ModuleOptions): Rule { return (host: Tree) => { if (!options.module) { return host; } const modulePath = options.module; const sourceText = host.readText(modulePath); const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true); const relativePath = buildRelativeModulePath(options, modulePath); const changes = addImportToModule( source, modulePath, strings.classify(`${options.name}Module`), relativePath, ); const recorder = host.beginUpdate(modulePath); for (const change of changes) { if (change instanceof InsertChange) { recorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(recorder); return host; }; } function addRouteDeclarationToNgModule( options: ModuleOptions, routingModulePath: string | undefined, ): Rule { return (host: Tree) => { if (!options.route) { return host; } if (!options.module) { throw new Error('Module option required when creating a lazy loaded routing module.'); } let path: string; if (routingModulePath) { path = routingModulePath; } else { path = options.module; } const sourceText = host.readText(path); const addDeclaration = addRouteDeclarationToModule( ts.createSourceFile(path, sourceText, ts.ScriptTarget.Latest, true), path, buildRoute(options, options.module), ) as InsertChange; const recorder = host.beginUpdate(path); recorder.insertLeft(addDeclaration.pos, addDeclaration.toAdd); host.commitUpdate(recorder); return host; }; } function getRoutingModulePath(host: Tree, modulePath: string): string | undefined { const routingModulePath = modulePath.endsWith(ROUTING_MODULE_EXT) ? modulePath : modulePath.replace(MODULE_EXT, ROUTING_MODULE_EXT); return host.exists(routingModulePath) ? routingModulePath : undefined; } function buildRoute(options: ModuleOptions, modulePath: string) { const relativeModulePath = buildRelativeModulePath(options, modulePath); const moduleName = `${strings.classify(options.name)}Module`; const loadChildren = `() => import('${relativeModulePath}').then(m => m.${moduleName})`; return `{ path: '${options.route}', loadChildren: ${loadChildren} }`; } export default function (options: ModuleOptions): Rule { return async (host: Tree) => { if (options.path === undefined) { options.path = await createDefaultPath(host, options.project); } if (options.module) { options.module = findModuleFromOptions(host, options); } let routingModulePath; const isLazyLoadedModuleGen = !!(options.route && options.module); if (isLazyLoadedModuleGen) { options.routingScope = RoutingScope.Child; routingModulePath = getRoutingModulePath(host, options.module as string); } const parsedPath = parseName(options.path, options.name); options.name = parsedPath.name; options.path = parsedPath.path; validateClassName(strings.classify(options.name)); const templateSource = apply(url('./files'), [ options.routing || (isLazyLoadedModuleGen && routingModulePath) ? noop() : filter((path) => !path.endsWith('-routing.module.ts.template')), applyTemplates({ ...strings, 'if-flat': (s: string) => (options.flat ? '' : s), lazyRoute: isLazyLoadedModuleGen, lazyRouteWithoutRouteModule: isLazyLoadedModuleGen && !routingModulePath, lazyRouteWithRouteModule: isLazyLoadedModuleGen && !!routingModulePath, ...options, }), move(parsedPath.path), ]); const moduleDasherized = strings.dasherize(options.name); const modulePath = `${ !options.flat ? moduleDasherized + '/' : '' }${moduleDasherized}.module.ts`; const componentOptions: ComponentOptions = { module: modulePath, flat: options.flat, name: options.name, path: options.path, project: options.project, standalone: false, }; return chain([ !isLazyLoadedModuleGen ? addImportToNgModule(options) : noop(), addRouteDeclarationToNgModule(options, routingModulePath), mergeWith(templateSource), isLazyLoadedModuleGen ? schematic('component', componentOptions) : noop(), ]); }; }
{ "end_byte": 5755, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/module/index.ts" }
angular-cli/packages/schematics/angular/module/index_spec.ts_0_5168
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ModuleOptions } from './schema'; describe('Module Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ModuleOptions = { name: 'foo', module: undefined, flat: false, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, standalone: false, routing: true, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create a module', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('module', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.module.ts'); }); it('should import into another module', async () => { const options = { ...defaultOptions, module: 'app.module.ts' }; const tree = await schematicRunner.runSchematic('module', options, appTree); const content = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(content).toMatch(/import { FooModule } from '.\/foo\/foo.module'/); expect(content).toMatch(/imports: \[[^\]]*FooModule[^\]]*\]/m); }); it('should import into another module when using flat', async () => { const options = { ...defaultOptions, flat: true, module: 'app.module.ts' }; const tree = await schematicRunner.runSchematic('module', options, appTree); const content = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(content).toMatch(/import { FooModule } from '.\/foo.module'/); expect(content).toMatch(/imports: \[[^\]]*FooModule[^\]]*\]/m); }); it('should import into another module when using flat', async () => { const options = { ...defaultOptions, flat: true, module: 'app.module.ts' }; const tree = await schematicRunner.runSchematic('module', options, appTree); const content = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(content).toMatch(/import { FooModule } from '.\/foo.module'/); expect(content).toMatch(/imports: \[[^\]]*FooModule[^\]]*\]/m); }); it('should import into another module (deep)', async () => { let tree = appTree; tree = await schematicRunner.runSchematic( 'module', { ...defaultOptions, path: 'projects/bar/src/app/sub1', name: 'test1', }, tree, ); tree = await schematicRunner.runSchematic( 'module', { ...defaultOptions, path: 'projects/bar/src/app/sub2', name: 'test2', module: '../sub1/test1', }, tree, ); const content = tree.readContent('/projects/bar/src/app/sub1/test1/test1.module.ts'); expect(content).toMatch(/import { Test2Module } from '..\/..\/sub2\/test2\/test2.module'/); }); it('should create a routing module', async () => { const options = { ...defaultOptions, routing: true }; const tree = await schematicRunner.runSchematic('module', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.module.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo-routing.module.ts'); const moduleContent = tree.readContent('/projects/bar/src/app/foo/foo.module.ts'); expect(moduleContent).toMatch(/import { FooRoutingModule } from '.\/foo-routing.module'/); const routingModuleContent = tree.readContent( '/projects/bar/src/app/foo/foo-routing.module.ts', ); expect(routingModuleContent).toMatch(/RouterModule.forChild\(routes\)/); }); it('should dasherize a name', async () => { const options = { ...defaultOptions, name: 'TwoWord' }; const tree = await schematicRunner.runSchematic('module', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/two-word/two-word.module.ts'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('module', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo/foo.module.ts'); });
{ "end_byte": 5168, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/module/index_spec.ts" }
angular-cli/packages/schematics/angular/module/index_spec.ts_5172_11808
describe('lazy route generator', () => { const options = { ...defaultOptions, route: '/new-route', module: 'app', }; it('should generate a lazy loaded module with a routing module', async () => { const tree = await schematicRunner.runSchematic('module', options, appTree); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/bar/src/app/foo/foo.module.ts', '/projects/bar/src/app/foo/foo-routing.module.ts', '/projects/bar/src/app/foo/foo.component.ts', '/projects/bar/src/app/foo/foo.component.html', '/projects/bar/src/app/foo/foo.component.css', ]), ); const appRoutingModuleContent = tree.readContent( '/projects/bar/src/app/app-routing.module.ts', ); expect(appRoutingModuleContent).toMatch( /path: '\/new-route', loadChildren: \(\) => import\('.\/foo\/foo.module'\).then\(m => m.FooModule\)/, ); const fooRoutingModuleContent = tree.readContent( '/projects/bar/src/app/foo/foo-routing.module.ts', ); expect(fooRoutingModuleContent).toMatch(/RouterModule.forChild\(routes\)/); expect(fooRoutingModuleContent).toMatch( /const routes: Routes = \[\r?\n?\s*{ path: '', component: FooComponent }\r?\n?\s*\];/, ); }); it('should generate a lazy loaded module with embedded route declarations', async () => { appTree.overwrite( '/projects/bar/src/app/app.module.ts', ` import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, RouterModule.forRoot([]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, ); appTree.delete('/projects/bar/src/app/app-routing.module.ts'); const tree = await schematicRunner.runSchematic('module', options, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo/foo.module.ts'); expect(files).not.toContain('/projects/bar/src/app/foo/foo-routing.module.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.component.ts'); expect(files).toContain('/projects/bar/src/app/foo/foo.component.html'); expect(files).toContain('/projects/bar/src/app/foo/foo.component.css'); const appModuleContent = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(appModuleContent).toMatch( /path: '\/new-route', loadChildren: \(\) => import\('.\/foo\/foo.module'\).then\(m => m.FooModule\)/, ); const fooModuleContent = tree.readContent('/projects/bar/src/app/foo/foo.module.ts'); expect(fooModuleContent).toMatch(/RouterModule.forChild\(routes\)/); expect(fooModuleContent).toMatch( /const routes: Routes = \[\r?\n?\s*{ path: '', component: FooComponent }\r?\n?\s*\];/, ); }); it('should generate a lazy loaded module when "flat" flag is true', async () => { const tree = await schematicRunner.runSchematic( 'module', { ...options, flat: true }, appTree, ); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/bar/src/app/foo.module.ts', '/projects/bar/src/app/foo-routing.module.ts', '/projects/bar/src/app/foo.component.ts', '/projects/bar/src/app/foo.component.html', '/projects/bar/src/app/foo.component.css', ]), ); const appRoutingModuleContent = tree.readContent( '/projects/bar/src/app/app-routing.module.ts', ); expect(appRoutingModuleContent).toMatch( /path: '\/new-route', loadChildren: \(\) => import\('.\/foo.module'\).then\(m => m.FooModule\)/, ); }); it('should generate a lazy loaded module and add route in another parallel routing module', async () => { await schematicRunner.runSchematic( 'module', { ...defaultOptions, name: 'foo', routing: true, }, appTree, ); const tree = await schematicRunner.runSchematic( 'module', { ...defaultOptions, name: 'bar', module: 'foo', route: 'new-route', }, appTree, ); expect(tree.files).toEqual( jasmine.arrayContaining([ '/projects/bar/src/app/foo/foo-routing.module.ts', '/projects/bar/src/app/foo/foo.module.ts', '/projects/bar/src/app/bar/bar-routing.module.ts', '/projects/bar/src/app/bar/bar.module.ts', '/projects/bar/src/app/bar/bar.component.ts', ]), ); const barRoutingModuleContent = tree.readContent( '/projects/bar/src/app/bar/bar-routing.module.ts', ); expect(barRoutingModuleContent).toContain(`path: '', component: BarComponent `); const fooRoutingModuleContent = tree.readContent( '/projects/bar/src/app/foo/foo-routing.module.ts', ); expect(fooRoutingModuleContent).toContain( `loadChildren: () => import('../bar/bar.module').then(m => m.BarModule)`, ); }); it('should not add reference to RouterModule when referencing lazy routing module', async () => { // Delete routing module appTree.delete('/projects/bar/src/app/app-routing.module.ts'); // Update app.module to contain the route config. appTree.overwrite( 'projects/bar/src/app/app.module.ts', ` import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [BrowserModule, RouterModule.forRoot([])], declarations: [AppComponent], }) export class AppModule {} `, ); const tree = await schematicRunner.runSchematic( 'module', { ...defaultOptions, name: 'bar', route: 'bar', routing: true, module: 'app.module.ts', }, appTree, ); const content = tree.readContent('/projects/bar/src/app/bar/bar.module.ts'); expect(content).toContain('RouterModule.forChild(routes)'); expect(content).not.toContain('BarRoutingModule'); }); }); });
{ "end_byte": 11808, "start_byte": 5172, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/module/index_spec.ts" }
angular-cli/packages/schematics/angular/module/files/__name@dasherize@if-flat__/__name@dasherize__-routing.module.ts.template_0_476
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router';<% if (lazyRoute) { %> import { <%= classify(name) %>Component } from './<%= dasherize(name) %>.component';<% } %> const routes: Routes = [<% if (lazyRoute) { %>{ path: '', component: <%= classify(name) %>Component }<% } %>]; @NgModule({ imports: [RouterModule.for<%= routingScope %>(routes)], exports: [RouterModule] }) export class <%= classify(name) %>RoutingModule { }
{ "end_byte": 476, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/module/files/__name@dasherize@if-flat__/__name@dasherize__-routing.module.ts.template" }
angular-cli/packages/schematics/angular/module/files/__name@dasherize@if-flat__/__name@dasherize__.module.ts.template_0_865
import { NgModule } from '@angular/core';<% if (commonModule) { %> import { CommonModule } from '@angular/common';<% } %><% if (lazyRouteWithoutRouteModule) { %> import { Routes, RouterModule } from '@angular/router';<% } %> <% if ((!lazyRoute && routing) || lazyRouteWithRouteModule) { %> import { <%= classify(name) %>RoutingModule } from './<%= dasherize(name) %>-routing.module';<% } %> <% if (lazyRouteWithoutRouteModule) { %> const routes: Routes = [ { path: '', component: <%= classify(name) %>Component } ];<% } %> @NgModule({ declarations: [], imports: [<% if (commonModule) { %> CommonModule<% } %><% if ((!lazyRoute && routing) || lazyRouteWithRouteModule) { %>, <%= classify(name) %>RoutingModule<% } %><% if (lazyRouteWithoutRouteModule) { %>, RouterModule.forChild(routes)<% } %> ] }) export class <%= classify(name) %>Module { }
{ "end_byte": 865, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/module/files/__name@dasherize@if-flat__/__name@dasherize__.module.ts.template" }
angular-cli/packages/schematics/angular/workspace/index.ts_0_787
/** * @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 { Rule, apply, applyTemplates, filter, mergeWith, noop, strings, url, } from '@angular-devkit/schematics'; import { latestVersions } from '../utility/latest-versions'; import { Schema as WorkspaceOptions } from './schema'; export default function (options: WorkspaceOptions): Rule { return mergeWith( apply(url('./files'), [ options.minimal ? filter((path) => !path.endsWith('editorconfig.template')) : noop(), applyTemplates({ utils: strings, ...options, 'dot': '.', latestVersions, }), ]), ); }
{ "end_byte": 787, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/index.ts" }
angular-cli/packages/schematics/angular/workspace/index_spec.ts_0_5257
/** * @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 { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import { parse as parseJson } from 'jsonc-parser'; import { latestVersions } from '../utility/latest-versions'; import { Schema as WorkspaceOptions } from './schema'; describe('Workspace Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: WorkspaceOptions = { name: 'foo', version: '6.0.0', }; it('should create all files of a workspace', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('workspace', options); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/.vscode/extensions.json', '/.vscode/launch.json', '/.vscode/tasks.json', '/.editorconfig', '/angular.json', '/.gitignore', '/package.json', '/README.md', '/tsconfig.json', ]), ); }); it('should set the name in package.json', async () => { const tree = await schematicRunner.runSchematic('workspace', defaultOptions); const pkg = JSON.parse(tree.readContent('/package.json')); expect(pkg.name).toEqual('foo'); }); it('should set the CLI version in package.json', async () => { const tree = await schematicRunner.runSchematic('workspace', defaultOptions); const pkg = JSON.parse(tree.readContent('/package.json')); expect(pkg.devDependencies['@angular/cli']).toMatch('6.0.0'); }); it('should use the latest known versions in package.json', async () => { const tree = await schematicRunner.runSchematic('workspace', defaultOptions); const pkg = JSON.parse(tree.readContent('/package.json')); expect(pkg.dependencies['@angular/core']).toEqual(latestVersions.Angular); expect(pkg.dependencies['rxjs']).toEqual(latestVersions['rxjs']); expect(pkg.dependencies['zone.js']).toEqual(latestVersions['zone.js']); expect(pkg.devDependencies['typescript']).toEqual(latestVersions['typescript']); }); it('should create correct files when using minimal', async () => { const tree = await schematicRunner.runSchematic('workspace', { ...defaultOptions, minimal: true, }); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/.vscode/extensions.json', '/.vscode/launch.json', '/.vscode/tasks.json', '/angular.json', '/.gitignore', '/package.json', '/README.md', '/tsconfig.json', ]), ); expect(files).not.toContain('/.editorconfig'); }); it('should set the `enableI18nLegacyMessageIdFormat` Angular compiler option', async () => { const tree = await schematicRunner.runSchematic('workspace', defaultOptions); const { angularCompilerOptions } = parseJson(tree.readContent('tsconfig.json').toString()); expect(angularCompilerOptions.enableI18nLegacyMessageIdFormat).toBe(false); }); it('should not add strict compiler options when false', async () => { const tree = await schematicRunner.runSchematic('workspace', { ...defaultOptions, strict: false, }); const { compilerOptions, angularCompilerOptions } = parseJson( tree.readContent('tsconfig.json').toString(), ); expect(compilerOptions.strict).toBeUndefined(); expect( Object.keys(angularCompilerOptions).filter((option) => option.startsWith('strict')), ).toEqual([]); }); it('should add strict compiler options when true', async () => { const tree = await schematicRunner.runSchematic('workspace', { ...defaultOptions, strict: true, }); const { compilerOptions, angularCompilerOptions } = parseJson( tree.readContent('tsconfig.json').toString(), ); expect(compilerOptions.strict).toBe(true); expect(angularCompilerOptions.strictTemplates).toBe(true); }); it('should add vscode testing configuration', async () => { const tree = await schematicRunner.runSchematic('workspace', { ...defaultOptions }); const { configurations } = parseJson(tree.readContent('.vscode/launch.json').toString()); expect(configurations).toContain(jasmine.objectContaining({ name: 'ng test' })); const { tasks } = parseJson(tree.readContent('.vscode/tasks.json').toString()); expect(tasks).toContain(jasmine.objectContaining({ type: 'npm', script: 'test' })); }); it('should not add vscode testing configuration when using minimal', async () => { const tree = await schematicRunner.runSchematic('workspace', { ...defaultOptions, minimal: true, }); const { configurations } = parseJson(tree.readContent('.vscode/launch.json').toString()); expect(configurations).not.toContain(jasmine.objectContaining({ name: 'ng test' })); const { tasks } = parseJson(tree.readContent('.vscode/tasks.json').toString()); expect(tasks).not.toContain(jasmine.objectContaining({ type: 'npm', script: 'test' })); }); });
{ "end_byte": 5257, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/index_spec.ts" }
angular-cli/packages/schematics/angular/workspace/files/angular.json.template_0_248
{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1,<% if (packageManager) { %> "cli": { "packageManager": "<%= packageManager %>" },<% } %> "newProjectRoot": "<%= newProjectRoot %>", "projects": { } }
{ "end_byte": 248, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/angular.json.template" }
angular-cli/packages/schematics/angular/workspace/files/__dot__editorconfig.template_0_314
# Editor configuration, see https://editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true [*.ts] quote_type = single ij_typescript_use_double_quotes = false [*.md] max_line_length = off trim_trailing_whitespace = false
{ "end_byte": 314, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/__dot__editorconfig.template" }
angular-cli/packages/schematics/angular/workspace/files/README.md.template_0_1498
# <%= utils.classify(name) %> This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version <%= version %>. ## Development server To start a local development server, run: ```bash ng serve ``` Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files. ## Code scaffolding Angular CLI includes powerful code scaffolding tools. To generate a new component, run: ```bash ng generate component component-name ``` For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run: ```bash ng generate --help ``` ## Building To build the project run: ```bash ng build ``` This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed. ## Running unit tests To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command: ```bash ng test ``` ## Running end-to-end tests For end-to-end (e2e) testing, run: ```bash ng e2e ``` Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs. ## Additional Resources For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
{ "end_byte": 1498, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/README.md.template" }
angular-cli/packages/schematics/angular/workspace/files/__dot__gitignore.template_0_587
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. # Compiled output /dist /tmp /out-tsc /bazel-out # Node /node_modules npm-debug.log yarn-error.log # IDEs and editors .idea/ .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # Visual Studio Code .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json .history/* # Miscellaneous /.angular/cache .sass-cache/ /connect.lock /coverage /libpeerconnection.log testem.log /typings # System files .DS_Store Thumbs.db
{ "end_byte": 587, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/__dot__gitignore.template" }
angular-cli/packages/schematics/angular/workspace/files/tsconfig.json.template_0_967
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc",<% if (strict) { %> "strict": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true,<% } %> "skipLibCheck": true, "isolatedModules": true, "esModuleInterop": true, "experimentalDecorators": true, "moduleResolution": "bundler", "importHelpers": true, "target": "ES2022", "module": "ES2022" }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false<% if (strict) { %>, "strictInjectionParameters": true, "strictInputAccessModifiers": true, "strictTemplates": true<% } %> } }
{ "end_byte": 967, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/tsconfig.json.template" }
angular-cli/packages/schematics/angular/workspace/files/package.json.template_0_1618
{ "name": "<%= utils.dasherize(name) %>", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "watch": "ng build --watch --configuration development"<% if (!minimal) { %>, "test": "ng test"<% } %> }, "private": true, "dependencies": { "@angular/animations": "<%= latestVersions.Angular %>", "@angular/common": "<%= latestVersions.Angular %>", "@angular/compiler": "<%= latestVersions.Angular %>", "@angular/core": "<%= latestVersions.Angular %>", "@angular/forms": "<%= latestVersions.Angular %>", "@angular/platform-browser": "<%= latestVersions.Angular %>", "@angular/platform-browser-dynamic": "<%= latestVersions.Angular %>", "@angular/router": "<%= latestVersions.Angular %>", "rxjs": "<%= latestVersions['rxjs'] %>", "tslib": "<%= latestVersions['tslib'] %>", "zone.js": "<%= latestVersions['zone.js'] %>" }, "devDependencies": { "@angular/cli": "<%= '^' + version %>", "@angular/compiler-cli": "<%= latestVersions.Angular %>",<% if (!minimal) { %> "@types/jasmine": "<%= latestVersions['@types/jasmine'] %>", "jasmine-core": "<%= latestVersions['jasmine-core'] %>", "karma": "<%= latestVersions['karma'] %>", "karma-chrome-launcher": "<%= latestVersions['karma-chrome-launcher'] %>", "karma-coverage": "<%= latestVersions['karma-coverage'] %>", "karma-jasmine": "<%= latestVersions['karma-jasmine'] %>", "karma-jasmine-html-reporter": "<%= latestVersions['karma-jasmine-html-reporter'] %>",<% } %> "typescript": "<%= latestVersions['typescript'] %>" } }
{ "end_byte": 1618, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/package.json.template" }
angular-cli/packages/schematics/angular/workspace/files/__dot__vscode/launch.json.template_0_498
{ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "ng serve", "type": "chrome", "request": "launch", "preLaunchTask": "npm: start", "url": "http://localhost:4200/" }<% if (!minimal) { %>, { "name": "ng test", "type": "chrome", "request": "launch", "preLaunchTask": "npm: test", "url": "http://localhost:9876/debug.html" }<% } %> ] }
{ "end_byte": 498, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/__dot__vscode/launch.json.template" }
angular-cli/packages/schematics/angular/workspace/files/__dot__vscode/extensions.json.template_0_130
{ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 "recommendations": ["angular.ng-template"] }
{ "end_byte": 130, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/__dot__vscode/extensions.json.template" }
angular-cli/packages/schematics/angular/workspace/files/__dot__vscode/tasks.json.template_0_966
{ // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "type": "npm", "script": "start", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } }<% if (!minimal) { %>, { "type": "npm", "script": "test", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } }<% } %> ] }
{ "end_byte": 966, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/workspace/files/__dot__vscode/tasks.json.template" }
angular-cli/packages/schematics/angular/enum/index.ts_0_526
/** * @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 { Rule } from '@angular-devkit/schematics'; import { generateFromFiles } from '../utility/generate-from-files'; import { Schema as EnumOptions } from './schema'; export default function (options: EnumOptions): Rule { options.type = options.type ? `.${options.type}` : ''; return generateFromFiles(options); }
{ "end_byte": 526, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/enum/index.ts" }
angular-cli/packages/schematics/angular/enum/index_spec.ts_0_2760
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as EnumOptions } from './schema'; describe('Enum Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: EnumOptions = { name: 'foo', project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create an enumeration', async () => { const tree = await schematicRunner.runSchematic('enum', defaultOptions, appTree); const files = tree.files; expect(files).toContain('/projects/bar/src/app/foo.ts'); }); it('should create an enumeration', async () => { const tree = await schematicRunner.runSchematic('enum', defaultOptions, appTree); const content = tree.readContent('/projects/bar/src/app/foo.ts'); expect(content).toMatch('export enum Foo {'); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.bar.sourceRoot = 'projects/bar/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); appTree = await schematicRunner.runSchematic('enum', defaultOptions, appTree); expect(appTree.files).toContain('/projects/bar/custom/app/foo.ts'); }); it('should put type in the file name', async () => { const options = { ...defaultOptions, type: 'enum' }; const tree = await schematicRunner.runSchematic('enum', options, appTree); expect(tree.files).toContain('/projects/bar/src/app/foo.enum.ts'); }); it('should error when class name contains invalid characters', async () => { const options = { ...defaultOptions, name: '1Clazz' }; await expectAsync(schematicRunner.runSchematic('enum', options, appTree)).toBeRejectedWithError( 'Class name "1Clazz" is invalid.', ); }); });
{ "end_byte": 2760, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/enum/index_spec.ts" }
angular-cli/packages/schematics/angular/enum/files/__name@dasherize____type__.ts.template_0_38
export enum <%= classify(name) %> { }
{ "end_byte": 38, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/enum/files/__name@dasherize____type__.ts.template" }
angular-cli/packages/schematics/angular/component/index.ts_0_2990
/** * @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 { FileOperator, Rule, SchematicsException, Tree, apply, applyTemplates, chain, filter, forEach, mergeWith, move, noop, strings, url, } from '@angular-devkit/schematics'; import { addDeclarationToNgModule } from '../utility/add-declaration-to-ng-module'; import { findModuleFromOptions } from '../utility/find-module'; import { parseName } from '../utility/parse-name'; import { validateClassName, validateHtmlSelector } from '../utility/validation'; import { buildDefaultPath, getWorkspace } from '../utility/workspace'; import { Schema as ComponentOptions, Style } from './schema'; function buildSelector(options: ComponentOptions, projectPrefix: string) { let selector = strings.dasherize(options.name); if (options.prefix) { selector = `${options.prefix}-${selector}`; } else if (options.prefix === undefined && projectPrefix) { selector = `${projectPrefix}-${selector}`; } return selector; } export default function (options: ComponentOptions): Rule { return async (host: Tree) => { const workspace = await getWorkspace(host); const project = workspace.projects.get(options.project); if (!project) { throw new SchematicsException(`Project "${options.project}" does not exist.`); } if (options.path === undefined) { options.path = buildDefaultPath(project); } options.module = findModuleFromOptions(host, options); const parsedPath = parseName(options.path, options.name); options.name = parsedPath.name; options.path = parsedPath.path; options.selector = options.selector || buildSelector(options, (project && project.prefix) || ''); validateHtmlSelector(options.selector); validateClassName(strings.classify(options.name)); const skipStyleFile = options.inlineStyle || options.style === Style.None; const templateSource = apply(url('./files'), [ options.skipTests ? filter((path) => !path.endsWith('.spec.ts.template')) : noop(), skipStyleFile ? filter((path) => !path.endsWith('.__style__.template')) : noop(), options.inlineTemplate ? filter((path) => !path.endsWith('.html.template')) : noop(), applyTemplates({ ...strings, 'if-flat': (s: string) => (options.flat ? '' : s), ...options, }), !options.type ? forEach(((file) => { return file.path.includes('..') ? { content: file.content, path: file.path.replace('..', '.'), } : file; }) as FileOperator) : noop(), move(parsedPath.path), ]); return chain([ addDeclarationToNgModule({ type: 'component', ...options, }), mergeWith(templateSource), ]); }; }
{ "end_byte": 2990, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/index.ts" }
angular-cli/packages/schematics/angular/component/index_spec.ts_0_576
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { Style as AppStyle, Schema as ApplicationOptions } from '../application/schema'; import { createAppModule } from '../utility/test'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { ChangeDetection, Schema as ComponentOptions, Style } from './schema';
{ "end_byte": 576, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/index_spec.ts" }
angular-cli/packages/schematics/angular/component/index_spec.ts_578_8563
describe('Component Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ComponentOptions = { name: 'foo', // path: 'src/app', inlineStyle: false, inlineTemplate: false, displayBlock: false, changeDetection: ChangeDetection.Default, style: Style.Css, type: 'Component', skipTests: false, module: undefined, export: false, project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, style: AppStyle.Css, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should contain a TestBed compileComponents call', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.spec.ts'); expect(tsContent).toContain('compileComponents()'); }); it('should set change detection to OnPush', async () => { const options = { ...defaultOptions, changeDetection: 'OnPush' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(tsContent).toMatch(/changeDetection: ChangeDetectionStrategy.OnPush/); }); it('should not set view encapsulation', async () => { const options = { ...defaultOptions }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(tsContent).not.toMatch(/encapsulation: ViewEncapsulation/); }); it('should set view encapsulation to Emulated', async () => { const options = { ...defaultOptions, viewEncapsulation: 'Emulated' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(tsContent).toMatch(/encapsulation: ViewEncapsulation.Emulated/); }); it('should set view encapsulation to None', async () => { const options = { ...defaultOptions, viewEncapsulation: 'None' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(tsContent).toMatch(/encapsulation: ViewEncapsulation.None/); }); it('should create a flat component', async () => { const options = { ...defaultOptions, flat: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/bar/src/app/foo.component.css', '/projects/bar/src/app/foo.component.html', '/projects/bar/src/app/foo.component.spec.ts', '/projects/bar/src/app/foo.component.ts', ]), ); }); it('should handle upper case paths', async () => { const pathOption = 'projects/bar/src/app/SOME/UPPER/DIR'; const options = { ...defaultOptions, path: pathOption }; const tree = await schematicRunner.runSchematic('component', options, appTree); let files = tree.files; let root = `/${pathOption}/foo/foo.component`; expect(files).toEqual( jasmine.arrayContaining([`${root}.css`, `${root}.html`, `${root}.spec.ts`, `${root}.ts`]), ); const options2 = { ...options, name: 'BAR' }; const tree2 = await schematicRunner.runSchematic('component', options2, tree); files = tree2.files; root = `/${pathOption}/bar/bar.component`; expect(files).toEqual( jasmine.arrayContaining([`${root}.css`, `${root}.html`, `${root}.spec.ts`, `${root}.ts`]), ); }); it('should create a component in a sub-directory', async () => { const options = { ...defaultOptions, path: 'projects/bar/src/app/a/b/c' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const files = tree.files; const root = `/${options.path}/foo/foo.component`; expect(files).toEqual( jasmine.arrayContaining([`${root}.css`, `${root}.html`, `${root}.spec.ts`, `${root}.ts`]), ); }); it('should use the prefix', async () => { const options = { ...defaultOptions, prefix: 'pre' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/selector: 'pre-foo'/); }); it('should error when name starts with a digit', async () => { const options = { ...defaultOptions, name: '1-one' }; await expectAsync( schematicRunner.runSchematic('component', options, appTree), ).toBeRejectedWithError('Selector "app-1-one" is invalid.'); }); it('should error when class name contains invalid characters', async () => { const options = { ...defaultOptions, name: '404' }; await expectAsync( schematicRunner.runSchematic('component', options, appTree), ).toBeRejectedWithError('Class name "404" is invalid.'); }); it('should allow dash in selector before a number', async () => { const options = { ...defaultOptions, name: 'one-1' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/one-1/one-1.component.ts'); expect(content).toMatch(/selector: 'app-one-1'/); }); it('should allow dash in selector before a number and with a custom prefix', async () => { const options = { ...defaultOptions, name: 'one-1', prefix: 'pre' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/one-1/one-1.component.ts'); expect(content).toMatch(/selector: 'pre-one-1'/); }); it('should allow dash in selector before a number and without a prefix', async () => { const options = { ...defaultOptions, name: 'one-2', selector: 'one-2' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/one-2/one-2.component.ts'); expect(content).toMatch(/selector: 'one-2'/); }); it('should use the default project prefix if none is passed', async () => { const options = { ...defaultOptions, prefix: undefined }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/selector: 'app-foo'/); }); it('should use the supplied prefix if it is ""', async () => { const options = { ...defaultOptions, prefix: '' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/selector: 'foo'/); }); it('should respect the inlineTemplate option', async () => { const options = { ...defaultOptions, inlineTemplate: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/template: /); expect(content).not.toMatch(/templateUrl: /); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.html'); });
{ "end_byte": 8563, "start_byte": 578, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/index_spec.ts" }
angular-cli/packages/schematics/angular/component/index_spec.ts_8567_16535
it('should respect the inlineStyle option', async () => { const options = { ...defaultOptions, inlineStyle: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/styles: `/); expect(content).not.toMatch(/styleUrl: /); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.css'); }); it('should respect the displayBlock option when inlineStyle is `false`', async () => { const options = { ...defaultOptions, displayBlock: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.css'); expect(content).toMatch(/:host {\r?\n {2}display: block;\r?\n}/); }); it('should respect the displayBlock option when inlineStyle is `false` and use correct syntax for `scss`', async () => { const options = { ...defaultOptions, displayBlock: true, style: 'scss' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.scss'); expect(content).toMatch(/:host {\r?\n {2}display: block;\r?\n}/); }); it('should respect the displayBlock option when inlineStyle is `false` and use correct syntax for `sass', async () => { const options = { ...defaultOptions, displayBlock: true, style: 'sass' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.sass'); expect(content).toMatch(/\\:host\r?\n {2}display: block;\r?\n/); }); it('should respect the displayBlock option when inlineStyle is `true`', async () => { const options = { ...defaultOptions, displayBlock: true, inlineStyle: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/:host {\r?\n(\s*)display: block;(\s*)}\r?\n/); }); it('should respect the style option', async () => { const options = { ...defaultOptions, style: Style.Sass }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).toMatch(/styleUrl: '.\/foo.component.sass/); expect(tree.files).toContain('/projects/bar/src/app/foo/foo.component.sass'); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.css'); }); it('should respect the style=none option', async () => { const options = { ...defaultOptions, style: Style.None }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).not.toMatch(/styleUrls: /); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.css'); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.none'); }); it('should respect the type option', async () => { const options = { ...defaultOptions, type: 'Route' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.route.ts'); const testContent = tree.readContent('/projects/bar/src/app/foo/foo.route.spec.ts'); expect(content).toContain('export class FooRoute'); expect(testContent).toContain("describe('FooRoute'"); expect(tree.files).toContain('/projects/bar/src/app/foo/foo.route.css'); expect(tree.files).toContain('/projects/bar/src/app/foo/foo.route.html'); }); it('should allow empty string in the type option', async () => { const options = { ...defaultOptions, type: '' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.ts'); const testContent = tree.readContent('/projects/bar/src/app/foo/foo.spec.ts'); expect(content).toContain('export class Foo'); expect(testContent).toContain("describe('Foo'"); expect(tree.files).toContain('/projects/bar/src/app/foo/foo.css'); expect(tree.files).toContain('/projects/bar/src/app/foo/foo.html'); }); it('should create the right selector with a path in the name', async () => { const options = { ...defaultOptions, name: 'sub/test' }; appTree = await schematicRunner.runSchematic('component', options, appTree); const content = appTree.readContent('/projects/bar/src/app/sub/test/test.component.ts'); expect(content).toMatch(/selector: 'app-test'/); }); it('should respect the skipSelector option', async () => { const options = { ...defaultOptions, name: 'sub/test', skipSelector: true }; appTree = await schematicRunner.runSchematic('component', options, appTree); const content = appTree.readContent('/projects/bar/src/app/sub/test/test.component.ts'); expect(content).not.toMatch(/selector: 'app-test'/); }); it('should respect the skipTests option', async () => { const options = { ...defaultOptions, skipTests: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/bar/src/app/foo/foo.component.css', '/projects/bar/src/app/foo/foo.component.html', '/projects/bar/src/app/foo/foo.component.ts', ]), ); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.spec.ts'); }); it('should respect templateUrl when style=none and changeDetection=OnPush', async () => { const options = { ...defaultOptions, style: Style.None, changeDetection: 'OnPush' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).not.toMatch(/styleUrls: /); expect(content).toMatch(/templateUrl: '.\/foo.component.html',\n/); expect(content).toMatch(/changeDetection: ChangeDetectionStrategy.OnPush/); }); it('should respect inlineTemplate when style=none and changeDetection=OnPush', async () => { const options = { ...defaultOptions, style: Style.None, changeDetection: 'OnPush', inlineTemplate: true, }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(content).not.toMatch(/styleUrls: /); expect(content).toMatch(/template: `(\n(.|)*){3}\n\s*`,\n/); expect(content).toMatch(/changeDetection: ChangeDetectionStrategy.OnPush/); }); it('should create a standalone component', async () => { const options = { ...defaultOptions, standalone: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const moduleContent = tree.readContent('/projects/bar/src/app/app.module.ts'); const componentContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(componentContent).toContain('class FooComponent'); expect(moduleContent).not.toContain('FooComponent'); expect(componentContent).not.toContain('standalone'); }); it('should declare standalone components in the `imports` of a test', async () => { const options = { ...defaultOptions, standalone: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const testContent = tree.readContent('/projects/bar/src/app/foo/foo.component.spec.ts'); expect(testContent).toContain('imports: [FooComponent]'); expect(testContent).not.toContain('declarations'); });
{ "end_byte": 16535, "start_byte": 8567, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/index_spec.ts" }
angular-cli/packages/schematics/angular/component/index_spec.ts_16539_22924
describe('standalone=false', () => { const defaultNonStandaloneOptions: ComponentOptions = { ...defaultOptions, standalone: false, project: 'baz', }; beforeEach(async () => { appTree = await schematicRunner.runSchematic( 'application', { ...appOptions, standalone: false, name: 'baz' }, appTree, ); }); it('should create a component', async () => { const options = { ...defaultNonStandaloneOptions }; const tree = await schematicRunner.runSchematic('component', options, appTree); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/baz/src/app/foo/foo.component.css', '/projects/baz/src/app/foo/foo.component.html', '/projects/baz/src/app/foo/foo.component.spec.ts', '/projects/baz/src/app/foo/foo.component.ts', ]), ); const moduleContent = tree.readContent('/projects/baz/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); }); it('should use the module flag even if the module is a routing module', async () => { const routingFileName = 'app-routing.module.ts'; const routingModulePath = `/projects/baz/src/app/${routingFileName}`; const newTree = createAppModule(appTree, routingModulePath); const options = { ...defaultNonStandaloneOptions, module: routingFileName }; const tree = await schematicRunner.runSchematic('component', options, newTree); const content = tree.readContent(routingModulePath); expect(content).toMatch(/import { FooComponent } from '.\/foo\/foo.component/); }); it('should handle a path in the name option', async () => { const options = { ...defaultNonStandaloneOptions, name: 'dir/test-component' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const content = tree.readContent('/projects/baz/src/app/app.module.ts'); expect(content).toMatch( /import { TestComponentComponent } from '\.\/dir\/test-component\/test-component.component'/, ); }); it('should handle a path in the name and module options', async () => { appTree = await schematicRunner.runSchematic( 'module', { name: 'admin/module', project: 'baz' }, appTree, ); const options = { ...defaultNonStandaloneOptions, name: 'other/test-component', module: 'admin/module', }; appTree = await schematicRunner.runSchematic('component', options, appTree); const content = appTree.readContent('/projects/baz/src/app/admin/module/module.module.ts'); expect(content).toMatch( /import { TestComponentComponent } from '..\/..\/other\/test-component\/test-component.component'/, ); }); it('should find the closest module', async () => { const options = { ...defaultNonStandaloneOptions }; const fooModule = '/projects/baz/src/app/foo/foo.module.ts'; appTree.create( fooModule, ` import { NgModule } from '@angular/core'; @NgModule({ imports: [], declarations: [] }) export class FooModule { } `, ); const tree = await schematicRunner.runSchematic('component', options, appTree); const fooModuleContent = tree.readContent(fooModule); expect(fooModuleContent).toMatch(/import { FooComponent } from '.\/foo.component'/); }); it('should export the component', async () => { const options = { ...defaultNonStandaloneOptions, export: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const appModuleContent = tree.readContent('/projects/baz/src/app/app.module.ts'); expect(appModuleContent).toMatch(/exports: \[\n(\s*) {2}FooComponent\n\1\]/); }); it('should import into a specified module', async () => { const options = { ...defaultNonStandaloneOptions, module: 'app.module.ts' }; const tree = await schematicRunner.runSchematic('component', options, appTree); const appModule = tree.readContent('/projects/baz/src/app/app.module.ts'); expect(appModule).toMatch(/import { FooComponent } from '.\/foo\/foo.component'/); }); it('should respect the sourceRoot value', async () => { const config = JSON.parse(appTree.readContent('/angular.json')); config.projects.baz.sourceRoot = 'projects/baz/custom'; appTree.overwrite('/angular.json', JSON.stringify(config, null, 2)); // should fail without a module in that dir await expectAsync( schematicRunner.runSchematic('component', defaultNonStandaloneOptions, appTree), ).toBeRejected(); // move the module appTree.rename( '/projects/baz/src/app/app.module.ts', '/projects/baz/custom/app/app.module.ts', ); appTree = await schematicRunner.runSchematic( 'component', defaultNonStandaloneOptions, appTree, ); expect(appTree.files).toContain('/projects/baz/custom/app/foo/foo.component.ts'); }); it('should fail if specified module does not exist', async () => { const options = { ...defaultNonStandaloneOptions, module: '/projects/baz/src/app.moduleXXX.ts', }; await expectAsync(schematicRunner.runSchematic('component', options, appTree)).toBeRejected(); }); }); it('should export the component as default when exportDefault is true', async () => { const options = { ...defaultOptions, exportDefault: true }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(tsContent).toContain('export default class FooComponent'); }); it('should export the component as a named export when exportDefault is false', async () => { const options = { ...defaultOptions, exportDefault: false }; const tree = await schematicRunner.runSchematic('component', options, appTree); const tsContent = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); expect(tsContent).toContain('export class FooComponent'); }); });
{ "end_byte": 22924, "start_byte": 16539, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/index_spec.ts" }
angular-cli/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.spec.ts.template_0_838
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { <%= classify(name) %><%= classify(type) %> } from './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>'; describe('<%= classify(name) %><%= classify(type) %>', () => { let component: <%= classify(name) %><%= classify(type) %>; let fixture: ComponentFixture<<%= classify(name) %><%= classify(type) %>>; beforeEach(async () => { await TestBed.configureTestingModule({ <%= standalone ? 'imports' : 'declarations' %>: [<%= classify(name) %><%= classify(type) %>] }) .compileComponents(); fixture = TestBed.createComponent(<%= classify(name) %><%= classify(type) %>); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 838, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.spec.ts.template" }
angular-cli/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.ts.template_0_1079
import { <% if(changeDetection !== 'Default') { %>ChangeDetectionStrategy, <% }%>Component<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%> } from '@angular/core'; @Component({<% if(!skipSelector) {%> selector: '<%= selector %>',<%}%><% if(standalone) {%> imports: [],<%} else { %> standalone: false, <% }%><% if(inlineTemplate) { %> template: ` <p> <%= dasherize(name) %> works! </p> `<% } else { %> templateUrl: './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.html'<% } if(inlineStyle) { %>, styles: `<% if(displayBlock){ %> :host { display: block; } <% } %>`<% } else if (style !== 'none') { %>, styleUrl: './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %> }) export <% if(exportDefault) {%>default <%}%>class <%= classify(name) %><%= classify(type) %> { }
{ "end_byte": 1079, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.ts.template" }
angular-cli/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.html.template_0_37
<p><%= dasherize(name) %> works!</p>
{ "end_byte": 37, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.html.template" }
angular-cli/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.__style__.template_0_120
<% if(displayBlock){ if(style != 'sass') { %>:host { display: block; } <% } else { %>\:host display: block; <% }} %>
{ "end_byte": 120, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.__style__.template" }
angular-cli/packages/schematics/angular/server/index.ts_0_8821
/** * @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 { JsonValue, Path, basename, dirname, join, normalize } from '@angular-devkit/core'; import { Rule, SchematicsException, Tree, apply, applyTemplates, chain, filter, mergeWith, move, noop, strings, url, } from '@angular-devkit/schematics'; import { posix } from 'node:path'; import { DependencyType, InstallBehavior, addDependency, addRootProvider } from '../utility'; import { getPackageJsonDependency } from '../utility/dependencies'; import { JSONFile } from '../utility/json-file'; import { latestVersions } from '../utility/latest-versions'; import { isStandaloneApp } from '../utility/ng-ast-utils'; import { relativePathToWorkspaceRoot } from '../utility/paths'; import { targetBuildNotFoundError } from '../utility/project-targets'; import { getMainFilePath } from '../utility/standalone/util'; import { getWorkspace, updateWorkspace } from '../utility/workspace'; import { Builders } from '../utility/workspace-models'; import { Schema as ServerOptions } from './schema'; const serverMainEntryName = 'main.server.ts'; function updateConfigFileBrowserBuilder(options: ServerOptions, tsConfigDirectory: Path): Rule { return updateWorkspace((workspace) => { const clientProject = workspace.projects.get(options.project); if (clientProject) { // In case the browser builder hashes the assets // we need to add this setting to the server builder // as otherwise when assets it will be requested twice. // One for the server which will be unhashed, and other on the client which will be hashed. const getServerOptions = (options: Record<string, JsonValue | undefined> = {}): {} => { return { buildOptimizer: options?.buildOptimizer, outputHashing: options?.outputHashing === 'all' ? 'media' : options?.outputHashing, fileReplacements: options?.fileReplacements, optimization: options?.optimization === undefined ? undefined : !!options?.optimization, sourceMap: options?.sourceMap, localization: options?.localization, stylePreprocessorOptions: options?.stylePreprocessorOptions, resourcesOutputPath: options?.resourcesOutputPath, deployUrl: options?.deployUrl, i18nMissingTranslation: options?.i18nMissingTranslation, preserveSymlinks: options?.preserveSymlinks, extractLicenses: options?.extractLicenses, inlineStyleLanguage: options?.inlineStyleLanguage, vendorChunk: options?.vendorChunk, }; }; const buildTarget = clientProject.targets.get('build'); if (buildTarget?.options) { buildTarget.options.outputPath = `dist/${options.project}/browser`; } const buildConfigurations = buildTarget?.configurations; const configurations: Record<string, {}> = {}; if (buildConfigurations) { for (const [key, options] of Object.entries(buildConfigurations)) { configurations[key] = getServerOptions(options); } } const sourceRoot = clientProject.sourceRoot ?? join(normalize(clientProject.root), 'src'); const serverTsConfig = join(tsConfigDirectory, 'tsconfig.server.json'); clientProject.targets.add({ name: 'server', builder: Builders.Server, defaultConfiguration: 'production', options: { outputPath: `dist/${options.project}/server`, main: join(normalize(sourceRoot), serverMainEntryName), tsConfig: serverTsConfig, ...(buildTarget?.options ? getServerOptions(buildTarget?.options) : {}), }, configurations, }); } }); } function updateConfigFileApplicationBuilder(options: ServerOptions): Rule { return updateWorkspace((workspace) => { const project = workspace.projects.get(options.project); if (!project) { return; } const buildTarget = project.targets.get('build'); if (!buildTarget) { return; } buildTarget.options ??= {}; buildTarget.options['server'] = posix.join( project.sourceRoot ?? posix.join(project.root, 'src'), serverMainEntryName, ); if (options.serverRouting) { buildTarget.options['outputMode'] = 'static'; } }); } function updateTsConfigFile(tsConfigPath: string): Rule { return (host: Tree) => { const json = new JSONFile(host, tsConfigPath); const filesPath = ['files']; const files = new Set((json.get(filesPath) as string[] | undefined) ?? []); files.add('src/' + serverMainEntryName); json.modify(filesPath, [...files]); const typePath = ['compilerOptions', 'types']; const types = new Set((json.get(typePath) as string[] | undefined) ?? []); types.add('node'); json.modify(typePath, [...types]); }; } function addDependencies(skipInstall: boolean | undefined): Rule { return (host: Tree) => { const coreDep = getPackageJsonDependency(host, '@angular/core'); if (coreDep === null) { throw new SchematicsException('Could not find version.'); } const install = skipInstall ? InstallBehavior.None : InstallBehavior.Auto; return chain([ addDependency('@angular/ssr', latestVersions.AngularSSR, { type: DependencyType.Default, install, }), addDependency('@angular/platform-server', coreDep.version, { type: DependencyType.Default, install, }), addDependency('@types/node', latestVersions['@types/node'], { type: DependencyType.Dev, install, }), ]); }; } export default function (options: ServerOptions): Rule { return async (host: Tree) => { const workspace = await getWorkspace(host); const clientProject = workspace.projects.get(options.project); if (clientProject?.extensions.projectType !== 'application') { throw new SchematicsException(`Server schematic requires a project type of "application".`); } const clientBuildTarget = clientProject.targets.get('build'); if (!clientBuildTarget) { throw targetBuildNotFoundError(); } const isUsingApplicationBuilder = clientBuildTarget.builder === Builders.Application || clientBuildTarget.builder === Builders.BuildApplication; if ( clientProject.targets.has('server') || (isUsingApplicationBuilder && clientBuildTarget.options?.server !== undefined) ) { // Server has already been added. return; } const clientBuildOptions = clientBuildTarget.options as Record<string, string>; const browserEntryPoint = await getMainFilePath(host, options.project); const isStandalone = isStandaloneApp(host, browserEntryPoint); const sourceRoot = clientProject.sourceRoot ?? join(normalize(clientProject.root), 'src'); let filesUrl = `./files/${isUsingApplicationBuilder ? 'application-builder/' : 'server-builder/'}`; filesUrl += isStandalone ? 'standalone-src' : 'ngmodule-src'; const templateSource = apply(url(filesUrl), [ options.serverRouting ? noop() : filter((path) => !path.endsWith('app.routes.server.ts.template')), applyTemplates({ ...strings, ...options, }), move(sourceRoot), ]); const clientTsConfig = normalize(clientBuildOptions.tsConfig); const tsConfigExtends = basename(clientTsConfig); const tsConfigDirectory = dirname(clientTsConfig); return chain([ mergeWith(templateSource), ...(isUsingApplicationBuilder ? [ updateConfigFileApplicationBuilder(options), updateTsConfigFile(clientBuildOptions.tsConfig), ] : [ mergeWith( apply(url('./files/server-builder/root'), [ applyTemplates({ ...strings, ...options, stripTsExtension: (s: string) => s.replace(/\.ts$/, ''), tsConfigExtends, hasLocalizePackage: !!getPackageJsonDependency(host, '@angular/localize'), relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(tsConfigDirectory), }), move(tsConfigDirectory), ]), ), updateConfigFileBrowserBuilder(options, tsConfigDirectory), ]), addDependencies(options.skipInstall), addRootProvider( options.project, ({ code, external }) => code`${external('provideClientHydration', '@angular/platform-browser')}(${external( 'withEventReplay', '@angular/platform-browser', )}())`, ), ]); }; }
{ "end_byte": 8821, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/index.ts" }
angular-cli/packages/schematics/angular/server/index_spec.ts_0_778
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { parse as parseJson } from 'jsonc-parser'; import { Schema as ApplicationOptions, Style } from '../application/schema'; import { CompilerOptions } from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { NodeDependencyType, addPackageJsonDependency } from '../utility/dependencies'; import { Builders } from '../utility/workspace-models'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as ServerOptions } from './schema';
{ "end_byte": 778, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/index_spec.ts" }
angular-cli/packages/schematics/angular/server/index_spec.ts_780_10275
describe('Server Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/angular', require.resolve('../collection.json'), ); const defaultOptions: ServerOptions = { project: 'bar', }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; const appOptions: ApplicationOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, routing: false, style: Style.Css, skipTests: false, skipPackageJson: false, }; let appTree: UnitTestTree; beforeEach(async () => { appTree = await schematicRunner.runSchematic('workspace', workspaceOptions); }); describe('non standalone application', () => { beforeEach(async () => { appTree = await schematicRunner.runSchematic( 'application', { ...appOptions, standalone: false }, appTree, ); }); it('should create a root module file', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/src/app/app.module.server.ts'; expect(tree.exists(filePath)).toBeTrue(); }); it('should create a main file', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/src/main.server.ts'; expect(tree.exists(filePath)).toBeTrue(); const contents = tree.readContent(filePath); expect(contents).toContain( `export { AppServerModule as default } from './app/app.module.server';`, ); }); it('should add dependency: @angular/platform-server', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/package.json'; const contents = tree.readContent(filePath); expect(contents).toMatch(/"@angular\/platform-server": "/); }); it('should install npm dependencies', async () => { await schematicRunner.runSchematic('server', defaultOptions, appTree); expect(schematicRunner.tasks.length).toBe(1); expect(schematicRunner.tasks[0].name).toBe('node-package'); expect((schematicRunner.tasks[0].options as { command: string }).command).toBe('install'); }); it('should update tsconfig.app.json', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/tsconfig.app.json'; const contents = parseJson(tree.readContent(filePath).toString()); expect(contents.compilerOptions.types).toEqual(['node']); expect(contents.files).toEqual(['src/main.ts', 'src/main.server.ts']); }); it(`should add 'provideClientHydration' to the providers list`, async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const contents = tree.readContent('/projects/bar/src/app/app.module.ts'); expect(contents).toContain(`provideClientHydration(withEventReplay())`); }); }); describe('standalone application', () => { beforeEach(async () => { appTree = await schematicRunner.runSchematic('application', appOptions, appTree); }); it('should create not root module file', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/src/app/app.module.server.ts'; expect(tree.exists(filePath)).toEqual(false); }); it('should update workspace and add the server option', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/angular.json'; const contents = tree.readContent(filePath); const config = JSON.parse(contents.toString()); const targets = config.projects.bar.architect; expect(targets.build.options.server).toEqual('projects/bar/src/main.server.ts'); }); it('should create a main file', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/src/main.server.ts'; expect(tree.exists(filePath)).toBeTrue(); const contents = tree.readContent(filePath); expect(contents).toContain(`bootstrapApplication(AppComponent, config)`); }); it('should create server app config file', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/src/app/app.config.server.ts'; expect(tree.exists(filePath)).toBeTrue(); const contents = tree.readContent(filePath); expect(contents).toContain(`const serverConfig: ApplicationConfig = {`); }); it(`should add 'provideClientHydration' to the providers list`, async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const contents = tree.readContent('/projects/bar/src/app/app.config.ts'); expect(contents).toContain(`provideClientHydration(withEventReplay())`); }); }); describe('Legacy browser builder', () => { function convertBuilderToLegacyBrowser(): void { const config = JSON.parse(appTree.readContent('/angular.json')); const build = config.projects.bar.architect.build; build.builder = Builders.Browser; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; appTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2)); } beforeEach(async () => { appTree = await schematicRunner.runSchematic('application', appOptions, appTree); convertBuilderToLegacyBrowser(); }); it(`should not add import to '@angular/localize' as type in 'tsconfig.server.json' when it's not a dependency`, async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const { compilerOptions } = tree.readJson('/projects/bar/tsconfig.server.json') as { compilerOptions: CompilerOptions; }; expect(compilerOptions.types).not.toContain('@angular/localize'); }); it(`should add import to '@angular/localize' as type in 'tsconfig.server.json' when it's a dependency`, async () => { addPackageJsonDependency(appTree, { name: '@angular/localize', type: NodeDependencyType.Default, version: 'latest', }); const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const { compilerOptions } = tree.readJson('/projects/bar/tsconfig.server.json') as { compilerOptions: CompilerOptions; }; expect(compilerOptions.types).toContain('@angular/localize'); }); it('should update workspace with a server target', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/angular.json'; const contents = tree.readContent(filePath); const config = JSON.parse(contents.toString()); const targets = config.projects.bar.architect; expect(targets.server).toBeDefined(); expect(targets.server.builder).toBeDefined(); const opts = targets.server.options; expect(opts.outputPath).toEqual('dist/bar/server'); expect(opts.main).toEqual('projects/bar/src/main.server.ts'); expect(opts.tsConfig).toEqual('projects/bar/tsconfig.server.json'); }); it('should update workspace with a build target outputPath', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/angular.json'; const contents = tree.readContent(filePath); const config = JSON.parse(contents.toString()); const targets = config.projects.bar.architect; expect(targets.build.options.outputPath).toEqual('dist/bar/browser'); }); it(`should work when 'tsconfig.app.json' has comments`, async () => { const appTsConfigPath = '/projects/bar/tsconfig.app.json'; const appTsConfigContent = appTree.readContent(appTsConfigPath); appTree.overwrite(appTsConfigPath, '// comment in json file\n' + appTsConfigContent); const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/tsconfig.server.json'; expect(tree.exists(filePath)).toBeTrue(); }); it('should create a tsconfig file for a generated application', async () => { const tree = await schematicRunner.runSchematic('server', defaultOptions, appTree); const filePath = '/projects/bar/tsconfig.server.json'; expect(tree.exists(filePath)).toBeTrue(); const contents = parseJson(tree.readContent(filePath).toString()); expect(contents).toEqual({ extends: './tsconfig.app.json', compilerOptions: { outDir: '../../out-tsc/server', types: ['node'], }, files: ['src/main.server.ts'], }); const angularConfig = JSON.parse(tree.readContent('angular.json')); expect(angularConfig.projects.bar.architect.server.options.tsConfig).toEqual( 'projects/bar/tsconfig.server.json', ); }); }); });
{ "end_byte": 10275, "start_byte": 780, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/index_spec.ts" }
angular-cli/packages/schematics/angular/server/files/server-builder/ngmodule-src/main.server.ts.template_0_70
export { AppServerModule as default } from './app/app.module.server';
{ "end_byte": 70, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/server-builder/ngmodule-src/main.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/server-builder/ngmodule-src/app/app.module.server.ts.template_0_318
import { NgModule } from '@angular/core'; import { ServerModule } from '@angular/platform-server'; import { AppModule } from './app.module'; import { AppComponent } from './app.component'; @NgModule({ imports: [ AppModule, ServerModule, ], bootstrap: [AppComponent], }) export class AppServerModule {}
{ "end_byte": 318, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/server-builder/ngmodule-src/app/app.module.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/server-builder/standalone-src/main.server.ts.template_0_264
import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { config } from './app/app.config.server'; const bootstrap = () => bootstrapApplication(AppComponent, config); export default bootstrap;
{ "end_byte": 264, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/server-builder/standalone-src/main.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/server-builder/standalone-src/app/app.config.server.ts.template_0_350
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core'; import { provideServerRendering } from '@angular/platform-server'; import { appConfig } from './app.config'; const serverConfig: ApplicationConfig = { providers: [ provideServerRendering() ] }; export const config = mergeApplicationConfig(appConfig, serverConfig);
{ "end_byte": 350, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/server-builder/standalone-src/app/app.config.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/server-builder/root/tsconfig.server.json.template_0_519
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./<%= tsConfigExtends %>", "compilerOptions": { "outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/server", "types": [ "node"<% if (hasLocalizePackage) { %>, "@angular/localize"<% } %> ] }, "files": [ "src/main.server.ts" ] }
{ "end_byte": 519, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/server-builder/root/tsconfig.server.json.template" }
angular-cli/packages/schematics/angular/server/files/application-builder/ngmodule-src/main.server.ts.template_0_70
export { AppServerModule as default } from './app/app.module.server';
{ "end_byte": 70, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/application-builder/ngmodule-src/main.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/application-builder/ngmodule-src/app/app.routes.server.ts.template_0_166
import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '**', renderMode: RenderMode.Prerender } ];
{ "end_byte": 166, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/application-builder/ngmodule-src/app/app.routes.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/application-builder/ngmodule-src/app/app.module.server.ts.template_0_566
import { NgModule } from '@angular/core'; import { ServerModule } from '@angular/platform-server';<% if(serverRouting) { %> import { provideServerRoutesConfig } from '@angular/ssr';<% } %> import { AppComponent } from './app.component'; import { AppModule } from './app.module';<% if(serverRouting) { %> import { serverRoutes } from './app.routes.server';<% } %> @NgModule({ imports: [AppModule, ServerModule],<% if(serverRouting) { %> providers: [provideServerRoutesConfig(serverRoutes)],<% } %> bootstrap: [AppComponent], }) export class AppServerModule {}
{ "end_byte": 566, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/application-builder/ngmodule-src/app/app.module.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/application-builder/standalone-src/main.server.ts.template_0_264
import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { config } from './app/app.config.server'; const bootstrap = () => bootstrapApplication(AppComponent, config); export default bootstrap;
{ "end_byte": 264, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/application-builder/standalone-src/main.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/application-builder/standalone-src/app/app.config.server.ts.template_0_601
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core'; import { provideServerRendering } from '@angular/platform-server';<% if(serverRouting) { %> import { provideServerRoutesConfig } from '@angular/ssr';<% } %> import { appConfig } from './app.config';<% if(serverRouting) { %> import { serverRoutes } from './app.routes.server';<% } %> const serverConfig: ApplicationConfig = { providers: [ provideServerRendering(),<% if(serverRouting) { %> provideServerRoutesConfig(serverRoutes)<% } %> ] }; export const config = mergeApplicationConfig(appConfig, serverConfig);
{ "end_byte": 601, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/application-builder/standalone-src/app/app.config.server.ts.template" }
angular-cli/packages/schematics/angular/server/files/application-builder/standalone-src/app/app.routes.server.ts.template_0_166
import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '**', renderMode: RenderMode.Prerender } ];
{ "end_byte": 166, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/server/files/application-builder/standalone-src/app/app.routes.server.ts.template" }
angular-cli/packages/schematics/angular/library/index.ts_0_5803
/** * @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 { Rule, SchematicContext, Tree, apply, applyTemplates, chain, mergeWith, move, noop, schematic, strings, url, } from '@angular-devkit/schematics'; import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import { join } from 'node:path/posix'; import { NodeDependencyType, addPackageJsonDependency } from '../utility/dependencies'; import { JSONFile } from '../utility/json-file'; import { latestVersions } from '../utility/latest-versions'; import { relativePathToWorkspaceRoot } from '../utility/paths'; import { getWorkspace, updateWorkspace } from '../utility/workspace'; import { Builders, ProjectType } from '../utility/workspace-models'; import { Schema as LibraryOptions } from './schema'; function updateTsConfig(packageName: string, ...paths: string[]) { return (host: Tree) => { if (!host.exists('tsconfig.json')) { return host; } const file = new JSONFile(host, 'tsconfig.json'); const jsonPath = ['compilerOptions', 'paths', packageName]; const value = file.get(jsonPath); file.modify(jsonPath, Array.isArray(value) ? [...value, ...paths] : paths); }; } function addDependenciesToPackageJson() { return (host: Tree) => { [ { type: NodeDependencyType.Dev, name: '@angular/compiler-cli', version: latestVersions.Angular, }, { type: NodeDependencyType.Dev, name: '@angular-devkit/build-angular', version: latestVersions.DevkitBuildAngular, }, { type: NodeDependencyType.Dev, name: 'ng-packagr', version: latestVersions['ng-packagr'], }, { type: NodeDependencyType.Default, name: 'tslib', version: latestVersions['tslib'], }, { type: NodeDependencyType.Dev, name: 'typescript', version: latestVersions['typescript'], }, ].forEach((dependency) => addPackageJsonDependency(host, dependency)); return host; }; } function addLibToWorkspaceFile( options: LibraryOptions, projectRoot: string, projectName: string, ): Rule { return updateWorkspace((workspace) => { workspace.projects.add({ name: projectName, root: projectRoot, sourceRoot: `${projectRoot}/src`, projectType: ProjectType.Library, prefix: options.prefix, targets: { build: { builder: Builders.NgPackagr, defaultConfiguration: 'production', options: { project: `${projectRoot}/ng-package.json`, }, configurations: { production: { tsConfig: `${projectRoot}/tsconfig.lib.prod.json`, }, development: { tsConfig: `${projectRoot}/tsconfig.lib.json`, }, }, }, test: { builder: Builders.Karma, options: { tsConfig: `${projectRoot}/tsconfig.spec.json`, polyfills: ['zone.js', 'zone.js/testing'], }, }, }, }); }); } export default function (options: LibraryOptions): Rule { return async (host: Tree) => { const prefix = options.prefix; // If scoped project (i.e. "@foo/bar"), convert projectDir to "foo/bar". const packageName = options.name; if (/^@.*\/.*/.test(options.name)) { const [, name] = options.name.split('/'); options.name = name; } const workspace = await getWorkspace(host); const newProjectRoot = (workspace.extensions.newProjectRoot as string | undefined) || ''; let folderName = packageName.startsWith('@') ? packageName.slice(1) : packageName; if (/[A-Z]/.test(folderName)) { folderName = strings.dasherize(folderName); } const libDir = options.projectRoot !== undefined ? join(options.projectRoot) : join(newProjectRoot, folderName); const distRoot = `dist/${folderName}`; const sourceDir = `${libDir}/src/lib`; const templateSource = apply(url('./files'), [ applyTemplates({ ...strings, ...options, packageName, libDir, distRoot, relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(libDir), prefix, angularLatestVersion: latestVersions.Angular.replace(/~|\^/, ''), tsLibLatestVersion: latestVersions['tslib'].replace(/~|\^/, ''), folderName, }), move(libDir), ]); return chain([ mergeWith(templateSource), addLibToWorkspaceFile(options, libDir, packageName), options.skipPackageJson ? noop() : addDependenciesToPackageJson(), options.skipTsConfig ? noop() : updateTsConfig(packageName, './' + distRoot), options.standalone ? noop() : schematic('module', { name: options.name, commonModule: false, flat: true, path: sourceDir, project: packageName, }), schematic('component', { name: options.name, selector: `${prefix}-${options.name}`, inlineStyle: true, inlineTemplate: true, flat: true, path: sourceDir, export: true, standalone: options.standalone, project: packageName, }), schematic('service', { name: options.name, flat: true, path: sourceDir, project: packageName, }), (_tree: Tree, context: SchematicContext) => { if (!options.skipPackageJson && !options.skipInstall) { context.addTask(new NodePackageInstallTask()); } }, ]); }; }
{ "end_byte": 5803, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/index.ts" }
angular-cli/packages/schematics/angular/library/index_spec.ts_0_8170
/** * @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import { parse as parseJson } from 'jsonc-parser'; import { getFileContent } from '../../angular/utility/test'; import { Schema as ComponentOptions } from '../component/schema'; import { latestVersions } from '../utility/latest-versions'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as GenerateLibrarySchema } from './schema'; // eslint-disable-next-line @typescript-eslint/no-explicit-any function getJsonFileContent(tree: UnitTestTree, path: string): any { return parseJson(tree.readContent(path).toString()); } describe('Library Schematic', () => { const schematicRunner = new SchematicTestRunner( '@schematics/ng_packagr', require.resolve('../collection.json'), ); const defaultOptions: GenerateLibrarySchema = { name: 'foo', entryFile: 'my-index', skipPackageJson: false, skipTsConfig: false, skipInstall: false, }; const workspaceOptions: WorkspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '6.0.0', }; let workspaceTree: UnitTestTree; beforeEach(async () => { workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions); }); it('should create correct files', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/foo/ng-package.json', '/projects/foo/package.json', '/projects/foo/README.md', '/projects/foo/tsconfig.lib.json', '/projects/foo/tsconfig.lib.prod.json', '/projects/foo/src/my-index.ts', '/projects/foo/src/lib/foo.component.spec.ts', '/projects/foo/src/lib/foo.component.ts', '/projects/foo/src/lib/foo.service.spec.ts', '/projects/foo/src/lib/foo.service.ts', ]), ); }); it('should not add reference to module file in entry-file', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); expect(tree.readContent('/projects/foo/src/my-index.ts')).not.toContain('foo.module'); }); it('should create a standalone component', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const componentContent = tree.readContent('/projects/foo/src/lib/foo.component.ts'); expect(componentContent).not.toContain('standalone'); }); describe('custom projectRoot', () => { const customProjectRootOptions: GenerateLibrarySchema = { name: 'foo', entryFile: 'my-index', skipPackageJson: false, skipTsConfig: false, skipInstall: false, projectRoot: 'some/other/directory/bar', }; it('should create files in /some/other/directory/bar', async () => { const tree = await schematicRunner.runSchematic( 'library', customProjectRootOptions, workspaceTree, ); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/some/other/directory/bar/ng-package.json', '/some/other/directory/bar/package.json', '/some/other/directory/bar/README.md', '/some/other/directory/bar/tsconfig.lib.json', '/some/other/directory/bar/tsconfig.lib.prod.json', '/some/other/directory/bar/src/my-index.ts', '/some/other/directory/bar/src/lib/foo.component.spec.ts', '/some/other/directory/bar/src/lib/foo.component.ts', '/some/other/directory/bar/src/lib/foo.service.spec.ts', '/some/other/directory/bar/src/lib/foo.service.ts', ]), ); }); it(`should add library to workspace`, async () => { const tree = await schematicRunner.runSchematic( 'library', customProjectRootOptions, workspaceTree, ); const workspace = getJsonFileContent(tree, '/angular.json'); expect(workspace.projects.foo).toBeDefined(); }); }); it('should create a package.json named "foo"', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const fileContent = getFileContent(tree, '/projects/foo/package.json'); expect(fileContent).toMatch(/"name": "foo"/); }); it('should have the latest Angular major versions in package.json named "foo"', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const fileContent = getJsonFileContent(tree, '/projects/foo/package.json'); const angularVersion = latestVersions.Angular.replace('~', '').replace('^', ''); expect(fileContent.peerDependencies['@angular/core']).toBe(`^${angularVersion}`); }); it('should add sideEffects: false flag to package.json named "foo"', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const fileContent = getFileContent(tree, '/projects/foo/package.json'); expect(fileContent).toMatch(/"sideEffects": false/); }); it('should create a README.md named "foo"', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const fileContent = getFileContent(tree, '/projects/foo/README.md'); expect(fileContent).toMatch(/# Foo/); }); it('should create a tsconfig for library', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const fileContent = getJsonFileContent(tree, '/projects/foo/tsconfig.lib.json'); expect(fileContent).toBeDefined(); }); it('should create a ng-package.json with ngPackage conf', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const fileContent = getJsonFileContent(tree, '/projects/foo/ng-package.json'); expect(fileContent.lib).toBeDefined(); expect(fileContent.lib.entryFile).toEqual('src/my-index.ts'); expect(fileContent.dest).toEqual('../../dist/foo'); }); it('should use default value for baseDir and entryFile', async () => { const tree = await schematicRunner.runSchematic( 'library', { name: 'foobar', }, workspaceTree, ); expect(tree.files).toContain('/projects/foobar/src/public-api.ts'); }); it(`should add library to workspace`, async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const workspace = getJsonFileContent(tree, '/angular.json'); expect(workspace.projects.foo).toBeDefined(); }); it('should set the prefix to lib if none is set', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const workspace = JSON.parse(tree.readContent('/angular.json')); expect(workspace.projects.foo.prefix).toEqual('lib'); }); it('should set the prefix correctly', async () => { const options = { ...defaultOptions, prefix: 'pre' }; const tree = await schematicRunner.runSchematic('library', options, workspaceTree); const workspace = JSON.parse(tree.readContent('/angular.json')); expect(workspace.projects.foo.prefix).toEqual('pre'); }); it('should handle a pascalCasedName', async () => { const options = { ...defaultOptions, name: 'pascalCasedName' }; const tree = await schematicRunner.runSchematic('library', options, workspaceTree); const config = getJsonFileContent(tree, '/angular.json'); const project = config.projects.pascalCasedName; expect(project).toBeDefined(); expect(project.root).toEqual('projects/pascal-cased-name'); const svcContent = tree.readContent( '/projects/pascal-cased-name/src/lib/pascal-cased-name.service.ts', ); expect(svcContent).toMatch(/providedIn: 'root'/); });
{ "end_byte": 8170, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/index_spec.ts" }
angular-cli/packages/schematics/angular/library/index_spec.ts_8174_16839
describe(`update package.json`, () => { it(`should add ng-packagr to devDependencies`, async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const packageJson = getJsonFileContent(tree, 'package.json'); expect(packageJson.devDependencies['ng-packagr']).toEqual(latestVersions['ng-packagr']); }); it('should use the latest known versions in package.json', async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const pkg = JSON.parse(tree.readContent('/package.json')); expect(pkg.devDependencies['@angular/compiler-cli']).toEqual(latestVersions.Angular); expect(pkg.devDependencies['typescript']).toEqual(latestVersions['typescript']); }); it(`should not override existing users dependencies`, async () => { const oldPackageJson = workspaceTree.readContent('package.json'); workspaceTree.overwrite( 'package.json', oldPackageJson.replace( `"typescript": "${latestVersions['typescript']}"`, `"typescript": "~2.5.2"`, ), ); const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const packageJson = getJsonFileContent(tree, 'package.json'); expect(packageJson.devDependencies.typescript).toEqual('~2.5.2'); }); it(`should not modify the file when --skipPackageJson`, async () => { const tree = await schematicRunner.runSchematic( 'library', { name: 'foo', skipPackageJson: true, }, workspaceTree, ); const packageJson = getJsonFileContent(tree, 'package.json'); expect(packageJson.devDependencies['ng-packagr']).toBeUndefined(); expect(packageJson.devDependencies['@angular-devkit/build-angular']).toBeUndefined(); }); }); describe(`update tsconfig.json`, () => { it(`should add paths mapping to empty tsconfig`, async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const tsConfigJson = getJsonFileContent(tree, 'tsconfig.json'); expect(tsConfigJson.compilerOptions.paths['foo']).toEqual(['./dist/foo']); }); it(`should append to existing paths mappings`, async () => { workspaceTree.overwrite( 'tsconfig.json', JSON.stringify({ compilerOptions: { paths: { 'unrelated': ['./something/else.ts'], 'foo': ['libs/*'], }, }, }), ); const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const tsConfigJson = getJsonFileContent(tree, 'tsconfig.json'); expect(tsConfigJson.compilerOptions.paths['foo']).toEqual(['libs/*', './dist/foo']); }); it(`should not modify the file when --skipTsConfig`, async () => { const tree = await schematicRunner.runSchematic( 'library', { name: 'foo', skipTsConfig: true, }, workspaceTree, ); const tsConfigJson = getJsonFileContent(tree, 'tsconfig.json'); expect(tsConfigJson.compilerOptions.paths).toBeUndefined(); }); }); it('should generate inside of a library', async () => { let tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const componentOptions: ComponentOptions = { name: 'comp', project: 'foo', }; tree = await schematicRunner.runSchematic('component', componentOptions, tree); expect(tree.exists('/projects/foo/src/lib/comp/comp.component.ts')).toBe(true); }); it(`should support creating scoped libraries`, async () => { const scopedName = '@myscope/mylib'; const options = { ...defaultOptions, name: scopedName }; const tree = await schematicRunner.runSchematic('library', options, workspaceTree); const pkgJsonPath = '/projects/myscope/mylib/package.json'; expect(tree.files).toContain(pkgJsonPath); expect(tree.files).toContain('/projects/myscope/mylib/src/lib/mylib.service.ts'); expect(tree.files).toContain('/projects/myscope/mylib/src/lib/mylib.component.ts'); const pkgJson = JSON.parse(tree.readContent(pkgJsonPath)); expect(pkgJson.name).toEqual(scopedName); const tsConfigJson = getJsonFileContent(tree, '/projects/myscope/mylib/tsconfig.spec.json'); expect(tsConfigJson.extends).toEqual('../../../tsconfig.json'); const cfg = JSON.parse(tree.readContent('/angular.json')); expect(cfg.projects['@myscope/mylib']).toBeDefined(); const rootTsCfg = getJsonFileContent(tree, '/tsconfig.json'); expect(rootTsCfg.compilerOptions.paths['@myscope/mylib']).toEqual(['./dist/myscope/mylib']); }); it(`should dasherize scoped libraries`, async () => { const scopedName = '@myScope/myLib'; const expectedScopeName = '@my-scope/my-lib'; const expectedFolderName = 'my-scope/my-lib'; const options = { ...defaultOptions, name: scopedName }; const tree = await schematicRunner.runSchematic('library', options, workspaceTree); const pkgJsonPath = '/projects/my-scope/my-lib/package.json'; expect(tree.readContent(pkgJsonPath)).toContain(expectedScopeName); const ngPkgJsonPath = '/projects/my-scope/my-lib/ng-package.json'; expect(tree.readContent(ngPkgJsonPath)).toContain(expectedFolderName); const pkgJson = JSON.parse(tree.readContent(pkgJsonPath)); expect(pkgJson.name).toEqual(expectedScopeName); const cfg = JSON.parse(tree.readContent('/angular.json')); expect(cfg.projects['@myScope/myLib']).toBeDefined(); }); it(`should create correct paths when 'newProjectRoot' is blank`, async () => { const workspaceTree = await schematicRunner.runSchematic('workspace', { ...workspaceOptions, newProjectRoot: '', }); const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const config = getJsonFileContent(tree, '/angular.json'); const project = config.projects.foo; expect(project.root).toEqual('foo'); const { options, configurations } = project.architect.build; expect(options.project).toEqual('foo/ng-package.json'); expect(configurations.production.tsConfig).toEqual('foo/tsconfig.lib.prod.json'); const libTsConfig = getJsonFileContent(tree, '/foo/tsconfig.lib.json'); expect(libTsConfig.extends).toEqual('../tsconfig.json'); const specTsConfig = getJsonFileContent(tree, '/foo/tsconfig.spec.json'); expect(specTsConfig.extends).toEqual('../tsconfig.json'); }); it(`should add 'development' configuration`, async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const workspace = JSON.parse(tree.readContent('/angular.json')); expect(workspace.projects.foo.architect.build.configurations.development).toBeDefined(); }); it(`should add 'ng-packagr' builder`, async () => { const tree = await schematicRunner.runSchematic('library', defaultOptions, workspaceTree); const workspace = JSON.parse(tree.readContent('/angular.json')); expect(workspace.projects.foo.architect.build.builder).toBe( '@angular-devkit/build-angular:ng-packagr', ); }); describe('standalone=false', () => { const defaultNonStandaloneOptions = { ...defaultOptions, standalone: false }; it('should export the component in the NgModule', async () => { const tree = await schematicRunner.runSchematic( 'library', defaultNonStandaloneOptions, workspaceTree, ); const fileContent = getFileContent(tree, '/projects/foo/src/lib/foo.module.ts'); expect(fileContent).toMatch(/exports: \[\n(\s*) {2}FooComponent\n\1\]/); }); it('should create files', async () => { const tree = await schematicRunner.runSchematic( 'library', defaultNonStandaloneOptions, workspaceTree, ); const files = tree.files; expect(files).toEqual( jasmine.arrayContaining([ '/projects/foo/ng-package.json', '/projects/foo/package.json', '/projects/foo/README.md', '/projects/foo/tsconfig.lib.json', '/projects/foo/tsconfig.lib.prod.json', '/projects/foo/src/my-index.ts', '/projects/foo/src/lib/foo.module.ts', '/projects/foo/src/lib/foo.component.spec.ts', '/projects/foo/src/lib/foo.component.ts', '/projects/foo/src/lib/foo.service.spec.ts', '/projects/foo/src/lib/foo.service.ts', ]), ); }); }); });
{ "end_byte": 16839, "start_byte": 8174, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/index_spec.ts" }
angular-cli/packages/schematics/angular/library/files/ng-package.json.template_0_223
{ "$schema": "<%= relativePathToWorkspaceRoot %>/node_modules/ng-packagr/ng-package.schema.json", "dest": "<%= relativePathToWorkspaceRoot %>/<%= distRoot %>", "lib": { "entryFile": "src/<%= entryFile %>.ts" } }
{ "end_byte": 223, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/files/ng-package.json.template" }
angular-cli/packages/schematics/angular/library/files/tsconfig.lib.json.template_0_533
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ /* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "<%= relativePathToWorkspaceRoot %>/tsconfig.json", "compilerOptions": { "outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/lib", "declaration": true, "declarationMap": true, "inlineSources": true, "types": [] }, "exclude": [ "**/*.spec.ts" ] }
{ "end_byte": 533, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/files/tsconfig.lib.json.template" }
angular-cli/packages/schematics/angular/library/files/README.md.template_0_1498
# <%= classify(name) %> This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version <%= angularLatestVersion %>. ## Code scaffolding Angular CLI includes powerful code scaffolding tools. To generate a new component, run: ```bash ng generate component component-name ``` For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run: ```bash ng generate --help ``` ## Building To build the library, run: ```bash ng build <%= name %> ``` This command will compile your project, and the build artifacts will be placed in the `dist/` directory. ### Publishing the Library Once the project is built, you can publish your library by following these steps: 1. Navigate to the `dist` directory: ```bash cd dist/<%= dasherize(name) %> ``` 2. Run the `npm publish` command to publish your library to the npm registry: ```bash npm publish ``` ## Running unit tests To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command: ```bash ng test ``` ## Running end-to-end tests For end-to-end (e2e) testing, run: ```bash ng e2e ``` Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs. ## Additional Resources For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
{ "end_byte": 1498, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/files/README.md.template" }
angular-cli/packages/schematics/angular/library/files/package.json.template_0_295
{ "name": "<%= dasherize(packageName) %>", "version": "0.0.1", "peerDependencies": { "@angular/common": "^<%= angularLatestVersion %>", "@angular/core": "^<%= angularLatestVersion %>" }, "dependencies": { "tslib": "^<%= tsLibLatestVersion %>" }, "sideEffects": false }
{ "end_byte": 295, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/library/files/package.json.template" }