_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/src/ngtsc/scope/src/component_scope.ts_0_1265
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {ClassDeclaration} from '../../reflection'; import {ComponentScope, ComponentScopeReader, LocalModuleScope, RemoteScope} from './api'; /** * A `ComponentScopeReader` that reads from an ordered set of child readers until it obtains the * requested scope. * * This is used to combine `ComponentScopeReader`s that read from different sources (e.g. from a * registry and from the incremental state). */ export class CompoundComponentScopeReader implements ComponentScopeReader { constructor(private readers: ComponentScopeReader[]) {} getScopeForComponent(clazz: ClassDeclaration): ComponentScope | null { for (const reader of this.readers) { const meta = reader.getScopeForComponent(clazz); if (meta !== null) { return meta; } } return null; } getRemoteScope(clazz: ClassDeclaration): RemoteScope | null { for (const reader of this.readers) { const remoteScope = reader.getRemoteScope(clazz); if (remoteScope !== null) { return remoteScope; } } return null; } }
{ "end_byte": 1265, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/component_scope.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/dependency.ts_0_5634
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {AliasingHost, Reference} from '../../imports'; import {DirectiveMeta, MetadataReader, PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {ExportScope} from './api'; export interface DtsModuleScopeResolver { resolve(ref: Reference<ClassDeclaration>): ExportScope | null; } /** * Reads Angular metadata from classes declared in .d.ts files and computes an `ExportScope`. * * Given an NgModule declared in a .d.ts file, this resolver can produce a transitive `ExportScope` * of all of the directives/pipes it exports. It does this by reading metadata off of Ivy static * fields on directives, components, pipes, and NgModules. */ export class MetadataDtsModuleScopeResolver implements DtsModuleScopeResolver { /** * Cache which holds fully resolved scopes for NgModule classes from .d.ts files. */ private cache = new Map<ClassDeclaration, ExportScope | null>(); /** * @param dtsMetaReader a `MetadataReader` which can read metadata from `.d.ts` files. */ constructor( private dtsMetaReader: MetadataReader, private aliasingHost: AliasingHost | null, ) {} /** * Resolve a `Reference`'d NgModule from a .d.ts file and produce a transitive `ExportScope` * listing the directives and pipes which that NgModule exports to others. * * This operation relies on a `Reference` instead of a direct TypeScript node as the `Reference`s * produced depend on how the original NgModule was imported. */ resolve(ref: Reference<ClassDeclaration>): ExportScope | null { const clazz = ref.node; const sourceFile = clazz.getSourceFile(); if (!sourceFile.isDeclarationFile) { throw new Error( `Debug error: DtsModuleScopeResolver.read(${ref.debugName} from ${sourceFile.fileName}), but not a .d.ts file`, ); } if (this.cache.has(clazz)) { return this.cache.get(clazz)!; } // Build up the export scope - those directives and pipes made visible by this module. const dependencies: Array<DirectiveMeta | PipeMeta> = []; const meta = this.dtsMetaReader.getNgModuleMetadata(ref); if (meta === null) { this.cache.set(clazz, null); return null; } const declarations = new Set<ClassDeclaration>(); for (const declRef of meta.declarations) { declarations.add(declRef.node); } // Only the 'exports' field of the NgModule's metadata is important. Imports and declarations // don't affect the export scope. for (const exportRef of meta.exports) { // Attempt to process the export as a directive. const directive = this.dtsMetaReader.getDirectiveMetadata(exportRef); if (directive !== null) { const isReExport = !declarations.has(exportRef.node); dependencies.push(this.maybeAlias(directive, sourceFile, isReExport)); continue; } // Attempt to process the export as a pipe. const pipe = this.dtsMetaReader.getPipeMetadata(exportRef); if (pipe !== null) { const isReExport = !declarations.has(exportRef.node); dependencies.push(this.maybeAlias(pipe, sourceFile, isReExport)); continue; } // Attempt to process the export as a module. const exportScope = this.resolve(exportRef); if (exportScope !== null) { // It is a module. Add exported directives and pipes to the current scope. This might // involve rewriting the `Reference`s to those types to have an alias expression if one is // required. if (this.aliasingHost === null) { // Fast path when aliases aren't required. dependencies.push(...exportScope.exported.dependencies); } else { // It's necessary to rewrite the `Reference`s to add alias expressions. This way, imports // generated to these directives and pipes will use a shallow import to `sourceFile` // instead of a deep import directly to the directive or pipe class. // // One important check here is whether the directive/pipe is declared in the same // source file as the re-exporting NgModule. This can happen if both a directive, its // NgModule, and the re-exporting NgModule are all in the same file. In this case, // no import alias is needed as it would go to the same file anyway. for (const dep of exportScope.exported.dependencies) { dependencies.push(this.maybeAlias(dep, sourceFile, /* isReExport */ true)); } } } continue; // The export was not a directive, a pipe, or a module. This is an error. // TODO(alxhub): produce a ts.Diagnostic } const exportScope: ExportScope = { exported: { dependencies, isPoisoned: false, }, }; this.cache.set(clazz, exportScope); return exportScope; } private maybeAlias<T extends DirectiveMeta | PipeMeta>( dirOrPipe: T, maybeAliasFrom: ts.SourceFile, isReExport: boolean, ): T { const ref = dirOrPipe.ref; if (this.aliasingHost === null || ref.node.getSourceFile() === maybeAliasFrom) { return dirOrPipe; } const alias = this.aliasingHost.getAliasIn(ref.node, maybeAliasFrom, isReExport); if (alias === null) { return dirOrPipe; } return { ...dirOrPipe, ref: ref.cloneWithAlias(alias), }; } }
{ "end_byte": 5634, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/dependency.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/api.ts_0_2620
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {SchemaMetadata} from '@angular/compiler'; import {Reexport, Reference} from '../../imports'; import {DirectiveMeta, NgModuleMeta, PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; /** * Data for one of a given NgModule's scopes (either compilation scope or export scopes). */ export interface ScopeData { dependencies: Array<DirectiveMeta | PipeMeta>; /** * Whether some module or component in this scope contains errors and is thus semantically * unreliable. */ isPoisoned: boolean; } /** * An export scope of an NgModule, containing the directives/pipes it contributes to other NgModules * which import it. */ export interface ExportScope { /** * The scope exported by an NgModule, and available for import. */ exported: ScopeData; } /** * A resolved scope for a given component that cannot be set locally in the component definition, * and must be set via remote scoping call in the component's NgModule file. */ export interface RemoteScope { /** * Those directives used by the component that requires this scope to be set remotely. */ directives: Reference[]; /** * Those pipes used by the component that requires this scope to be set remotely. */ pipes: Reference[]; } export enum ComponentScopeKind { NgModule, Standalone, } export interface LocalModuleScope extends ExportScope { kind: ComponentScopeKind.NgModule; ngModule: ClassDeclaration; compilation: ScopeData; reexports: Reexport[] | null; schemas: SchemaMetadata[]; } export interface StandaloneScope { kind: ComponentScopeKind.Standalone; dependencies: Array<DirectiveMeta | PipeMeta | NgModuleMeta>; deferredDependencies: Array<DirectiveMeta | PipeMeta>; component: ClassDeclaration; schemas: SchemaMetadata[]; isPoisoned: boolean; } export type ComponentScope = LocalModuleScope | StandaloneScope; /** * Read information about the compilation scope of components. */ export interface ComponentScopeReader { getScopeForComponent(clazz: ClassDeclaration): ComponentScope | null; /** * Get the `RemoteScope` required for this component, if any. * * If the component requires remote scoping, then retrieve the directives/pipes registered for * that component. If remote scoping is not required (the common case), returns `null`. */ getRemoteScope(clazz: ClassDeclaration): RemoteScope | null; }
{ "end_byte": 2620, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/api.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/local.ts_0_2429
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {ExternalExpr} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, makeDiagnostic, makeRelatedInformation} from '../../diagnostics'; import { AliasingHost, assertSuccessfulReferenceEmit, Reexport, Reference, ReferenceEmitter, } from '../../imports'; import { DirectiveMeta, MetadataReader, MetadataRegistry, MetaKind, NgModuleMeta, PipeMeta, } from '../../metadata'; import {ClassDeclaration, DeclarationNode} from '../../reflection'; import {identifierOfNode, nodeNameForError} from '../../util/src/typescript'; import { ComponentScopeKind, ComponentScopeReader, ExportScope, LocalModuleScope, RemoteScope, ScopeData, } from './api'; import {DtsModuleScopeResolver} from './dependency'; import {getDiagnosticNode, makeNotStandaloneDiagnostic} from './util'; export interface LocalNgModuleData { declarations: Reference<ClassDeclaration>[]; imports: Reference<ClassDeclaration>[]; exports: Reference<ClassDeclaration>[]; } /** Value used to mark a module whose scope is in the process of being resolved. */ const IN_PROGRESS_RESOLUTION = {}; /** * A registry which collects information about NgModules, Directives, Components, and Pipes which * are local (declared in the ts.Program being compiled), and can produce `LocalModuleScope`s * which summarize the compilation scope of a component. * * This class implements the logic of NgModule declarations, imports, and exports and can produce, * for a given component, the set of directives and pipes which are "visible" in that component's * template. * * The `LocalModuleScopeRegistry` has two "modes" of operation. During analysis, data for each * individual NgModule, Directive, Component, and Pipe is added to the registry. No attempt is made * to traverse or validate the NgModule graph (imports, exports, etc). After analysis, one of * `getScopeOfModule` or `getScopeForComponent` can be called, which traverses the NgModule graph * and applies the NgModule logic to generate a `LocalModuleScope`, the full scope for the given * module or component. * * The `LocalModuleScopeRegistry` is also capable of producing `ts.Diagnostic` errors when Angular * semantics are violated. */
{ "end_byte": 2429, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/local.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/local.ts_2430_9481
export class LocalModuleScopeRegistry implements MetadataRegistry, ComponentScopeReader { /** * Tracks whether the registry has been asked to produce scopes for a module or component. Once * this is true, the registry cannot accept registrations of new directives/pipes/modules as it * would invalidate the cached scope data. */ private sealed = false; /** * A map of components from the current compilation unit to the NgModule which declared them. * * As components and directives are not distinguished at the NgModule level, this map may also * contain directives. This doesn't cause any problems but isn't useful as there is no concept of * a directive's compilation scope. */ private declarationToModule = new Map<ClassDeclaration, DeclarationData>(); /** * This maps from the directive/pipe class to a map of data for each NgModule that declares the * directive/pipe. This data is needed to produce an error for the given class. */ private duplicateDeclarations = new Map< ClassDeclaration, Map<ClassDeclaration, DeclarationData> >(); private moduleToRef = new Map<ClassDeclaration, Reference<ClassDeclaration>>(); /** * A cache of calculated `LocalModuleScope`s for each NgModule declared in the current program. */ private cache = new Map< ClassDeclaration, LocalModuleScope | typeof IN_PROGRESS_RESOLUTION | null >(); /** * Tracks the `RemoteScope` for components requiring "remote scoping". * * Remote scoping is when the set of directives which apply to a given component is set in the * NgModule's file instead of directly on the component def (which is sometimes needed to get * around cyclic import issues). This is not used in calculation of `LocalModuleScope`s, but is * tracked here for convenience. */ private remoteScoping = new Map<ClassDeclaration, RemoteScope>(); /** * Tracks errors accumulated in the processing of scopes for each module declaration. */ private scopeErrors = new Map<ClassDeclaration, ts.Diagnostic[]>(); /** * Tracks which NgModules have directives/pipes that are declared in more than one module. */ private modulesWithStructuralErrors = new Set<ClassDeclaration>(); constructor( private localReader: MetadataReader, private fullReader: MetadataReader, private dependencyScopeReader: DtsModuleScopeResolver, private refEmitter: ReferenceEmitter, private aliasingHost: AliasingHost | null, ) {} /** * Add an NgModule's data to the registry. */ registerNgModuleMetadata(data: NgModuleMeta): void { this.assertCollecting(); const ngModule = data.ref.node; this.moduleToRef.set(data.ref.node, data.ref); // Iterate over the module's declarations, and add them to declarationToModule. If duplicates // are found, they're instead tracked in duplicateDeclarations. for (const decl of data.declarations) { this.registerDeclarationOfModule(ngModule, decl, data.rawDeclarations); } } registerDirectiveMetadata(directive: DirectiveMeta): void {} registerPipeMetadata(pipe: PipeMeta): void {} getScopeForComponent(clazz: ClassDeclaration): LocalModuleScope | null { const scope = !this.declarationToModule.has(clazz) ? null : this.getScopeOfModule(this.declarationToModule.get(clazz)!.ngModule); return scope; } /** * If `node` is declared in more than one NgModule (duplicate declaration), then get the * `DeclarationData` for each offending declaration. * * Ordinarily a class is only declared in one NgModule, in which case this function returns * `null`. */ getDuplicateDeclarations(node: ClassDeclaration): DeclarationData[] | null { if (!this.duplicateDeclarations.has(node)) { return null; } return Array.from(this.duplicateDeclarations.get(node)!.values()); } /** * Collects registered data for a module and its directives/pipes and convert it into a full * `LocalModuleScope`. * * This method implements the logic of NgModule imports and exports. It returns the * `LocalModuleScope` for the given NgModule if one can be produced, `null` if no scope was ever * defined, or the string `'error'` if the scope contained errors. */ getScopeOfModule(clazz: ClassDeclaration): LocalModuleScope | null { return this.moduleToRef.has(clazz) ? this.getScopeOfModuleReference(this.moduleToRef.get(clazz)!) : null; } /** * Retrieves any `ts.Diagnostic`s produced during the calculation of the `LocalModuleScope` for * the given NgModule, or `null` if no errors were present. */ getDiagnosticsOfModule(clazz: ClassDeclaration): ts.Diagnostic[] | null { // Required to ensure the errors are populated for the given class. If it has been processed // before, this will be a no-op due to the scope cache. this.getScopeOfModule(clazz); if (this.scopeErrors.has(clazz)) { return this.scopeErrors.get(clazz)!; } else { return null; } } private registerDeclarationOfModule( ngModule: ClassDeclaration, decl: Reference<ClassDeclaration>, rawDeclarations: ts.Expression | null, ): void { const declData: DeclarationData = { ngModule, ref: decl, rawDeclarations, }; // First, check for duplicate declarations of the same directive/pipe. if (this.duplicateDeclarations.has(decl.node)) { // This directive/pipe has already been identified as being duplicated. Add this module to the // map of modules for which a duplicate declaration exists. this.duplicateDeclarations.get(decl.node)!.set(ngModule, declData); } else if ( this.declarationToModule.has(decl.node) && this.declarationToModule.get(decl.node)!.ngModule !== ngModule ) { // This directive/pipe is already registered as declared in another module. Mark it as a // duplicate instead. const duplicateDeclMap = new Map<ClassDeclaration, DeclarationData>(); const firstDeclData = this.declarationToModule.get(decl.node)!; // Mark both modules as having duplicate declarations. this.modulesWithStructuralErrors.add(firstDeclData.ngModule); this.modulesWithStructuralErrors.add(ngModule); // Being detected as a duplicate means there are two NgModules (for now) which declare this // directive/pipe. Add both of them to the duplicate tracking map. duplicateDeclMap.set(firstDeclData.ngModule, firstDeclData); duplicateDeclMap.set(ngModule, declData); this.duplicateDeclarations.set(decl.node, duplicateDeclMap); // Remove the directive/pipe from `declarationToModule` as it's a duplicate declaration, and // therefore not valid. this.declarationToModule.delete(decl.node); } else { // This is the first declaration of this directive/pipe, so map it. this.declarationToModule.set(decl.node, declData); } } /** * Implementation of `getScopeOfModule` which accepts a reference to a class. */
{ "end_byte": 9481, "start_byte": 2430, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/local.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/local.ts_9484_17391
private getScopeOfModuleReference(ref: Reference<ClassDeclaration>): LocalModuleScope | null { if (this.cache.has(ref.node)) { const cachedValue = this.cache.get(ref.node); if (cachedValue !== IN_PROGRESS_RESOLUTION) { return cachedValue as LocalModuleScope | null; } } this.cache.set(ref.node, IN_PROGRESS_RESOLUTION); // Seal the registry to protect the integrity of the `LocalModuleScope` cache. this.sealed = true; // `ref` should be an NgModule previously added to the registry. If not, a scope for it // cannot be produced. const ngModule = this.localReader.getNgModuleMetadata(ref); if (ngModule === null) { this.cache.set(ref.node, null); return null; } // Errors produced during computation of the scope are recorded here. At the end, if this array // isn't empty then `undefined` will be cached and returned to indicate this scope is invalid. const diagnostics: ts.Diagnostic[] = []; // At this point, the goal is to produce two distinct transitive sets: // - the directives and pipes which are visible to components declared in the NgModule. // - the directives and pipes which are exported to any NgModules which import this one. // Directives and pipes in the compilation scope. const compilationDirectives = new Map<DeclarationNode, DirectiveMeta>(); const compilationPipes = new Map<DeclarationNode, PipeMeta>(); const declared = new Set<DeclarationNode>(); // Directives and pipes exported to any importing NgModules. const exportDirectives = new Map<DeclarationNode, DirectiveMeta>(); const exportPipes = new Map<DeclarationNode, PipeMeta>(); // The algorithm is as follows: // 1) Add all of the directives/pipes from each NgModule imported into the current one to the // compilation scope. // 2) Add directives/pipes declared in the NgModule to the compilation scope. At this point, the // compilation scope is complete. // 3) For each entry in the NgModule's exports: // a) Attempt to resolve it as an NgModule with its own exported directives/pipes. If it is // one, add them to the export scope of this NgModule. // b) Otherwise, it should be a class in the compilation scope of this NgModule. If it is, // add it to the export scope. // c) If it's neither an NgModule nor a directive/pipe in the compilation scope, then this // is an error. // let isPoisoned = false; if (this.modulesWithStructuralErrors.has(ngModule.ref.node)) { // If the module contains declarations that are duplicates, then it's considered poisoned. isPoisoned = true; } // 1) process imports. for (const decl of ngModule.imports) { const importScope = this.getExportedScope(decl, diagnostics, ref.node, 'import'); if (importScope !== null) { if ( importScope === 'invalid' || importScope === 'cycle' || importScope.exported.isPoisoned ) { // An import was an NgModule but contained errors of its own. Record this as an error too, // because this scope is always going to be incorrect if one of its imports could not be // read. isPoisoned = true; // Prevent the module from reporting a diagnostic about itself when there's a cycle. if (importScope !== 'cycle') { diagnostics.push(invalidTransitiveNgModuleRef(decl, ngModule.rawImports, 'import')); } if (importScope === 'invalid' || importScope === 'cycle') { continue; } } for (const dep of importScope.exported.dependencies) { if (dep.kind === MetaKind.Directive) { compilationDirectives.set(dep.ref.node, dep); } else if (dep.kind === MetaKind.Pipe) { compilationPipes.set(dep.ref.node, dep); } } // Successfully processed the import as an NgModule (even if it had errors). continue; } // The import wasn't an NgModule. Maybe it's a standalone entity? const directive = this.fullReader.getDirectiveMetadata(decl); if (directive !== null) { if (directive.isStandalone) { compilationDirectives.set(directive.ref.node, directive); } else { // Error: can't import a non-standalone component/directive. diagnostics.push( makeNotStandaloneDiagnostic( this, decl, ngModule.rawImports, directive.isComponent ? 'component' : 'directive', ), ); isPoisoned = true; } continue; } // It wasn't a directive (standalone or otherwise). Maybe a pipe? const pipe = this.fullReader.getPipeMetadata(decl); if (pipe !== null) { if (pipe.isStandalone) { compilationPipes.set(pipe.ref.node, pipe); } else { diagnostics.push(makeNotStandaloneDiagnostic(this, decl, ngModule.rawImports, 'pipe')); isPoisoned = true; } continue; } // This reference was neither another NgModule nor a standalone entity. Report it as invalid. diagnostics.push(invalidRef(decl, ngModule.rawImports, 'import')); isPoisoned = true; } // 2) add declarations. for (const decl of ngModule.declarations) { const directive = this.localReader.getDirectiveMetadata(decl); const pipe = this.localReader.getPipeMetadata(decl); if (directive !== null) { if (directive.isStandalone) { const refType = directive.isComponent ? 'Component' : 'Directive'; diagnostics.push( makeDiagnostic( ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE, decl.getOriginForDiagnostics(ngModule.rawDeclarations!), `${refType} ${decl.node.name.text} is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?`, ), ); isPoisoned = true; continue; } compilationDirectives.set(decl.node, {...directive, ref: decl}); if (directive.isPoisoned) { isPoisoned = true; } } else if (pipe !== null) { if (pipe.isStandalone) { diagnostics.push( makeDiagnostic( ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE, decl.getOriginForDiagnostics(ngModule.rawDeclarations!), `Pipe ${decl.node.name.text} is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?`, ), ); isPoisoned = true; continue; } compilationPipes.set(decl.node, {...pipe, ref: decl}); } else { const errorNode = decl.getOriginForDiagnostics(ngModule.rawDeclarations!); diagnostics.push( makeDiagnostic( ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode, `The class '${decl.node.name.text}' is listed in the declarations ` + `of the NgModule '${ngModule.ref.node.name.text}', but is not a directive, a component, or a pipe. ` + `Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.`, [makeRelatedInformation(decl.node.name, `'${decl.node.name.text}' is declared here.`)], ), ); isPoisoned = true; continue; } declared.add(decl.node); } // 3) process exports. // Exports can contain modules, components, or directives. They're processed differently. // Modules are straightforward. Directives and pipes from exported modules are added to the // export maps. Directives/pipes are different - they might be exports of declared types or // imported types.
{ "end_byte": 17391, "start_byte": 9484, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/local.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/local.ts_17396_26090
for (const decl of ngModule.exports) { // Attempt to resolve decl as an NgModule. const exportScope = this.getExportedScope(decl, diagnostics, ref.node, 'export'); if ( exportScope === 'invalid' || exportScope === 'cycle' || (exportScope !== null && exportScope.exported.isPoisoned) ) { // An export was an NgModule but contained errors of its own. Record this as an error too, // because this scope is always going to be incorrect if one of its exports could not be // read. isPoisoned = true; // Prevent the module from reporting a diagnostic about itself when there's a cycle. if (exportScope !== 'cycle') { diagnostics.push(invalidTransitiveNgModuleRef(decl, ngModule.rawExports, 'export')); } if (exportScope === 'invalid' || exportScope === 'cycle') { continue; } } else if (exportScope !== null) { // decl is an NgModule. for (const dep of exportScope.exported.dependencies) { if (dep.kind == MetaKind.Directive) { exportDirectives.set(dep.ref.node, dep); } else if (dep.kind === MetaKind.Pipe) { exportPipes.set(dep.ref.node, dep); } } } else if (compilationDirectives.has(decl.node)) { // decl is a directive or component in the compilation scope of this NgModule. const directive = compilationDirectives.get(decl.node)!; exportDirectives.set(decl.node, directive); } else if (compilationPipes.has(decl.node)) { // decl is a pipe in the compilation scope of this NgModule. const pipe = compilationPipes.get(decl.node)!; exportPipes.set(decl.node, pipe); } else { // decl is an unknown export. const dirMeta = this.fullReader.getDirectiveMetadata(decl); const pipeMeta = this.fullReader.getPipeMetadata(decl); if (dirMeta !== null || pipeMeta !== null) { const isStandalone = dirMeta !== null ? dirMeta.isStandalone : pipeMeta!.isStandalone; diagnostics.push(invalidReexport(decl, ngModule.rawExports, isStandalone)); } else { diagnostics.push(invalidRef(decl, ngModule.rawExports, 'export')); } isPoisoned = true; continue; } } const exported: ScopeData = { dependencies: [...exportDirectives.values(), ...exportPipes.values()], isPoisoned, }; const reexports = this.getReexports( ngModule, ref, declared, exported.dependencies, diagnostics, ); // Finally, produce the `LocalModuleScope` with both the compilation and export scopes. const scope: LocalModuleScope = { kind: ComponentScopeKind.NgModule, ngModule: ngModule.ref.node, compilation: { dependencies: [...compilationDirectives.values(), ...compilationPipes.values()], isPoisoned, }, exported, reexports, schemas: ngModule.schemas, }; // Check if this scope had any errors during production. if (diagnostics.length > 0) { // Save the errors for retrieval. this.scopeErrors.set(ref.node, diagnostics); // Mark this module as being tainted. this.modulesWithStructuralErrors.add(ref.node); } this.cache.set(ref.node, scope); return scope; } /** * Check whether a component requires remote scoping. */ getRemoteScope(node: ClassDeclaration): RemoteScope | null { return this.remoteScoping.has(node) ? this.remoteScoping.get(node)! : null; } /** * Set a component as requiring remote scoping, with the given directives and pipes to be * registered remotely. */ setComponentRemoteScope( node: ClassDeclaration, directives: Reference[], pipes: Reference[], ): void { this.remoteScoping.set(node, {directives, pipes}); } /** * Look up the `ExportScope` of a given `Reference` to an NgModule. * * The NgModule in question may be declared locally in the current ts.Program, or it may be * declared in a .d.ts file. * * @returns `null` if no scope could be found, or `'invalid'` if the `Reference` is not a valid * NgModule. * * May also contribute diagnostics of its own by adding to the given `diagnostics` * array parameter. */ private getExportedScope( ref: Reference<ClassDeclaration>, diagnostics: ts.Diagnostic[], ownerForErrors: DeclarationNode, type: 'import' | 'export', ): ExportScope | null | 'invalid' | 'cycle' { if (ref.node.getSourceFile().isDeclarationFile) { // The NgModule is declared in a .d.ts file. Resolve it with the `DependencyScopeReader`. if (!ts.isClassDeclaration(ref.node)) { // The NgModule is in a .d.ts file but is not declared as a ts.ClassDeclaration. This is an // error in the .d.ts metadata. const code = type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT; diagnostics.push( makeDiagnostic( code, identifierOfNode(ref.node) || ref.node, `Appears in the NgModule.${type}s of ${nodeNameForError( ownerForErrors, )}, but could not be resolved to an NgModule`, ), ); return 'invalid'; } return this.dependencyScopeReader.resolve(ref); } else { if (this.cache.get(ref.node) === IN_PROGRESS_RESOLUTION) { diagnostics.push( makeDiagnostic( type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT, identifierOfNode(ref.node) || ref.node, `NgModule "${type}" field contains a cycle`, ), ); return 'cycle'; } // The NgModule is declared locally in the current program. Resolve it from the registry. return this.getScopeOfModuleReference(ref); } } private getReexports( ngModule: NgModuleMeta, ref: Reference<ClassDeclaration>, declared: Set<DeclarationNode>, exported: Array<DirectiveMeta | PipeMeta>, diagnostics: ts.Diagnostic[], ): Reexport[] | null { let reexports: Reexport[] | null = null; const sourceFile = ref.node.getSourceFile(); if (this.aliasingHost === null) { return null; } reexports = []; // Track re-exports by symbol name, to produce diagnostics if two alias re-exports would share // the same name. const reexportMap = new Map<string, Reference<ClassDeclaration>>(); // Alias ngModuleRef added for readability below. const ngModuleRef = ref; const addReexport = (exportRef: Reference<ClassDeclaration>) => { if (exportRef.node.getSourceFile() === sourceFile) { return; } const isReExport = !declared.has(exportRef.node); const exportName = this.aliasingHost!.maybeAliasSymbolAs( exportRef, sourceFile, ngModule.ref.node.name.text, isReExport, ); if (exportName === null) { return; } if (!reexportMap.has(exportName)) { if (exportRef.alias && exportRef.alias instanceof ExternalExpr) { reexports!.push({ fromModule: exportRef.alias.value.moduleName!, symbolName: exportRef.alias.value.name!, asAlias: exportName, }); } else { const emittedRef = this.refEmitter.emit(exportRef.cloneWithNoIdentifiers(), sourceFile); assertSuccessfulReferenceEmit(emittedRef, ngModuleRef.node.name, 'class'); const expr = emittedRef.expression; if ( !(expr instanceof ExternalExpr) || expr.value.moduleName === null || expr.value.name === null ) { throw new Error('Expected ExternalExpr'); } reexports!.push({ fromModule: expr.value.moduleName, symbolName: expr.value.name, asAlias: exportName, }); } reexportMap.set(exportName, exportRef); } else { // Another re-export already used this name. Produce a diagnostic. const prevRef = reexportMap.get(exportName)!; diagnostics.push(reexportCollision(ngModuleRef.node, prevRef, exportRef)); } }; for (const {ref} of exported) { addReexport(ref); } return reexports; } private assertCollecting(): void { if (this.sealed) { throw new Error(`Assertion: LocalModuleScopeRegistry is not COLLECTING`); } } } /** * Produce a `ts.Diagnostic` for an invalid import or export from an NgModule. */
{ "end_byte": 26090, "start_byte": 17396, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/local.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/local.ts_26091_30997
function invalidRef( decl: Reference<ClassDeclaration>, rawExpr: ts.Expression | null, type: 'import' | 'export', ): ts.Diagnostic { const code = type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT; const resolveTarget = type === 'import' ? 'NgModule' : 'NgModule, Component, Directive, or Pipe'; const message = `'${decl.node.name.text}' does not appear to be an ${resolveTarget} class.`; const library = decl.ownedByModuleGuess !== null ? ` (${decl.ownedByModuleGuess})` : ''; const sf = decl.node.getSourceFile(); let relatedMessage: string; // Provide extra context to the error for the user. if (!sf.isDeclarationFile) { // This is a file in the user's program. Highlight the class as undecorated. const annotationType = type === 'import' ? '@NgModule' : 'Angular'; relatedMessage = `Is it missing an ${annotationType} annotation?`; } else if (sf.fileName.indexOf('node_modules') !== -1) { // This file comes from a third-party library in node_modules. relatedMessage = `This likely means that the library${library} which declares ${decl.debugName} is not ` + 'compatible with Angular Ivy. Check if a newer version of the library is available, ' + "and update if so. Also consider checking with the library's authors to see if the " + 'library is expected to be compatible with Ivy.'; } else { // This is a monorepo style local dependency. Unfortunately these are too different to really // offer much more advice than this. relatedMessage = `This likely means that the dependency${library} which declares ${decl.debugName} is not compatible with Angular Ivy.`; } return makeDiagnostic(code, getDiagnosticNode(decl, rawExpr), message, [ makeRelatedInformation(decl.node.name, relatedMessage), ]); } /** * Produce a `ts.Diagnostic` for an import or export which itself has errors. */ function invalidTransitiveNgModuleRef( decl: Reference<ClassDeclaration>, rawExpr: ts.Expression | null, type: 'import' | 'export', ): ts.Diagnostic { const code = type === 'import' ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT; return makeDiagnostic( code, getDiagnosticNode(decl, rawExpr), `This ${type} contains errors, which may affect components that depend on this NgModule.`, ); } /** * Produce a `ts.Diagnostic` for an exported directive or pipe which was not declared or imported * by the NgModule in question. */ function invalidReexport( decl: Reference<ClassDeclaration>, rawExpr: ts.Expression | null, isStandalone: boolean, ): ts.Diagnostic { // The root error is the same here - this export is not valid. Give a helpful error message based // on the specific circumstance. let message = `Can't be exported from this NgModule, as `; if (isStandalone) { // Standalone types need to be imported into an NgModule before they can be re-exported. message += 'it must be imported first'; } else if (decl.node.getSourceFile().isDeclarationFile) { // Non-standalone types can be re-exported, but need to be imported into the NgModule first. // This requires importing their own NgModule. message += 'it must be imported via its NgModule first'; } else { // Local non-standalone types must either be declared directly by this NgModule, or imported as // above. message += 'it must be either declared by this NgModule, or imported here via its NgModule first'; } return makeDiagnostic( ErrorCode.NGMODULE_INVALID_REEXPORT, getDiagnosticNode(decl, rawExpr), message, ); } /** * Produce a `ts.Diagnostic` for a collision in re-export names between two directives/pipes. */ function reexportCollision( module: ClassDeclaration, refA: Reference<ClassDeclaration>, refB: Reference<ClassDeclaration>, ): ts.Diagnostic { const childMessageText = `This directive/pipe is part of the exports of '${module.name.text}' and shares the same name as another exported directive/pipe.`; return makeDiagnostic( ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION, module.name, ` There was a name collision between two classes named '${refA.node.name.text}', which are both part of the exports of '${module.name.text}'. Angular generates re-exports of an NgModule's exported directives/pipes from the module's source file in certain cases, using the declared name of the class. If two classes of the same name are exported, this automatic naming does not work. To fix this problem please re-export one or both classes directly from this file. `.trim(), [ makeRelatedInformation(refA.node.name, childMessageText), makeRelatedInformation(refB.node.name, childMessageText), ], ); } export interface DeclarationData { ngModule: ClassDeclaration; ref: Reference; rawDeclarations: ts.Expression | null; }
{ "end_byte": 30997, "start_byte": 26091, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/local.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/util.ts_0_3648
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {ErrorCode, makeDiagnostic, makeRelatedInformation} from '../../diagnostics'; import {Reference} from '../../imports'; import {ClassDeclaration} from '../../reflection'; import {ComponentScopeKind, ComponentScopeReader} from './api'; export function getDiagnosticNode( ref: Reference<ClassDeclaration>, rawExpr: ts.Expression | null, ): ts.Expression { // Show the diagnostic on the node within `rawExpr` which references the declaration // in question. `rawExpr` represents the raw expression from which `ref` was partially evaluated, // so use that to find the right node. Note that by the type system, `rawExpr` might be `null`, so // fall back on the declaration identifier in that case (even though in practice this should never // happen since local NgModules always have associated expressions). return rawExpr !== null ? ref.getOriginForDiagnostics(rawExpr) : ref.node.name; } export function makeNotStandaloneDiagnostic( scopeReader: ComponentScopeReader, ref: Reference<ClassDeclaration>, rawExpr: ts.Expression | null, kind: 'component' | 'directive' | 'pipe', ): ts.Diagnostic { const scope = scopeReader.getScopeForComponent(ref.node); let message = `The ${kind} '${ref.node.name.text}' appears in 'imports', but is not standalone and cannot be imported directly.`; let relatedInformation: ts.DiagnosticRelatedInformation[] | undefined = undefined; if (scope !== null && scope.kind === ComponentScopeKind.NgModule) { // The directive/pipe in question is declared in an NgModule. Check if it's also exported. const isExported = scope.exported.dependencies.some((dep) => dep.ref.node === ref.node); const relatedInfoMessageText = isExported ? `It can be imported using its '${scope.ngModule.name.text}' NgModule instead.` : `It's declared in the '${scope.ngModule.name.text}' NgModule, but is not exported. ` + 'Consider exporting it and importing the NgModule instead.'; relatedInformation = [makeRelatedInformation(scope.ngModule.name, relatedInfoMessageText)]; } else { // TODO(alxhub): the above case handles directives/pipes in NgModules that are declared in the // current compilation, but not those imported from .d.ts dependencies. We could likely scan the // program here and find NgModules to suggest, to improve the error in that case. } if (relatedInformation === undefined) { // If no contextual pointers can be provided to suggest a specific remedy, then at least tell // the user broadly what they need to do. message += ' It must be imported via an NgModule.'; } return makeDiagnostic( ErrorCode.COMPONENT_IMPORT_NOT_STANDALONE, getDiagnosticNode(ref, rawExpr), message, relatedInformation, ); } export function makeUnknownComponentImportDiagnostic( ref: Reference<ClassDeclaration>, rawExpr: ts.Expression, ) { return makeDiagnostic( ErrorCode.COMPONENT_UNKNOWN_IMPORT, getDiagnosticNode(ref, rawExpr), `Component imports must be standalone components, directives, pipes, or must be NgModules.`, ); } export function makeUnknownComponentDeferredImportDiagnostic( ref: Reference<ClassDeclaration>, rawExpr: ts.Expression, ) { return makeDiagnostic( ErrorCode.COMPONENT_UNKNOWN_DEFERRED_IMPORT, getDiagnosticNode(ref, rawExpr), `Component deferred imports must be standalone components, directives or pipes.`, ); }
{ "end_byte": 3648, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/util.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/typecheck.ts_0_5512
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {CssSelector, SchemaMetadata, SelectorMatcher} from '@angular/compiler'; import ts from 'typescript'; import {Reference} from '../../imports'; import { DirectiveMeta, flattenInheritedDirectiveMetadata, HostDirectivesResolver, MetadataReader, MetaKind, PipeMeta, } from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {ComponentScopeKind, ComponentScopeReader} from './api'; /** * The scope that is used for type-check code generation of a component template. */ export interface TypeCheckScope { /** * A `SelectorMatcher` instance that contains the flattened directive metadata of all directives * that are in the compilation scope of the declaring NgModule. */ matcher: SelectorMatcher<DirectiveMeta[]>; /** * All of the directives available in the compilation scope of the declaring NgModule. */ directives: DirectiveMeta[]; /** * The pipes that are available in the compilation scope. */ pipes: Map<string, PipeMeta>; /** * The schemas that are used in this scope. */ schemas: SchemaMetadata[]; /** * Whether the original compilation scope which produced this `TypeCheckScope` was itself poisoned * (contained semantic errors during its production). */ isPoisoned: boolean; } /** * Computes scope information to be used in template type checking. */ export class TypeCheckScopeRegistry { /** * Cache of flattened directive metadata. Because flattened metadata is scope-invariant it's * cached individually, such that all scopes refer to the same flattened metadata. */ private flattenedDirectiveMetaCache = new Map<ClassDeclaration, DirectiveMeta>(); /** * Cache of the computed type check scope per NgModule declaration. */ private scopeCache = new Map<ClassDeclaration, TypeCheckScope>(); constructor( private scopeReader: ComponentScopeReader, private metaReader: MetadataReader, private hostDirectivesResolver: HostDirectivesResolver, ) {} /** * Computes the type-check scope information for the component declaration. If the NgModule * contains an error, then 'error' is returned. If the component is not declared in any NgModule, * an empty type-check scope is returned. */ getTypeCheckScope(node: ClassDeclaration): TypeCheckScope { const matcher = new SelectorMatcher<DirectiveMeta[]>(); const directives: DirectiveMeta[] = []; const pipes = new Map<string, PipeMeta>(); const scope = this.scopeReader.getScopeForComponent(node); if (scope === null) { return { matcher, directives, pipes, schemas: [], isPoisoned: false, }; } const isNgModuleScope = scope.kind === ComponentScopeKind.NgModule; const cacheKey = isNgModuleScope ? scope.ngModule : scope.component; const dependencies = isNgModuleScope ? scope.compilation.dependencies : scope.dependencies; if (this.scopeCache.has(cacheKey)) { return this.scopeCache.get(cacheKey)!; } let allDependencies = dependencies; if ( !isNgModuleScope && Array.isArray(scope.deferredDependencies) && scope.deferredDependencies.length > 0 ) { allDependencies = [...allDependencies, ...scope.deferredDependencies]; } for (const meta of allDependencies) { if (meta.kind === MetaKind.Directive && meta.selector !== null) { const extMeta = this.getTypeCheckDirectiveMetadata(meta.ref); if (extMeta === null) { continue; } // Carry over the `isExplicitlyDeferred` flag from the dependency info. const directiveMeta = this.applyExplicitlyDeferredFlag(extMeta, meta.isExplicitlyDeferred); matcher.addSelectables(CssSelector.parse(meta.selector), [ ...this.hostDirectivesResolver.resolve(directiveMeta), directiveMeta, ]); directives.push(directiveMeta); } else if (meta.kind === MetaKind.Pipe) { if (!ts.isClassDeclaration(meta.ref.node)) { throw new Error( `Unexpected non-class declaration ${ts.SyntaxKind[meta.ref.node.kind]} for pipe ${ meta.ref.debugName }`, ); } pipes.set(meta.name, meta); } } const typeCheckScope: TypeCheckScope = { matcher, directives, pipes, schemas: scope.schemas, isPoisoned: scope.kind === ComponentScopeKind.NgModule ? scope.compilation.isPoisoned || scope.exported.isPoisoned : scope.isPoisoned, }; this.scopeCache.set(cacheKey, typeCheckScope); return typeCheckScope; } getTypeCheckDirectiveMetadata(ref: Reference<ClassDeclaration>): DirectiveMeta | null { const clazz = ref.node; if (this.flattenedDirectiveMetaCache.has(clazz)) { return this.flattenedDirectiveMetaCache.get(clazz)!; } const meta = flattenInheritedDirectiveMetadata(this.metaReader, ref); if (meta === null) { return null; } this.flattenedDirectiveMetaCache.set(clazz, meta); return meta; } private applyExplicitlyDeferredFlag<T extends DirectiveMeta | PipeMeta>( meta: T, isExplicitlyDeferred: boolean, ): T { return isExplicitlyDeferred === true ? {...meta, isExplicitlyDeferred} : meta; } }
{ "end_byte": 5512, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/typecheck.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/src/standalone.ts_0_4789
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {Reference} from '../../imports'; import {DirectiveMeta, MetadataReader, NgModuleMeta, PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import { ComponentScopeKind, ComponentScopeReader, ExportScope, RemoteScope, StandaloneScope, } from './api'; import {DtsModuleScopeResolver} from './dependency'; import {LocalModuleScopeRegistry} from './local'; /** * Computes scopes for standalone components based on their `imports`, expanding imported NgModule * scopes where necessary. */ export class StandaloneComponentScopeReader implements ComponentScopeReader { private cache = new Map<ClassDeclaration, StandaloneScope | null>(); constructor( private metaReader: MetadataReader, private localModuleReader: LocalModuleScopeRegistry, private dtsModuleReader: DtsModuleScopeResolver, ) {} getScopeForComponent(clazz: ClassDeclaration): StandaloneScope | null { if (!this.cache.has(clazz)) { const clazzRef = new Reference(clazz); const clazzMeta = this.metaReader.getDirectiveMetadata(clazzRef); if (clazzMeta === null || !clazzMeta.isComponent || !clazzMeta.isStandalone) { this.cache.set(clazz, null); return null; } // A standalone component always has itself in scope, so add `clazzMeta` during // initialization. const dependencies = new Set<DirectiveMeta | PipeMeta | NgModuleMeta>([clazzMeta]); const deferredDependencies = new Set<DirectiveMeta | PipeMeta>(); const seen = new Set<ClassDeclaration>([clazz]); let isPoisoned = clazzMeta.isPoisoned; if (clazzMeta.imports !== null) { for (const ref of clazzMeta.imports) { if (seen.has(ref.node)) { continue; } seen.add(ref.node); const dirMeta = this.metaReader.getDirectiveMetadata(ref); if (dirMeta !== null) { dependencies.add({...dirMeta, ref}); isPoisoned = isPoisoned || dirMeta.isPoisoned || !dirMeta.isStandalone; continue; } const pipeMeta = this.metaReader.getPipeMetadata(ref); if (pipeMeta !== null) { dependencies.add({...pipeMeta, ref}); isPoisoned = isPoisoned || !pipeMeta.isStandalone; continue; } const ngModuleMeta = this.metaReader.getNgModuleMetadata(ref); if (ngModuleMeta !== null) { dependencies.add({...ngModuleMeta, ref}); let ngModuleScope: ExportScope | null; if (ref.node.getSourceFile().isDeclarationFile) { ngModuleScope = this.dtsModuleReader.resolve(ref); } else { ngModuleScope = this.localModuleReader.getScopeOfModule(ref.node); } if (ngModuleScope === null) { // This technically shouldn't happen, but mark the scope as poisoned just in case. isPoisoned = true; continue; } isPoisoned = isPoisoned || ngModuleScope.exported.isPoisoned; for (const dep of ngModuleScope.exported.dependencies) { if (!seen.has(dep.ref.node)) { seen.add(dep.ref.node); dependencies.add(dep); } } continue; } // Import was not a component/directive/pipe/NgModule, which is an error and poisons the // scope. isPoisoned = true; } } if (clazzMeta.deferredImports !== null) { for (const ref of clazzMeta.deferredImports) { const dirMeta = this.metaReader.getDirectiveMetadata(ref); if (dirMeta !== null) { deferredDependencies.add({...dirMeta, ref, isExplicitlyDeferred: true}); isPoisoned = isPoisoned || dirMeta.isPoisoned || !dirMeta.isStandalone; continue; } const pipeMeta = this.metaReader.getPipeMetadata(ref); if (pipeMeta !== null) { deferredDependencies.add({...pipeMeta, ref, isExplicitlyDeferred: true}); isPoisoned = isPoisoned || !pipeMeta.isStandalone; continue; } } } this.cache.set(clazz, { kind: ComponentScopeKind.Standalone, component: clazz, dependencies: Array.from(dependencies), deferredDependencies: Array.from(deferredDependencies), isPoisoned, schemas: clazzMeta.schemas ?? [], }); } return this.cache.get(clazz)!; } getRemoteScope(): null { return null; } }
{ "end_byte": 4789, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/src/standalone.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/README.md_0_7203
# `imports` The `imports` module attempts to unify all import handling in ngtsc. It powers the compiler's reference system - how the compiler tracks classes like components, directives, NgModules, etc, and how it generates imports to them in user code. At its heart is the `Reference` abstraction, which combines a class `ts.Declaration` with any additional context needed to generate an import of that class in different situations. In Angular, users do not import the directives and pipes they use in templates directly. Instead, they import an NgModule, and the NgModule exports a set of directives/pipes which will be available in the template of any consumer. When generating code for the template, though, the directives/pipes used there need to be imported directly. This creates a challenge for the compiler: it must choose an ES module specifier from which they can be imported, since the user never provided it. Much of the logic around imports and references in the compiler is dedicated to answering this question. The compiler has two major modes of operation here: 1. Module specifier (import path) tracking If a directive/pipe is within the user's program, then it can be imported directly. If not (e.g. the directive came from a library in `node_modules`), the compiler will look at the NgModule that caused the directive to be available in the template, look at its import, and attempt to use the same module specifier. This logic is based on the Angular Package Format, which dictates that libraries are organized into entrypoints, and both an NgModule and its directives/pipes must be exported from the same entrypoint (usually an `index.ts` file). Thus, if `CommonModule` is imported from the specifier '@angular/common', and its `NgIf` directive is used in a template, the compiler will always import `NgIf` from '@angular/common' as well. It's important to note that this logic is transitive. If the user instead imported `BrowserModule` from '@angular/platform-browser' (which re-exports `CommonModule` and thus `NgIf`), the compiler will note that `BrowserModule` itself imported `CommonModule` from '@angular/common', and so `NgIf` will be imported from '@angular/common' still. This logic of course breaks down for non-Angular Package Format libraries, such as "internal" libraries within a monorepo, which frequently don't use `index.ts` files or entrypoints. In this case, the user will likely import NgModules directly from their declaration (e.g. via a 'lib/module' specifier), and the compiler cannot simply assume that the user has exported all of the directives/pipes from the NgModule via this same specifier. In this case a compiler feature called "aliasing" kicks in (see below) and generates private exports from the NgModule file. 2. Using a `UnifiedModulesHost` The `ts.CompilerHost` given to the compiler may optionally implement an interface called `UnifiedModulesHost`, which allows an absolute module specifier to be generated for any file. If a `UnifiedModulesHost` is present, the compiler will attempt to directly import all directives and pipes from the file which declares them, instead of going via the specifier of the NgModule as in the first mode described above. This logic is used internally in the Google monorepo. This approach comes with a significant caveat: the build system may prevent importing from files which are not directly declared dependencies of the current compilation (this is known as "strict dependency checking"). This is a problem when attempting to consume a re-exported directive. For example, if the user depends only on '@angular/platform-browser', imports `BrowserModule` from '@angular/platform-browser' and attempts to use the re-exported `NgIf`, the compiler cannot import `NgIf` directly from its declaration within '@angular/common', which is a transitive (but not direct) dependency. To support these re-exports, a compiler feature called "aliasing" will create a re-export of `NgIf` from within @angular/platform-browser when compiling that package. Then, the downstream application compiler can import `NgIf` via this "alias" re-export from a direct dependency, instead of needing to import it from a transitive dependency. ## References At its heart, the compiler keeps track of the types (classes) it's operating on using the `ts.Declaration` of that class. This suffices to _identify_ a class; however, the compiler frequently needs to track not only the class itself, but how that class came to be known in a particular context. For example, the compiler might see that `CommonModule` is included in `AppModule`'s imports, but it also needs to keep track of from where `CommonModule` was imported to apply the logic of "module specifier tracking" described above. To do this, the compiler will wrap the `ts.Declaration` of `CommonModule` into a `Reference`. A `Reference` is a pointer to a `ts.Declaration` plus any additional information and context about _how_ that reference came to be. ### Identifier tracking Where possible, the compiler tries to use existing user-provided imports to refer to classes, instead of generating new imports. This is possible because `Reference`s keep track of any `ts.Identifier`s encountered which refer to the referenced class. If Angular, in the course of processing a `ts.Expression` (such as the `declarations` array of an NgModule), determines that the `ts.Identifier` points to a `Reference`, it adds the `ts.Identifier` to that `Reference` for future use. The `Reference.getIdentityIn` method queries the `Reference` for a `ts.Identifier` that's valid in a given `ts.SourceFile`. This is used by the `LocalIdentifierStrategy` when emitting an `Expression` for the `Reference` (see the description of `ReferenceEmitter` below). #### Synthetic references In some cases, identifier tracking needs to be disabled for a `Reference`. For example, when the compiler synthesizes a `Reference` as part of "foreign function evaluation", the evaluated `ts.Identifier` may not be a direct reference to the `Reference`'s class at runtime, even if logically that interpretation makes sense in the context of the current expression. In these cases, the `Reference`s are marked as `synthetic`, which disables all `ts.Identifier` tracking. ### Owning modules As described above, one piece of information the compiler tracks about a `Reference` is the module specifier from which it came. This is known as its "owning module". For a `Reference`, the compiler tracks both the module specifier itself as well as the context file which contained this module specifier (which is important for TypeScript module resolution operations). This information is tracked in `Reference.bestGuessOwningModule`. This field carries the "best guess" prefix because the compiler cannot verify that each `Reference` which was extracted from a given ES module is actually exported via that module specifier. This depends on the packaging convention the user chose to use. Since a `Reference` may not belong to any external module, `bestGuessOwningModule` may be `null`. For convenience, the module specifier as a string is also made available as `Reference.ownedByModuleGuess`.
{ "end_byte": 7203, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/README.md" }
angular/packages/compiler-cli/src/ngtsc/imports/README.md_7203_14817
## ReferenceEmitter During evaluation of `ts.Expression`s, `Reference`s to specific directives/pipes/etc are created. During code generation, imports need to be generated for a particular component's template function, based on these `Reference`s. This job falls to the `ReferenceEmitter`. A `ReferenceEmitter` takes a `Reference` as well as a `ts.SourceFile` which will contain the import, and generates an `Expression` which can be used to refer to the referenced class within that file. This may or may not be an `ExternalExpression` (which would generate an import statement), depending on whether it's possible to rely on an existing import of the class within that file. `ReferenceEmitter` is a wrapper around one or more `ReferenceEmitStrategy` instances. Each strategy is tried in succession until an `Expression` can be determined. An error is produced if no valid mechanism of referring to the referenced class can be found. ### `LocalIdentifierStrategy` This `ReferenceEmitStrategy` queries the `Reference` for a `ts.Identifier` that's valid in the requested file (see "identifier tracking" for `Reference`s above). ### `LogicalProjectStrategy` This `ReferenceEmitStrategy` is used to import referenced classes that are declared in the current project, and not in any third-party or external libraries, whenever `rootDir` or `rootDirs` is set in the TS compiler options. When `rootDir`(s) are present, multiple physical directories can be mapped into the same logical namespace. So consider two files `/app/app.cmp.ts` and `/lib/lib.cmp.ts`. Ordinarily, a relative import (such as the kind generated by `RelativePathStrategy`) from the former to the latter would be `../lib/lib.cmp`. However, if both `/app` and `/lib` are project `rootDirs`, then the files within are logically in the same "directory", and the correct import is `./lib.cmp`. The `LogicalProjectStrategy` constructs `LogicalProjectPath`s between files and generates module specifiers that are relative imports within that namespace, honoring the project's `rootDirs` settings. The `LogicalProjectStrategy` will decline to generate an import into any file which falls outside the project's `rootDirs`, as such a relative specifier is not representable in the merged namespace. ### `RelativePathStrategy` This `ReferenceEmitStrategy` is used to generate relative imports between two files in the project, assuming the layout of files on the disk maps directly to the module specifier namespace. This is the case if the project does not have `rootDir`/`rootDirs` configured in its TS compiler options. ### `AbsoluteModuleStrategy` This `ReferenceEmitStrategy` uses the `bestGuessOwningModule` of a `Reference` to generate an import of the referenced class. Note that the `bestGuessOwningModule` only gives the module specifier for the import, not the symbol name. The user may have renamed the class as part of re-exporting it from an entrypoint, so the `AbsoluteModuleStrategy` searches the exports of the target module and finds the symbol name by which the class is re-exported, if it exists. ### `UnifiedModulesStrategy` This `ReferenceEmitStrategy` uses a `UnifiedModulesHost` to implement the major import mode #2 described at the beginning of this document. Under this strategy, direct imports to referenced classes are constructed using globally valid absolute module specifiers determined by the `UnifiedModulesHost`. Like with `AbsoluteModuleStrategy`, the `UnifiedModulesHost` only gives the module specifier and not the symbol name, so an appropriate symbol name must be determined by searching the exports of the module. ### `AliasStrategy` The `AliasStrategy` will choose the alias `Expression` of a `Reference`. This strategy is used before the `UnifiedModulesStrategy` to guarantee aliases are preferred to direct imports when available. See the description of aliasing in the case of `UnifiedModulesAliasingHost` below. ## Aliasing and re-exports In certain cases, the exports written by the user are not sufficient to guarantee that a downstream compiler will be able to depend on directives/pipes correctly. In these circumstances the compiler's "aliasing" system creates new exports to bridge the gaps. An `AliasingHost` interface allows different aliasing strategies to be chosen based on the needs of the current compilation. It supports two operations: 1. Determination of a re-export name, if needed, for a given directive/pipe. When compiling an NgModule, the compiler will consult the `AliasingHost` via its `maybeAliasSymbolAs` method to determine whether to add re-exports of any directives/pipes exported (directly or indirectly) by the NgModule. 2. Determination of an alias `Expression` for a directive/pipe, based on a re-export that was expected to have been generated previously. When the user imports an NgModule from an external library (via a `.d.ts` file), the compiler will construct a "scope" of exported directives/pipes that this NgModule makes available to any templates. In the process of constructing this scope, the compiler creates `Reference`s for each directive/pipe. As part of this operation, the compiler will consult the `AliasingHost` via its `getAliasIn` method to determine whether an alias `Expression` should be used to refer to each class instead of going through other import generation logic. This alias is saved on the `Reference`. Because the first import of an NgModule from a user library to a `.d.ts` is always from a direct dependency, the result is that all `Reference`s to directives/pipes which can be used from this module will have an associated alias `Expression` specifying how to import them from that direct dependency, instead of from a transitive dependency. Aliasing is currently used in two cases: 1. To address strict dependency checking issues when using a `UnifiedModulesHost`. 2. To support depending on non-Angular Package Format packages (e.g. private libraries in monorepos) which do not have an entrypoint file through which all directives/pipes/modules are exported. In environments with "strict dependency checking" as described above, an NgModule which exports another NgModule from one of its dependencies needs to export its directives/pipes as well, in order to make them available to the downstream compiler. ### Aliasing under `UnifiedModulesHost` A `UnifiedModulesAliasingHost` implements `AliasingHost` and makes full use of the aliasing system in the case of a `UnifiedModulesHost`. When compiling an NgModule, re-exports are added under a stable name for each directive/pipe that's re-exported by the NgModule. When importing that NgModule, alias `Expression`s are added to all the `Reference`s for those directives/pipes that are guaranteed to be from a direct dependency. ### Private re-exports for non-APF packages A `PrivateExportAliasingHost` is used to add re-exports of directives/pipes in the case where the compiler cannot determine that all directives/pipes are re-exported from a common entrypoint (like in the case of an Angular Package Format compilation). In this case, aliasing is used to proactively add re-exports of directives/pipes to the file of any NgModule which exports them, ensuring they can be imported from the same module specifier as the NgModule itself. This is only done if the user has not already added such exports directly. This `AliasingHost` does not tag any `Reference`s with aliases, and relies on the action of the `AbsoluteModuleStrategy` described above to find and select the alias re-export when attempting to write an import for a given `Reference`.
{ "end_byte": 14817, "start_byte": 7203, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/README.md" }
angular/packages/compiler-cli/src/ngtsc/imports/README.md_14817_17747
## Default imports This aspect of the `imports` package is a little different than the rest of the code as it's not concerned with directive/pipe imports. Instead, it's concerned with a different problem: preventing the removal of default import statements which were converted from type-only to value imports through compilation. ### Type-to-value compilation This occurs when a default import is used as a type parameter in a service constructor: ```typescript import Foo from 'foo'; @Injectable() export class Svc { constructor(private foo: Foo) {} } ``` Here, `Foo` is used in the type position only, but the compiler will eventually generate an `inject(Foo)` call in the factory function for this service. The use of `Foo` like this in the output depends on the import statement surviving compilation. Due to quirks in TypeScript transformers (see below), TypeScript considers the import to be type-only and does not notice the additional usage as a value added during transformation, and so will attempt to remove the import. The default import managing system exists to prevent this. It consists of two mechanisms: 1. A `DefaultImportTracker`, which records information about both default imports encountered in the program as well as usages of those imports added during compilation. 2. A TypeScript transformer which processes default import statements and can preserve those which are actually used. This is accessed via `DefaultImportTracker.importPreservingTransformer`. ### Why default imports are problematic This section is the result of speculation, as we have not traced the TypeScript compiler thoroughly. Consider the class: ```typescript import {Foo} from './foo'; class X { constructor(foo: Foo) {} } ``` Angular wants to generate a value expression (`inject(Foo)`), using the value side of the `Foo` type from the constructor. After transforms, this roughly looks like: ```javascript let foo_1 = require('./foo'); inject(foo_1.Foo); ``` The Angular compiler takes the `Foo` `ts.Identifier` from the import statement `import {Foo} from './foo'`, which has a "provenance" in TypeScript that indicates it's associated with the import statement. After transforms, TypeScript will scan the output code and notice this `ts.Identifier` is still present, and so it will choose to preserve the import statement. If, however, `Foo` was a default import: ```typescript import Foo from './foo'; ``` Then the generated code depends on a few factors (target/module/esModuleInterop settings), but roughly looks like: ```javascript let foo_1 = require('./foo'); inject(foo_1.default); ``` Note in this output, the `Foo` identifier from before has disappeared. TypeScript then does not find any `ts.Identifier`s which point back to the original import statement, and thus it concludes that the import is unused. It's likely that this case was overlooked in the design of the transformers API.
{ "end_byte": 17747, "start_byte": 14817, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/README.md" }
angular/packages/compiler-cli/src/ngtsc/imports/BUILD.bazel_0_606
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "imports", srcs = ["index.ts"] + glob([ "src/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 606, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/imports/index.ts_0_1401
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { AliasingHost, AliasStrategy, PrivateExportAliasingHost, UnifiedModulesAliasingHost, } from './src/alias'; export { ImportRewriter, NoopImportRewriter, R3SymbolsImportRewriter, validateAndRewriteCoreSymbol, } from './src/core'; export {DefaultImportTracker} from './src/default'; export {DeferredSymbolTracker} from './src/deferred_symbol_tracker'; export { AbsoluteModuleStrategy, assertSuccessfulReferenceEmit, EmittedReference, FailedEmitResult, ImportedFile, ImportFlags, LocalIdentifierStrategy, LogicalProjectStrategy, ReferenceEmitKind, ReferenceEmitResult, ReferenceEmitStrategy, ReferenceEmitter, RelativePathStrategy, UnifiedModulesStrategy, } from './src/emitter'; export {ImportedSymbolsTracker} from './src/imported_symbols_tracker'; export {LocalCompilationExtraImportsTracker} from './src/local_compilation_extra_imports_tracker'; export { AliasImportDeclaration, isAliasImportDeclaration, loadIsReferencedAliasDeclarationPatch, } from './src/patch_alias_reference_resolution'; export {Reexport} from './src/reexport'; export {OwningModule, Reference} from './src/references'; export {ModuleResolver} from './src/resolver';
{ "end_byte": 1401, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/index.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts_0_6928
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {ExternalExpr} from '@angular/compiler'; import ts from 'typescript'; import {UnifiedModulesHost} from '../../core/api'; import {absoluteFrom as _, basename, LogicalFileSystem} from '../../file_system'; import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import {Declaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import { AbsoluteModuleStrategy, ImportFlags, LogicalProjectStrategy, ReferenceEmitKind, RelativePathStrategy, UnifiedModulesStrategy, } from '../src/emitter'; import {Reference} from '../src/references'; import {ModuleResolver} from '../src/resolver'; runInEachFileSystem(() => { describe('AbsoluteModuleStrategy', () => { function makeStrategy(files: TestFile[]) { const {program, host} = makeProgram(files); const checker = program.getTypeChecker(); const moduleResolver = new ModuleResolver( program, program.getCompilerOptions(), host, /* moduleResolutionCache */ null, ); const strategy = new AbsoluteModuleStrategy( program, checker, moduleResolver, new TypeScriptReflectionHost(checker), ); return {strategy, program}; } it('should not generate an import for a reference without owning module', () => { const {strategy, program} = makeStrategy([ { name: _('/node_modules/external.d.ts'), contents: `export declare class Foo {}`, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isClassDeclaration, ); const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl); const emitted = strategy.emit(reference, context, ImportFlags.None); expect(emitted).toBeNull(); }); it('should prefer non-aliased exports', () => { const {strategy, program} = makeStrategy([ { name: _('/node_modules/external.d.ts'), contents: ` declare class Foo {} export {Foo as A}; export {Foo}; export {Foo as B}; `, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isClassDeclaration, ); const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, { specifier: 'external', resolutionContext: context.fileName, }); const emitted = strategy.emit(reference, context, ImportFlags.None); if (emitted === null || emitted.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Foo'); expect(emitted.expression.value.moduleName).toEqual('external'); }); it('should generate an import using the exported name of the declaration', () => { const {strategy, program} = makeStrategy([ { name: _('/node_modules/external.d.ts'), contents: ` declare class Foo {} export {Foo as Bar}; `, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isClassDeclaration, ); const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, { specifier: 'external', resolutionContext: context.fileName, }); const emitted = strategy.emit(reference, context, ImportFlags.None); if (emitted === null || emitted.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Bar'); expect(emitted.expression.value.moduleName).toEqual('external'); }); it('should throw when generating an import to a type-only declaration when not allowed', () => { const {strategy, program} = makeStrategy([ { name: _('/node_modules/external.d.ts'), contents: `export declare interface Foo {}`, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isInterfaceDeclaration, ); const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, { specifier: 'external', resolutionContext: context.fileName, }); expect(() => strategy.emit(reference, context, ImportFlags.None)).toThrowError( 'Importing a type-only declaration of type InterfaceDeclaration in a value position is not allowed.', ); }); it('should generate an import to a type-only declaration when allowed', () => { const {strategy, program} = makeStrategy([ { name: _('/node_modules/external.d.ts'), contents: `export declare interface Foo {}`, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const decl = getDeclaration( program, _('/node_modules/external.d.ts'), 'Foo', ts.isInterfaceDeclaration, ); const context = program.getSourceFile(_('/context.ts'))!; const reference = new Reference(decl, { specifier: 'external', resolutionContext: context.fileName, }); const emitted = strategy.emit(reference, context, ImportFlags.AllowTypeImports); if (emitted === null || emitted.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Foo'); expect(emitted.expression.value.moduleName).toEqual('external'); }); });
{ "end_byte": 6928, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts_6932_16105
describe('LogicalProjectStrategy', () => { it('should enumerate exports with the ReflectionHost', () => { // Use a modified ReflectionHost that prefixes all export names that it enumerates. class TestHost extends TypeScriptReflectionHost { override getExportsOfModule(node: ts.Node): Map<string, Declaration> | null { const realExports = super.getExportsOfModule(node); if (realExports === null) { return null; } const fakeExports = new Map<string, Declaration>(); realExports.forEach((decl, name) => { fakeExports.set(`test${name}`, decl); }); return fakeExports; } } const {program, host} = makeProgram([ { name: _('/index.ts'), contents: `export class Foo {}`, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem([_('/')], host); const strategy = new LogicalProjectStrategy(new TestHost(checker), logicalFs); const decl = getDeclaration(program, _('/index.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/context.ts'))!; const ref = strategy.emit(new Reference(decl), context, ImportFlags.None); if (ref === null || ref.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } // Expect the prefixed name from the TestHost. expect((ref!.expression as ExternalExpr).value.name).toEqual('testFoo'); }); it('should prefer non-aliased exports', () => { const {program, host} = makeProgram([ { name: _('/index.ts'), contents: ` declare class Foo {} export {Foo as A}; export {Foo}; export {Foo as B}; `, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem([_('/')], host); const strategy = new LogicalProjectStrategy(new TypeScriptReflectionHost(checker), logicalFs); const decl = getDeclaration(program, _('/index.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/context.ts'))!; const emitted = strategy.emit(new Reference(decl), context, ImportFlags.None); if (emitted === null || emitted.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Foo'); expect(emitted.expression.value.moduleName).toEqual('./index'); }); it('should never use relative imports outside of the logical filesystem for source files', () => { const {program, host} = makeProgram([ { name: _('/app/context.ts'), contents: ` export {}; `, }, { name: _('/foo.ts'), contents: 'export declare class Foo {}', }, ]); const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem([_('/app')], host); const strategy = new LogicalProjectStrategy(new TypeScriptReflectionHost(checker), logicalFs); const decl = getDeclaration(program, _('/foo.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/app/context.ts'))!; const emitted = strategy.emit( new Reference(decl), context, ImportFlags.AllowRelativeDtsImports, ); if (emitted === null || emitted.kind !== ReferenceEmitKind.Failed) { return fail('Reference emit should have failed'); } expect(emitted.reason).toEqual( `The file ${decl.getSourceFile().fileName} is outside of the configured 'rootDir'.`, ); }); it('should use relative imports outside of the logical filesystem for declaration files if allowed', () => { const {program, host} = makeProgram([ { name: _('/app/context.ts'), contents: ` export {}; `, }, { name: _('/foo.d.ts'), contents: 'export declare class Foo {}', }, ]); const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem([_('/app')], host); const strategy = new LogicalProjectStrategy(new TypeScriptReflectionHost(checker), logicalFs); const decl = getDeclaration(program, _('/foo.d.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/app/context.ts'))!; const emitted = strategy.emit( new Reference(decl), context, ImportFlags.AllowRelativeDtsImports, ); if (emitted === null || emitted.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Foo'); expect(emitted.expression.value.moduleName).toEqual('../foo'); }); it('should not use relative imports outside of the logical filesystem for declaration files if not allowed', () => { const {program, host} = makeProgram([ { name: _('/app/context.ts'), contents: ` export {}; `, }, { name: _('/foo.d.ts'), contents: 'export declare class Foo {}', }, ]); const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem([_('/app')], host); const strategy = new LogicalProjectStrategy(new TypeScriptReflectionHost(checker), logicalFs); const decl = getDeclaration(program, _('/foo.d.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/app/context.ts'))!; const emitted = strategy.emit(new Reference(decl), context, ImportFlags.None); if (emitted === null || emitted.kind !== ReferenceEmitKind.Failed) { return fail('Reference emit should have failed'); } expect(emitted.reason).toEqual( `The file ${decl.getSourceFile().fileName} is outside of the configured 'rootDir'.`, ); }); }); describe('RelativePathStrategy', () => { it('should prefer non-aliased exports', () => { const {program} = makeProgram([ { name: _('/index.ts'), contents: ` declare class Foo {} export {Foo as A}; export {Foo}; export {Foo as B}; `, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const checker = program.getTypeChecker(); const strategy = new RelativePathStrategy(new TypeScriptReflectionHost(checker)); const decl = getDeclaration(program, _('/index.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/context.ts'))!; const emitted = strategy.emit(new Reference(decl), context); if (emitted === null || emitted.kind !== ReferenceEmitKind.Success) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Foo'); expect(emitted.expression.value.moduleName).toEqual('./index'); }); }); describe('UnifiedModulesStrategy', () => { it('should prefer non-aliased exports', () => { const {program} = makeProgram([ { name: _('/index.ts'), contents: ` declare class Foo {} export {Foo as A}; export {Foo}; export {Foo as B}; `, }, { name: _('/context.ts'), contents: 'export class Context {}', }, ]); const checker = program.getTypeChecker(); const host: UnifiedModulesHost = { fileNameToModuleName(importedFilePath): string { return basename(importedFilePath, '.ts'); }, }; const strategy = new UnifiedModulesStrategy(new TypeScriptReflectionHost(checker), host); const decl = getDeclaration(program, _('/index.ts'), 'Foo', ts.isClassDeclaration); const context = program.getSourceFile(_('/context.ts'))!; const emitted = strategy.emit(new Reference(decl), context); if (emitted === null) { return fail('Reference should be emitted'); } if (!(emitted.expression instanceof ExternalExpr)) { return fail('Reference should be emitted as ExternalExpr'); } expect(emitted.expression.value.name).toEqual('Foo'); expect(emitted.expression.value.moduleName).toEqual('index'); }); }); });
{ "end_byte": 16105, "start_byte": 6932, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/test/emitter_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/test/default_spec.ts_0_4003
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {absoluteFrom} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {getDeclaration, makeProgram} from '../../testing'; import {DefaultImportTracker} from '../src/default'; runInEachFileSystem(() => { describe('DefaultImportTracker', () => { let _: typeof absoluteFrom; beforeEach(() => (_ = absoluteFrom)); it('should prevent a default import from being elided if used', () => { const {program, host} = makeProgram( [ {name: _('/dep.ts'), contents: `export default class Foo {}`}, { name: _('/test.ts'), contents: `import Foo from './dep'; export function test(f: Foo) {}`, }, // This control file is identical to the test file, but will not have its import marked // for preservation. It exists to verify that it is in fact the action of // DefaultImportTracker and not some other artifact of the test setup which causes the // import to be preserved. It will also verify that DefaultImportTracker does not // preserve imports which are not marked for preservation. { name: _('/ctrl.ts'), contents: `import Foo from './dep'; export function test(f: Foo) {}`, }, ], { module: ts.ModuleKind.ES2015, }, ); const fooClause = getDeclaration(program, _('/test.ts'), 'Foo', ts.isImportClause); const fooDecl = fooClause.parent as ts.ImportDeclaration; const tracker = new DefaultImportTracker(); tracker.recordUsedImport(fooDecl); program.emit(undefined, undefined, undefined, undefined, { before: [tracker.importPreservingTransformer()], }); const testContents = host.readFile('/test.js')!; expect(testContents).toContain(`import Foo from './dep';`); // The control should have the import elided. const ctrlContents = host.readFile('/ctrl.js'); expect(ctrlContents).not.toContain(`import Foo from './dep';`); }); it('should transpile imports correctly into commonjs', () => { const {program, host} = makeProgram( [ {name: _('/dep.ts'), contents: `export default class Foo {}`}, { name: _('/test.ts'), contents: `import Foo from './dep'; export function test(f: Foo) {}`, }, ], { module: ts.ModuleKind.CommonJS, }, ); const fooClause = getDeclaration(program, _('/test.ts'), 'Foo', ts.isImportClause); const fooId = fooClause.name!; const fooDecl = fooClause.parent as ts.ImportDeclaration; const tracker = new DefaultImportTracker(); tracker.recordUsedImport(fooDecl); program.emit(undefined, undefined, undefined, undefined, { before: [addReferenceTransformer(fooId), tracker.importPreservingTransformer()], }); const testContents = host.readFile('/test.js')!; expect(testContents).toContain(`var dep_1 = require("./dep");`); expect(testContents).toContain(`var ref = dep_1.default;`); }); }); function addReferenceTransformer(id: ts.Identifier): ts.TransformerFactory<ts.SourceFile> { return (context: ts.TransformationContext) => { return (sf: ts.SourceFile) => { if (id.getSourceFile().fileName === sf.fileName) { return ts.factory.updateSourceFile(sf, [ ...sf.statements, ts.factory.createVariableStatement( undefined, ts.factory.createVariableDeclarationList([ ts.factory.createVariableDeclaration('ref', undefined, undefined, id), ]), ), ]); } return sf; }; }; } });
{ "end_byte": 4003, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/test/default_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/test/BUILD.bazel_0_803
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 803, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/imports/src/deferred_symbol_tracker.ts_0_7840
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {ClassDeclaration} from '../../reflection'; import {getContainingImportDeclaration} from '../../reflection/src/typescript'; const AssumeEager = 'AssumeEager'; type AssumeEager = typeof AssumeEager; /** * Maps imported symbol name to a set of locations where the symbols is used * in a source file. */ type SymbolMap = Map<string, Set<ts.Identifier> | AssumeEager>; /** * Allows to register a symbol as deferrable and keep track of its usage. * * This information is later used to determine whether it's safe to drop * a regular import of this symbol (actually the entire import declaration) * in favor of using a dynamic import for cases when defer blocks are used. */ export class DeferredSymbolTracker { private readonly imports = new Map<ts.ImportDeclaration, SymbolMap>(); /** * Map of a component class -> all import declarations that bring symbols * used within `@Component.deferredImports` field. */ private readonly explicitlyDeferredImports = new Map<ClassDeclaration, ts.ImportDeclaration[]>(); constructor( private readonly typeChecker: ts.TypeChecker, private onlyExplicitDeferDependencyImports: boolean, ) {} /** * Given an import declaration node, extract the names of all imported symbols * and return them as a map where each symbol is a key and `AssumeEager` is a value. * * The logic recognizes the following import shapes: * * Case 1: `import {a, b as B} from 'a'` * Case 2: `import X from 'a'` * Case 3: `import * as x from 'a'` */ private extractImportedSymbols(importDecl: ts.ImportDeclaration): Map<string, AssumeEager> { const symbolMap = new Map<string, AssumeEager>(); // Unsupported case: `import 'a'` if (importDecl.importClause === undefined) { throw new Error(`Provided import declaration doesn't have any symbols.`); } // If the entire import is a type-only import, none of the symbols can be eager. if (importDecl.importClause.isTypeOnly) { return symbolMap; } if (importDecl.importClause.namedBindings !== undefined) { const bindings = importDecl.importClause.namedBindings; if (ts.isNamedImports(bindings)) { // Case 1: `import {a, b as B} from 'a'` for (const element of bindings.elements) { if (!element.isTypeOnly) { symbolMap.set(element.name.text, AssumeEager); } } } else { // Case 2: `import X from 'a'` symbolMap.set(bindings.name.text, AssumeEager); } } else if (importDecl.importClause.name !== undefined) { // Case 2: `import * as x from 'a'` symbolMap.set(importDecl.importClause.name.text, AssumeEager); } else { throw new Error('Unrecognized import structure.'); } return symbolMap; } /** * Retrieves a list of import declarations that contain symbols used within * `@Component.deferredImports` of a specific component class, but those imports * can not be removed, since there are other symbols imported alongside deferred * components. */ getNonRemovableDeferredImports( sourceFile: ts.SourceFile, classDecl: ClassDeclaration, ): ts.ImportDeclaration[] { const affectedImports: ts.ImportDeclaration[] = []; const importDecls = this.explicitlyDeferredImports.get(classDecl) ?? []; for (const importDecl of importDecls) { if (importDecl.getSourceFile() === sourceFile && !this.canDefer(importDecl)) { affectedImports.push(importDecl); } } return affectedImports; } /** * Marks a given identifier and an associated import declaration as a candidate * for defer loading. */ markAsDeferrableCandidate( identifier: ts.Identifier, importDecl: ts.ImportDeclaration, componentClassDecl: ClassDeclaration, isExplicitlyDeferred: boolean, ): void { if (this.onlyExplicitDeferDependencyImports && !isExplicitlyDeferred) { // Ignore deferrable candidates when only explicit deferred imports mode is enabled. // In that mode only dependencies from the `@Component.deferredImports` field are // defer-loadable. return; } if (isExplicitlyDeferred) { if (this.explicitlyDeferredImports.has(componentClassDecl)) { this.explicitlyDeferredImports.get(componentClassDecl)!.push(importDecl); } else { this.explicitlyDeferredImports.set(componentClassDecl, [importDecl]); } } let symbolMap = this.imports.get(importDecl); // Do we come across this import for the first time? if (!symbolMap) { symbolMap = this.extractImportedSymbols(importDecl); this.imports.set(importDecl, symbolMap); } if (!symbolMap.has(identifier.text)) { throw new Error( `The '${identifier.text}' identifier doesn't belong ` + `to the provided import declaration.`, ); } if (symbolMap.get(identifier.text) === AssumeEager) { // We process this symbol for the first time, populate references. symbolMap.set( identifier.text, this.lookupIdentifiersInSourceFile(identifier.text, importDecl), ); } const identifiers = symbolMap.get(identifier.text) as Set<ts.Identifier>; // Drop the current identifier, since we are trying to make it deferrable // (it's used as a dependency in one of the defer blocks). identifiers.delete(identifier); } /** * Whether all symbols from a given import declaration have no references * in a source file, thus it's safe to use dynamic imports. */ canDefer(importDecl: ts.ImportDeclaration): boolean { if (!this.imports.has(importDecl)) { return false; } const symbolsMap = this.imports.get(importDecl)!; for (const refs of symbolsMap.values()) { if (refs === AssumeEager || refs.size > 0) { // There may be still eager references to this symbol. return false; } } return true; } /** * Returns a set of import declarations that is safe to remove * from the current source file and generate dynamic imports instead. */ getDeferrableImportDecls(): Set<ts.ImportDeclaration> { const deferrableDecls = new Set<ts.ImportDeclaration>(); for (const [importDecl] of this.imports) { if (this.canDefer(importDecl)) { deferrableDecls.add(importDecl); } } return deferrableDecls; } private lookupIdentifiersInSourceFile( name: string, importDecl: ts.ImportDeclaration, ): Set<ts.Identifier> { const results = new Set<ts.Identifier>(); const visit = (node: ts.Node): void => { // Don't record references from the declaration itself or inside // type nodes which will be stripped from the JS output. if (node === importDecl || ts.isTypeNode(node)) { return; } if (ts.isIdentifier(node) && node.text === name) { // Is `node` actually a reference to this symbol? const sym = this.typeChecker.getSymbolAtLocation(node); if (sym === undefined) { return; } if (sym.declarations === undefined || sym.declarations.length === 0) { return; } const importClause = sym.declarations[0]; // Is declaration from this import statement? const decl = getContainingImportDeclaration(importClause); if (decl !== importDecl) { return; } // `node` *is* a reference to the same import. results.add(node); } ts.forEachChild(node, visit); }; visit(importDecl.getSourceFile()); return results; } }
{ "end_byte": 7840, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/deferred_symbol_tracker.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/reexport.ts_0_297
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export interface Reexport { symbolName: string; asAlias: string; fromModule: string; }
{ "end_byte": 297, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/reexport.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/patch_alias_reference_resolution.ts_0_7352
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; /** Possible alias import declarations */ export type AliasImportDeclaration = ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause; /** * Describes a TypeScript transformation context with the internal emit * resolver exposed. There are requests upstream in TypeScript to expose * that as public API: https://github.com/microsoft/TypeScript/issues/17516. */ interface TransformationContextWithResolver extends ts.TransformationContext { getEmitResolver: () => EmitResolver; } const patchedReferencedAliasesSymbol = Symbol('patchedReferencedAliases'); /** Describes a subset of the TypeScript internal emit resolver. */ interface EmitResolver { isReferencedAliasDeclaration?(node: ts.Node, ...args: unknown[]): void; [patchedReferencedAliasesSymbol]?: Set<AliasImportDeclaration>; } /** * Patches the alias declaration reference resolution for a given transformation context * so that TypeScript knows about the specified alias declarations being referenced. * * This exists because TypeScript performs analysis of import usage before transformers * run and doesn't refresh its state after transformations. This means that imports * for symbols used as constructor types are elided due to their original type-only usage. * * In reality though, since we downlevel decorators and constructor parameters, we want * these symbols to be retained in the JavaScript output as they will be used as values * at runtime. We can instruct TypeScript to preserve imports for such identifiers by * creating a mutable clone of a given import specifier/clause or namespace, but that * has the downside of preserving the full import in the JS output. See: * https://github.com/microsoft/TypeScript/blob/3eaa7c65f6f076a08a5f7f1946fd0df7c7430259/src/compiler/transformers/ts.ts#L242-L250. * * This is a trick the CLI used in the past for constructor parameter downleveling in JIT: * https://github.com/angular/angular-cli/blob/b3f84cc5184337666ce61c07b7b9df418030106f/packages/ngtools/webpack/src/transformers/ctor-parameters.ts#L323-L325 * The trick is not ideal though as it preserves the full import (as outlined before), and it * results in a slow-down due to the type checker being involved multiple times. The CLI worked * around this import preserving issue by having another complex post-process step that detects and * elides unused imports. Note that these unused imports could cause unused chunks being generated * by Webpack if the application or library is not marked as side-effect free. * * This is not ideal though, as we basically re-implement the complex import usage resolution * from TypeScript. We can do better by letting TypeScript do the import eliding, but providing * information about the alias declarations (e.g. import specifiers) that should not be elided * because they are actually referenced (as they will now appear in static properties). * * More information about these limitations with transformers can be found in: * 1. https://github.com/Microsoft/TypeScript/issues/17552. * 2. https://github.com/microsoft/TypeScript/issues/17516. * 3. https://github.com/angular/tsickle/issues/635. * * The patch we apply to tell TypeScript about actual referenced aliases (i.e. imported symbols), * matches conceptually with the logic that runs internally in TypeScript when the * `emitDecoratorMetadata` flag is enabled. TypeScript basically surfaces the same problem and * solves it conceptually the same way, but obviously doesn't need to access an internal API. * * The set that is returned by this function is meant to be filled with import declaration nodes * that have been referenced in a value-position by the transform, such the installed patch can * ensure that those import declarations are not elided. * * See below. Note that this uses sourcegraph as the TypeScript checker file doesn't display on * Github. * https://sourcegraph.com/github.com/microsoft/TypeScript@3eaa7c65f6f076a08a5f7f1946fd0df7c7430259/-/blob/src/compiler/checker.ts#L31219-31257 */ export function loadIsReferencedAliasDeclarationPatch( context: ts.TransformationContext, ): Set<ts.Declaration> { // If the `getEmitResolver` method is not available, TS most likely changed the // internal structure of the transformation context. We will abort gracefully. if (!isTransformationContextWithEmitResolver(context)) { throwIncompatibleTransformationContextError(); } const emitResolver = context.getEmitResolver(); // The emit resolver may have been patched already, in which case we return the set of referenced // aliases that was created when the patch was first applied. // See https://github.com/angular/angular/issues/40276. const existingReferencedAliases = emitResolver[patchedReferencedAliasesSymbol]; if (existingReferencedAliases !== undefined) { return existingReferencedAliases; } const originalIsReferencedAliasDeclaration = emitResolver.isReferencedAliasDeclaration; // If the emit resolver does not have a function called `isReferencedAliasDeclaration`, then // we abort gracefully as most likely TS changed the internal structure of the emit resolver. if (originalIsReferencedAliasDeclaration === undefined) { throwIncompatibleTransformationContextError(); } const referencedAliases = new Set<AliasImportDeclaration>(); emitResolver.isReferencedAliasDeclaration = function (node, ...args) { if (isAliasImportDeclaration(node) && (referencedAliases as Set<ts.Node>).has(node)) { return true; } return originalIsReferencedAliasDeclaration.call(emitResolver, node, ...args); }; return (emitResolver[patchedReferencedAliasesSymbol] = referencedAliases); } /** * Gets whether a given node corresponds to an import alias declaration. Alias * declarations can be import specifiers, namespace imports or import clauses * as these do not declare an actual symbol but just point to a target declaration. */ export function isAliasImportDeclaration(node: ts.Node): node is AliasImportDeclaration { return ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node); } /** Whether the transformation context exposes its emit resolver. */ function isTransformationContextWithEmitResolver( context: ts.TransformationContext, ): context is TransformationContextWithResolver { return (context as Partial<TransformationContextWithResolver>).getEmitResolver !== undefined; } /** * Throws an error about an incompatible TypeScript version for which the alias * declaration reference resolution could not be monkey-patched. The error will * also propose potential solutions that can be applied by developers. */ function throwIncompatibleTransformationContextError(): never { throw Error( 'Angular compiler is incompatible with this version of the TypeScript compiler.\n\n' + 'If you recently updated TypeScript and this issue surfaces now, consider downgrading.\n\n' + 'Please report an issue on the Angular repositories when this issue ' + 'surfaces and you are using a supposedly compatible TypeScript version.', ); }
{ "end_byte": 7352, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/patch_alias_reference_resolution.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts_0_8233
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {Expression, ExternalExpr, ExternalReference, WrappedNodeExpr} from '@angular/compiler'; import ts from 'typescript'; import {UnifiedModulesHost} from '../../core/api'; import { ErrorCode, FatalDiagnosticError, makeDiagnosticChain, makeRelatedInformation, } from '../../diagnostics'; import { absoluteFromSourceFile, dirname, LogicalFileSystem, LogicalProjectPath, relative, toRelativeImport, } from '../../file_system'; import {stripExtension} from '../../file_system/src/util'; import {DeclarationNode, ReflectionHost} from '../../reflection'; import { getSourceFile, identifierOfNode, isDeclaration, isNamedDeclaration, isTypeDeclaration, nodeNameForError, } from '../../util/src/typescript'; import {findExportedNameOfNode} from './find_export'; import {Reference} from './references'; import {ModuleResolver} from './resolver'; /** * Flags which alter the imports generated by the `ReferenceEmitter`. */ export enum ImportFlags { None = 0x00, /** * Force the generation of a new import when generating a reference, even if an identifier already * exists in the target file which could be used instead. * * This is sometimes required if there's a risk TypeScript might remove imports during emit. */ ForceNewImport = 0x01, /** * Don't make use of any aliasing information when emitting a reference. * * This is sometimes required if emitting into a context where generated references will be fed * into TypeScript and type-checked (such as in template type-checking). */ NoAliasing = 0x02, /** * Indicates that an import to a type-only declaration is allowed. * * For references that occur in type-positions, the referred declaration may be a type-only * declaration that is not retained during emit. Including this flag allows to emit references to * type-only declarations as used in e.g. template type-checking. */ AllowTypeImports = 0x04, /** * Indicates that importing from a declaration file using a relative import path is allowed. * * The generated imports should normally use module specifiers that are valid for use in * production code, where arbitrary relative imports into e.g. node_modules are not allowed. For * template type-checking code it is however acceptable to use relative imports, as such files are * never emitted to JS code. * * Non-declaration files have to be contained within a configured `rootDir` so using relative * paths may not be possible for those, hence this flag only applies when importing from a * declaration file. */ AllowRelativeDtsImports = 0x08, /** * Indicates that references coming from ambient imports are allowed. */ AllowAmbientReferences = 0x010, } /** * An emitter strategy has the ability to indicate which `ts.SourceFile` is being imported by the * expression that it has generated. This information is useful for consumers of the emitted * reference that would otherwise have to perform a relatively expensive module resolution step, * e.g. for cyclic import analysis. In cases the emitter is unable to definitively determine the * imported source file or a computation would be required to actually determine the imported * source file, then `'unknown'` should be returned. If the generated expression does not represent * an import then `null` should be used. */ export type ImportedFile = ts.SourceFile | 'unknown' | null; export const enum ReferenceEmitKind { Success, Failed, } /** * Represents the emitted expression of a `Reference` that is valid in the source file it was * emitted from. */ export interface EmittedReference { kind: ReferenceEmitKind.Success; /** * The expression that refers to `Reference`. */ expression: Expression; /** * The `ts.SourceFile` that is imported by `expression`. This is not necessarily the source file * of the `Reference`'s declaration node, as the reference may have been rewritten through an * alias export. It could also be `null` if `expression` is a local identifier, or `'unknown'` if * the exact source file that is being imported is not known to the emitter. */ importedFile: ImportedFile; } /** * Represents a failure to emit a `Reference` into a different source file. */ export interface FailedEmitResult { kind: ReferenceEmitKind.Failed; /** * The reference that could not be emitted. */ ref: Reference; /** * The source file into which the reference was requested to be emitted. */ context: ts.SourceFile; /** * Describes why the reference could not be emitted. This may be shown in a diagnostic. */ reason: string; } export type ReferenceEmitResult = EmittedReference | FailedEmitResult; /** * Verifies that a reference was emitted successfully, or raises a `FatalDiagnosticError` otherwise. * @param result The emit result that should have been successful. * @param origin The node that is used to report the failure diagnostic. * @param typeKind The kind of the symbol that the reference represents, e.g. 'component' or * 'class'. */ export function assertSuccessfulReferenceEmit( result: ReferenceEmitResult, origin: ts.Node, typeKind: string, ): asserts result is EmittedReference { if (result.kind === ReferenceEmitKind.Success) { return; } const message = makeDiagnosticChain( `Unable to import ${typeKind} ${nodeNameForError(result.ref.node)}.`, [makeDiagnosticChain(result.reason)], ); throw new FatalDiagnosticError(ErrorCode.IMPORT_GENERATION_FAILURE, origin, message, [ makeRelatedInformation(result.ref.node, `The ${typeKind} is declared here.`), ]); } /** * A particular strategy for generating an expression which refers to a `Reference`. * * There are many potential ways a given `Reference` could be referred to in the context of a given * file. A local declaration could be available, the `Reference` could be importable via a relative * import within the project, or an absolute import into `node_modules` might be necessary. * * Different `ReferenceEmitStrategy` implementations implement specific logic for generating such * references. A single strategy (such as using a local declaration) may not always be able to * generate an expression for every `Reference` (for example, if no local identifier is available), * and may return `null` in such a case. */ export interface ReferenceEmitStrategy { /** * Emit an `Expression` which refers to the given `Reference` in the context of a particular * source file, if possible. * * @param ref the `Reference` for which to generate an expression * @param context the source file in which the `Expression` must be valid * @param importFlags a flag which controls whether imports should be generated or not * @returns an `EmittedReference` which refers to the `Reference`, or `null` if none can be * generated */ emit( ref: Reference, context: ts.SourceFile, importFlags: ImportFlags, ): ReferenceEmitResult | null; } /** * Generates `Expression`s which refer to `Reference`s in a given context. * * A `ReferenceEmitter` uses one or more `ReferenceEmitStrategy` implementations to produce an * `Expression` which refers to a `Reference` in the context of a particular file. */ export class ReferenceEmitter { constructor(private strategies: ReferenceEmitStrategy[]) {} emit( ref: Reference, context: ts.SourceFile, importFlags: ImportFlags = ImportFlags.None, ): ReferenceEmitResult { for (const strategy of this.strategies) { const emitted = strategy.emit(ref, context, importFlags); if (emitted !== null) { return emitted; } } return { kind: ReferenceEmitKind.Failed, ref, context, reason: `Unable to write a reference to ${nodeNameForError(ref.node)}.`, }; } } /** * A `ReferenceEmitStrategy` which will refer to declarations by any local `ts.Identifier`s, if * such identifiers are available. */
{ "end_byte": 8233, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts_8234_15462
export class LocalIdentifierStrategy implements ReferenceEmitStrategy { emit(ref: Reference, context: ts.SourceFile, importFlags: ImportFlags): EmittedReference | null { const refSf = getSourceFile(ref.node); // If the emitter has specified ForceNewImport, then LocalIdentifierStrategy should not use a // local identifier at all, *except* in the source file where the node is actually declared. if (importFlags & ImportFlags.ForceNewImport && refSf !== context) { return null; } // If referenced node is not an actual TS declaration (e.g. `class Foo` or `function foo() {}`, // etc) and it is in the current file then just use it directly. // This is important because the reference could be a property access (e.g. `exports.foo`). In // such a case, the reference's `identities` property would be `[foo]`, which would result in an // invalid emission of a free-standing `foo` identifier, rather than `exports.foo`. if (!isDeclaration(ref.node) && refSf === context) { return { kind: ReferenceEmitKind.Success, expression: new WrappedNodeExpr(ref.node), importedFile: null, }; } // If the reference is to an ambient type, it can be referenced directly. if (ref.isAmbient && importFlags & ImportFlags.AllowAmbientReferences) { const identifier = identifierOfNode(ref.node); if (identifier !== null) { return { kind: ReferenceEmitKind.Success, expression: new WrappedNodeExpr(identifier), importedFile: null, }; } else { return null; } } // A Reference can have multiple identities in different files, so it may already have an // Identifier in the requested context file. const identifier = ref.getIdentityIn(context); if (identifier !== null) { return { kind: ReferenceEmitKind.Success, expression: new WrappedNodeExpr(identifier), importedFile: null, }; } else { return null; } } } /** * Represents the exported declarations from a module source file. */ interface ModuleExports { /** * The source file of the module. */ module: ts.SourceFile | null; /** * The map of declarations to their exported name. */ exportMap: Map<DeclarationNode, string> | null; } /** * A `ReferenceEmitStrategy` which will refer to declarations that come from `node_modules` using * an absolute import. * * Part of this strategy involves looking at the target entry point and identifying the exported * name of the targeted declaration, as it might be different from the declared name (e.g. a * directive might be declared as FooDirImpl, but exported as FooDir). If no export can be found * which maps back to the original directive, an error is thrown. */ export class AbsoluteModuleStrategy implements ReferenceEmitStrategy { /** * A cache of the exports of specific modules, because resolving a module to its exports is a * costly operation. */ private moduleExportsCache = new Map<string, ModuleExports>(); constructor( protected program: ts.Program, protected checker: ts.TypeChecker, protected moduleResolver: ModuleResolver, private reflectionHost: ReflectionHost, ) {} emit( ref: Reference, context: ts.SourceFile, importFlags: ImportFlags, ): ReferenceEmitResult | null { if (ref.bestGuessOwningModule === null) { // There is no module name available for this Reference, meaning it was arrived at via a // relative path. return null; } else if (!isDeclaration(ref.node)) { // It's not possible to import something which isn't a declaration. throw new Error( `Debug assert: unable to import a Reference to non-declaration of type ${ ts.SyntaxKind[ref.node.kind] }.`, ); } else if ((importFlags & ImportFlags.AllowTypeImports) === 0 && isTypeDeclaration(ref.node)) { throw new Error( `Importing a type-only declaration of type ${ ts.SyntaxKind[ref.node.kind] } in a value position is not allowed.`, ); } // Try to find the exported name of the declaration, if one is available. const {specifier, resolutionContext} = ref.bestGuessOwningModule; const exports = this.getExportsOfModule(specifier, resolutionContext); if (exports.module === null) { return { kind: ReferenceEmitKind.Failed, ref, context, reason: `The module '${specifier}' could not be found.`, }; } else if (exports.exportMap === null || !exports.exportMap.has(ref.node)) { return { kind: ReferenceEmitKind.Failed, ref, context, reason: `The symbol is not exported from ${exports.module.fileName} (module '${specifier}').`, }; } const symbolName = exports.exportMap.get(ref.node)!; return { kind: ReferenceEmitKind.Success, expression: new ExternalExpr(new ExternalReference(specifier, symbolName)), importedFile: exports.module, }; } private getExportsOfModule(moduleName: string, fromFile: string): ModuleExports { if (!this.moduleExportsCache.has(moduleName)) { this.moduleExportsCache.set(moduleName, this.enumerateExportsOfModule(moduleName, fromFile)); } return this.moduleExportsCache.get(moduleName)!; } protected enumerateExportsOfModule(specifier: string, fromFile: string): ModuleExports { // First, resolve the module specifier to its entry point, and get the ts.Symbol for it. const entryPointFile = this.moduleResolver.resolveModule(specifier, fromFile); if (entryPointFile === null) { return {module: null, exportMap: null}; } const exports = this.reflectionHost.getExportsOfModule(entryPointFile); if (exports === null) { return {module: entryPointFile, exportMap: null}; } const exportMap = new Map<DeclarationNode, string>(); for (const [name, declaration] of exports) { if (exportMap.has(declaration.node)) { // An export for this declaration has already been registered. We prefer an export that // has the same name as the declared name, i.e. is not an aliased export. This is relevant // for partial compilations where emitted references should import symbols using a stable // name. This is particularly relevant for declarations inside VE-generated libraries, as // such libraries contain private, unstable reexports of symbols. const existingExport = exportMap.get(declaration.node)!; if (isNamedDeclaration(declaration.node) && declaration.node.name.text === existingExport) { continue; } } exportMap.set(declaration.node, name); } return {module: entryPointFile, exportMap}; } } /** * A `ReferenceEmitStrategy` which will refer to declarations via relative paths, provided they're * both in the logical project "space" of paths. * * This is trickier than it sounds, as the two files may be in different root directories in the * project. Simply calculating a file system relative path between the two is not sufficient. * Instead, `LogicalProjectPath`s are used. */
{ "end_byte": 15462, "start_byte": 8234, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts_15463_20012
export class LogicalProjectStrategy implements ReferenceEmitStrategy { private relativePathStrategy: RelativePathStrategy; constructor( private reflector: ReflectionHost, private logicalFs: LogicalFileSystem, ) { this.relativePathStrategy = new RelativePathStrategy(this.reflector); } emit( ref: Reference, context: ts.SourceFile, importFlags: ImportFlags, ): ReferenceEmitResult | null { const destSf = getSourceFile(ref.node); // Compute the relative path from the importing file to the file being imported. This is done // as a logical path computation, because the two files might be in different rootDirs. const destPath = this.logicalFs.logicalPathOfSf(destSf); if (destPath === null) { // The imported file is not within the logical project filesystem. An import into a // declaration file is exempt from `TS6059: File is not under 'rootDir'` so we choose to allow // using a filesystem relative path as fallback, if allowed per the provided import flags. if (destSf.isDeclarationFile && importFlags & ImportFlags.AllowRelativeDtsImports) { return this.relativePathStrategy.emit(ref, context); } // Note: this error is analogous to `TS6059: File is not under 'rootDir'` that TypeScript // reports. return { kind: ReferenceEmitKind.Failed, ref, context, reason: `The file ${destSf.fileName} is outside of the configured 'rootDir'.`, }; } const originPath = this.logicalFs.logicalPathOfSf(context); if (originPath === null) { throw new Error( `Debug assert: attempt to import from ${context.fileName} but it's outside the program?`, ); } // There's no way to emit a relative reference from a file to itself. if (destPath === originPath) { return null; } const name = findExportedNameOfNode(ref.node, destSf, this.reflector); if (name === null) { // The target declaration isn't exported from the file it's declared in. This is an issue! return { kind: ReferenceEmitKind.Failed, ref, context, reason: `The symbol is not exported from ${destSf.fileName}.`, }; } // With both files expressed as LogicalProjectPaths, getting the module specifier as a relative // path is now straightforward. const moduleName = LogicalProjectPath.relativePathBetween(originPath, destPath); return { kind: ReferenceEmitKind.Success, expression: new ExternalExpr({moduleName, name}), importedFile: destSf, }; } } /** * A `ReferenceEmitStrategy` which constructs relatives paths between `ts.SourceFile`s. * * This strategy can be used if there is no `rootDir`/`rootDirs` structure for the project which * necessitates the stronger logic of `LogicalProjectStrategy`. */ export class RelativePathStrategy implements ReferenceEmitStrategy { constructor(private reflector: ReflectionHost) {} emit(ref: Reference, context: ts.SourceFile): ReferenceEmitResult | null { const destSf = getSourceFile(ref.node); const relativePath = relative( dirname(absoluteFromSourceFile(context)), absoluteFromSourceFile(destSf), ); const moduleName = toRelativeImport(stripExtension(relativePath)); const name = findExportedNameOfNode(ref.node, destSf, this.reflector); if (name === null) { return { kind: ReferenceEmitKind.Failed, ref, context, reason: `The symbol is not exported from ${destSf.fileName}.`, }; } return { kind: ReferenceEmitKind.Success, expression: new ExternalExpr({moduleName, name}), importedFile: destSf, }; } } /** * A `ReferenceEmitStrategy` which uses a `UnifiedModulesHost` to generate absolute import * references. */ export class UnifiedModulesStrategy implements ReferenceEmitStrategy { constructor( private reflector: ReflectionHost, private unifiedModulesHost: UnifiedModulesHost, ) {} emit(ref: Reference, context: ts.SourceFile): EmittedReference | null { const destSf = getSourceFile(ref.node); const name = findExportedNameOfNode(ref.node, destSf, this.reflector); if (name === null) { return null; } const moduleName = this.unifiedModulesHost.fileNameToModuleName( destSf.fileName, context.fileName, ); return { kind: ReferenceEmitKind.Success, expression: new ExternalExpr({moduleName, name}), importedFile: destSf, }; } }
{ "end_byte": 20012, "start_byte": 15463, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/emitter.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/find_export.ts_0_1163
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {ReflectionHost} from '../../reflection'; import {isNamedDeclaration} from '../../util/src/typescript'; /** * Find the name, if any, by which a node is exported from a given file. */ export function findExportedNameOfNode( target: ts.Node, file: ts.SourceFile, reflector: ReflectionHost, ): string | null { const exports = reflector.getExportsOfModule(file); if (exports === null) { return null; } const declaredName = isNamedDeclaration(target) ? target.name.text : null; // Look for the export which declares the node. let foundExportName: string | null = null; for (const [exportName, declaration] of exports) { if (declaration.node !== target) { continue; } if (exportName === declaredName) { // A non-alias export exists which is always preferred, so use that one. return exportName; } foundExportName = exportName; } return foundExportName; }
{ "end_byte": 1163, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/find_export.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/resolver.ts_0_1361
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {absoluteFrom} from '../../file_system'; import {getSourceFileOrNull, resolveModuleName} from '../../util/src/typescript'; /** * Used by `RouterEntryPointManager` and `NgModuleRouteAnalyzer` (which is in turn is used by * `NgModuleDecoratorHandler`) for resolving the module source-files references in lazy-loaded * routes (relative to the source-file containing the `NgModule` that provides the route * definitions). */ export class ModuleResolver { constructor( private program: ts.Program, private compilerOptions: ts.CompilerOptions, private host: ts.ModuleResolutionHost & Pick<ts.CompilerHost, 'resolveModuleNames'>, private moduleResolutionCache: ts.ModuleResolutionCache | null, ) {} resolveModule(moduleName: string, containingFile: string): ts.SourceFile | null { const resolved = resolveModuleName( moduleName, containingFile, this.compilerOptions, this.host, this.moduleResolutionCache, ); if (resolved === undefined) { return null; } return getSourceFileOrNull(this.program, absoluteFrom(resolved.resolvedFileName)); } }
{ "end_byte": 1361, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/resolver.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/default.ts_0_4645
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {WrappedNodeExpr} from '@angular/compiler'; import ts from 'typescript'; import {getSourceFile} from '../../util/src/typescript'; import {loadIsReferencedAliasDeclarationPatch} from './patch_alias_reference_resolution'; const DefaultImportDeclaration = Symbol('DefaultImportDeclaration'); interface WithDefaultImportDeclaration { [DefaultImportDeclaration]?: ts.ImportDeclaration; } /** * Attaches a default import declaration to `expr` to indicate the dependency of `expr` on the * default import. */ export function attachDefaultImportDeclaration( expr: WrappedNodeExpr<unknown>, importDecl: ts.ImportDeclaration, ): void { (expr as WithDefaultImportDeclaration)[DefaultImportDeclaration] = importDecl; } /** * Obtains the default import declaration that `expr` depends on, or `null` if there is no such * dependency. */ export function getDefaultImportDeclaration( expr: WrappedNodeExpr<unknown>, ): ts.ImportDeclaration | null { return (expr as WithDefaultImportDeclaration)[DefaultImportDeclaration] ?? null; } /** * TypeScript has trouble with generating default imports inside of transformers for some module * formats. The issue is that for the statement: * * import X from 'some/module'; * console.log(X); * * TypeScript will not use the "X" name in generated code. For normal user code, this is fine * because references to X will also be renamed. However, if both the import and any references are * added in a transformer, TypeScript does not associate the two, and will leave the "X" references * dangling while renaming the import variable. The generated code looks something like: * * const module_1 = require('some/module'); * console.log(X); // now X is a dangling reference. * * Therefore, we cannot synthetically add default imports, and must reuse the imports that users * include. Doing this poses a challenge for imports that are only consumed in the type position in * the user's code. If Angular reuses the imported symbol in a value position (for example, we * see a constructor parameter of type Foo and try to write "inject(Foo)") we will also end up with * a dangling reference, as TS will elide the import because it was only used in the type position * originally. * * To avoid this, the compiler must patch the emit resolver, and should only do this for imports * which are actually consumed. The `DefaultImportTracker` keeps track of these imports as they're * encountered and emitted, and implements a transform which can correctly flag the imports as * required. * * This problem does not exist for non-default imports as the compiler can easily insert * "import * as X" style imports for those, and the "X" identifier survives transformation. */ export class DefaultImportTracker { /** * A `Map` which tracks the `Set` of `ts.ImportClause`s for default imports that were used in * a given file name. */ private sourceFileToUsedImports = new Map<string, Set<ts.ImportClause>>(); recordUsedImport(importDecl: ts.ImportDeclaration): void { if (importDecl.importClause) { const sf = getSourceFile(importDecl); // Add the default import declaration to the set of used import declarations for the file. if (!this.sourceFileToUsedImports.has(sf.fileName)) { this.sourceFileToUsedImports.set(sf.fileName, new Set<ts.ImportClause>()); } this.sourceFileToUsedImports.get(sf.fileName)!.add(importDecl.importClause); } } /** * Get a `ts.TransformerFactory` which will preserve default imports that were previously marked * as used. * * This transformer must run after any other transformers which call `recordUsedImport`. */ importPreservingTransformer(): ts.TransformerFactory<ts.SourceFile> { return (context) => { let clausesToPreserve: Set<ts.Declaration> | null = null; return (sourceFile) => { const clausesForFile = this.sourceFileToUsedImports.get(sourceFile.fileName); if (clausesForFile !== undefined) { for (const clause of clausesForFile) { // Initialize the patch lazily so that apps that // don't use default imports aren't patched. if (clausesToPreserve === null) { clausesToPreserve = loadIsReferencedAliasDeclarationPatch(context); } clausesToPreserve.add(clause); } } return sourceFile; }; }; } }
{ "end_byte": 4645, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/default.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/local_compilation_extra_imports_tracker.ts_0_4699
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {getContainingImportDeclaration} from '../../reflection/src/typescript'; /** * A tool to track extra imports to be added to the generated files in the local compilation mode. * * This is needed for g3 bundling mechanism which requires dev files (= locally compiled) to have * imports resemble those generated for prod files (= full compilation mode). In full compilation * mode Angular compiler generates extra imports for statically analyzed component dependencies. We * need similar imports in local compilation as well. * * The tool offers API for adding local imports (to be added to a specific file) and global imports * (to be added to all the files in the local compilation). For more details on how these extra * imports are determined see this design doc: * https://docs.google.com/document/d/1dOWoSDvOY9ozlMmyCnxoFLEzGgHmTFVRAOVdVU-bxlI/edit?tab=t.0#heading=h.5n3k516r57g5 * * An instance of this class will be passed to each annotation handler so that they can register the * extra imports that they see fit. Later on, the instance is passed to the Ivy transformer ({@link * ivyTransformFactory}) and it is used to add the extra imports registered by the handlers to the * import manager ({@link ImportManager}) in order to have these imports generated. * * The extra imports are all side effect imports, and so they are identified by a single string * containing the module name. * */ export class LocalCompilationExtraImportsTracker { private readonly localImportsMap = new Map<string, Set<string>>(); private readonly globalImportsSet = new Set<string>(); /** Names of the files marked for extra import generation. */ private readonly markedFilesSet = new Set<string>(); constructor(private readonly typeChecker: ts.TypeChecker) {} /** * Marks the source file for extra imports generation. * * The extra imports are generated only for the files marked through this method. In other words, * the method {@link getImportsForFile} returns empty if the file is not marked. This allows the * consumers of this tool to avoid generating extra imports for unrelated files (e.g., non-Angular * files) */ markFileForExtraImportGeneration(sf: ts.SourceFile) { this.markedFilesSet.add(sf.fileName); } /** * Adds an extra import to be added to the generated file of a specific source file. */ addImportForFile(sf: ts.SourceFile, moduleName: string): void { if (!this.localImportsMap.has(sf.fileName)) { this.localImportsMap.set(sf.fileName, new Set<string>()); } this.localImportsMap.get(sf.fileName)!.add(moduleName); } /** * If the given node is an imported identifier, this method adds the module from which it is * imported as an extra import to the generated file of each source file in the compilation unit, * otherwise the method is noop. * * Adding an extra import to all files is not optimal though. There are rooms to optimize and a * add the import to a subset of files (e.g., exclude all the non Angular files as they don't need * any extra import). However for this first version of this feature we go by this mechanism for * simplicity. There will be on-going work to further optimize this method to add the extra import * to smallest possible candidate files instead of all files. */ addGlobalImportFromIdentifier(node: ts.Node): void { let identifier: ts.Identifier | null = null; if (ts.isIdentifier(node)) { identifier = node; } else if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) { identifier = node.expression; } if (identifier === null) { return; } const sym = this.typeChecker.getSymbolAtLocation(identifier); if (!sym?.declarations?.length) { return; } const importClause = sym.declarations[0]; const decl = getContainingImportDeclaration(importClause); if (decl !== null) { this.globalImportsSet.add(removeQuotations(decl.moduleSpecifier.getText())); } } /** * Returns the list of all module names that the given file should include as its extra imports. */ getImportsForFile(sf: ts.SourceFile): string[] { if (!this.markedFilesSet.has(sf.fileName)) { return []; } return [...this.globalImportsSet, ...(this.localImportsMap.get(sf.fileName) ?? [])]; } } function removeQuotations(s: string): string { return s.substring(1, s.length - 1).trim(); }
{ "end_byte": 4699, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/local_compilation_extra_imports_tracker.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/core.ts_0_3518
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {relativePathBetween} from '../../util/src/path'; /** * Rewrites imports of symbols being written into generated code. */ export interface ImportRewriter { /** * Optionally rewrite a reference to an imported symbol, changing either the binding prefix or the * symbol name itself. */ rewriteSymbol(symbol: string, specifier: string): string; /** * Optionally rewrite the given module specifier in the context of a given file. */ rewriteSpecifier(specifier: string, inContextOfFile: string): string; /** * Optionally rewrite the identifier of a namespace import. */ rewriteNamespaceImportIdentifier(specifier: string, moduleName: string): string; } /** * `ImportRewriter` that does no rewriting. */ export class NoopImportRewriter implements ImportRewriter { rewriteSymbol(symbol: string, specifier: string): string { return symbol; } rewriteSpecifier(specifier: string, inContextOfFile: string): string { return specifier; } rewriteNamespaceImportIdentifier(specifier: string): string { return specifier; } } /** * A mapping of supported symbols that can be imported from within @angular/core, and the names by * which they're exported from r3_symbols. */ const CORE_SUPPORTED_SYMBOLS = new Map<string, string>([ ['ɵɵdefineInjectable', 'ɵɵdefineInjectable'], ['ɵɵdefineInjector', 'ɵɵdefineInjector'], ['ɵɵdefineNgModule', 'ɵɵdefineNgModule'], ['ɵɵsetNgModuleScope', 'ɵɵsetNgModuleScope'], ['ɵɵinject', 'ɵɵinject'], ['ɵɵFactoryDeclaration', 'ɵɵFactoryDeclaration'], ['ɵsetClassMetadata', 'setClassMetadata'], ['ɵsetClassMetadataAsync', 'setClassMetadataAsync'], ['ɵɵInjectableDeclaration', 'ɵɵInjectableDeclaration'], ['ɵɵInjectorDeclaration', 'ɵɵInjectorDeclaration'], ['ɵɵNgModuleDeclaration', 'ɵɵNgModuleDeclaration'], ['ɵNgModuleFactory', 'NgModuleFactory'], ['ɵnoSideEffects', 'ɵnoSideEffects'], ]); const CORE_MODULE = '@angular/core'; /** * `ImportRewriter` that rewrites imports from '@angular/core' to be imported from the r3_symbols.ts * file instead. */ export class R3SymbolsImportRewriter implements ImportRewriter { constructor(private r3SymbolsPath: string) {} rewriteSymbol(symbol: string, specifier: string): string { if (specifier !== CORE_MODULE) { // This import isn't from core, so ignore it. return symbol; } return validateAndRewriteCoreSymbol(symbol); } rewriteSpecifier(specifier: string, inContextOfFile: string): string { if (specifier !== CORE_MODULE) { // This module isn't core, so ignore it. return specifier; } const relativePathToR3Symbols = relativePathBetween(inContextOfFile, this.r3SymbolsPath); if (relativePathToR3Symbols === null) { throw new Error( `Failed to rewrite import inside ${CORE_MODULE}: ${inContextOfFile} -> ${this.r3SymbolsPath}`, ); } return relativePathToR3Symbols; } rewriteNamespaceImportIdentifier(specifier: string): string { return specifier; } } export function validateAndRewriteCoreSymbol(name: string): string { if (!CORE_SUPPORTED_SYMBOLS.has(name)) { throw new Error(`Importing unexpected symbol ${name} while compiling ${CORE_MODULE}`); } return CORE_SUPPORTED_SYMBOLS.get(name)!; }
{ "end_byte": 3518, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/core.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/references.ts_0_6217
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {Expression} from '@angular/compiler'; import ts from 'typescript'; import {AmbientImport} from '../../reflection'; import {identifierOfNode} from '../../util/src/typescript'; export interface OwningModule { specifier: string; resolutionContext: string; } /** * A `ts.Node` plus the context in which it was discovered. * * A `Reference` is a pointer to a `ts.Node` that was extracted from the program somehow. It * contains not only the node itself, but the information regarding how the node was located. In * particular, it might track different identifiers by which the node is exposed, as well as * potentially a module specifier which might expose the node. * * The Angular compiler uses `Reference`s instead of `ts.Node`s when tracking classes or generating * imports. */ export class Reference<T extends ts.Node = ts.Node> { /** * The compiler's best guess at an absolute module specifier which owns this `Reference`. * * This is usually determined by tracking the import statements which led the compiler to a given * node. If any of these imports are absolute, it's an indication that the node being imported * might come from that module. * * It is not _guaranteed_ that the node in question is exported from its `bestGuessOwningModule` - * that is mostly a convention that applies in certain package formats. * * If `bestGuessOwningModule` is `null`, then it's likely the node came from the current program. */ readonly bestGuessOwningModule: OwningModule | null; private identifiers: ts.Identifier[] = []; /** * Indicates that the Reference was created synthetically, not as a result of natural value * resolution. * * This is used to avoid misinterpreting the Reference in certain contexts. */ synthetic = false; private _alias: Expression | null = null; readonly isAmbient: boolean; constructor( readonly node: T, bestGuessOwningModule: OwningModule | AmbientImport | null = null, ) { if (bestGuessOwningModule === AmbientImport) { this.isAmbient = true; this.bestGuessOwningModule = null; } else { this.isAmbient = false; this.bestGuessOwningModule = bestGuessOwningModule as OwningModule | null; } const id = identifierOfNode(node); if (id !== null) { this.identifiers.push(id); } } /** * The best guess at which module specifier owns this particular reference, or `null` if there * isn't one. */ get ownedByModuleGuess(): string | null { if (this.bestGuessOwningModule !== null) { return this.bestGuessOwningModule.specifier; } else { return null; } } /** * Whether this reference has a potential owning module or not. * * See `bestGuessOwningModule`. */ get hasOwningModuleGuess(): boolean { return this.bestGuessOwningModule !== null; } /** * A name for the node, if one is available. * * This is only suited for debugging. Any actual references to this node should be made with * `ts.Identifier`s (see `getIdentityIn`). */ get debugName(): string | null { const id = identifierOfNode(this.node); return id !== null ? id.text : null; } get alias(): Expression | null { return this._alias; } /** * Record a `ts.Identifier` by which it's valid to refer to this node, within the context of this * `Reference`. */ addIdentifier(identifier: ts.Identifier): void { this.identifiers.push(identifier); } /** * Get a `ts.Identifier` within this `Reference` that can be used to refer within the context of a * given `ts.SourceFile`, if any. */ getIdentityIn(context: ts.SourceFile): ts.Identifier | null { return this.identifiers.find((id) => id.getSourceFile() === context) || null; } /** * Get a `ts.Identifier` for this `Reference` that exists within the given expression. * * This is very useful for producing `ts.Diagnostic`s that reference `Reference`s that were * extracted from some larger expression, as it can be used to pinpoint the `ts.Identifier` within * the expression from which the `Reference` originated. */ getIdentityInExpression(expr: ts.Expression): ts.Identifier | null { const sf = expr.getSourceFile(); return ( this.identifiers.find((id) => { if (id.getSourceFile() !== sf) { return false; } // This identifier is a match if its position lies within the given expression. return id.pos >= expr.pos && id.end <= expr.end; }) || null ); } /** * Given the 'container' expression from which this `Reference` was extracted, produce a * `ts.Expression` to use in a diagnostic which best indicates the position within the container * expression that generated the `Reference`. * * For example, given a `Reference` to the class 'Bar' and the containing expression: * `[Foo, Bar, Baz]`, this function would attempt to return the `ts.Identifier` for `Bar` within * the array. This could be used to produce a nice diagnostic context: * * ```text * [Foo, Bar, Baz] * ~~~ * ``` * * If no specific node can be found, then the `fallback` expression is used, which defaults to the * entire containing expression. */ getOriginForDiagnostics( container: ts.Expression, fallback: ts.Expression = container, ): ts.Expression { const id = this.getIdentityInExpression(container); return id !== null ? id : fallback; } cloneWithAlias(alias: Expression): Reference<T> { const ref = new Reference( this.node, this.isAmbient ? AmbientImport : this.bestGuessOwningModule, ); ref.identifiers = [...this.identifiers]; ref._alias = alias; return ref; } cloneWithNoIdentifiers(): Reference<T> { const ref = new Reference( this.node, this.isAmbient ? AmbientImport : this.bestGuessOwningModule, ); ref._alias = this._alias; ref.identifiers = []; return ref; } }
{ "end_byte": 6217, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/references.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/alias.ts_0_6936
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {Expression, ExternalExpr} from '@angular/compiler'; import ts from 'typescript'; import {UnifiedModulesHost} from '../../core/api'; import {ClassDeclaration, ReflectionHost} from '../../reflection'; import {EmittedReference, ImportFlags, ReferenceEmitKind, ReferenceEmitStrategy} from './emitter'; import {Reference} from './references'; // Escape anything that isn't alphanumeric, '/' or '_'. const CHARS_TO_ESCAPE = /[^a-zA-Z0-9/_]/g; /** * A host for the aliasing system, which allows for alternative exports/imports of directives/pipes. * * Given an import of an NgModule (e.g. `CommonModule`), the compiler must generate imports to the * directives and pipes exported by this module (e.g. `NgIf`) when they're used in a particular * template. In its default configuration, if the compiler is not directly able to import the * component from another file within the same project, it will attempt to import the component * from the same (absolute) path by which the module was imported. So in the above example if * `CommonModule` was imported from '@angular/common', the compiler will attempt to import `NgIf` * from '@angular/common' as well. * * The aliasing system interacts with the above logic in two distinct ways. * * 1) It can be used to create "alias" re-exports from different files, which can be used when the * user hasn't exported the directive(s) from the ES module containing the NgModule. These re- * exports can also be helpful when using a `UnifiedModulesHost`, which overrides the import * logic described above. * * 2) It can be used to get an alternative import expression for a directive or pipe, instead of * the import that the normal logic would apply. The alias used depends on the provenance of the * `Reference` which was obtained for the directive/pipe, which is usually a property of how it * came to be in a template's scope (e.g. by which NgModule). * * See the README.md for more information on how aliasing works within the compiler. */ export interface AliasingHost { /** * Controls whether any alias re-exports are rendered into .d.ts files. * * This is not always necessary for aliasing to function correctly, so this flag allows an * `AliasingHost` to avoid cluttering the .d.ts files if exports are not strictly needed. */ readonly aliasExportsInDts: boolean; /** * Determine a name by which `decl` should be re-exported from `context`, depending on the * particular set of aliasing rules in place. * * `maybeAliasSymbolAs` can return `null`, in which case no alias export should be generated. * * @param ref a `Reference` to the directive/pipe to consider for aliasing. * @param context the `ts.SourceFile` in which the alias re-export might need to be generated. * @param ngModuleName the declared name of the `NgModule` within `context` for which the alias * would be generated. * @param isReExport whether the directive/pipe under consideration is re-exported from another * NgModule (as opposed to being declared by it directly). */ maybeAliasSymbolAs( ref: Reference<ClassDeclaration>, context: ts.SourceFile, ngModuleName: string, isReExport: boolean, ): string | null; /** * Determine an `Expression` by which `decl` should be imported from `via` using an alias export * (which should have been previously created when compiling `via`). * * `getAliasIn` can return `null`, in which case no alias is needed to import `decl` from `via` * (and the normal import rules should be used). * * @param decl the declaration of the directive/pipe which is being imported, and which might be * aliased. * @param via the `ts.SourceFile` which might contain an alias to the */ getAliasIn(decl: ClassDeclaration, via: ts.SourceFile, isReExport: boolean): Expression | null; } /** * An `AliasingHost` which generates and consumes alias re-exports when module names for each file * are determined by a `UnifiedModulesHost`. * * When using a `UnifiedModulesHost`, aliasing prevents issues with transitive dependencies. See the * README.md for more details. */ export class UnifiedModulesAliasingHost implements AliasingHost { constructor(private unifiedModulesHost: UnifiedModulesHost) {} /** * With a `UnifiedModulesHost`, aliases are chosen automatically without the need to look through * the exports present in a .d.ts file, so we can avoid cluttering the .d.ts files. */ readonly aliasExportsInDts = false; maybeAliasSymbolAs( ref: Reference<ClassDeclaration>, context: ts.SourceFile, ngModuleName: string, isReExport: boolean, ): string | null { if (!isReExport) { // Aliasing is used with a UnifiedModulesHost to prevent transitive dependencies. Thus, // aliases // only need to be created for directives/pipes which are not direct declarations of an // NgModule which exports them. return null; } return this.aliasName(ref.node, context); } /** * Generates an `Expression` to import `decl` from `via`, assuming an export was added when `via` * was compiled per `maybeAliasSymbolAs` above. */ getAliasIn(decl: ClassDeclaration, via: ts.SourceFile, isReExport: boolean): Expression | null { if (!isReExport) { // Directly exported directives/pipes don't require an alias, per the logic in // `maybeAliasSymbolAs`. return null; } // viaModule is the module it'll actually be imported from. const moduleName = this.unifiedModulesHost.fileNameToModuleName(via.fileName, via.fileName); return new ExternalExpr({moduleName, name: this.aliasName(decl, via)}); } /** * Generates an alias name based on the full module name of the file which declares the aliased * directive/pipe. */ private aliasName(decl: ClassDeclaration, context: ts.SourceFile): string { // The declared module is used to get the name of the alias. const declModule = this.unifiedModulesHost.fileNameToModuleName( decl.getSourceFile().fileName, context.fileName, ); const replaced = declModule.replace(CHARS_TO_ESCAPE, '_').replace(/\//g, '$'); return 'ɵng$' + replaced + '$$' + decl.name.text; } } /** * An `AliasingHost` which exports directives from any file containing an NgModule in which they're * declared/exported, under a private symbol name. * * These exports support cases where an NgModule is imported deeply from an absolute module path * (that is, it's not part of an Angular Package Format entrypoint), and the compiler needs to * import any matched directives/pipes from the same path (to the NgModule file). See README.md for * more details. */
{ "end_byte": 6936, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/alias.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/alias.ts_6937_9698
xport class PrivateExportAliasingHost implements AliasingHost { constructor(private host: ReflectionHost) {} /** * Under private export aliasing, the `AbsoluteModuleStrategy` used for emitting references will * will select aliased exports that it finds in the .d.ts file for an NgModule's file. Thus, * emitting these exports in .d.ts is a requirement for the `PrivateExportAliasingHost` to * function correctly. */ readonly aliasExportsInDts = true; maybeAliasSymbolAs( ref: Reference<ClassDeclaration>, context: ts.SourceFile, ngModuleName: string, ): string | null { if (ref.hasOwningModuleGuess) { // Skip nodes that already have an associated absolute module specifier, since they can be // safely imported from that specifier. return null; } // Look for a user-provided export of `decl` in `context`. If one exists, then an alias export // is not needed. // TODO(alxhub): maybe add a host method to check for the existence of an export without going // through the entire list of exports. const exports = this.host.getExportsOfModule(context); if (exports === null) { // Something went wrong, and no exports were available at all. Bail rather than risk creating // re-exports when they're not needed. throw new Error(`Could not determine the exports of: ${context.fileName}`); } let found: boolean = false; exports.forEach((value) => { if (value.node === ref.node) { found = true; } }); if (found) { // The module exports the declared class directly, no alias is necessary. return null; } return `ɵngExportɵ${ngModuleName}ɵ${ref.node.name.text}`; } /** * A `PrivateExportAliasingHost` only generates re-exports and does not direct the compiler to * directly consume the aliases it creates. * * Instead, they're consumed indirectly: `AbsoluteModuleStrategy` `ReferenceEmitterStrategy` will * select these alias exports automatically when looking for an export of the directive/pipe from * the same path as the NgModule was imported. * * Thus, `getAliasIn` always returns `null`. */ getAliasIn(): null { return null; } } /** * A `ReferenceEmitStrategy` which will consume the alias attached to a particular `Reference` to a * directive or pipe, if it exists. */ export class AliasStrategy implements ReferenceEmitStrategy { emit(ref: Reference, context: ts.SourceFile, importMode: ImportFlags): EmittedReference | null { if (importMode & ImportFlags.NoAliasing || ref.alias === null) { return null; } return { kind: ReferenceEmitKind.Success, expression: ref.alias, importedFile: 'unknown', }; } }
{ "end_byte": 9698, "start_byte": 6937, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/alias.ts" }
angular/packages/compiler-cli/src/ngtsc/imports/src/imported_symbols_tracker.ts_0_5286
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; /** * A map of imported symbols to local names under which the symbols are available within a file. */ type LocalNamesMap = Map<string, Set<string>>; /** Mapping between modules and the named imports consumed by them in a file. */ type NamedImportsMap = Map<string, LocalNamesMap>; /** * Tracks which symbols are imported in specific files and under what names. Allows for efficient * querying for references to those symbols without having to consult the type checker early in the * process. * * Note that the tracker doesn't account for variable shadowing so a final verification with the * type checker may be necessary, depending on the context. Also does not track dynamic imports. */ export class ImportedSymbolsTracker { private fileToNamedImports = new WeakMap<ts.SourceFile, NamedImportsMap>(); private fileToNamespaceImports = new WeakMap<ts.SourceFile, LocalNamesMap>(); /** * Checks if an identifier is a potential reference to a specific named import within the same * file. * @param node Identifier to be checked. * @param exportedName Name of the exported symbol that is being searched for. * @param moduleName Module from which the symbol should be imported. */ isPotentialReferenceToNamedImport( node: ts.Identifier, exportedName: string, moduleName: string, ): boolean { const sourceFile = node.getSourceFile(); this.scanImports(sourceFile); const fileImports = this.fileToNamedImports.get(sourceFile)!; const moduleImports = fileImports.get(moduleName); const symbolImports = moduleImports?.get(exportedName); return symbolImports !== undefined && symbolImports.has(node.text); } /** * Checks if an identifier is a potential reference to a specific namespace import within the same * file. * @param node Identifier to be checked. * @param moduleName Module from which the namespace is imported. */ isPotentialReferenceToNamespaceImport(node: ts.Identifier, moduleName: string): boolean { const sourceFile = node.getSourceFile(); this.scanImports(sourceFile); const namespaces = this.fileToNamespaceImports.get(sourceFile)!; return namespaces.get(moduleName)?.has(node.text) ?? false; } /** * Checks if a file has a named imported of a certain symbol. * @param sourceFile File to be checked. * @param exportedName Name of the exported symbol that is being checked. * @param moduleName Module that exports the symbol. */ hasNamedImport(sourceFile: ts.SourceFile, exportedName: string, moduleName: string): boolean { this.scanImports(sourceFile); const fileImports = this.fileToNamedImports.get(sourceFile)!; const moduleImports = fileImports.get(moduleName); return moduleImports !== undefined && moduleImports.has(exportedName); } /** * Checks if a file has namespace imports of a certain symbol. * @param sourceFile File to be checked. * @param moduleName Module whose namespace import is being searched for. */ hasNamespaceImport(sourceFile: ts.SourceFile, moduleName: string): boolean { this.scanImports(sourceFile); const namespaces = this.fileToNamespaceImports.get(sourceFile)!; return namespaces.has(moduleName); } /** Scans a `SourceFile` for import statements and caches them for later use. */ private scanImports(sourceFile: ts.SourceFile): void { if (this.fileToNamedImports.has(sourceFile) && this.fileToNamespaceImports.has(sourceFile)) { return; } const namedImports: NamedImportsMap = new Map(); const namespaceImports: LocalNamesMap = new Map(); this.fileToNamedImports.set(sourceFile, namedImports); this.fileToNamespaceImports.set(sourceFile, namespaceImports); // Only check top-level imports. for (const stmt of sourceFile.statements) { if ( !ts.isImportDeclaration(stmt) || !ts.isStringLiteralLike(stmt.moduleSpecifier) || stmt.importClause?.namedBindings === undefined ) { continue; } const moduleName = stmt.moduleSpecifier.text; if (ts.isNamespaceImport(stmt.importClause.namedBindings)) { // import * as foo from 'module' if (!namespaceImports.has(moduleName)) { namespaceImports.set(moduleName, new Set()); } namespaceImports.get(moduleName)!.add(stmt.importClause.namedBindings.name.text); } else { // import {foo, bar as alias} from 'module' for (const element of stmt.importClause.namedBindings.elements) { const localName = element.name.text; const exportedName = element.propertyName === undefined ? localName : element.propertyName.text; if (!namedImports.has(moduleName)) { namedImports.set(moduleName, new Map()); } const localNames = namedImports.get(moduleName)!; if (!localNames.has(exportedName)) { localNames.set(exportedName, new Set()); } localNames.get(exportedName)?.add(localName); } } } } }
{ "end_byte": 5286, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/imports/src/imported_symbols_tracker.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/BUILD.bazel_0_634
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) # Compiler code pertaining to extracting data for generating API reference documentation. ts_library( name = "docs", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), module_name = "@angular/compiler-cli/src/ngtsc/docs", deps = [ "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 634, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/docs/index.ts_0_292
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {DocEntry} from './src/entities'; export {DocsExtractor} from './src/extractor';
{ "end_byte": 292, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/index.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/function_extractor.ts_0_5005
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {EntryType, FunctionEntry, ParameterEntry} from './entities'; import {extractGenerics} from './generics_extractor'; import {extractJsDocDescription, extractJsDocTags, extractRawJsDoc} from './jsdoc_extractor'; import {extractResolvedTypeString} from './type_extractor'; export type FunctionLike = | ts.FunctionDeclaration | ts.MethodDeclaration | ts.MethodSignature | ts.CallSignatureDeclaration | ts.ConstructSignatureDeclaration; export class FunctionExtractor { constructor( private name: string, private exportDeclaration: FunctionLike, private typeChecker: ts.TypeChecker, ) {} extract(): FunctionEntry { // TODO: is there any real situation in which the signature would not be available here? // Is void a better type? const signature = this.typeChecker.getSignatureFromDeclaration(this.exportDeclaration); const returnType = signature ? this.typeChecker.typeToString( this.typeChecker.getReturnTypeOfSignature(signature), undefined, // This ensures that e.g. `T | undefined` is not reduced to `T`. ts.TypeFormatFlags.NoTypeReduction | ts.TypeFormatFlags.NoTruncation, ) : 'unknown'; const implementation = findImplementationOfFunction(this.exportDeclaration, this.typeChecker) ?? this.exportDeclaration; const type = this.typeChecker.getTypeAtLocation(this.exportDeclaration); const overloads = extractCallSignatures(this.name, this.typeChecker, type); const jsdocsTags = extractJsDocTags(implementation); const description = extractJsDocDescription(implementation); return { name: this.name, signatures: overloads, implementation: { params: extractAllParams(implementation.parameters, this.typeChecker), isNewType: ts.isConstructSignatureDeclaration(implementation), returnType, returnDescription: jsdocsTags.find((tag) => tag.name === 'returns')?.comment, generics: extractGenerics(implementation), name: this.name, description, entryType: EntryType.Function, jsdocTags: jsdocsTags, rawComment: extractRawJsDoc(implementation), }, entryType: EntryType.Function, description, jsdocTags: jsdocsTags, rawComment: extractRawJsDoc(implementation), }; } } /** Extracts parameters of the given parameter declaration AST nodes. */ export function extractAllParams( params: ts.NodeArray<ts.ParameterDeclaration>, typeChecker: ts.TypeChecker, ): ParameterEntry[] { return params.map((param) => ({ name: param.name.getText(), description: extractJsDocDescription(param), type: extractResolvedTypeString(param, typeChecker), isOptional: !!(param.questionToken || param.initializer), isRestParam: !!param.dotDotDotToken, })); } /** Filters the list signatures to valid function and initializer API signatures. */ function filterSignatureDeclarations(signatures: readonly ts.Signature[]) { const result: Array<{ signature: ts.Signature; decl: ts.FunctionDeclaration | ts.CallSignatureDeclaration | ts.MethodDeclaration; }> = []; for (const signature of signatures) { const decl = signature.getDeclaration(); if ( ts.isFunctionDeclaration(decl) || ts.isCallSignatureDeclaration(decl) || ts.isMethodDeclaration(decl) ) { result.push({signature, decl}); } } return result; } export function extractCallSignatures(name: string, typeChecker: ts.TypeChecker, type: ts.Type) { return filterSignatureDeclarations(type.getCallSignatures()).map(({decl, signature}) => ({ name, entryType: EntryType.Function, description: extractJsDocDescription(decl), generics: extractGenerics(decl), isNewType: false, jsdocTags: extractJsDocTags(decl), params: extractAllParams(decl.parameters, typeChecker), rawComment: extractRawJsDoc(decl), returnType: typeChecker.typeToString( typeChecker.getReturnTypeOfSignature(signature), undefined, // This ensures that e.g. `T | undefined` is not reduced to `T`. ts.TypeFormatFlags.NoTypeReduction | ts.TypeFormatFlags.NoTruncation, ), })); } /** Finds the implementation of the given function declaration overload signature. */ export function findImplementationOfFunction( node: FunctionLike, typeChecker: ts.TypeChecker, ): FunctionLike | undefined { if ((node as ts.FunctionDeclaration).body !== undefined || node.name === undefined) { return node; } const symbol = typeChecker.getSymbolAtLocation(node.name); const implementation = symbol?.declarations?.find( (s): s is ts.FunctionDeclaration => ts.isFunctionDeclaration(s) && s.body !== undefined, ); return implementation; }
{ "end_byte": 5005, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/function_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/enum_extractor.ts_0_2153
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { EntryType, EnumEntry, EnumMemberEntry, MemberType, } from '@angular/compiler-cli/src/ngtsc/docs/src/entities'; import { extractJsDocDescription, extractJsDocTags, extractRawJsDoc, } from '@angular/compiler-cli/src/ngtsc/docs/src/jsdoc_extractor'; import {extractResolvedTypeString} from '@angular/compiler-cli/src/ngtsc/docs/src/type_extractor'; import ts from 'typescript'; /** Extracts documentation entry for an enum. */ export function extractEnum( declaration: ts.EnumDeclaration, typeChecker: ts.TypeChecker, ): EnumEntry { return { name: declaration.name.getText(), entryType: EntryType.Enum, members: extractEnumMembers(declaration, typeChecker), rawComment: extractRawJsDoc(declaration), description: extractJsDocDescription(declaration), jsdocTags: extractJsDocTags(declaration), }; } /** Extracts doc info for an enum's members. */ function extractEnumMembers( declaration: ts.EnumDeclaration, checker: ts.TypeChecker, ): EnumMemberEntry[] { return declaration.members.map((member) => ({ name: member.name.getText(), type: extractResolvedTypeString(member, checker), value: getEnumMemberValue(member), memberType: MemberType.EnumItem, jsdocTags: extractJsDocTags(member), description: extractJsDocDescription(member), memberTags: [], })); } /** Gets the explicitly assigned value for an enum member, or an empty string if there is none. */ function getEnumMemberValue(memberNode: ts.EnumMember): string { // If the enum member has a child number literal or string literal, // we use that literal as the "value" of the member. const literal = memberNode.getChildren().find((n) => { return ( ts.isNumericLiteral(n) || ts.isStringLiteral(n) || (ts.isPrefixUnaryExpression(n) && n.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(n.operand)) ); }); return literal?.getText() ?? ''; }
{ "end_byte": 2153, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/enum_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/filters.ts_0_420
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** Gets whether a symbol's name indicates it is an Angular-private API. */ export function isAngularPrivateName(name: string) { const firstChar = name[0] ?? ''; return firstChar === 'ɵ' || firstChar === '_'; }
{ "end_byte": 420, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/filters.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/constant_extractor.ts_0_4346
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {ConstantEntry, EntryType, EnumEntry, EnumMemberEntry, MemberType} from './entities'; import {extractJsDocDescription, extractJsDocTags, extractRawJsDoc} from './jsdoc_extractor'; /** Name of the tag indicating that an object literal should be shown as an enum in docs. */ const LITERAL_AS_ENUM_TAG = 'object-literal-as-enum'; /** Extracts documentation entry for a constant. */ export function extractConstant( declaration: ts.VariableDeclaration, typeChecker: ts.TypeChecker, ): ConstantEntry | EnumEntry { // For constants specifically, we want to get the base type for any literal types. // For example, TypeScript by default extracts `const PI = 3.14` as PI having a type of the // literal `3.14`. We don't want this behavior for constants, since generally one wants the // _value_ of the constant to be able to change between releases without changing the type. // `VERSION` is a good example here; the version is always a `string`, but the actual value of // the version string shouldn't matter to the type system. const resolvedType = typeChecker.getBaseTypeOfLiteralType( typeChecker.getTypeAtLocation(declaration), ); // In the TS AST, the leading comment for a variable declaration is actually // on the ancestor `ts.VariableStatement` (since a single variable statement may // contain multiple variable declarations). const rawComment = extractRawJsDoc(declaration.parent.parent); const jsdocTags = extractJsDocTags(declaration); const description = extractJsDocDescription(declaration); const name = declaration.name.getText(); // Some constants have to be treated as enums for documentation purposes. if (jsdocTags.some((tag) => tag.name === LITERAL_AS_ENUM_TAG)) { return { name, entryType: EntryType.Enum, members: extractLiteralPropertiesAsEnumMembers(declaration), rawComment, description, jsdocTags: jsdocTags.filter((tag) => tag.name !== LITERAL_AS_ENUM_TAG), }; } return { name: name, type: typeChecker.typeToString(resolvedType), entryType: EntryType.Constant, rawComment, description, jsdocTags, }; } /** Gets whether a given constant is an Angular-added const that should be ignored for docs. */ export function isSyntheticAngularConstant(declaration: ts.VariableDeclaration) { return declaration.name.getText() === 'USED_FOR_NG_TYPE_CHECKING'; } /** * Extracts the properties of a variable initialized as an object literal as if they were enum * members. Will throw for any variables that can't be statically analyzed easily. */ function extractLiteralPropertiesAsEnumMembers( declaration: ts.VariableDeclaration, ): EnumMemberEntry[] { let initializer = declaration.initializer; // Unwrap `as` and parenthesized expressions. while ( initializer && (ts.isAsExpression(initializer) || ts.isParenthesizedExpression(initializer)) ) { initializer = initializer.expression; } if (initializer === undefined || !ts.isObjectLiteralExpression(initializer)) { throw new Error( `Declaration tagged with "${LITERAL_AS_ENUM_TAG}" must be initialized to an object literal, but received ${ initializer ? ts.SyntaxKind[initializer.kind] : 'undefined' }`, ); } return initializer.properties.map((prop) => { if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) { throw new Error( `Property in declaration tagged with "${LITERAL_AS_ENUM_TAG}" must be a property assignment with a static name`, ); } if (!ts.isNumericLiteral(prop.initializer) && !ts.isStringLiteralLike(prop.initializer)) { throw new Error( `Property in declaration tagged with "${LITERAL_AS_ENUM_TAG}" must be initialized to a number or string literal`, ); } return { name: prop.name.text, type: `${declaration.name.getText()}.${prop.name.text}`, value: prop.initializer.getText(), memberType: MemberType.EnumItem, jsdocTags: extractJsDocTags(prop), description: extractJsDocDescription(prop), memberTags: [], }; }); }
{ "end_byte": 4346, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/constant_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/initializer_api_function_extractor.ts_0_7119
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import { EntryType, FunctionDefinitionEntry, InitializerApiFunctionEntry, JsDocTagEntry, } from './entities'; import { extractAllParams, extractCallSignatures, findImplementationOfFunction, } from './function_extractor'; import {extractGenerics} from './generics_extractor'; import {extractJsDocDescription, extractJsDocTags, extractRawJsDoc} from './jsdoc_extractor'; /** JSDoc used to recognize an initializer API function. */ const initializerApiTag = 'initializerApiFunction'; /** * Checks whether the given node corresponds to an initializer API function. * * An initializer API function is a function declaration or variable declaration * that is explicitly annotated with `@initializerApiFunction`. * * Note: The node may be a function overload signature that is automatically * resolved to its implementation to detect the JSDoc tag. */ export function isInitializerApiFunction( node: ts.Node, typeChecker: ts.TypeChecker, ): node is ts.VariableDeclaration | ts.FunctionDeclaration { // If this is matching an overload signature, resolve to the implementation // as it would hold the `@initializerApiFunction` tag. if (ts.isFunctionDeclaration(node) && node.name !== undefined && node.body === undefined) { const implementation = findImplementationOfFunction(node, typeChecker); if (implementation !== undefined) { node = implementation; } } if (!ts.isFunctionDeclaration(node) && !ts.isVariableDeclaration(node)) { return false; } let tagContainer = ts.isFunctionDeclaration(node) ? node : getContainerVariableStatement(node); if (tagContainer === null) { return false; } const tags = ts.getJSDocTags(tagContainer); return tags.some((t) => t.tagName.text === initializerApiTag); } /** * Extracts the given node as initializer API function and returns * a docs entry that can be rendered to represent the API function. */ export function extractInitializerApiFunction( node: ts.VariableDeclaration | ts.FunctionDeclaration, typeChecker: ts.TypeChecker, ): InitializerApiFunctionEntry { if (node.name === undefined || !ts.isIdentifier(node.name)) { throw new Error(`Initializer API: Expected literal variable name.`); } const container = ts.isFunctionDeclaration(node) ? node : getContainerVariableStatement(node); if (container === null) { throw new Error('Initializer API: Could not find container AST node of variable.'); } const name = node.name.text; const type = typeChecker.getTypeAtLocation(node); // Top-level call signatures. E.g. `input()`, `input<ReadT>(initialValue: ReadT)`. etc. const callFunction: FunctionDefinitionEntry = extractFunctionWithOverloads( name, type, typeChecker, ); // Sub-functions like `input.required()`. const subFunctions: FunctionDefinitionEntry[] = []; for (const property of type.getProperties()) { const subName = property.getName(); const subDecl = property.getDeclarations()?.[0]; if (subDecl === undefined || !ts.isPropertySignature(subDecl)) { throw new Error( `Initializer API: Could not resolve declaration of sub-property: ${name}.${subName}`, ); } const subType = typeChecker.getTypeAtLocation(subDecl); subFunctions.push(extractFunctionWithOverloads(subName, subType, typeChecker)); } let jsdocTags: JsDocTagEntry[]; let description: string; let rawComment: string; // Extract container API documentation. // The container description describes the overall function, while // we allow the individual top-level call signatures to represent // their individual overloads. if (ts.isFunctionDeclaration(node)) { const implementation = findImplementationOfFunction(node, typeChecker); if (implementation === undefined) { throw new Error(`Initializer API: Could not find implementation of function: ${name}`); } callFunction.implementation = { name, entryType: EntryType.Function, isNewType: false, description: extractJsDocDescription(implementation), generics: extractGenerics(implementation), jsdocTags: extractJsDocTags(implementation), params: extractAllParams(implementation.parameters, typeChecker), rawComment: extractRawJsDoc(implementation), returnType: typeChecker.typeToString( typeChecker.getReturnTypeOfSignature( typeChecker.getSignatureFromDeclaration(implementation)!, ), ), }; jsdocTags = callFunction.implementation.jsdocTags; description = callFunction.implementation.description; rawComment = callFunction.implementation.description; } else { jsdocTags = extractJsDocTags(container); description = extractJsDocDescription(container); rawComment = extractRawJsDoc(container); } // Extract additional docs metadata from the initializer API JSDoc tag. const metadataTag = jsdocTags.find((t) => t.name === initializerApiTag); if (metadataTag === undefined) { throw new Error( 'Initializer API: Detected initializer API function does ' + `not have "@initializerApiFunction" tag: ${name}`, ); } let parsedMetadata: InitializerApiFunctionEntry['__docsMetadata__'] = undefined; if (metadataTag.comment.trim() !== '') { try { parsedMetadata = JSON.parse(metadataTag.comment) as typeof parsedMetadata; } catch (e: unknown) { throw new Error(`Could not parse initializer API function metadata: ${e}`); } } return { entryType: EntryType.InitializerApiFunction, name, description, jsdocTags, rawComment, callFunction, subFunctions, __docsMetadata__: parsedMetadata, }; } /** * Gets the container node of the given variable declaration. * * A variable declaration may be annotated with e.g. `@initializerApiFunction`, * but the JSDoc tag is not attached to the node, but to the containing variable * statement. */ function getContainerVariableStatement(node: ts.VariableDeclaration): ts.VariableStatement | null { if (!ts.isVariableDeclarationList(node.parent)) { return null; } if (!ts.isVariableStatement(node.parent.parent)) { return null; } return node.parent.parent; } /** * Extracts all given signatures and returns them as a function with * overloads. * * The implementation of the function may be attached later, or may * be non-existent. E.g. initializer APIs declared using an interface * with call signatures do not have an associated implementation function * that is statically retrievable. The constant holds the overall API description. */ function extractFunctionWithOverloads( name: string, type: ts.Type, typeChecker: ts.TypeChecker, ): FunctionDefinitionEntry { return { name, signatures: extractCallSignatures(name, typeChecker, type), // Implementation may be populated later. implementation: null, }; }
{ "end_byte": 7119, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/initializer_api_function_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/entities.ts_0_5854
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** The JSON data file format for extracted API reference info. */ export interface EntryCollection { moduleName: string; // The normalized name is shared so rendering and manifest use the same common field normalizedModuleName: string; moduleLabel: string; entries: DocEntry[]; } /** Type of top-level documentation entry. */ export enum EntryType { Block = 'block', Component = 'component', Constant = 'constant', Decorator = 'decorator', Directive = 'directive', Element = 'element', Enum = 'enum', Function = 'function', Interface = 'interface', NgModule = 'ng_module', Pipe = 'pipe', TypeAlias = 'type_alias', UndecoratedClass = 'undecorated_class', InitializerApiFunction = 'initializer_api_function', } /** Types of class members */ export enum MemberType { Property = 'property', Method = 'method', Getter = 'getter', Setter = 'setter', EnumItem = 'enum_item', } export enum DecoratorType { Class = 'class', Member = 'member', Parameter = 'parameter', } /** Informational tags applicable to class members. */ export enum MemberTags { Abstract = 'abstract', Static = 'static', Readonly = 'readonly', Protected = 'protected', Optional = 'optional', Input = 'input', Output = 'output', Inherited = 'override', } /** Documentation entity for single JsDoc tag. */ export interface JsDocTagEntry { name: string; comment: string; } /** Documentation entity for single generic parameter. */ export interface GenericEntry { name: string; constraint: string | undefined; default: string | undefined; } export interface SourceEntry { filePath: string; startLine: number; endLine: number; } export interface DocEntryWithSourceInfo extends DocEntry { source: SourceEntry; } /** Base type for all documentation entities. */ export interface DocEntry { entryType: EntryType; name: string; description: string; rawComment: string; jsdocTags: JsDocTagEntry[]; } /** Documentation entity for a constant. */ export interface ConstantEntry extends DocEntry { type: string; } /** Documentation entity for a type alias. */ export type TypeAliasEntry = ConstantEntry; /** Documentation entity for a TypeScript class. */ export interface ClassEntry extends DocEntry { isAbstract: boolean; members: MemberEntry[]; generics: GenericEntry[]; extends?: string; implements: string[]; } // From an API doc perspective, class and interfaces are identical. /** Documentation entity for a TypeScript interface. */ export type InterfaceEntry = ClassEntry; /** Documentation entity for a TypeScript enum. */ export interface EnumEntry extends DocEntry { members: EnumMemberEntry[]; } /** Documentation entity for an Angular decorator. */ export interface DecoratorEntry extends DocEntry { decoratorType: DecoratorType; members: PropertyEntry[]; } /** Documentation entity for an Angular directives and components. */ export interface DirectiveEntry extends ClassEntry { selector: string; exportAs: string[]; isStandalone: boolean; } export interface PipeEntry extends ClassEntry { pipeName: string; isStandalone: boolean; // TODO: add `isPure`. } export interface FunctionSignatureMetadata extends DocEntry { params: ParameterEntry[]; returnType: string; returnDescription?: string; generics: GenericEntry[]; isNewType: boolean; } /** Sub-entry for a single class or enum member. */ export interface MemberEntry { name: string; memberType: MemberType; memberTags: MemberTags[]; description: string; jsdocTags: JsDocTagEntry[]; } /** Sub-entry for an enum member. */ export interface EnumMemberEntry extends MemberEntry { type: string; value: string; } /** Sub-entry for a class property. */ export interface PropertyEntry extends MemberEntry { type: string; inputAlias?: string; outputAlias?: string; isRequiredInput?: boolean; } /** Sub-entry for a class method. */ export type MethodEntry = MemberEntry & FunctionEntry; /** Sub-entry for a single function parameter. */ export interface ParameterEntry { name: string; description: string; type: string; isOptional: boolean; isRestParam: boolean; } export type FunctionEntry = FunctionDefinitionEntry & DocEntry & { implementation: FunctionSignatureMetadata; }; /** Interface describing a function with overload signatures. */ export interface FunctionDefinitionEntry { name: string; signatures: FunctionSignatureMetadata[]; implementation: FunctionSignatureMetadata | null; } /** * Docs entry describing an initializer API function. * * An initializer API function is a function that is invoked as * initializer of class members. The function may hold additional * sub functions, like `.required`. * * Known popular initializer APIs are `input()`, `output()`, `model()`. * * Initializer APIs are often constructed typed in complex ways so this * entry type allows for readable "parsing" and interpretation of such * constructs. Initializer APIs are explicitly denoted via a JSDoc tag. */ export interface InitializerApiFunctionEntry extends DocEntry { callFunction: FunctionDefinitionEntry; subFunctions: FunctionDefinitionEntry[]; __docsMetadata__?: { /** * Whether types should be shown in the signature * preview of docs. * * By default, for readability purposes, types are omitted, but * shorter initializer API functions like `output` may decide to * render these types. */ showTypesInSignaturePreview?: boolean; }; } export function isDocEntryWithSourceInfo(entry: DocEntry): entry is DocEntryWithSourceInfo { return 'source' in entry; }
{ "end_byte": 5854, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/entities.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/generics_extractor.ts_0_772
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {GenericEntry} from './entities'; type DeclarationWithTypeParams = { typeParameters?: ts.NodeArray<ts.TypeParameterDeclaration> | undefined; }; /** Gets a list of all the generic type parameters for a declaration. */ export function extractGenerics(declaration: DeclarationWithTypeParams): GenericEntry[] { return ( declaration.typeParameters?.map((typeParam) => ({ name: typeParam.name.getText(), constraint: typeParam.constraint?.getText(), default: typeParam.default?.getText(), })) ?? [] ); }
{ "end_byte": 772, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/generics_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/import_extractor.ts_0_1364
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; /** * For a given SourceFile, it extracts all imported symbols from other Angular packages. * * @returns a map Symbol => Package, eg: ApplicationRef => @angular/core */ export function getImportedSymbols(sourceFile: ts.SourceFile): Map<string, string> { const importSpecifiers = new Map<string, string>(); function visit(node: ts.Node) { if (ts.isImportDeclaration(node)) { let moduleSpecifier = node.moduleSpecifier.getText(sourceFile).replace(/['"]/g, ''); if (moduleSpecifier.startsWith('@angular/')) { const namedBindings = node.importClause?.namedBindings; if (namedBindings && ts.isNamedImports(namedBindings)) { namedBindings.elements.forEach((importSpecifier) => { const importName = importSpecifier.name.text; const importAlias = importSpecifier.propertyName ? importSpecifier.propertyName.text : undefined; importSpecifiers.set(importAlias ?? importName, moduleSpecifier); }); } } } ts.forEachChild(node, visit); } visit(sourceFile); return importSpecifiers; }
{ "end_byte": 1364, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/import_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/jsdoc_extractor.ts_0_3420
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {JsDocTagEntry} from './entities'; /** * RegExp to match the `@` character follow by any Angular decorator, used to escape Angular * decorators in JsDoc blocks so that they're not parsed as JsDoc tags. */ const decoratorExpression = /@(?=(Injectable|Component|Directive|Pipe|NgModule|Input|Output|HostBinding|HostListener|Inject|Optional|Self|Host|SkipSelf|ViewChild|ViewChildren|ContentChild|ContentChildren))/g; /** Gets the set of JsDoc tags applied to a node. */ export function extractJsDocTags(node: ts.HasJSDoc): JsDocTagEntry[] { const escapedNode = getEscapedNode(node); return ts.getJSDocTags(escapedNode).map((t) => { return { name: t.tagName.getText(), comment: unescapeAngularDecorators(ts.getTextOfJSDocComment(t.comment) ?? ''), }; }); } /** * Gets the JsDoc description for a node. If the node does not have * a description, returns the empty string. */ export function extractJsDocDescription(node: ts.HasJSDoc): string { const escapedNode = getEscapedNode(node); // If the node is a top-level statement (const, class, function, etc.), we will get // a `ts.JSDoc` here. If the node is a `ts.ParameterDeclaration`, we will get // a `ts.JSDocParameterTag`. const commentOrTag = ts.getJSDocCommentsAndTags(escapedNode).find((d) => { return ts.isJSDoc(d) || ts.isJSDocParameterTag(d); }); const comment = commentOrTag?.comment ?? ''; const description = typeof comment === 'string' ? comment : (ts.getTextOfJSDocComment(comment) ?? ''); return unescapeAngularDecorators(description); } /** * Gets the raw JsDoc applied to a node. * If the node does not have a JsDoc block, returns the empty string. */ export function extractRawJsDoc(node: ts.HasJSDoc): string { // Assume that any node has at most one JsDoc block. const comment = ts.getJSDocCommentsAndTags(node).find(ts.isJSDoc)?.getFullText() ?? ''; return unescapeAngularDecorators(comment); } /** * Gets an "escaped" version of the node by copying its raw JsDoc into a new source file * on top of a dummy class declaration. For the purposes of JsDoc extraction, we don't actually * care about the node itself, only its JsDoc block. */ function getEscapedNode(node: ts.HasJSDoc): ts.HasJSDoc { // TODO(jelbourn): It's unclear whether we need to escape @param JsDoc, since they're unlikely // to have an Angular decorator on the beginning of a line. If we do need to escape them, // it will require some more complicated copying below. if (ts.isParameter(node)) { return node; } const rawComment = extractRawJsDoc(node); const escaped = escapeAngularDecorators(rawComment); const file = ts.createSourceFile('x.ts', `${escaped}class X {}`, ts.ScriptTarget.ES2020, true); return file.statements.find((s) => ts.isClassDeclaration(s)) as ts.ClassDeclaration; } /** Escape the `@` character for Angular decorators. */ function escapeAngularDecorators(comment: string): string { return comment.replace(decoratorExpression, '_NG_AT_'); } /** Unescapes the `@` character for Angular decorators. */ function unescapeAngularDecorators(comment: string): string { return comment.replace(/_NG_AT_/g, '@'); }
{ "end_byte": 3420, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/jsdoc_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/type_extractor.ts_0_457
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; /** Gets the string representation of a node's resolved type. */ export function extractResolvedTypeString(node: ts.Node, checker: ts.TypeChecker): string { return checker.typeToString(checker.getTypeAtLocation(node)); }
{ "end_byte": 457, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/type_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/type_alias_extractor.ts_0_981
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {EntryType} from './entities'; import {extractJsDocDescription, extractJsDocTags, extractRawJsDoc} from './jsdoc_extractor'; /** Extract the documentation entry for a type alias. */ export function extractTypeAlias(declaration: ts.TypeAliasDeclaration) { // TODO: this does not yet resolve type queries (`typeof`). We may want to // fix this eventually, but for now it does not appear that any type aliases in // Angular's public API rely on this. return { name: declaration.name.getText(), type: declaration.type.getText(), entryType: EntryType.TypeAlias, rawComment: extractRawJsDoc(declaration), description: extractJsDocDescription(declaration), jsdocTags: extractJsDocTags(declaration), }; }
{ "end_byte": 981, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/type_alias_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/extractor.ts_0_8060
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {MetadataReader} from '../../metadata'; import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {extractClass, extractInterface} from './class_extractor'; import {extractConstant, isSyntheticAngularConstant} from './constant_extractor'; import { extractorDecorator, isDecoratorDeclaration, isDecoratorOptionsInterface, } from './decorator_extractor'; import {DocEntry, DocEntryWithSourceInfo} from './entities'; import {extractEnum} from './enum_extractor'; import {isAngularPrivateName} from './filters'; import {FunctionExtractor} from './function_extractor'; import { extractInitializerApiFunction, isInitializerApiFunction, } from './initializer_api_function_extractor'; import {extractTypeAlias} from './type_alias_extractor'; import {getImportedSymbols} from './import_extractor'; type DeclarationWithExportName = readonly [string, ts.Declaration]; /** * Extracts all information from a source file that may be relevant for generating * public API documentation. */ export class DocsExtractor { constructor( private typeChecker: ts.TypeChecker, private metadataReader: MetadataReader, ) {} /** * Gets the set of all documentable entries from a source file, including * declarations that are re-exported from this file as an entry-point. * * @param sourceFile The file from which to extract documentable entries. */ extractAll( sourceFile: ts.SourceFile, rootDir: string, privateModules: Set<string>, ): {entries: DocEntry[]; symbols: Map<string, string>} { const entries: DocEntry[] = []; const symbols = new Map<string, string>(); const exportedDeclarations = this.getExportedDeclarations(sourceFile); for (const [exportName, node] of exportedDeclarations) { // Skip any symbols with an Angular-internal name. if (isAngularPrivateName(exportName)) { continue; } const entry = this.extractDeclaration(node); if (entry && !isIgnoredDocEntry(entry)) { // The source file parameter is the package entry: the index.ts // We want the real source file of the declaration. const realSourceFile = node.getSourceFile(); /** * The `sourceFile` from `extractAll` is the main entry-point file of a package. * Usually following a format like `export * from './public_api';`, simply re-exporting. * It is necessary to pick-up every import from the actual source files * where declarations are living, so that we can determine what symbols * are actually referenced in the context of that particular declaration * By doing this, the generation remains independent from other packages */ const importedSymbols = getImportedSymbols(realSourceFile); importedSymbols.forEach((moduleName, symbolName) => { if (symbolName.startsWith('ɵ') || privateModules.has(moduleName)) { return; } if (symbols.has(symbolName) && symbols.get(symbolName) !== moduleName) { // If this ever throws, we need to improve the symbol extraction strategy throw new Error( `Ambigous symbol \`${symbolName}\` exported by both ${symbols.get( symbolName, )} & ${moduleName}`, ); } symbols.set(symbolName, moduleName); }); // Set the source code references for the extracted entry. (entry as DocEntryWithSourceInfo).source = { filePath: getRelativeFilePath(realSourceFile, rootDir), // Start & End are off by 1 startLine: ts.getLineAndCharacterOfPosition(realSourceFile, node.getStart()).line + 1, endLine: ts.getLineAndCharacterOfPosition(realSourceFile, node.getEnd()).line + 1, }; // The exported name of an API may be different from its declaration name, so // use the declaration name. entries.push({...entry, name: exportName}); } } return {entries, symbols}; } /** Extract the doc entry for a single declaration. */ private extractDeclaration(node: ts.Declaration): DocEntry | null { // Ignore anonymous classes. if (isNamedClassDeclaration(node)) { return extractClass(node, this.metadataReader, this.typeChecker); } if (isInitializerApiFunction(node, this.typeChecker)) { return extractInitializerApiFunction(node, this.typeChecker); } if (ts.isInterfaceDeclaration(node) && !isIgnoredInterface(node)) { return extractInterface(node, this.typeChecker); } if (ts.isFunctionDeclaration(node)) { // Name is guaranteed to be set, because it's exported directly. const functionExtractor = new FunctionExtractor(node.name!.getText(), node, this.typeChecker); return functionExtractor.extract(); } if (ts.isVariableDeclaration(node) && !isSyntheticAngularConstant(node)) { return isDecoratorDeclaration(node) ? extractorDecorator(node, this.typeChecker) : extractConstant(node, this.typeChecker); } if (ts.isTypeAliasDeclaration(node)) { return extractTypeAlias(node); } if (ts.isEnumDeclaration(node)) { return extractEnum(node, this.typeChecker); } return null; } /** Gets the list of exported declarations for doc extraction. */ private getExportedDeclarations(sourceFile: ts.SourceFile): DeclarationWithExportName[] { // Use the reflection host to get all the exported declarations from this // source file entry point. const reflector = new TypeScriptReflectionHost(this.typeChecker); const exportedDeclarationMap = reflector.getExportsOfModule(sourceFile); // Augment each declaration with the exported name in the public API. let exportedDeclarations = Array.from(exportedDeclarationMap?.entries() ?? []).map( ([exportName, declaration]) => [exportName, declaration.node] as const, ); // Sort the declaration nodes into declaration position because their order is lost in // reading from the export map. This is primarily useful for testing and debugging. return exportedDeclarations.sort( ([a, declarationA], [b, declarationB]) => declarationA.pos - declarationB.pos, ); } } /** Gets whether an interface should be ignored for docs extraction. */ function isIgnoredInterface(node: ts.InterfaceDeclaration) { // We filter out all interfaces that end with "Decorator" because we capture their // types as part of the main decorator entry (which are declared as constants). // This approach to dealing with decorators is admittedly fuzzy, but this aspect of // the framework's source code is unlikely to change. We also filter out the interfaces // that contain the decorator options. return node.name.getText().endsWith('Decorator') || isDecoratorOptionsInterface(node); } /** * Whether the doc entry should be ignored. * * Note: We cannot check whether a node is marked as docs private * before extraction because the extractor may find the attached * JSDoc tags on different AST nodes. For example, a variable declaration * never has JSDoc tags attached, but rather the parent variable statement. */ function isIgnoredDocEntry(entry: DocEntry): boolean { const isDocsPrivate = entry.jsdocTags.find((e) => e.name === 'docsPrivate'); if (isDocsPrivate !== undefined && isDocsPrivate.comment === '') { throw new Error( `Docs extraction: Entry "${entry.name}" is marked as ` + `"@docsPrivate" but without reasoning.`, ); } return isDocsPrivate !== undefined; } function getRelativeFilePath(sourceFile: ts.SourceFile, rootDir: string): string { const fullPath = sourceFile.fileName; const relativePath = fullPath.replace(rootDir, ''); return relativePath; }
{ "end_byte": 8060, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/decorator_extractor.ts_0_5829
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {extractInterface} from './class_extractor'; import {DecoratorEntry, DecoratorType, EntryType, PropertyEntry} from './entities'; import {extractJsDocDescription, extractJsDocTags, extractRawJsDoc} from './jsdoc_extractor'; /** Extracts an API documentation entry for an Angular decorator. */ export function extractorDecorator( declaration: ts.VariableDeclaration, typeChecker: ts.TypeChecker, ): DecoratorEntry { const documentedNode = getDecoratorJsDocNode(declaration); const decoratorType = getDecoratorType(declaration); if (!decoratorType) { throw new Error(`"${declaration.name.getText()} is not a decorator."`); } return { name: declaration.name.getText(), decoratorType: decoratorType, entryType: EntryType.Decorator, rawComment: extractRawJsDoc(documentedNode), description: extractJsDocDescription(documentedNode), jsdocTags: extractJsDocTags(documentedNode), members: getDecoratorOptions(declaration, typeChecker), }; } /** Gets whether the given variable declaration is an Angular decorator declaration. */ export function isDecoratorDeclaration(declaration: ts.VariableDeclaration): boolean { return !!getDecoratorType(declaration); } /** Gets whether an interface is the options interface for a decorator in the same file. */ export function isDecoratorOptionsInterface(declaration: ts.InterfaceDeclaration): boolean { return declaration .getSourceFile() .statements.some( (s) => ts.isVariableStatement(s) && s.declarationList.declarations.some( (d) => isDecoratorDeclaration(d) && d.name.getText() === declaration.name.getText(), ), ); } /** Gets the type of decorator, or undefined if the declaration is not a decorator. */ function getDecoratorType(declaration: ts.VariableDeclaration): DecoratorType | undefined { // All Angular decorators are initialized with one of `makeDecorator`, `makePropDecorator`, // or `makeParamDecorator`. const initializer = declaration.initializer?.getFullText() ?? ''; if (initializer.includes('makeDecorator')) return DecoratorType.Class; if (initializer.includes('makePropDecorator')) return DecoratorType.Member; if (initializer.includes('makeParamDecorator')) return DecoratorType.Parameter; return undefined; } /** Gets the doc entry for the options object for an Angular decorator */ function getDecoratorOptions( declaration: ts.VariableDeclaration, typeChecker: ts.TypeChecker, ): PropertyEntry[] { const name = declaration.name.getText(); // Every decorator has an interface with its options in the same SourceFile. // Queries, however, are defined as a type alias pointing to an interface. const optionsDeclaration = declaration.getSourceFile().statements.find((node) => { return ( (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) && node.name.getText() === name ); }); if (!optionsDeclaration) { throw new Error(`Decorator "${name}" has no corresponding options interface.`); } let optionsInterface: ts.InterfaceDeclaration; if (ts.isTypeAliasDeclaration(optionsDeclaration)) { // We hard-code the assumption that if the decorator's option type is a type alias, // it resolves to a single interface (this is true for all query decorators at time of // this writing). const aliasedType = typeChecker.getTypeAtLocation(optionsDeclaration.type); optionsInterface = (aliasedType.getSymbol()?.getDeclarations() ?? []).find((d) => ts.isInterfaceDeclaration(d), ) as ts.InterfaceDeclaration; } else { optionsInterface = optionsDeclaration as ts.InterfaceDeclaration; } if (!optionsInterface || !ts.isInterfaceDeclaration(optionsInterface)) { throw new Error(`Options for decorator "${name}" is not an interface.`); } // Take advantage of the interface extractor to pull the appropriate member info. // Hard code the knowledge that decorator options only have properties, never methods. return extractInterface(optionsInterface, typeChecker).members as PropertyEntry[]; } /** * Gets the call signature node that has the decorator's public JsDoc block. * * Every decorator has three parts: * - A const that has the actual decorator. * - An interface with the same name as the const that documents the decorator's options. * - An interface suffixed with "Decorator" that has the decorator's call signature and JsDoc block. * * For the description and JsDoc tags, we need the interface suffixed with "Decorator". */ function getDecoratorJsDocNode(declaration: ts.VariableDeclaration): ts.HasJSDoc { const name = declaration.name.getText(); // Assume the existence of an interface in the same file with the same name // suffixed with "Decorator". const decoratorInterface = declaration.getSourceFile().statements.find((s) => { return ts.isInterfaceDeclaration(s) && s.name.getText() === `${name}Decorator`; }); if (!decoratorInterface || !ts.isInterfaceDeclaration(decoratorInterface)) { throw new Error(`No interface "${name}Decorator" found.`); } // The public-facing JsDoc for each decorator is on one of its interface's call signatures. const callSignature = decoratorInterface.members.find((node) => { // The description block lives on one of the call signatures for this interface. return ts.isCallSignatureDeclaration(node) && extractRawJsDoc(node); }); if (!callSignature || !ts.isCallSignatureDeclaration(callSignature)) { throw new Error(`No call signature with JsDoc on "${name}Decorator"`); } return callSignature; }
{ "end_byte": 5829, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/decorator_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.ts_0_2204
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {Reference} from '../../imports'; import { DirectiveMeta, InputMapping, InputOrOutput, MetadataReader, NgModuleMeta, PipeMeta, } from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import { ClassEntry, DirectiveEntry, EntryType, InterfaceEntry, MemberEntry, MemberTags, MemberType, MethodEntry, PipeEntry, PropertyEntry, } from './entities'; import {isAngularPrivateName} from './filters'; import {FunctionExtractor} from './function_extractor'; import {extractGenerics} from './generics_extractor'; import {isInternal} from './internal'; import {extractJsDocDescription, extractJsDocTags, extractRawJsDoc} from './jsdoc_extractor'; import {extractResolvedTypeString} from './type_extractor'; // For the purpose of extraction, we can largely treat properties and accessors the same. /** A class member declaration that is *like* a property (including accessors) */ type PropertyDeclarationLike = ts.PropertyDeclaration | ts.AccessorDeclaration; // For the purposes of extraction, we can treat interfaces as identical to classes // with a couple of shorthand types to normalize over the differences between them. /** Type representing either a class declaration ro an interface declaration. */ type ClassDeclarationLike = ts.ClassDeclaration | ts.InterfaceDeclaration; /** Type representing either a class or interface member. */ type MemberElement = ts.ClassElement | ts.TypeElement; /** Type representing a signature element of an interface. */ type SignatureElement = ts.CallSignatureDeclaration | ts.ConstructSignatureDeclaration; /** * Type representing either: */ type MethodLike = ts.MethodDeclaration | ts.MethodSignature; /** * Type representing either a class property declaration or an interface property signature. */ type PropertyLike = PropertyDeclarationLike | ts.PropertySignature; /** Extractor to pull info for API reference documentation for a TypeScript class or interface. */
{ "end_byte": 2204, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.ts_2205_11747
class ClassExtractor { constructor( protected declaration: ClassDeclaration & ClassDeclarationLike, protected typeChecker: ts.TypeChecker, ) {} /** Extract docs info specific to classes. */ extract(): ClassEntry { return { name: this.declaration.name.text, isAbstract: this.isAbstract(), entryType: ts.isInterfaceDeclaration(this.declaration) ? EntryType.Interface : EntryType.UndecoratedClass, members: this.extractSignatures().concat(this.extractAllClassMembers()), generics: extractGenerics(this.declaration), description: extractJsDocDescription(this.declaration), jsdocTags: extractJsDocTags(this.declaration), rawComment: extractRawJsDoc(this.declaration), extends: this.extractInheritance(this.declaration), implements: this.extractInterfaceConformance(this.declaration), }; } /** Extracts doc info for a class's members. */ protected extractAllClassMembers(): MemberEntry[] { const members: MemberEntry[] = []; for (const member of this.getMemberDeclarations()) { if (this.isMemberExcluded(member)) continue; const memberEntry = this.extractClassMember(member); if (memberEntry) { members.push(memberEntry); } } return members; } /** Extract docs for a class's members (methods and properties). */ protected extractClassMember(memberDeclaration: MemberElement): MemberEntry | undefined { if (this.isMethod(memberDeclaration)) { return this.extractMethod(memberDeclaration); } else if ( this.isProperty(memberDeclaration) && !this.hasPrivateComputedProperty(memberDeclaration) ) { return this.extractClassProperty(memberDeclaration); } else if (ts.isAccessor(memberDeclaration)) { return this.extractGetterSetter(memberDeclaration); } // We only expect methods, properties, and accessors. If we encounter something else, // return undefined and let the rest of the program filter it out. return undefined; } /** Extract docs for all call signatures in the current class/interface. */ protected extractSignatures(): MemberEntry[] { return this.computeAllSignatureDeclarations().map((s) => this.extractSignature(s)); } /** Extracts docs for a class method. */ protected extractMethod(methodDeclaration: MethodLike): MethodEntry { const functionExtractor = new FunctionExtractor( methodDeclaration.name.getText(), methodDeclaration, this.typeChecker, ); return { ...functionExtractor.extract(), memberType: MemberType.Method, memberTags: this.getMemberTags(methodDeclaration), }; } /** Extracts docs for a signature element (usually inside an interface). */ protected extractSignature(signature: SignatureElement): MethodEntry { // No name for the function if we are dealing with call signatures. // For construct signatures we are using `new` as the name of the function for now. // TODO: Consider exposing a new entry type for signature types. const functionExtractor = new FunctionExtractor( ts.isConstructSignatureDeclaration(signature) ? 'new' : '', signature, this.typeChecker, ); return { ...functionExtractor.extract(), memberType: MemberType.Method, memberTags: [], }; } /** Extracts doc info for a property declaration. */ protected extractClassProperty(propertyDeclaration: PropertyLike): PropertyEntry { return { name: propertyDeclaration.name.getText(), type: extractResolvedTypeString(propertyDeclaration, this.typeChecker), memberType: MemberType.Property, memberTags: this.getMemberTags(propertyDeclaration), description: extractJsDocDescription(propertyDeclaration), jsdocTags: extractJsDocTags(propertyDeclaration), }; } /** Extracts doc info for an accessor member (getter/setter). */ protected extractGetterSetter(accessor: ts.AccessorDeclaration): PropertyEntry { return { ...this.extractClassProperty(accessor), memberType: ts.isGetAccessor(accessor) ? MemberType.Getter : MemberType.Setter, }; } protected extractInheritance( declaration: ClassDeclaration & ClassDeclarationLike, ): string | undefined { if (!declaration.heritageClauses) { return undefined; } for (const clause of declaration.heritageClauses) { if (clause.token === ts.SyntaxKind.ExtendsKeyword) { // We are assuming a single class can only extend one class. const types = clause.types; if (types.length > 0) { const baseClass: ts.ExpressionWithTypeArguments = types[0]; return baseClass.getText(); } } } return undefined; } protected extractInterfaceConformance( declaration: ClassDeclaration & ClassDeclarationLike, ): string[] { const implementClause = declaration.heritageClauses?.find( (clause) => clause.token === ts.SyntaxKind.ImplementsKeyword, ); return implementClause?.types.map((m) => m.getText()) ?? []; } /** Gets the tags for a member (protected, readonly, static, etc.) */ protected getMemberTags(member: MethodLike | PropertyLike): MemberTags[] { const tags: MemberTags[] = this.getMemberTagsFromModifiers(member.modifiers ?? []); if (member.questionToken) { tags.push(MemberTags.Optional); } if (member.parent !== this.declaration) { tags.push(MemberTags.Inherited); } return tags; } /** Computes all signature declarations of the class/interface. */ private computeAllSignatureDeclarations(): SignatureElement[] { const type = this.typeChecker.getTypeAtLocation(this.declaration); const signatures = [...type.getCallSignatures(), ...type.getConstructSignatures()]; const result: SignatureElement[] = []; for (const signature of signatures) { const decl = signature.getDeclaration(); if (this.isDocumentableSignature(decl) && this.isDocumentableMember(decl)) { result.push(decl); } } return result; } /** Gets all member declarations, including inherited members. */ private getMemberDeclarations(): MemberElement[] { // We rely on TypeScript to resolve all the inherited members to their // ultimate form via `getProperties`. This is important because child // classes may narrow types or add method overloads. const type = this.typeChecker.getTypeAtLocation(this.declaration); const members = type.getProperties(); // While the properties of the declaration type represent the properties that exist // on a class *instance*, static members are properties on the class symbol itself. const typeOfConstructor = this.typeChecker.getTypeOfSymbol(type.symbol); const staticMembers = typeOfConstructor.getProperties(); const result: MemberElement[] = []; for (const member of [...members, ...staticMembers]) { // A member may have multiple declarations in the case of function overloads. const memberDeclarations = this.filterMethodOverloads(member.getDeclarations() ?? []); for (const memberDeclaration of memberDeclarations) { if (this.isDocumentableMember(memberDeclaration)) { result.push(memberDeclaration); } } } return result; } /** The result only contains properties, method implementations and abstracts */ private filterMethodOverloads(declarations: ts.Declaration[]): ts.Declaration[] { return declarations.filter((declaration, index) => { if (ts.isFunctionDeclaration(declaration) || ts.isMethodDeclaration(declaration)) { if (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Abstract) { // TS enforces that all declarations of an abstract method are consecutive const previousDeclaration = declarations[index - 1]; const samePreviousAbstractMethod = previousDeclaration && ts.isMethodDeclaration(previousDeclaration) && ts.getCombinedModifierFlags(previousDeclaration) & ts.ModifierFlags.Abstract && previousDeclaration.name.getText() === declaration.name?.getText(); // We just need a reference to one member // In the case of Abstract Methods we only want to return the first abstract. // Others with the same name are considered as overloads // Later on, the function extractor will handle overloads and implementation detection return !samePreviousAbstractMethod; } return !!declaration.body; } return true; }); } /** Get the tags for a member that come from the declaration modifiers. */ private getMemberTagsFromModifiers(mods: Iterable<ts.ModifierLike>): MemberTags[] { const tags: MemberTags[] = []; for (const mod of mods) { const tag = this.getTagForMemberModifier(mod); if (tag) tags.push(tag); } return tags; } /** Gets the doc tag corresponding to a class member modifier (readonly, protected, etc.). */ private getTagForMemberModifier(mod: ts.ModifierLike): MemberTags | undefined { switch (mod.kind) { case ts.SyntaxKind.StaticKeyword: return MemberTags.Static; case ts.SyntaxKind.ReadonlyKeyword: return MemberTags.Readonly; case ts.SyntaxKind.ProtectedKeyword: return MemberTags.Protected; case ts.SyntaxKind.AbstractKeyword: return MemberTags.Abstract; default: return undefined; } }
{ "end_byte": 11747, "start_byte": 2205, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.ts_11751_19206
/** * Gets whether a given class member should be excluded from public API docs. * This is the case if: * - The member does not have a name * - The member is neither a method nor property * - The member is private * - The member has a name that marks it as Angular-internal. * - The member is marked as internal via JSDoc. */ private isMemberExcluded(member: MemberElement): boolean { return ( !member.name || !this.isDocumentableMember(member) || (!ts.isCallSignatureDeclaration(member) && member.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.PrivateKeyword)) || member.name.getText() === 'prototype' || isAngularPrivateName(member.name.getText()) || isInternal(member) ); } /** Gets whether a class member is a method, property, or accessor. */ private isDocumentableMember( member: ts.Node, ): member is MethodLike | PropertyLike | ts.CallSignatureDeclaration { return ( this.isMethod(member) || this.isProperty(member) || ts.isAccessor(member) || // Signatures are documentable if they are part of an interface. ts.isCallSignatureDeclaration(member) ); } /** Check if the parameter is a constructor parameter with a public modifier */ private isPublicConstructorParameterProperty(node: ts.Node): boolean { if (ts.isParameterPropertyDeclaration(node, node.parent) && node.modifiers) { return node.modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.PublicKeyword); } return false; } /** Gets whether a member is a property. */ private isProperty(member: ts.Node): member is PropertyLike { // Classes have declarations, interface have signatures return ( ts.isPropertyDeclaration(member) || ts.isPropertySignature(member) || this.isPublicConstructorParameterProperty(member) ); } /** Gets whether a member is a method. */ private isMethod(member: ts.Node): member is MethodLike { // Classes have declarations, interface have signatures return ts.isMethodDeclaration(member) || ts.isMethodSignature(member); } /** Gets whether the given signature declaration is documentable. */ private isDocumentableSignature( signature: ts.SignatureDeclaration, ): signature is SignatureElement { return ( ts.isConstructSignatureDeclaration(signature) || ts.isCallSignatureDeclaration(signature) ); } /** Gets whether the declaration for this extractor is abstract. */ private isAbstract(): boolean { const modifiers = this.declaration.modifiers ?? []; return modifiers.some((mod) => mod.kind === ts.SyntaxKind.AbstractKeyword); } /** * Check wether a member has a private computed property name like [ɵWRITABLE_SIGNAL] * * This will prevent exposing private computed properties in the docs. */ private hasPrivateComputedProperty(property: PropertyLike) { return ( ts.isComputedPropertyName(property.name) && property.name.expression.getText().startsWith('ɵ') ); } } /** Extractor to pull info for API reference documentation for an Angular directive. */ class DirectiveExtractor extends ClassExtractor { constructor( declaration: ClassDeclaration & ts.ClassDeclaration, protected reference: Reference, protected metadata: DirectiveMeta, checker: ts.TypeChecker, ) { super(declaration, checker); } /** Extract docs info for directives and components (including underlying class info). */ override extract(): DirectiveEntry { return { ...super.extract(), isStandalone: this.metadata.isStandalone, selector: this.metadata.selector ?? '', exportAs: this.metadata.exportAs ?? [], entryType: this.metadata.isComponent ? EntryType.Component : EntryType.Directive, }; } /** Extracts docs info for a directive property, including input/output metadata. */ override extractClassProperty(propertyDeclaration: ts.PropertyDeclaration): PropertyEntry { const entry = super.extractClassProperty(propertyDeclaration); const inputMetadata = this.getInputMetadata(propertyDeclaration); if (inputMetadata) { entry.memberTags.push(MemberTags.Input); entry.inputAlias = inputMetadata.bindingPropertyName; entry.isRequiredInput = inputMetadata.required; } const outputMetadata = this.getOutputMetadata(propertyDeclaration); if (outputMetadata) { entry.memberTags.push(MemberTags.Output); entry.outputAlias = outputMetadata.bindingPropertyName; } return entry; } /** Gets the input metadata for a directive property. */ private getInputMetadata(prop: ts.PropertyDeclaration): InputMapping | undefined { const propName = prop.name.getText(); return this.metadata.inputs?.getByClassPropertyName(propName) ?? undefined; } /** Gets the output metadata for a directive property. */ private getOutputMetadata(prop: ts.PropertyDeclaration): InputOrOutput | undefined { const propName = prop.name.getText(); return this.metadata?.outputs?.getByClassPropertyName(propName) ?? undefined; } } /** Extractor to pull info for API reference documentation for an Angular pipe. */ class PipeExtractor extends ClassExtractor { constructor( declaration: ClassDeclaration & ts.ClassDeclaration, protected reference: Reference, private metadata: PipeMeta, typeChecker: ts.TypeChecker, ) { super(declaration, typeChecker); } override extract(): PipeEntry { return { ...super.extract(), pipeName: this.metadata.name, entryType: EntryType.Pipe, isStandalone: this.metadata.isStandalone, }; } } /** Extractor to pull info for API reference documentation for an Angular pipe. */ class NgModuleExtractor extends ClassExtractor { constructor( declaration: ClassDeclaration & ts.ClassDeclaration, protected reference: Reference, private metadata: NgModuleMeta, typeChecker: ts.TypeChecker, ) { super(declaration, typeChecker); } override extract(): ClassEntry { return { ...super.extract(), entryType: EntryType.NgModule, }; } } /** Extracts documentation info for a class, potentially including Angular-specific info. */ export function extractClass( classDeclaration: ClassDeclaration & ts.ClassDeclaration, metadataReader: MetadataReader, typeChecker: ts.TypeChecker, ): ClassEntry { const ref = new Reference(classDeclaration); let extractor: ClassExtractor; let directiveMetadata = metadataReader.getDirectiveMetadata(ref); let pipeMetadata = metadataReader.getPipeMetadata(ref); let ngModuleMetadata = metadataReader.getNgModuleMetadata(ref); if (directiveMetadata) { extractor = new DirectiveExtractor(classDeclaration, ref, directiveMetadata, typeChecker); } else if (pipeMetadata) { extractor = new PipeExtractor(classDeclaration, ref, pipeMetadata, typeChecker); } else if (ngModuleMetadata) { extractor = new NgModuleExtractor(classDeclaration, ref, ngModuleMetadata, typeChecker); } else { extractor = new ClassExtractor(classDeclaration, typeChecker); } return extractor.extract(); } /** Extracts documentation info for an interface. */ export function extractInterface( declaration: ts.InterfaceDeclaration, typeChecker: ts.TypeChecker, ): InterfaceEntry { const extractor = new ClassExtractor(declaration, typeChecker); return extractor.extract(); }
{ "end_byte": 19206, "start_byte": 11751, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.ts" }
angular/packages/compiler-cli/src/ngtsc/docs/src/internal.ts_0_1070
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {extractJsDocTags} from './jsdoc_extractor'; /** * Check if the member has a JSDoc @internal or a @internal is a normal comment */ export function isInternal(member: ts.HasJSDoc): boolean { return ( extractJsDocTags(member).some((tag) => tag.name === 'internal') || hasLeadingInternalComment(member) ); } /* * Check if the member has a comment block with @internal */ function hasLeadingInternalComment(member: ts.Node): boolean { const memberText = member.getSourceFile().text; return ( ts.reduceEachLeadingCommentRange( memberText, member.getFullStart(), (pos, end, kind, hasTrailingNewLine, containsInternal) => { return containsInternal || memberText.slice(pos, end).includes('@internal'); }, /* state */ false, /* initial */ false, ) ?? false ); }
{ "end_byte": 1070, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/docs/src/internal.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/BUILD.bazel_0_434
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "translator", srcs = glob(["**/*.ts"]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], )
{ "end_byte": 434, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/translator/index.ts_0_1165
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { AstFactory, BinaryOperator, LeadingComment, ObjectLiteralProperty, SourceMapLocation, SourceMapRange, TemplateElement, TemplateLiteral, UnaryOperator, VariableDeclarationType, } from './src/api/ast_factory'; export {ImportGenerator, ImportRequest} from './src/api/import_generator'; export {Context} from './src/context'; export { ImportManager, ImportManagerConfig, presetImportManagerForceNamespaceImports, } from './src/import_manager/import_manager'; export { ExpressionTranslatorVisitor, RecordWrappedNodeFn, TranslatorOptions, } from './src/translator'; export {canEmitType, TypeEmitter, TypeReferenceTranslator} from './src/type_emitter'; export {translateType} from './src/type_translator'; export { attachComments, createTemplateMiddle, createTemplateTail, TypeScriptAstFactory, } from './src/typescript_ast_factory'; export {translateExpression, translateStatement} from './src/typescript_translator';
{ "end_byte": 1165, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/index.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts_0_8729
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {absoluteFrom} from '../../file_system'; import {initMockFileSystem} from '../../file_system/testing'; import {NgtscTestCompilerHost} from '../../testing'; import {ImportManager} from '../src/import_manager/import_manager'; describe('import manager', () => { it('should be possible to import a symbol', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const ref = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(ref)]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; input; `), ); }); it('should be possible to import a namespace', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const ref = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: null, requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(ref)]); expect(res).toBe( omitLeadingWhitespace(` import * as i0 from "@angular/core"; i0; `), ); }); it('should be possible to import multiple symbols', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(outputRef), ]); expect(res).toBe( omitLeadingWhitespace(` import { input, output } from "@angular/core"; input; output; `), ); }); it('should be possible to import multiple namespaces', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const coreNamespace = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: null, requestedFile: testFile, }); const interopNamespace = manager.addImport({ exportModuleSpecifier: '@angular/core/rxjs-interop', exportSymbolName: null, requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(coreNamespace), ts.factory.createExpressionStatement(interopNamespace), ]); expect(res).toBe( omitLeadingWhitespace(` import * as i0 from "@angular/core"; import * as i1 from "@angular/core/rxjs-interop"; i0; i1; `), ); }); it('should be possible to generate a namespace import and re-use it for future symbols', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const coreNamespace = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: null, requestedFile: testFile, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(coreNamespace), ts.factory.createExpressionStatement(outputRef), ]); expect(res).toBe( omitLeadingWhitespace(` import * as i0 from "@angular/core"; i0; i0.output; `), ); }); it('should always generate a new namespace import if there is only a named import', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const coreNamespace = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: null, requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(coreNamespace), ]); expect(res).toBe( omitLeadingWhitespace(` import * as i0 from "@angular/core"; import { input } from "@angular/core"; input; i0; `), ); }); it('should be able to re-use existing source file namespace imports for symbols', () => { const {testFile, emit} = createTestProgram(` import * as existingImport from '@angular/core'; `); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import * as existingImport from '@angular/core'; existingImport.input; `), ); }); it('should re-use existing source file namespace imports for a namespace request', () => { const {testFile, emit} = createTestProgram(` import * as existingImport from '@angular/core'; `); const manager = new ImportManager(); const coreRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: null, requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(coreRef)]); expect(res).toBe( omitLeadingWhitespace(` import * as existingImport from '@angular/core'; existingImport; `), ); }); it('should be able to re-use existing source named bindings', () => { const {testFile, emit} = createTestProgram(` import {input} from '@angular/core'; `); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input } from '@angular/core'; input; `), ); }); it('should be able to add symbols to an existing source file named import', () => { const {testFile, emit} = createTestProgram(` import {input} from '@angular/core'; const x = input(); `); const manager = new ImportManager(); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(outputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input, output } from '@angular/core'; output; const x = input(); `), ); }); it( 'should be able to add symbols to an existing source file named import, ' + 'while still eliding unused specifiers of the updated import', () => { const {testFile, emit} = createTestProgram(` import {input} from '@angular/core'; `); const manager = new ImportManager(); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(outputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { output } from '@angular/core'; output; `), ); }, ); it('should not re-use an original file import if re-use is disabled', () => { const {testFile, emit} = createTestProgram(` import {input} from '@angular/core'; `); const manager = new ImportManager({ disableOriginalSourceFileReuse: true, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(outputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { output } from "@angular/core"; output; `), ); });
{ "end_byte": 8729, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts_8733_17486
it('should not re-use an original namespace import if re-use is disabled', () => { const {testFile, emit} = createTestProgram(` import * as existingCore from '@angular/core'; `); const manager = new ImportManager({ disableOriginalSourceFileReuse: true, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(outputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { output } from "@angular/core"; output; `), ); }); it('should be able to always prefer namespace imports for new imports', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager({ forceGenerateNamespacesForNewImports: true, }); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(outputRef), ]); expect(res).toBe( omitLeadingWhitespace(` import * as i0 from "@angular/core"; i0.input; i0.output; `), ); }); it( 'should be able to always prefer namespace imports for new imports, ' + 'but still re-use source file namespace imports', () => { const {testFile, emit} = createTestProgram(` import * as existingNamespace from '@angular/core'; `); const manager = new ImportManager({ forceGenerateNamespacesForNewImports: true, }); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(outputRef), ]); expect(res).toBe( omitLeadingWhitespace(` import * as existingNamespace from '@angular/core'; existingNamespace.input; existingNamespace.output; `), ); }, ); it( 'should be able to always prefer namespace imports for new imports, ' + 'but still re-use source file individual imports', () => { const {testFile, emit} = createTestProgram(` import {Dir} from 'bla'; const x = new Dir(); `); const manager = new ImportManager({ forceGenerateNamespacesForNewImports: true, }); const blaRef = manager.addImport({ exportModuleSpecifier: 'bla', exportSymbolName: 'Dir', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(blaRef)]); expect(res).toBe( omitLeadingWhitespace(` import { Dir } from 'bla'; Dir; const x = new Dir(); `), ); }, ); it('should not change existing unrelated imports', () => { const {testFile, emit} = createTestProgram(` import {MyComp} from './bla'; console.log(MyComp); `); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { MyComp } from './bla'; import { input } from "@angular/core"; input; console.log(MyComp); `), ); }); it('should be able to add a side effect import', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager(); manager.addSideEffectImport(testFile, '@angular/core'); const res = emit(manager, []); expect(res).toBe( omitLeadingWhitespace(` import "@angular/core"; `), ); }); it('should avoid conflicts with existing top-level identifiers', () => { const {testFile, emit} = createTestProgram(` const input = 1; `); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input as input_1 } from "@angular/core"; input_1; const input = 1; `), ); }); it('should avoid conflicts with existing deep identifiers', () => { const {testFile, emit} = createTestProgram(` function x() { const p = () => { const input = 1; }; } `); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input as input_1 } from "@angular/core"; input_1; function x() { const p = () => { const input = 1; }; } `), ); }); it('should avoid an import specifier alias if similar import is generated in different', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager(); manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: ts.createSourceFile('other_file', '', ts.ScriptTarget.Latest), }); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; input; `), ); }); it('should avoid an import alias specifier if identifier is free to use', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; input; `), ); }); it('should avoid collisions with generated identifiers', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const inputRef2 = manager.addImport({ exportModuleSpecifier: '@angular/core2', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(inputRef2), ]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; import { input as input_1 } from "@angular/core2"; input; input_1; `), ); }); it('should avoid collisions with generated identifiers', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const inputRef2 = manager.addImport({ exportModuleSpecifier: '@angular/core2', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(inputRef2), ]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; import { input as input_1 } from "@angular/core2"; input; input_1; `), ); });
{ "end_byte": 17486, "start_byte": 8733, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts_17490_25741
it('should re-use previous similar generated imports', () => { const {testFile, emit} = createTestProgram(``); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const inputRef2 = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(inputRef2), ]); expect(inputRef).toBe(inputRef2); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; input; input; `), ); }); it('should not re-use original source file type-only imports', () => { const {testFile, emit} = createTestProgram(` import type {input} from '@angular/core'; `); const manager = new ImportManager(); const ref = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'bla', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(ref)]); expect(res).toBe( omitLeadingWhitespace(` import { bla } from "@angular/core"; bla; `), ); }); it('should not re-use original source file type-only import specifiers', () => { const {testFile, emit} = createTestProgram(` import {type input} from '@angular/core'; // existing. `); const manager = new ImportManager(); const ref = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'bla', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(ref)]); expect(res).toBe( omitLeadingWhitespace(` import { bla } from '@angular/core'; // existing. bla; `), ); }); it('should allow for a specific alias to be passed in', () => { const {testFile, emit} = createTestProgram(` import { input } from "@angular/core"; input(); `); const manager = new ImportManager(); const fooRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'bar', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(fooRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input, foo as bar } from "@angular/core"; bar; input(); `), ); }); it('should allow for a specific alias to be passed in when reuse is disabled', () => { const {testFile, emit} = createTestProgram(` import { input } from "@angular/core"; input(); `); const manager = new ImportManager({ disableOriginalSourceFileReuse: true, }); const fooRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'bar', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(fooRef)]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; import { foo as bar } from "@angular/core"; bar; input(); `), ); }); it('should reuse a pre-existing import that has the same name and alias', () => { const {testFile, emit} = createTestProgram(` import { foo as bar } from "@angular/core"; bar(); `); const manager = new ImportManager(); const fooRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'bar', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(fooRef)]); expect(res).toBe( omitLeadingWhitespace(` import { foo as bar } from "@angular/core"; bar; bar(); `), ); }); it('should reuse import if both the name and alias are the same when added through `addImport`', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const firstRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'bar', requestedFile: testFile, }); const secondRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'bar', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(firstRef), ts.factory.createExpressionStatement(secondRef), ]); expect(res).toBe( omitLeadingWhitespace(` import { foo as bar } from "@angular/core"; bar; bar; `), ); }); it('should not reuse import if symbol is imported under a different alias', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const barRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'bar', requestedFile: testFile, }); const bazRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', unsafeAliasOverride: 'baz', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(barRef), ts.factory.createExpressionStatement(bazRef), ]); expect(res).toBe( omitLeadingWhitespace(` import { foo as bar, foo as baz } from "@angular/core"; bar; baz; `), ); }); it('should not attempt to de-duplicate imports with an explicit alias', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const fooRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', requestedFile: testFile, }); const barRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'bar', unsafeAliasOverride: 'foo', requestedFile: testFile, }); const res = emit(manager, [ ts.factory.createExpressionStatement(fooRef), ts.factory.createExpressionStatement(barRef), ]); expect(res).toBe( omitLeadingWhitespace(` import { foo, bar as foo } from "@angular/core"; foo; foo; `), ); }); it('should remove a pre-existing import from a declaration', () => { const {testFile, emit} = createTestProgram(` import { input, output, model } from '@angular/core'; input(); output(); model(); `); const manager = new ImportManager(); manager.removeImport(testFile, 'output', '@angular/core'); const res = emit(manager, []); expect(res).toBe( omitLeadingWhitespace(` import { input, model } from '@angular/core'; input(); output(); model(); `), ); }); it('should remove the entire declaration if all pre-existing imports are removed', () => { const {testFile, emit} = createTestProgram(` import { input, output } from '@angular/core'; input(); output(); `); const manager = new ImportManager(); manager.removeImport(testFile, 'input', '@angular/core'); manager.removeImport(testFile, 'output', '@angular/core'); expect(emit(manager, [])).toBe( omitLeadingWhitespace(` input(); output(); export {}; `), ); }); it('should remove a pre-existing aliased import', () => { const {testFile, emit} = createTestProgram(` import { input, output as foo } from '@angular/core'; input(); foo(); `); const manager = new ImportManager(); manager.removeImport(testFile, 'output', '@angular/core'); expect(emit(manager, [])).toBe( omitLeadingWhitespace(` import { input } from '@angular/core'; input(); foo(); `), ); });
{ "end_byte": 25741, "start_byte": 17490, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts_25745_30732
it('should remove all pre-existing instances of a specific import', () => { const {testFile, emit} = createTestProgram(` import { input, input as foo } from '@angular/core'; import { input as bar } from '@angular/core'; input(); foo(); bar(); `); const manager = new ImportManager(); manager.removeImport(testFile, 'input', '@angular/core'); expect(emit(manager, [])).toBe( omitLeadingWhitespace(` input(); foo(); bar(); export {}; `), ); }); it('should be able to remove from an import that is being modified', () => { const {testFile, emit} = createTestProgram(` import { input } from '@angular/core'; input(); `); const manager = new ImportManager(); const ref = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'foo', requestedFile: testFile, }); manager.removeImport(testFile, 'input', '@angular/core'); const res = emit(manager, [ts.factory.createExpressionStatement(ref)]); expect(res).toBe( omitLeadingWhitespace(` import { foo } from '@angular/core'; foo; input(); `), ); }); it('should be able to remove a symbol from a newly-created import declaration', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const outputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'output', requestedFile: testFile, }); manager.removeImport(testFile, 'input', '@angular/core'); const res = emit(manager, [ ts.factory.createExpressionStatement(inputRef), ts.factory.createExpressionStatement(outputRef), ]); expect(res).toBe( omitLeadingWhitespace(` import { output } from "@angular/core"; input; output; `), ); }); it('should add a symbol if addImport is called after removeImport', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); manager.removeImport(testFile, 'input', '@angular/core'); const ref = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: testFile, }); const res = emit(manager, [ts.factory.createExpressionStatement(ref)]); expect(res).toBe( omitLeadingWhitespace(` import { input } from "@angular/core"; input; `), ); }); it('should remove a newly-added aliased import', () => { const {testFile, emit} = createTestProgram(''); const manager = new ImportManager(); const inputRef = manager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', unsafeAliasOverride: 'foo', requestedFile: testFile, }); manager.removeImport(testFile, 'input', '@angular/core'); const res = emit(manager, [ts.factory.createExpressionStatement(inputRef)]); expect(res).toBe( omitLeadingWhitespace(` foo; `), ); }); }); function createTestProgram(text: string): { testFile: ts.SourceFile; emit: (manager: ImportManager, extraStatements: ts.Statement[]) => string; } { const fs = initMockFileSystem('Native'); const options: ts.CompilerOptions = { rootDir: '/', module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ESNext, skipLibCheck: true, types: [], }; fs.ensureDir(absoluteFrom('/')); fs.writeFile(absoluteFrom('/test.ts'), text); const program = ts.createProgram({ rootNames: ['/test.ts'], options, host: new NgtscTestCompilerHost(fs, options), }); const testFile = program.getSourceFile('/test.ts'); if (testFile === undefined) { throw new Error('Could not get test source file from program.'); } const emit = (manager: ImportManager, newStatements: ts.Statement[]) => { const transformer = manager.toTsTransform(new Map([[testFile.fileName, newStatements]])); let emitResult: string | null = null; const {emitSkipped} = program.emit( testFile, (fileName, resultText) => { if (fileName === '/test.js') { emitResult = resultText; } }, undefined, undefined, {before: [transformer]}, ); if (emitSkipped || emitResult === null) { throw new Error(`Unexpected emit failure when emitting test file.`); } return omitLeadingWhitespace(emitResult); }; return {testFile, emit}; } /** Omits the leading whitespace for each line of the given text. */ function omitLeadingWhitespace(text: string): string { return text.replace(/^\s+/gm, ''); }
{ "end_byte": 30732, "start_byte": 25745, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/import_manager_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/BUILD.bazel_0_696
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/translator", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 696, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts_0_390
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {leadingComment} from '@angular/compiler'; import ts from 'typescript'; import {TypeScriptAstFactory} from '../src/typescript_ast_factory'; describe('TypeScriptAstFactory', () =>
{ "end_byte": 390, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts_391_8364
{ let factory: TypeScriptAstFactory; beforeEach(() => (factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false))); describe('attachComments()', () => { it('should add the comments to the given statement', () => { const { items: [stmt], generate, } = setupStatements('x = 10;'); factory.attachComments(stmt, [ leadingComment('comment 1', true), leadingComment('comment 2', false), ]); expect(generate(stmt)).toEqual(['/* comment 1 */', '//comment 2', 'x = 10;'].join('\n')); }); it('should add the comments to the given expression', () => { const { items: [expr], generate, } = setupExpressions('x + 10'); factory.attachComments(expr, [ leadingComment('comment 1', true), leadingComment('comment 2', false), ]); expect(generate(expr)).toEqual(['/* comment 1 */', '//comment 2', 'x + 10'].join('\n')); }); }); describe('createArrayLiteral()', () => { it('should create an array node containing the provided expressions', () => { const { items: [expr1, expr2], generate, } = setupExpressions(`42`, '"moo"'); const array = factory.createArrayLiteral([expr1, expr2]); expect(generate(array)).toEqual('[42, "moo"]'); }); }); describe('createAssignment()', () => { it('should create an assignment node using the target and value expressions', () => { const { items: [target, value], generate, } = setupExpressions(`x`, `42`); const assignment = factory.createAssignment(target, value); expect(generate(assignment)).toEqual('x = 42'); }); }); describe('createBinaryExpression()', () => { it('should create a binary operation node using the left and right expressions', () => { const { items: [left, right], generate, } = setupExpressions(`17`, `42`); const assignment = factory.createBinaryExpression(left, '+', right); expect(generate(assignment)).toEqual('17 + 42'); }); }); describe('createDynamicImport()', () => { it('should create a dynamic import expression from a string URL', () => { const {generate} = setupExpressions(``); const url = './some/path'; const assignment = factory.createDynamicImport(url); expect(generate(assignment)).toEqual(`import("${url}")`); }); it('should create a dynamic import expression from an expression URL', () => { const {items, generate} = setupExpressions(`'/' + 'abc' + '/'`); const assignment = factory.createDynamicImport(items[0]); expect(generate(assignment)).toEqual(`import('/' + 'abc' + '/')`); }); }); describe('createBlock()', () => { it('should create a block statement containing the given statements', () => { const {items: stmts, generate} = setupStatements('x = 10; y = 20;'); const block = factory.createBlock(stmts); expect(generate(block)).toEqual(['{', ' x = 10;', ' y = 20;', '}'].join('\n')); }); }); describe('createCallExpression()', () => { it('should create a call on the `callee` with the given `args`', () => { const { items: [callee, arg1, arg2], generate, } = setupExpressions('foo', '42', '"moo"'); const call = factory.createCallExpression(callee, [arg1, arg2], false); expect(generate(call)).toEqual('foo(42, "moo")'); }); it('should create a call marked with a PURE comment if `pure` is true', () => { const { items: [callee, arg1, arg2], generate, } = setupExpressions(`foo`, `42`, `"moo"`); const call = factory.createCallExpression(callee, [arg1, arg2], true); expect(generate(call)).toEqual('/*@__PURE__*/ foo(42, "moo")'); }); it('should create a call marked with a closure-style pure comment if `pure` is true', () => { factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ true); const { items: [callee, arg1, arg2], generate, } = setupExpressions(`foo`, `42`, `"moo"`); const call = factory.createCallExpression(callee, [arg1, arg2], true); expect(generate(call)).toEqual('/** @pureOrBreakMyCode */ foo(42, "moo")'); }); }); describe('createConditional()', () => { it('should create a condition expression', () => { const { items: [test, thenExpr, elseExpr], generate, } = setupExpressions(`!test`, `42`, `"moo"`); const conditional = factory.createConditional(test, thenExpr, elseExpr); expect(generate(conditional)).toEqual('!test ? 42 : "moo"'); }); }); describe('createElementAccess()', () => { it('should create an expression accessing the element of an array/object', () => { const { items: [expr, element], generate, } = setupExpressions(`obj`, `"moo"`); const access = factory.createElementAccess(expr, element); expect(generate(access)).toEqual('obj["moo"]'); }); }); describe('createExpressionStatement()', () => { it('should create a statement node from the given expression', () => { const { items: [expr], generate, } = setupExpressions(`x = 10`); const stmt = factory.createExpressionStatement(expr); expect(ts.isExpressionStatement(stmt)).toBe(true); expect(generate(stmt)).toEqual('x = 10;'); }); }); describe('createFunctionDeclaration()', () => { it('should create a function declaration node with the given name, parameters and body statements', () => { const { items: [body], generate, } = setupStatements('{x = 10; y = 20;}'); const fn = factory.createFunctionDeclaration('foo', ['arg1', 'arg2'], body); expect(generate(fn)).toEqual('function foo(arg1, arg2) { x = 10; y = 20; }'); }); }); describe('createFunctionExpression()', () => { it('should create a function expression node with the given name, parameters and body statements', () => { const { items: [body], generate, } = setupStatements('{x = 10; y = 20;}'); const fn = factory.createFunctionExpression('foo', ['arg1', 'arg2'], body); expect(ts.isExpressionStatement(fn)).toBe(false); expect(generate(fn)).toEqual('function foo(arg1, arg2) { x = 10; y = 20; }'); }); it('should create an anonymous function expression node if the name is null', () => { const { items: [body], generate, } = setupStatements('{x = 10; y = 20;}'); const fn = factory.createFunctionExpression(null, ['arg1', 'arg2'], body); expect(generate(fn)).toEqual('function (arg1, arg2) { x = 10; y = 20; }'); }); }); describe('createIdentifier()', () => { it('should create an identifier with the given name', () => { const id = factory.createIdentifier('someId') as ts.Identifier; expect(ts.isIdentifier(id)).toBe(true); expect(id.text).toEqual('someId'); }); }); describe('createIfStatement()', () => { it('should create an if-else statement', () => { const { items: [testStmt, thenStmt, elseStmt], generate, } = setupStatements('!test;x = 10;x = 42;'); const test = (testStmt as ts.ExpressionStatement).expression; const ifStmt = factory.createIfStatement(test, thenStmt, elseStmt); expect(generate(ifStmt)).toEqual( ['if (!test)', ' x = 10;', 'else', ' x = 42;'].join('\n'), ); }); it('should create an if statement if the else expression is null', () => { const { items: [testStmt, thenStmt], generate, } = setupStatements('!test;x = 10;'); const test = (testStmt as ts.ExpressionStatement).expression; const ifStmt = factory.createIfStatement(test, thenStmt, null); expect(generate(ifStmt)).toEqual(['if (!test)', ' x = 10;'].join('\n')); }); });
{ "end_byte": 8364, "start_byte": 391, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts_8368_16723
describe('createArrowFunctionExpression()', () => { it('should create an arrow function with an implicit return if a single statement is provided', () => { const { items: [body], generate, } = setupExpressions('arg2 + arg1'); const fn = factory.createArrowFunctionExpression(['arg1', 'arg2'], body); expect(generate(fn)).toEqual('(arg1, arg2) => arg2 + arg1'); }); it('should create an arrow function with an implicit return object literal', () => { const { items: [body], generate, } = setupExpressions('{a: 1, b: 2}'); const fn = factory.createArrowFunctionExpression([], body); expect(generate(fn)).toEqual('() => ({ a: 1, b: 2 })'); }); it('should create an arrow function with a body when an array of statements is provided', () => { const { items: [body], generate, } = setupStatements('{x = 10; y = 20; return x + y;}'); const fn = factory.createArrowFunctionExpression(['arg1', 'arg2'], body); expect(generate(fn)).toEqual('(arg1, arg2) => { x = 10; y = 20; return x + y; }'); }); }); describe('createLiteral()', () => { it('should create a string literal', () => { const {generate} = setupStatements(); const literal = factory.createLiteral('moo'); expect(ts.isStringLiteral(literal)).toBe(true); expect(generate(literal)).toEqual('"moo"'); }); it('should create a number literal', () => { const {generate} = setupStatements(); const literal = factory.createLiteral(42); expect(ts.isNumericLiteral(literal)).toBe(true); expect(generate(literal)).toEqual('42'); }); it('should create a negative number literal', () => { const {generate} = setupStatements(); const literal = factory.createLiteral(-42); expect(ts.isPrefixUnaryExpression(literal)).toBe(true); expect(generate(literal)).toEqual('-42'); }); it('should create a number literal for `NaN`', () => { const {generate} = setupStatements(); const literal = factory.createLiteral(NaN); expect(ts.isNumericLiteral(literal)).toBe(true); expect(generate(literal)).toEqual('NaN'); }); it('should create a boolean literal', () => { const {generate} = setupStatements(); const literal = factory.createLiteral(true); expect(ts.isToken(literal)).toBe(true); expect(generate(literal)).toEqual('true'); }); it('should create an `undefined` literal', () => { const {generate} = setupStatements(); const literal = factory.createLiteral(undefined); expect(ts.isIdentifier(literal)).toBe(true); expect(generate(literal)).toEqual('undefined'); }); it('should create a `null` literal', () => { const {generate} = setupStatements(); const literal = factory.createLiteral(null); expect(ts.isToken(literal)).toBe(true); expect(generate(literal)).toEqual('null'); }); }); describe('createNewExpression()', () => { it('should create a `new` operation on the constructor `expression` with the given `args`', () => { const { items: [expr, arg1, arg2], generate, } = setupExpressions('Foo', '42', '"moo"'); const call = factory.createNewExpression(expr, [arg1, arg2]); expect(generate(call)).toEqual('new Foo(42, "moo")'); }); }); describe('createObjectLiteral()', () => { it('should create an object literal node, with the given properties', () => { const { items: [prop1, prop2], generate, } = setupExpressions('42', '"moo"'); const obj = factory.createObjectLiteral([ {propertyName: 'prop1', value: prop1, quoted: false}, {propertyName: 'prop2', value: prop2, quoted: true}, ]); expect(generate(obj)).toEqual('{ prop1: 42, "prop2": "moo" }'); }); }); describe('createParenthesizedExpression()', () => { it('should add parentheses around the given expression', () => { const { items: [expr], generate, } = setupExpressions(`a + b`); const paren = factory.createParenthesizedExpression(expr); expect(generate(paren)).toEqual('(a + b)'); }); }); describe('createPropertyAccess()', () => { it('should create a property access expression node', () => { const { items: [expr], generate, } = setupExpressions(`obj`); const access = factory.createPropertyAccess(expr, 'moo'); expect(generate(access)).toEqual('obj.moo'); }); }); describe('createReturnStatement()', () => { it('should create a return statement returning the given expression', () => { const { items: [expr], generate, } = setupExpressions(`42`); const returnStmt = factory.createReturnStatement(expr); expect(generate(returnStmt)).toEqual('return 42;'); }); it('should create a void return statement if the expression is null', () => { const {generate} = setupStatements(); const returnStmt = factory.createReturnStatement(null); expect(generate(returnStmt)).toEqual('return;'); }); }); describe('createTaggedTemplate()', () => { it('should create a tagged template node from the tag, elements and expressions', () => { const elements = [ {raw: 'raw\\n1', cooked: 'raw\n1', range: null}, {raw: 'raw\\n2', cooked: 'raw\n2', range: null}, {raw: 'raw\\n3', cooked: 'raw\n3', range: null}, ]; const { items: [tag, ...expressions], generate, } = setupExpressions('tagFn', '42', '"moo"'); const template = factory.createTaggedTemplate(tag, {elements, expressions}); expect(generate(template)).toEqual('tagFn `raw\\n1${42}raw\\n2${"moo"}raw\\n3`'); }); }); describe('createThrowStatement()', () => { it('should create a throw statement, throwing the given expression', () => { const { items: [expr], generate, } = setupExpressions(`new Error("bad")`); const throwStmt = factory.createThrowStatement(expr); expect(generate(throwStmt)).toEqual('throw new Error("bad");'); }); }); describe('createTypeOfExpression()', () => { it('should create a typeof expression node', () => { const { items: [expr], generate, } = setupExpressions(`42`); const typeofExpr = factory.createTypeOfExpression(expr); expect(generate(typeofExpr)).toEqual('typeof 42'); }); }); describe('createUnaryExpression()', () => { it('should create a unary expression with the operator and operand', () => { const { items: [expr], generate, } = setupExpressions(`value`); const unaryExpr = factory.createUnaryExpression('!', expr); expect(generate(unaryExpr)).toEqual('!value'); }); }); describe('createVariableDeclaration()', () => { it('should create a variable declaration statement node for the given variable name and initializer', () => { const { items: [initializer], generate, } = setupExpressions(`42`); const varDecl = factory.createVariableDeclaration('foo', initializer, 'let'); expect(generate(varDecl)).toEqual('let foo = 42;'); }); it('should create a constant declaration statement node for the given variable name and initializer', () => { const { items: [initializer], generate, } = setupExpressions(`42`); const varDecl = factory.createVariableDeclaration('foo', initializer, 'const'); expect(generate(varDecl)).toEqual('const foo = 42;'); }); it('should create a downleveled declaration statement node for the given variable name and initializer', () => { const { items: [initializer], generate, } = setupExpressions(`42`); const varDecl = factory.createVariableDeclaration('foo', initializer, 'var'); expect(generate(varDecl)).toEqual('var foo = 42;'); }); it('should create an uninitialized variable declaration statement node for the given variable name and a null initializer', () => { const {generate} = setupStatements(); const varDecl = factory.createVariableDeclaration('foo', null, 'let'); expect(generate(varDecl)).toEqual('let foo;'); }); });
{ "end_byte": 16723, "start_byte": 8368, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts_16727_19129
describe('setSourceMapRange()', () => { it('should attach the `sourceMapRange` to the given `node`', () => { const { items: [expr], } = setupExpressions(`42`); factory.setSourceMapRange(expr, { start: {line: 0, column: 1, offset: 1}, end: {line: 2, column: 3, offset: 15}, content: '-****\n*****\n****', url: 'original.ts', }); const range = ts.getSourceMapRange(expr); expect(range.pos).toEqual(1); expect(range.end).toEqual(15); expect(range.source?.getLineAndCharacterOfPosition(range.pos)).toEqual({ line: 0, character: 1, }); expect(range.source?.getLineAndCharacterOfPosition(range.end)).toEqual({ line: 2, character: 3, }); }); }); }); /** * Setup some statements to use in a test, along with a generate function to print the created nodes * out. * * The TypeScript printer requires access to the original source of non-synthesized nodes. * It uses the source content to output things like text between parts of nodes, which it doesn't * store in the AST node itself. * * So this helper (and its sister `setupExpressions()`) capture the original source file used to * provide the original statements/expressions that are used in the tests so that the printing will * work via the returned `generate()` function. */ function setupStatements(stmts: string = ''): SetupResult<ts.Statement> { const printer = ts.createPrinter({newLine: ts.NewLineKind.LineFeed}); const sf = ts.createSourceFile('test.ts', stmts, ts.ScriptTarget.ES2015, true); return { items: Array.from(sf.statements), generate: (node: ts.Node) => printer.printNode(ts.EmitHint.Unspecified, node, sf), }; } /** * Setup some statements to use in a test, along with a generate function to print the created nodes * out. * * See `setupStatements()` for more information about this helper function. */ function setupExpressions(...exprs: string[]): SetupResult<ts.Expression> { const { items: [arrayStmt], generate, } = setupStatements(`[${exprs.join(',')}];`); const expressions = Array.from( ((arrayStmt as ts.ExpressionStatement).expression as ts.ArrayLiteralExpression).elements, ); return {items: expressions, generate}; } interface SetupResult<TNode extends ts.Node> { items: TNode[]; generate(node: ts.Node): string; }
{ "end_byte": 19129, "start_byte": 16727, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/test/typescript_ast_factory_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/translator.ts_0_1688
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 o from '@angular/compiler'; import { AstFactory, BinaryOperator, ObjectLiteralProperty, SourceMapRange, TemplateElement, TemplateLiteral, UnaryOperator, } from './api/ast_factory'; import {ImportGenerator} from './api/import_generator'; import {Context} from './context'; const UNARY_OPERATORS = new Map<o.UnaryOperator, UnaryOperator>([ [o.UnaryOperator.Minus, '-'], [o.UnaryOperator.Plus, '+'], ]); const BINARY_OPERATORS = new Map<o.BinaryOperator, BinaryOperator>([ [o.BinaryOperator.And, '&&'], [o.BinaryOperator.Bigger, '>'], [o.BinaryOperator.BiggerEquals, '>='], [o.BinaryOperator.BitwiseAnd, '&'], [o.BinaryOperator.BitwiseOr, '|'], [o.BinaryOperator.Divide, '/'], [o.BinaryOperator.Equals, '=='], [o.BinaryOperator.Identical, '==='], [o.BinaryOperator.Lower, '<'], [o.BinaryOperator.LowerEquals, '<='], [o.BinaryOperator.Minus, '-'], [o.BinaryOperator.Modulo, '%'], [o.BinaryOperator.Multiply, '*'], [o.BinaryOperator.NotEquals, '!='], [o.BinaryOperator.NotIdentical, '!=='], [o.BinaryOperator.Or, '||'], [o.BinaryOperator.Plus, '+'], [o.BinaryOperator.NullishCoalesce, '??'], ]); export type RecordWrappedNodeFn<TExpression> = (node: o.WrappedNodeExpr<TExpression>) => void; export interface TranslatorOptions<TExpression> { downlevelTaggedTemplates?: boolean; downlevelVariableDeclarations?: boolean; recordWrappedNode?: RecordWrappedNodeFn<TExpression>; annotateForClosureCompiler?: boolean; }
{ "end_byte": 1688, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/translator.ts_1690_10567
export class ExpressionTranslatorVisitor<TFile, TStatement, TExpression> implements o.ExpressionVisitor, o.StatementVisitor { private downlevelTaggedTemplates: boolean; private downlevelVariableDeclarations: boolean; private recordWrappedNode: RecordWrappedNodeFn<TExpression>; constructor( private factory: AstFactory<TStatement, TExpression>, private imports: ImportGenerator<TFile, TExpression>, private contextFile: TFile, options: TranslatorOptions<TExpression>, ) { this.downlevelTaggedTemplates = options.downlevelTaggedTemplates === true; this.downlevelVariableDeclarations = options.downlevelVariableDeclarations === true; this.recordWrappedNode = options.recordWrappedNode || (() => {}); } visitDeclareVarStmt(stmt: o.DeclareVarStmt, context: Context): TStatement { const varType = this.downlevelVariableDeclarations ? 'var' : stmt.hasModifier(o.StmtModifier.Final) ? 'const' : 'let'; return this.attachComments( this.factory.createVariableDeclaration( stmt.name, stmt.value?.visitExpression(this, context.withExpressionMode), varType, ), stmt.leadingComments, ); } visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, context: Context): TStatement { return this.attachComments( this.factory.createFunctionDeclaration( stmt.name, stmt.params.map((param) => param.name), this.factory.createBlock(this.visitStatements(stmt.statements, context.withStatementMode)), ), stmt.leadingComments, ); } visitExpressionStmt(stmt: o.ExpressionStatement, context: Context): TStatement { return this.attachComments( this.factory.createExpressionStatement( stmt.expr.visitExpression(this, context.withStatementMode), ), stmt.leadingComments, ); } visitReturnStmt(stmt: o.ReturnStatement, context: Context): TStatement { return this.attachComments( this.factory.createReturnStatement( stmt.value.visitExpression(this, context.withExpressionMode), ), stmt.leadingComments, ); } visitIfStmt(stmt: o.IfStmt, context: Context): TStatement { return this.attachComments( this.factory.createIfStatement( stmt.condition.visitExpression(this, context), this.factory.createBlock(this.visitStatements(stmt.trueCase, context.withStatementMode)), stmt.falseCase.length > 0 ? this.factory.createBlock( this.visitStatements(stmt.falseCase, context.withStatementMode), ) : null, ), stmt.leadingComments, ); } visitReadVarExpr(ast: o.ReadVarExpr, _context: Context): TExpression { const identifier = this.factory.createIdentifier(ast.name!); this.setSourceMapRange(identifier, ast.sourceSpan); return identifier; } visitWriteVarExpr(expr: o.WriteVarExpr, context: Context): TExpression { const assignment = this.factory.createAssignment( this.setSourceMapRange(this.factory.createIdentifier(expr.name), expr.sourceSpan), expr.value.visitExpression(this, context), ); return context.isStatement ? assignment : this.factory.createParenthesizedExpression(assignment); } visitWriteKeyExpr(expr: o.WriteKeyExpr, context: Context): TExpression { const exprContext = context.withExpressionMode; const target = this.factory.createElementAccess( expr.receiver.visitExpression(this, exprContext), expr.index.visitExpression(this, exprContext), ); const assignment = this.factory.createAssignment( target, expr.value.visitExpression(this, exprContext), ); return context.isStatement ? assignment : this.factory.createParenthesizedExpression(assignment); } visitWritePropExpr(expr: o.WritePropExpr, context: Context): TExpression { const target = this.factory.createPropertyAccess( expr.receiver.visitExpression(this, context), expr.name, ); return this.factory.createAssignment(target, expr.value.visitExpression(this, context)); } visitInvokeFunctionExpr(ast: o.InvokeFunctionExpr, context: Context): TExpression { return this.setSourceMapRange( this.factory.createCallExpression( ast.fn.visitExpression(this, context), ast.args.map((arg) => arg.visitExpression(this, context)), ast.pure, ), ast.sourceSpan, ); } visitTaggedTemplateExpr(ast: o.TaggedTemplateExpr, context: Context): TExpression { return this.setSourceMapRange( this.createTaggedTemplateExpression(ast.tag.visitExpression(this, context), { elements: ast.template.elements.map((e) => createTemplateElement({ cooked: e.text, raw: e.rawText, range: e.sourceSpan ?? ast.sourceSpan, }), ), expressions: ast.template.expressions.map((e) => e.visitExpression(this, context)), }), ast.sourceSpan, ); } visitInstantiateExpr(ast: o.InstantiateExpr, context: Context): TExpression { return this.factory.createNewExpression( ast.classExpr.visitExpression(this, context), ast.args.map((arg) => arg.visitExpression(this, context)), ); } visitLiteralExpr(ast: o.LiteralExpr, _context: Context): TExpression { return this.setSourceMapRange(this.factory.createLiteral(ast.value), ast.sourceSpan); } visitLocalizedString(ast: o.LocalizedString, context: Context): TExpression { // A `$localize` message consists of `messageParts` and `expressions`, which get interleaved // together. The interleaved pieces look like: // `[messagePart0, expression0, messagePart1, expression1, messagePart2]` // // Note that there is always a message part at the start and end, and so therefore // `messageParts.length === expressions.length + 1`. // // Each message part may be prefixed with "metadata", which is wrapped in colons (:) delimiters. // The metadata is attached to the first and subsequent message parts by calls to // `serializeI18nHead()` and `serializeI18nTemplatePart()` respectively. // // The first message part (i.e. `ast.messageParts[0]`) is used to initialize `messageParts` // array. const elements: TemplateElement[] = [createTemplateElement(ast.serializeI18nHead())]; const expressions: TExpression[] = []; for (let i = 0; i < ast.expressions.length; i++) { const placeholder = this.setSourceMapRange( ast.expressions[i].visitExpression(this, context), ast.getPlaceholderSourceSpan(i), ); expressions.push(placeholder); elements.push(createTemplateElement(ast.serializeI18nTemplatePart(i + 1))); } const localizeTag = this.factory.createIdentifier('$localize'); return this.setSourceMapRange( this.createTaggedTemplateExpression(localizeTag, {elements, expressions}), ast.sourceSpan, ); } private createTaggedTemplateExpression( tag: TExpression, template: TemplateLiteral<TExpression>, ): TExpression { return this.downlevelTaggedTemplates ? this.createES5TaggedTemplateFunctionCall(tag, template) : this.factory.createTaggedTemplate(tag, template); } /** * Translate the tagged template literal into a call that is compatible with ES5, using the * imported `__makeTemplateObject` helper for ES5 formatted output. */ private createES5TaggedTemplateFunctionCall( tagHandler: TExpression, {elements, expressions}: TemplateLiteral<TExpression>, ): TExpression { // Ensure that the `__makeTemplateObject()` helper has been imported. const __makeTemplateObjectHelper = this.imports.addImport({ exportModuleSpecifier: 'tslib', exportSymbolName: '__makeTemplateObject', requestedFile: this.contextFile, }); // Collect up the cooked and raw strings into two separate arrays. const cooked: TExpression[] = []; const raw: TExpression[] = []; for (const element of elements) { cooked.push( this.factory.setSourceMapRange(this.factory.createLiteral(element.cooked), element.range), ); raw.push( this.factory.setSourceMapRange(this.factory.createLiteral(element.raw), element.range), ); } // Generate the helper call in the form: `__makeTemplateObject([cooked], [raw]);` const templateHelperCall = this.factory.createCallExpression( __makeTemplateObjectHelper, [this.factory.createArrayLiteral(cooked), this.factory.createArrayLiteral(raw)], /* pure */ false, ); // Finally create the tagged handler call in the form: // `tag(__makeTemplateObject([cooked], [raw]), ...expressions);` return this.factory.createCallExpression( tagHandler, [templateHelperCall, ...expressions], /* pure */ false, ); }
{ "end_byte": 10567, "start_byte": 1690, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/translator.ts_10571_18265
visitExternalExpr(ast: o.ExternalExpr, _context: Context): TExpression { if (ast.value.name === null) { if (ast.value.moduleName === null) { throw new Error('Invalid import without name nor moduleName'); } return this.imports.addImport({ exportModuleSpecifier: ast.value.moduleName, exportSymbolName: null, requestedFile: this.contextFile, }); } // If a moduleName is specified, this is a normal import. If there's no module name, it's a // reference to a global/ambient symbol. if (ast.value.moduleName !== null) { // This is a normal import. Find the imported module. return this.imports.addImport({ exportModuleSpecifier: ast.value.moduleName, exportSymbolName: ast.value.name, requestedFile: this.contextFile, }); } else { // The symbol is ambient, so just reference it. return this.factory.createIdentifier(ast.value.name); } } visitConditionalExpr(ast: o.ConditionalExpr, context: Context): TExpression { let cond: TExpression = ast.condition.visitExpression(this, context); // Ordinarily the ternary operator is right-associative. The following are equivalent: // `a ? b : c ? d : e` => `a ? b : (c ? d : e)` // // However, occasionally Angular needs to produce a left-associative conditional, such as in // the case of a null-safe navigation production: `{{a?.b ? c : d}}`. This template produces // a ternary of the form: // `a == null ? null : rest of expression` // If the rest of the expression is also a ternary though, this would produce the form: // `a == null ? null : a.b ? c : d` // which, if left as right-associative, would be incorrectly associated as: // `a == null ? null : (a.b ? c : d)` // // In such cases, the left-associativity needs to be enforced with parentheses: // `(a == null ? null : a.b) ? c : d` // // Such parentheses could always be included in the condition (guaranteeing correct behavior) in // all cases, but this has a code size cost. Instead, parentheses are added only when a // conditional expression is directly used as the condition of another. // // TODO(alxhub): investigate better logic for precendence of conditional operators if (ast.condition instanceof o.ConditionalExpr) { // The condition of this ternary needs to be wrapped in parentheses to maintain // left-associativity. cond = this.factory.createParenthesizedExpression(cond); } return this.factory.createConditional( cond, ast.trueCase.visitExpression(this, context), ast.falseCase!.visitExpression(this, context), ); } visitDynamicImportExpr(ast: o.DynamicImportExpr, context: any) { const urlExpression = typeof ast.url === 'string' ? this.factory.createLiteral(ast.url) : ast.url.visitExpression(this, context); if (ast.urlComment) { this.factory.attachComments(urlExpression, [o.leadingComment(ast.urlComment, true)]); } return this.factory.createDynamicImport(urlExpression); } visitNotExpr(ast: o.NotExpr, context: Context): TExpression { return this.factory.createUnaryExpression('!', ast.condition.visitExpression(this, context)); } visitFunctionExpr(ast: o.FunctionExpr, context: Context): TExpression { return this.factory.createFunctionExpression( ast.name ?? null, ast.params.map((param) => param.name), this.factory.createBlock(this.visitStatements(ast.statements, context)), ); } visitArrowFunctionExpr(ast: o.ArrowFunctionExpr, context: any) { return this.factory.createArrowFunctionExpression( ast.params.map((param) => param.name), Array.isArray(ast.body) ? this.factory.createBlock(this.visitStatements(ast.body, context)) : ast.body.visitExpression(this, context), ); } visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, context: Context): TExpression { if (!BINARY_OPERATORS.has(ast.operator)) { throw new Error(`Unknown binary operator: ${o.BinaryOperator[ast.operator]}`); } return this.factory.createBinaryExpression( ast.lhs.visitExpression(this, context), BINARY_OPERATORS.get(ast.operator)!, ast.rhs.visitExpression(this, context), ); } visitReadPropExpr(ast: o.ReadPropExpr, context: Context): TExpression { return this.factory.createPropertyAccess(ast.receiver.visitExpression(this, context), ast.name); } visitReadKeyExpr(ast: o.ReadKeyExpr, context: Context): TExpression { return this.factory.createElementAccess( ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ); } visitLiteralArrayExpr(ast: o.LiteralArrayExpr, context: Context): TExpression { return this.factory.createArrayLiteral( ast.entries.map((expr) => this.setSourceMapRange(expr.visitExpression(this, context), ast.sourceSpan), ), ); } visitLiteralMapExpr(ast: o.LiteralMapExpr, context: Context): TExpression { const properties: ObjectLiteralProperty<TExpression>[] = ast.entries.map((entry) => { return { propertyName: entry.key, quoted: entry.quoted, value: entry.value.visitExpression(this, context), }; }); return this.setSourceMapRange(this.factory.createObjectLiteral(properties), ast.sourceSpan); } visitCommaExpr(ast: o.CommaExpr, context: Context): never { throw new Error('Method not implemented.'); } visitWrappedNodeExpr(ast: o.WrappedNodeExpr<any>, _context: Context): any { this.recordWrappedNode(ast); return ast.node; } visitTypeofExpr(ast: o.TypeofExpr, context: Context): TExpression { return this.factory.createTypeOfExpression(ast.expr.visitExpression(this, context)); } visitUnaryOperatorExpr(ast: o.UnaryOperatorExpr, context: Context): TExpression { if (!UNARY_OPERATORS.has(ast.operator)) { throw new Error(`Unknown unary operator: ${o.UnaryOperator[ast.operator]}`); } return this.factory.createUnaryExpression( UNARY_OPERATORS.get(ast.operator)!, ast.expr.visitExpression(this, context), ); } private visitStatements(statements: o.Statement[], context: Context): TStatement[] { return statements .map((stmt) => stmt.visitStatement(this, context)) .filter((stmt) => stmt !== undefined); } private setSourceMapRange<T extends TExpression | TStatement>( ast: T, span: o.ParseSourceSpan | null, ): T { return this.factory.setSourceMapRange(ast, createRange(span)); } private attachComments( statement: TStatement, leadingComments: o.LeadingComment[] | undefined, ): TStatement { if (leadingComments !== undefined) { this.factory.attachComments(statement, leadingComments); } return statement; } } /** * Convert a cooked-raw string object into one that can be used by the AST factories. */ function createTemplateElement({ cooked, raw, range, }: { cooked: string; raw: string; range: o.ParseSourceSpan | null; }): TemplateElement { return {cooked, raw, range: createRange(range)}; } /** * Convert an OutputAST source-span into a range that can be used by the AST factories. */ function createRange(span: o.ParseSourceSpan | null): SourceMapRange | null { if (span === null) { return null; } const {start, end} = span; const {url, content} = start.file; if (!url) { return null; } return { url, content, start: {offset: start.offset, line: start.line, column: start.col}, end: {offset: end.offset, line: end.line, column: end.col}, }; }
{ "end_byte": 18265, "start_byte": 10571, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/context.ts_0_651
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * The current context of a translator visitor as it traverses the AST tree. * * It tracks whether we are in the process of outputting a statement or an expression. */ export class Context { constructor(readonly isStatement: boolean) {} get withExpressionMode(): Context { return this.isStatement ? new Context(false) : this; } get withStatementMode(): Context { return !this.isStatement ? new Context(true) : this; } }
{ "end_byte": 651, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/context.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/ts_util.ts_0_822
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; /** * Creates a TypeScript node representing a numeric value. */ export function tsNumericExpression(value: number): ts.NumericLiteral | ts.PrefixUnaryExpression { // As of TypeScript 5.3 negative numbers are represented as `prefixUnaryOperator` and passing a // negative number (even as a string) into `createNumericLiteral` will result in an error. if (value < 0) { const operand = ts.factory.createNumericLiteral(Math.abs(value)); return ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, operand); } return ts.factory.createNumericLiteral(value); }
{ "end_byte": 822, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/ts_util.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/typescript_translator.ts_0_1508
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 o from '@angular/compiler'; import ts from 'typescript'; import {ImportGenerator} from './api/import_generator'; import {Context} from './context'; import {ExpressionTranslatorVisitor, TranslatorOptions} from './translator'; import {TypeScriptAstFactory} from './typescript_ast_factory'; export function translateExpression( contextFile: ts.SourceFile, expression: o.Expression, imports: ImportGenerator<ts.SourceFile, ts.Expression>, options: TranslatorOptions<ts.Expression> = {}, ): ts.Expression { return expression.visitExpression( new ExpressionTranslatorVisitor<ts.SourceFile, ts.Statement, ts.Expression>( new TypeScriptAstFactory(options.annotateForClosureCompiler === true), imports, contextFile, options, ), new Context(false), ); } export function translateStatement( contextFile: ts.SourceFile, statement: o.Statement, imports: ImportGenerator<ts.SourceFile, ts.Expression>, options: TranslatorOptions<ts.Expression> = {}, ): ts.Statement { return statement.visitStatement( new ExpressionTranslatorVisitor<ts.SourceFile, ts.Statement, ts.Expression>( new TypeScriptAstFactory(options.annotateForClosureCompiler === true), imports, contextFile, options, ), new Context(true), ); }
{ "end_byte": 1508, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/typescript_translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.ts_0_2165
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import { AstFactory, BinaryOperator, LeadingComment, ObjectLiteralProperty, SourceMapRange, TemplateLiteral, UnaryOperator, VariableDeclarationType, } from './api/ast_factory'; import {tsNumericExpression} from './ts_util'; /** * Different optimizers use different annotations on a function or method call to indicate its pure * status. */ enum PureAnnotation { /** * Closure's annotation for purity is `@pureOrBreakMyCode`, but this needs to be in a semantic * (jsdoc) enabled comment. Thus, the actual comment text for Closure must include the `*` that * turns a `/*` comment into a `/**` comment, as well as surrounding whitespace. */ CLOSURE = '* @pureOrBreakMyCode ', TERSER = '@__PURE__', } const UNARY_OPERATORS: Record<UnaryOperator, ts.PrefixUnaryOperator> = { '+': ts.SyntaxKind.PlusToken, '-': ts.SyntaxKind.MinusToken, '!': ts.SyntaxKind.ExclamationToken, }; const BINARY_OPERATORS: Record<BinaryOperator, ts.BinaryOperator> = { '&&': ts.SyntaxKind.AmpersandAmpersandToken, '>': ts.SyntaxKind.GreaterThanToken, '>=': ts.SyntaxKind.GreaterThanEqualsToken, '&': ts.SyntaxKind.AmpersandToken, '|': ts.SyntaxKind.BarToken, '/': ts.SyntaxKind.SlashToken, '==': ts.SyntaxKind.EqualsEqualsToken, '===': ts.SyntaxKind.EqualsEqualsEqualsToken, '<': ts.SyntaxKind.LessThanToken, '<=': ts.SyntaxKind.LessThanEqualsToken, '-': ts.SyntaxKind.MinusToken, '%': ts.SyntaxKind.PercentToken, '*': ts.SyntaxKind.AsteriskToken, '!=': ts.SyntaxKind.ExclamationEqualsToken, '!==': ts.SyntaxKind.ExclamationEqualsEqualsToken, '||': ts.SyntaxKind.BarBarToken, '+': ts.SyntaxKind.PlusToken, '??': ts.SyntaxKind.QuestionQuestionToken, }; const VAR_TYPES: Record<VariableDeclarationType, ts.NodeFlags> = { 'const': ts.NodeFlags.Const, 'let': ts.NodeFlags.Let, 'var': ts.NodeFlags.None, }; /** * A TypeScript flavoured implementation of the AstFactory. */
{ "end_byte": 2165, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.ts_2166_11255
export class TypeScriptAstFactory implements AstFactory<ts.Statement, ts.Expression> { private externalSourceFiles = new Map<string, ts.SourceMapSource>(); constructor(private annotateForClosureCompiler: boolean) {} attachComments = attachComments; createArrayLiteral = ts.factory.createArrayLiteralExpression; createAssignment(target: ts.Expression, value: ts.Expression): ts.Expression { return ts.factory.createBinaryExpression(target, ts.SyntaxKind.EqualsToken, value); } createBinaryExpression( leftOperand: ts.Expression, operator: BinaryOperator, rightOperand: ts.Expression, ): ts.Expression { return ts.factory.createBinaryExpression(leftOperand, BINARY_OPERATORS[operator], rightOperand); } createBlock(body: ts.Statement[]): ts.Statement { return ts.factory.createBlock(body); } createCallExpression(callee: ts.Expression, args: ts.Expression[], pure: boolean): ts.Expression { const call = ts.factory.createCallExpression(callee, undefined, args); if (pure) { ts.addSyntheticLeadingComment( call, ts.SyntaxKind.MultiLineCommentTrivia, this.annotateForClosureCompiler ? PureAnnotation.CLOSURE : PureAnnotation.TERSER, /* trailing newline */ false, ); } return call; } createConditional( condition: ts.Expression, whenTrue: ts.Expression, whenFalse: ts.Expression, ): ts.Expression { return ts.factory.createConditionalExpression( condition, undefined, whenTrue, undefined, whenFalse, ); } createElementAccess = ts.factory.createElementAccessExpression; createExpressionStatement = ts.factory.createExpressionStatement; createDynamicImport(url: string | ts.Expression) { return ts.factory.createCallExpression( ts.factory.createToken(ts.SyntaxKind.ImportKeyword) as ts.ImportExpression, /* type */ undefined, [typeof url === 'string' ? ts.factory.createStringLiteral(url) : url], ); } createFunctionDeclaration( functionName: string, parameters: string[], body: ts.Statement, ): ts.Statement { if (!ts.isBlock(body)) { throw new Error(`Invalid syntax, expected a block, but got ${ts.SyntaxKind[body.kind]}.`); } return ts.factory.createFunctionDeclaration( undefined, undefined, functionName, undefined, parameters.map((param) => ts.factory.createParameterDeclaration(undefined, undefined, param)), undefined, body, ); } createFunctionExpression( functionName: string | null, parameters: string[], body: ts.Statement, ): ts.Expression { if (!ts.isBlock(body)) { throw new Error(`Invalid syntax, expected a block, but got ${ts.SyntaxKind[body.kind]}.`); } return ts.factory.createFunctionExpression( undefined, undefined, functionName ?? undefined, undefined, parameters.map((param) => ts.factory.createParameterDeclaration(undefined, undefined, param)), undefined, body, ); } createArrowFunctionExpression( parameters: string[], body: ts.Statement | ts.Expression, ): ts.Expression { if (ts.isStatement(body) && !ts.isBlock(body)) { throw new Error(`Invalid syntax, expected a block, but got ${ts.SyntaxKind[body.kind]}.`); } return ts.factory.createArrowFunction( undefined, undefined, parameters.map((param) => ts.factory.createParameterDeclaration(undefined, undefined, param)), undefined, undefined, body, ); } createIdentifier = ts.factory.createIdentifier; createIfStatement( condition: ts.Expression, thenStatement: ts.Statement, elseStatement: ts.Statement | null, ): ts.Statement { return ts.factory.createIfStatement(condition, thenStatement, elseStatement ?? undefined); } createLiteral(value: string | number | boolean | null | undefined): ts.Expression { if (value === undefined) { return ts.factory.createIdentifier('undefined'); } else if (value === null) { return ts.factory.createNull(); } else if (typeof value === 'boolean') { return value ? ts.factory.createTrue() : ts.factory.createFalse(); } else if (typeof value === 'number') { return tsNumericExpression(value); } else { return ts.factory.createStringLiteral(value); } } createNewExpression(expression: ts.Expression, args: ts.Expression[]): ts.Expression { return ts.factory.createNewExpression(expression, undefined, args); } createObjectLiteral(properties: ObjectLiteralProperty<ts.Expression>[]): ts.Expression { return ts.factory.createObjectLiteralExpression( properties.map((prop) => ts.factory.createPropertyAssignment( prop.quoted ? ts.factory.createStringLiteral(prop.propertyName) : ts.factory.createIdentifier(prop.propertyName), prop.value, ), ), ); } createParenthesizedExpression = ts.factory.createParenthesizedExpression; createPropertyAccess = ts.factory.createPropertyAccessExpression; createReturnStatement(expression: ts.Expression | null): ts.Statement { return ts.factory.createReturnStatement(expression ?? undefined); } createTaggedTemplate( tag: ts.Expression, template: TemplateLiteral<ts.Expression>, ): ts.Expression { let templateLiteral: ts.TemplateLiteral; const length = template.elements.length; const head = template.elements[0]; if (length === 1) { templateLiteral = ts.factory.createNoSubstitutionTemplateLiteral(head.cooked, head.raw); } else { const spans: ts.TemplateSpan[] = []; // Create the middle parts for (let i = 1; i < length - 1; i++) { const {cooked, raw, range} = template.elements[i]; const middle = createTemplateMiddle(cooked, raw); if (range !== null) { this.setSourceMapRange(middle, range); } spans.push(ts.factory.createTemplateSpan(template.expressions[i - 1], middle)); } // Create the tail part const resolvedExpression = template.expressions[length - 2]; const templatePart = template.elements[length - 1]; const templateTail = createTemplateTail(templatePart.cooked, templatePart.raw); if (templatePart.range !== null) { this.setSourceMapRange(templateTail, templatePart.range); } spans.push(ts.factory.createTemplateSpan(resolvedExpression, templateTail)); // Put it all together templateLiteral = ts.factory.createTemplateExpression( ts.factory.createTemplateHead(head.cooked, head.raw), spans, ); } if (head.range !== null) { this.setSourceMapRange(templateLiteral, head.range); } return ts.factory.createTaggedTemplateExpression(tag, undefined, templateLiteral); } createThrowStatement = ts.factory.createThrowStatement; createTypeOfExpression = ts.factory.createTypeOfExpression; createUnaryExpression(operator: UnaryOperator, operand: ts.Expression): ts.Expression { return ts.factory.createPrefixUnaryExpression(UNARY_OPERATORS[operator], operand); } createVariableDeclaration( variableName: string, initializer: ts.Expression | null, type: VariableDeclarationType, ): ts.Statement { return ts.factory.createVariableStatement( undefined, ts.factory.createVariableDeclarationList( [ ts.factory.createVariableDeclaration( variableName, undefined, undefined, initializer ?? undefined, ), ], VAR_TYPES[type], ), ); } setSourceMapRange<T extends ts.Node>(node: T, sourceMapRange: SourceMapRange | null): T { if (sourceMapRange === null) { return node; } const url = sourceMapRange.url; if (!this.externalSourceFiles.has(url)) { this.externalSourceFiles.set( url, ts.createSourceMapSource(url, sourceMapRange.content, (pos) => pos), ); } const source = this.externalSourceFiles.get(url); ts.setSourceMapRange(node, { pos: sourceMapRange.start.offset, end: sourceMapRange.end.offset, source, }); return node; } } // HACK: Use this in place of `ts.createTemplateMiddle()`. // Revert once https://github.com/microsoft/TypeScript/issues/35374 is fixed. export function createTemplateMiddle(cooked: string, raw: string): ts.TemplateMiddle { const node: ts.TemplateLiteralLikeNode = ts.factory.createTemplateHead(cooked, raw); (node.kind as ts.SyntaxKind) = ts.SyntaxKind.TemplateMiddle; return node as ts.TemplateMiddle; } // HACK: Use this in place of `ts.createTemplateTail()`. // Revert once https://github.com/microsoft/TypeScript/issues/35374 is fixed. export function createTemplateTail(cooked: string, raw: string): ts.TemplateTail { const node: ts.TemplateLiteralLikeNode = ts.factory.createTemplateHead(cooked, raw); (node.kind as ts.SyntaxKind) = ts.SyntaxKind.TemplateTail; return node as ts.TemplateTail; }
{ "end_byte": 11255, "start_byte": 2166, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.ts_11257_12126
/** * Attach the given `leadingComments` to the `statement` node. * * @param statement The statement that will have comments attached. * @param leadingComments The comments to attach to the statement. */ export function attachComments( statement: ts.Statement | ts.Expression, leadingComments: LeadingComment[], ): void { for (const comment of leadingComments) { const commentKind = comment.multiline ? ts.SyntaxKind.MultiLineCommentTrivia : ts.SyntaxKind.SingleLineCommentTrivia; if (comment.multiline) { ts.addSyntheticLeadingComment( statement, commentKind, comment.toString(), comment.trailingNewline, ); } else { for (const line of comment.toString().split('\n')) { ts.addSyntheticLeadingComment(statement, commentKind, line, comment.trailingNewline); } } } }
{ "end_byte": 12126, "start_byte": 11257, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/type_translator.ts_0_971
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 o from '@angular/compiler'; import ts from 'typescript'; import { assertSuccessfulReferenceEmit, ImportFlags, OwningModule, Reference, ReferenceEmitter, } from '../../imports'; import {AmbientImport, ReflectionHost} from '../../reflection'; import {Context} from './context'; import {ImportManager} from './import_manager/import_manager'; import {tsNumericExpression} from './ts_util'; import {TypeEmitter} from './type_emitter'; export function translateType( type: o.Type, contextFile: ts.SourceFile, reflector: ReflectionHost, refEmitter: ReferenceEmitter, imports: ImportManager, ): ts.TypeNode { return type.visitType( new TypeTranslatorVisitor(imports, contextFile, reflector, refEmitter), new Context(false), ); }
{ "end_byte": 971, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/type_translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/type_translator.ts_973_9489
class TypeTranslatorVisitor implements o.ExpressionVisitor, o.TypeVisitor { constructor( private imports: ImportManager, private contextFile: ts.SourceFile, private reflector: ReflectionHost, private refEmitter: ReferenceEmitter, ) {} visitBuiltinType(type: o.BuiltinType, context: Context): ts.KeywordTypeNode { switch (type.name) { case o.BuiltinTypeName.Bool: return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword); case o.BuiltinTypeName.Dynamic: return ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); case o.BuiltinTypeName.Int: case o.BuiltinTypeName.Number: return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword); case o.BuiltinTypeName.String: return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword); case o.BuiltinTypeName.None: return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword); default: throw new Error(`Unsupported builtin type: ${o.BuiltinTypeName[type.name]}`); } } visitExpressionType(type: o.ExpressionType, context: Context): ts.TypeNode { const typeNode = this.translateExpression(type.value, context); if (type.typeParams === null) { return typeNode; } if (!ts.isTypeReferenceNode(typeNode)) { throw new Error( 'An ExpressionType with type arguments must translate into a TypeReferenceNode', ); } else if (typeNode.typeArguments !== undefined) { throw new Error( `An ExpressionType with type arguments cannot have multiple levels of type arguments`, ); } const typeArgs = type.typeParams.map((param) => this.translateType(param, context)); return ts.factory.createTypeReferenceNode(typeNode.typeName, typeArgs); } visitArrayType(type: o.ArrayType, context: Context): ts.ArrayTypeNode { return ts.factory.createArrayTypeNode(this.translateType(type.of, context)); } visitMapType(type: o.MapType, context: Context): ts.TypeLiteralNode { const parameter = ts.factory.createParameterDeclaration( undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), ); const typeArgs = type.valueType !== null ? this.translateType(type.valueType, context) : ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword); const indexSignature = ts.factory.createIndexSignature(undefined, [parameter], typeArgs); return ts.factory.createTypeLiteralNode([indexSignature]); } visitTransplantedType(ast: o.TransplantedType<unknown>, context: Context) { const node = ast.type instanceof Reference ? ast.type.node : ast.type; if (!ts.isTypeNode(node)) { throw new Error(`A TransplantedType must wrap a TypeNode`); } const viaModule = ast.type instanceof Reference ? ast.type.bestGuessOwningModule : null; const emitter = new TypeEmitter((typeRef) => this.translateTypeReference(typeRef, context, viaModule), ); return emitter.emitType(node); } visitReadVarExpr(ast: o.ReadVarExpr, context: Context): ts.TypeQueryNode { if (ast.name === null) { throw new Error(`ReadVarExpr with no variable name in type`); } return ts.factory.createTypeQueryNode(ts.factory.createIdentifier(ast.name)); } visitWriteVarExpr(expr: o.WriteVarExpr, context: Context): never { throw new Error('Method not implemented.'); } visitWriteKeyExpr(expr: o.WriteKeyExpr, context: Context): never { throw new Error('Method not implemented.'); } visitWritePropExpr(expr: o.WritePropExpr, context: Context): never { throw new Error('Method not implemented.'); } visitInvokeFunctionExpr(ast: o.InvokeFunctionExpr, context: Context): never { throw new Error('Method not implemented.'); } visitTaggedTemplateExpr(ast: o.TaggedTemplateExpr, context: Context): never { throw new Error('Method not implemented.'); } visitInstantiateExpr(ast: o.InstantiateExpr, context: Context): never { throw new Error('Method not implemented.'); } visitLiteralExpr(ast: o.LiteralExpr, context: Context): ts.TypeNode { if (ast.value === null) { return ts.factory.createLiteralTypeNode(ts.factory.createNull()); } else if (ast.value === undefined) { return ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword); } else if (typeof ast.value === 'boolean') { return ts.factory.createLiteralTypeNode( ast.value ? ts.factory.createTrue() : ts.factory.createFalse(), ); } else if (typeof ast.value === 'number') { return ts.factory.createLiteralTypeNode(tsNumericExpression(ast.value)); } else { return ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(ast.value)); } } visitLocalizedString(ast: o.LocalizedString, context: Context): never { throw new Error('Method not implemented.'); } visitExternalExpr(ast: o.ExternalExpr, context: Context): ts.EntityName | ts.TypeReferenceNode { if (ast.value.moduleName === null || ast.value.name === null) { throw new Error(`Import unknown module or symbol`); } const typeName = this.imports.addImport({ exportModuleSpecifier: ast.value.moduleName, exportSymbolName: ast.value.name, requestedFile: this.contextFile, asTypeReference: true, }); const typeArguments = ast.typeParams !== null ? ast.typeParams.map((type) => this.translateType(type, context)) : undefined; return ts.factory.createTypeReferenceNode(typeName, typeArguments); } visitConditionalExpr(ast: o.ConditionalExpr, context: Context) { throw new Error('Method not implemented.'); } visitDynamicImportExpr(ast: o.outputAst.DynamicImportExpr, context: any) { throw new Error('Method not implemented.'); } visitNotExpr(ast: o.NotExpr, context: Context) { throw new Error('Method not implemented.'); } visitFunctionExpr(ast: o.FunctionExpr, context: Context) { throw new Error('Method not implemented.'); } visitArrowFunctionExpr(ast: o.ArrowFunctionExpr, context: any) { throw new Error('Method not implemented.'); } visitUnaryOperatorExpr(ast: o.UnaryOperatorExpr, context: Context) { throw new Error('Method not implemented.'); } visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, context: Context) { throw new Error('Method not implemented.'); } visitReadPropExpr(ast: o.ReadPropExpr, context: Context) { throw new Error('Method not implemented.'); } visitReadKeyExpr(ast: o.ReadKeyExpr, context: Context) { throw new Error('Method not implemented.'); } visitLiteralArrayExpr(ast: o.LiteralArrayExpr, context: Context): ts.TupleTypeNode { const values = ast.entries.map((expr) => this.translateExpression(expr, context)); return ts.factory.createTupleTypeNode(values); } visitLiteralMapExpr(ast: o.LiteralMapExpr, context: Context): ts.TypeLiteralNode { const entries = ast.entries.map((entry) => { const {key, quoted} = entry; const type = this.translateExpression(entry.value, context); return ts.factory.createPropertySignature( /* modifiers */ undefined, /* name */ quoted ? ts.factory.createStringLiteral(key) : key, /* questionToken */ undefined, /* type */ type, ); }); return ts.factory.createTypeLiteralNode(entries); } visitCommaExpr(ast: o.CommaExpr, context: Context) { throw new Error('Method not implemented.'); } visitWrappedNodeExpr(ast: o.WrappedNodeExpr<any>, context: Context): ts.TypeNode { const node: ts.Node = ast.node; if (ts.isEntityName(node)) { return ts.factory.createTypeReferenceNode(node, /* typeArguments */ undefined); } else if (ts.isTypeNode(node)) { return node; } else if (ts.isLiteralExpression(node)) { return ts.factory.createLiteralTypeNode(node); } else { throw new Error( `Unsupported WrappedNodeExpr in TypeTranslatorVisitor: ${ts.SyntaxKind[node.kind]}`, ); } } visitTypeofExpr(ast: o.TypeofExpr, context: Context): ts.TypeQueryNode { const typeNode = this.translateExpression(ast.expr, context); if (!ts.isTypeReferenceNode(typeNode)) { throw new Error(`The target of a typeof expression must be a type reference, but it was ${ts.SyntaxKind[typeNode.kind]}`); } return ts.factory.createTypeQueryNode(typeNode.typeName); }
{ "end_byte": 9489, "start_byte": 973, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/type_translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/type_translator.ts_9493_11541
private translateType(type: o.Type, context: Context): ts.TypeNode { const typeNode = type.visitType(this, context); if (!ts.isTypeNode(typeNode)) { throw new Error( `A Type must translate to a TypeNode, but was ${ts.SyntaxKind[typeNode.kind]}`, ); } return typeNode; } private translateExpression(expr: o.Expression, context: Context): ts.TypeNode { const typeNode = expr.visitExpression(this, context); if (!ts.isTypeNode(typeNode)) { throw new Error( `An Expression must translate to a TypeNode, but was ${ts.SyntaxKind[typeNode.kind]}`, ); } return typeNode; } private translateTypeReference( type: ts.TypeReferenceNode, context: Context, viaModule: OwningModule | null, ): ts.TypeReferenceNode | null { const target = ts.isIdentifier(type.typeName) ? type.typeName : type.typeName.right; const declaration = this.reflector.getDeclarationOfIdentifier(target); if (declaration === null) { throw new Error( `Unable to statically determine the declaration file of type node ${target.text}`, ); } let owningModule = viaModule; if (typeof declaration.viaModule === 'string') { owningModule = { specifier: declaration.viaModule, resolutionContext: type.getSourceFile().fileName, }; } const reference = new Reference( declaration.node, declaration.viaModule === AmbientImport ? AmbientImport : owningModule, ); const emittedType = this.refEmitter.emit( reference, this.contextFile, ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowAmbientReferences, ); assertSuccessfulReferenceEmit(emittedType, target, 'type'); const typeNode = this.translateExpression(emittedType.expression, context); if (!ts.isTypeReferenceNode(typeNode)) { throw new Error( `Expected TypeReferenceNode for emitted reference, got ${ts.SyntaxKind[typeNode.kind]}.`, ); } return typeNode; } }
{ "end_byte": 11541, "start_byte": 9493, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/type_translator.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/type_emitter.ts_0_6987
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; /** * A type reference resolver function is responsible for translating a type reference from the * origin source file into a type reference that is valid in the desired source file. If the type * cannot be translated to the desired source file, then null can be returned. */ export type TypeReferenceTranslator = (type: ts.TypeReferenceNode) => ts.TypeReferenceNode | null; /** * A marker to indicate that a type reference is ineligible for emitting. This needs to be truthy * as it's returned from `ts.forEachChild`, which only returns truthy values. */ type INELIGIBLE = { __brand: 'ineligible'; }; const INELIGIBLE: INELIGIBLE = {} as INELIGIBLE; /** * Determines whether the provided type can be emitted, which means that it can be safely emitted * into a different location. * * If this function returns true, a `TypeEmitter` should be able to succeed. Vice versa, if this * function returns false, then using the `TypeEmitter` should not be attempted as it is known to * fail. */ export function canEmitType( type: ts.TypeNode, canEmit: (type: ts.TypeReferenceNode) => boolean, ): boolean { return canEmitTypeWorker(type); function canEmitTypeWorker(type: ts.TypeNode): boolean { return visitNode(type) !== INELIGIBLE; } // To determine whether a type can be emitted, we have to recursively look through all type nodes. // If an unsupported type node is found at any position within the type, then the `INELIGIBLE` // constant is returned to stop the recursive walk as the type as a whole cannot be emitted in // that case. Otherwise, the result of visiting all child nodes determines the result. If no // ineligible type reference node is found then the walk returns `undefined`, indicating that // no type node was visited that could not be emitted. function visitNode(node: ts.Node): INELIGIBLE | undefined { // `import('module')` type nodes are not supported, as it may require rewriting the module // specifier which is currently not done. if (ts.isImportTypeNode(node)) { return INELIGIBLE; } // Emitting a type reference node in a different context requires that an import for the type // can be created. If a type reference node cannot be emitted, `INELIGIBLE` is returned to stop // the walk. if (ts.isTypeReferenceNode(node) && !canEmitTypeReference(node)) { return INELIGIBLE; } else { return ts.forEachChild(node, visitNode); } } function canEmitTypeReference(type: ts.TypeReferenceNode): boolean { if (!canEmit(type)) { return false; } // The type can be emitted if either it does not have any type arguments, or all of them can be // emitted. return type.typeArguments === undefined || type.typeArguments.every(canEmitTypeWorker); } } /** * Given a `ts.TypeNode`, this class derives an equivalent `ts.TypeNode` that has been emitted into * a different context. * * For example, consider the following code: * * ``` * import {NgIterable} from '@angular/core'; * * class NgForOf<T, U extends NgIterable<T>> {} * ``` * * Here, the generic type parameters `T` and `U` can be emitted into a different context, as the * type reference to `NgIterable` originates from an absolute module import so that it can be * emitted anywhere, using that same module import. The process of emitting translates the * `NgIterable` type reference to a type reference that is valid in the context in which it is * emitted, for example: * * ``` * import * as i0 from '@angular/core'; * import * as i1 from '@angular/common'; * * const _ctor1: <T, U extends i0.NgIterable<T>>(o: Pick<i1.NgForOf<T, U>, 'ngForOf'>): * i1.NgForOf<T, U>; * ``` * * Notice how the type reference for `NgIterable` has been translated into a qualified name, * referring to the namespace import that was created. */ export class TypeEmitter { constructor(private translator: TypeReferenceTranslator) {} emitType(type: ts.TypeNode): ts.TypeNode { const typeReferenceTransformer: ts.TransformerFactory<ts.TypeNode> = (context) => { const visitNode = (node: ts.Node): ts.Node => { if (ts.isImportTypeNode(node)) { throw new Error('Unable to emit import type'); } if (ts.isTypeReferenceNode(node)) { return this.emitTypeReference(node); } else if (ts.isLiteralExpression(node)) { // TypeScript would typically take the emit text for a literal expression from the source // file itself. As the type node is being emitted into a different file, however, // TypeScript would extract the literal text from the wrong source file. To mitigate this // issue the literal is cloned and explicitly marked as synthesized by setting its text // range to a negative range, forcing TypeScript to determine the node's literal text from // the synthesized node's text instead of the incorrect source file. let clone: ts.LiteralExpression; if (ts.isStringLiteral(node)) { clone = ts.factory.createStringLiteral(node.text); } else if (ts.isNumericLiteral(node)) { clone = ts.factory.createNumericLiteral(node.text); } else if (ts.isBigIntLiteral(node)) { clone = ts.factory.createBigIntLiteral(node.text); } else if (ts.isNoSubstitutionTemplateLiteral(node)) { clone = ts.factory.createNoSubstitutionTemplateLiteral(node.text, node.rawText); } else if (ts.isRegularExpressionLiteral(node)) { clone = ts.factory.createRegularExpressionLiteral(node.text); } else { throw new Error(`Unsupported literal kind ${ts.SyntaxKind[node.kind]}`); } ts.setTextRange(clone, {pos: -1, end: -1}); return clone; } else { return ts.visitEachChild(node, visitNode, context); } }; return (node) => ts.visitNode(node, visitNode, ts.isTypeNode); }; return ts.transform(type, [typeReferenceTransformer]).transformed[0]; } private emitTypeReference(type: ts.TypeReferenceNode): ts.TypeNode { // Determine the reference that the type corresponds with. const translatedType = this.translator(type); if (translatedType === null) { throw new Error('Unable to emit an unresolved reference'); } // Emit the type arguments, if any. let typeArguments: ts.NodeArray<ts.TypeNode> | undefined = undefined; if (type.typeArguments !== undefined) { typeArguments = ts.factory.createNodeArray( type.typeArguments.map((typeArg) => this.emitType(typeArg)), ); } return ts.factory.updateTypeReferenceNode(type, translatedType.typeName, typeArguments); } }
{ "end_byte": 6987, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/type_emitter.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/reuse_source_file_imports.ts_0_5930
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {AliasImportDeclaration} from '../../../imports'; import {ImportRequest} from '../api/import_generator'; /** * Tracker necessary for enabling re-use of original source file imports. * * The tracker holds information about original source file imports that * need to be updated, or import declarations/specifiers that are now * referenced due to the import manager. */ export interface ReuseExistingSourceFileImportsTracker { /** * Map of import declarations that need to be updated to include the * given symbols. */ updatedImports: Map< ts.ImportDeclaration, {propertyName: ts.Identifier; fileUniqueAlias: ts.Identifier | null}[] >; /** * Set of re-used alias import declarations. * * These are captured so that we can tell TypeScript to not elide these source file * imports as we introduced references to them. More details: {@link AliasImportDeclaration}. */ reusedAliasDeclarations: Set<AliasImportDeclaration>; /** Generates a unique identifier for a name in the given file. */ generateUniqueIdentifier(file: ts.SourceFile, symbolName: string): ts.Identifier | null; } /** Attempts to re-use original source file imports for the given request. */ export function attemptToReuseExistingSourceFileImports( tracker: ReuseExistingSourceFileImportsTracker, sourceFile: ts.SourceFile, request: ImportRequest<ts.SourceFile>, ): ts.Identifier | [ts.Identifier, ts.Identifier] | null { // Walk through all source-file top-level statements and search for import declarations // that already match the specified "moduleName" and can be updated to import the // given symbol. If no matching import can be found, the last import in the source-file // will be used as starting point for a new import that will be generated. let candidateImportToBeUpdated: ts.ImportDeclaration | null = null; for (let i = sourceFile.statements.length - 1; i >= 0; i--) { const statement = sourceFile.statements[i]; if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) { continue; } // Side-effect imports are ignored, or type-only imports. // TODO: Consider re-using type-only imports efficiently. if (!statement.importClause || statement.importClause.isTypeOnly) { continue; } const moduleSpecifier = statement.moduleSpecifier.text; // If the import does not match the module name, or requested target file, continue. // Note: In the future, we may consider performing better analysis here. E.g. resolve paths, // or try to detect re-usable symbols via type-checking. if (moduleSpecifier !== request.exportModuleSpecifier) { continue; } if (statement.importClause.namedBindings) { const namedBindings = statement.importClause.namedBindings; // A namespace import can be reused. if (ts.isNamespaceImport(namedBindings)) { tracker.reusedAliasDeclarations.add(namedBindings); if (request.exportSymbolName === null) { return namedBindings.name; } return [namedBindings.name, ts.factory.createIdentifier(request.exportSymbolName)]; } // Named imports can be re-used if a specific symbol is requested. if (ts.isNamedImports(namedBindings) && request.exportSymbolName !== null) { const existingElement = namedBindings.elements.find((e) => { // TODO: Consider re-using type-only imports efficiently. let nameMatches: boolean; if (request.unsafeAliasOverride) { // If a specific alias is passed, both the original name and alias have to match. nameMatches = e.propertyName?.text === request.exportSymbolName && e.name.text === request.unsafeAliasOverride; } else { nameMatches = e.propertyName ? e.propertyName.text === request.exportSymbolName : e.name.text === request.exportSymbolName; } return !e.isTypeOnly && nameMatches; }); if (existingElement !== undefined) { tracker.reusedAliasDeclarations.add(existingElement); return existingElement.name; } // In case the symbol could not be found in an existing import, we // keep track of the import declaration as it can be updated to include // the specified symbol name without having to create a new import. candidateImportToBeUpdated = statement; } } } if (candidateImportToBeUpdated === null || request.exportSymbolName === null) { return null; } // We have a candidate import. Update it to import what we need. if (!tracker.updatedImports.has(candidateImportToBeUpdated)) { tracker.updatedImports.set(candidateImportToBeUpdated, []); } const symbolsToBeImported = tracker.updatedImports.get(candidateImportToBeUpdated)!; const propertyName = ts.factory.createIdentifier(request.exportSymbolName); const fileUniqueAlias = request.unsafeAliasOverride ? ts.factory.createIdentifier(request.unsafeAliasOverride) : tracker.generateUniqueIdentifier(sourceFile, request.exportSymbolName); // Since it can happen that multiple classes need to be imported within the // specified source file and we want to add the identifiers to the existing // import declaration, we need to keep track of the updated import declarations. // We can't directly update the import declaration for each identifier as this // would not be reflected in the AST— or would throw of update recording offsets. symbolsToBeImported.push({ propertyName, fileUniqueAlias, }); return fileUniqueAlias ?? propertyName; }
{ "end_byte": 5930, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/reuse_source_file_imports.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/check_unique_identifier_name.ts_0_1882
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import type {ImportManagerConfig} from './import_manager'; /** Extension of `ts.SourceFile` with metadata fields that are marked as internal. */ interface SourceFileWithIdentifiers extends ts.SourceFile { /** List of all identifiers encountered while parsing the source file. */ identifiers?: Map<string, string>; } /** * Generates a helper for `ImportManagerConfig` to generate unique identifiers * for a given source file. */ export function createGenerateUniqueIdentifierHelper(): ImportManagerConfig['generateUniqueIdentifier'] { const generatedIdentifiers = new Set<string>(); const isGeneratedIdentifier = (sf: ts.SourceFile, identifierName: string) => generatedIdentifiers.has(`${sf.fileName}@@${identifierName}`); const markIdentifierAsGenerated = (sf: ts.SourceFile, identifierName: string) => generatedIdentifiers.add(`${sf.fileName}@@${identifierName}`); return (sourceFile: ts.SourceFile, symbolName: string) => { const sf = sourceFile as SourceFileWithIdentifiers; if (sf.identifiers === undefined) { throw new Error('Source file unexpectedly lacks map of parsed `identifiers`.'); } const isUniqueIdentifier = (name: string) => !sf.identifiers!.has(name) && !isGeneratedIdentifier(sf, name); if (isUniqueIdentifier(symbolName)) { markIdentifierAsGenerated(sf, symbolName); return null; } let name = null; let counter = 1; do { name = `${symbolName}_${counter++}`; } while (!isUniqueIdentifier(name)); markIdentifierAsGenerated(sf, name); return ts.factory.createUniqueName(name, ts.GeneratedIdentifierFlags.Optimistic); }; }
{ "end_byte": 1882, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/check_unique_identifier_name.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/reuse_generated_imports.ts_0_2937
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {ImportRequest} from '../api/import_generator'; import type {ModuleName} from './import_manager'; /** Branded string identifying a hashed {@link ImportRequest}. */ type ImportRequestHash = string & {__importHash: string}; /** Tracker capturing re-used generated imports. */ export interface ReuseGeneratedImportsTracker { /** * Map of previously resolved symbol imports. Cache can be re-used to return * the same identifier without checking the source-file again. */ directReuseCache: Map<ImportRequestHash, ts.Identifier | [ts.Identifier, ts.Identifier]>; /** * Map of module names and their potential namespace import * identifiers. Allows efficient re-using of namespace imports. */ namespaceImportReuseCache: Map<ModuleName, ts.Identifier>; } /** Attempts to efficiently re-use previous generated import requests. */ export function attemptToReuseGeneratedImports( tracker: ReuseGeneratedImportsTracker, request: ImportRequest<ts.SourceFile>, ): ts.Identifier | [ts.Identifier, ts.Identifier] | null { const requestHash = hashImportRequest(request); // In case the given import has been already generated previously, we just return // the previous generated identifier in order to avoid duplicate generated imports. const existingExactImport = tracker.directReuseCache.get(requestHash); if (existingExactImport !== undefined) { return existingExactImport; } const potentialNamespaceImport = tracker.namespaceImportReuseCache.get( request.exportModuleSpecifier as ModuleName, ); if (potentialNamespaceImport === undefined) { return null; } if (request.exportSymbolName === null) { return potentialNamespaceImport; } return [potentialNamespaceImport, ts.factory.createIdentifier(request.exportSymbolName)]; } /** Captures the given import request and its generated reference node/path for future re-use. */ export function captureGeneratedImport( request: ImportRequest<ts.SourceFile>, tracker: ReuseGeneratedImportsTracker, referenceNode: ts.Identifier | [ts.Identifier, ts.Identifier], ) { tracker.directReuseCache.set(hashImportRequest(request), referenceNode); if (request.exportSymbolName === null && !Array.isArray(referenceNode)) { tracker.namespaceImportReuseCache.set( request.exportModuleSpecifier as ModuleName, referenceNode, ); } } /** Generates a unique hash for the given import request. */ function hashImportRequest(req: ImportRequest<ts.SourceFile>): ImportRequestHash { return `${req.requestedFile.fileName}:${req.exportModuleSpecifier}:${req.exportSymbolName}${ req.unsafeAliasOverride ? ':' + req.unsafeAliasOverride : '' }` as ImportRequestHash; }
{ "end_byte": 2937, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/reuse_generated_imports.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_typescript_transform.ts_0_4638
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {loadIsReferencedAliasDeclarationPatch} from '../../../imports'; import type {ImportManager} from './import_manager'; /** * Creates a TypeScript transform for the given import manager. * * - The transform updates existing imports with new symbols to be added. * - The transform adds new necessary imports. * - The transform inserts additional optional statements after imports. * - The transform deletes any nodes that are marked for deletion by the manager. */ export function createTsTransformForImportManager( manager: ImportManager, extraStatementsForFiles?: Map<string, ts.Statement[]>, ): ts.TransformerFactory<ts.SourceFile> { return (ctx) => { const { affectedFiles, newImports, updatedImports, reusedOriginalAliasDeclarations, deletedImports, } = manager.finalize(); // If we re-used existing source file alias declarations, mark those as referenced so TypeScript // doesn't drop these thinking they are unused. if (reusedOriginalAliasDeclarations.size > 0) { const referencedAliasDeclarations = loadIsReferencedAliasDeclarationPatch(ctx); reusedOriginalAliasDeclarations.forEach((aliasDecl) => referencedAliasDeclarations.add(aliasDecl), ); } // Update the set of affected files to include files that need extra statements to be inserted. if (extraStatementsForFiles !== undefined) { for (const [fileName, statements] of extraStatementsForFiles.entries()) { if (statements.length > 0) { affectedFiles.add(fileName); } } } const visitStatement: ts.Visitor<ts.Node, ts.Node | undefined> = (node) => { if (!ts.isImportDeclaration(node)) { return node; } if (deletedImports.has(node)) { return undefined; } if (node.importClause === undefined || !ts.isImportClause(node.importClause)) { return node; } const clause = node.importClause; if ( clause.namedBindings === undefined || !ts.isNamedImports(clause.namedBindings) || !updatedImports.has(clause.namedBindings) ) { return node; } const newClause = ctx.factory.updateImportClause( clause, clause.isTypeOnly, clause.name, updatedImports.get(clause.namedBindings), ); const newImport = ctx.factory.updateImportDeclaration( node, node.modifiers, newClause, node.moduleSpecifier, node.attributes, ); // This tricks TypeScript into thinking that the `importClause` is still optimizable. // By default, TS assumes, no specifiers are elide-able if the clause of the "original // node" has changed. google3: // typescript/unstable/src/compiler/transformers/ts.ts;l=456;rcl=611254538. ts.setOriginalNode(newImport, { importClause: newClause, kind: newImport.kind, } as Partial<ts.ImportDeclaration> as any); return newImport; }; return (sourceFile) => { if (!affectedFiles.has(sourceFile.fileName)) { return sourceFile; } sourceFile = ts.visitEachChild(sourceFile, visitStatement, ctx); // Filter out the existing imports and the source file body. // All new statements will be inserted between them. const extraStatements = extraStatementsForFiles?.get(sourceFile.fileName) ?? []; const existingImports: ts.Statement[] = []; const body: ts.Statement[] = []; for (const statement of sourceFile.statements) { if (isImportStatement(statement)) { existingImports.push(statement); } else { body.push(statement); } } return ctx.factory.updateSourceFile( sourceFile, [ ...existingImports, ...(newImports.get(sourceFile.fileName) ?? []), ...extraStatements, ...body, ], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives, ); }; }; } /** Whether the given statement is an import statement. */ function isImportStatement(stmt: ts.Statement): boolean { return ( ts.isImportDeclaration(stmt) || ts.isImportEqualsDeclaration(stmt) || ts.isNamespaceImport(stmt) ); }
{ "end_byte": 4638, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_typescript_transform.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.ts_0_2338
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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'; import {AliasImportDeclaration, ImportRewriter} from '../../../imports'; import {ImportGenerator, ImportRequest} from '../api/import_generator'; import {createGenerateUniqueIdentifierHelper} from './check_unique_identifier_name'; import {createTsTransformForImportManager} from './import_typescript_transform'; import { attemptToReuseGeneratedImports, captureGeneratedImport, ReuseGeneratedImportsTracker, } from './reuse_generated_imports'; import { attemptToReuseExistingSourceFileImports, ReuseExistingSourceFileImportsTracker, } from './reuse_source_file_imports'; /** Configuration for the import manager. */ export interface ImportManagerConfig { generateUniqueIdentifier(file: ts.SourceFile, baseName: string): ts.Identifier | null; shouldUseSingleQuotes(file: ts.SourceFile): boolean; rewriter: ImportRewriter | null; namespaceImportPrefix: string; disableOriginalSourceFileReuse: boolean; forceGenerateNamespacesForNewImports: boolean; } /** * Preset configuration for forcing namespace imports. * * This preset is commonly used to avoid test differences to previous * versions of the `ImportManager`. */ export const presetImportManagerForceNamespaceImports: Partial<ImportManagerConfig> = { // Forcing namespace imports also means no-reuse. // Re-using would otherwise become more complicated and we don't // expect re-usable namespace imports. disableOriginalSourceFileReuse: true, forceGenerateNamespacesForNewImports: true, }; /** Branded string to identify a module name. */ export type ModuleName = string & {__moduleName: boolean}; /** * Import manager that can be used to conveniently and efficiently generate * imports It efficiently re-uses existing source file imports, or previous * generated imports. * * These capabilities are important for efficient TypeScript transforms that * minimize structural changes to the dependency graph of source files, enabling * as much incremental re-use as possible. * * Those imports may be inserted via a TypeScript transform, or via manual string * manipulation using e.g. `magic-string`. */
{ "end_byte": 2338, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.ts_2339_11302
export class ImportManager implements ImportGenerator<ts.SourceFile, ts.Identifier | ts.PropertyAccessExpression> { /** List of new imports that will be inserted into given source files. */ private newImports: Map< ts.SourceFile, { namespaceImports: Map<ModuleName, ts.NamespaceImport>; namedImports: Map<ModuleName, ts.ImportSpecifier[]>; sideEffectImports: Set<ModuleName>; } > = new Map(); /** * Keeps track of imports marked for removal. The root-level key is the file from which the * import should be removed, the inner map key is the name of the module from which the symbol * is being imported. The value of the inner map is a set of symbol names that should be removed. * Note! the inner map tracks the original names of the imported symbols, not their local aliases. */ private removedImports: Map<ts.SourceFile, Map<ModuleName, Set<string>>> = new Map(); private nextUniqueIndex = 0; private config: ImportManagerConfig; private reuseSourceFileImportsTracker: ReuseExistingSourceFileImportsTracker; private reuseGeneratedImportsTracker: ReuseGeneratedImportsTracker = { directReuseCache: new Map(), namespaceImportReuseCache: new Map(), }; constructor(config: Partial<ImportManagerConfig> = {}) { this.config = { shouldUseSingleQuotes: config.shouldUseSingleQuotes ?? (() => false), rewriter: config.rewriter ?? null, disableOriginalSourceFileReuse: config.disableOriginalSourceFileReuse ?? false, forceGenerateNamespacesForNewImports: config.forceGenerateNamespacesForNewImports ?? false, namespaceImportPrefix: config.namespaceImportPrefix ?? 'i', generateUniqueIdentifier: config.generateUniqueIdentifier ?? createGenerateUniqueIdentifierHelper(), }; this.reuseSourceFileImportsTracker = { generateUniqueIdentifier: this.config.generateUniqueIdentifier, reusedAliasDeclarations: new Set(), updatedImports: new Map(), }; } /** Adds a side-effect import for the given module. */ addSideEffectImport(requestedFile: ts.SourceFile, moduleSpecifier: string) { if (this.config.rewriter !== null) { moduleSpecifier = this.config.rewriter.rewriteSpecifier( moduleSpecifier, requestedFile.fileName, ); } this._getNewImportsTrackerForFile(requestedFile).sideEffectImports.add( moduleSpecifier as ModuleName, ); } /** * Adds an import to the given source-file and returns a TypeScript * expression that can be used to access the newly imported symbol. */ addImport( request: ImportRequest<ts.SourceFile> & {asTypeReference: true}, ): ts.Identifier | ts.QualifiedName; addImport( request: ImportRequest<ts.SourceFile> & {asTypeReference?: undefined}, ): ts.Identifier | ts.PropertyAccessExpression; addImport( request: ImportRequest<ts.SourceFile> & {asTypeReference?: boolean}, ): ts.Identifier | ts.PropertyAccessExpression | ts.QualifiedName { if (this.config.rewriter !== null) { if (request.exportSymbolName !== null) { request.exportSymbolName = this.config.rewriter.rewriteSymbol( request.exportSymbolName, request.exportModuleSpecifier, ); } request.exportModuleSpecifier = this.config.rewriter.rewriteSpecifier( request.exportModuleSpecifier, request.requestedFile.fileName, ); } // Remove the newly-added import from the set of removed imports. if (request.exportSymbolName !== null && !request.asTypeReference) { this.removedImports .get(request.requestedFile) ?.get(request.exportModuleSpecifier as ModuleName) ?.delete(request.exportSymbolName); } // Attempt to re-use previous identical import requests. const previousGeneratedImportRef = attemptToReuseGeneratedImports( this.reuseGeneratedImportsTracker, request, ); if (previousGeneratedImportRef !== null) { return createImportReference(!!request.asTypeReference, previousGeneratedImportRef); } // Generate a new one, and cache it. const resultImportRef = this._generateNewImport(request); captureGeneratedImport(request, this.reuseGeneratedImportsTracker, resultImportRef); return createImportReference(!!request.asTypeReference, resultImportRef); } /** * Marks all imported symbols with a specific name for removal. * Call `addImport` to undo this operation. * @param requestedFile File from which to remove the imports. * @param exportSymbolName Declared name of the symbol being removed. * @param moduleSpecifier Module from which the symbol is being imported. */ removeImport( requestedFile: ts.SourceFile, exportSymbolName: string, moduleSpecifier: string, ): void { let moduleMap = this.removedImports.get(requestedFile); if (!moduleMap) { moduleMap = new Map(); this.removedImports.set(requestedFile, moduleMap); } let removedSymbols = moduleMap.get(moduleSpecifier as ModuleName); if (!removedSymbols) { removedSymbols = new Set(); moduleMap.set(moduleSpecifier as ModuleName, removedSymbols); } removedSymbols.add(exportSymbolName); } private _generateNewImport( request: ImportRequest<ts.SourceFile>, ): ts.Identifier | [ts.Identifier, ts.Identifier] { const {requestedFile: sourceFile} = request; const disableOriginalSourceFileReuse = this.config.disableOriginalSourceFileReuse; const forceGenerateNamespacesForNewImports = this.config.forceGenerateNamespacesForNewImports; // If desired, attempt to re-use original source file imports as a base, or as much as possible. // This may involve updates to existing import named bindings. if (!disableOriginalSourceFileReuse) { const reuseResult = attemptToReuseExistingSourceFileImports( this.reuseSourceFileImportsTracker, sourceFile, request, ); if (reuseResult !== null) { return reuseResult; } } // A new import needs to be generated. // No candidate existing import was found. const {namedImports, namespaceImports} = this._getNewImportsTrackerForFile(sourceFile); // If a namespace import is requested, or the symbol should be forcibly // imported through namespace imports: if (request.exportSymbolName === null || forceGenerateNamespacesForNewImports) { let namespaceImportName = `${this.config.namespaceImportPrefix}${this.nextUniqueIndex++}`; if (this.config.rewriter) { namespaceImportName = this.config.rewriter.rewriteNamespaceImportIdentifier( namespaceImportName, request.exportModuleSpecifier, ); } const namespaceImport = ts.factory.createNamespaceImport( this.config.generateUniqueIdentifier(sourceFile, namespaceImportName) ?? ts.factory.createIdentifier(namespaceImportName), ); namespaceImports.set(request.exportModuleSpecifier as ModuleName, namespaceImport); // Capture the generated namespace import alone, to allow re-use. captureGeneratedImport( {...request, exportSymbolName: null}, this.reuseGeneratedImportsTracker, namespaceImport.name, ); if (request.exportSymbolName !== null) { return [namespaceImport.name, ts.factory.createIdentifier(request.exportSymbolName)]; } return namespaceImport.name; } // Otherwise, an individual named import is requested. if (!namedImports.has(request.exportModuleSpecifier as ModuleName)) { namedImports.set(request.exportModuleSpecifier as ModuleName, []); } const exportSymbolName = ts.factory.createIdentifier(request.exportSymbolName); const fileUniqueName = request.unsafeAliasOverride ? null : this.config.generateUniqueIdentifier(sourceFile, request.exportSymbolName); let needsAlias: boolean; let specifierName: ts.Identifier; if (request.unsafeAliasOverride) { needsAlias = true; specifierName = ts.factory.createIdentifier(request.unsafeAliasOverride); } else if (fileUniqueName !== null) { needsAlias = true; specifierName = fileUniqueName; } else { needsAlias = false; specifierName = exportSymbolName; } namedImports .get(request.exportModuleSpecifier as ModuleName)! .push( ts.factory.createImportSpecifier( false, needsAlias ? exportSymbolName : undefined, specifierName, ), ); return specifierName; } /** * Finalizes the import manager by computing all necessary import changes * and returning them. * * Changes are collected once at the end, after all imports are requested, * because this simplifies building up changes to existing imports that need * to be updated, and allows more trivial re-use of previous generated imports. */
{ "end_byte": 11302, "start_byte": 2339, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.ts_11305_19356
finalize(): { affectedFiles: Set<string>; updatedImports: Map<ts.NamedImports, ts.NamedImports>; newImports: Map<string, ts.ImportDeclaration[]>; reusedOriginalAliasDeclarations: Set<AliasImportDeclaration>; deletedImports: Set<ts.ImportDeclaration>; } { const affectedFiles = new Set<string>(); const updatedImportsResult = new Map<ts.NamedImports, ts.NamedImports>(); const newImportsResult = new Map<string, ts.ImportDeclaration[]>(); const deletedImports = new Set<ts.ImportDeclaration>(); const importDeclarationsPerFile = new Map<ts.SourceFile, ts.ImportDeclaration[]>(); const addNewImport = (fileName: string, importDecl: ts.ImportDeclaration) => { affectedFiles.add(fileName); if (newImportsResult.has(fileName)) { newImportsResult.get(fileName)!.push(importDecl); } else { newImportsResult.set(fileName, [importDecl]); } }; // Collect original source file imports that need to be updated. this.reuseSourceFileImportsTracker.updatedImports.forEach((expressions, importDecl) => { const sourceFile = importDecl.getSourceFile(); const namedBindings = importDecl.importClause!.namedBindings as ts.NamedImports; const moduleName = (importDecl.moduleSpecifier as ts.StringLiteral).text as ModuleName; const newElements = namedBindings.elements .concat( expressions.map(({propertyName, fileUniqueAlias}) => ts.factory.createImportSpecifier( false, fileUniqueAlias !== null ? propertyName : undefined, fileUniqueAlias ?? propertyName, ), ), ) .filter((specifier) => this._canAddSpecifier(sourceFile, moduleName, specifier)); affectedFiles.add(sourceFile.fileName); if (newElements.length === 0) { deletedImports.add(importDecl); } else { updatedImportsResult.set( namedBindings, ts.factory.updateNamedImports(namedBindings, newElements), ); } }); this.removedImports.forEach((removeMap, sourceFile) => { if (removeMap.size === 0) { return; } let allImports = importDeclarationsPerFile.get(sourceFile); if (!allImports) { allImports = sourceFile.statements.filter(ts.isImportDeclaration); importDeclarationsPerFile.set(sourceFile, allImports); } for (const node of allImports) { if ( !node.importClause?.namedBindings || !ts.isNamedImports(node.importClause.namedBindings) || this.reuseSourceFileImportsTracker.updatedImports.has(node) || deletedImports.has(node) ) { continue; } const namedBindings = node.importClause.namedBindings; const moduleName = (node.moduleSpecifier as ts.StringLiteral).text as ModuleName; const newImports = namedBindings.elements.filter((specifier) => this._canAddSpecifier(sourceFile, moduleName, specifier), ); if (newImports.length === 0) { affectedFiles.add(sourceFile.fileName); deletedImports.add(node); } else if (newImports.length !== namedBindings.elements.length) { affectedFiles.add(sourceFile.fileName); updatedImportsResult.set( namedBindings, ts.factory.updateNamedImports(namedBindings, newImports), ); } } }); // Collect all new imports to be added. Named imports, namespace imports or side-effects. this.newImports.forEach(({namedImports, namespaceImports, sideEffectImports}, sourceFile) => { const useSingleQuotes = this.config.shouldUseSingleQuotes(sourceFile); const fileName = sourceFile.fileName; sideEffectImports.forEach((moduleName) => { addNewImport( fileName, ts.factory.createImportDeclaration( undefined, undefined, ts.factory.createStringLiteral(moduleName), ), ); }); namespaceImports.forEach((namespaceImport, moduleName) => { const newImport = ts.factory.createImportDeclaration( undefined, ts.factory.createImportClause(false, undefined, namespaceImport), ts.factory.createStringLiteral(moduleName, useSingleQuotes), ); // IMPORTANT: Set the original TS node to the `ts.ImportDeclaration`. This allows // downstream transforms such as tsickle to properly process references to this import. // // This operation is load-bearing in g3 as some imported modules contain special metadata // generated by clutz, which tsickle uses to transform imports and references to those // imports. See: `google3: node_modules/tsickle/src/googmodule.ts;l=637-640;rcl=615418148` ts.setOriginalNode(namespaceImport.name, newImport); addNewImport(fileName, newImport); }); namedImports.forEach((specifiers, moduleName) => { const filteredSpecifiers = specifiers.filter((specifier) => this._canAddSpecifier(sourceFile, moduleName, specifier), ); if (filteredSpecifiers.length > 0) { const newImport = ts.factory.createImportDeclaration( undefined, ts.factory.createImportClause( false, undefined, ts.factory.createNamedImports(filteredSpecifiers), ), ts.factory.createStringLiteral(moduleName, useSingleQuotes), ); addNewImport(fileName, newImport); } }); }); return { affectedFiles, newImports: newImportsResult, updatedImports: updatedImportsResult, reusedOriginalAliasDeclarations: this.reuseSourceFileImportsTracker.reusedAliasDeclarations, deletedImports, }; } /** * Gets a TypeScript transform for the import manager. * * @param extraStatementsMap Additional set of statements to be inserted * for given source files after their imports. E.g. top-level constants. */ toTsTransform( extraStatementsMap?: Map<string, ts.Statement[]>, ): ts.TransformerFactory<ts.SourceFile> { return createTsTransformForImportManager(this, extraStatementsMap); } /** * Transforms a single file as a shorthand, using {@link toTsTransform}. * * @param extraStatementsMap Additional set of statements to be inserted * for given source files after their imports. E.g. top-level constants. */ transformTsFile( ctx: ts.TransformationContext, file: ts.SourceFile, extraStatementsAfterImports?: ts.Statement[], ): ts.SourceFile { const extraStatementsMap = extraStatementsAfterImports ? new Map([[file.fileName, extraStatementsAfterImports]]) : undefined; return this.toTsTransform(extraStatementsMap)(ctx)(file); } private _getNewImportsTrackerForFile( file: ts.SourceFile, ): NonNullable<ReturnType<(typeof this.newImports)['get']>> { if (!this.newImports.has(file)) { this.newImports.set(file, { namespaceImports: new Map(), namedImports: new Map(), sideEffectImports: new Set(), }); } return this.newImports.get(file)!; } private _canAddSpecifier( sourceFile: ts.SourceFile, moduleSpecifier: ModuleName, specifier: ts.ImportSpecifier, ): boolean { return !this.removedImports .get(sourceFile) ?.get(moduleSpecifier) ?.has((specifier.propertyName || specifier.name).text); } } /** Creates an import reference based on the given identifier, or nested access. */ function createImportReference( asTypeReference: boolean, ref: ts.Identifier | [ts.Identifier, ts.Identifier], ): ts.Identifier | ts.QualifiedName | ts.PropertyAccessExpression { if (asTypeReference) { return Array.isArray(ref) ? ts.factory.createQualifiedName(ref[0], ref[1]) : ref; } else { return Array.isArray(ref) ? ts.factory.createPropertyAccessExpression(ref[0], ref[1]) : ref; } }
{ "end_byte": 19356, "start_byte": 11305, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/api/ast_factory.ts_0_627
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * Used to create transpiler specific AST nodes from Angular Output AST nodes in an abstract way. * * Note that the `AstFactory` makes no assumptions about the target language being generated. * It is up to the caller to do this - e.g. only call `createTaggedTemplate()` or pass `let`|`const` * to `createVariableDeclaration()` if the final JS will allow it. */ export interface AstFactory<TStatement, TExpression>
{ "end_byte": 627, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/api/ast_factory.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/api/ast_factory.ts_628_8865
{ /** * Attach the `leadingComments` to the given `statement` node. * * @param statement the statement where the comments are to be attached. * @param leadingComments the comments to attach. */ attachComments(statement: TStatement | TExpression, leadingComments: LeadingComment[]): void; /** * Create a literal array expression (e.g. `[expr1, expr2]`). * * @param elements a collection of the expressions to appear in each array slot. */ createArrayLiteral(elements: TExpression[]): TExpression; /** * Create an assignment expression (e.g. `lhsExpr = rhsExpr`). * * @param target an expression that evaluates to the left side of the assignment. * @param value an expression that evaluates to the right side of the assignment. */ createAssignment(target: TExpression, value: TExpression): TExpression; /** * Create a binary expression (e.g. `lhs && rhs`). * * @param leftOperand an expression that will appear on the left of the operator. * @param operator the binary operator that will be applied. * @param rightOperand an expression that will appear on the right of the operator. */ createBinaryExpression( leftOperand: TExpression, operator: BinaryOperator, rightOperand: TExpression, ): TExpression; /** * Create a block of statements (e.g. `{ stmt1; stmt2; }`). * * @param body an array of statements to be wrapped in a block. */ createBlock(body: TStatement[]): TStatement; /** * Create an expression that is calling the `callee` with the given `args`. * * @param callee an expression that evaluates to a function to be called. * @param args the arguments to be passed to the call. * @param pure whether to mark the call as pure (having no side-effects). */ createCallExpression(callee: TExpression, args: TExpression[], pure: boolean): TExpression; /** * Create a ternary expression (e.g. `testExpr ? trueExpr : falseExpr`). * * @param condition an expression that will be tested for truthiness. * @param thenExpression an expression that is executed if `condition` is truthy. * @param elseExpression an expression that is executed if `condition` is falsy. */ createConditional( condition: TExpression, thenExpression: TExpression, elseExpression: TExpression, ): TExpression; /** * Create an element access (e.g. `obj[expr]`). * * @param expression an expression that evaluates to the object to be accessed. * @param element an expression that evaluates to the element on the object. */ createElementAccess(expression: TExpression, element: TExpression): TExpression; /** * Create a statement that is simply executing the given `expression` (e.g. `x = 10;`). * * @param expression the expression to be converted to a statement. */ createExpressionStatement(expression: TExpression): TStatement; /** * Create a statement that declares a function (e.g. `function foo(param1, param2) { stmt; }`). * * @param functionName the name of the function. * @param parameters the names of the function's parameters. * @param body a statement (or a block of statements) that are the body of the function. */ createFunctionDeclaration( functionName: string, parameters: string[], body: TStatement, ): TStatement; /** * Create an expression that represents a function * (e.g. `function foo(param1, param2) { stmt; }`). * * @param functionName the name of the function. * @param parameters the names of the function's parameters. * @param body a statement (or a block of statements) that are the body of the function. */ createFunctionExpression( functionName: string | null, parameters: string[], body: TStatement, ): TExpression; /** * Create an expression that represents an arrow function * (e.g. `(param1, param2) => body`). * * @param parameters the names of the function's parameters. * @param body an expression or block of statements that are the body of the function. */ createArrowFunctionExpression(parameters: string[], body: TExpression | TStatement): TExpression; /** * Creates an expression that represents a dynamic import * (e.g. `import('./some/path')`) * * @param url the URL that should by used in the dynamic import */ createDynamicImport(url: string | TExpression): TExpression; /** * Create an identifier. * * @param name the name of the identifier. */ createIdentifier(name: string): TExpression; /** * Create an if statement (e.g. `if (testExpr) { trueStmt; } else { falseStmt; }`). * * @param condition an expression that will be tested for truthiness. * @param thenStatement a statement (or block of statements) that is executed if `condition` is * truthy. * @param elseStatement a statement (or block of statements) that is executed if `condition` is * falsy. */ createIfStatement( condition: TExpression, thenStatement: TStatement, elseStatement: TStatement | null, ): TStatement; /** * Create a simple literal (e.g. `"string"`, `123`, `false`, etc). * * @param value the value of the literal. */ createLiteral(value: string | number | boolean | null | undefined): TExpression; /** * Create an expression that is instantiating the `expression` as a class. * * @param expression an expression that evaluates to a constructor to be instantiated. * @param args the arguments to be passed to the constructor. */ createNewExpression(expression: TExpression, args: TExpression[]): TExpression; /** * Create a literal object expression (e.g. `{ prop1: expr1, prop2: expr2 }`). * * @param properties the properties (key and value) to appear in the object. */ createObjectLiteral(properties: ObjectLiteralProperty<TExpression>[]): TExpression; /** * Wrap an expression in parentheses. * * @param expression the expression to wrap in parentheses. */ createParenthesizedExpression(expression: TExpression): TExpression; /** * Create a property access (e.g. `obj.prop`). * * @param expression an expression that evaluates to the object to be accessed. * @param propertyName the name of the property to access. */ createPropertyAccess(expression: TExpression, propertyName: string): TExpression; /** * Create a return statement (e.g `return expr;`). * * @param expression the expression to be returned. */ createReturnStatement(expression: TExpression | null): TStatement; /** * Create a tagged template literal string. E.g. * * ``` * tag`str1${expr1}str2${expr2}str3` * ``` * * @param tag an expression that is applied as a tag handler for this template string. * @param template the collection of strings and expressions that constitute an interpolated * template literal. */ createTaggedTemplate(tag: TExpression, template: TemplateLiteral<TExpression>): TExpression; /** * Create a throw statement (e.g. `throw expr;`). * * @param expression the expression to be thrown. */ createThrowStatement(expression: TExpression): TStatement; /** * Create an expression that extracts the type of an expression (e.g. `typeof expr`). * * @param expression the expression whose type we want. */ createTypeOfExpression(expression: TExpression): TExpression; /** * Prefix the `operand` with the given `operator` (e.g. `-expr`). * * @param operator the text of the operator to apply (e.g. `+`, `-` or `!`). * @param operand the expression that the operator applies to. */ createUnaryExpression(operator: UnaryOperator, operand: TExpression): TExpression; /** * Create an expression that declares a new variable, possibly initialized to `initializer`. * * @param variableName the name of the variable. * @param initializer if not `null` then this expression is assigned to the declared variable. * @param type whether this variable should be declared as `var`, `let` or `const`. */ createVariableDeclaration( variableName: string, initializer: TExpression | null, type: VariableDeclarationType, ): TStatement;
{ "end_byte": 8865, "start_byte": 628, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/api/ast_factory.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/api/ast_factory.ts_8869_11753
/** * Attach a source map range to the given node. * * @param node the node to which the range should be attached. * @param sourceMapRange the range to attach to the node, or null if there is no range to attach. * @returns the `node` with the `sourceMapRange` attached. */ setSourceMapRange<T extends TStatement | TExpression>( node: T, sourceMapRange: SourceMapRange | null, ): T; } /** * The type of a variable declaration. */ export type VariableDeclarationType = 'const' | 'let' | 'var'; /** * The unary operators supported by the `AstFactory`. */ export type UnaryOperator = '+' | '-' | '!'; /** * The binary operators supported by the `AstFactory`. */ export type BinaryOperator = | '&&' | '>' | '>=' | '&' | '|' | '/' | '==' | '===' | '<' | '<=' | '-' | '%' | '*' | '!=' | '!==' | '||' | '+' | '??'; /** * The original location of the start or end of a node created by the `AstFactory`. */ export interface SourceMapLocation { /** 0-based character position of the location in the original source file. */ offset: number; /** 0-based line index of the location in the original source file. */ line: number; /** 0-based column position of the location in the original source file. */ column: number; } /** * The original range of a node created by the `AstFactory`. */ export interface SourceMapRange { url: string; content: string; start: SourceMapLocation; end: SourceMapLocation; } /** * Information used by the `AstFactory` to create a property on an object literal expression. */ export interface ObjectLiteralProperty<TExpression> { propertyName: string; value: TExpression; /** * Whether the `propertyName` should be enclosed in quotes. */ quoted: boolean; } /** * Information used by the `AstFactory` to create a template literal string (i.e. a back-ticked * string with interpolations). */ export interface TemplateLiteral<TExpression> { /** * A collection of the static string pieces of the interpolated template literal string. */ elements: TemplateElement[]; /** * A collection of the interpolated expressions that are interleaved between the elements. */ expressions: TExpression[]; } /** * Information about a static string piece of an interpolated template literal string. */ export interface TemplateElement { /** The raw string as it was found in the original source code. */ raw: string; /** The parsed string, with escape codes etc processed. */ cooked: string; /** The original location of this piece of the template literal string. */ range: SourceMapRange | null; } /** * Information used by the `AstFactory` to prepend a comment to a statement that was created by the * `AstFactory`. */ export interface LeadingComment { toString(): string; multiline: boolean; trailingNewline: boolean; }
{ "end_byte": 11753, "start_byte": 8869, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/api/ast_factory.ts" }
angular/packages/compiler-cli/src/ngtsc/translator/src/api/import_generator.ts_0_1696
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * A request to import a given symbol from the given module. */ export interface ImportRequest<TFile> { /** * Name of the export to be imported. * May be `null` if a namespace import is requested. */ exportSymbolName: string | null; /** * Module specifier to be imported. * May be a module name, or a file-relative path. */ exportModuleSpecifier: string; /** * File for which the import is requested for. This may * be used by import generators to re-use existing imports. * * Import managers may also allow this to be nullable if * imports are never re-used. E.g. in the linker generator. */ requestedFile: TFile; /** * Specifies an alias under which the symbol can be referenced within * the file (e.g. `import { symbol as alias } from 'module'`). * * !!!Warning!!! passing in this alias is considered unsafe, because the import manager won't * try to avoid conflicts with existing identifiers in the file if it is specified. As such, * this option should only be used if the caller has verified that the alias won't conflict * with anything in the file. */ unsafeAliasOverride?: string; } /** * Generate import information based on the context of the code being generated. * * Implementations of these methods return a specific identifier that corresponds to the imported * module. */ export interface ImportGenerator<TFile, TExpression> { addImport(request: ImportRequest<TFile>): TExpression; }
{ "end_byte": 1696, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/translator/src/api/import_generator.ts" }
angular/packages/compiler-cli/src/ngtsc/annotations/README.md_0_1812
# What is the 'annotations' package? This package implements compilation of Angular-annotated classes - those with `@Component`, `@NgModule`, etc. decorators. (Note that the compiler uses 'decorator' and 'annotation' interchangeably, despite them having slightly different semantics). The 'transform' package of the compiler provides an abstraction for a `DecoratorHandler`, which defines how to compile a class decorated with a particular Angular decorator. This package implements a `DecoratorHandler` for each Angular type. The methods of these `DecoratorHandler`s then allow the rest of the compiler to process each decorated class through the phases of compilation. # Anatomy of `DecoratorHandler`s Each handler implemented here performs some similar operations: * It uses the `PartialEvaluator` to resolve expressions within the decorator metadata or other decorated fields that need to be understood statically. * It extracts information from constructors of decorated classes which is required to generate dependency injection instructions. * It reports errors when developers have misused or misconfigured the decorators. * It populates registries that describe decorated classes to the rest of the compiler. * It uses those same registries to understand decorated classes within the context of the compilation (for example, to understand which dependencies are used in a given template). * It creates `SemanticSymbol`s which allow for accurate incremental compilation when reacting to input changes. * It builds metadata objects for `@angular/compiler` which describe the decorated classes, which can then perform the actual code generation. Since there is significant overlap between `DecoratorHandler` implementations, much of this functionality is implemented in a shared 'common' sub-package.
{ "end_byte": 1812, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/README.md" }
angular/packages/compiler-cli/src/ngtsc/annotations/BUILD.bazel_0_1660
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "annotations", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/annotations/common", "//packages/compiler-cli/src/ngtsc/annotations/component", "//packages/compiler-cli/src/ngtsc/annotations/directive", "//packages/compiler-cli/src/ngtsc/annotations/ng_module", "//packages/compiler-cli/src/ngtsc/cycles", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/incremental/semantic_graph", "//packages/compiler-cli/src/ngtsc/indexer", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/shims:api", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "//packages/compiler-cli/src/ngtsc/util", "//packages/compiler-cli/src/ngtsc/xi18n", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 1660, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/annotations/index.ts_0_1055
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> export { forwardRefResolver, getAngularDecorators, isAngularDecorator, NoopReferencesRegistry, ReferencesRegistry, ResourceLoader, ResourceLoaderContext, JitDeclarationRegistry, } from './common'; export {ComponentDecoratorHandler} from './component'; export { DirectiveDecoratorHandler, InitializerApiFunction, INPUT_INITIALIZER_FN, MODEL_INITIALIZER_FN, OUTPUT_INITIALIZER_FNS, QUERY_INITIALIZER_FNS, queryDecoratorNames, QueryFunctionName, tryParseInitializerApi, tryParseInitializerBasedOutput, tryParseSignalInputMapping, tryParseSignalModelMapping, tryParseSignalQueryFromInitializer, } from './directive'; export {NgModuleDecoratorHandler} from './ng_module'; export {InjectableDecoratorHandler} from './src/injectable'; export {PipeDecoratorHandler} from './src/pipe';
{ "end_byte": 1055, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/index.ts" }
angular/packages/compiler-cli/src/ngtsc/annotations/test/BUILD.bazel_0_1369
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/annotations", "//packages/compiler-cli/src/ngtsc/annotations/common", "//packages/compiler-cli/src/ngtsc/cycles", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/translator", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 1369, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/annotations/test/injectable_spec.ts_0_4147
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {InjectableClassRegistry} from '../../annotations/common'; import {ErrorCode, FatalDiagnosticError, ngErrorCode} from '../../diagnostics'; import {absoluteFrom} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {PartialEvaluator} from '../../partial_evaluator'; import {NOOP_PERF_RECORDER} from '../../perf'; import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {CompilationMode} from '../../transform'; import {InjectableDecoratorHandler} from '../src/injectable'; runInEachFileSystem(() => { describe('InjectableDecoratorHandler', () => { describe('compile()', () => { it('should produce a diagnostic when injectable already has a static ɵprov property (with errorOnDuplicateProv true)', () => { const {handler, TestClass, ɵprov, analysis} = setupHandler(/* errorOnDuplicateProv */ true); try { handler.compileFull(TestClass, analysis); return fail('Compilation should have failed'); } catch (err) { if (!(err instanceof FatalDiagnosticError)) { return fail('Error should be a FatalDiagnosticError'); } const diag = err.toDiagnostic(); expect(diag.code).toEqual(ngErrorCode(ErrorCode.INJECTABLE_DUPLICATE_PROV)); expect(diag.file.fileName.endsWith('entry.ts')).toBe(true); expect(diag.start).toBe(ɵprov.nameNode!.getStart()); } }); it('should not add new ɵprov property when injectable already has one (with errorOnDuplicateProv false)', () => { const {handler, TestClass, ɵprov, analysis} = setupHandler( /* errorOnDuplicateProv */ false, ); const res = handler.compileFull(TestClass, analysis); expect(res).not.toContain(jasmine.objectContaining({name: 'ɵprov'})); }); }); }); }); function setupHandler(errorOnDuplicateProv: boolean) { const ENTRY_FILE = absoluteFrom('/entry.ts'); const ANGULAR_CORE = absoluteFrom('/node_modules/@angular/core/index.d.ts'); const {program} = makeProgram([ { name: ANGULAR_CORE, contents: 'export const Injectable: any; export const ɵɵdefineInjectable: any', }, { name: ENTRY_FILE, contents: ` import {Injectable, ɵɵdefineInjectable} from '@angular/core'; export const TestClassToken = 'TestClassToken'; @Injectable({providedIn: 'module'}) export class TestClass { static ɵprov = ɵɵdefineInjectable({ factory: () => {}, token: TestClassToken, providedIn: "module" }); }`, }, ]); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const injectableRegistry = new InjectableClassRegistry(reflectionHost, /* isCore */ false); const evaluator = new PartialEvaluator(reflectionHost, checker, null); const handler = new InjectableDecoratorHandler( reflectionHost, evaluator, /* isCore */ false, /* strictCtorDeps */ false, injectableRegistry, NOOP_PERF_RECORDER, true, /*compilationMode */ CompilationMode.FULL, errorOnDuplicateProv, ); const TestClass = getDeclaration(program, ENTRY_FILE, 'TestClass', isNamedClassDeclaration); const ɵprov = reflectionHost .getMembersOfClass(TestClass) .find((member) => member.name === 'ɵprov'); if (ɵprov === undefined) { throw new Error('TestClass did not contain a `ɵprov` member'); } const detected = handler.detect(TestClass, reflectionHost.getDecoratorsOfDeclaration(TestClass)); if (detected === undefined) { throw new Error('Failed to recognize TestClass'); } const {analysis} = handler.analyze(TestClass, detected.metadata); if (analysis === undefined) { throw new Error('Failed to analyze TestClass'); } return {handler, TestClass, ɵprov, analysis}; }
{ "end_byte": 4147, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/test/injectable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/README.md_0_315
# What is the 'annotations/ng_module' package? This package implements the `NgModuleDecoratorHandler`, which processes and compiles `@NgModule`-decorated classes. It's separated out because other `DecoratorHandler`s interact with the `NgModuleSymbol` to implement the incremental compilation semantics of Angular.
{ "end_byte": 315, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/README.md" }
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/BUILD.bazel_0_1050
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "ng_module", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/annotations/common", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/incremental/semantic_graph", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/shims:api", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 1050, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/index.ts_0_424
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {NgModuleDecoratorHandler, NgModuleSymbol} from './src/handler'; export { createModuleWithProvidersResolver, isResolvedModuleWithProviders, ResolvedModuleWithProviders, } from './src/module_with_providers';
{ "end_byte": 424, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/index.ts" }
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/test/ng_module_spec.ts_0_3330
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 {R3NgModuleMetadataGlobal, WrappedNodeExpr} from '@angular/compiler'; import {R3Reference} from '@angular/compiler/src/compiler'; import ts from 'typescript'; import {absoluteFrom} from '../../../file_system'; import {runInEachFileSystem} from '../../../file_system/testing'; import {LocalIdentifierStrategy, ReferenceEmitter} from '../../../imports'; import { CompoundMetadataReader, DtsMetadataReader, ExportedProviderStatusResolver, LocalMetadataRegistry, } from '../../../metadata'; import {PartialEvaluator} from '../../../partial_evaluator'; import {NOOP_PERF_RECORDER} from '../../../perf'; import { ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost, } from '../../../reflection'; import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../../scope'; import {getDeclaration, makeProgram} from '../../../testing'; import {CompilationMode} from '../../../transform'; import { InjectableClassRegistry, JitDeclarationRegistry, NoopReferencesRegistry, } from '../../common'; import {NgModuleDecoratorHandler} from '../src/handler'; function setup(program: ts.Program, compilationMode = CompilationMode.FULL) { const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost( checker, compilationMode === CompilationMode.LOCAL, ); const evaluator = new PartialEvaluator(reflectionHost, checker, /* dependencyTracker */ null); const referencesRegistry = new NoopReferencesRegistry(); const metaRegistry = new LocalMetadataRegistry(); const dtsReader = new DtsMetadataReader(checker, reflectionHost); const metaReader = new CompoundMetadataReader([metaRegistry, dtsReader]); const scopeRegistry = new LocalModuleScopeRegistry( metaRegistry, metaReader, new MetadataDtsModuleScopeResolver(dtsReader, null), new ReferenceEmitter([]), null, ); const refEmitter = new ReferenceEmitter([new LocalIdentifierStrategy()]); const injectableRegistry = new InjectableClassRegistry(reflectionHost, /* isCore */ false); const exportedProviderStatusResolver = new ExportedProviderStatusResolver(metaReader); const jitDeclarationRegistry = new JitDeclarationRegistry(); const handler = new NgModuleDecoratorHandler( reflectionHost, evaluator, metaReader, metaRegistry, scopeRegistry, referencesRegistry, exportedProviderStatusResolver, /* semanticDepGraphUpdater */ null, /* isCore */ false, refEmitter, /* annotateForClosureCompiler */ false, /* onlyPublishPublicTypings */ false, injectableRegistry, NOOP_PERF_RECORDER, true, true, compilationMode, /* localCompilationExtraImportsTracker */ null, jitDeclarationRegistry, ); return {handler, reflectionHost}; } function detectNgModule( module: ClassDeclaration, handler: NgModuleDecoratorHandler, reflectionHost: TypeScriptReflectionHost, ) { const detected = handler.detect(module, reflectionHost.getDecoratorsOfDeclaration(module)); if (detected === undefined) { throw new Error('Failed to recognize @NgModule'); } return detected; }
{ "end_byte": 3330, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/test/ng_module_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/test/ng_module_spec.ts_3332_11119
runInEachFileSystem(() => { describe('NgModuleDecoratorHandler', () => { const _ = absoluteFrom; it('should resolve forwardRef', () => { const {program} = makeProgram([ { name: _('/node_modules/@angular/core/index.d.ts'), contents: ` export const Component: any; export const NgModule: any; export declare function forwardRef(fn: () => any): any; `, }, { name: _('/entry.ts'), contents: ` import {Component, forwardRef, NgModule} from '@angular/core'; @Component({ template: '', }) export class TestComp {} @NgModule() export class TestModuleDependency {} @NgModule({ declarations: [forwardRef(() => TestComp)], exports: [forwardRef(() => TestComp)], imports: [forwardRef(() => TestModuleDependency)] }) export class TestModule {} `, }, ]); const {handler, reflectionHost} = setup(program); const TestModule = getDeclaration( program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration, ); const detected = detectNgModule(TestModule, handler, reflectionHost); const moduleDef = handler.analyze(TestModule, detected.metadata).analysis! .mod as R3NgModuleMetadataGlobal; expect(getReferenceIdentifierTexts(moduleDef.declarations)).toEqual(['TestComp']); expect(getReferenceIdentifierTexts(moduleDef.exports)).toEqual(['TestComp']); expect(getReferenceIdentifierTexts(moduleDef.imports)).toEqual(['TestModuleDependency']); function getReferenceIdentifierTexts(references: R3Reference[]) { return references.map((ref) => (ref.value as WrappedNodeExpr<ts.Identifier>).node.text); } }); describe('local compilation mode', () => { it('should not produce diagnostic for cross-file imports', () => { const {program} = makeProgram( [ { name: _('/node_modules/@angular/core/index.d.ts'), contents: 'export const NgModule: any;', }, { name: _('/entry.ts'), contents: ` import {NgModule} from '@angular/core'; import {SomeModule} from './some_where'; @NgModule({ imports: [SomeModule], }) class TestModule {} `, }, ], undefined, undefined, false, ); const {reflectionHost, handler} = setup(program, CompilationMode.LOCAL); const TestModule = getDeclaration( program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration, ); const detected = detectNgModule(TestModule, handler, reflectionHost); const {diagnostics} = handler.analyze(TestModule, detected.metadata); expect(diagnostics).toBeUndefined(); }); it('should not produce diagnostic for cross-file exports', () => { const {program} = makeProgram( [ { name: _('/node_modules/@angular/core/index.d.ts'), contents: 'export const NgModule: any;', }, { name: _('/entry.ts'), contents: ` import {NgModule} from '@angular/core'; import {SomeModule} from './some_where'; @NgModule({ exports: [SomeModule], }) class TestModule {} `, }, ], undefined, undefined, false, ); const {reflectionHost, handler} = setup(program, CompilationMode.LOCAL); const TestModule = getDeclaration( program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration, ); const detected = detectNgModule(TestModule, handler, reflectionHost); const {diagnostics} = handler.analyze(TestModule, detected.metadata); expect(diagnostics).toBeUndefined(); }); it('should not produce diagnostic for cross-file declarations', () => { const {program} = makeProgram( [ { name: _('/node_modules/@angular/core/index.d.ts'), contents: 'export const NgModule: any;', }, { name: _('/entry.ts'), contents: ` import {NgModule} from '@angular/core'; import {SomeComponent} from './some_where'; @NgModule({ declarations: [SomeComponent], }) class TestModule {} `, }, ], undefined, undefined, false, ); const {reflectionHost, handler} = setup(program, CompilationMode.LOCAL); const TestModule = getDeclaration( program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration, ); const detected = detectNgModule(TestModule, handler, reflectionHost); const {diagnostics} = handler.analyze(TestModule, detected.metadata); expect(diagnostics).toBeUndefined(); }); it('should not produce diagnostic for cross-file bootstrap', () => { const {program} = makeProgram( [ { name: _('/node_modules/@angular/core/index.d.ts'), contents: 'export const NgModule: any;', }, { name: _('/entry.ts'), contents: ` import {NgModule} from '@angular/core'; import {SomeComponent} from './some_where'; @NgModule({ bootstrap: [SomeComponent], }) class TestModule {} `, }, ], undefined, undefined, false, ); const {reflectionHost, handler} = setup(program, CompilationMode.LOCAL); const TestModule = getDeclaration( program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration, ); const detected = detectNgModule(TestModule, handler, reflectionHost); const {diagnostics} = handler.analyze(TestModule, detected.metadata); expect(diagnostics).toBeUndefined(); }); it('should not produce diagnostic for schemas', () => { const {program} = makeProgram( [ { name: _('/node_modules/@angular/core/index.d.ts'), contents: 'export const NgModule: any; export const CUSTOM_ELEMENTS_SCHEMA: any;', }, { name: _('/entry.ts'), contents: ` import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; import {SomeComponent} from './some_where'; @NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule {} `, }, ], undefined, undefined, false, ); const {reflectionHost, handler} = setup(program, CompilationMode.LOCAL); const TestModule = getDeclaration( program, _('/entry.ts'), 'TestModule', isNamedClassDeclaration, ); const detected = detectNgModule(TestModule, handler, reflectionHost); const {diagnostics} = handler.analyze(TestModule, detected.metadata); expect(diagnostics).toBeUndefined(); }); }); }); });
{ "end_byte": 11119, "start_byte": 3332, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/test/ng_module_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/test/BUILD.bazel_0_1153
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/annotations/common", "//packages/compiler-cli/src/ngtsc/annotations/ng_module", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/transform", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 1153, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/test/BUILD.bazel" }