_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts_25887_27646 | decoratorsFor(node: ts.Declaration): ts.Decorator[] {
const original = ts.getOriginalNode(node) as typeof node;
if (!this.reflector.isClass(original) || !this.classes.has(original)) {
return [];
}
const record = this.classes.get(original)!;
const decorators: ts.Decorator[] = [];
for (const trait of record.traits) {
// In global compilation mode skip the non-resolved traits.
if (this.compilationMode !== CompilationMode.LOCAL && trait.state !== TraitState.Resolved) {
continue;
}
if (trait.detected.trigger !== null && ts.isDecorator(trait.detected.trigger)) {
decorators.push(trait.detected.trigger);
}
}
return decorators;
}
get diagnostics(): ReadonlyArray<ts.Diagnostic> {
const diagnostics: ts.Diagnostic[] = [];
for (const clazz of this.classes.keys()) {
const record = this.classes.get(clazz)!;
if (record.metaDiagnostics !== null) {
diagnostics.push(...record.metaDiagnostics);
}
for (const trait of record.traits) {
if (
(trait.state === TraitState.Analyzed || trait.state === TraitState.Resolved) &&
trait.analysisDiagnostics !== null
) {
diagnostics.push(...trait.analysisDiagnostics);
}
if (trait.state === TraitState.Resolved) {
diagnostics.push(...(trait.resolveDiagnostics ?? []));
}
}
}
return diagnostics;
}
get exportStatements(): Map<string, Map<string, [string, string]>> {
return this.reexportMap;
}
}
function containsErrors(diagnostics: ts.Diagnostic[] | null): boolean {
return (
diagnostics !== null &&
diagnostics.some((diag) => diag.category === ts.DiagnosticCategory.Error)
);
} | {
"end_byte": 27646,
"start_byte": 25887,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/compilation.ts"
} |
angular/packages/compiler-cli/src/ngtsc/transform/src/api.ts_0_8687 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool, Expression, Statement, Type} from '@angular/compiler';
import ts from 'typescript';
import {Reexport, ReferenceEmitter} from '../../imports';
import {SemanticSymbol} from '../../incremental/semantic_graph';
import {IndexingContext} from '../../indexer';
import {ClassDeclaration, Decorator, ReflectionHost} from '../../reflection';
import {ImportManager} from '../../translator';
import {TypeCheckContext} from '../../typecheck/api';
import {ExtendedTemplateChecker} from '../../typecheck/extended/api';
import {TemplateSemanticsChecker} from '../../typecheck/template_semantics/api/api';
import {Xi18nContext} from '../../xi18n';
/**
* Specifies the compilation mode that is used for the compilation.
*/
export enum CompilationMode {
/**
* Generates fully AOT compiled code using Ivy instructions.
*/
FULL,
/**
* Generates code using a stable, but intermediate format suitable to be published to NPM.
*/
PARTIAL,
/**
* Generates code based on each individual source file without using its
* dependencies (suitable for local dev edit/refresh workflow).
*/
LOCAL,
}
export enum HandlerPrecedence {
/**
* Handler with PRIMARY precedence cannot overlap - there can only be one on a given class.
*
* If more than one PRIMARY handler matches a class, an error is produced.
*/
PRIMARY,
/**
* Handlers with SHARED precedence can match any class, possibly in addition to a single PRIMARY
* handler.
*
* It is not an error for a class to have any number of SHARED handlers.
*/
SHARED,
/**
* Handlers with WEAK precedence that match a class are ignored if any handlers with stronger
* precedence match a class.
*/
WEAK,
}
/**
* Provides the interface between a decorator compiler from @angular/compiler and the Typescript
* compiler/transform.
*
* The decorator compilers in @angular/compiler do not depend on Typescript. The handler is
* responsible for extracting the information required to perform compilation from the decorators
* and Typescript source, invoking the decorator compiler, and returning the result.
*
* @param `D` The type of decorator metadata produced by `detect`.
* @param `A` The type of analysis metadata produced by `analyze`.
* @param `R` The type of resolution metadata produced by `resolve`.
*/
export interface DecoratorHandler<D, A, S extends SemanticSymbol | null, R> {
readonly name: string;
/**
* The precedence of a handler controls how it interacts with other handlers that match the same
* class.
*
* See the descriptions on `HandlerPrecedence` for an explanation of the behaviors involved.
*/
readonly precedence: HandlerPrecedence;
/**
* Scan a set of reflected decorators and determine if this handler is responsible for compilation
* of one of them.
*/
detect(node: ClassDeclaration, decorators: Decorator[] | null): DetectResult<D> | undefined;
/**
* Asynchronously perform pre-analysis on the decorator/class combination.
*
* `preanalyze` is optional and is not guaranteed to be called through all compilation flows. It
* will only be called if asynchronicity is supported in the CompilerHost.
*/
preanalyze?(node: ClassDeclaration, metadata: Readonly<D>): Promise<void> | undefined;
/**
* Perform analysis on the decorator/class combination, extracting information from the class
* required for compilation.
*
* Returns analyzed metadata if successful, or an array of diagnostic messages if the analysis
* fails or the decorator isn't valid.
*
* Analysis should always be a "pure" operation, with no side effects. This is because the
* detect/analysis steps might be skipped for files which have not changed during incremental
* builds. Any side effects required for compilation (e.g. registration of metadata) should happen
* in the `register` phase, which is guaranteed to run even for incremental builds.
*/
analyze(node: ClassDeclaration, metadata: Readonly<D>): AnalysisOutput<A>;
/**
* React to a change in a resource file by updating the `analysis` or `resolution`, under the
* assumption that nothing in the TypeScript code has changed.
*/
updateResources?(node: ClassDeclaration, analysis: A, resolution: R): void;
/**
* Produces a `SemanticSymbol` that represents the class, which is registered into the semantic
* dependency graph. The symbol is used in incremental compilations to let the compiler determine
* how a change to the class affects prior emit results. See the `incremental` target's README for
* details on how this works.
*
* The symbol is passed in to `resolve`, where it can be extended with references into other parts
* of the compilation as needed.
*
* Only primary handlers are allowed to have symbols; handlers with `precedence` other than
* `HandlerPrecedence.PRIMARY` must return a `null` symbol.
*/
symbol(node: ClassDeclaration, analysis: Readonly<A>): S;
/**
* Post-process the analysis of a decorator/class combination and record any necessary information
* in the larger compilation.
*
* Registration always occurs for a given decorator/class, regardless of whether analysis was
* performed directly or whether the analysis results were reused from the previous program.
*/
register?(node: ClassDeclaration, analysis: A): void;
/**
* Registers information about the decorator for the indexing phase in a
* `IndexingContext`, which stores information about components discovered in the
* program.
*/
index?(
context: IndexingContext,
node: ClassDeclaration,
analysis: Readonly<A>,
resolution: Readonly<R>,
): void;
/**
* Perform resolution on the given decorator along with the result of analysis.
*
* The resolution phase happens after the entire `ts.Program` has been analyzed, and gives the
* `DecoratorHandler` a chance to leverage information from the whole compilation unit to enhance
* the `analysis` before the emit phase.
*/
resolve?(node: ClassDeclaration, analysis: Readonly<A>, symbol: S): ResolveResult<R>;
/**
* Extract i18n messages into the `Xi18nContext`, which is useful for generating various formats
* of message file outputs.
*/
xi18n?(bundle: Xi18nContext, node: ClassDeclaration, analysis: Readonly<A>): void;
typeCheck?(
ctx: TypeCheckContext,
node: ClassDeclaration,
analysis: Readonly<A>,
resolution: Readonly<R>,
): void;
extendedTemplateCheck?(
component: ts.ClassDeclaration,
extendedTemplateChecker: ExtendedTemplateChecker,
): ts.Diagnostic[];
templateSemanticsCheck?(
component: ts.ClassDeclaration,
templateSemanticsChecker: TemplateSemanticsChecker,
): ts.Diagnostic[];
/**
* Generate a description of the field which should be added to the class, including any
* initialization code to be generated.
*
* If the compilation mode is configured as other than full but an implementation of the
* corresponding method is not provided, then this method is called as a fallback.
*/
compileFull(
node: ClassDeclaration,
analysis: Readonly<A>,
resolution: Readonly<R>,
constantPool: ConstantPool,
): CompileResult | CompileResult[];
/**
* Generates code for the decorator using a stable, but intermediate format suitable to be
* published to NPM. This code is meant to be processed by the linker to achieve the final AOT
* compiled code.
*
* If present, this method is used if the compilation mode is configured as partial, otherwise
* `compileFull` is.
*/
compilePartial?(
node: ClassDeclaration,
analysis: Readonly<A>,
resolution: Readonly<R>,
): CompileResult | CompileResult[];
/**
* Generates the function that will update a class' metadata at runtime during HMR.
*/
compileHmrUpdateDeclaration?(
node: ClassDeclaration,
analysis: Readonly<A>,
resolution: Readonly<R>,
): ts.FunctionDeclaration | null;
/**
* Generates code based on each individual source file without using its
* dependencies (suitable for local dev edit/refresh workflow)
*/
compileLocal(
node: ClassDeclaration,
analysis: Readonly<A>,
resolution: Readonly<Partial<R>>,
constantPool: ConstantPool,
): CompileResult | CompileResult[];
}
/**
* The output of detecting a trait for a declaration as the result of the first phase of the
* compilation pipeline.
*/ | {
"end_byte": 8687,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/transform/src/api.ts_8688_10447 | export interface DetectResult<M> {
/**
* The node that triggered the match, which is typically a decorator.
*/
trigger: ts.Node | null;
/**
* Refers to the decorator that was recognized for this detection, if any. This can be a concrete
* decorator that is actually present in a file, or a synthetic decorator as inserted
* programmatically.
*/
decorator: Decorator | null;
/**
* An arbitrary object to carry over from the detection phase into the analysis phase.
*/
metadata: Readonly<M>;
}
/**
* The output of an analysis operation, consisting of possibly an arbitrary analysis object (used as
* the input to code generation) and potentially diagnostics if there were errors uncovered during
* analysis.
*/
export interface AnalysisOutput<A> {
analysis?: Readonly<A>;
diagnostics?: ts.Diagnostic[];
}
/**
* A description of the static field to add to a class, including an initialization expression
* and a type for the .d.ts file.
*/
export interface CompileResult {
name: string;
initializer: Expression | null;
statements: Statement[];
type: Type;
deferrableImports: Set<ts.ImportDeclaration> | null;
}
export interface ResolveResult<R> {
reexports?: Reexport[];
diagnostics?: ts.Diagnostic[];
data?: Readonly<R>;
}
export interface DtsTransform {
transformClassElement?(element: ts.ClassElement, imports: ImportManager): ts.ClassElement;
transformFunctionDeclaration?(
element: ts.FunctionDeclaration,
imports: ImportManager,
): ts.FunctionDeclaration;
transformClass?(
clazz: ts.ClassDeclaration,
elements: ReadonlyArray<ts.ClassElement>,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
imports: ImportManager,
): ts.ClassDeclaration;
} | {
"end_byte": 10447,
"start_byte": 8688,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/transform/src/declaration.ts_0_8169 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Type} from '@angular/compiler';
import ts from 'typescript';
import {ImportRewriter, ReferenceEmitter} from '../../imports';
import {ClassDeclaration, ReflectionHost} from '../../reflection';
import {
ImportManager,
presetImportManagerForceNamespaceImports,
translateType,
} from '../../translator';
import {DtsTransform} from './api';
/**
* Keeps track of `DtsTransform`s per source file, so that it is known which source files need to
* have their declaration file transformed.
*/
export class DtsTransformRegistry {
private ivyDeclarationTransforms = new Map<ts.SourceFile, IvyDeclarationDtsTransform>();
getIvyDeclarationTransform(sf: ts.SourceFile): IvyDeclarationDtsTransform {
if (!this.ivyDeclarationTransforms.has(sf)) {
this.ivyDeclarationTransforms.set(sf, new IvyDeclarationDtsTransform());
}
return this.ivyDeclarationTransforms.get(sf)!;
}
/**
* Gets the dts transforms to be applied for the given source file, or `null` if no transform is
* necessary.
*/
getAllTransforms(sf: ts.SourceFile): DtsTransform[] | null {
// No need to transform if it's not a declarations file, or if no changes have been requested
// to the input file. Due to the way TypeScript afterDeclarations transformers work, the
// `ts.SourceFile` path is the same as the original .ts. The only way we know it's actually a
// declaration file is via the `isDeclarationFile` property.
if (!sf.isDeclarationFile) {
return null;
}
const originalSf = ts.getOriginalNode(sf) as ts.SourceFile;
let transforms: DtsTransform[] | null = null;
if (this.ivyDeclarationTransforms.has(originalSf)) {
transforms = [];
transforms.push(this.ivyDeclarationTransforms.get(originalSf)!);
}
return transforms;
}
}
export function declarationTransformFactory(
transformRegistry: DtsTransformRegistry,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
importRewriter: ImportRewriter,
): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => {
const transformer = new DtsTransformer(context, reflector, refEmitter, importRewriter);
return (fileOrBundle) => {
if (ts.isBundle(fileOrBundle)) {
// Only attempt to transform source files.
return fileOrBundle;
}
const transforms = transformRegistry.getAllTransforms(fileOrBundle);
if (transforms === null) {
return fileOrBundle;
}
return transformer.transform(fileOrBundle, transforms);
};
};
}
/**
* Processes .d.ts file text and adds static field declarations, with types.
*/
class DtsTransformer {
constructor(
private ctx: ts.TransformationContext,
private reflector: ReflectionHost,
private refEmitter: ReferenceEmitter,
private importRewriter: ImportRewriter,
) {}
/**
* Transform the declaration file and add any declarations which were recorded.
*/
transform(sf: ts.SourceFile, transforms: DtsTransform[]): ts.SourceFile {
const imports = new ImportManager({
...presetImportManagerForceNamespaceImports,
rewriter: this.importRewriter,
});
const visitor: ts.Visitor = (node: ts.Node): ts.VisitResult<ts.Node> => {
if (ts.isClassDeclaration(node)) {
return this.transformClassDeclaration(node, transforms, imports);
} else if (ts.isFunctionDeclaration(node)) {
return this.transformFunctionDeclaration(node, transforms, imports);
} else {
// Otherwise return node as is.
return ts.visitEachChild(node, visitor, this.ctx);
}
};
// Recursively scan through the AST and process all nodes as desired.
sf = ts.visitNode(sf, visitor, ts.isSourceFile) || sf;
// Update/insert needed imports.
return imports.transformTsFile(this.ctx, sf);
}
private transformClassDeclaration(
clazz: ts.ClassDeclaration,
transforms: DtsTransform[],
imports: ImportManager,
): ts.ClassDeclaration {
let elements: ts.ClassElement[] | ReadonlyArray<ts.ClassElement> = clazz.members;
let elementsChanged = false;
for (const transform of transforms) {
if (transform.transformClassElement !== undefined) {
for (let i = 0; i < elements.length; i++) {
const res = transform.transformClassElement(elements[i], imports);
if (res !== elements[i]) {
if (!elementsChanged) {
elements = [...elements];
elementsChanged = true;
}
(elements as ts.ClassElement[])[i] = res;
}
}
}
}
let newClazz: ts.ClassDeclaration = clazz;
for (const transform of transforms) {
if (transform.transformClass !== undefined) {
// If no DtsTransform has changed the class yet, then the (possibly mutated) elements have
// not yet been incorporated. Otherwise, `newClazz.members` holds the latest class members.
const inputMembers = clazz === newClazz ? elements : newClazz.members;
newClazz = transform.transformClass(
newClazz,
inputMembers,
this.reflector,
this.refEmitter,
imports,
);
}
}
// If some elements have been transformed but the class itself has not been transformed, create
// an updated class declaration with the updated elements.
if (elementsChanged && clazz === newClazz) {
newClazz = ts.factory.updateClassDeclaration(
/* node */ clazz,
/* modifiers */ clazz.modifiers,
/* name */ clazz.name,
/* typeParameters */ clazz.typeParameters,
/* heritageClauses */ clazz.heritageClauses,
/* members */ elements,
);
}
return newClazz;
}
private transformFunctionDeclaration(
declaration: ts.FunctionDeclaration,
transforms: DtsTransform[],
imports: ImportManager,
): ts.FunctionDeclaration {
let newDecl = declaration;
for (const transform of transforms) {
if (transform.transformFunctionDeclaration !== undefined) {
newDecl = transform.transformFunctionDeclaration(newDecl, imports);
}
}
return newDecl;
}
}
export interface IvyDeclarationField {
name: string;
type: Type;
}
export class IvyDeclarationDtsTransform implements DtsTransform {
private declarationFields = new Map<ClassDeclaration, IvyDeclarationField[]>();
addFields(decl: ClassDeclaration, fields: IvyDeclarationField[]): void {
this.declarationFields.set(decl, fields);
}
transformClass(
clazz: ts.ClassDeclaration,
members: ReadonlyArray<ts.ClassElement>,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
imports: ImportManager,
): ts.ClassDeclaration {
const original = ts.getOriginalNode(clazz) as ClassDeclaration;
if (!this.declarationFields.has(original)) {
return clazz;
}
const fields = this.declarationFields.get(original)!;
const newMembers = fields.map((decl) => {
const modifiers = [ts.factory.createModifier(ts.SyntaxKind.StaticKeyword)];
const typeRef = translateType(
decl.type,
original.getSourceFile(),
reflector,
refEmitter,
imports,
);
markForEmitAsSingleLine(typeRef);
return ts.factory.createPropertyDeclaration(
/* modifiers */ modifiers,
/* name */ decl.name,
/* questionOrExclamationToken */ undefined,
/* type */ typeRef,
/* initializer */ undefined,
);
});
return ts.factory.updateClassDeclaration(
/* node */ clazz,
/* modifiers */ clazz.modifiers,
/* name */ clazz.name,
/* typeParameters */ clazz.typeParameters,
/* heritageClauses */ clazz.heritageClauses,
/* members */ [...members, ...newMembers],
);
}
}
function markForEmitAsSingleLine(node: ts.Node) {
ts.setEmitFlags(node, ts.EmitFlags.SingleLine);
ts.forEachChild(node, markForEmitAsSingleLine);
}
| {
"end_byte": 8169,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/declaration.ts"
} |
angular/packages/compiler-cli/src/ngtsc/transform/src/trait.ts_0_5500 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {SemanticSymbol} from '../../incremental/semantic_graph';
import {DecoratorHandler, DetectResult} from './api';
export enum TraitState {
/**
* Pending traits are freshly created and have never been analyzed.
*/
Pending,
/**
* Analyzed traits have successfully been analyzed, but are pending resolution.
*/
Analyzed,
/**
* Resolved traits have successfully been analyzed and resolved and are ready for compilation.
*/
Resolved,
/**
* Skipped traits are no longer considered for compilation.
*/
Skipped,
}
/**
* An Ivy aspect added to a class (for example, the compilation of a component definition).
*
* Traits are created when a `DecoratorHandler` matches a class. Each trait begins in a pending
* state and undergoes transitions as compilation proceeds through the various steps.
*
* In practice, traits are instances of the private class `TraitImpl` declared below. Through the
* various interfaces included in this union type, the legal API of a trait in any given state is
* represented in the type system. This includes any possible transitions from one type to the next.
*
* This not only simplifies the implementation, but ensures traits are monomorphic objects as
* they're all just "views" in the type system of the same object (which never changes shape).
*/
export type Trait<D, A, S extends SemanticSymbol | null, R> =
| PendingTrait<D, A, S, R>
| SkippedTrait<D, A, S, R>
| AnalyzedTrait<D, A, S, R>
| ResolvedTrait<D, A, S, R>;
/**
* The value side of `Trait` exposes a helper to create a `Trait` in a pending state (by delegating
* to `TraitImpl`).
*/
export const Trait = {
pending: <D, A, S extends SemanticSymbol | null, R>(
handler: DecoratorHandler<D, A, S, R>,
detected: DetectResult<D>,
): PendingTrait<D, A, S, R> => TraitImpl.pending(handler, detected),
};
/**
* The part of the `Trait` interface that's common to all trait states.
*/
export interface TraitBase<D, A, S extends SemanticSymbol | null, R> {
/**
* Current state of the trait.
*
* This will be narrowed in the interfaces for each specific state.
*/
state: TraitState;
/**
* The `DecoratorHandler` which matched on the class to create this trait.
*/
handler: DecoratorHandler<D, A, S, R>;
/**
* The detection result (of `handler.detect`) which indicated that this trait applied to the
* class.
*
* This is mainly used to cache the detection between pre-analysis and analysis.
*/
detected: DetectResult<D>;
}
/**
* A trait in the pending state.
*
* Pending traits have yet to be analyzed in any way.
*/
export interface PendingTrait<D, A, S extends SemanticSymbol | null, R>
extends TraitBase<D, A, S, R> {
state: TraitState.Pending;
/**
* This pending trait has been successfully analyzed, and should transition to the "analyzed"
* state.
*/
toAnalyzed(
analysis: A | null,
diagnostics: ts.Diagnostic[] | null,
symbol: S,
): AnalyzedTrait<D, A, S, R>;
/**
* During analysis it was determined that this trait is not eligible for compilation after all,
* and should be transitioned to the "skipped" state.
*/
toSkipped(): SkippedTrait<D, A, S, R>;
}
/**
* A trait in the "skipped" state.
*
* Skipped traits aren't considered for compilation.
*
* This is a terminal state.
*/
export interface SkippedTrait<D, A, S extends SemanticSymbol | null, R>
extends TraitBase<D, A, S, R> {
state: TraitState.Skipped;
}
/**
* A trait in the "analyzed" state.
*
* Analyzed traits have analysis results available, and are eligible for resolution.
*/
export interface AnalyzedTrait<D, A, S extends SemanticSymbol | null, R>
extends TraitBase<D, A, S, R> {
state: TraitState.Analyzed;
symbol: S;
/**
* Analysis results of the given trait (if able to be produced), or `null` if analysis failed
* completely.
*/
analysis: Readonly<A> | null;
/**
* Any diagnostics that resulted from analysis, or `null` if none.
*/
analysisDiagnostics: ts.Diagnostic[] | null;
/**
* This analyzed trait has been successfully resolved, and should be transitioned to the
* "resolved" state.
*/
toResolved(resolution: R | null, diagnostics: ts.Diagnostic[] | null): ResolvedTrait<D, A, S, R>;
}
/**
* A trait in the "resolved" state.
*
* Resolved traits have been successfully analyzed and resolved, contain no errors, and are ready
* for the compilation phase.
*
* This is a terminal state.
*/
export interface ResolvedTrait<D, A, S extends SemanticSymbol | null, R>
extends TraitBase<D, A, S, R> {
state: TraitState.Resolved;
symbol: S;
/**
* Resolved traits must have produced valid analysis results.
*/
analysis: Readonly<A>;
/**
* Analysis may have still resulted in diagnostics.
*/
analysisDiagnostics: ts.Diagnostic[] | null;
/**
* Diagnostics resulting from resolution are tracked separately from
*/
resolveDiagnostics: ts.Diagnostic[] | null;
/**
* The results returned by a successful resolution of the given class/`DecoratorHandler`
* combination.
*/
resolution: Readonly<R> | null;
}
/**
* An implementation of the `Trait` type which transitions safely between the various
* `TraitState`s.
*/ | {
"end_byte": 5500,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/trait.ts"
} |
angular/packages/compiler-cli/src/ngtsc/transform/src/trait.ts_5501_8418 | class TraitImpl<D, A, S extends SemanticSymbol | null, R> {
state: TraitState = TraitState.Pending;
handler: DecoratorHandler<D, A, S, R>;
detected: DetectResult<D>;
analysis: Readonly<A> | null = null;
symbol: S | null = null;
resolution: Readonly<R> | null = null;
analysisDiagnostics: ts.Diagnostic[] | null = null;
resolveDiagnostics: ts.Diagnostic[] | null = null;
typeCheckDiagnostics: ts.Diagnostic[] | null = null;
constructor(handler: DecoratorHandler<D, A, S, R>, detected: DetectResult<D>) {
this.handler = handler;
this.detected = detected;
}
toAnalyzed(
analysis: A | null,
diagnostics: ts.Diagnostic[] | null,
symbol: S,
): AnalyzedTrait<D, A, S, R> {
// Only pending traits can be analyzed.
this.assertTransitionLegal(TraitState.Pending, TraitState.Analyzed);
this.analysis = analysis;
this.analysisDiagnostics = diagnostics;
this.symbol = symbol;
this.state = TraitState.Analyzed;
return this as AnalyzedTrait<D, A, S, R>;
}
toResolved(resolution: R | null, diagnostics: ts.Diagnostic[] | null): ResolvedTrait<D, A, S, R> {
// Only analyzed traits can be resolved.
this.assertTransitionLegal(TraitState.Analyzed, TraitState.Resolved);
if (this.analysis === null) {
throw new Error(`Cannot transition an Analyzed trait with a null analysis to Resolved`);
}
this.resolution = resolution;
this.state = TraitState.Resolved;
this.resolveDiagnostics = diagnostics;
this.typeCheckDiagnostics = null;
return this as ResolvedTrait<D, A, S, R>;
}
toSkipped(): SkippedTrait<D, A, S, R> {
// Only pending traits can be skipped.
this.assertTransitionLegal(TraitState.Pending, TraitState.Skipped);
this.state = TraitState.Skipped;
return this as SkippedTrait<D, A, S, R>;
}
/**
* Verifies that the trait is currently in one of the `allowedState`s.
*
* If correctly used, the `Trait` type and transition methods prevent illegal transitions from
* occurring. However, if a reference to the `TraitImpl` instance typed with the previous
* interface is retained after calling one of its transition methods, it will allow for illegal
* transitions to take place. Hence, this assertion provides a little extra runtime protection.
*/
private assertTransitionLegal(allowedState: TraitState, transitionTo: TraitState): void {
if (!(this.state === allowedState)) {
throw new Error(
`Assertion failure: cannot transition from ${TraitState[this.state]} to ${
TraitState[transitionTo]
}.`,
);
}
}
/**
* Construct a new `TraitImpl` in the pending state.
*/
static pending<D, A, S extends SemanticSymbol | null, R>(
handler: DecoratorHandler<D, A, S, R>,
detected: DetectResult<D>,
): PendingTrait<D, A, S, R> {
return new TraitImpl(handler, detected) as PendingTrait<D, A, S, R>;
}
} | {
"end_byte": 8418,
"start_byte": 5501,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/trait.ts"
} |
angular/packages/compiler-cli/src/ngtsc/transform/src/alias.ts_0_1158 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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';
export function aliasTransformFactory(
exportStatements: Map<string, Map<string, [string, string]>>,
): ts.TransformerFactory<ts.SourceFile> {
return () => {
return (file: ts.SourceFile) => {
if (ts.isBundle(file) || !exportStatements.has(file.fileName)) {
return file;
}
const statements = [...file.statements];
exportStatements.get(file.fileName)!.forEach(([moduleName, symbolName], aliasName) => {
const stmt = ts.factory.createExportDeclaration(
/* modifiers */ undefined,
/* isTypeOnly */ false,
/* exportClause */ ts.factory.createNamedExports([
ts.factory.createExportSpecifier(false, symbolName, aliasName),
]),
/* moduleSpecifier */ ts.factory.createStringLiteral(moduleName),
);
statements.push(stmt);
});
return ts.factory.updateSourceFile(file, statements);
};
};
}
| {
"end_byte": 1158,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/transform/src/alias.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/BUILD.bazel_0_495 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "metadata",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/util",
"@npm//typescript",
],
)
| {
"end_byte": 495,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/index.ts_0_974 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/api';
export {DtsMetadataReader} from './src/dts';
export {flattenInheritedDirectiveMetadata} from './src/inheritance';
export {CompoundMetadataRegistry, LocalMetadataRegistry} from './src/registry';
export {
ResourceRegistry,
Resource,
ComponentResources,
isExternalResource,
ExternalResource,
} from './src/resource_registry';
export {
extractDirectiveTypeCheckMeta,
hasInjectableFields,
CompoundMetadataReader,
isHostDirectiveMetaForGlobalMode,
} from './src/util';
export {
BindingPropertyName,
ClassPropertyMapping,
ClassPropertyName,
InputOrOutput,
} from './src/property_mapping';
export {ExportedProviderStatusResolver} from './src/providers';
export {HostDirectivesResolver} from './src/host_directives_resolver';
| {
"end_byte": 974,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/test/dts_spec.ts_0_658 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {absoluteFrom, getFileSystem, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {OwningModule, Reference} from '../../imports';
import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {loadAngularCore, makeProgram} from '../../testing';
import {DtsMetadataReader} from '../src/dts';
import {isHostDirectiveMetaForGlobalMode} from '../src/util'; | {
"end_byte": 658,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/test/dts_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/test/dts_spec.ts_660_9049 | runInEachFileSystem(() => {
beforeEach(() => {
loadAngularCore(getFileSystem());
});
describe('DtsMetadataReader', () => {
it('should not assume directives are structural', () => {
const mainPath = absoluteFrom('/main.d.ts');
const {program} = makeProgram(
[
{
name: mainPath,
contents: `
import {ViewContainerRef} from '@angular/core';
import * as i0 from '@angular/core';
export declare class TestDir {
constructor(p0: ViewContainerRef);
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {}, {}, never>
}
`,
},
],
{
skipLibCheck: true,
lib: ['es6', 'dom'],
},
);
const sf = getSourceFileOrError(program, mainPath);
const clazz = sf.statements[2];
if (!isNamedClassDeclaration(clazz)) {
return fail('Expected class declaration');
}
const typeChecker = program.getTypeChecker();
const dtsReader = new DtsMetadataReader(
typeChecker,
new TypeScriptReflectionHost(typeChecker),
);
const meta = dtsReader.getDirectiveMetadata(new Reference(clazz))!;
expect(meta.isStructural).toBeFalse();
});
it('should identify a structural directive by its constructor', () => {
const mainPath = absoluteFrom('/main.d.ts');
const {program} = makeProgram(
[
{
name: mainPath,
contents: `
import {TemplateRef, ViewContainerRef} from '@angular/core';
import * as i0 from '@angular/core';
export declare class TestDir {
constructor(p0: ViewContainerRef, p1: TemplateRef);
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {}, {}, never>
}
`,
},
],
{
skipLibCheck: true,
lib: ['es6', 'dom'],
},
);
const sf = getSourceFileOrError(program, mainPath);
const clazz = sf.statements[2];
if (!isNamedClassDeclaration(clazz)) {
return fail('Expected class declaration');
}
const typeChecker = program.getTypeChecker();
const dtsReader = new DtsMetadataReader(
typeChecker,
new TypeScriptReflectionHost(typeChecker),
);
const meta = dtsReader.getDirectiveMetadata(new Reference(clazz))!;
expect(meta.isStructural).toBeTrue();
});
it('should retain an absolute owning module for relative imports', () => {
const externalPath = absoluteFrom('/external.d.ts');
const {program} = makeProgram(
[
{
name: externalPath,
contents: `
import * as i0 from '@angular/core';
import * as i1 from 'absolute';
import * as i2 from './relative';
export declare class ExternalModule {
static ɵmod: i0.ɵɵNgModuleDeclaration<RelativeModule, [typeof i2.RelativeDir], never, [typeof i1.AbsoluteDir, typeof i2.RelativeDir]>;
}
`,
},
{
name: absoluteFrom('/relative.d.ts'),
contents: `
import * as i0 from '@angular/core';
export declare class RelativeDir {
static ɵdir: i0.ɵɵDirectiveDeclaration<RelativeDir, '[dir]', never, never, never, never>;
}
`,
},
{
name: absoluteFrom('/node_modules/absolute.d.ts'),
contents: `
import * as i0 from '@angular/core';
export declare class AbsoluteDir {
static ɵdir: i0.ɵɵDirectiveDeclaration<ExternalDir, '[dir]', never, never, never, never>;
}
`,
},
],
{
skipLibCheck: true,
lib: ['es6', 'dom'],
},
);
const externalSf = getSourceFileOrError(program, externalPath);
const clazz = externalSf.statements[3];
if (!isNamedClassDeclaration(clazz)) {
return fail('Expected class declaration');
}
const typeChecker = program.getTypeChecker();
const dtsReader = new DtsMetadataReader(
typeChecker,
new TypeScriptReflectionHost(typeChecker),
);
const withoutOwningModule = dtsReader.getNgModuleMetadata(new Reference(clazz))!;
expect(withoutOwningModule.exports.length).toBe(2);
// `AbsoluteDir` was imported from an absolute module so the export Reference should have
// a corresponding best guess owning module.
expect(withoutOwningModule.exports[0].bestGuessOwningModule).toEqual({
specifier: 'absolute',
resolutionContext: externalSf.fileName,
});
// `RelativeDir` was imported from a relative module specifier so the original reference's
// best guess owning module should have been retained, which was null.
expect(withoutOwningModule.exports[1].bestGuessOwningModule).toBeNull();
const owningModule: OwningModule = {
specifier: 'module',
resolutionContext: absoluteFrom('/context.ts'),
};
const withOwningModule = dtsReader.getNgModuleMetadata(new Reference(clazz, owningModule))!;
expect(withOwningModule.exports.length).toBe(2);
// Again, `AbsoluteDir` was imported from an absolute module so the export Reference should
// have a corresponding best guess owning module; the owning module of the incoming reference
// is irrelevant here.
expect(withOwningModule.exports[0].bestGuessOwningModule).toEqual({
specifier: 'absolute',
resolutionContext: externalSf.fileName,
});
// As `RelativeDir` was imported from a relative module specifier, the export Reference should
// continue to have the owning module of the incoming reference as the relatively imported
// symbol is assumed to also be exported from the absolute module specifier as captured in the
// best guess owning module.
expect(withOwningModule.exports[1].bestGuessOwningModule).toEqual(owningModule);
});
});
it('should identify host directives', () => {
const mainPath = absoluteFrom('/main.d.ts');
const {program} = makeProgram(
[
{
name: mainPath,
contents: `
import * as i0 from '@angular/core';
export declare class SimpleHostDir {
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {}, {}, never, never, true, never>
}
export declare class AdvancedHostDir {
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {"input": "inputAlias"}, {"output": "outputAlias"}, never, never, true, never>
}
export declare class Dir {
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {}, {}, never, never, true, [
{directive: typeof SimpleHostDir; inputs: {}; outputs: {};},
{directive: typeof AdvancedHostDir; inputs: { "inputAlias": "customInputAlias"; }; outputs: { "outputAlias": "customOutputAlias"; };}
]>
}
`,
},
],
{
skipLibCheck: true,
lib: ['es6', 'dom'],
},
);
const sf = getSourceFileOrError(program, mainPath);
const clazz = sf.statements[3];
if (!isNamedClassDeclaration(clazz)) {
return fail('Expected class declaration');
}
const typeChecker = program.getTypeChecker();
const dtsReader = new DtsMetadataReader(typeChecker, new TypeScriptReflectionHost(typeChecker));
const meta = dtsReader.getDirectiveMetadata(new Reference(clazz))!;
const hostDirectives = meta.hostDirectives?.map((hostDir) => ({
name: isHostDirectiveMetaForGlobalMode(hostDir)
? hostDir.directive.debugName
: 'Unresolved host dir',
directive: hostDir.directive,
inputs: hostDir.inputs,
outputs: hostDir.outputs,
}));
expect(hostDirectives).toEqual([
{
name: 'SimpleHostDir',
directive: jasmine.any(Reference),
inputs: {},
outputs: {},
},
{
name: 'AdvancedHostDir',
directive: jasmine.any(Reference),
inputs: {inputAlias: 'customInputAlias'},
outputs: {outputAlias: 'customOutputAlias'},
},
]);
});
it('should read the | {
"end_byte": 9049,
"start_byte": 660,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/test/dts_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/test/dts_spec.ts_9053_11600 | -v16 inputs map syntax', () => {
const mainPath = absoluteFrom('/main.d.ts');
const {program} = makeProgram(
[
{
name: mainPath,
contents: `
import * as i0 from '@angular/core';
export declare class TestDir {
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {
"input": {"alias": "input", "required": false},
"otherInput": {"alias": "alias", "required": true}
}, {}, never>
}
`,
},
],
{
skipLibCheck: true,
lib: ['es6', 'dom'],
},
);
const sf = getSourceFileOrError(program, mainPath);
const clazz = sf.statements[1];
if (!isNamedClassDeclaration(clazz)) {
return fail('Expected class declaration');
}
const typeChecker = program.getTypeChecker();
const dtsReader = new DtsMetadataReader(typeChecker, new TypeScriptReflectionHost(typeChecker));
const meta = dtsReader.getDirectiveMetadata(new Reference(clazz))!;
expect(meta.inputs.toDirectMappedObject()).toEqual({input: 'input', otherInput: 'alias'});
expect(
Array.from(meta.inputs)
.filter((i) => i.required)
.map((i) => i.classPropertyName),
).toEqual(['otherInput']);
});
it('should read the pre-v16 inputs map syntax', () => {
const mainPath = absoluteFrom('/main.d.ts');
const {program} = makeProgram(
[
{
name: mainPath,
contents: `
import * as i0 from '@angular/core';
export declare class TestDir {
static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[test]", never, {
"input": "input",
"otherInput": "alias"
}, {}, never>
}
`,
},
],
{
skipLibCheck: true,
lib: ['es6', 'dom'],
},
);
const sf = getSourceFileOrError(program, mainPath);
const clazz = sf.statements[1];
if (!isNamedClassDeclaration(clazz)) {
return fail('Expected class declaration');
}
const typeChecker = program.getTypeChecker();
const dtsReader = new DtsMetadataReader(typeChecker, new TypeScriptReflectionHost(typeChecker));
const meta = dtsReader.getDirectiveMetadata(new Reference(clazz))!;
expect(meta.inputs.toDirectMappedObject()).toEqual({input: 'input', otherInput: 'alias'});
expect(Array.from(meta.inputs).filter((i) => i.required)).toEqual([]);
});
});
| {
"end_byte": 11600,
"start_byte": 9053,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/test/dts_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/test/BUILD.bazel_0_926 | 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/imports",
"//packages/compiler-cli/src/ngtsc/metadata",
"//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"],
data = [
"//packages/core:npm_package",
],
deps =
[
":test_lib",
],
)
| {
"end_byte": 926,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.ts_0_3143 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ClassDeclaration} from '../../reflection';
import {DirectiveMeta, HostDirectiveMeta, InputMapping, MetadataReader} from './api';
import {ClassPropertyMapping, ClassPropertyName} from './property_mapping';
/**
* Given a reference to a directive, return a flattened version of its `DirectiveMeta` metadata
* which includes metadata from its entire inheritance chain.
*
* The returned `DirectiveMeta` will either have `baseClass: null` if the inheritance chain could be
* fully resolved, or `baseClass: 'dynamic'` if the inheritance chain could not be completely
* followed.
*/
export function flattenInheritedDirectiveMetadata(
reader: MetadataReader,
dir: Reference<ClassDeclaration>,
): DirectiveMeta | null {
const topMeta = reader.getDirectiveMetadata(dir);
if (topMeta === null) {
return null;
}
if (topMeta.baseClass === null) {
return topMeta;
}
const coercedInputFields = new Set<ClassPropertyName>();
const undeclaredInputFields = new Set<ClassPropertyName>();
const restrictedInputFields = new Set<ClassPropertyName>();
const stringLiteralInputFields = new Set<ClassPropertyName>();
let hostDirectives: HostDirectiveMeta[] | null = null;
let isDynamic = false;
let inputs = ClassPropertyMapping.empty<InputMapping>();
let outputs = ClassPropertyMapping.empty();
let isStructural: boolean = false;
const addMetadata = (meta: DirectiveMeta): void => {
if (meta.baseClass === 'dynamic') {
isDynamic = true;
} else if (meta.baseClass !== null) {
const baseMeta = reader.getDirectiveMetadata(meta.baseClass);
if (baseMeta !== null) {
addMetadata(baseMeta);
} else {
// Missing metadata for the base class means it's effectively dynamic.
isDynamic = true;
}
}
isStructural = isStructural || meta.isStructural;
inputs = ClassPropertyMapping.merge(inputs, meta.inputs);
outputs = ClassPropertyMapping.merge(outputs, meta.outputs);
for (const coercedInputField of meta.coercedInputFields) {
coercedInputFields.add(coercedInputField);
}
for (const undeclaredInputField of meta.undeclaredInputFields) {
undeclaredInputFields.add(undeclaredInputField);
}
for (const restrictedInputField of meta.restrictedInputFields) {
restrictedInputFields.add(restrictedInputField);
}
for (const field of meta.stringLiteralInputFields) {
stringLiteralInputFields.add(field);
}
if (meta.hostDirectives !== null && meta.hostDirectives.length > 0) {
hostDirectives ??= [];
hostDirectives.push(...meta.hostDirectives);
}
};
addMetadata(topMeta);
return {
...topMeta,
inputs,
outputs,
coercedInputFields,
undeclaredInputFields,
restrictedInputFields,
stringLiteralInputFields,
baseClass: isDynamic ? 'dynamic' : null,
isStructural,
hostDirectives,
};
}
| {
"end_byte": 3143,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/resource_registry.ts_0_3962 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {AbsoluteFsPath} from '../../file_system';
import {ClassDeclaration} from '../../reflection';
/**
* Represents an resource for a component and contains the `AbsoluteFsPath`
* to the file which was resolved by evaluating the `ts.Expression` (generally, a relative or
* absolute string path to the resource).
*
* If the resource is inline, the `path` will be `null`.
*/
export interface Resource {
path: AbsoluteFsPath | null;
expression: ts.Expression;
}
export interface ExternalResource extends Resource {
path: AbsoluteFsPath;
}
export function isExternalResource(resource: Resource): resource is ExternalResource {
return resource.path !== null;
}
/**
* Represents the either inline or external resources of a component.
*
* A resource with a `path` of `null` is considered inline.
*/
export interface ComponentResources {
template: Resource;
styles: ReadonlySet<Resource>;
}
/**
* Tracks the mapping between external template/style files and the component(s) which use them.
*
* This information is produced during analysis of the program and is used mainly to support
* external tooling, for which such a mapping is challenging to determine without compiler
* assistance.
*/
export class ResourceRegistry {
private externalTemplateToComponentsMap = new Map<AbsoluteFsPath, Set<ClassDeclaration>>();
private componentToTemplateMap = new Map<ClassDeclaration, Resource>();
private componentToStylesMap = new Map<ClassDeclaration, Set<Resource>>();
private externalStyleToComponentsMap = new Map<AbsoluteFsPath, Set<ClassDeclaration>>();
getComponentsWithTemplate(template: AbsoluteFsPath): ReadonlySet<ClassDeclaration> {
if (!this.externalTemplateToComponentsMap.has(template)) {
return new Set();
}
return this.externalTemplateToComponentsMap.get(template)!;
}
registerResources(resources: ComponentResources, component: ClassDeclaration) {
if (resources.template !== null) {
this.registerTemplate(resources.template, component);
}
for (const style of resources.styles) {
this.registerStyle(style, component);
}
}
registerTemplate(templateResource: Resource, component: ClassDeclaration): void {
const {path} = templateResource;
if (path !== null) {
if (!this.externalTemplateToComponentsMap.has(path)) {
this.externalTemplateToComponentsMap.set(path, new Set());
}
this.externalTemplateToComponentsMap.get(path)!.add(component);
}
this.componentToTemplateMap.set(component, templateResource);
}
getTemplate(component: ClassDeclaration): Resource | null {
if (!this.componentToTemplateMap.has(component)) {
return null;
}
return this.componentToTemplateMap.get(component)!;
}
registerStyle(styleResource: Resource, component: ClassDeclaration): void {
const {path} = styleResource;
if (!this.componentToStylesMap.has(component)) {
this.componentToStylesMap.set(component, new Set());
}
if (path !== null) {
if (!this.externalStyleToComponentsMap.has(path)) {
this.externalStyleToComponentsMap.set(path, new Set());
}
this.externalStyleToComponentsMap.get(path)!.add(component);
}
this.componentToStylesMap.get(component)!.add(styleResource);
}
getStyles(component: ClassDeclaration): Set<Resource> {
if (!this.componentToStylesMap.has(component)) {
return new Set();
}
return this.componentToStylesMap.get(component)!;
}
getComponentsWithStyle(styleUrl: AbsoluteFsPath): ReadonlySet<ClassDeclaration> {
if (!this.externalStyleToComponentsMap.has(styleUrl)) {
return new Set();
}
return this.externalStyleToComponentsMap.get(styleUrl)!;
}
}
| {
"end_byte": 3962,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/resource_registry.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts_0_8140 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {OwningModule, Reference} from '../../imports';
import {
ClassDeclaration,
isNamedClassDeclaration,
ReflectionHost,
TypeValueReferenceKind,
} from '../../reflection';
import {nodeDebugInfo} from '../../util/src/typescript';
import {
DirectiveMeta,
HostDirectiveMeta,
InputMapping,
MatchSource,
MetadataReader,
MetaKind,
NgModuleMeta,
PipeMeta,
} from './api';
import {ClassPropertyMapping} from './property_mapping';
import {
extractDirectiveTypeCheckMeta,
extractReferencesFromType,
extraReferenceFromTypeQuery,
readBooleanType,
readMapType,
readStringArrayType,
readStringType,
} from './util';
/**
* A `MetadataReader` that can read metadata from `.d.ts` files, which have static Ivy properties
* from an upstream compilation already.
*/
export class DtsMetadataReader implements MetadataReader {
constructor(
private checker: ts.TypeChecker,
private reflector: ReflectionHost,
) {}
/**
* Read the metadata from a class that has already been compiled somehow (either it's in a .d.ts
* file, or in a .ts file with a handwritten definition).
*
* @param ref `Reference` to the class of interest, with the context of how it was obtained.
*/
getNgModuleMetadata(ref: Reference<ClassDeclaration>): NgModuleMeta | null {
const clazz = ref.node;
// This operation is explicitly not memoized, as it depends on `ref.ownedByModuleGuess`.
// TODO(alxhub): investigate caching of .d.ts module metadata.
const ngModuleDef = this.reflector
.getMembersOfClass(clazz)
.find((member) => member.name === 'ɵmod' && member.isStatic);
if (ngModuleDef === undefined) {
return null;
} else if (
// Validate that the shape of the ngModuleDef type is correct.
ngModuleDef.type === null ||
!ts.isTypeReferenceNode(ngModuleDef.type) ||
ngModuleDef.type.typeArguments === undefined ||
ngModuleDef.type.typeArguments.length !== 4
) {
return null;
}
// Read the ModuleData out of the type arguments.
const [_, declarationMetadata, importMetadata, exportMetadata] = ngModuleDef.type.typeArguments;
return {
kind: MetaKind.NgModule,
ref,
declarations: extractReferencesFromType(
this.checker,
declarationMetadata,
ref.bestGuessOwningModule,
),
exports: extractReferencesFromType(this.checker, exportMetadata, ref.bestGuessOwningModule),
imports: extractReferencesFromType(this.checker, importMetadata, ref.bestGuessOwningModule),
schemas: [],
rawDeclarations: null,
rawImports: null,
rawExports: null,
decorator: null,
// NgModules declared outside the current compilation are assumed to contain providers, as it
// would be a non-breaking change for a library to introduce providers at any point.
mayDeclareProviders: true,
};
}
/**
* Read directive (or component) metadata from a referenced class in a .d.ts file.
*/
getDirectiveMetadata(ref: Reference<ClassDeclaration>): DirectiveMeta | null {
const clazz = ref.node;
const def = this.reflector
.getMembersOfClass(clazz)
.find((field) => field.isStatic && (field.name === 'ɵcmp' || field.name === 'ɵdir'));
if (def === undefined) {
// No definition could be found.
return null;
} else if (
def.type === null ||
!ts.isTypeReferenceNode(def.type) ||
def.type.typeArguments === undefined ||
def.type.typeArguments.length < 2
) {
// The type metadata was the wrong shape.
return null;
}
const isComponent = def.name === 'ɵcmp';
const ctorParams = this.reflector.getConstructorParameters(clazz);
// A directive is considered to be structural if:
// 1) it's a directive, not a component, and
// 2) it injects `TemplateRef`
const isStructural =
!isComponent &&
ctorParams !== null &&
ctorParams.some((param) => {
return (
param.typeValueReference.kind === TypeValueReferenceKind.IMPORTED &&
param.typeValueReference.moduleName === '@angular/core' &&
param.typeValueReference.importedName === 'TemplateRef'
);
});
const ngContentSelectors =
def.type.typeArguments.length > 6 ? readStringArrayType(def.type.typeArguments[6]) : null;
// Note: the default value is still `false` here, because only legacy .d.ts files written before
// we had so many arguments use this default.
const isStandalone =
def.type.typeArguments.length > 7 && (readBooleanType(def.type.typeArguments[7]) ?? false);
const inputs = ClassPropertyMapping.fromMappedObject(readInputsType(def.type.typeArguments[3]));
const outputs = ClassPropertyMapping.fromMappedObject(
readMapType(def.type.typeArguments[4], readStringType),
);
const hostDirectives =
def.type.typeArguments.length > 8
? readHostDirectivesType(this.checker, def.type.typeArguments[8], ref.bestGuessOwningModule)
: null;
const isSignal =
def.type.typeArguments.length > 9 && (readBooleanType(def.type.typeArguments[9]) ?? false);
return {
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: clazz.name.text,
isComponent,
selector: readStringType(def.type.typeArguments[1]),
exportAs: readStringArrayType(def.type.typeArguments[2]),
inputs,
outputs,
hostDirectives,
queries: readStringArrayType(def.type.typeArguments[5]),
...extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector),
baseClass: readBaseClass(clazz, this.checker, this.reflector),
isPoisoned: false,
isStructural,
animationTriggerNames: null,
ngContentSelectors,
isStandalone,
isSignal,
// We do not transfer information about inputs from class metadata
// via `.d.ts` declarations. This is fine because this metadata is
// currently only used for classes defined in source files. E.g. in migrations.
inputFieldNamesFromMetadataArray: null,
// Imports are tracked in metadata only for template type-checking purposes,
// so standalone components from .d.ts files don't have any.
imports: null,
rawImports: null,
deferredImports: null,
// The same goes for schemas.
schemas: null,
decorator: null,
// Assume that standalone components from .d.ts files may export providers.
assumedToExportProviders: isComponent && isStandalone,
// `preserveWhitespaces` isn't encoded in the .d.ts and is only
// used to increase the accuracy of a diagnostic.
preserveWhitespaces: false,
isExplicitlyDeferred: false,
};
}
/**
* Read pipe metadata from a referenced class in a .d.ts file.
*/
getPipeMetadata(ref: Reference<ClassDeclaration>): PipeMeta | null {
const def = this.reflector
.getMembersOfClass(ref.node)
.find((field) => field.isStatic && field.name === 'ɵpipe');
if (def === undefined) {
// No definition could be found.
return null;
} else if (
def.type === null ||
!ts.isTypeReferenceNode(def.type) ||
def.type.typeArguments === undefined ||
def.type.typeArguments.length < 2
) {
// The type metadata was the wrong shape.
return null;
}
const type = def.type.typeArguments[1];
if (!ts.isLiteralTypeNode(type) || !ts.isStringLiteral(type.literal)) {
// The type metadata was the wrong type.
return null;
}
const name = type.literal.text;
const isStandalone =
def.type.typeArguments.length > 2 && (readBooleanType(def.type.typeArguments[2]) ?? false);
return {
kind: MetaKind.Pipe,
ref,
name,
nameExpr: null,
isStandalone,
decorator: null,
isExplicitlyDeferred: false,
};
}
}
fun | {
"end_byte": 8140,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts_8142_12244 | ion readInputsType(type: ts.TypeNode): Record<string, InputMapping> {
const inputsMap = {} as Record<string, InputMapping>;
if (ts.isTypeLiteralNode(type)) {
for (const member of type.members) {
if (
!ts.isPropertySignature(member) ||
member.type === undefined ||
member.name === undefined ||
(!ts.isStringLiteral(member.name) && !ts.isIdentifier(member.name))
) {
continue;
}
const stringValue = readStringType(member.type);
const classPropertyName = member.name.text;
// Before v16 the inputs map has the type of `{[field: string]: string}`.
// After v16 it has the type of `{[field: string]: {alias: string, required: boolean}}`.
if (stringValue != null) {
inputsMap[classPropertyName] = {
bindingPropertyName: stringValue,
classPropertyName,
required: false,
// Signal inputs were not supported pre v16- so those inputs are never signal based.
isSignal: false,
// Input transform are only tracked for locally-compiled directives. Directives coming
// from the .d.ts already have them included through `ngAcceptInputType` class members,
// or via the `InputSignal` type of the member.
transform: null,
};
} else {
const config = readMapType(member.type, (innerValue) => {
return readStringType(innerValue) ?? readBooleanType(innerValue);
}) as {alias: string; required: boolean; isSignal?: boolean};
inputsMap[classPropertyName] = {
classPropertyName,
bindingPropertyName: config.alias,
required: config.required,
isSignal: !!config.isSignal,
// Input transform are only tracked for locally-compiled directives. Directives coming
// from the .d.ts already have them included through `ngAcceptInputType` class members,
// or via the `InputSignal` type of the member.
transform: null,
};
}
}
}
return inputsMap;
}
function readBaseClass(
clazz: ClassDeclaration,
checker: ts.TypeChecker,
reflector: ReflectionHost,
): Reference<ClassDeclaration> | 'dynamic' | null {
if (!isNamedClassDeclaration(clazz)) {
// Technically this is an error in a .d.ts file, but for the purposes of finding the base class
// it's ignored.
return reflector.hasBaseClass(clazz) ? 'dynamic' : null;
}
if (clazz.heritageClauses !== undefined) {
for (const clause of clazz.heritageClauses) {
if (clause.token === ts.SyntaxKind.ExtendsKeyword) {
const baseExpr = clause.types[0].expression;
let symbol = checker.getSymbolAtLocation(baseExpr);
if (symbol === undefined) {
return 'dynamic';
} else if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = checker.getAliasedSymbol(symbol);
}
if (
symbol.valueDeclaration !== undefined &&
isNamedClassDeclaration(symbol.valueDeclaration)
) {
return new Reference(symbol.valueDeclaration);
} else {
return 'dynamic';
}
}
}
}
return null;
}
function readHostDirectivesType(
checker: ts.TypeChecker,
type: ts.TypeNode,
bestGuessOwningModule: OwningModule | null,
): HostDirectiveMeta[] | null {
if (!ts.isTupleTypeNode(type) || type.elements.length === 0) {
return null;
}
const result: HostDirectiveMeta[] = [];
for (const hostDirectiveType of type.elements) {
const {directive, inputs, outputs} = readMapType(hostDirectiveType, (type) => type);
if (directive) {
if (!ts.isTypeQueryNode(directive)) {
throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(directive)}`);
}
result.push({
directive: extraReferenceFromTypeQuery(checker, directive, type, bestGuessOwningModule),
isForwardReference: false,
inputs: readMapType(inputs, readStringType),
outputs: readMapType(outputs, readStringType),
});
}
}
return result.length > 0 ? result : null;
}
| {
"end_byte": 12244,
"start_byte": 8142,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/dts.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/host_directives_resolver.ts_0_4140 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DirectiveMeta, InputMapping, MatchSource, MetadataReader} from '../../metadata/src/api';
import {ClassDeclaration} from '../../reflection';
import {ClassPropertyMapping, InputOrOutput} from '../src/property_mapping';
import {flattenInheritedDirectiveMetadata} from './inheritance';
import {isHostDirectiveMetaForGlobalMode} from './util';
const EMPTY_ARRAY: ReadonlyArray<any> = [];
/** Resolves the host directives of a directive to a flat array of matches. */
export class HostDirectivesResolver {
private cache = new Map<ClassDeclaration, ReadonlyArray<DirectiveMeta>>();
constructor(private metaReader: MetadataReader) {}
/** Resolves all of the host directives that apply to a directive. */
resolve(metadata: DirectiveMeta): ReadonlyArray<DirectiveMeta> {
if (this.cache.has(metadata.ref.node)) {
return this.cache.get(metadata.ref.node)!;
}
const results =
metadata.hostDirectives && metadata.hostDirectives.length > 0
? this.walkHostDirectives(metadata.hostDirectives, [])
: EMPTY_ARRAY;
this.cache.set(metadata.ref.node, results);
return results;
}
/**
* Traverses all of the host directive chains and produces a flat array of
* directive metadata representing the host directives that apply to the host.
*/
private walkHostDirectives(
directives: NonNullable<DirectiveMeta['hostDirectives']>,
results: DirectiveMeta[],
): ReadonlyArray<DirectiveMeta> {
for (const current of directives) {
if (!isHostDirectiveMetaForGlobalMode(current)) {
throw new Error('Impossible state: resolving code path in local compilation mode');
}
const hostMeta = flattenInheritedDirectiveMetadata(this.metaReader, current.directive);
// This case has been checked for already and produces a diagnostic
if (hostMeta === null) {
continue;
}
if (hostMeta.hostDirectives) {
this.walkHostDirectives(hostMeta.hostDirectives, results);
}
results.push({
...hostMeta,
matchSource: MatchSource.HostDirective,
inputs: ClassPropertyMapping.fromMappedObject(
this.filterMappings(hostMeta.inputs, current.inputs, resolveInput),
),
outputs: ClassPropertyMapping.fromMappedObject(
this.filterMappings(hostMeta.outputs, current.outputs, resolveOutput),
),
});
}
return results;
}
/**
* Filters the class property mappings so that only the allowed ones are present.
* @param source Property mappings that should be filtered.
* @param allowedProperties Property mappings that are allowed in the final results.
* @param valueResolver Function used to resolve the value that is assigned to the final mapping.
*/
private filterMappings<T, M extends InputOrOutput>(
source: ClassPropertyMapping<M>,
allowedProperties: Record<string, string> | null,
valueResolver: (bindingName: string, binding: M) => T,
): Record<string, T> {
const result: Record<string, T> = {};
if (allowedProperties !== null) {
for (const publicName in allowedProperties) {
if (allowedProperties.hasOwnProperty(publicName)) {
const bindings = source.getByBindingPropertyName(publicName);
if (bindings !== null) {
for (const binding of bindings) {
result[binding.classPropertyName] = valueResolver(
allowedProperties[publicName],
binding,
);
}
}
}
}
}
return result;
}
}
function resolveInput(bindingName: string, binding: InputMapping): InputMapping {
return {
bindingPropertyName: bindingName,
classPropertyName: binding.classPropertyName,
required: binding.required,
transform: binding.transform,
isSignal: binding.isSignal,
};
}
function resolveOutput(bindingName: string): string {
return bindingName;
}
| {
"end_byte": 4140,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/host_directives_resolver.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/api.ts_0_8561 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DirectiveMeta as T2DirectiveMeta, Expression, SchemaMetadata} from '@angular/compiler';
import ts from 'typescript';
import {Reference} from '../../imports';
import {ClassDeclaration} from '../../reflection';
import {ClassPropertyMapping, ClassPropertyName, InputOrOutput} from './property_mapping';
/**
* Metadata collected for an `NgModule`.
*/
export interface NgModuleMeta {
kind: MetaKind.NgModule;
ref: Reference<ClassDeclaration>;
declarations: Reference<ClassDeclaration>[];
imports: Reference<ClassDeclaration>[];
exports: Reference<ClassDeclaration>[];
schemas: SchemaMetadata[];
/**
* The raw `ts.Expression` which gave rise to `declarations`, if one exists.
*
* If this is `null`, then either no declarations exist, or no expression was available (likely
* because the module came from a .d.ts file).
*/
rawDeclarations: ts.Expression | null;
/**
* The raw `ts.Expression` which gave rise to `imports`, if one exists.
*
* If this is `null`, then either no imports exist, or no expression was available (likely
* because the module came from a .d.ts file).
*/
rawImports: ts.Expression | null;
/**
* The raw `ts.Expression` which gave rise to `exports`, if one exists.
*
* If this is `null`, then either no exports exist, or no expression was available (likely
* because the module came from a .d.ts file).
*/
rawExports: ts.Expression | null;
/**
* The primary decorator associated with this `ngModule`.
*
* If this is `null`, no decorator exists, meaning it's probably from a .d.ts file.
*/
decorator: ts.Decorator | null;
/**
* Whether this NgModule may declare providers.
*
* If the compiler does not know if the NgModule may declare providers, this will be `true` (for
* example, NgModules declared outside the current compilation are assumed to declare providers).
*/
mayDeclareProviders: boolean;
}
/**
* Typing metadata collected for a directive within an NgModule's scope.
*/
export interface DirectiveTypeCheckMeta {
/**
* List of static `ngTemplateGuard_xx` members found on the Directive's class.
* @see `TemplateGuardMeta`
*/
ngTemplateGuards: TemplateGuardMeta[];
/**
* Whether the Directive's class has a static ngTemplateContextGuard function.
*/
hasNgTemplateContextGuard: boolean;
/**
* The set of input fields which have a corresponding static `ngAcceptInputType_` on the
* Directive's class. This allows inputs to accept a wider range of types and coerce the input to
* a narrower type with a getter/setter. See https://angular.dev/tools/cli/template-typecheck.
*/
coercedInputFields: Set<ClassPropertyName>;
/**
* The set of input fields which map to `readonly`, `private`, or `protected` members in the
* Directive's class.
*/
restrictedInputFields: Set<ClassPropertyName>;
/**
* The set of input fields which are declared as string literal members in the Directive's class.
* We need to track these separately because these fields may not be valid JS identifiers so
* we cannot use them with property access expressions when assigning inputs.
*/
stringLiteralInputFields: Set<ClassPropertyName>;
/**
* The set of input fields which do not have corresponding members in the Directive's class.
*/
undeclaredInputFields: Set<ClassPropertyName>;
/**
* Whether the Directive's class is generic, i.e. `class MyDir<T> {...}`.
*/
isGeneric: boolean;
}
/**
* Disambiguates different kinds of compiler metadata objects.
*/
export enum MetaKind {
Directive,
Pipe,
NgModule,
}
/**
* Possible ways that a directive can be matched.
*/
export enum MatchSource {
/** The directive was matched by its selector. */
Selector,
/** The directive was applied as a host directive. */
HostDirective,
}
/** Metadata for a single input mapping. */
export type InputMapping = InputOrOutput & {
required: boolean;
/**
* Transform for the input. Null if no transform is configured.
*
* For signal-based inputs, this is always `null` even if a transform
* is configured. Signal inputs capture their transform write type
* automatically in the `InputSignal`, nor is there a need to emit a
* reference to the transform.
*
* For zone-based decorator `@Input`s this is different because the transform
* write type needs to be captured in a coercion member as the decorator information
* is lost in the `.d.ts` for type-checking.
*/
transform: DecoratorInputTransform | null;
};
/** Metadata for a model mapping. */
export interface ModelMapping {
/** Node defining the model mapping. */
call: ts.CallExpression;
/** Information about the input declared by the model. */
input: InputMapping;
/** Information about the output implicitly declared by the model. */
output: InputOrOutput;
}
/** Metadata for an `@Input()` transform function. */
export interface DecoratorInputTransform {
/**
* Reference to the transform function so that it can be
* referenced when the input metadata is emitted in the declaration.
*/
node: ts.Node;
/**
* Emittable type for the input transform. Null for signal inputs
*
* This type will be used for inputs to capture the transform type
* for type-checking in corresponding `ngAcceptInputType_` members.
*/
type: Reference<ts.TypeNode>;
}
/**
* Metadata collected for a directive within an NgModule's scope.
*/
export interface DirectiveMeta extends T2DirectiveMeta, DirectiveTypeCheckMeta {
kind: MetaKind.Directive;
/** Way in which the directive was matched. */
matchSource: MatchSource;
ref: Reference<ClassDeclaration>;
/**
* Unparsed selector of the directive, or null if the directive does not have a selector.
*/
selector: string | null;
queries: string[];
/**
* A mapping of input field names to the property names.
*/
inputs: ClassPropertyMapping<InputMapping>;
/**
* List of input fields that were defined in the class decorator
* metadata. Null for directives extracted from `.d.ts`
*/
inputFieldNamesFromMetadataArray: Set<string> | null;
/**
* A mapping of output field names to the property names.
*/
outputs: ClassPropertyMapping;
/**
* A `Reference` to the base class for the directive, if one was detected.
*
* A value of `'dynamic'` indicates that while the analyzer detected that this directive extends
* another type, it could not statically determine the base class.
*/
baseClass: Reference<ClassDeclaration> | 'dynamic' | null;
/**
* Whether the directive had some issue with its declaration that means it might not have complete
* and reliable metadata.
*/
isPoisoned: boolean;
/**
* Whether the directive is likely a structural directive (injects `TemplateRef`).
*/
isStructural: boolean;
/**
* Whether the directive is a standalone entity.
*/
isStandalone: boolean;
/**
* Whether the directive is a signal entity.
*/
isSignal: boolean;
/**
* For standalone components, the list of imported types.
*/
imports: Reference<ClassDeclaration>[] | null;
/**
* Node declaring the `imports` of a standalone component. Used to produce diagnostics.
*/
rawImports: ts.Expression | null;
/**
* For standalone components, the list of imported types that can be used
* in `@defer` blocks (when only explicit dependencies are allowed).
*/
deferredImports: Reference<ClassDeclaration>[] | null;
/**
* For standalone components, the list of schemas declared.
*/
schemas: SchemaMetadata[] | null;
/**
* The primary decorator associated with this directive.
*
* If this is `null`, no decorator exists, meaning it's probably from a .d.ts file.
*/
decorator: ts.Decorator | null;
/** Additional directives applied to the directive host. */
hostDirectives: HostDirectiveMeta[] | null;
/**
* Whether the directive should be assumed to export providers if imported as a standalone type.
*/
assumedToExportProviders: boolean;
/**
* Whether this class was imported into a standalone component's
* scope via `@Component.deferredImports` field.
*/
isExplicitlyDeferred: boolean;
}
/** Metadata collected about an additional directive that is being applied to a directive host. */ | {
"end_byte": 8561,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/api.ts_8562_11744 | export interface HostDirectiveMeta {
/**
* Reference to the host directive class.
*
* Only in local compilation mode this can be Expression
* which indicates the expression could not be resolved due to being imported from some external
* file. In this case, the expression is the raw expression as appears in the decorator.
*/
directive: Reference<ClassDeclaration> | Expression;
/** Whether the reference to the host directive is a forward reference. */
isForwardReference: boolean;
/** Inputs from the host directive that have been exposed. */
inputs: {[publicName: string]: string} | null;
/** Outputs from the host directive that have been exposed. */
outputs: {[publicName: string]: string} | null;
}
/**
* Metadata collected about an additional directive that is being applied to a directive host in
* global compilation mode.
*/
export interface HostDirectiveMetaForGlobalMode extends HostDirectiveMeta {
directive: Reference<ClassDeclaration>;
}
/**
* Metadata collected about an additional directive that is being applied to a directive host in
* local compilation mode.
*/
export interface HostDirectiveMetaForLocalMode extends HostDirectiveMeta {
directive: Expression;
}
/**
* Metadata that describes a template guard for one of the directive's inputs.
*/
export interface TemplateGuardMeta {
/**
* The input name that this guard should be applied to.
*/
inputName: string;
/**
* Represents the type of the template guard.
*
* - 'invocation' means that a call to the template guard function is emitted so that its return
* type can result in narrowing of the input type.
* - 'binding' means that the input binding expression itself is used as template guard.
*/
type: 'invocation' | 'binding';
}
/**
* Metadata for a pipe within an NgModule's scope.
*/
export interface PipeMeta {
kind: MetaKind.Pipe;
ref: Reference<ClassDeclaration>;
name: string;
nameExpr: ts.Expression | null;
isStandalone: boolean;
decorator: ts.Decorator | null;
isExplicitlyDeferred: boolean;
}
/**
* Reads metadata for directives, pipes, and modules from a particular source, such as .d.ts files
* or a registry.
*/
export interface MetadataReader {
getDirectiveMetadata(node: Reference<ClassDeclaration>): DirectiveMeta | null;
getNgModuleMetadata(node: Reference<ClassDeclaration>): NgModuleMeta | null;
getPipeMetadata(node: Reference<ClassDeclaration>): PipeMeta | null;
}
/**
* A MetadataReader which also allows access to the set of all known trait classes.
*/
export interface MetadataReaderWithIndex extends MetadataReader {
getKnown(kind: MetaKind): Array<ClassDeclaration>;
}
/**
* An NgModuleIndex allows access to information about traits exported by NgModules.
*/
export interface NgModuleIndex {
getNgModulesExporting(directiveOrPipe: ClassDeclaration): Array<Reference<ClassDeclaration>>;
}
/**
* Registers new metadata for directives, pipes, and modules.
*/
export interface MetadataRegistry {
registerDirectiveMetadata(meta: DirectiveMeta): void;
registerNgModuleMetadata(meta: NgModuleMeta): void;
registerPipeMetadata(meta: PipeMeta): void;
} | {
"end_byte": 11744,
"start_byte": 8562,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/providers.ts_0_3380 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ClassDeclaration} from '../../reflection';
import {MetadataReader} from './api';
/**
* Determines whether types may or may not export providers to NgModules, by transitively walking
* the NgModule & standalone import graph.
*/
export class ExportedProviderStatusResolver {
/**
* `ClassDeclaration`s that we are in the process of determining the provider status for.
*
* This is used to detect cycles in the import graph and avoid getting stuck in them.
*/
private calculating = new Set<ClassDeclaration>();
constructor(private metaReader: MetadataReader) {}
/**
* Determines whether `ref` may or may not export providers to NgModules which import it.
*
* NgModules export providers if any are declared, and standalone components export providers from
* their `imports` array (if any).
*
* If `true`, then `ref` should be assumed to export providers. In practice, this could mean
* either that `ref` is a local type that we _know_ exports providers, or it's imported from a
* .d.ts library and is declared in a way where the compiler cannot prove that it doesn't.
*
* If `false`, then `ref` is guaranteed not to export providers.
*
* @param `ref` the class for which the provider status should be determined
* @param `dependencyCallback` a callback that, if provided, will be called for every type
* which is used in the determination of provider status for `ref`
* @returns `true` if `ref` should be assumed to export providers, or `false` if the compiler can
* prove that it does not
*/
mayExportProviders(
ref: Reference<ClassDeclaration>,
dependencyCallback?: (importRef: Reference<ClassDeclaration>) => void,
): boolean {
if (this.calculating.has(ref.node)) {
// For cycles, we treat the cyclic edge as not having providers.
return false;
}
this.calculating.add(ref.node);
if (dependencyCallback !== undefined) {
dependencyCallback(ref);
}
try {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
if (!dirMeta.isComponent || !dirMeta.isStandalone) {
return false;
}
if (dirMeta.assumedToExportProviders) {
return true;
}
// If one of the imports contains providers, then so does this component.
return (dirMeta.imports ?? []).some((importRef) =>
this.mayExportProviders(importRef, dependencyCallback),
);
}
const pipeMeta = this.metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
return false;
}
const ngModuleMeta = this.metaReader.getNgModuleMetadata(ref);
if (ngModuleMeta !== null) {
if (ngModuleMeta.mayDeclareProviders) {
return true;
}
// If one of the NgModule's imports may contain providers, then so does this NgModule.
return ngModuleMeta.imports.some((importRef) =>
this.mayExportProviders(importRef, dependencyCallback),
);
}
return false;
} finally {
this.calculating.delete(ref.node);
}
}
}
| {
"end_byte": 3380,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/providers.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/ng_module_index.ts_0_4325 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ClassDeclaration} from '../../reflection';
import {MetadataReader, MetadataReaderWithIndex, MetaKind, NgModuleIndex} from './api';
/**
* An index of all NgModules that export or re-export a given trait.
*/
export class NgModuleIndexImpl implements NgModuleIndex {
constructor(
private metaReader: MetadataReader,
private localReader: MetadataReaderWithIndex,
) {}
// A map from an NgModule's Class Declaration to the "main" reference to that module, aka the one
// present in the reader metadata object
private ngModuleAuthoritativeReference = new Map<ClassDeclaration, Reference<ClassDeclaration>>();
// A map from a Directive/Pipe's class declaration to the class declarations of all re-exporting
// NgModules
private typeToExportingModules = new Map<ClassDeclaration, Set<ClassDeclaration>>();
private indexed = false;
private updateWith<K, V>(cache: Map<K, Set<V>>, key: K, elem: V) {
if (cache.has(key)) {
cache.get(key)!.add(elem);
} else {
const set = new Set<V>();
set.add(elem);
cache.set(key, set);
}
}
private index(): void {
const seenTypesWithReexports = new Map<ClassDeclaration, Set<ClassDeclaration>>();
const locallyDeclaredDirsAndNgModules = [
...this.localReader.getKnown(MetaKind.NgModule),
...this.localReader.getKnown(MetaKind.Directive),
];
for (const decl of locallyDeclaredDirsAndNgModules) {
// Here it's safe to create a new Reference because these are known local types.
this.indexTrait(new Reference(decl), seenTypesWithReexports);
}
this.indexed = true;
}
private indexTrait(
ref: Reference<ClassDeclaration>,
seenTypesWithReexports: Map<ClassDeclaration, Set<ClassDeclaration>>,
): void {
if (seenTypesWithReexports.has(ref.node)) {
// We've processed this type before.
return;
}
seenTypesWithReexports.set(ref.node, new Set());
const meta =
this.metaReader.getDirectiveMetadata(ref) ?? this.metaReader.getNgModuleMetadata(ref);
if (meta === null) {
return;
}
// Component + NgModule: recurse into imports
if (meta.imports !== null) {
for (const childRef of meta.imports) {
this.indexTrait(childRef, seenTypesWithReexports);
}
}
if (meta.kind === MetaKind.NgModule) {
if (!this.ngModuleAuthoritativeReference.has(ref.node)) {
this.ngModuleAuthoritativeReference.set(ref.node, ref);
}
for (const childRef of meta.exports) {
this.indexTrait(childRef, seenTypesWithReexports);
const childMeta =
this.metaReader.getDirectiveMetadata(childRef) ??
this.metaReader.getPipeMetadata(childRef) ??
this.metaReader.getNgModuleMetadata(childRef);
if (childMeta === null) {
continue;
}
switch (childMeta.kind) {
case MetaKind.Directive:
case MetaKind.Pipe:
this.updateWith(this.typeToExportingModules, childRef.node, ref.node);
this.updateWith(seenTypesWithReexports, ref.node, childRef.node);
break;
case MetaKind.NgModule:
if (seenTypesWithReexports.has(childRef.node)) {
for (const reexported of seenTypesWithReexports.get(childRef.node)!) {
this.updateWith(this.typeToExportingModules, reexported, ref.node);
this.updateWith(seenTypesWithReexports, ref.node, reexported);
}
}
break;
}
}
}
}
getNgModulesExporting(directiveOrPipe: ClassDeclaration): Array<Reference<ClassDeclaration>> {
if (!this.indexed) {
this.index();
}
if (!this.typeToExportingModules.has(directiveOrPipe)) {
return [];
}
const refs: Array<Reference<ClassDeclaration>> = [];
for (const ngModule of this.typeToExportingModules.get(directiveOrPipe)!) {
if (this.ngModuleAuthoritativeReference.has(ngModule)) {
refs.push(this.ngModuleAuthoritativeReference.get(ngModule)!);
}
}
return refs;
}
}
| {
"end_byte": 4325,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/ng_module_index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/registry.ts_0_2754 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ClassDeclaration} from '../../reflection';
import {
DirectiveMeta,
MetadataReaderWithIndex,
MetadataRegistry,
MetaKind,
NgModuleMeta,
PipeMeta,
} from './api';
/**
* A registry of directive, pipe, and module metadata for types defined in the current compilation
* unit, which supports both reading and registering.
*/
export class LocalMetadataRegistry implements MetadataRegistry, MetadataReaderWithIndex {
private directives = new Map<ClassDeclaration, DirectiveMeta>();
private ngModules = new Map<ClassDeclaration, NgModuleMeta>();
private pipes = new Map<ClassDeclaration, PipeMeta>();
getDirectiveMetadata(ref: Reference<ClassDeclaration>): DirectiveMeta | null {
return this.directives.has(ref.node) ? this.directives.get(ref.node)! : null;
}
getNgModuleMetadata(ref: Reference<ClassDeclaration>): NgModuleMeta | null {
return this.ngModules.has(ref.node) ? this.ngModules.get(ref.node)! : null;
}
getPipeMetadata(ref: Reference<ClassDeclaration>): PipeMeta | null {
return this.pipes.has(ref.node) ? this.pipes.get(ref.node)! : null;
}
registerDirectiveMetadata(meta: DirectiveMeta): void {
this.directives.set(meta.ref.node, meta);
}
registerNgModuleMetadata(meta: NgModuleMeta): void {
this.ngModules.set(meta.ref.node, meta);
}
registerPipeMetadata(meta: PipeMeta): void {
this.pipes.set(meta.ref.node, meta);
}
getKnown(kind: MetaKind): Array<ClassDeclaration> {
switch (kind) {
case MetaKind.Directive:
return Array.from(this.directives.values()).map((v) => v.ref.node);
case MetaKind.Pipe:
return Array.from(this.pipes.values()).map((v) => v.ref.node);
case MetaKind.NgModule:
return Array.from(this.ngModules.values()).map((v) => v.ref.node);
}
}
}
/**
* A `MetadataRegistry` which registers metadata with multiple delegate `MetadataRegistry`
* instances.
*/
export class CompoundMetadataRegistry implements MetadataRegistry {
constructor(private registries: MetadataRegistry[]) {}
registerDirectiveMetadata(meta: DirectiveMeta): void {
for (const registry of this.registries) {
registry.registerDirectiveMetadata(meta);
}
}
registerNgModuleMetadata(meta: NgModuleMeta): void {
for (const registry of this.registries) {
registry.registerNgModuleMetadata(meta);
}
}
registerPipeMetadata(meta: PipeMeta): void {
for (const registry of this.registries) {
registry.registerPipeMetadata(meta);
}
}
}
| {
"end_byte": 2754,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/registry.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/util.ts_0_7742 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {OwningModule, Reference} from '../../imports';
import {
ClassDeclaration,
ClassMember,
ClassMemberKind,
isNamedClassDeclaration,
ReflectionHost,
reflectTypeEntityToDeclaration,
} from '../../reflection';
import {nodeDebugInfo} from '../../util/src/typescript';
import {
DirectiveMeta,
DirectiveTypeCheckMeta,
HostDirectiveMeta,
HostDirectiveMetaForGlobalMode,
InputMapping,
MetadataReader,
NgModuleMeta,
PipeMeta,
TemplateGuardMeta,
} from './api';
import {ClassPropertyMapping, ClassPropertyName} from './property_mapping';
export function extractReferencesFromType(
checker: ts.TypeChecker,
def: ts.TypeNode,
bestGuessOwningModule: OwningModule | null,
): Reference<ClassDeclaration>[] {
if (!ts.isTupleTypeNode(def)) {
return [];
}
return def.elements.map((element) => {
if (!ts.isTypeQueryNode(element)) {
throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(element)}`);
}
return extraReferenceFromTypeQuery(checker, element, def, bestGuessOwningModule);
});
}
export function extraReferenceFromTypeQuery(
checker: ts.TypeChecker,
typeNode: ts.TypeQueryNode,
origin: ts.TypeNode,
bestGuessOwningModule: OwningModule | null,
) {
const type = typeNode.exprName;
const {node, from} = reflectTypeEntityToDeclaration(type, checker);
if (!isNamedClassDeclaration(node)) {
throw new Error(`Expected named ClassDeclaration: ${nodeDebugInfo(node)}`);
}
if (from !== null && !from.startsWith('.')) {
// The symbol was imported using an absolute module specifier so return a reference that
// uses that absolute module specifier as its best guess owning module.
return new Reference(node, {
specifier: from,
resolutionContext: origin.getSourceFile().fileName,
});
}
// For local symbols or symbols that were imported using a relative module import it is
// assumed that the symbol is exported from the provided best guess owning module.
return new Reference(node, bestGuessOwningModule);
}
export function readBooleanType(type: ts.TypeNode): boolean | null {
if (!ts.isLiteralTypeNode(type)) {
return null;
}
switch (type.literal.kind) {
case ts.SyntaxKind.TrueKeyword:
return true;
case ts.SyntaxKind.FalseKeyword:
return false;
default:
return null;
}
}
export function readStringType(type: ts.TypeNode): string | null {
if (!ts.isLiteralTypeNode(type) || !ts.isStringLiteral(type.literal)) {
return null;
}
return type.literal.text;
}
export function readMapType<T>(
type: ts.TypeNode,
valueTransform: (type: ts.TypeNode) => T | null,
): {[key: string]: T} {
if (!ts.isTypeLiteralNode(type)) {
return {};
}
const obj: {[key: string]: T} = {};
type.members.forEach((member) => {
if (
!ts.isPropertySignature(member) ||
member.type === undefined ||
member.name === undefined ||
(!ts.isStringLiteral(member.name) && !ts.isIdentifier(member.name))
) {
return;
}
const value = valueTransform(member.type);
if (value !== null) {
obj[member.name.text] = value;
}
});
return obj;
}
export function readStringArrayType(type: ts.TypeNode): string[] {
if (!ts.isTupleTypeNode(type)) {
return [];
}
const res: string[] = [];
type.elements.forEach((el) => {
if (!ts.isLiteralTypeNode(el) || !ts.isStringLiteral(el.literal)) {
return;
}
res.push(el.literal.text);
});
return res;
}
/**
* Inspects the class' members and extracts the metadata that is used when type-checking templates
* that use the directive. This metadata does not contain information from a base class, if any,
* making this metadata invariant to changes of inherited classes.
*/
export function extractDirectiveTypeCheckMeta(
node: ClassDeclaration,
inputs: ClassPropertyMapping<InputMapping>,
reflector: ReflectionHost,
): DirectiveTypeCheckMeta {
const members = reflector.getMembersOfClass(node);
const staticMembers = members.filter((member) => member.isStatic);
const ngTemplateGuards = staticMembers
.map(extractTemplateGuard)
.filter((guard): guard is TemplateGuardMeta => guard !== null);
const hasNgTemplateContextGuard = staticMembers.some(
(member) => member.kind === ClassMemberKind.Method && member.name === 'ngTemplateContextGuard',
);
const coercedInputFields = new Set<ClassPropertyName>(
staticMembers.map(extractCoercedInput).filter((inputName): inputName is ClassPropertyName => {
// If the input refers to a signal input, we will not respect coercion members.
// A transform function should be used instead.
if (inputName === null || inputs.getByClassPropertyName(inputName)?.isSignal) {
return false;
}
return true;
}),
);
const restrictedInputFields = new Set<ClassPropertyName>();
const stringLiteralInputFields = new Set<ClassPropertyName>();
const undeclaredInputFields = new Set<ClassPropertyName>();
for (const {classPropertyName, transform} of inputs) {
const field = members.find((member) => member.name === classPropertyName);
if (field === undefined || field.node === null) {
undeclaredInputFields.add(classPropertyName);
continue;
}
if (isRestricted(field.node)) {
restrictedInputFields.add(classPropertyName);
}
if (field.nameNode !== null && ts.isStringLiteral(field.nameNode)) {
stringLiteralInputFields.add(classPropertyName);
}
if (transform !== null) {
coercedInputFields.add(classPropertyName);
}
}
const arity = reflector.getGenericArityOfClass(node);
return {
hasNgTemplateContextGuard,
ngTemplateGuards,
coercedInputFields,
restrictedInputFields,
stringLiteralInputFields,
undeclaredInputFields,
isGeneric: arity !== null && arity > 0,
};
}
function isRestricted(node: ts.Node): boolean {
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
return (
modifiers !== undefined &&
modifiers.some(({kind}) => {
return (
kind === ts.SyntaxKind.PrivateKeyword ||
kind === ts.SyntaxKind.ProtectedKeyword ||
kind === ts.SyntaxKind.ReadonlyKeyword
);
})
);
}
function extractTemplateGuard(member: ClassMember): TemplateGuardMeta | null {
if (!member.name.startsWith('ngTemplateGuard_')) {
return null;
}
const inputName = afterUnderscore(member.name);
if (member.kind === ClassMemberKind.Property) {
let type: string | null = null;
if (
member.type !== null &&
ts.isLiteralTypeNode(member.type) &&
ts.isStringLiteral(member.type.literal)
) {
type = member.type.literal.text;
}
// Only property members with string literal type 'binding' are considered as template guard.
if (type !== 'binding') {
return null;
}
return {inputName, type};
} else if (member.kind === ClassMemberKind.Method) {
return {inputName, type: 'invocation'};
} else {
return null;
}
}
function extractCoercedInput(member: ClassMember): string | null {
if (member.kind !== ClassMemberKind.Property || !member.name.startsWith('ngAcceptInputType_')) {
return null!;
}
return afterUnderscore(member.name);
}
/**
* A `MetadataReader` that reads from an ordered set of child readers until it obtains the requested
* metadata.
*
* This is used to combine `MetadataReader`s that read from different sources (e.g. from a registry
* and from .d.ts files).
*/ | {
"end_byte": 7742,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/util.ts_7743_9415 | export class CompoundMetadataReader implements MetadataReader {
constructor(private readers: MetadataReader[]) {}
getDirectiveMetadata(node: Reference<ClassDeclaration<ts.Declaration>>): DirectiveMeta | null {
for (const reader of this.readers) {
const meta = reader.getDirectiveMetadata(node);
if (meta !== null) {
return meta;
}
}
return null;
}
getNgModuleMetadata(node: Reference<ClassDeclaration<ts.Declaration>>): NgModuleMeta | null {
for (const reader of this.readers) {
const meta = reader.getNgModuleMetadata(node);
if (meta !== null) {
return meta;
}
}
return null;
}
getPipeMetadata(node: Reference<ClassDeclaration<ts.Declaration>>): PipeMeta | null {
for (const reader of this.readers) {
const meta = reader.getPipeMetadata(node);
if (meta !== null) {
return meta;
}
}
return null;
}
}
function afterUnderscore(str: string): string {
const pos = str.indexOf('_');
if (pos === -1) {
throw new Error(`Expected '${str}' to contain '_'`);
}
return str.slice(pos + 1);
}
/** Returns whether a class declaration has the necessary class fields to make it injectable. */
export function hasInjectableFields(clazz: ClassDeclaration, host: ReflectionHost): boolean {
const members = host.getMembersOfClass(clazz);
return members.some(({isStatic, name}) => isStatic && (name === 'ɵprov' || name === 'ɵfac'));
}
export function isHostDirectiveMetaForGlobalMode(
hostDirectiveMeta: HostDirectiveMeta,
): hostDirectiveMeta is HostDirectiveMetaForGlobalMode {
return hostDirectiveMeta.directive instanceof Reference;
}
| {
"end_byte": 9415,
"start_byte": 7743,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/metadata/src/property_mapping.ts_0_7296 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InputOutputPropertySet} from '@angular/compiler';
/**
* The name of a class property that backs an input or output declared by a directive or component.
*
* This type exists for documentation only.
*/
export type ClassPropertyName = string;
/**
* The name by which an input or output of a directive or component is bound in an Angular template.
*
* This type exists for documentation only.
*/
export type BindingPropertyName = string;
/**
* An input or output of a directive that has both a named JavaScript class property on a component
* or directive class, as well as an Angular template property name used for binding.
*/
export interface InputOrOutput {
/**
* The name of the JavaScript property on the component or directive instance for this input or
* output.
*/
readonly classPropertyName: ClassPropertyName;
/**
* The property name used to bind this input or output in an Angular template.
*/
readonly bindingPropertyName: BindingPropertyName;
/** Whether the input or output is signal based. */
readonly isSignal: boolean;
}
/**
* A mapping of component property and template binding property names, for example containing the
* inputs of a particular directive or component.
*
* A single component property has exactly one input/output annotation (and therefore one binding
* property name) associated with it, but the same binding property name may be shared across many
* component property names.
*
* Allows bidirectional querying of the mapping - looking up all inputs/outputs with a given
* property name, or mapping from a specific class property to its binding property name.
*/
export class ClassPropertyMapping<T extends InputOrOutput = InputOrOutput>
implements InputOutputPropertySet
{
/**
* Mapping from class property names to the single `InputOrOutput` for that class property.
*/
private forwardMap: Map<ClassPropertyName, T>;
/**
* Mapping from property names to one or more `InputOrOutput`s which share that name.
*/
private reverseMap: Map<BindingPropertyName, T[]>;
private constructor(forwardMap: Map<ClassPropertyName, T>) {
this.forwardMap = forwardMap;
this.reverseMap = reverseMapFromForwardMap(forwardMap);
}
/**
* Construct a `ClassPropertyMapping` with no entries.
*/
static empty<T extends InputOrOutput>(): ClassPropertyMapping<T> {
return new ClassPropertyMapping(new Map());
}
/**
* Construct a `ClassPropertyMapping` from a primitive JS object which maps class property names
* to either binding property names or an array that contains both names, which is used in on-disk
* metadata formats (e.g. in .d.ts files).
*/
static fromMappedObject<T extends InputOrOutput>(obj: {
[classPropertyName: string]: BindingPropertyName | T;
}): ClassPropertyMapping<T> {
const forwardMap = new Map<ClassPropertyName, T>();
for (const classPropertyName of Object.keys(obj)) {
const value = obj[classPropertyName];
let inputOrOutput: InputOrOutput;
if (typeof value === 'string') {
inputOrOutput = {
classPropertyName,
bindingPropertyName: value,
// Inputs/outputs not captured via an explicit `InputOrOutput` mapping
// value are always considered non-signal. This is the string shorthand.
isSignal: false,
};
} else {
inputOrOutput = value;
}
forwardMap.set(classPropertyName, inputOrOutput as T);
}
return new ClassPropertyMapping(forwardMap);
}
/**
* Merge two mappings into one, with class properties from `b` taking precedence over class
* properties from `a`.
*/
static merge<T extends InputOrOutput>(
a: ClassPropertyMapping<T>,
b: ClassPropertyMapping<T>,
): ClassPropertyMapping<T> {
const forwardMap = new Map<ClassPropertyName, T>(a.forwardMap.entries());
for (const [classPropertyName, inputOrOutput] of b.forwardMap) {
forwardMap.set(classPropertyName, inputOrOutput);
}
return new ClassPropertyMapping(forwardMap);
}
/**
* All class property names mapped in this mapping.
*/
get classPropertyNames(): ClassPropertyName[] {
return Array.from(this.forwardMap.keys());
}
/**
* All binding property names mapped in this mapping.
*/
get propertyNames(): BindingPropertyName[] {
return Array.from(this.reverseMap.keys());
}
/**
* Check whether a mapping for the given property name exists.
*/
hasBindingPropertyName(propertyName: BindingPropertyName): boolean {
return this.reverseMap.has(propertyName);
}
/**
* Lookup all `InputOrOutput`s that use this `propertyName`.
*/
getByBindingPropertyName(propertyName: string): ReadonlyArray<T> | null {
return this.reverseMap.has(propertyName) ? this.reverseMap.get(propertyName)! : null;
}
/**
* Lookup the `InputOrOutput` associated with a `classPropertyName`.
*/
getByClassPropertyName(classPropertyName: string): T | null {
return this.forwardMap.has(classPropertyName) ? this.forwardMap.get(classPropertyName)! : null;
}
/**
* Convert this mapping to a primitive JS object which maps each class property directly to the
* binding property name associated with it.
*/
toDirectMappedObject(): {[classPropertyName: string]: BindingPropertyName} {
const obj: {[classPropertyName: string]: BindingPropertyName} = {};
for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
obj[classPropertyName] = inputOrOutput.bindingPropertyName;
}
return obj;
}
/**
* Convert this mapping to a primitive JS object which maps each class property either to itself
* (for cases where the binding property name is the same) or to an array which contains both
* names if they differ.
*
* This object format is used when mappings are serialized (for example into .d.ts files).
* @param transform Function used to transform the values of the generated map.
*/
toJointMappedObject<O = T>(transform: (value: T) => O): {[classPropertyName: string]: O} {
const obj: {[classPropertyName: string]: O} = {};
for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
obj[classPropertyName] = transform(inputOrOutput);
}
return obj;
}
/**
* Implement the iterator protocol and return entry objects which contain the class and binding
* property names (and are useful for destructuring).
*/
*[Symbol.iterator](): IterableIterator<T> {
for (const inputOrOutput of this.forwardMap.values()) {
yield inputOrOutput;
}
}
}
function reverseMapFromForwardMap<T extends InputOrOutput>(
forwardMap: Map<ClassPropertyName, T>,
): Map<BindingPropertyName, T[]> {
const reverseMap = new Map<BindingPropertyName, T[]>();
for (const [_, inputOrOutput] of forwardMap) {
if (!reverseMap.has(inputOrOutput.bindingPropertyName)) {
reverseMap.set(inputOrOutput.bindingPropertyName, []);
}
reverseMap.get(inputOrOutput.bindingPropertyName)!.push(inputOrOutput);
}
return reverseMap;
}
| {
"end_byte": 7296,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/metadata/src/property_mapping.ts"
} |
angular/packages/compiler-cli/src/ngtsc/logging/README.md_0_110 | # Logging
Here you can find a simple abstraction over the console logging that allows
filtered logs by level. | {
"end_byte": 110,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/logging/BUILD.bazel_0_248 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "logging",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"@npm//@types/node",
],
)
| {
"end_byte": 248,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/logging/index.ts_0_302 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {ConsoleLogger} from './src/console_logger';
export {Logger, LogLevel} from './src/logger';
| {
"end_byte": 302,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/logging/test/console_logger_spec.ts_0_1977 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConsoleLogger, DEBUG, ERROR, WARN} from '../src/console_logger';
import {LogLevel} from '../src/logger';
describe('ConsoleLogger', () => {
it('should pass through calls to Console', () => {
spyOn(console, 'debug');
spyOn(console, 'info');
spyOn(console, 'warn');
spyOn(console, 'error');
const logger = new ConsoleLogger(LogLevel.debug);
logger.debug('debug', 'test');
expect(console.debug).toHaveBeenCalledWith(DEBUG, 'debug', 'test');
logger.info('info', 'test');
expect(console.info).toHaveBeenCalledWith('info', 'test');
logger.warn('warn', 'test');
expect(console.warn).toHaveBeenCalledWith(WARN, 'warn', 'test');
logger.error('error', 'test');
expect(console.error).toHaveBeenCalledWith(ERROR, 'error', 'test');
});
it('should filter out calls below the given log level', () => {
spyOn(console, 'debug');
spyOn(console, 'info');
spyOn(console, 'warn');
spyOn(console, 'error');
const logger = new ConsoleLogger(LogLevel.warn);
logger.debug('debug', 'test');
expect(console.debug).not.toHaveBeenCalled();
logger.info('info', 'test');
expect(console.info).not.toHaveBeenCalled();
logger.warn('warn', 'test');
expect(console.warn).toHaveBeenCalledWith(WARN, 'warn', 'test');
logger.error('error', 'test');
expect(console.error).toHaveBeenCalledWith(ERROR, 'error', 'test');
});
it('should expose the logging level', () => {
expect(new ConsoleLogger(LogLevel.debug).level).toEqual(LogLevel.debug);
expect(new ConsoleLogger(LogLevel.info).level).toEqual(LogLevel.info);
expect(new ConsoleLogger(LogLevel.warn).level).toEqual(LogLevel.warn);
expect(new ConsoleLogger(LogLevel.error).level).toEqual(LogLevel.error);
});
});
| {
"end_byte": 1977,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/test/console_logger_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/logging/test/BUILD.bazel_0_431 | 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/compiler-cli/src/ngtsc/logging",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 431,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/logging/testing/BUILD.bazel_0_253 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages/compiler-cli/src/ngtsc/logging",
],
)
| {
"end_byte": 253,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/testing/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/logging/testing/index.ts_0_249 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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 {MockLogger} from './src/mock_logger';
| {
"end_byte": 249,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/testing/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/logging/testing/src/mock_logger.ts_0_722 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Logger, LogLevel} from '../..';
export class MockLogger implements Logger {
constructor(public level = LogLevel.info) {}
logs: {[P in Exclude<keyof Logger, 'level'>]: string[][]} = {
debug: [],
info: [],
warn: [],
error: [],
};
debug(...args: string[]) {
this.logs.debug.push(args);
}
info(...args: string[]) {
this.logs.info.push(args);
}
warn(...args: string[]) {
this.logs.warn.push(args);
}
error(...args: string[]) {
this.logs.error.push(args);
}
}
| {
"end_byte": 722,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/testing/src/mock_logger.ts"
} |
angular/packages/compiler-cli/src/ngtsc/logging/src/console_logger.ts_0_1141 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Logger, LogLevel} from './logger';
const RESET = '\x1b[0m';
const RED = '\x1b[31m';
const YELLOW = '\x1b[33m';
const BLUE = '\x1b[36m';
export const DEBUG = `${BLUE}Debug:${RESET}`;
export const WARN = `${YELLOW}Warning:${RESET}`;
export const ERROR = `${RED}Error:${RESET}`;
/**
* A simple logger that outputs directly to the Console.
*
* The log messages can be filtered based on severity via the `logLevel`
* constructor parameter.
*/
export class ConsoleLogger implements Logger {
constructor(public level: LogLevel) {}
debug(...args: string[]) {
if (this.level <= LogLevel.debug) console.debug(DEBUG, ...args);
}
info(...args: string[]) {
if (this.level <= LogLevel.info) console.info(...args);
}
warn(...args: string[]) {
if (this.level <= LogLevel.warn) console.warn(WARN, ...args);
}
error(...args: string[]) {
if (this.level <= LogLevel.error) console.error(ERROR, ...args);
}
}
| {
"end_byte": 1141,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/src/console_logger.ts"
} |
angular/packages/compiler-cli/src/ngtsc/logging/src/logger.ts_0_565 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Implement this interface if you want to provide different logging
* output from the standard ConsoleLogger.
*/
export interface Logger {
level: LogLevel;
debug(...args: string[]): void;
info(...args: string[]): void;
warn(...args: string[]): void;
error(...args: string[]): void;
}
export enum LogLevel {
debug,
info,
warn,
error,
}
| {
"end_byte": 565,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/logging/src/logger.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/README.md_0_984 | # `indexer`
The `indexer` module generates semantic analysis about components used in an
Angular project. The module is consumed by a semantic analysis API on an Angular
program, which can be invoked separately from the regular Angular compilation
pipeline.
The module is _not_ a fully-featured source code indexer. Rather, it is designed
to produce semantic information about an Angular project that can then be used
by language analysis tools to generate, for example, cross-references in Angular
templates.
The `indexer` module is developed primarily with the
[Kythe](https://github.com/kythe/kythe) ecosystem in mind as an indexing
service.
### Scope of Analysis
The scope of analysis performed by the module includes
- indexing template syntax identifiers in a component template
- generating information about directives used in a template
- generating metadata about component and template source files
The module does not support indexing TypeScript source code.
| {
"end_byte": 984,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/BUILD.bazel_0_441 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "indexer",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/reflection",
"@npm//typescript",
],
)
| {
"end_byte": 441,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/index.ts_0_328 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/api';
export {IndexingContext} from './src/context';
export {generateAnalysis} from './src/transform';
| {
"end_byte": 328,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/context_spec.ts_0_1380 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ParseSourceFile} from '@angular/compiler';
import {runInEachFileSystem} from '../../file_system/testing';
import {IndexingContext} from '../src/context';
import * as util from './util';
runInEachFileSystem(() => {
describe('ComponentAnalysisContext', () => {
it('should store and return information about components', () => {
const context = new IndexingContext();
const declaration = util.getComponentDeclaration('class C {};', 'C');
const boundTemplate = util.getBoundTemplate('<div></div>');
context.addComponent({
declaration,
selector: 'c-selector',
boundTemplate,
templateMeta: {
isInline: false,
file: new ParseSourceFile('<div></div>', declaration.getSourceFile().fileName),
},
});
expect(context.components).toEqual(
new Set([
{
declaration,
selector: 'c-selector',
boundTemplate,
templateMeta: {
isInline: false,
file: new ParseSourceFile('<div></div>', declaration.getSourceFile().fileName),
},
},
]),
);
});
});
});
| {
"end_byte": 1380,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/context_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/util.ts_0_2465 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
BoundTarget,
CssSelector,
parseTemplate,
ParseTemplateOptions,
R3TargetBinder,
SelectorMatcher,
} from '@angular/compiler';
import ts from 'typescript';
import {absoluteFrom, AbsoluteFsPath} from '../../file_system';
import {Reference} from '../../imports';
import {ClassPropertyMapping} from '../../metadata';
import {ClassDeclaration} from '../../reflection';
import {getDeclaration, makeProgram} from '../../testing';
import {ComponentMeta} from '../src/context';
/** Dummy file URL */
function getTestFilePath(): AbsoluteFsPath {
return absoluteFrom('/TEST_FILE.ts');
}
/**
* Creates a class declaration from a component source code.
*/
export function getComponentDeclaration(componentStr: string, className: string): ClassDeclaration {
const program = makeProgram([{name: getTestFilePath(), contents: componentStr}]);
return getDeclaration(
program.program,
getTestFilePath(),
className,
(value: ts.Node): value is ClassDeclaration => ts.isClassDeclaration(value),
);
}
/**
* Parses a template source code and returns a template-bound target, optionally with information
* about used components.
*
* @param template template to parse
* @param options extra template parsing options
* @param components components to bind to the template target
*/
export function getBoundTemplate(
template: string,
options: ParseTemplateOptions = {},
components: Array<{selector: string; declaration: ClassDeclaration}> = [],
): BoundTarget<ComponentMeta> {
const matcher = new SelectorMatcher<ComponentMeta[]>();
components.forEach(({selector, declaration}) => {
matcher.addSelectables(CssSelector.parse(selector), [
{
ref: new Reference(declaration),
selector,
name: declaration.name.getText(),
isComponent: true,
inputs: ClassPropertyMapping.fromMappedObject({}),
outputs: ClassPropertyMapping.fromMappedObject({}),
exportAs: null,
isStructural: false,
animationTriggerNames: null,
ngContentSelectors: null,
preserveWhitespaces: false,
},
]);
});
const binder = new R3TargetBinder(matcher);
return binder.bind({template: parseTemplate(template, getTestFilePath(), options).nodes});
}
| {
"end_byte": 2465,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts_0_4689 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BoundTarget} from '@angular/compiler';
import {
AbsoluteSourceSpan,
AttributeIdentifier,
ElementIdentifier,
IdentifierKind,
LetDeclarationIdentifier,
ReferenceIdentifier,
TemplateNodeIdentifier,
TopLevelIdentifier,
VariableIdentifier,
} from '..';
import {runInEachFileSystem} from '../../file_system/testing';
import {ComponentMeta} from '../src/context';
import {getTemplateIdentifiers as getTemplateIdentifiersAndErrors} from '../src/template';
import * as util from './util';
function bind(template: string) {
return util.getBoundTemplate(template, {
preserveWhitespaces: true,
leadingTriviaChars: [],
});
}
function getTemplateIdentifiers(boundTemplate: BoundTarget<ComponentMeta>) {
return getTemplateIdentifiersAndErrors(boundTemplate).identifiers;
}
runInEachFileSystem(() => {
describe('getTemplateIdentifiers', () => {
it('should handle svg elements', () => {
const template = '<svg></svg>';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
expect(ref).toEqual({
kind: IdentifierKind.Element,
name: 'svg',
span: new AbsoluteSourceSpan(1, 4),
usedDirectives: new Set(),
attributes: new Set(),
});
});
it('should handle svg elements on templates', () => {
const template = '<svg *ngIf="true"></svg>';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
expect(ref).toEqual({
kind: IdentifierKind.Template,
name: 'svg',
span: new AbsoluteSourceSpan(1, 4),
usedDirectives: new Set(),
attributes: new Set(),
});
});
it('should handle comments in interpolations', () => {
const template = '{{foo // comment}}';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
expect(ref).toEqual({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(2, 5),
target: null,
});
});
it('should handle whitespace and comments in interpolations', () => {
const template = '{{ foo // comment }}';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
expect(ref).toEqual({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(5, 8),
target: null,
});
});
it('works when structural directives are on templates', () => {
const template = '<ng-template *ngIf="true">';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
expect(ref).toEqual({
kind: IdentifierKind.Template,
name: 'ng-template',
span: new AbsoluteSourceSpan(1, 12),
usedDirectives: new Set(),
attributes: new Set(),
});
});
it('should generate nothing in empty template', () => {
const template = '';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(0);
});
it('should ignore comments', () => {
const template = '<!-- {{comment}} -->';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(0);
});
it('should handle arbitrary whitespace', () => {
const template = '\n\n {{foo}}';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
expect(ref).toEqual({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(7, 10),
target: null,
});
});
it('should resist collisions', () => {
const template = '<div [bar]="bar ? bar : bar"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
{
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(12, 15),
target: null,
},
{
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(18, 21),
target: null,
},
{
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(24, 27),
target: null,
},
] as TopLevelIdentifier[]),
);
}); | {
"end_byte": 4689,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts_4695_12183 | describe('generates identifiers for PropertyReads', () => {
it('should discover component properties', () => {
const template = '{{foo}}';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref).toEqual({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(2, 5),
target: null,
});
});
it('should discover component properties read using "this" as a receiver', () => {
const template = '{{this.foo}}';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref).toEqual({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(7, 10),
target: null,
});
});
it('should discover nested properties', () => {
const template = '<div><span>{{foo}}</span></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(13, 16),
target: null,
});
});
it('should ignore identifiers that are not implicitly received by the template', () => {
const template = '{{foo.bar.baz}}';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref.name).toBe('foo');
});
it('should discover properties in bound attributes', () => {
const template = '<div [bar]="bar"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(12, 15),
target: null,
});
});
it('should handle bound attributes with no value', () => {
const template = '<div [bar]></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toEqual([
{
name: 'div',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 4),
attributes: new Set(),
usedDirectives: new Set(),
},
]);
});
it('should discover variables in bound attributes', () => {
const template = '<div #div [value]="div.innerText"></div>';
const refs = getTemplateIdentifiers(bind(template));
const elementReference: ElementIdentifier = {
name: 'div',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 4),
attributes: new Set(),
usedDirectives: new Set(),
};
const reference: ReferenceIdentifier = {
name: 'div',
kind: IdentifierKind.Reference,
span: new AbsoluteSourceSpan(6, 9),
target: {node: elementReference, directive: null},
};
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'div',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(19, 22),
target: reference,
});
});
it('should discover properties in template expressions', () => {
const template = '<div [bar]="bar ? bar1 : bar2"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
{
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(12, 15),
target: null,
},
{
name: 'bar1',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(18, 22),
target: null,
},
{
name: 'bar2',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(25, 29),
target: null,
},
] as TopLevelIdentifier[]),
);
});
it('should discover properties in template expressions', () => {
const template = '<div *ngFor="let foo of foos"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'foos',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(24, 28),
target: null,
});
});
it('should discover properties in template expressions and resist collisions', () => {
const template = '<div *ngFor="let foo of (foos ? foos : foos)"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
{
name: 'foos',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(25, 29),
target: null,
},
{
name: 'foos',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(32, 36),
target: null,
},
{
name: 'foos',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(39, 43),
target: null,
},
]),
);
});
});
describe('generates identifiers for PropertyWrites', () => {
it('should discover property writes in bound events', () => {
const template = '<div (click)="foo=bar"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(14, 17),
target: null,
},
{
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(18, 21),
target: null,
},
] as TopLevelIdentifier[]),
);
});
it('should discover nested property writes', () => {
const template = '<div><span (click)="foo=bar"></span></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(20, 23),
target: null,
},
] as TopLevelIdentifier[]),
);
});
it('should ignore property writes that are not implicitly received by the template', () => {
const template = '<div><span (click)="foo.bar=baz"></span></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
const bar = refArr.find((ref) => ref.name.includes('bar'));
expect(bar).toBeUndefined();
});
}); | {
"end_byte": 12183,
"start_byte": 4695,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts_12189_19905 | describe('generates identifiers for method calls', () => {
it('should discover component method calls', () => {
const template = '{{foo()}}';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref).toEqual({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(2, 5),
target: null,
});
});
it('should discover nested properties', () => {
const template = '<div><span>{{foo()}}</span></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(13, 16),
target: null,
});
});
it('should ignore identifiers that are not implicitly received by the template', () => {
const template = '{{foo().bar().baz()}}';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref.name).toBe('foo');
});
it('should discover method calls in bound attributes', () => {
const template = '<div [bar]="bar()"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'bar',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(12, 15),
target: null,
});
});
it('should discover method calls in template expressions', () => {
const template = '<div *ngFor="let foo of foos()"></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'foos',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(24, 28),
target: null,
});
});
});
});
describe('generates identifiers for template reference variables', () => {
it('should discover references', () => {
const template = '<div #foo>';
const refs = getTemplateIdentifiers(bind(template));
const elementReference: ElementIdentifier = {
name: 'div',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 4),
attributes: new Set(),
usedDirectives: new Set(),
};
const refArray = Array.from(refs);
expect(refArray).toEqual(
jasmine.arrayContaining([
{
name: 'foo',
kind: IdentifierKind.Reference,
span: new AbsoluteSourceSpan(6, 9),
target: {node: elementReference, directive: null},
},
] as TopLevelIdentifier[]),
);
});
it('should discover nested references', () => {
const template = '<div><span #foo></span></div>';
const refs = getTemplateIdentifiers(bind(template));
const elementReference: ElementIdentifier = {
name: 'span',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(6, 10),
attributes: new Set(),
usedDirectives: new Set(),
};
const refArray = Array.from(refs);
expect(refArray).toEqual(
jasmine.arrayContaining([
{
name: 'foo',
kind: IdentifierKind.Reference,
span: new AbsoluteSourceSpan(12, 15),
target: {node: elementReference, directive: null},
},
] as TopLevelIdentifier[]),
);
});
it('should discover references to references', () => {
const template = `<div #foo>{{foo.className}}</div>`;
const refs = getTemplateIdentifiers(bind(template));
const elementIdentifier: ElementIdentifier = {
name: 'div',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 4),
attributes: new Set(),
usedDirectives: new Set(),
};
const referenceIdentifier: ReferenceIdentifier = {
name: 'foo',
kind: IdentifierKind.Reference,
span: new AbsoluteSourceSpan(6, 9),
target: {node: elementIdentifier, directive: null},
};
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
elementIdentifier,
referenceIdentifier,
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(12, 15),
target: referenceIdentifier,
},
] as TopLevelIdentifier[]),
);
});
it('should discover forward references', () => {
const template = `{{foo}}<div #foo></div>`;
const refs = getTemplateIdentifiers(bind(template));
const elementIdentifier: ElementIdentifier = {
name: 'div',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(8, 11),
attributes: new Set(),
usedDirectives: new Set(),
};
const referenceIdentifier: ReferenceIdentifier = {
name: 'foo',
kind: IdentifierKind.Reference,
span: new AbsoluteSourceSpan(13, 16),
target: {node: elementIdentifier, directive: null},
};
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
elementIdentifier,
referenceIdentifier,
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(2, 5),
target: referenceIdentifier,
},
] as TopLevelIdentifier[]),
);
});
it('should generate information directive targets', () => {
const declB = util.getComponentDeclaration('class B {}', 'B');
const template = '<div #foo b-selector>';
const boundTemplate = util.getBoundTemplate(template, {}, [
{selector: '[b-selector]', declaration: declB},
]);
const refs = getTemplateIdentifiers(boundTemplate);
const refArr = Array.from(refs);
let fooRef = refArr.find((id) => id.name === 'foo');
expect(fooRef).toBeDefined();
expect(fooRef!.kind).toBe(IdentifierKind.Reference);
fooRef = fooRef as ReferenceIdentifier;
expect(fooRef.target).toBeDefined();
expect(fooRef.target!.node.kind).toBe(IdentifierKind.Element);
expect(fooRef.target!.node.name).toBe('div');
expect(fooRef.target!.node.span).toEqual(new AbsoluteSourceSpan(1, 4));
expect(fooRef.target!.directive).toEqual(declB);
});
it('should discover references to references', () => {
const template = `<div #foo (ngSubmit)="do(foo)"></div>`;
const refs = getTemplateIdentifiers(bind(template));
const elementIdentifier: ElementIdentifier = {
name: 'div',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 4),
attributes: new Set(),
usedDirectives: new Set(),
};
const referenceIdentifier: ReferenceIdentifier = {
name: 'foo',
kind: IdentifierKind.Reference,
span: new AbsoluteSourceSpan(6, 9),
target: {node: elementIdentifier, directive: null},
};
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
elementIdentifier,
referenceIdentifier,
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(25, 28),
target: referenceIdentifier,
},
] as TopLevelIdentifier[]),
);
});
}); | {
"end_byte": 19905,
"start_byte": 12189,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts_19909_28553 | describe('generates identifiers for template variables', () => {
it('should discover variables', () => {
const template = '<div *ngFor="let foo of foos">';
const refs = getTemplateIdentifiers(bind(template));
const refArray = Array.from(refs);
expect(refArray).toEqual(
jasmine.arrayContaining([
{
name: 'foo',
kind: IdentifierKind.Variable,
span: new AbsoluteSourceSpan(17, 20),
},
] as TopLevelIdentifier[]),
);
});
it('should discover variables with let- syntax', () => {
const template = '<ng-template let-var="classVar">';
const refs = getTemplateIdentifiers(bind(template));
const refArray = Array.from(refs);
expect(refArray).toEqual(
jasmine.arrayContaining([
{
name: 'var',
kind: IdentifierKind.Variable,
span: new AbsoluteSourceSpan(17, 20),
},
] as TopLevelIdentifier[]),
);
});
it('should discover nested variables', () => {
const template = '<div><span *ngFor="let foo of foos"></span></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArray = Array.from(refs);
expect(refArray).toEqual(
jasmine.arrayContaining([
{
name: 'foo',
kind: IdentifierKind.Variable,
span: new AbsoluteSourceSpan(23, 26),
},
] as TopLevelIdentifier[]),
);
});
it('should discover references to variables', () => {
const template = `<div *ngFor="let foo of foos; let i = index">{{foo + i}}</div>`;
const refs = getTemplateIdentifiers(bind(template));
const fooIdentifier: VariableIdentifier = {
name: 'foo',
kind: IdentifierKind.Variable,
span: new AbsoluteSourceSpan(17, 20),
};
const iIdentifier: VariableIdentifier = {
name: 'i',
kind: IdentifierKind.Variable,
span: new AbsoluteSourceSpan(34, 35),
};
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
fooIdentifier,
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(47, 50),
target: fooIdentifier,
},
iIdentifier,
{
name: 'i',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(53, 54),
target: iIdentifier,
},
] as TopLevelIdentifier[]),
);
});
it('should discover references to variables', () => {
const template = `<div *ngFor="let foo of foos" (click)="do(foo)"></div>`;
const refs = getTemplateIdentifiers(bind(template));
const variableIdentifier: VariableIdentifier = {
name: 'foo',
kind: IdentifierKind.Variable,
span: new AbsoluteSourceSpan(17, 20),
};
const refArr = Array.from(refs);
expect(refArr).toEqual(
jasmine.arrayContaining([
variableIdentifier,
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(42, 45),
target: variableIdentifier,
},
] as TopLevelIdentifier[]),
);
});
});
describe('let declarations', () => {
it('should discover references to let declaration', () => {
const template = `@let foo = 123; <div [someInput]="foo"></div>`;
const refs = getTemplateIdentifiers(bind(template));
const letIdentifier: LetDeclarationIdentifier = {
name: 'foo',
kind: IdentifierKind.LetDeclaration,
span: new AbsoluteSourceSpan(5, 8),
};
expect(Array.from(refs)).toEqual(
jasmine.arrayContaining([
letIdentifier,
{
name: 'foo',
kind: IdentifierKind.Property,
span: new AbsoluteSourceSpan(34, 37),
target: letIdentifier,
},
]),
);
});
});
describe('generates identifiers for elements', () => {
it('should record elements as ElementIdentifiers', () => {
const template = '<test-selector>';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref.kind).toBe(IdentifierKind.Element);
});
it('should record element names as their selector', () => {
const template = '<test-selector>';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref as ElementIdentifier).toEqual({
name: 'test-selector',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 14),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should discover selectors in self-closing elements', () => {
const template = '<img />';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref as ElementIdentifier).toEqual({
name: 'img',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 4),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should discover selectors in elements with adjacent open and close tags', () => {
const template = '<test-selector></test-selector>';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref as ElementIdentifier).toEqual({
name: 'test-selector',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 14),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should discover selectors in elements with non-adjacent open and close tags', () => {
const template = '<test-selector> text </test-selector>';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref as ElementIdentifier).toEqual({
name: 'test-selector',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(1, 14),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should discover nested selectors', () => {
const template = '<div><span></span></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'span',
kind: IdentifierKind.Element,
span: new AbsoluteSourceSpan(6, 10),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should generate information about attributes', () => {
const template = '<div attrA attrB="val"></div>';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
const attrs = (ref as ElementIdentifier).attributes;
expect(attrs).toEqual(
new Set<AttributeIdentifier>([
{
name: 'attrA',
kind: IdentifierKind.Attribute,
span: new AbsoluteSourceSpan(5, 10),
},
{
name: 'attrB',
kind: IdentifierKind.Attribute,
span: new AbsoluteSourceSpan(11, 22),
},
]),
);
});
it('should generate information about used directives', () => {
const declA = util.getComponentDeclaration('class A {}', 'A');
const declB = util.getComponentDeclaration('class B {}', 'B');
const declC = util.getComponentDeclaration('class C {}', 'C');
const template = '<a-selector b-selector></a-selector>';
const boundTemplate = util.getBoundTemplate(template, {}, [
{selector: 'a-selector', declaration: declA},
{selector: '[b-selector]', declaration: declB},
{selector: ':not(never-selector)', declaration: declC},
]);
const refs = getTemplateIdentifiers(boundTemplate);
const [ref] = Array.from(refs);
const usedDirectives = (ref as ElementIdentifier).usedDirectives;
expect(usedDirectives).toEqual(
new Set([
{
node: declA,
selector: 'a-selector',
},
{
node: declB,
selector: '[b-selector]',
},
{
node: declC,
selector: ':not(never-selector)',
},
]),
);
});
}); | {
"end_byte": 28553,
"start_byte": 19909,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts_28557_32040 | describe('generates identifiers for templates', () => {
it('should record templates as TemplateNodeIdentifiers', () => {
const template = '<ng-template>';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref.kind).toBe(IdentifierKind.Template);
});
it('should record template names as their tag name', () => {
const template = '<ng-template>';
const refs = getTemplateIdentifiers(bind(template));
expect(refs.size).toBe(1);
const [ref] = Array.from(refs);
expect(ref as TemplateNodeIdentifier).toEqual({
name: 'ng-template',
kind: IdentifierKind.Template,
span: new AbsoluteSourceSpan(1, 12),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should discover nested templates', () => {
const template = '<div><ng-template></ng-template></div>';
const refs = getTemplateIdentifiers(bind(template));
const refArr = Array.from(refs);
expect(refArr).toContain({
name: 'ng-template',
kind: IdentifierKind.Template,
span: new AbsoluteSourceSpan(6, 17),
attributes: new Set(),
usedDirectives: new Set(),
});
});
it('should generate information about attributes', () => {
const template = '<ng-template attrA attrB="val">';
const refs = getTemplateIdentifiers(bind(template));
const [ref] = Array.from(refs);
const attrs = (ref as TemplateNodeIdentifier).attributes;
expect(attrs).toEqual(
new Set<AttributeIdentifier>([
{
name: 'attrA',
kind: IdentifierKind.Attribute,
span: new AbsoluteSourceSpan(13, 18),
},
{
name: 'attrB',
kind: IdentifierKind.Attribute,
span: new AbsoluteSourceSpan(19, 30),
},
]),
);
});
it('should generate information about used directives', () => {
const declB = util.getComponentDeclaration('class B {}', 'B');
const declC = util.getComponentDeclaration('class C {}', 'C');
const template = '<ng-template b-selector>';
const boundTemplate = util.getBoundTemplate(template, {}, [
{selector: '[b-selector]', declaration: declB},
{selector: ':not(never-selector)', declaration: declC},
]);
const refs = getTemplateIdentifiers(boundTemplate);
const [ref] = Array.from(refs);
const usedDirectives = (ref as ElementIdentifier).usedDirectives;
expect(usedDirectives).toEqual(
new Set([
{
node: declB,
selector: '[b-selector]',
},
{
node: declC,
selector: ':not(never-selector)',
},
]),
);
});
it('should handle interpolations in attributes, preceded by HTML entity', () => {
const template = `<img src=" {{foo}}" />`;
const refs = getTemplateIdentifiers(bind(template));
expect(Array.from(refs)).toEqual([
{
kind: IdentifierKind.Element,
name: 'img',
span: new AbsoluteSourceSpan(1, 4),
usedDirectives: new Set(),
attributes: new Set(),
},
{
kind: IdentifierKind.Property,
name: 'foo',
span: new AbsoluteSourceSpan(18, 21),
target: null,
},
]);
});
});
}); | {
"end_byte": 32040,
"start_byte": 28557,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/template_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/BUILD.bazel_0_828 | 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/compiler",
"//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/indexer",
"//packages/compiler-cli/src/ngtsc/metadata",
"//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": 828,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/test/transform_spec.ts_0_4574 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BoundTarget, ParseSourceFile} from '@angular/compiler';
import {runInEachFileSystem} from '../../file_system/testing';
import {ClassDeclaration} from '../../reflection';
import {ComponentMeta, IndexingContext} from '../src/context';
import {getTemplateIdentifiers} from '../src/template';
import {generateAnalysis} from '../src/transform';
import * as util from './util';
/**
* Adds information about a component to a context.
*/
function populateContext(
context: IndexingContext,
component: ClassDeclaration,
selector: string,
template: string,
boundTemplate: BoundTarget<ComponentMeta>,
isInline: boolean = false,
) {
context.addComponent({
declaration: component,
selector,
boundTemplate,
templateMeta: {
isInline,
file: new ParseSourceFile(template, component.getSourceFile().fileName),
},
});
}
runInEachFileSystem(() => {
describe('generateAnalysis', () => {
it('should emit component and template analysis information', () => {
const context = new IndexingContext();
const decl = util.getComponentDeclaration('class C {}', 'C');
const template = '<div>{{foo}}</div>';
populateContext(context, decl, 'c-selector', template, util.getBoundTemplate(template));
const analysis = generateAnalysis(context);
expect(analysis.size).toBe(1);
const info = analysis.get(decl);
expect(info).toEqual({
name: 'C',
selector: 'c-selector',
file: new ParseSourceFile('class C {}', decl.getSourceFile().fileName),
template: {
identifiers: getTemplateIdentifiers(util.getBoundTemplate('<div>{{foo}}</div>'))
.identifiers,
usedComponents: new Set(),
isInline: false,
file: new ParseSourceFile('<div>{{foo}}</div>', decl.getSourceFile().fileName),
},
errors: [],
});
});
it('should give inline templates the component source file', () => {
const context = new IndexingContext();
const decl = util.getComponentDeclaration('class C {}', 'C');
const template = '<div>{{foo}}</div>';
populateContext(
context,
decl,
'c-selector',
'<div>{{foo}}</div>',
util.getBoundTemplate(template),
/* inline template */ true,
);
const analysis = generateAnalysis(context);
expect(analysis.size).toBe(1);
const info = analysis.get(decl);
expect(info).toBeDefined();
expect(info!.template.file).toEqual(
new ParseSourceFile('class C {}', decl.getSourceFile().fileName),
);
});
it('should give external templates their own source file', () => {
const context = new IndexingContext();
const decl = util.getComponentDeclaration('class C {}', 'C');
const template = '<div>{{foo}}</div>';
populateContext(context, decl, 'c-selector', template, util.getBoundTemplate(template));
const analysis = generateAnalysis(context);
expect(analysis.size).toBe(1);
const info = analysis.get(decl);
expect(info).toBeDefined();
expect(info!.template.file).toEqual(
new ParseSourceFile('<div>{{foo}}</div>', decl.getSourceFile().fileName),
);
});
it('should emit used components', () => {
const context = new IndexingContext();
const templateA = '<b-selector></b-selector>';
const declA = util.getComponentDeclaration('class A {}', 'A');
const templateB = '<a-selector></a-selector>';
const declB = util.getComponentDeclaration('class B {}', 'B');
const boundA = util.getBoundTemplate(templateA, {}, [
{selector: 'b-selector', declaration: declB},
]);
const boundB = util.getBoundTemplate(templateB, {}, [
{selector: 'a-selector', declaration: declA},
]);
populateContext(context, declA, 'a-selector', templateA, boundA);
populateContext(context, declB, 'b-selector', templateB, boundB);
const analysis = generateAnalysis(context);
expect(analysis.size).toBe(2);
const infoA = analysis.get(declA);
expect(infoA).toBeDefined();
expect(infoA!.template.usedComponents).toEqual(new Set([declB]));
const infoB = analysis.get(declB);
expect(infoB).toBeDefined();
expect(infoB!.template.usedComponents).toEqual(new Set([declA]));
});
});
});
| {
"end_byte": 4574,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/test/transform_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/src/template.ts_0_6222 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AST,
ASTWithSource,
BoundTarget,
ImplicitReceiver,
ParseSourceSpan,
PropertyRead,
PropertyWrite,
RecursiveAstVisitor,
TmplAstBoundAttribute,
TmplAstBoundDeferredTrigger,
TmplAstBoundEvent,
TmplAstBoundText,
TmplAstDeferredBlock,
TmplAstDeferredBlockError,
TmplAstDeferredBlockLoading,
TmplAstDeferredBlockPlaceholder,
TmplAstDeferredTrigger,
TmplAstElement,
TmplAstForLoopBlock,
TmplAstForLoopBlockEmpty,
TmplAstIfBlock,
TmplAstIfBlockBranch,
TmplAstLetDeclaration,
TmplAstNode,
TmplAstRecursiveVisitor,
TmplAstReference,
TmplAstSwitchBlock,
TmplAstSwitchBlockCase,
TmplAstTemplate,
TmplAstVariable,
} from '@angular/compiler';
import {ClassDeclaration, DeclarationNode} from '../../reflection';
import {
AbsoluteSourceSpan,
AttributeIdentifier,
ElementIdentifier,
IdentifierKind,
LetDeclarationIdentifier,
MethodIdentifier,
PropertyIdentifier,
ReferenceIdentifier,
TemplateNodeIdentifier,
TopLevelIdentifier,
VariableIdentifier,
} from './api';
import {ComponentMeta} from './context';
/**
* A parsed node in a template, which may have a name (if it is a selector) or
* be anonymous (like a text span).
*/
interface HTMLNode extends TmplAstNode {
tagName?: string;
name?: string;
}
type ExpressionIdentifier = PropertyIdentifier | MethodIdentifier;
type TmplTarget = TmplAstReference | TmplAstVariable | TmplAstLetDeclaration;
type TargetIdentifier = ReferenceIdentifier | VariableIdentifier | LetDeclarationIdentifier;
type TargetIdentifierMap = Map<TmplTarget, TargetIdentifier>;
/**
* Visits the AST of an Angular template syntax expression, finding interesting
* entities (variable references, etc.). Creates an array of Entities found in
* the expression, with the location of the Entities being relative to the
* expression.
*
* Visiting `text {{prop}}` will return
* `[TopLevelIdentifier {name: 'prop', span: {start: 7, end: 11}}]`.
*/
class ExpressionVisitor extends RecursiveAstVisitor {
readonly identifiers: ExpressionIdentifier[] = [];
readonly errors: Error[] = [];
private constructor(
private readonly expressionStr: string,
private readonly absoluteOffset: number,
private readonly boundTemplate: BoundTarget<ComponentMeta>,
private readonly targetToIdentifier: (target: TmplTarget) => TargetIdentifier | null,
) {
super();
}
/**
* Returns identifiers discovered in an expression.
*
* @param ast expression AST to visit
* @param source expression AST source code
* @param absoluteOffset absolute byte offset from start of the file to the start of the AST
* source code.
* @param boundTemplate bound target of the entire template, which can be used to query for the
* entities expressions target.
* @param targetToIdentifier closure converting a template target node to its identifier.
*/
static getIdentifiers(
ast: AST,
source: string,
absoluteOffset: number,
boundTemplate: BoundTarget<ComponentMeta>,
targetToIdentifier: (target: TmplTarget) => TargetIdentifier | null,
): {identifiers: TopLevelIdentifier[]; errors: Error[]} {
const visitor = new ExpressionVisitor(
source,
absoluteOffset,
boundTemplate,
targetToIdentifier,
);
visitor.visit(ast);
return {identifiers: visitor.identifiers, errors: visitor.errors};
}
override visit(ast: AST) {
ast.visit(this);
}
override visitPropertyRead(ast: PropertyRead, context: {}) {
this.visitIdentifier(ast, IdentifierKind.Property);
super.visitPropertyRead(ast, context);
}
override visitPropertyWrite(ast: PropertyWrite, context: {}) {
this.visitIdentifier(ast, IdentifierKind.Property);
super.visitPropertyWrite(ast, context);
}
/**
* Visits an identifier, adding it to the identifier store if it is useful for indexing.
*
* @param ast expression AST the identifier is in
* @param kind identifier kind
*/
private visitIdentifier(
ast: AST & {name: string; receiver: AST},
kind: ExpressionIdentifier['kind'],
) {
// The definition of a non-top-level property such as `bar` in `{{foo.bar}}` is currently
// impossible to determine by an indexer and unsupported by the indexing module.
// The indexing module also does not currently support references to identifiers declared in the
// template itself, which have a non-null expression target.
if (!(ast.receiver instanceof ImplicitReceiver)) {
return;
}
// The source span of the requested AST starts at a location that is offset from the expression.
let identifierStart = ast.sourceSpan.start - this.absoluteOffset;
if (ast instanceof PropertyRead || ast instanceof PropertyWrite) {
// For `PropertyRead` and `PropertyWrite`, the identifier starts at the `nameSpan`, not
// necessarily the `sourceSpan`.
identifierStart = ast.nameSpan.start - this.absoluteOffset;
}
if (!this.expressionStr.substring(identifierStart).startsWith(ast.name)) {
this.errors.push(
new Error(
`Impossible state: "${ast.name}" not found in "${this.expressionStr}" at location ${identifierStart}`,
),
);
return;
}
// Join the relative position of the expression within a node with the absolute position
// of the node to get the absolute position of the expression in the source code.
const absoluteStart = this.absoluteOffset + identifierStart;
const span = new AbsoluteSourceSpan(absoluteStart, absoluteStart + ast.name.length);
const targetAst = this.boundTemplate.getExpressionTarget(ast);
const target = targetAst ? this.targetToIdentifier(targetAst) : null;
const identifier = {
name: ast.name,
span,
kind,
target,
} as ExpressionIdentifier;
this.identifiers.push(identifier);
}
}
/**
* Visits the AST of a parsed Angular template. Discovers and stores
* identifiers of interest, deferring to an `ExpressionVisitor` as needed.
*/ | {
"end_byte": 6222,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/src/template.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/src/template.ts_6223_13970 | class TemplateVisitor extends TmplAstRecursiveVisitor {
// Identifiers of interest found in the template.
readonly identifiers = new Set<TopLevelIdentifier>();
readonly errors: Error[] = [];
// Map of targets in a template to their identifiers.
private readonly targetIdentifierCache: TargetIdentifierMap = new Map();
// Map of elements and templates to their identifiers.
private readonly elementAndTemplateIdentifierCache = new Map<
TmplAstElement | TmplAstTemplate,
ElementIdentifier | TemplateNodeIdentifier
>();
/**
* Creates a template visitor for a bound template target. The bound target can be used when
* deferred to the expression visitor to get information about the target of an expression.
*
* @param boundTemplate bound template target
*/
constructor(private boundTemplate: BoundTarget<ComponentMeta>) {
super();
}
/**
* Visits a node in the template.
*
* @param node node to visit
*/
visit(node: HTMLNode) {
node.visit(this);
}
visitAll(nodes: TmplAstNode[]) {
nodes.forEach((node) => this.visit(node));
}
/**
* Add an identifier for an HTML element and visit its children recursively.
*
* @param element
*/
override visitElement(element: TmplAstElement) {
const elementIdentifier = this.elementOrTemplateToIdentifier(element);
if (elementIdentifier !== null) {
this.identifiers.add(elementIdentifier);
}
this.visitAll(element.references);
this.visitAll(element.inputs);
this.visitAll(element.attributes);
this.visitAll(element.children);
this.visitAll(element.outputs);
}
override visitTemplate(template: TmplAstTemplate) {
const templateIdentifier = this.elementOrTemplateToIdentifier(template);
if (templateIdentifier !== null) {
this.identifiers.add(templateIdentifier);
}
this.visitAll(template.variables);
this.visitAll(template.attributes);
this.visitAll(template.templateAttrs);
this.visitAll(template.children);
this.visitAll(template.references);
}
override visitBoundAttribute(attribute: TmplAstBoundAttribute) {
// If the bound attribute has no value, it cannot have any identifiers in the value expression.
if (attribute.valueSpan === undefined) {
return;
}
const {identifiers, errors} = ExpressionVisitor.getIdentifiers(
attribute.value,
attribute.valueSpan.toString(),
attribute.valueSpan.start.offset,
this.boundTemplate,
this.targetToIdentifier.bind(this),
);
identifiers.forEach((id) => this.identifiers.add(id));
this.errors.push(...errors);
}
override visitBoundEvent(attribute: TmplAstBoundEvent) {
this.visitExpression(attribute.handler);
}
override visitBoundText(text: TmplAstBoundText) {
this.visitExpression(text.value);
}
override visitReference(reference: TmplAstReference) {
const referenceIdentifier = this.targetToIdentifier(reference);
if (referenceIdentifier === null) {
return;
}
this.identifiers.add(referenceIdentifier);
}
override visitVariable(variable: TmplAstVariable) {
const variableIdentifier = this.targetToIdentifier(variable);
if (variableIdentifier === null) {
return;
}
this.identifiers.add(variableIdentifier);
}
override visitDeferredBlock(deferred: TmplAstDeferredBlock) {
deferred.visitAll(this);
}
override visitDeferredBlockPlaceholder(block: TmplAstDeferredBlockPlaceholder) {
this.visitAll(block.children);
}
override visitDeferredBlockError(block: TmplAstDeferredBlockError) {
this.visitAll(block.children);
}
override visitDeferredBlockLoading(block: TmplAstDeferredBlockLoading) {
this.visitAll(block.children);
}
override visitDeferredTrigger(trigger: TmplAstDeferredTrigger) {
if (trigger instanceof TmplAstBoundDeferredTrigger) {
this.visitExpression(trigger.value);
}
}
override visitSwitchBlock(block: TmplAstSwitchBlock) {
this.visitExpression(block.expression);
this.visitAll(block.cases);
}
override visitSwitchBlockCase(block: TmplAstSwitchBlockCase) {
block.expression && this.visitExpression(block.expression);
this.visitAll(block.children);
}
override visitForLoopBlock(block: TmplAstForLoopBlock): void {
block.item.visit(this);
this.visitAll(block.contextVariables);
this.visitExpression(block.expression);
this.visitAll(block.children);
block.empty?.visit(this);
}
override visitForLoopBlockEmpty(block: TmplAstForLoopBlockEmpty): void {
this.visitAll(block.children);
}
override visitIfBlock(block: TmplAstIfBlock): void {
this.visitAll(block.branches);
}
override visitIfBlockBranch(block: TmplAstIfBlockBranch): void {
block.expression && this.visitExpression(block.expression);
block.expressionAlias?.visit(this);
this.visitAll(block.children);
}
override visitLetDeclaration(decl: TmplAstLetDeclaration): void {
const identifier = this.targetToIdentifier(decl);
if (identifier !== null) {
this.identifiers.add(identifier);
}
this.visitExpression(decl.value);
}
/** Creates an identifier for a template element or template node. */
private elementOrTemplateToIdentifier(
node: TmplAstElement | TmplAstTemplate,
): ElementIdentifier | TemplateNodeIdentifier | null {
// If this node has already been seen, return the cached result.
if (this.elementAndTemplateIdentifierCache.has(node)) {
return this.elementAndTemplateIdentifierCache.get(node)!;
}
let name: string;
let kind: IdentifierKind.Element | IdentifierKind.Template;
if (node instanceof TmplAstTemplate) {
name = node.tagName ?? 'ng-template';
kind = IdentifierKind.Template;
} else {
name = node.name;
kind = IdentifierKind.Element;
}
// Namespaced elements have a particular format for `node.name` that needs to be handled.
// For example, an `<svg>` element has a `node.name` of `':svg:svg'`.
// TODO(alxhub): properly handle namespaced elements
if (name.startsWith(':')) {
name = name.split(':').pop()!;
}
const sourceSpan = node.startSourceSpan;
// An element's or template's source span can be of the form `<element>`, `<element />`, or
// `<element></element>`. Only the selector is interesting to the indexer, so the source is
// searched for the first occurrence of the element (selector) name.
const start = this.getStartLocation(name, sourceSpan);
if (start === null) {
return null;
}
const absoluteSpan = new AbsoluteSourceSpan(start, start + name.length);
// Record the nodes's attributes, which an indexer can later traverse to see if any of them
// specify a used directive on the node.
const attributes = node.attributes.map(({name, sourceSpan}): AttributeIdentifier => {
return {
name,
span: new AbsoluteSourceSpan(sourceSpan.start.offset, sourceSpan.end.offset),
kind: IdentifierKind.Attribute,
};
});
const usedDirectives = this.boundTemplate.getDirectivesOfNode(node) || [];
const identifier = {
name,
span: absoluteSpan,
kind,
attributes: new Set(attributes),
usedDirectives: new Set(
usedDirectives.map((dir) => {
return {
node: dir.ref.node,
selector: dir.selector,
};
}),
),
// cast b/c pre-TypeScript 3.5 unions aren't well discriminated
} as ElementIdentifier | TemplateNodeIdentifier;
this.elementAndTemplateIdentifierCache.set(node, identifier);
return identifier;
}
/** Creates an identifier for a template reference or template variable target. */ | {
"end_byte": 13970,
"start_byte": 6223,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/src/template.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/src/template.ts_13973_17924 | private targetToIdentifier(node: TmplTarget): TargetIdentifier | null {
// If this node has already been seen, return the cached result.
if (this.targetIdentifierCache.has(node)) {
return this.targetIdentifierCache.get(node)!;
}
const {name, sourceSpan} = node;
const start = this.getStartLocation(name, sourceSpan);
if (start === null) {
return null;
}
const span = new AbsoluteSourceSpan(start, start + name.length);
let identifier: ReferenceIdentifier | VariableIdentifier | LetDeclarationIdentifier;
if (node instanceof TmplAstReference) {
// If the node is a reference, we care about its target. The target can be an element, a
// template, a directive applied on a template or element (in which case the directive field
// is non-null), or nothing at all.
const refTarget = this.boundTemplate.getReferenceTarget(node);
let target = null;
if (refTarget) {
let node: ElementIdentifier | TemplateNodeIdentifier | null = null;
let directive: ClassDeclaration<DeclarationNode> | null = null;
if (refTarget instanceof TmplAstElement || refTarget instanceof TmplAstTemplate) {
node = this.elementOrTemplateToIdentifier(refTarget);
} else {
node = this.elementOrTemplateToIdentifier(refTarget.node);
directive = refTarget.directive.ref.node;
}
if (node === null) {
return null;
}
target = {
node,
directive,
};
}
identifier = {
name,
span,
kind: IdentifierKind.Reference,
target,
};
} else if (node instanceof TmplAstVariable) {
identifier = {
name,
span,
kind: IdentifierKind.Variable,
};
} else {
identifier = {
name,
span,
kind: IdentifierKind.LetDeclaration,
};
}
this.targetIdentifierCache.set(node, identifier);
return identifier;
}
/** Gets the start location of a string in a SourceSpan */
private getStartLocation(name: string, context: ParseSourceSpan): number | null {
const localStr = context.toString();
if (!localStr.includes(name)) {
this.errors.push(new Error(`Impossible state: "${name}" not found in "${localStr}"`));
return null;
}
return context.start.offset + localStr.indexOf(name);
}
/**
* Visits a node's expression and adds its identifiers, if any, to the visitor's state.
* Only ASTs with information about the expression source and its location are visited.
*
* @param node node whose expression to visit
*/
private visitExpression(ast: AST) {
// Only include ASTs that have information about their source and absolute source spans.
if (ast instanceof ASTWithSource && ast.source !== null) {
// Make target to identifier mapping closure stateful to this visitor instance.
const targetToIdentifier = this.targetToIdentifier.bind(this);
const absoluteOffset = ast.sourceSpan.start;
const {identifiers, errors} = ExpressionVisitor.getIdentifiers(
ast,
ast.source,
absoluteOffset,
this.boundTemplate,
targetToIdentifier,
);
identifiers.forEach((id) => this.identifiers.add(id));
this.errors.push(...errors);
}
}
}
/**
* Traverses a template AST and builds identifiers discovered in it.
*
* @param boundTemplate bound template target, which can be used for querying expression targets.
* @return identifiers in template
*/
export function getTemplateIdentifiers(boundTemplate: BoundTarget<ComponentMeta>): {
identifiers: Set<TopLevelIdentifier>;
errors: Error[];
} {
const visitor = new TemplateVisitor(boundTemplate);
if (boundTemplate.target.template !== undefined) {
visitor.visitAll(boundTemplate.target.template);
}
return {identifiers: visitor.identifiers, errors: visitor.errors};
} | {
"end_byte": 17924,
"start_byte": 13973,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/src/template.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/src/transform.ts_0_2004 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ParseSourceFile} from '@angular/compiler';
import {DeclarationNode} from '../../reflection';
import {IndexedComponent} from './api';
import {IndexingContext} from './context';
import {getTemplateIdentifiers} from './template';
/**
* Generates `IndexedComponent` entries from a `IndexingContext`, which has information
* about components discovered in the program registered in it.
*
* The context must be populated before `generateAnalysis` is called.
*/
export function generateAnalysis(context: IndexingContext): Map<DeclarationNode, IndexedComponent> {
const analysis = new Map<DeclarationNode, IndexedComponent>();
context.components.forEach(({declaration, selector, boundTemplate, templateMeta}) => {
const name = declaration.name.getText();
const usedComponents = new Set<DeclarationNode>();
const usedDirs = boundTemplate.getUsedDirectives();
usedDirs.forEach((dir) => {
if (dir.isComponent) {
usedComponents.add(dir.ref.node);
}
});
// Get source files for the component and the template. If the template is inline, its source
// file is the component's.
const componentFile = new ParseSourceFile(
declaration.getSourceFile().getFullText(),
declaration.getSourceFile().fileName,
);
let templateFile: ParseSourceFile;
if (templateMeta.isInline) {
templateFile = componentFile;
} else {
templateFile = templateMeta.file;
}
const {identifiers, errors} = getTemplateIdentifiers(boundTemplate);
analysis.set(declaration, {
name,
selector,
file: componentFile,
template: {
identifiers,
usedComponents,
isInline: templateMeta.isInline,
file: templateFile,
},
errors,
});
});
return analysis;
}
| {
"end_byte": 2004,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/src/transform.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/src/context.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
*/
import {BoundTarget, DirectiveMeta, ParseSourceFile} from '@angular/compiler';
import {Reference} from '../../imports';
import {ClassDeclaration} from '../../reflection';
export interface ComponentMeta extends DirectiveMeta {
ref: Reference<ClassDeclaration>;
/**
* Unparsed selector of the directive, or null if the directive does not have a selector.
*/
selector: string | null;
}
/**
* An intermediate representation of a component.
*/
export interface ComponentInfo {
/** Component TypeScript class declaration */
declaration: ClassDeclaration;
/** Component template selector if it exists, otherwise null. */
selector: string | null;
/**
* BoundTarget containing the parsed template. Can also be used to query for directives used in
* the template.
*/
boundTemplate: BoundTarget<ComponentMeta>;
/** Metadata about the template */
templateMeta: {
/** Whether the component template is inline */
isInline: boolean;
/** Template file recorded by template parser */
file: ParseSourceFile;
};
}
/**
* A context for storing indexing information about components of a program.
*
* An `IndexingContext` collects component and template analysis information from
* `DecoratorHandler`s and exposes them to be indexed.
*/
export class IndexingContext {
readonly components = new Set<ComponentInfo>();
/**
* Adds a component to the context.
*/
addComponent(info: ComponentInfo) {
this.components.add(info);
}
}
| {
"end_byte": 1696,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/src/context.ts"
} |
angular/packages/compiler-cli/src/ngtsc/indexer/src/api.ts_0_4567 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ParseSourceFile} from '@angular/compiler';
import {ClassDeclaration, DeclarationNode} from '../../reflection';
/**
* Describes the kind of identifier found in a template.
*/
export enum IdentifierKind {
Property,
Method, // TODO: No longer being used. To be removed together with `MethodIdentifier`.
Element,
Template,
Attribute,
Reference,
Variable,
LetDeclaration,
}
/**
* Describes a semantically-interesting identifier in a template, such as an interpolated variable
* or selector.
*/
export interface TemplateIdentifier {
name: string;
span: AbsoluteSourceSpan;
kind: IdentifierKind;
}
/** Describes a template expression, which may have a template reference or variable target. */
interface ExpressionIdentifier extends TemplateIdentifier {
/**
* ReferenceIdentifier or VariableIdentifier in the template that this identifier targets, if
* any. If the target is `null`, it points to a declaration on the component class.
* */
target: ReferenceIdentifier | VariableIdentifier | LetDeclarationIdentifier | null;
}
/** Describes a property accessed in a template. */
export interface PropertyIdentifier extends ExpressionIdentifier {
kind: IdentifierKind.Property;
}
/**
* Describes a method accessed in a template.
* @deprecated No longer being used. To be removed.
*/
export interface MethodIdentifier extends ExpressionIdentifier {
kind: IdentifierKind.Method;
}
/** Describes an element attribute in a template. */
export interface AttributeIdentifier extends TemplateIdentifier {
kind: IdentifierKind.Attribute;
}
/** A reference to a directive node and its selector. */
interface DirectiveReference {
node: ClassDeclaration;
selector: string;
}
/** A base interface for element and template identifiers. */
interface BaseElementOrTemplateIdentifier extends TemplateIdentifier {
/** Attributes on an element or template. */
attributes: Set<AttributeIdentifier>;
/** Directives applied to an element or template. */
usedDirectives: Set<DirectiveReference>;
}
/**
* Describes an indexed element in a template. The name of an `ElementIdentifier` is the entire
* element tag, which can be parsed by an indexer to determine where used directives should be
* referenced.
*/
export interface ElementIdentifier extends BaseElementOrTemplateIdentifier {
kind: IdentifierKind.Element;
}
/** Describes an indexed template node in a component template file. */
export interface TemplateNodeIdentifier extends BaseElementOrTemplateIdentifier {
kind: IdentifierKind.Template;
}
/** Describes a reference in a template like "foo" in `<div #foo></div>`. */
export interface ReferenceIdentifier extends TemplateIdentifier {
kind: IdentifierKind.Reference;
/** The target of this reference. If the target is not known, this is `null`. */
target: {
/** The template AST node that the reference targets. */
node: ElementIdentifier | TemplateIdentifier;
/**
* The directive on `node` that the reference targets. If no directive is targeted, this is
* `null`.
*/
directive: ClassDeclaration | null;
} | null;
}
/** Describes a template variable like "foo" in `<div *ngFor="let foo of foos"></div>`. */
export interface VariableIdentifier extends TemplateIdentifier {
kind: IdentifierKind.Variable;
}
/** Describes a `@let` declaration in a template. */
export interface LetDeclarationIdentifier extends TemplateIdentifier {
kind: IdentifierKind.LetDeclaration;
}
/**
* Identifiers recorded at the top level of the template, without any context about the HTML nodes
* they were discovered in.
*/
export type TopLevelIdentifier =
| PropertyIdentifier
| ElementIdentifier
| TemplateNodeIdentifier
| ReferenceIdentifier
| VariableIdentifier
| MethodIdentifier
| LetDeclarationIdentifier;
/**
* Describes the absolute byte offsets of a text anchor in a source code.
*/
export class AbsoluteSourceSpan {
constructor(
public start: number,
public end: number,
) {}
}
/**
* Describes an analyzed, indexed component and its template.
*/
export interface IndexedComponent {
name: string;
selector: string | null;
file: ParseSourceFile;
template: {
identifiers: Set<TopLevelIdentifier>;
usedComponents: Set<DeclarationNode>;
isInline: boolean;
file: ParseSourceFile;
};
errors: Error[];
}
| {
"end_byte": 4567,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/indexer/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/validation/BUILD.bazel_0_542 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "validation",
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 542,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/validation/index.ts_0_269 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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 {SourceFileValidator} from './src/source_file_validator';
| {
"end_byte": 269,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/validation/src/config.ts_0_399 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Whether the rule to check for unused standalone imports is enabled.
* Used to disable it conditionally in internal builds.
*/
export const UNUSED_STANDALONE_IMPORTS_RULE_ENABLED = true;
| {
"end_byte": 399,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/src/config.ts"
} |
angular/packages/compiler-cli/src/ngtsc/validation/src/source_file_validator.ts_0_2597 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ImportedSymbolsTracker} from '../../imports';
import {ReflectionHost} from '../../reflection';
import {SourceFileValidatorRule} from './rules/api';
import {InitializerApiUsageRule} from './rules/initializer_api_usage_rule';
import {UnusedStandaloneImportsRule} from './rules/unused_standalone_imports_rule';
import {TemplateTypeChecker, TypeCheckingConfig} from '../../typecheck/api';
import {UNUSED_STANDALONE_IMPORTS_RULE_ENABLED} from './config';
/**
* Validates that TypeScript files match a specific set of rules set by the Angular compiler.
*/
export class SourceFileValidator {
private rules: SourceFileValidatorRule[];
constructor(
reflector: ReflectionHost,
importedSymbolsTracker: ImportedSymbolsTracker,
templateTypeChecker: TemplateTypeChecker,
typeCheckingConfig: TypeCheckingConfig,
) {
this.rules = [new InitializerApiUsageRule(reflector, importedSymbolsTracker)];
if (UNUSED_STANDALONE_IMPORTS_RULE_ENABLED) {
this.rules.push(
new UnusedStandaloneImportsRule(
templateTypeChecker,
typeCheckingConfig,
importedSymbolsTracker,
),
);
}
}
/**
* Gets the diagnostics for a specific file, or null if the file is valid.
* @param sourceFile File to be checked.
*/
getDiagnosticsForFile(sourceFile: ts.SourceFile): ts.Diagnostic[] | null {
if (sourceFile.isDeclarationFile || sourceFile.fileName.endsWith('.ngtypecheck.ts')) {
return null;
}
let rulesToRun: SourceFileValidatorRule[] | null = null;
for (const rule of this.rules) {
if (rule.shouldCheck(sourceFile)) {
rulesToRun ??= [];
rulesToRun.push(rule);
}
}
if (rulesToRun === null) {
return null;
}
let fileDiagnostics: ts.Diagnostic[] | null = null;
sourceFile.forEachChild(function walk(node) {
// Note: non-null assertion is here because of g3.
for (const rule of rulesToRun!) {
const nodeDiagnostics = rule.checkNode(node);
if (nodeDiagnostics !== null) {
fileDiagnostics ??= [];
if (Array.isArray(nodeDiagnostics)) {
fileDiagnostics.push(...nodeDiagnostics);
} else {
fileDiagnostics.push(nodeDiagnostics);
}
}
}
node.forEachChild(walk);
});
return fileDiagnostics;
}
}
| {
"end_byte": 2597,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/src/source_file_validator.ts"
} |
angular/packages/compiler-cli/src/ngtsc/validation/src/rules/unused_standalone_imports_rule.ts_0_5665 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ImportedSymbolsTracker, Reference} from '../../../imports';
import {
TemplateTypeChecker,
TypeCheckableDirectiveMeta,
TypeCheckingConfig,
} from '../../../typecheck/api';
import {SourceFileValidatorRule} from './api';
/**
* Rule that flags unused symbols inside of the `imports` array of a component.
*/
export class UnusedStandaloneImportsRule implements SourceFileValidatorRule {
constructor(
private templateTypeChecker: TemplateTypeChecker,
private typeCheckingConfig: TypeCheckingConfig,
private importedSymbolsTracker: ImportedSymbolsTracker,
) {}
shouldCheck(sourceFile: ts.SourceFile): boolean {
return (
this.typeCheckingConfig.unusedStandaloneImports !== 'suppress' &&
(this.importedSymbolsTracker.hasNamedImport(sourceFile, 'Component', '@angular/core') ||
this.importedSymbolsTracker.hasNamespaceImport(sourceFile, '@angular/core'))
);
}
checkNode(node: ts.Node): ts.Diagnostic | null {
if (!ts.isClassDeclaration(node)) {
return null;
}
const metadata = this.templateTypeChecker.getDirectiveMetadata(node);
if (
!metadata ||
!metadata.isStandalone ||
metadata.rawImports === null ||
metadata.imports === null ||
metadata.imports.length === 0
) {
return null;
}
const usedDirectives = this.templateTypeChecker.getUsedDirectives(node);
const usedPipes = this.templateTypeChecker.getUsedPipes(node);
// These will be null if the component is invalid for some reason.
if (!usedDirectives || !usedPipes) {
return null;
}
const unused = this.getUnusedSymbols(
metadata,
new Set(usedDirectives.map((dir) => dir.ref.node as ts.ClassDeclaration)),
new Set(usedPipes),
);
if (unused === null) {
return null;
}
const category =
this.typeCheckingConfig.unusedStandaloneImports === 'error'
? ts.DiagnosticCategory.Error
: ts.DiagnosticCategory.Warning;
if (unused.length === metadata.imports.length) {
return makeDiagnostic(
ErrorCode.UNUSED_STANDALONE_IMPORTS,
metadata.rawImports,
'All imports are unused',
undefined,
category,
);
}
return makeDiagnostic(
ErrorCode.UNUSED_STANDALONE_IMPORTS,
metadata.rawImports,
'Imports array contains unused imports',
unused.map(([ref, type, name]) =>
makeRelatedInformation(
ref.getOriginForDiagnostics(metadata.rawImports!),
`${type} "${name}" is not used within the template`,
),
),
category,
);
}
private getUnusedSymbols(
metadata: TypeCheckableDirectiveMeta,
usedDirectives: Set<ts.ClassDeclaration>,
usedPipes: Set<string>,
) {
const {imports, rawImports} = metadata;
if (imports === null || rawImports === null) {
return null;
}
let unused: [ref: Reference, type: string, name: string][] | null = null;
for (const current of imports) {
const currentNode = current.node as ts.ClassDeclaration;
const dirMeta = this.templateTypeChecker.getDirectiveMetadata(currentNode);
if (dirMeta !== null) {
if (
dirMeta.isStandalone &&
!usedDirectives.has(currentNode) &&
!this.isPotentialSharedReference(current, rawImports)
) {
unused ??= [];
unused.push([current, dirMeta.isComponent ? 'Component' : 'Directive', dirMeta.name]);
}
continue;
}
const pipeMeta = this.templateTypeChecker.getPipeMetadata(currentNode);
if (
pipeMeta !== null &&
pipeMeta.isStandalone &&
!usedPipes.has(pipeMeta.name) &&
!this.isPotentialSharedReference(current, rawImports)
) {
unused ??= [];
unused.push([current, 'Pipe', pipeMeta.ref.node.name.text]);
}
}
return unused;
}
/**
* Determines if an import reference *might* be coming from a shared imports array.
* @param reference Reference to be checked.
* @param rawImports AST node that defines the `imports` array.
*/
private isPotentialSharedReference(reference: Reference, rawImports: ts.Expression): boolean {
// If the reference is defined directly in the `imports` array, it cannot be shared.
if (reference.getIdentityInExpression(rawImports) !== null) {
return false;
}
// The reference might be shared if it comes from an exported array. If the variable is local
/// to the file, then it likely isn't shared. Note that this has the potential for false
// positives if a non-exported array of imports is shared between components in the same
// file. This scenario is unlikely and even if we report the diagnostic for it, it would be
// okay since the user only has to refactor components within the same file, rather than the
// entire application.
let current: ts.Node | null = reference.getIdentityIn(rawImports.getSourceFile());
while (current !== null) {
if (ts.isVariableStatement(current)) {
return !!current.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
}
current = current.parent;
}
// Otherwise the reference likely comes from an imported
// symbol like an array of shared common components.
return true;
}
}
| {
"end_byte": 5665,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/src/rules/unused_standalone_imports_rule.ts"
} |
angular/packages/compiler-cli/src/ngtsc/validation/src/rules/initializer_api_usage_rule.ts_0_3730 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {
InitializerApiFunction,
INPUT_INITIALIZER_FN,
MODEL_INITIALIZER_FN,
OUTPUT_INITIALIZER_FNS,
QUERY_INITIALIZER_FNS,
tryParseInitializerApi,
} from '../../../annotations';
import {ErrorCode, makeDiagnostic} from '../../../diagnostics';
import {ImportedSymbolsTracker} from '../../../imports';
import {ReflectionHost} from '../../../reflection';
import {SourceFileValidatorRule} from './api';
/** APIs whose usages should be checked by the rule. */
const APIS_TO_CHECK: InitializerApiFunction[] = [
INPUT_INITIALIZER_FN,
MODEL_INITIALIZER_FN,
...OUTPUT_INITIALIZER_FNS,
...QUERY_INITIALIZER_FNS,
];
/**
* Rule that flags any initializer APIs that are used outside of an initializer.
*/
export class InitializerApiUsageRule implements SourceFileValidatorRule {
constructor(
private reflector: ReflectionHost,
private importedSymbolsTracker: ImportedSymbolsTracker,
) {}
shouldCheck(sourceFile: ts.SourceFile): boolean {
// Skip the traversal if there are no imports of the initializer APIs.
return APIS_TO_CHECK.some(({functionName, owningModule}) => {
return (
this.importedSymbolsTracker.hasNamedImport(sourceFile, functionName, owningModule) ||
this.importedSymbolsTracker.hasNamespaceImport(sourceFile, owningModule)
);
});
}
checkNode(node: ts.Node): ts.Diagnostic | null {
// We only care about call expressions.
if (!ts.isCallExpression(node)) {
return null;
}
// Unwrap any parenthesized and `as` expressions since they don't affect the runtime behavior.
while (
node.parent &&
(ts.isParenthesizedExpression(node.parent) || ts.isAsExpression(node.parent))
) {
node = node.parent;
}
if (!node.parent || !ts.isCallExpression(node)) {
return null;
}
const identifiedInitializer = tryParseInitializerApi(
APIS_TO_CHECK,
node,
this.reflector,
this.importedSymbolsTracker,
);
if (identifiedInitializer === null) {
return null;
}
const functionName =
identifiedInitializer.api.functionName +
(identifiedInitializer.isRequired ? '.required' : '');
if (ts.isPropertyDeclaration(node.parent) && node.parent.initializer === node) {
let closestClass: ts.Node = node.parent;
while (closestClass && !ts.isClassDeclaration(closestClass)) {
closestClass = closestClass.parent;
}
if (closestClass && ts.isClassDeclaration(closestClass)) {
const decorators = this.reflector.getDecoratorsOfDeclaration(closestClass);
const isComponentOrDirective =
decorators !== null &&
decorators.some((decorator) => {
return (
decorator.import?.from === '@angular/core' &&
(decorator.name === 'Component' || decorator.name === 'Directive')
);
});
return isComponentOrDirective
? null
: makeDiagnostic(
ErrorCode.UNSUPPORTED_INITIALIZER_API_USAGE,
node,
`Unsupported call to the ${functionName} function. This function can only be used as the initializer ` +
`of a property on a @Component or @Directive class.`,
);
}
}
return makeDiagnostic(
ErrorCode.UNSUPPORTED_INITIALIZER_API_USAGE,
node,
`Unsupported call to the ${functionName} function. This function can only be called in the initializer of a class member.`,
);
}
}
| {
"end_byte": 3730,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/src/rules/initializer_api_usage_rule.ts"
} |
angular/packages/compiler-cli/src/ngtsc/validation/src/rules/api.ts_0_756 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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';
/**
* Rule that checks a source file a specific issue.
*/
export interface SourceFileValidatorRule {
/**
* Whether the file should be checked. Used to stop the traversal of the file early.
* @param sourceFile File to be checked.
*/
shouldCheck(sourceFile: ts.SourceFile): boolean;
/**
* Produces diagnostics for a specific node that may
* contain the issue that the rule is enforcing.
* @param node Node to be checked.
*/
checkNode(node: ts.Node): ts.Diagnostic | ts.Diagnostic[] | null;
}
| {
"end_byte": 756,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/validation/src/rules/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/BUILD.bazel_0_250 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "reflection",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"@npm//typescript",
],
)
| {
"end_byte": 250,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/index.ts_0_641 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/host';
export {typeNodeToValueExpr, entityNameToValue} from './src/type_to_value';
export {
TypeScriptReflectionHost,
filterToMembersWithDecorator,
reflectIdentifierOfDeclaration,
reflectNameOfDeclaration,
reflectObjectLiteral,
reflectTypeEntityToDeclaration,
} from './src/typescript';
export {
isNamedClassDeclaration,
isNamedFunctionDeclaration,
isNamedVariableDeclaration,
} from './src/util';
| {
"end_byte": 641,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts_0_9041 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {getDeclaration, makeProgram} from '../../testing';
import {ClassMember, ClassMemberKind, CtorParameter, TypeValueReferenceKind} from '../src/host';
import {TypeScriptReflectionHost} from '../src/typescript';
import {isNamedClassDeclaration} from '../src/util';
function findFirstImportDeclaration(node: ts.Node): ts.ImportDeclaration | null {
let found: ts.ImportDeclaration | null = null;
const visit = (node: ts.Node): void => {
if (found) return;
if (ts.isImportDeclaration(node)) {
found = node;
return;
}
ts.forEachChild(node, visit);
};
visit(node);
return found;
}
runInEachFileSystem(() => {
describe('reflector', () => {
let _: typeof absoluteFrom;
beforeEach(() => (_ = absoluteFrom));
describe('getConstructorParameters()', () => {
it('should reflect a single argument', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
class Bar {}
class Foo {
constructor(bar: Bar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
expectParameter(args[0], 'bar', 'Bar');
});
it('should reflect a decorated argument', () => {
const {program} = makeProgram([
{
name: _('/dec.ts'),
contents: `
export function dec(target: any, key: string, index: number) {
}
`,
},
{
name: _('/entry.ts'),
contents: `
import {dec} from './dec';
class Bar {}
class Foo {
constructor(@dec bar: Bar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
expectParameter(args[0], 'bar', 'Bar', 'dec', './dec');
});
it('should reflect a decorated argument with a call', () => {
const {program} = makeProgram([
{
name: _('/dec.ts'),
contents: `
export function dec(target: any, key: string, index: number) {
}
`,
},
{
name: _('/entry.ts'),
contents: `
import {dec} from './dec';
class Bar {}
class Foo {
constructor(@dec bar: Bar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
expectParameter(args[0], 'bar', 'Bar', 'dec', './dec');
});
it('should reflect a decorated argument with an indirection', () => {
const {program} = makeProgram([
{
name: _('/bar.ts'),
contents: `
export class Bar {}
`,
},
{
name: _('/entry.ts'),
contents: `
import {Bar} from './bar';
import * as star from './bar';
class Foo {
constructor(bar: Bar, otherBar: star.Bar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(2);
expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'});
expectParameter(args[1], 'otherBar', {moduleName: './bar', name: 'Bar'});
});
it('should reflect an argument from an aliased import', () => {
const {program} = makeProgram([
{
name: _('/bar.ts'),
contents: `
export class Bar {}
`,
},
{
name: _('/entry.ts'),
contents: `
import {Bar as LocalBar} from './bar';
class Foo {
constructor(bar: LocalBar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'});
});
it('should reflect an argument from a namespace declarations', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
export declare class Bar {}
declare namespace i1 {
export {
Bar,
}
}
class Foo {
constructor(bar: i1.Bar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
expectParameter(args[0], 'bar', 'i1.Bar');
});
it('should reflect an argument from a default import', () => {
const {program} = makeProgram([
{
name: _('/bar.ts'),
contents: `
export default class Bar {}
`,
},
{
name: _('/entry.ts'),
contents: `
import Bar from './bar';
class Foo {
constructor(bar: Bar) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
const param = args[0].typeValueReference;
if (param === null || param.kind !== TypeValueReferenceKind.LOCAL) {
return fail('Expected local parameter');
}
expect(param).not.toBeNull();
expect(param.defaultImportStatement).not.toBeNull();
});
it('should reflect a nullable argument', () => {
const {program} = makeProgram([
{
name: _('/bar.ts'),
contents: `
export class Bar {}
`,
},
{
name: _('/entry.ts'),
contents: `
import {Bar} from './bar';
class Foo {
constructor(bar: Bar|null) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(1);
expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'});
});
it('should reflect the arguments from an overloaded constructor', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
class Bar {}
class Baz {}
class Foo {
constructor(bar: Bar);
constructor(bar: Bar, baz?: Baz) {}
}
`,
},
]);
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const args = host.getConstructorParameters(clazz)!;
expect(args.length).toBe(2);
expectParameter(args[0], 'bar', 'Bar');
expectParameter(args[1], 'baz', 'Baz');
});
}); | {
"end_byte": 9041,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts_9047_18248 | describe('getImportOfIdentifier()', () => {
it('should resolve a direct import', () => {
const {program} = makeProgram([
{name: _('/node_modules/absolute/index.ts'), contents: 'export class Target {}'},
{
name: _('/entry.ts'),
contents: `
import {Target} from 'absolute';
let foo: Target;
`,
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const foo = getDeclaration(program, _('/entry.ts'), 'foo', ts.isVariableDeclaration);
if (
foo.type === undefined ||
!ts.isTypeReferenceNode(foo.type) ||
!ts.isIdentifier(foo.type.typeName)
) {
return fail('Unexpected type for foo');
}
const Target = foo.type.typeName;
const directImport = host.getImportOfIdentifier(Target);
const sf = foo.getSourceFile();
const importDecl = findFirstImportDeclaration(sf);
expect(directImport).toEqual({
name: 'Target',
from: 'absolute',
node: importDecl as ts.ImportDeclaration,
});
});
it('should resolve a namespaced import', () => {
const {program} = makeProgram([
{name: _('/node_modules/absolute/index.ts'), contents: 'export class Target {}'},
{
name: _('/entry.ts'),
contents: `
import * as abs from 'absolute';
let foo: abs.Target;
`,
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const foo = getDeclaration(program, _('/entry.ts'), 'foo', ts.isVariableDeclaration);
if (
foo.type === undefined ||
!ts.isTypeReferenceNode(foo.type) ||
!ts.isQualifiedName(foo.type.typeName)
) {
return fail('Unexpected type for foo');
}
const Target = foo.type.typeName.right;
const namespacedImport = host.getImportOfIdentifier(Target);
const sf = foo.getSourceFile();
const importDecl = findFirstImportDeclaration(sf);
expect(namespacedImport).toEqual({
name: 'Target',
from: 'absolute',
node: importDecl as ts.ImportDeclaration,
});
});
});
describe('getDeclarationOfIdentifier()', () => {
it('should reflect a re-export', () => {
const {program} = makeProgram([
{name: _('/node_modules/absolute/index.ts'), contents: 'export class Target {}'},
{name: _('/local1.ts'), contents: `export {Target as AliasTarget} from 'absolute';`},
{name: _('/local2.ts'), contents: `export {AliasTarget as Target} from './local1';`},
{
name: _('/entry.ts'),
contents: `
import {Target} from './local2';
import {Target as DirectTarget} from 'absolute';
const target = Target;
const directTarget = DirectTarget;
`,
},
]);
const target = getDeclaration(program, _('/entry.ts'), 'target', ts.isVariableDeclaration);
if (target.initializer === undefined || !ts.isIdentifier(target.initializer)) {
return fail('Unexpected initializer for target');
}
const directTarget = getDeclaration(
program,
_('/entry.ts'),
'directTarget',
ts.isVariableDeclaration,
);
if (directTarget.initializer === undefined || !ts.isIdentifier(directTarget.initializer)) {
return fail('Unexpected initializer for directTarget');
}
const Target = target.initializer;
const DirectTarget = directTarget.initializer;
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const targetDecl = host.getDeclarationOfIdentifier(Target);
const directTargetDecl = host.getDeclarationOfIdentifier(DirectTarget);
if (targetDecl === null) {
return fail('No declaration found for Target');
} else if (directTargetDecl === null) {
return fail('No declaration found for DirectTarget');
}
expect(targetDecl.node!.getSourceFile()).toBe(
getSourceFileOrError(program, _('/node_modules/absolute/index.ts')),
);
expect(ts.isClassDeclaration(targetDecl.node!)).toBe(true);
expect(directTargetDecl.viaModule).toBe('absolute');
expect(directTargetDecl.node).toBe(targetDecl.node);
});
it('should resolve a direct import', () => {
const {program} = makeProgram([
{name: _('/node_modules/absolute/index.ts'), contents: 'export class Target {}'},
{
name: _('/entry.ts'),
contents: `
import {Target} from 'absolute';
let foo: Target;
`,
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const targetDecl = getDeclaration(
program,
_('/node_modules/absolute/index.ts'),
'Target',
ts.isClassDeclaration,
);
const foo = getDeclaration(program, _('/entry.ts'), 'foo', ts.isVariableDeclaration);
if (
foo.type === undefined ||
!ts.isTypeReferenceNode(foo.type) ||
!ts.isIdentifier(foo.type.typeName)
) {
return fail('Unexpected type for foo');
}
const Target = foo.type.typeName;
const decl = host.getDeclarationOfIdentifier(Target);
expect(decl).toEqual({
node: targetDecl,
viaModule: 'absolute',
});
});
it('should resolve a namespaced import', () => {
const {program} = makeProgram([
{name: _('/node_modules/absolute/index.ts'), contents: 'export class Target {}'},
{
name: _('/entry.ts'),
contents: `
import * as abs from 'absolute';
let foo: abs.Target;
`,
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const targetDecl = getDeclaration(
program,
_('/node_modules/absolute/index.ts'),
'Target',
ts.isClassDeclaration,
);
const foo = getDeclaration(program, _('/entry.ts'), 'foo', ts.isVariableDeclaration);
if (
foo.type === undefined ||
!ts.isTypeReferenceNode(foo.type) ||
!ts.isQualifiedName(foo.type.typeName)
) {
return fail('Unexpected type for foo');
}
const Target = foo.type.typeName.right;
const decl = host.getDeclarationOfIdentifier(Target);
expect(decl).toEqual({
node: targetDecl,
viaModule: 'absolute',
});
});
});
describe('getExportsOfModule()', () => {
it('should handle simple exports', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
export const x = 10;
export function foo() {}
export type T = string;
export interface I {}
export enum E {}
`,
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const exportedDeclarations = host.getExportsOfModule(
program.getSourceFile(_('/entry.ts'))!,
);
expect(Array.from(exportedDeclarations!.keys())).toEqual(['foo', 'x', 'T', 'I', 'E']);
expect(Array.from(exportedDeclarations!.values()).map((v) => v.viaModule)).toEqual([
null,
null,
null,
null,
null,
]);
});
it('should handle re-exports', () => {
const {program} = makeProgram([
{name: _('/node_modules/absolute/index.ts'), contents: 'export class Target {}'},
{name: _('/local1.ts'), contents: `export {Target as AliasTarget} from 'absolute';`},
{name: _('/local2.ts'), contents: `export {AliasTarget as Target} from './local1';`},
{
name: _('/entry.ts'),
contents: `
export {Target as Target1} from 'absolute';
export {AliasTarget} from './local1';
export {Target as AliasTarget2} from './local2';
export * from 'absolute';
`,
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const exportedDeclarations = host.getExportsOfModule(
program.getSourceFile(_('/entry.ts'))!,
);
expect(Array.from(exportedDeclarations!.keys())).toEqual([
'Target1',
'AliasTarget',
'AliasTarget2',
'Target',
]);
expect(Array.from(exportedDeclarations!.values()).map((v) => v.viaModule)).toEqual([
null,
null,
null,
null,
]);
});
}); | {
"end_byte": 18248,
"start_byte": 9047,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts_18254_23125 | describe('getMembersOfClass()', () => {
it('should get string literal members of class', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
class Foo {
'string-literal-property-member' = 'my value';
}
`,
},
]);
const members = getMembers(program);
expect(members.length).toBe(1);
expectMember(members[0], 'string-literal-property-member', ClassMemberKind.Property);
});
it('should retrieve method members', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
class Foo {
myMethod(): void {
}
}
`,
},
]);
const members = getMembers(program);
expect(members.length).toBe(1);
expectMember(members[0], 'myMethod', ClassMemberKind.Method);
});
it('should retrieve constructor as member', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
class Foo {
constructor() {}
}
`,
},
]);
const members = getMembers(program);
expect(members.length).toBe(1);
expectMember(members[0], 'constructor', ClassMemberKind.Constructor);
});
it('should retrieve decorators of member', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
declare var Input;
class Foo {
@Input()
prop: string;
}
`,
},
]);
const members = getMembers(program);
expect(members.length).toBe(1);
expect(members[0].decorators).not.toBeNull();
expect(members[0].decorators![0].name).toBe('Input');
});
it('identifies static members', () => {
const {program} = makeProgram([
{
name: _('/entry.ts'),
contents: `
class Foo {
static staticMember = '';
}
`,
},
]);
const members = getMembers(program);
expect(members.length).toBe(1);
expect(members[0].isStatic).toBeTrue();
});
function getMembers(program: ts.Program) {
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
return host.getMembersOfClass(clazz);
}
function expectMember(member: ClassMember, name: string, kind: ClassMemberKind) {
expect(member.name).toEqual(name);
expect(member.kind).toEqual(kind);
}
});
});
function expectParameter(
param: CtorParameter,
name: string,
type?: string | {name: string; moduleName: string},
decorator?: string,
decoratorFrom?: string,
): void {
expect(param.name!).toEqual(name);
if (type === undefined) {
expect(param.typeValueReference).toBeNull();
} else {
if (param.typeValueReference.kind === TypeValueReferenceKind.UNAVAILABLE) {
return fail(`Expected parameter ${name} to have a typeValueReference`);
}
if (
param.typeValueReference.kind === TypeValueReferenceKind.LOCAL &&
typeof type === 'string'
) {
expect(argExpressionToString(param.typeValueReference.expression)).toEqual(type);
} else if (
param.typeValueReference.kind === TypeValueReferenceKind.IMPORTED &&
typeof type !== 'string'
) {
expect(param.typeValueReference.moduleName).toEqual(type.moduleName);
expect(param.typeValueReference.importedName).toEqual(type.name);
} else {
return fail(
`Mismatch between typeValueReference and expected type: ${param.name} / ${param.typeValueReference.kind}`,
);
}
}
if (decorator !== undefined) {
expect(param.decorators).not.toBeNull();
expect(param.decorators!.length).toBeGreaterThan(0);
expect(
param.decorators!.some(
(dec) =>
dec.name === decorator && dec.import !== null && dec.import.from === decoratorFrom,
),
).toBe(true);
}
}
function argExpressionToString(name: ts.Node | null): string {
if (name == null) {
throw new Error("'name' argument can't be null");
}
if (ts.isIdentifier(name)) {
return name.text;
} else if (ts.isPropertyAccessExpression(name)) {
return `${argExpressionToString(name.expression)}.${name.name.text}`;
} else {
throw new Error(`Unexpected node in arg expression: ${ts.SyntaxKind[name.kind]}.`);
}
}
}); | {
"end_byte": 23125,
"start_byte": 18254,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/test/ts_host_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/test/BUILD.bazel_0_665 | 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-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//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": 665,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/util.ts_0_1567 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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, ClassMemberAccessLevel} from './host';
export function isNamedClassDeclaration(
node: ts.Node,
): node is ClassDeclaration<ts.ClassDeclaration> {
return ts.isClassDeclaration(node) && isIdentifier(node.name);
}
export function isNamedFunctionDeclaration(
node: ts.Node,
): node is ClassDeclaration<ts.FunctionDeclaration> {
return ts.isFunctionDeclaration(node) && isIdentifier(node.name);
}
export function isNamedVariableDeclaration(
node: ts.Node,
): node is ClassDeclaration<ts.VariableDeclaration> {
return ts.isVariableDeclaration(node) && isIdentifier(node.name);
}
function isIdentifier(node: ts.Node | undefined): node is ts.Identifier {
return node !== undefined && ts.isIdentifier(node);
}
/**
* Converts the given class member access level to a string.
* Useful fo error messages.
*/
export function classMemberAccessLevelToString(level: ClassMemberAccessLevel): string {
switch (level) {
case ClassMemberAccessLevel.EcmaScriptPrivate:
return 'ES private';
case ClassMemberAccessLevel.Private:
return 'private';
case ClassMemberAccessLevel.Protected:
return 'protected';
case ClassMemberAccessLevel.PublicReadonly:
return 'public readonly';
case ClassMemberAccessLevel.PublicWritable:
default:
return 'public';
}
}
| {
"end_byte": 1567,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts_0_762 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {
AmbientImport,
ClassDeclaration,
ClassMember,
ClassMemberAccessLevel,
ClassMemberKind,
CtorParameter,
Declaration,
DeclarationNode,
Decorator,
FunctionDefinition,
Import,
isDecoratorIdentifier,
ReflectionHost,
} from './host';
import {typeToValue} from './type_to_value';
import {isNamedClassDeclaration} from './util';
/**
* reflector.ts implements static reflection of declarations using the TypeScript `ts.TypeChecker`.
*/
export class TypeScriptReflectionHost implements ReflectionHost | {
"end_byte": 762,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts_763_9491 | {
constructor(
protected checker: ts.TypeChecker,
private readonly isLocalCompilation = false,
) {}
getDecoratorsOfDeclaration(declaration: DeclarationNode): Decorator[] | null {
const decorators = ts.canHaveDecorators(declaration)
? ts.getDecorators(declaration)
: undefined;
return decorators !== undefined && decorators.length
? decorators
.map((decorator) => this._reflectDecorator(decorator))
.filter((dec): dec is Decorator => dec !== null)
: null;
}
getMembersOfClass(clazz: ClassDeclaration): ClassMember[] {
const tsClazz = castDeclarationToClassOrDie(clazz);
return tsClazz.members
.map((member) => {
const result = reflectClassMember(member);
if (result === null) {
return null;
}
return {
...result,
decorators: this.getDecoratorsOfDeclaration(member),
};
})
.filter((member): member is NonNullable<typeof member> => member !== null);
}
getConstructorParameters(clazz: ClassDeclaration): CtorParameter[] | null {
const tsClazz = castDeclarationToClassOrDie(clazz);
const isDeclaration = tsClazz.getSourceFile().isDeclarationFile;
// For non-declaration files, we want to find the constructor with a `body`. The constructors
// without a `body` are overloads whereas we want the implementation since it's the one that'll
// be executed and which can have decorators. For declaration files, we take the first one that
// we get.
const ctor = tsClazz.members.find(
(member): member is ts.ConstructorDeclaration =>
ts.isConstructorDeclaration(member) && (isDeclaration || member.body !== undefined),
);
if (ctor === undefined) {
return null;
}
return ctor.parameters.map((node) => {
// The name of the parameter is easy.
const name = parameterName(node.name);
const decorators = this.getDecoratorsOfDeclaration(node);
// It may or may not be possible to write an expression that refers to the value side of the
// type named for the parameter.
let originalTypeNode = node.type || null;
let typeNode = originalTypeNode;
// Check if we are dealing with a simple nullable union type e.g. `foo: Foo|null`
// and extract the type. More complex union types e.g. `foo: Foo|Bar` are not supported.
// We also don't need to support `foo: Foo|undefined` because Angular's DI injects `null` for
// optional tokes that don't have providers.
if (typeNode && ts.isUnionTypeNode(typeNode)) {
let childTypeNodes = typeNode.types.filter(
(childTypeNode) =>
!(
ts.isLiteralTypeNode(childTypeNode) &&
childTypeNode.literal.kind === ts.SyntaxKind.NullKeyword
),
);
if (childTypeNodes.length === 1) {
typeNode = childTypeNodes[0];
}
}
const typeValueReference = typeToValue(typeNode, this.checker, this.isLocalCompilation);
return {
name,
nameNode: node.name,
typeValueReference,
typeNode: originalTypeNode,
decorators,
};
});
}
getImportOfIdentifier(id: ts.Identifier): Import | null {
const directImport = this.getDirectImportOfIdentifier(id);
if (directImport !== null) {
return directImport;
} else if (ts.isQualifiedName(id.parent) && id.parent.right === id) {
return this.getImportOfNamespacedIdentifier(id, getQualifiedNameRoot(id.parent));
} else if (ts.isPropertyAccessExpression(id.parent) && id.parent.name === id) {
return this.getImportOfNamespacedIdentifier(id, getFarLeftIdentifier(id.parent));
} else {
return null;
}
}
getExportsOfModule(node: ts.Node): Map<string, Declaration> | null {
// In TypeScript code, modules are only ts.SourceFiles. Throw if the node isn't a module.
if (!ts.isSourceFile(node)) {
throw new Error(`getExportsOfModule() called on non-SourceFile in TS code`);
}
// Reflect the module to a Symbol, and use getExportsOfModule() to get a list of exported
// Symbols.
const symbol = this.checker.getSymbolAtLocation(node);
if (symbol === undefined) {
return null;
}
const map = new Map<string, Declaration>();
this.checker.getExportsOfModule(symbol).forEach((exportSymbol) => {
// Map each exported Symbol to a Declaration and add it to the map.
const decl = this.getDeclarationOfSymbol(exportSymbol, null);
if (decl !== null) {
map.set(exportSymbol.name, decl);
}
});
return map;
}
isClass(node: ts.Node): node is ClassDeclaration {
// For our purposes, classes are "named" ts.ClassDeclarations;
// (`node.name` can be undefined in unnamed default exports: `default export class { ... }`).
return isNamedClassDeclaration(node);
}
hasBaseClass(clazz: ClassDeclaration): boolean {
return this.getBaseClassExpression(clazz) !== null;
}
getBaseClassExpression(clazz: ClassDeclaration): ts.Expression | null {
if (
!(ts.isClassDeclaration(clazz) || ts.isClassExpression(clazz)) ||
clazz.heritageClauses === undefined
) {
return null;
}
const extendsClause = clazz.heritageClauses.find(
(clause) => clause.token === ts.SyntaxKind.ExtendsKeyword,
);
if (extendsClause === undefined) {
return null;
}
const extendsType = extendsClause.types[0];
if (extendsType === undefined) {
return null;
}
return extendsType.expression;
}
getDeclarationOfIdentifier(id: ts.Identifier): Declaration | null {
// Resolve the identifier to a Symbol, and return the declaration of that.
let symbol: ts.Symbol | undefined = this.checker.getSymbolAtLocation(id);
if (symbol === undefined) {
return null;
}
return this.getDeclarationOfSymbol(symbol, id);
}
getDefinitionOfFunction(node: ts.Node): FunctionDefinition | null {
if (
!ts.isFunctionDeclaration(node) &&
!ts.isMethodDeclaration(node) &&
!ts.isFunctionExpression(node) &&
!ts.isArrowFunction(node)
) {
return null;
}
let body: ts.Statement[] | null = null;
if (node.body !== undefined) {
// The body might be an expression if the node is an arrow function.
body = ts.isBlock(node.body)
? Array.from(node.body.statements)
: [ts.factory.createReturnStatement(node.body)];
}
const type = this.checker.getTypeAtLocation(node);
const signatures = this.checker.getSignaturesOfType(type, ts.SignatureKind.Call);
return {
node,
body,
signatureCount: signatures.length,
typeParameters: node.typeParameters === undefined ? null : Array.from(node.typeParameters),
parameters: node.parameters.map((param) => {
const name = parameterName(param.name);
const initializer = param.initializer || null;
return {name, node: param, initializer, type: param.type || null};
}),
};
}
getGenericArityOfClass(clazz: ClassDeclaration): number | null {
if (!ts.isClassDeclaration(clazz)) {
return null;
}
return clazz.typeParameters !== undefined ? clazz.typeParameters.length : 0;
}
getVariableValue(declaration: ts.VariableDeclaration): ts.Expression | null {
return declaration.initializer || null;
}
isStaticallyExported(decl: ts.Node): boolean {
// First check if there's an `export` modifier directly on the declaration.
let topLevel = decl;
if (ts.isVariableDeclaration(decl) && ts.isVariableDeclarationList(decl.parent)) {
topLevel = decl.parent.parent;
}
const modifiers = ts.canHaveModifiers(topLevel) ? ts.getModifiers(topLevel) : undefined;
if (
modifiers !== undefined &&
modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
) {
// The node is part of a declaration that's directly exported.
return true;
}
// If `topLevel` is not directly exported via a modifier, then it might be indirectly exported,
// e.g.:
//
// class Foo {}
// export {Foo};
//
// The only way to check this is to look at the module level for exports of the class. As a
// performance optimization, this check is only performed if the class is actually declared at
// the top level of the file and thus eligible for exporting in the first place.
if (topLevel.parent === undefined || !ts.isSourceFile(topLevel.parent)) {
return false;
}
const localExports = this.getLocalExportedDeclarationsOfSourceFile(decl.getSourceFile());
return localExports.has(decl as ts.Declaration);
} | {
"end_byte": 9491,
"start_byte": 763,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts_9495_18354 | protected getDirectImportOfIdentifier(id: ts.Identifier): Import | null {
const symbol = this.checker.getSymbolAtLocation(id);
if (
symbol === undefined ||
symbol.declarations === undefined ||
symbol.declarations.length !== 1
) {
return null;
}
const decl = symbol.declarations[0];
const importDecl = getContainingImportDeclaration(decl);
// Ignore declarations that are defined locally (not imported).
if (importDecl === null) {
return null;
}
// The module specifier is guaranteed to be a string literal, so this should always pass.
if (!ts.isStringLiteral(importDecl.moduleSpecifier)) {
// Not allowed to happen in TypeScript ASTs.
return null;
}
return {
from: importDecl.moduleSpecifier.text,
name: getExportedName(decl, id),
node: importDecl,
};
}
/**
* Try to get the import info for this identifier as though it is a namespaced import.
*
* For example, if the identifier is the `Directive` part of a qualified type chain like:
*
* ```
* core.Directive
* ```
*
* then it might be that `core` is a namespace import such as:
*
* ```
* import * as core from 'tslib';
* ```
*
* @param id the TypeScript identifier to find the import info for.
* @returns The import info if this is a namespaced import or `null`.
*/
protected getImportOfNamespacedIdentifier(
id: ts.Identifier,
namespaceIdentifier: ts.Identifier | null,
): Import | null {
if (namespaceIdentifier === null) {
return null;
}
const namespaceSymbol = this.checker.getSymbolAtLocation(namespaceIdentifier);
if (!namespaceSymbol || namespaceSymbol.declarations === undefined) {
return null;
}
const declaration =
namespaceSymbol.declarations.length === 1 ? namespaceSymbol.declarations[0] : null;
if (!declaration) {
return null;
}
const namespaceDeclaration = ts.isNamespaceImport(declaration) ? declaration : null;
if (!namespaceDeclaration) {
return null;
}
const importDeclaration = namespaceDeclaration.parent.parent;
if (
!ts.isImportDeclaration(importDeclaration) ||
!ts.isStringLiteral(importDeclaration.moduleSpecifier)
) {
// Should not happen as this would be invalid TypesScript
return null;
}
return {
from: importDeclaration.moduleSpecifier.text,
name: id.text,
node: importDeclaration,
};
}
/**
* Resolve a `ts.Symbol` to its declaration, keeping track of the `viaModule` along the way.
*/
protected getDeclarationOfSymbol(
symbol: ts.Symbol,
originalId: ts.Identifier | null,
): Declaration | null {
// If the symbol points to a ShorthandPropertyAssignment, resolve it.
let valueDeclaration: ts.Declaration | undefined = undefined;
if (symbol.valueDeclaration !== undefined) {
valueDeclaration = symbol.valueDeclaration;
} else if (symbol.declarations !== undefined && symbol.declarations.length > 0) {
valueDeclaration = symbol.declarations[0];
}
if (valueDeclaration !== undefined && ts.isShorthandPropertyAssignment(valueDeclaration)) {
const shorthandSymbol = this.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
if (shorthandSymbol === undefined) {
return null;
}
return this.getDeclarationOfSymbol(shorthandSymbol, originalId);
} else if (valueDeclaration !== undefined && ts.isExportSpecifier(valueDeclaration)) {
const targetSymbol = this.checker.getExportSpecifierLocalTargetSymbol(valueDeclaration);
if (targetSymbol === undefined) {
return null;
}
return this.getDeclarationOfSymbol(targetSymbol, originalId);
}
const importInfo = originalId && this.getImportOfIdentifier(originalId);
// Now, resolve the Symbol to its declaration by following any and all aliases.
while (symbol.flags & ts.SymbolFlags.Alias) {
symbol = this.checker.getAliasedSymbol(symbol);
}
// Look at the resolved Symbol's declarations and pick one of them to return. Value declarations
// are given precedence over type declarations.
if (symbol.valueDeclaration !== undefined) {
return {
node: symbol.valueDeclaration,
viaModule: this._viaModule(symbol.valueDeclaration, originalId, importInfo),
};
} else if (symbol.declarations !== undefined && symbol.declarations.length > 0) {
return {
node: symbol.declarations[0],
viaModule: this._viaModule(symbol.declarations[0], originalId, importInfo),
};
} else {
return null;
}
}
private _reflectDecorator(node: ts.Decorator): Decorator | null {
// Attempt to resolve the decorator expression into a reference to a concrete Identifier. The
// expression may contain a call to a function which returns the decorator function, in which
// case we want to return the arguments.
let decoratorExpr: ts.Expression = node.expression;
let args: ts.Expression[] | null = null;
// Check for call expressions.
if (ts.isCallExpression(decoratorExpr)) {
args = Array.from(decoratorExpr.arguments);
decoratorExpr = decoratorExpr.expression;
}
// The final resolved decorator should be a `ts.Identifier` - if it's not, then something is
// wrong and the decorator can't be resolved statically.
if (!isDecoratorIdentifier(decoratorExpr)) {
return null;
}
const decoratorIdentifier = ts.isIdentifier(decoratorExpr) ? decoratorExpr : decoratorExpr.name;
const importDecl = this.getImportOfIdentifier(decoratorIdentifier);
return {
name: decoratorIdentifier.text,
identifier: decoratorExpr,
import: importDecl,
node,
args,
};
}
/**
* Get the set of declarations declared in `file` which are exported.
*/
private getLocalExportedDeclarationsOfSourceFile(file: ts.SourceFile): Set<ts.Declaration> {
const cacheSf: SourceFileWithCachedExports = file as SourceFileWithCachedExports;
if (cacheSf[LocalExportedDeclarations] !== undefined) {
// TS does not currently narrow symbol-keyed fields, hence the non-null assert is needed.
return cacheSf[LocalExportedDeclarations]!;
}
const exportSet = new Set<ts.Declaration>();
cacheSf[LocalExportedDeclarations] = exportSet;
const sfSymbol = this.checker.getSymbolAtLocation(cacheSf);
if (sfSymbol === undefined || sfSymbol.exports === undefined) {
return exportSet;
}
// Scan the exported symbol of the `ts.SourceFile` for the original `symbol` of the class
// declaration.
//
// Note: when checking multiple classes declared in the same file, this repeats some operations.
// In theory, this could be expensive if run in the context of a massive input file. If
// performance does become an issue here, it should be possible to create a `Set<>`
// Unfortunately, `ts.Iterator` doesn't implement the iterator protocol, so iteration here is
// done manually.
const iter = sfSymbol.exports.values();
let item = iter.next();
while (item.done !== true) {
let exportedSymbol = item.value;
// If this exported symbol comes from an `export {Foo}` statement, then the symbol is actually
// for the export declaration, not the original declaration. Such a symbol will be an alias,
// so unwrap aliasing if necessary.
if (exportedSymbol.flags & ts.SymbolFlags.Alias) {
exportedSymbol = this.checker.getAliasedSymbol(exportedSymbol);
}
if (
exportedSymbol.valueDeclaration !== undefined &&
exportedSymbol.valueDeclaration.getSourceFile() === file
) {
exportSet.add(exportedSymbol.valueDeclaration);
}
item = iter.next();
}
return exportSet;
}
private _viaModule(
declaration: ts.Declaration,
originalId: ts.Identifier | null,
importInfo: Import | null,
): string | AmbientImport | null {
if (
importInfo === null &&
originalId !== null &&
declaration.getSourceFile() !== originalId.getSourceFile()
) {
return AmbientImport;
}
return importInfo !== null && importInfo.from !== null && !importInfo.from.startsWith('.')
? importInfo.from
: null;
}
}
export function reflectNameOfDeclaration(decl: ts.Declaration): string | null {
const id = reflectIdentifierOfDeclaration(decl);
return (id && id.text) || null;
}
export function reflectIdentifierOfDeclaration(decl: ts.Declaration): ts.Identifier | null {
if (ts.isClassDeclaration(decl) || ts.isFunctionDeclaration(decl)) {
return decl.name || null;
} else if (ts.isVariableDeclaration(decl)) {
if (ts.isIdentifier(decl.name)) {
return decl.name;
}
}
return null;
} | {
"end_byte": 18354,
"start_byte": 9495,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts_18356_26682 | export function reflectTypeEntityToDeclaration(
type: ts.EntityName,
checker: ts.TypeChecker,
): {node: ts.Declaration; from: string | null} {
let realSymbol = checker.getSymbolAtLocation(type);
if (realSymbol === undefined) {
throw new Error(`Cannot resolve type entity ${type.getText()} to symbol`);
}
while (realSymbol.flags & ts.SymbolFlags.Alias) {
realSymbol = checker.getAliasedSymbol(realSymbol);
}
let node: ts.Declaration | null = null;
if (realSymbol.valueDeclaration !== undefined) {
node = realSymbol.valueDeclaration;
} else if (realSymbol.declarations !== undefined && realSymbol.declarations.length === 1) {
node = realSymbol.declarations[0];
} else {
throw new Error(`Cannot resolve type entity symbol to declaration`);
}
if (ts.isQualifiedName(type)) {
if (!ts.isIdentifier(type.left)) {
throw new Error(`Cannot handle qualified name with non-identifier lhs`);
}
const symbol = checker.getSymbolAtLocation(type.left);
if (
symbol === undefined ||
symbol.declarations === undefined ||
symbol.declarations.length !== 1
) {
throw new Error(`Cannot resolve qualified type entity lhs to symbol`);
}
const decl = symbol.declarations[0];
if (ts.isNamespaceImport(decl)) {
const clause = decl.parent!;
const importDecl = clause.parent!;
if (!ts.isStringLiteral(importDecl.moduleSpecifier)) {
throw new Error(`Module specifier is not a string`);
}
return {node, from: importDecl.moduleSpecifier.text};
} else if (ts.isModuleDeclaration(decl)) {
return {node, from: null};
} else {
throw new Error(`Unknown import type?`);
}
} else {
return {node, from: null};
}
}
export function filterToMembersWithDecorator(
members: ClassMember[],
name: string,
module?: string,
): {member: ClassMember; decorators: Decorator[]}[] {
return members
.filter((member) => !member.isStatic)
.map((member) => {
if (member.decorators === null) {
return null;
}
const decorators = member.decorators.filter((dec) => {
if (dec.import !== null) {
return dec.import.name === name && (module === undefined || dec.import.from === module);
} else {
return dec.name === name && module === undefined;
}
});
if (decorators.length === 0) {
return null;
}
return {member, decorators};
})
.filter((value): value is {member: ClassMember; decorators: Decorator[]} => value !== null);
}
function extractModifiersOfMember(node: ts.ClassElement & ts.HasModifiers): {
accessLevel: ClassMemberAccessLevel;
isStatic: boolean;
} {
const modifiers = ts.getModifiers(node);
let isStatic = false;
let isReadonly = false;
let accessLevel = ClassMemberAccessLevel.PublicWritable;
if (modifiers !== undefined) {
for (const modifier of modifiers) {
switch (modifier.kind) {
case ts.SyntaxKind.StaticKeyword:
isStatic = true;
break;
case ts.SyntaxKind.PrivateKeyword:
accessLevel = ClassMemberAccessLevel.Private;
break;
case ts.SyntaxKind.ProtectedKeyword:
accessLevel = ClassMemberAccessLevel.Protected;
break;
case ts.SyntaxKind.ReadonlyKeyword:
isReadonly = true;
break;
}
}
}
if (isReadonly && accessLevel === ClassMemberAccessLevel.PublicWritable) {
accessLevel = ClassMemberAccessLevel.PublicReadonly;
}
if (node.name !== undefined && ts.isPrivateIdentifier(node.name)) {
accessLevel = ClassMemberAccessLevel.EcmaScriptPrivate;
}
return {accessLevel, isStatic};
}
/**
* Reflects a class element and returns static information about the
* class member.
*
* Note: Decorator information is not included in this helper as it relies
* on type checking to resolve originating import.
*/
export function reflectClassMember(node: ts.ClassElement): Omit<ClassMember, 'decorators'> | null {
let kind: ClassMemberKind | null = null;
let value: ts.Expression | null = null;
let name: string | null = null;
let nameNode: ts.Identifier | ts.PrivateIdentifier | ts.StringLiteral | null = null;
if (ts.isPropertyDeclaration(node)) {
kind = ClassMemberKind.Property;
value = node.initializer || null;
} else if (ts.isGetAccessorDeclaration(node)) {
kind = ClassMemberKind.Getter;
} else if (ts.isSetAccessorDeclaration(node)) {
kind = ClassMemberKind.Setter;
} else if (ts.isMethodDeclaration(node)) {
kind = ClassMemberKind.Method;
} else if (ts.isConstructorDeclaration(node)) {
kind = ClassMemberKind.Constructor;
} else {
return null;
}
if (ts.isConstructorDeclaration(node)) {
name = 'constructor';
} else if (ts.isIdentifier(node.name)) {
name = node.name.text;
nameNode = node.name;
} else if (ts.isStringLiteral(node.name)) {
name = node.name.text;
nameNode = node.name;
} else if (ts.isPrivateIdentifier(node.name)) {
name = node.name.text;
nameNode = node.name;
} else {
return null;
}
const {accessLevel, isStatic} = extractModifiersOfMember(node);
return {
node,
implementation: node,
kind,
type: node.type || null,
accessLevel,
name,
nameNode,
value,
isStatic,
};
}
export function findMember(
members: ClassMember[],
name: string,
isStatic: boolean = false,
): ClassMember | null {
return members.find((member) => member.isStatic === isStatic && member.name === name) || null;
}
export function reflectObjectLiteral(node: ts.ObjectLiteralExpression): Map<string, ts.Expression> {
const map = new Map<string, ts.Expression>();
node.properties.forEach((prop) => {
if (ts.isPropertyAssignment(prop)) {
const name = propertyNameToString(prop.name);
if (name === null) {
return;
}
map.set(name, prop.initializer);
} else if (ts.isShorthandPropertyAssignment(prop)) {
map.set(prop.name.text, prop.name);
} else {
return;
}
});
return map;
}
function castDeclarationToClassOrDie(
declaration: ClassDeclaration,
): ClassDeclaration<ts.ClassDeclaration> {
if (!ts.isClassDeclaration(declaration)) {
throw new Error(
`Reflecting on a ${ts.SyntaxKind[declaration.kind]} instead of a ClassDeclaration.`,
);
}
return declaration;
}
function parameterName(name: ts.BindingName): string | null {
if (ts.isIdentifier(name)) {
return name.text;
} else {
return null;
}
}
function propertyNameToString(node: ts.PropertyName): string | null {
if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) {
return node.text;
} else {
return null;
}
}
/**
* Compute the left most identifier in a qualified type chain. E.g. the `a` of `a.b.c.SomeType`.
* @param qualifiedName The starting property access expression from which we want to compute
* the left most identifier.
* @returns the left most identifier in the chain or `null` if it is not an identifier.
*/
function getQualifiedNameRoot(qualifiedName: ts.QualifiedName): ts.Identifier | null {
while (ts.isQualifiedName(qualifiedName.left)) {
qualifiedName = qualifiedName.left;
}
return ts.isIdentifier(qualifiedName.left) ? qualifiedName.left : null;
}
/**
* Compute the left most identifier in a property access chain. E.g. the `a` of `a.b.c.d`.
* @param propertyAccess The starting property access expression from which we want to compute
* the left most identifier.
* @returns the left most identifier in the chain or `null` if it is not an identifier.
*/
function getFarLeftIdentifier(propertyAccess: ts.PropertyAccessExpression): ts.Identifier | null {
while (ts.isPropertyAccessExpression(propertyAccess.expression)) {
propertyAccess = propertyAccess.expression;
}
return ts.isIdentifier(propertyAccess.expression) ? propertyAccess.expression : null;
}
/**
* Gets the closest ancestor `ImportDeclaration` to a node.
*/
export function getContainingImportDeclaration(node: ts.Node): ts.ImportDeclaration | null {
let parent = node.parent;
while (parent && !ts.isSourceFile(parent)) {
if (ts.isImportDeclaration(parent)) {
return parent;
}
parent = parent.parent;
}
return null;
} | {
"end_byte": 26682,
"start_byte": 18356,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts_26684_28037 | /**
* Compute the name by which the `decl` was exported, not imported.
* If no such declaration can be found (e.g. it is a namespace import)
* then fallback to the `originalId`.
*/
function getExportedName(decl: ts.Declaration, originalId: ts.Identifier): string {
return ts.isImportSpecifier(decl)
? (decl.propertyName !== undefined ? decl.propertyName : decl.name).text
: originalId.text;
}
const LocalExportedDeclarations = Symbol('LocalExportedDeclarations');
/**
* A `ts.SourceFile` expando which includes a cached `Set` of local `ts.Declaration`s that are
* exported either directly (`export class ...`) or indirectly (via `export {...}`).
*
* This cache does not cause memory leaks as:
*
* 1. The only references cached here are local to the `ts.SourceFile`, and thus also available in
* `this.statements`.
*
* 2. The only way this `Set` could change is if the source file itself was changed, which would
* invalidate the entire `ts.SourceFile` object in favor of a new version. Thus, changing the
* source file also invalidates this cache.
*/
interface SourceFileWithCachedExports extends ts.SourceFile {
/**
* Cached `Set` of `ts.Declaration`s which are locally declared in this file and are exported
* either directly or indirectly.
*/
[LocalExportedDeclarations]?: Set<ts.Declaration>;
} | {
"end_byte": 28037,
"start_byte": 26684,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/typescript.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/host.ts_0_7927 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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';
/**
* Metadata extracted from an instance of a decorator on another declaration.
*/
export interface Decorator {
/**
* Name by which the decorator was invoked in the user's code.
*
* This is distinct from the name by which the decorator was imported (though in practice they
* will usually be the same).
*/
name: string;
/**
* Identifier which refers to the decorator in the user's code.
*/
identifier: DecoratorIdentifier;
/**
* `Import` by which the decorator was brought into the module in which it was invoked, or `null`
* if the decorator was declared in the same module and not imported.
*/
import: Import | null;
/**
* TypeScript reference to the decorator itself.
*/
node: ts.Node;
/**
* Arguments of the invocation of the decorator, if the decorator is invoked, or `null`
* otherwise.
*/
args: ts.Expression[] | null;
}
/**
* A decorator is identified by either a simple identifier (e.g. `Decorator`) or, in some cases,
* a namespaced property access (e.g. `core.Decorator`).
*/
export type DecoratorIdentifier = ts.Identifier | NamespacedIdentifier;
export type NamespacedIdentifier = ts.PropertyAccessExpression & {
expression: ts.Identifier;
name: ts.Identifier;
};
export function isDecoratorIdentifier(exp: ts.Expression): exp is DecoratorIdentifier {
return (
ts.isIdentifier(exp) ||
(ts.isPropertyAccessExpression(exp) &&
ts.isIdentifier(exp.expression) &&
ts.isIdentifier(exp.name))
);
}
/**
* The `ts.Declaration` of a "class".
*
* Classes are represented differently in different code formats:
* - In TS code, they are typically defined using the `class` keyword.
* - In ES2015 code, they are usually defined using the `class` keyword, but they can also be
* variable declarations, which are initialized to a class expression (e.g.
* `let Foo = Foo1 = class Foo {}`).
* - In ES5 code, they are typically defined as variable declarations being assigned the return
* value of an IIFE. The actual "class" is implemented as a constructor function inside the IIFE,
* but the outer variable declaration represents the "class" to the rest of the program.
*
* For `ReflectionHost` purposes, a class declaration should always have a `name` identifier,
* because we need to be able to reference it in other parts of the program.
*/
export type ClassDeclaration<T extends DeclarationNode = DeclarationNode> = T & {
name: ts.Identifier;
};
/**
* An enumeration of possible kinds of class members.
*/
export enum ClassMemberKind {
Constructor,
Getter,
Setter,
Property,
Method,
}
/** Possible access levels of a class member. */
export enum ClassMemberAccessLevel {
PublicWritable,
PublicReadonly,
Protected,
Private,
EcmaScriptPrivate,
}
/**
* A member of a class, such as a property, method, or constructor.
*/
export interface ClassMember {
/**
* TypeScript reference to the class member itself, or null if it is not applicable.
*/
node: ts.Node | null;
/**
* Indication of which type of member this is (property, method, etc).
*/
kind: ClassMemberKind;
/** Access level describing the class member modifiers. */
accessLevel: ClassMemberAccessLevel;
/**
* TypeScript `ts.TypeNode` representing the type of the member, or `null` if not present or
* applicable.
*/
type: ts.TypeNode | null;
/**
* Name of the class member.
*/
name: string;
/**
* TypeScript `ts.Identifier`, `ts.PrivateIdentifier`, or `ts.StringLiteral` representing the
* name of the member, or `null` if no such node is present.
*
* The `nameNode` is useful in writing references to this member that will be correctly source-
* mapped back to the original file.
*/
nameNode: ts.Identifier | ts.PrivateIdentifier | ts.StringLiteral | null;
/**
* TypeScript `ts.Expression` which represents the value of the member.
*
* If the member is a property, this will be the property initializer if there is one, or null
* otherwise.
*/
value: ts.Expression | null;
/**
* TypeScript `ts.Declaration` which represents the implementation of the member.
*
* In TypeScript code this is identical to the node, but in downleveled code this should always be
* the Declaration which actually represents the member's runtime value.
*
* For example, the TS code:
*
* ```
* class Clazz {
* static get property(): string {
* return 'value';
* }
* }
* ```
*
* Downlevels to:
*
* ```
* var Clazz = (function () {
* function Clazz() {
* }
* Object.defineProperty(Clazz, "property", {
* get: function () {
* return 'value';
* },
* enumerable: true,
* configurable: true
* });
* return Clazz;
* }());
* ```
*
* In this example, for the property "property", the node would be the entire
* Object.defineProperty ExpressionStatement, but the implementation would be this
* FunctionDeclaration:
*
* ```
* function () {
* return 'value';
* },
* ```
*/
implementation: ts.Declaration | null;
/**
* Whether the member is static or not.
*/
isStatic: boolean;
/**
* Any `Decorator`s which are present on the member, or `null` if none are present.
*/
decorators: Decorator[] | null;
}
export const enum TypeValueReferenceKind {
LOCAL,
IMPORTED,
UNAVAILABLE,
}
/**
* A type reference that refers to any type via a `ts.Expression` that's valid within the local file
* where the type was referenced.
*/
export interface LocalTypeValueReference {
kind: TypeValueReferenceKind.LOCAL;
/**
* The synthesized expression to reference the type in a value position.
*/
expression: ts.Expression;
/**
* If the type originates from a default import, the import statement is captured here to be able
* to track its usages, preventing the import from being elided if it was originally only used in
* a type-position. See `DefaultImportTracker` for details.
*/
defaultImportStatement: ts.ImportDeclaration | null;
}
/**
* A reference that refers to a type that was imported, and gives the symbol `name` and the
* `moduleName` of the import. Note that this `moduleName` may be a relative path, and thus is
* likely only valid within the context of the file which contained the original type reference.
*/
export interface ImportedTypeValueReference {
kind: TypeValueReferenceKind.IMPORTED;
/**
* The module specifier from which the `importedName` symbol should be imported.
*/
moduleName: string;
/**
* The name of the top-level symbol that is imported from `moduleName`. If `nestedPath` is also
* present, a nested object is being referenced from the top-level symbol.
*/
importedName: string;
/**
* If present, represents the symbol names that are referenced from the top-level import.
* When `null` or empty, the `importedName` itself is the symbol being referenced.
*/
nestedPath: string[] | null;
// This field can be null in local compilation mode when resolving is not possible.
valueDeclaration: DeclarationNode | null;
}
/**
* A representation for a type value reference that is used when no value is available. This can
* occur due to various reasons, which is indicated in the `reason` field.
*/
export interface UnavailableTypeValueReference {
kind: TypeValueReferenceKind.UNAVAILABLE;
/**
* The reason why no value reference could be determined for a type.
*/
reason: UnavailableValue;
}
/**
* The various reasons why the compiler may be unable to synthesize a value from a type reference.
*/ | {
"end_byte": 7927,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/host.ts_7928_15192 | export const enum ValueUnavailableKind {
/**
* No type node was available.
*/
MISSING_TYPE,
/**
* The type does not have a value declaration, e.g. an interface.
*/
NO_VALUE_DECLARATION,
/**
* The type is imported using a type-only imports, so it is not suitable to be used in a
* value-position.
*/
TYPE_ONLY_IMPORT,
/**
* The type reference could not be resolved to a declaration.
*/
UNKNOWN_REFERENCE,
/**
* The type corresponds with a namespace.
*/
NAMESPACE,
/**
* The type is not supported in the compiler, for example union types.
*/
UNSUPPORTED,
}
export interface UnsupportedType {
kind: ValueUnavailableKind.UNSUPPORTED;
typeNode: ts.TypeNode;
}
export interface NoValueDeclaration {
kind: ValueUnavailableKind.NO_VALUE_DECLARATION;
typeNode: ts.TypeNode;
decl: ts.Declaration | null;
}
export interface TypeOnlyImport {
kind: ValueUnavailableKind.TYPE_ONLY_IMPORT;
typeNode: ts.TypeNode;
node: ts.ImportClause | ts.ImportSpecifier;
}
export interface NamespaceImport {
kind: ValueUnavailableKind.NAMESPACE;
typeNode: ts.TypeNode;
importClause: ts.ImportClause;
}
export interface UnknownReference {
kind: ValueUnavailableKind.UNKNOWN_REFERENCE;
typeNode: ts.TypeNode;
}
export interface MissingType {
kind: ValueUnavailableKind.MISSING_TYPE;
}
/**
* The various reasons why a type node may not be referred to as a value.
*/
export type UnavailableValue =
| UnsupportedType
| NoValueDeclaration
| TypeOnlyImport
| NamespaceImport
| UnknownReference
| MissingType;
/**
* A reference to a value that originated from a type position.
*
* For example, a constructor parameter could be declared as `foo: Foo`. A `TypeValueReference`
* extracted from this would refer to the value of the class `Foo` (assuming it was actually a
* type).
*
* See the individual types for additional information.
*/
export type TypeValueReference =
| LocalTypeValueReference
| ImportedTypeValueReference
| UnavailableTypeValueReference;
/**
* A parameter to a constructor.
*/
export interface CtorParameter {
/**
* Name of the parameter, if available.
*
* Some parameters don't have a simple string name (for example, parameters which are destructured
* into multiple variables). In these cases, `name` can be `null`.
*/
name: string | null;
/**
* TypeScript `ts.BindingName` representing the name of the parameter.
*
* The `nameNode` is useful in writing references to this member that will be correctly source-
* mapped back to the original file.
*/
nameNode: ts.BindingName;
/**
* Reference to the value of the parameter's type annotation, if it's possible to refer to the
* parameter's type as a value.
*
* This can either be a reference to a local value, a reference to an imported value, or no
* value if no is present or cannot be represented as an expression.
*/
typeValueReference: TypeValueReference;
/**
* TypeScript `ts.TypeNode` representing the type node found in the type position.
*
* This field can be used for diagnostics reporting if `typeValueReference` is `null`.
*
* Can be null, if the param has no type declared.
*/
typeNode: ts.TypeNode | null;
/**
* Any `Decorator`s which are present on the parameter, or `null` if none are present.
*/
decorators: Decorator[] | null;
}
/**
* Definition of a function or method, including its body if present and any parameters.
*
* In TypeScript code this metadata will be a simple reflection of the declarations in the node
* itself. In ES5 code this can be more complicated, as the default values for parameters may
* be extracted from certain body statements.
*/
export interface FunctionDefinition {
/**
* A reference to the node which declares the function.
*/
node:
| ts.MethodDeclaration
| ts.FunctionDeclaration
| ts.FunctionExpression
| ts.VariableDeclaration
| ts.ArrowFunction;
/**
* Statements of the function body, if a body is present, or null if no body is present or the
* function is identified to represent a tslib helper function, in which case `helper` will
* indicate which helper this function represents.
*
* This list may have been filtered to exclude statements which perform parameter default value
* initialization.
*/
body: ts.Statement[] | null;
/**
* Metadata regarding the function's parameters, including possible default value expressions.
*/
parameters: Parameter[];
/**
* Generic type parameters of the function.
*/
typeParameters: ts.TypeParameterDeclaration[] | null;
/**
* Number of known signatures of the function.
*/
signatureCount: number;
}
/**
* A parameter to a function or method.
*/
export interface Parameter {
/**
* Name of the parameter, if available.
*/
name: string | null;
/**
* Declaration which created this parameter.
*/
node: ts.ParameterDeclaration;
/**
* Expression which represents the default value of the parameter, if any.
*/
initializer: ts.Expression | null;
/**
* Type of the parameter.
*/
type: ts.TypeNode | null;
}
/**
* The source of an imported symbol, including the original symbol name and the module from which it
* was imported.
*/
export interface Import {
/**
* The name of the imported symbol under which it was exported (not imported).
*/
name: string;
/**
* The module from which the symbol was imported.
*
* This could either be an absolute module name (@angular/core for example) or a relative path.
*/
from: string;
/**
* TypeScript node that represents this import.
*/
node: ts.ImportDeclaration;
}
/**
* A type that is used to identify a declaration.
*/
export type DeclarationNode = ts.Declaration;
export type AmbientImport = {
__brand: 'AmbientImport';
};
/** Indicates that a declaration is referenced through an ambient type. */
export const AmbientImport = {} as AmbientImport;
/**
* The declaration of a symbol, along with information about how it was imported into the
* application.
*/
export interface Declaration<T extends ts.Declaration = ts.Declaration> {
/**
* The absolute module path from which the symbol was imported into the application, if the symbol
* was imported via an absolute module (even through a chain of re-exports). If the symbol is part
* of the application and was not imported from an absolute path, this will be `null`.
*/
viaModule: string | AmbientImport | null;
/**
* TypeScript reference to the declaration itself, if one exists.
*/
node: T;
}
/**
* Abstracts reflection operations on a TypeScript AST.
*
* Depending on the format of the code being interpreted, different concepts are represented
* with different syntactical structures. The `ReflectionHost` abstracts over those differences and
* presents a single API by which the compiler can query specific information about the AST.
*
* All operations on the `ReflectionHost` require the use of TypeScript `ts.Node`s with binding
* information already available (that is, nodes that come from a `ts.Program` that has been
* type-checked, and are not synthetically created).
*/ | {
"end_byte": 15192,
"start_byte": 7928,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/host.ts_15193_23146 | export interface ReflectionHost {
/**
* Examine a declaration (for example, of a class or function) and return metadata about any
* decorators present on the declaration.
*
* @param declaration a TypeScript `ts.Declaration` node representing the class or function over
* which to reflect. For example, if the intent is to reflect the decorators of a class and the
* source is in ES6 format, this will be a `ts.ClassDeclaration` node. If the source is in ES5
* format, this might be a `ts.VariableDeclaration` as classes in ES5 are represented as the
* result of an IIFE execution.
*
* @returns an array of `Decorator` metadata if decorators are present on the declaration, or
* `null` if either no decorators were present or if the declaration is not of a decoratable type.
*/
getDecoratorsOfDeclaration(declaration: DeclarationNode): Decorator[] | null;
/**
* Examine a declaration which should be of a class, and return metadata about the members of the
* class.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*
* @returns an array of `ClassMember` metadata representing the members of the class.
*
* @throws if `declaration` does not resolve to a class declaration.
*/
getMembersOfClass(clazz: ClassDeclaration): ClassMember[];
/**
* Reflect over the constructor of a class and return metadata about its parameters.
*
* This method only looks at the constructor of a class directly and not at any inherited
* constructors.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*
* @returns an array of `Parameter` metadata representing the parameters of the constructor, if
* a constructor exists. If the constructor exists and has 0 parameters, this array will be empty.
* If the class has no constructor, this method returns `null`.
*/
getConstructorParameters(clazz: ClassDeclaration): CtorParameter[] | null;
/**
* Reflect over a function and return metadata about its parameters and body.
*
* Functions in TypeScript and ES5 code have different AST representations, in particular around
* default values for parameters. A TypeScript function has its default value as the initializer
* on the parameter declaration, whereas an ES5 function has its default value set in a statement
* of the form:
*
* if (param === void 0) { param = 3; }
*
* This method abstracts over these details, and interprets the function declaration and body to
* extract parameter default values and the "real" body.
*
* A current limitation is that this metadata has no representation for shorthand assignment of
* parameter objects in the function signature.
*
* @param fn a TypeScript `ts.Declaration` node representing the function over which to reflect.
*
* @returns a `FunctionDefinition` giving metadata about the function definition.
*/
getDefinitionOfFunction(fn: ts.Node): FunctionDefinition | null;
/**
* Determine if an identifier was imported from another module and return `Import` metadata
* describing its origin.
*
* @param id a TypeScript `ts.Identifier` to reflect.
*
* @returns metadata about the `Import` if the identifier was imported from another module, or
* `null` if the identifier doesn't resolve to an import but instead is locally defined.
*/
getImportOfIdentifier(id: ts.Identifier): Import | null;
/**
* Trace an identifier to its declaration, if possible.
*
* This method attempts to resolve the declaration of the given identifier, tracing back through
* imports and re-exports until the original declaration statement is found. A `Declaration`
* object is returned if the original declaration is found, or `null` is returned otherwise.
*
* If the declaration is in a different module, and that module is imported via an absolute path,
* this method also returns the absolute path of the imported module. For example, if the code is:
*
* ```
* import {RouterModule} from '@angular/core';
*
* export const ROUTES = RouterModule.forRoot([...]);
* ```
*
* and if `getDeclarationOfIdentifier` is called on `RouterModule` in the `ROUTES` expression,
* then it would trace `RouterModule` via its import from `@angular/core`, and note that the
* definition was imported from `@angular/core` into the application where it was referenced.
*
* If the definition is re-exported several times from different absolute module names, only
* the first one (the one by which the application refers to the module) is returned.
*
* This module name is returned in the `viaModule` field of the `Declaration`. If The declaration
* is relative to the application itself and there was no import through an absolute path, then
* `viaModule` is `null`.
*
* @param id a TypeScript `ts.Identifier` to trace back to a declaration.
*
* @returns metadata about the `Declaration` if the original declaration is found, or `null`
* otherwise.
*/
getDeclarationOfIdentifier(id: ts.Identifier): Declaration | null;
/**
* Collect the declarations exported from a module by name.
*
* Iterates over the exports of a module (including re-exports) and returns a map of export
* name to its `Declaration`. If an exported value is itself re-exported from another module,
* the `Declaration`'s `viaModule` will reflect that.
*
* @param node a TypeScript `ts.Node` representing the module (for example a `ts.SourceFile`) for
* which to collect exports.
*
* @returns a map of `Declaration`s for the module's exports, by name.
*/
getExportsOfModule(module: ts.Node): Map<string, Declaration> | null;
/**
* Check whether the given node actually represents a class.
*/
isClass(node: ts.Node): node is ClassDeclaration;
/**
* Determines whether the given declaration, which should be a class, has a base class.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*/
hasBaseClass(clazz: ClassDeclaration): boolean;
/**
* Get an expression representing the base class (if any) of the given `clazz`.
*
* This expression is most commonly an Identifier, but is possible to inherit from a more dynamic
* expression.
*
* @param clazz the class whose base we want to get.
*/
getBaseClassExpression(clazz: ClassDeclaration): ts.Expression | null;
/**
* Get the number of generic type parameters of a given class.
*
* @param clazz a `ClassDeclaration` representing the class over which to reflect.
*
* @returns the number of type parameters of the class, if known, or `null` if the declaration
* is not a class or has an unknown number of type parameters.
*/
getGenericArityOfClass(clazz: ClassDeclaration): number | null;
/**
* Find the assigned value of a variable declaration.
*
* Normally this will be the initializer of the declaration, but where the variable is
* not a `const` we may need to look elsewhere for the variable's value.
*
* @param declaration a TypeScript variable declaration, whose value we want.
* @returns the value of the variable, as a TypeScript expression node, or `undefined`
* if the value cannot be computed.
*/
getVariableValue(declaration: ts.VariableDeclaration): ts.Expression | null;
/**
* Returns `true` if a declaration is exported from the module in which it's defined.
*
* Not all mechanisms by which a declaration is exported can be statically detected, especially
* when processing already compiled JavaScript. A `false` result does not indicate that the
* declaration is never visible outside its module, only that it was not exported via one of the
* export mechanisms that the `ReflectionHost` is capable of statically checking.
*/
isStaticallyExported(decl: ts.Node): boolean;
} | {
"end_byte": 23146,
"start_byte": 15193,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts_0_8230 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {
TypeValueReference,
TypeValueReferenceKind,
UnavailableTypeValueReference,
ValueUnavailableKind,
} from './host';
/**
* Potentially convert a `ts.TypeNode` to a `TypeValueReference`, which indicates how to use the
* type given in the `ts.TypeNode` in a value position.
*
* This can return `null` if the `typeNode` is `null`, if it does not refer to a symbol with a value
* declaration, or if it is not possible to statically understand.
*/
export function typeToValue(
typeNode: ts.TypeNode | null,
checker: ts.TypeChecker,
isLocalCompilation: boolean,
): TypeValueReference {
// It's not possible to get a value expression if the parameter doesn't even have a type.
if (typeNode === null) {
return missingType();
}
if (!ts.isTypeReferenceNode(typeNode)) {
return unsupportedType(typeNode);
}
const symbols = resolveTypeSymbols(typeNode, checker);
if (symbols === null) {
return unknownReference(typeNode);
}
const {local, decl} = symbols;
// It's only valid to convert a type reference to a value reference if the type actually
// has a value declaration associated with it. Note that const enums are an exception,
// because while they do have a value declaration, they don't exist at runtime.
if (decl.valueDeclaration === undefined || decl.flags & ts.SymbolFlags.ConstEnum) {
let typeOnlyDecl: ts.Declaration | null = null;
if (decl.declarations !== undefined && decl.declarations.length > 0) {
typeOnlyDecl = decl.declarations[0];
}
// In local compilation mode a declaration is considered invalid only if it is a type related
// declaration.
if (
!isLocalCompilation ||
(typeOnlyDecl &&
[
ts.SyntaxKind.TypeParameter,
ts.SyntaxKind.TypeAliasDeclaration,
ts.SyntaxKind.InterfaceDeclaration,
].includes(typeOnlyDecl.kind))
) {
return noValueDeclaration(typeNode, typeOnlyDecl);
}
}
// The type points to a valid value declaration. Rewrite the TypeReference into an
// Expression which references the value pointed to by the TypeReference, if possible.
// Look at the local `ts.Symbol`'s declarations and see if it comes from an import
// statement. If so, extract the module specifier and the name of the imported type.
const firstDecl = local.declarations && local.declarations[0];
if (firstDecl !== undefined) {
if (ts.isImportClause(firstDecl) && firstDecl.name !== undefined) {
// This is a default import.
// import Foo from 'foo';
if (firstDecl.isTypeOnly) {
// Type-only imports cannot be represented as value.
return typeOnlyImport(typeNode, firstDecl);
}
if (!ts.isImportDeclaration(firstDecl.parent)) {
return unsupportedType(typeNode);
}
return {
kind: TypeValueReferenceKind.LOCAL,
expression: firstDecl.name,
defaultImportStatement: firstDecl.parent,
};
} else if (ts.isImportSpecifier(firstDecl)) {
// The symbol was imported by name
// import {Foo} from 'foo';
// or
// import {Foo as Bar} from 'foo';
if (firstDecl.isTypeOnly) {
// The import specifier can't be type-only (e.g. `import {type Foo} from '...')`.
return typeOnlyImport(typeNode, firstDecl);
}
if (firstDecl.parent.parent.isTypeOnly) {
// The import specifier can't be inside a type-only import clause
// (e.g. `import type {Foo} from '...')`.
return typeOnlyImport(typeNode, firstDecl.parent.parent);
}
// Determine the name to import (`Foo`) from the import specifier, as the symbol names of
// the imported type could refer to a local alias (like `Bar` in the example above).
const importedName = (firstDecl.propertyName || firstDecl.name).text;
// The first symbol name refers to the local name, which is replaced by `importedName` above.
// Any remaining symbol names make up the complete path to the value.
const [_localName, ...nestedPath] = symbols.symbolNames;
const importDeclaration = firstDecl.parent.parent.parent;
if (!ts.isImportDeclaration(importDeclaration)) {
return unsupportedType(typeNode);
}
const moduleName = extractModuleName(importDeclaration);
return {
kind: TypeValueReferenceKind.IMPORTED,
valueDeclaration: decl.valueDeclaration ?? null,
moduleName,
importedName,
nestedPath,
};
} else if (ts.isNamespaceImport(firstDecl)) {
// The import is a namespace import
// import * as Foo from 'foo';
if (firstDecl.parent.isTypeOnly) {
// Type-only imports cannot be represented as value.
return typeOnlyImport(typeNode, firstDecl.parent);
}
if (symbols.symbolNames.length === 1) {
// The type refers to the namespace itself, which cannot be represented as a value.
return namespaceImport(typeNode, firstDecl.parent);
}
// The first symbol name refers to the local name of the namespace, which is is discarded
// as a new namespace import will be generated. This is followed by the symbol name that needs
// to be imported and any remaining names that constitute the complete path to the value.
const [_ns, importedName, ...nestedPath] = symbols.symbolNames;
const importDeclaration = firstDecl.parent.parent;
if (!ts.isImportDeclaration(importDeclaration)) {
return unsupportedType(typeNode);
}
const moduleName = extractModuleName(importDeclaration);
return {
kind: TypeValueReferenceKind.IMPORTED,
valueDeclaration: decl.valueDeclaration ?? null,
moduleName,
importedName,
nestedPath,
};
}
}
// If the type is not imported, the type reference can be converted into an expression as is.
const expression = typeNodeToValueExpr(typeNode);
if (expression !== null) {
return {
kind: TypeValueReferenceKind.LOCAL,
expression,
defaultImportStatement: null,
};
} else {
return unsupportedType(typeNode);
}
}
function unsupportedType(typeNode: ts.TypeNode): UnavailableTypeValueReference {
return {
kind: TypeValueReferenceKind.UNAVAILABLE,
reason: {kind: ValueUnavailableKind.UNSUPPORTED, typeNode},
};
}
function noValueDeclaration(
typeNode: ts.TypeNode,
decl: ts.Declaration | null,
): UnavailableTypeValueReference {
return {
kind: TypeValueReferenceKind.UNAVAILABLE,
reason: {kind: ValueUnavailableKind.NO_VALUE_DECLARATION, typeNode, decl},
};
}
function typeOnlyImport(
typeNode: ts.TypeNode,
node: ts.ImportClause | ts.ImportSpecifier,
): UnavailableTypeValueReference {
return {
kind: TypeValueReferenceKind.UNAVAILABLE,
reason: {kind: ValueUnavailableKind.TYPE_ONLY_IMPORT, typeNode, node},
};
}
function unknownReference(typeNode: ts.TypeNode): UnavailableTypeValueReference {
return {
kind: TypeValueReferenceKind.UNAVAILABLE,
reason: {kind: ValueUnavailableKind.UNKNOWN_REFERENCE, typeNode},
};
}
function namespaceImport(
typeNode: ts.TypeNode,
importClause: ts.ImportClause,
): UnavailableTypeValueReference {
return {
kind: TypeValueReferenceKind.UNAVAILABLE,
reason: {kind: ValueUnavailableKind.NAMESPACE, typeNode, importClause},
};
}
function missingType(): UnavailableTypeValueReference {
return {
kind: TypeValueReferenceKind.UNAVAILABLE,
reason: {kind: ValueUnavailableKind.MISSING_TYPE},
};
}
/**
* Attempt to extract a `ts.Expression` that's equivalent to a `ts.TypeNode`, as the two have
* different AST shapes but can reference the same symbols.
*
* This will return `null` if an equivalent expression cannot be constructed.
*/
export function typeNodeToValueExpr(node: ts.TypeNode): ts.Expression | null {
if (ts.isTypeReferenceNode(node)) {
return entityNameToValue(node.typeName);
} else {
return null;
}
} | {
"end_byte": 8230,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts"
} |
angular/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts_8232_11593 | /**
* Resolve a `TypeReference` node to the `ts.Symbol`s for both its declaration and its local source.
*
* In the event that the `TypeReference` refers to a locally declared symbol, these will be the
* same. If the `TypeReference` refers to an imported symbol, then `decl` will be the fully resolved
* `ts.Symbol` of the referenced symbol. `local` will be the `ts.Symbol` of the `ts.Identifier`
* which points to the import statement by which the symbol was imported.
*
* All symbol names that make up the type reference are returned left-to-right into the
* `symbolNames` array, which is guaranteed to include at least one entry.
*/
function resolveTypeSymbols(
typeRef: ts.TypeReferenceNode,
checker: ts.TypeChecker,
): {local: ts.Symbol; decl: ts.Symbol; symbolNames: string[]} | null {
const typeName = typeRef.typeName;
// typeRefSymbol is the ts.Symbol of the entire type reference.
const typeRefSymbol: ts.Symbol | undefined = checker.getSymbolAtLocation(typeName);
if (typeRefSymbol === undefined) {
return null;
}
// `local` is the `ts.Symbol` for the local `ts.Identifier` for the type.
// If the type is actually locally declared or is imported by name, for example:
// import {Foo} from './foo';
// then it'll be the same as `typeRefSymbol`.
//
// If the type is imported via a namespace import, for example:
// import * as foo from './foo';
// and then referenced as:
// constructor(f: foo.Foo)
// then `local` will be the `ts.Symbol` of `foo`, whereas `typeRefSymbol` will be the `ts.Symbol`
// of `foo.Foo`. This allows tracking of the import behind whatever type reference exists.
let local = typeRefSymbol;
// Destructure a name like `foo.X.Y.Z` as follows:
// - in `leftMost`, the `ts.Identifier` of the left-most name (`foo`) in the qualified name.
// This identifier is used to resolve the `ts.Symbol` for `local`.
// - in `symbolNames`, all names involved in the qualified path, or a single symbol name if the
// type is not qualified.
let leftMost = typeName;
const symbolNames: string[] = [];
while (ts.isQualifiedName(leftMost)) {
symbolNames.unshift(leftMost.right.text);
leftMost = leftMost.left;
}
symbolNames.unshift(leftMost.text);
if (leftMost !== typeName) {
const localTmp = checker.getSymbolAtLocation(leftMost);
if (localTmp !== undefined) {
local = localTmp;
}
}
// De-alias the top-level type reference symbol to get the symbol of the actual declaration.
let decl = typeRefSymbol;
if (typeRefSymbol.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(typeRefSymbol);
}
return {local, decl, symbolNames};
}
export function entityNameToValue(node: ts.EntityName): ts.Expression | null {
if (ts.isQualifiedName(node)) {
const left = entityNameToValue(node.left);
return left !== null ? ts.factory.createPropertyAccessExpression(left, node.right) : null;
} else if (ts.isIdentifier(node)) {
const clone = ts.setOriginalNode(ts.factory.createIdentifier(node.text), node);
(clone as any).parent = node.parent;
return clone;
} else {
return null;
}
}
function extractModuleName(node: ts.ImportDeclaration): string {
if (!ts.isStringLiteral(node.moduleSpecifier)) {
throw new Error('not a module specifier');
}
return node.moduleSpecifier.text;
} | {
"end_byte": 11593,
"start_byte": 8232,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.ts"
} |
angular/packages/misc/angular-in-memory-web-api/CHANGELOG.md_0_6693 | # "angular-in-memory-web-api" versions
>This in-memory-web-api exists primarily to support the Angular documentation.
It is not supposed to emulate every possible real world web API and is not intended for production use.
>
>Most importantly, it is ***always experimental***.
We will make breaking changes and we won't feel bad about it
because this is a development tool, not a production product.
We do try to tell you about such changes in this `CHANGELOG.md`
and we fix bugs as fast as we can.
<a id="0.11.0"></a>
## 0.11.0 (2020-05-13)
* update to support Angular v10.
* no functional changes.
<a id="0.9.0"></a>
## 0.9.0 (2019-06-20)
* update to support Angular version 8.x and forward
* no functional changes
<a id="0.8.0"></a>
## 0.8.0 (2018-12-06)
* remove `@angular/http` support
* no functional changes
**BREAKING CHANGE**
This version no longer supports any functionality for `@angular/http`. Please use
`@angular/common/http` instead.
<a id="0.7.0"></a>
## 0.7.0 (2018-10-31)
* update to support Angular v7.
* no functional changes
<a id="0.6.1"></a>
## 0.6.1 (2018-05-04)
* update to Angular and RxJS v6 releases
<a id="0.6.0"></a>
## 0.6.0 (2018-03-22)
*Migrate to Angular v6 and RxJS v6 (rc and beta)*
Note that this release is pinned to Angular "^6.0.0-rc.0" and RxJS "^6.0.0-beta.1".
Will likely update again when they are official.
**BREAKING CHANGE**
This version depends on RxJS v6 and is not backward compatible with earlier RxJS versions.
<a id="0.5.4"></a>
## 0.5.4 (2018-03-09)
Simulated HTTP error responses were not delaying the prescribed time when using RxJS `delay()`
because it was short-circuited by the ErrorResponse.
New `delayResponse` function does it right.
Should not break you unless you incorrectly expected no delay for errors.
Also, this library no longer calls RxJS `delay()` which may make testing with it easier
(Angular TestBed does not handle RxJS `delay()` well because that operator uses `interval()`).
Also fixes type error (issue #180).
<a id="0.5.3"></a>
## 0.5.3 (2018-01-06)
Can make use of `HttpParams` which yields a `request.urlWithParams`.
Added supporting `HeroService.searchHeroes(term: string)` and test.
<a id="0.5.2"></a>
## 0.5.2 (2017-12-10)
No longer modify the request data coming from client. Fixes #164
<a id="0.5.1"></a>
## 0.5.1 (2017-10-21)
Support Angular v5.
<a id="0.5.0"></a>
## 0.5.0 (2017-10-05)
**BREAKING CHANGE**: HTTP response data no longer wrapped in object w/ `data` property by default.
In this release, the `dataEncapsulation` configuration default changed from `false` to `true`. The HTTP response body holds the data values directly rather than an object that encapsulates those values, `{data: ...}`. This is a **breaking change that affects almost all existing apps!**
Changing the default to `false` is a **breaking change**. Pre-existing apps that did not set this property explicitly will be broken because they expect encapsulation and are probably mapping
the HTTP response results from the `data` property like this:
```
.map(data => data.data as Hero[])
```
**To migrate, simply remove that line everywhere.**
If you would rather keep the web api's encapsulation, `{data: ...}`, set `dataEncapsulation` to `true` during configuration as in the following example:
```
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, { dataEncapsulation: true })
```
We made this change because
1. Almost everyone seems to hate the encapsulation
2. Encapsulation requires mapping to get the desired data out. With old `Http` that isn't _too_ bad because you needed to map to get data anyway (`res => res.json()`). But it is really ugly for `HttpClient` because you can't use the type HTTP method type parameter (e.g., `get<entity-type>`) and you have to map out of the data property (`.map(data => data.data as Hero[]`). That extra step requires explanations that distract from learning `HttpClient` itself.
Now you just write `http.get<Hero[]>()` and you’ve got data (please add error handling).
3. While you could have turned off encapsulation with configuration as of v.0.4, to do so took yet another step that you’d have to discover and explain. A big reason for the in-mem web api is to make it easy to introduce and demonstrate HTTP operations in Angular. The _out-of-box_ experience is more important than avoiding a breaking change.
4. The [security flaw](https://stackoverflow.com/questions/3503102/what-are-top-level-json-arrays-and-why-are-they-a-security-risk)
that prompted encapsulation seems to have been mitigated by all (almost all?) the browsers that can run an Angular (v2+) app. We don’t think it’s needed anymore.
5. A most real world APIs today will not encapsulate; they’ll return the data in the body without extra ceremony.
<a id="0.4.6"></a>
## 0.4.6 (2017-09-13)
- improves README
- updates v0.4.0 entry in the CHANGELOG to describe essential additions to SystemJS configuration.
- no important functional changes.
<a id="0.4.5"></a>
## 0.4.5 (2017-09-11)
Feature - offer separate `HttpClientInMemoryWebApiModule` and `HttpInMemoryWebApiModule`.
closes #140
<a id="0.4.4"></a>
## 0.4.4 (2017-09-11)
closes #136
A **breaking change** if you expected `genId` to generate ids for a collection
with non-numeric `item.id`.
<a id="0.4.3"></a>
## 0.4.3 (2017-09-11)
Refactoring for clarity and to correctly reflect intent.
A **breaking change** only if your customizations depend directly and explicitly on `RequestInfo` or the `get`, `delete`, `post`, or `put` methods.
- replace all `switchMap` with `concatMap` because, in all previous uses of `switchMap`,
I really meant to wait for the source observable to complete _before_ beginning the inner observable whereas `switchMap` starts the inner observable right away.
- restored `collection` to the `RequestInfo` interface and set it in `handleRequest_`
- `get`, `delete`, `post`, and `put` methods get the `collection` from `requestInfo`; simplifies their signatures to one parameter.
<a id="0.4.2"></a>
## 0.4.2 (2017-09-08)
- Postpones the in-memory database initialization (via `resetDb`) until the first HTTP request.
- Your `createDb` method _can_ be asynchronous.
You may return the database object (synchronous), an observable of it, or a promise of it. Issue #113.
- fixed some rare race conditions.
<a id="0.4.1"></a>
## 0.4.1 (2017-09-08)
**Support PassThru.**
The passthru feature was broken by 0.4.0
- add passthru to both `Http` and `HttpClient`
- test passThru feature with jasmine-ajax mock-ajax plugin
to intercept Angular's attempt to call browser's XHR
- update devDependency packages
- update karma.conf with jasmine-ajax plugin
<a id="0.4.0"></a>
## 0.4.0 ( | {
"end_byte": 6693,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/CHANGELOG.md"
} |
angular/packages/misc/angular-in-memory-web-api/CHANGELOG.md_6693_13482 | 2017-09-07)
**Theme: Support `HttpClient` and add tests**.
See PR #130.
The 0.4.0 release was a major overhaul of this library.
You don't have to change your existing application _code_ if your app uses this library without customizations.
But this release's **breaking changes** affect developers who used the customization features or loaded application files with SystemJS.
**BREAKING CHANGES**: Massive refactoring.
Many low-level and customization options have changed.
Apps that stuck with defaults should be (mostly) OK.
If you're loading application files with **SystemJS** (as you would in a plunker), see the [instructions below](#v-0-4-systemjs).
* added support for `HttpClient` -> renaming of backend service classes
* added tests
* refactor existing code to support tests
* correct bugs and clarify choices as result of test
* add some configuration options
- dataEncapsulation (issue #112, pr#123)
- post409
- put404b
* `POST commands/resetDb` passes the request to your `resetDb` method
so you can optionally reset the database dynamically
to arbitrary initial states (issue #128)
* when HTTP method interceptor returns null/undefined, continue with service's default processing (pr #120)
* can substitute your own id generator, `geniD`
* parseUrl -> parseRequestUrl
* utility methods exposed in `RequestInfo.utils`
* reorganize files into src/app and src/in-mem
* adjust gulp tasks accordingly
---
<a id="v-0-4-systemjs"></a>
### Plunkers and SystemJS
If you’re loading application files with **SystemJS** (as you would in a plunker), you’ll have to configure it to load Angular’s `umd.js` for `HttpModule` and the `tslib` package.
To see how, look in the `map` section of the
[`src/systemjs.config.js` for this project](https://github.com/angular/in-memory-web-api/blob/master/src/systemjs.config.js) for the following two _additional_ lines :
```
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
...
'tslib': 'npm:tslib/tslib.js',
```
You've already made these changes if you are using `HttpClient` today.
If you’re sticking with the original Angular `Http` module, you _must make this change anyway!_ Your app will break as soon as you run `npm install` and it installs >=v0.4.0.
If you're using webpack (as CLI devs do), you don't have to worry about this stuff because webpack bundles the dependencies for you.
---
<a id="0.3.2"></a>
## 0.3.2 (2017-05-02)
* Bug fixes PRs #91, 95, 106
<a id="0.3.1"></a>
## 0.3.1 (2017-03-08)
* Now runs in node so can use in "universal" demos.
See PR #102.
<a id="0.3.0"></a>
## 0.3.0 (2017-02-27)
* Support Angular version 4
<a id="0.2.4"></a>
## 0.2.4 (2017-01-02)
* Remove reflect-matadata and zone.js as peerDependencies
<a id="0.2.3"></a>
## 0.2.3 (2016-12-28)
* Unpin RxJs
<a id="0.2.2"></a>
## 0.2.2 (2016-12-20)
* Update to Angular 2.4.0
<a id="0.2.1"></a>
## 0.2.1 (2016-12-14)
* Fixed regression in handling commands, introduced in 0.2.0
* Improved README
<a id="0.2.0"></a>
## 0.2.0 (2016-12-11)
* BREAKING CHANGE: The observables returned by the `handleCollections` methods that process requests against the supplied in-mem-db collections are now "cold".
That means that requests aren't processed until something subscribes to the observable ... just like real-world `Http` calls.
Previously, these request were "hot" meaning that the operation was performed immediately
(e.g., an in-memory collection was updated) and _then_ we returned an `Observable<Response>`.
That was a mistake! Fixing that mistake _might_ break your app which is why bumped the _minor_ version number from 1 to 2.
We hope _very few apps are broken by this change_. Most will have subscribed anyway.
But any app that called an `http` method with fire-and-forget ... and didn't subscribe ...
expecting the database to be updated (for example) will discover that the operation did ***not*** happen.
* BREAKING CHANGE: `createErrorResponse` now requires the `Request` object as its first parameter
so it can prepare a proper error message.
For example, a 404 `errorResponse.toString()` now shows the request URL.
* Commands remain "hot" — processed immediately — as they should be.
* The `HTTP GET` interceptor in example `hero-data.service` shows how to create your own "cold" observable.
* While you can still specify the `inMemDbService['responseInterceptor']` to morph the response options,
the previously exported `responseInterceptor` function no longer exists as it served no useful purpose.
Added the `ResponseInterceptor` _type_ to remind you of the signature to implement.
* Allows objects with `id===0` (issue #56)
* The default `parseUrl` method is more flexible, thanks in part to the new `config.apiBase` property.
See the ReadMe to learn more.
* Added `config.post204` and `config.put204` to control whether PUT and POST return the saved entity.
It is `true` by default which means they do not return the entity (`status=204`) — the same behavior as before. (issue #74)
* `response.url` is set to `request.url` when this service itself creates the response.
* A few new methods (e.g., `emitResponse`) to assist in HTTP method interceptors.
<hr>
<a id="0.1.17"></a>
## 0.1.17 (2016-12-07)
* Update to Angular 2.2.0.
<a id="0.1.16"></a>
## 0.1.16 (2016-11-20)
* Swap `"lib": [ "es2015", "dom" ]` in `tsconfig.json` for @types/core-js` in `package.json` issue #288
<a id="0.1.15"></a>
## 0.1.15 (2016-11-14)
* Update to Angular 2.2.0.
<a id="0.1.14"></a>
## 0.1.14 (2016-10-29)
* Add `responseInterceptor` for [issue #61](https://github.com/angular/in-memory-web-api/issues/61)
<a id="0.1.13"></a>
## 0.1.13 (2016-10-20)
* Update README for 0.1.11 breaking change: npm publish as `esm` and a `umd` bundle
Going to `umd` changes your `systemjs.config` and the way you import the library.
In `systemjs.config.js` you should change the mapping to:
```
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
```
then delete from `packages`:
```
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
```
You must ES import the in-mem module (typically in `AppModule`) like this:
```
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
```
<a id="0.1.12"></a>
## 0.1.12 (2016-10-19)
* exclude travis.yml and rollup.config.js from npm package
<a id="0.1.11"></a>
## 0.1.11 (2016-10-19)
* BREAKING CHANGE: npm publish as `esm` and a `umd` bundle.
Does not change the API but does change the way you register and import the
in-mem module. Documented in later release, v.0.1.13
<a id="0.1.10"></a>
## 0.1.10 (2016-10-19)
* Catch a `handleRequest` error and return as a failed server response.
<a id="0.1.9"></a>
## 0.1.9 (2016-10- | {
"end_byte": 13482,
"start_byte": 6693,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/CHANGELOG.md"
} |
angular/packages/misc/angular-in-memory-web-api/CHANGELOG.md_13482_16912 | 18)
* Restore delay option, issue #53.
<a id="0.1.7"></a>
## 0.1.7 (2016-10-12)
* Angular 2.1.x support.
<a id="0.1.6"></a>
## 0.1.6 (2016-10-09)
* Do not add delay to observable if delay value === 0 (issue #47)
* Can override `parseUrl` method in your db service class (issue #46, #35)
* README.md explains `parseUrl` override.
* Exports functions helpful for custom HTTP Method Interceptors
* `createErrorResponse`
* `createObservableResponse`
* `setStatusText`
* Added `examples/hero-data.service.ts` to show overrides (issue #44)
<a id="0.1.5"></a>
## 0.1.5 (2016-10-03)
* project.json license changed again to match angular.io package.json
<a id="0.1.4"></a>
## 0.1.4 (2016-10-03)
* project.json license is "MIT"
<a id="0.1.3"></a>
## 0.1.3 (2016-09-29)
* Fix typos
<a id="0.1.2"></a>
## 0.1.2 (2016-09-29)
* AoT support from Tor PR #36
* Update npm packages
* `parseId` fix from PR #33
<a id="0.1.1"></a>
## 0.1.1 (2016-09-26)
* Exclude src folder and its TS files from npm package
<a id="0.1.0"></a>
## 0.1.0 (2016-09-25)
* Renamed package to "angular-in-memory-web-api"
* Added "passThruUnknownUrl" options
* Simplified `forRoot` and made it acceptable to AoT
* Support case sensitive search (PR #16)
# "angular2-in-memory-web-api" versions
The last npm package named "angular2-in-memory-web-api" was v.0.0.21
<a id="0.0.21"></a>
## 0.0.21 (2016-09-25)
* Add source maps (PR #14)
<a id="0.0.20"></a>
## 0.0.20 (2016-09-15)
* Angular 2.0.0
* Typescript 2.0.2
<a id="0.0.19"></a>
## 0.0.19 (2016-09-13)
* RC7
<a id="0.0.18"></a>
## 0.0.18 (2016-08-31)
* RC6 (doesn't work with older versions)
<a id="0.0.17"></a>
## 0.0.17 (2016-08-19)
* fix `forRoot` type constraint
* clarify `forRoot` param
<a id="0.0.16"></a>
## 0.0.16 (2016-08-19)
* No longer exports `HttpModule`
* Can specify configuration options in 2nd param of `forRoot`
* jsDocs for `forRoot`
<a id="0.0.15"></a>
## 0.0.15 (2016-08-09)
* RC5
* Support for NgModules
<a id="0.0.14"></a>
## 0.0.14 (2016-06-30)
* RC4
<a id="0.0.13"></a>
## 0.0.13 (2016-06-21)
* RC3
<a id="0.0.12"></a>
## 0.0.12 (2016-06-15)
* RC2
<a id="0.0.11"></a>
## 0.0.11 (2016-05-27)
* add RegExp query support
* find-by-id is sensitive to string ids that look like numbers
<a id="0.0.10"></a>
## 0.0.10 (2016-05-21)
* added "main:index.js" to package.json
* updated to typings v.1.0.4 (a breaking release)
* dependencies -> peerDependencies|devDependencies
* no es6-shim dependency.
* use core-js as devDependency.
<a id="0.0.9"></a>
## 0.0.9 (2016-05-19)
* renamed the barrel core.js -> index.js
<a id="0.0.8"></a>
## 0.0.8 (2016-05-19)
* systemjs -> commonjs
* replace es6-shim typings w/ core-js typings
<a id="0.0.7"></a>
## 0.0.7 (2016-05-03)
* RC1
* update to 2.0.0-rc.1
<a id="0.0.6"></a>
## 0.0.6 (2016-05-03)
* RC0
* update to 2.0.0-rc.0
<a id="0.0.5"></a>
## 0.0.5 (2016-05-01)
* PROVISIONAL - refers to @angular packages
* update to 0.0.0-5
<a id="0.0.4"></a>
## 0.0.4 (2016-04-30)
* PROVISIONAL - refers to @angular packages
* update to 0.0.0-3
* rxjs: "5.0.0-beta.6"
<a id="0.0.3"></a>
## 0.0.3 (2016-04-29)
* PROVISIONAL - refers to @angular packages
* update to 0.0.0-2
<a id="0.0.2"></a>
## 0.0.2 (2016-04-27)
* PROVISIONAL - refers to @angular packages
<a id="0.0.1"></a>
## 0.0.1 (2016-04-27)
* DO NOT USE. Not adapted to new package system.
* Initial cut for Angular 2 repackaged
* target forthcoming Angular 2 RC
| {
"end_byte": 16912,
"start_byte": 13482,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/CHANGELOG.md"
} |
angular/packages/misc/angular-in-memory-web-api/README.md_0_6352 | # Angular in-memory-web-api
An in-memory web api for Angular demos and tests
that emulates CRUD operations over a RESTy API.
It intercepts Angular `Http` and `HttpClient` requests that would otherwise go to the remote server and redirects them to an in-memory data store that you control.
See [Austin McDaniel's article](https://medium.com/@amcdnl/mocking-with-angular-more-than-just-unit-testing-cbb7908c9fcc)
for a quick introduction.
_This package used to live [in its own repository](https://github.com/angular/in-memory-web-api)._
### _It used to work and now it doesn't :-(_
Perhaps you installed a new version of this library? Check the
[CHANGELOG.md](https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/CHANGELOG.md)
for breaking changes that may have affected your app.
If that doesn't explain it, create an
[issue on github](https://github.com/angular/angular/issues),
preferably with a small repro.
## Use cases
* Demo apps that need to simulate CRUD data persistence operations without a real server.
You won't have to build and start a test server.
* Whip up prototypes and proofs of concept.
* Share examples with the community in a web coding environment such as Plunker or CodePen.
Create Angular issues and StackOverflow answers supported by live code.
* Simulate operations against data collections that aren't yet implemented on your dev/test server.
You can pass requests thru to the dev/test server for collections that are supported.
* Write unit test apps that read and write data.
Avoid the hassle of intercepting multiple http calls and manufacturing sequences of responses.
The in-memory data store resets for each test so there is no cross-test data pollution.
* End-to-end tests. If you can toggle the app into test mode
using the in-memory web api, you won't disturb the real database.
This can be especially useful for CI (continuous integration) builds.
>**LIMITATIONS**
>
>The _in-memory-web-api_ exists primarily to support the
[Angular documentation](https://angular.io/docs/ts/latest/ "Angular documentation web site").
It is not supposed to emulate every possible real world web API and is not intended for production use.
>
>Most importantly, it is ***always experimental***.
We will make breaking changes and we won't feel bad about it
because this is a development tool, not a production product.
We do try to tell you about such changes in the `CHANGELOG.md`
and we fix bugs as fast as we can.
## HTTP request handling
This in-memory web api service processes an HTTP request and
returns an `Observable` of HTTP `Response` object
in the manner of a RESTy web api.
It natively handles URI patterns in the form `:base/:collectionName/:id?`
Examples:
```ts
// for requests to an `api` base URL that gets heroes from a 'heroes' collection
GET api/heroes // all heroes
GET api/heroes/42 // the hero with id=42
GET api/heroes?name=^j // 'j' is a regex; returns heroes whose name starting with 'j' or 'J'
GET api/heroes.json/42 // ignores the ".json"
```
The in-memory web api service processes these requests against a "database" - a set of named collections - that you define during setup.
## Basic setup
<a id="createDb"></a>
Create an `InMemoryDataService` class that implements `InMemoryDbService`.
At minimum it must implement `createDb` which
creates a "database" hash whose keys are collection names
and whose values are arrays of collection objects to return or update.
For example:
```ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemHeroService implements InMemoryDbService {
createDb() {
let heroes = [
{ id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' },
{ id: 4, name: 'Tornado' }
];
return {heroes};
}
}
```
**Notes**
* The in-memory web api library _currently_ assumes that every collection has a primary key called `id`.
* The `createDb` method can be synchronous or asynchronous.
It would have to be asynchronous if you initialized your in-memory database service from a JSON file.
Return the database _object_, an _observable_ of that object, or a _promise_ of that object. The tests include an example of all three.
* The in-memory web api calls your `InMemoryDbService` data service class's `createDb` method on two occasions.
1. when it handles the _first_ HTTP request
1. when it receives a `resetdb` [command](#commands).
In the command case, the service passes in a `RequestInfo` object,
enabling the `createDb` logic to adjust its behavior per the client request. See the tests for examples.
### Import the in-memory web api module
Register your data store service implementation with the `HttpClientInMemoryWebApiModule`
in your root `AppModule.imports`
calling the `forRoot` static method with this service class and an optional configuration object:
```ts
import { HttpClientModule } from '@angular/common/http';
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemHeroService } from '../app/hero.service';
@NgModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(InMemHeroService),
...
],
...
})
export class AppModule { ... }
```
**_Notes_**
* Always import the `HttpClientInMemoryWebApiModule` _after_ the `HttpClientModule`
to ensure that the in-memory backend provider supersedes the Angular version.
* You can setup the in-memory web api within a lazy loaded feature module by calling the `.forFeature` method as you would `.forRoot`.
* In production, you want HTTP requests to go to the real server and probably have no need for the _in-memory_ provider.
CLI-based apps can exclude the provider in production builds like this:
```ts
imports: [
HttpClientModule,
environment.production ?
[] : HttpClientInMemoryWebApiModule.forRoot(InMemHeroService)
...
]
```
# Examples
The [tests](https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test)
are a good place to learn how to setup and use this in-memory web api library.
See also the example source code in the official Angular.dev documentation such as the
[HttpClient](https://angular.dev/guide/http) guide and the
[Tour of Heroes](https://angular.dev/tutorials/first-app/14-http).
| {
"end_byte": 6352,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/README.md"
} |
angular/packages/misc/angular-in-memory-web-api/README.md_6352_15010 | # Advanced Features
Some features are not readily apparent in the basic usage described above.
## Configuration arguments
The `InMemoryBackendConfigArgs` defines a set of options. Add them as the second `forRoot` argument:
```ts
InMemoryWebApiModule.forRoot(InMemHeroService, { delay: 500 }),
```
**Read the `InMemoryBackendConfigArgs` interface to learn about these options**.
## Request evaluation order
This service can evaluate requests in multiple ways depending upon the configuration.
Here's how it reasons:
1. If it looks like a [command](#commands), process as a command.
2. If the [HTTP method is overridden](#method-override), try the override.
3. If the resource name (after the api base path) matches one of the configured collections, process that.
4. If not but the `Config.passThruUnknownUrl` flag is `true`, try to [pass the request along to a real _XHR_](#passthru).
5. Return a 404.
See the `handleRequest` method implementation for details.
## Default delayed response
By default this service adds a 500ms delay
to all data requests to simulate round-trip latency.
>[Command requests](#commands) have zero added delay as they concern
in-memory service configuration and do not emulate real data requests.
You can change or eliminate the latency by setting a different `delay` value:
```ts
InMemoryWebApiModule.forRoot(InMemHeroService, { delay: 0 }), // no delay
InMemoryWebApiModule.forRoot(InMemHeroService, { delay: 1500 }), // 1.5 second delay
```
## Simple query strings
Pass custom filters as a regex pattern via query string.
The query string defines which property and value to match.
Format: `/app/heroes/?propertyName=regexPattern`
The following example matches all names that start with the letter 'j' or 'J' in the heroes collection.
`/app/heroes/?name=^j`
>Search pattern matches are case insensitive by default.
Set `config.caseSensitiveSearch = true` if needed.
<a id="passthru"></a>
## Pass thru to a live server
If an existing, running remote server should handle requests for collections
that are not in the in-memory database, set `Config.passThruUnknownUrl: true`.
Then this service will forward unrecognized requests to the remote server
via the Angular default `XHR` backend (it depends on whether your using `Http` or `HttpClient`).
<a id="commands"></a>
## Commands
The client may issue a command request to get configuration state
from the in-memory web api service, reconfigure it,
or reset the in-memory database.
When the last segment of the _api base path_ is "commands", the `collectionName` is treated as the _command_.
Example URLs:
```sh
commands/resetdb // Reset the "database" to its original state
commands/config // Get or update this service's config object
```
Usage:
```sh
http.post('commands/resetdb', undefined);
http.get('commands/config');
http.post('commands/config', '{"delay":1000}');
```
Command requests do not simulate real remote data access.
They ignore the latency delay and respond as quickly as possible.
The `resetDb` command
calls your `InMemoryDbService` data service's [`createDb` method](#createDb) with the `RequestInfo` object,
enabling the `createDb` logic to adjust its behavior per the client request.
In the following example, the client includes a reset option in the command request body:
```ts
http
// Reset the database collections with the `clear` option
.post('commands/resetDb', { clear: true }))
// when command finishes, get heroes
.concatMap(
()=> http.get<Data>('api/heroes')
.map(data => data.data as Hero[])
)
// execute the request sequence and
// do something with the heroes
.subscribe(...)
```
See the tests for other examples.
## _parseRequestUrl_
The `parseRequestUrl` parses the request URL into a `ParsedRequestUrl` object.
`ParsedRequestUrl` is a public interface whose properties guide the in-memory web api
as it processes the request.
### Default _parseRequestUrl_
Default parsing depends upon certain values of `config`: `apiBase`, `host`, and `urlRoot`.
Read the source code for the complete story.
Configuring the `apiBase` yields the most interesting changes to `parseRequestUrl` behavior:
* For `apiBase=undefined` and `url='http://localhost/api/customers/42'`
```ts
{apiBase: 'api/', collectionName: 'customers', id: '42', ...}
```
* For `apiBase='some/api/root/'` and `url='http://localhost/some/api/root/customers'`
```ts
{ apiBase: 'some/api/root/', collectionName: 'customers', id: undefined, ... }
```
* For `apiBase='/'` and `url='http://localhost/customers'`
```ts
{ apiBase: '/', collectionName: 'customers', id: undefined, ... }
```
**The actual api base segment values are ignored**. Only the number of segments matters.
The following api base strings are considered identical: 'a/b' ~ 'some/api/' ~ `two/segments'
This means that URLs that work with the in-memory web api may be rejected by the real server.
### Custom _parseRequestUrl_
You can override the default parser by implementing a `parseRequestUrl` method in your `InMemoryDbService`.
The service calls your method with two arguments.
1. `url` - the request URL string
1. `requestInfoUtils` - utility methods in a `RequestInfoUtilities` object, including the default parser.
Note that some values have not yet been set as they depend on the outcome of parsing.
Your method must either return a `ParsedRequestUrl` object or `null`|`undefined`,
in which case the service uses the default parser.
In this way you can intercept and parse some URLs and leave the others to the default parser.
## Custom _genId_
Collection items are presumed to have a primary key property called `id`.
You can specify the `id` while adding a new item.
The service will blindly use that `id`; it does not check for uniqueness.
If you do not specify the `id`, the service generates one via the `genId` method.
You can override the default id generator with a method called `genId` in your `InMemoryDbService`.
Your method receives the new item's collection and collection name.
It should return the generated id.
If your generator returns `null`|`undefined`, the service uses the default generator.
## _responseInterceptor_
You can change the response returned by the service's default HTTP methods.
A typical reason to intercept is to add a header that your application is expecting.
To intercept responses, add a `responseInterceptor` method to your `InMemoryDbService` class.
The service calls your interceptor like this:
```ts
responseOptions = this.responseInterceptor(responseOptions, requestInfo);
```
<a id="method-override"></a>
## HTTP method interceptors
You may have HTTP requests that the in-memory web api can't handle properly.
You can override any HTTP method by implementing a method
of that name in your `InMemoryDbService`.
Your method's name must be the same as the HTTP method name but **all lowercase**.
The in-memory web api calls it with a `RequestInfo` object that contains request data and utility methods.
For example, if you implemented a `get` method, the web api would be called like this:
`yourInMemDbService["get"](requestInfo)`.
Your custom HTTP method must return either:
* `Observable<Response>` - you handled the request and the response is available from this
observable. It _should be "cold"_.
* `null`/`undefined` - you decided not to intervene,
perhaps because you wish to intercept only certain paths for the given HTTP method.
The service continues with its default processing of the HTTP request.
The `RequestInfo` is an interface defined in `src/in-mem/interfaces.ts`.
Its members include:
```ts
req: Request; // the request object from the client
collectionName: string; // calculated from the request url
collection: any[]; // the corresponding collection (if found)
id: any; // the item `id` (if specified)
url: string; // the url in the request
utils: RequestInfoUtilities; // helper functions
```
The functions in `utils` can help you analyze the request
and compose a response.
## In-memory Web Api Examples
The [test fixtures](https://github.com/angular/angular/tree/main/packages/misc/angular-in-memory-web-api/test/fixtures)
demonstrates library usage with tested examples.
The `HeroInMemDataService` class (in `test/fixtures/hero-in-mem-data-service.ts`) is a Hero-oriented `InMemoryDbService`
such as you might see in an HTTP sample in the Angular documentation.
The `HeroInMemDataOverrideService` class (in `test/fixtures/hero-in-mem-data-override-service.ts`)
demonstrates a few ways to override methods of the base `HeroInMemDataService`.
| {
"end_byte": 15010,
"start_byte": 6352,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/README.md"
} |
angular/packages/misc/angular-in-memory-web-api/BUILD.bazel_0_612 | load("//tools:defaults.bzl", "ng_module", "ng_package")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "angular-in-memory-web-api",
package_name = "angular-in-memory-web-api",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
module_name = "angular-in-memory-web-api",
deps = [
"//packages/common",
"//packages/common/http",
"//packages/core",
"@npm//rxjs",
],
)
ng_package(
name = "npm_package",
srcs = ["package.json"],
deps = [
":angular-in-memory-web-api",
],
)
| {
"end_byte": 612,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/BUILD.bazel"
} |
angular/packages/misc/angular-in-memory-web-api/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/index.ts"
} |
angular/packages/misc/angular-in-memory-web-api/public_api.ts_0_321 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/in-memory-web-api';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 321,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/public_api.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts_0_1128 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import 'jasmine-ajax';
import {
FetchBackend,
HTTP_INTERCEPTORS,
HttpBackend,
HttpClient,
HttpClientModule,
HttpEvent,
HttpEventType,
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpResponse,
provideHttpClient,
withFetch,
} from '@angular/common/http';
import {importProvidersFrom, Injectable} from '@angular/core';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {HttpClientBackendService, HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api';
import {Observable, zip} from 'rxjs';
import {concatMap, map, tap} from 'rxjs/operators';
import {Hero} from './fixtures/hero';
import {HeroInMemDataOverrideService} from './fixtures/hero-in-mem-data-override-service';
import {HeroInMemDataService} from './fixtures/hero-in-mem-data-service';
import {HeroService} from './fixtures/hero-service';
import {HttpClientHeroService} from './fixtures/http-client-hero-service'; | {
"end_byte": 1128,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts_1130_8835 | describe('HttpClient Backend Service', () => {
const delay = 1; // some minimal simulated latency delay
describe('raw Angular HttpClient', () => {
let http: HttpClient;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}),
],
});
http = TestBed.get(HttpClient);
});
it('can get heroes', waitForAsync(() => {
http
.get<Hero[]>('api/heroes')
.subscribe(
(heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'),
failRequest,
);
}));
it('GET should be a "cold" observable', waitForAsync(() => {
const httpBackend = TestBed.get(HttpBackend);
const spy = spyOn(httpBackend, 'collectionHandler').and.callThrough();
const get$ = http.get<Hero[]>('api/heroes');
// spy on `collectionHandler` should not be called before subscribe
expect(spy).not.toHaveBeenCalled();
get$.subscribe((heroes) => {
expect(spy).toHaveBeenCalled();
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}, failRequest);
}));
it('GET should wait until after delay to respond', waitForAsync(() => {
// to make test fail, set `delay=0` above
let gotResponse = false;
http.get<Hero[]>('api/heroes').subscribe((heroes) => {
gotResponse = true;
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}, failRequest);
expect(gotResponse).toBe(false, 'should delay before response');
}));
it('Should only initialize the db once', waitForAsync(() => {
const httpBackend = TestBed.get(HttpBackend);
const spy = spyOn(httpBackend, 'resetDb').and.callThrough();
// Simultaneous backend.handler calls
// Only the first should initialize by calling `resetDb`
// All should wait until the db is "ready"
// then they share the same db instance.
http.get<Hero[]>('api/heroes').subscribe();
http.get<Hero[]>('api/heroes').subscribe();
http.get<Hero[]>('api/heroes').subscribe();
http.get<Hero[]>('api/heroes').subscribe();
expect(spy.calls.count()).toBe(1);
}));
it('can get heroes (w/ a different base path)', waitForAsync(() => {
http.get<Hero[]>('some-base-path/heroes').subscribe((heroes) => {
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}, failRequest);
}));
it('should 404 when GET unknown collection (after delay)', waitForAsync(() => {
let gotError = false;
const url = 'api/unknown-collection';
http.get<Hero[]>(url).subscribe(
() => fail(`should not have found data for '${url}'`),
(err) => {
gotError = true;
expect(err.status).toBe(404, 'should have 404 status');
},
);
expect(gotError).toBe(false, 'should not get error until after delay');
}));
it('should return the hero w/id=1 for GET app/heroes/1', waitForAsync(() => {
http
.get<Hero>('api/heroes/1')
.subscribe((hero) => expect(hero).toBeDefined('should find hero with id=1'), failRequest);
}));
// test where id is string that looks like a number
it('should return the stringer w/id="10" for GET app/stringers/10', waitForAsync(() => {
http
.get<Hero>('api/stringers/10')
.subscribe(
(hero) => expect(hero).toBeDefined('should find string with id="10"'),
failRequest,
);
}));
it('should return 1-item array for GET app/heroes/?id=1', waitForAsync(() => {
http
.get<Hero[]>('api/heroes/?id=1')
.subscribe(
(heroes) => expect(heroes.length).toBe(1, 'should find one hero w/id=1'),
failRequest,
);
}));
it('should return 1-item array for GET app/heroes?id=1', waitForAsync(() => {
http
.get<Hero[]>('api/heroes?id=1')
.subscribe(
(heroes) => expect(heroes.length).toBe(1, 'should find one hero w/id=1'),
failRequest,
);
}));
it('should return undefined for GET app/heroes?id=not-found-id', waitForAsync(() => {
http
.get<Hero[]>('api/heroes?id=123456')
.subscribe((heroes) => expect(heroes.length).toBe(0), failRequest);
}));
it('should return 404 for GET app/heroes/not-found-id', waitForAsync(() => {
const url = 'api/heroes/123456';
http.get<Hero[]>(url).subscribe(
() => fail(`should not have found data for '${url}'`),
(err) => expect(err.status).toBe(404, 'should have 404 status'),
);
}));
it('can generate the id when add a hero with no id', waitForAsync(() => {
const hero = new Hero(undefined, 'SuperDooper');
http.post<Hero>('api/heroes', hero).subscribe((replyHero) => {
expect(replyHero.id).toBeDefined('added hero should have an id');
expect(replyHero).not.toBe(hero, 'reply hero should not be the request hero');
}, failRequest);
}));
it('can get nobodies (empty collection)', waitForAsync(() => {
http.get<Hero[]>('api/nobodies').subscribe((nobodies) => {
expect(nobodies.length).toBe(0, 'should have no nobodies');
}, failRequest);
}));
it('can add a nobody with an id to empty nobodies collection', waitForAsync(() => {
const id = 'g-u-i-d';
http
.post('api/nobodies', {id, name: 'Noman'})
.pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies')))
.subscribe((nobodies) => {
expect(nobodies.length).toBe(1, 'should a nobody');
expect(nobodies[0].name).toBe('Noman', 'should be "Noman"');
expect(nobodies[0].id).toBe(id, 'should preserve the submitted, ' + id);
}, failRequest);
}));
it('should fail when add a nobody without an id to empty nobodies collection', waitForAsync(() => {
http.post('api/nobodies', {name: 'Noman'}).subscribe(
() => fail(`should not have been able to add 'Norman' to 'nobodies'`),
(err) => {
expect(err.status).toBe(422, 'should have 422 status');
expect(err.body.error).toContain('id type is non-numeric');
},
);
}));
describe('can reset the database', () => {
it('to empty (object db)', waitForAsync(() => resetDatabaseTest('object')));
it('to empty (observable db)', waitForAsync(() => resetDatabaseTest('observable')));
it('to empty (promise db)', waitForAsync(() => resetDatabaseTest('promise')));
function resetDatabaseTest(returnType: string) {
// Observable of the number of heroes and nobodies
const sizes$ = zip(
http.get<Hero[]>('api/heroes'),
http.get<Hero[]>('api/nobodies'),
http.get<Hero[]>('api/stringers'),
).pipe(map(([h, n, s]) => ({heroes: h.length, nobodies: n.length, stringers: s.length})));
// Add a nobody so that we have one
http
.post('api/nobodies', {id: 42, name: 'Noman'})
.pipe(
// Reset database with "clear" option
concatMap(() => http.post('commands/resetDb', {clear: true, returnType})),
// get the number of heroes and nobodies
concatMap(() => sizes$),
)
.subscribe((sizes) => {
expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes');
expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies');
expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers');
}, failRequest);
}
});
}); | {
"end_byte": 8835,
"start_byte": 1130,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts_8839_16546 | describe('raw Angular HttpClient w/ override service', () => {
let http: HttpClient;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataOverrideService, {delay}),
],
});
http = TestBed.get(HttpClient);
});
it('can get heroes', waitForAsync(() => {
http
.get<Hero[]>('api/heroes')
.subscribe(
(heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'),
failRequest,
);
}));
it('can translate `foo/heroes` to `heroes` via `parsedRequestUrl` override', waitForAsync(() => {
http
.get<Hero[]>('api/foo/heroes')
.subscribe(
(heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'),
failRequest,
);
}));
it('can get villains', waitForAsync(() => {
http
.get<Hero[]>('api/villains')
.subscribe(
(villains) => expect(villains.length).toBeGreaterThan(0, 'should have villains'),
failRequest,
);
}));
it('should 404 when POST to villains', waitForAsync(() => {
const url = 'api/villains';
http.post<Hero[]>(url, {id: 42, name: 'Dr. Evil'}).subscribe(
() => fail(`should not have POSTed data for '${url}'`),
(err) => expect(err.status).toBe(404, 'should have 404 status'),
);
}));
it('should 404 when GET unknown collection', waitForAsync(() => {
const url = 'api/unknown-collection';
http.get<Hero[]>(url).subscribe(
() => fail(`should not have found data for '${url}'`),
(err) => expect(err.status).toBe(404, 'should have 404 status'),
);
}));
it('should use genId override to add new hero, "Maxinius"', waitForAsync(() => {
http
.post('api/heroes', {name: 'Maxinius'})
.pipe(concatMap(() => http.get<Hero[]>('api/heroes?name=Maxi')))
.subscribe((heroes) => {
expect(heroes.length).toBe(1, 'should have found "Maxinius"');
expect(heroes[0].name).toBe('Maxinius');
expect(heroes[0].id).toBeGreaterThan(1000);
}, failRequest);
}));
it('should use genId override guid generator for a new nobody without an id', waitForAsync(() => {
http
.post('api/nobodies', {name: 'Noman'})
.pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies')))
.subscribe((nobodies) => {
expect(nobodies.length).toBe(1, 'should a nobody');
expect(nobodies[0].name).toBe('Noman', 'should be "Noman"');
expect(typeof nobodies[0].id).toBe('string', 'should create a string (guid) id');
}, failRequest);
}));
describe('can reset the database', () => {
it('to empty (object db)', waitForAsync(() => resetDatabaseTest('object')));
it('to empty (observable db)', waitForAsync(() => resetDatabaseTest('observable')));
it('to empty (promise db)', waitForAsync(() => resetDatabaseTest('promise')));
function resetDatabaseTest(returnType: string) {
// Observable of the number of heroes, nobodies and villains
const sizes$ = zip(
http.get<Hero[]>('api/heroes'),
http.get<Hero[]>('api/nobodies'),
http.get<Hero[]>('api/stringers'),
http.get<Hero[]>('api/villains'),
).pipe(
map(([h, n, s, v]) => ({
heroes: h.length,
nobodies: n.length,
stringers: s.length,
villains: v.length,
})),
);
// Add a nobody so that we have one
http
.post('api/nobodies', {id: 42, name: 'Noman'})
.pipe(
// Reset database with "clear" option
concatMap(() => http.post('commands/resetDb', {clear: true, returnType})),
// count all the collections
concatMap(() => sizes$),
)
.subscribe((sizes) => {
expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes');
expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies');
expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers');
expect(sizes.villains).toBeGreaterThan(0, 'reset should NOT clear villains');
}, failRequest);
}
});
});
describe('HttpClient HeroService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}),
],
providers: [{provide: HeroService, useClass: HttpClientHeroService}],
});
});
describe('HeroService core', () => {
let heroService: HeroService;
beforeEach(() => {
heroService = TestBed.get(HeroService);
});
it('can get heroes', waitForAsync(() => {
heroService.getHeroes().subscribe((heroes) => {
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}, failRequest);
}));
it('can get hero w/ id=1', waitForAsync(() => {
heroService.getHero(1).subscribe(
(hero) => {
expect(hero.name).toBe('Windstorm');
},
() => fail('getHero failed'),
);
}));
it('should 404 when hero id not found', waitForAsync(() => {
const id = 123456;
heroService.getHero(id).subscribe(
() => fail(`should not have found hero for id='${id}'`),
(err) => {
expect(err.status).toBe(404, 'should have 404 status');
},
);
}));
it('can add a hero', waitForAsync(() => {
heroService
.addHero('FunkyBob')
.pipe(
tap((hero) => expect(hero.name).toBe('FunkyBob')),
// Get the new hero by its generated id
concatMap((hero) => heroService.getHero(hero.id)),
)
.subscribe(
(hero) => {
expect(hero.name).toBe('FunkyBob');
},
() => failRequest('re-fetch of new hero failed'),
);
}), 10000);
it('can delete a hero', waitForAsync(() => {
const id = 1;
heroService.deleteHero(id).subscribe((_: {}) => expect(_).toBeDefined(), failRequest);
}));
it('should allow delete of non-existent hero', waitForAsync(() => {
const id = 123456;
heroService.deleteHero(id).subscribe((_: {}) => expect(_).toBeDefined(), failRequest);
}));
it('can search for heroes by name containing "a"', waitForAsync(() => {
heroService.searchHeroes('a').subscribe((heroes: Hero[]) => {
expect(heroes.length).toBe(3, 'should find 3 heroes with letter "a"');
}, failRequest);
}));
it('can update existing hero', waitForAsync(() => {
const id = 1;
heroService
.getHero(id)
.pipe(
concatMap((hero) => {
hero.name = 'Thunderstorm';
return heroService.updateHero(hero);
}),
concatMap(() => heroService.getHero(id)),
)
.subscribe(
(hero) => expect(hero.name).toBe('Thunderstorm'),
() => fail('re-fetch of updated hero failed'),
);
}), 10000);
it('should create new hero when try to update non-existent hero', waitForAsync(() => {
const falseHero = new Hero(12321, 'DryMan');
heroService
.updateHero(falseHero)
.subscribe((hero) => expect(hero.name).toBe(falseHero.name), failRequest);
}));
});
}); | {
"end_byte": 16546,
"start_byte": 8839,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts_16550_23413 | describe('HttpClient interceptor', () => {
let http: HttpClient;
let interceptors: HttpInterceptor[];
let httpBackend: HttpClientBackendService;
/**
* Test interceptor adds a request header and a response header
*/
@Injectable()
class TestHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const reqClone = req.clone({setHeaders: {'x-test-req': 'req-test-header'}});
return next.handle(reqClone).pipe(
map((event) => {
if (event instanceof HttpResponse) {
event = event.clone({headers: event.headers.set('x-test-res', 'res-test-header')});
}
return event;
}),
);
}
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}),
],
providers: [
// Add test interceptor just for this test suite
{provide: HTTP_INTERCEPTORS, useClass: TestHeaderInterceptor, multi: true},
],
});
http = TestBed.get(HttpClient);
httpBackend = TestBed.get(HttpBackend);
interceptors = TestBed.get(HTTP_INTERCEPTORS);
});
// sanity test
it('TestingModule should provide the test interceptor', () => {
const ti = interceptors.find((i) => i instanceof TestHeaderInterceptor);
expect(ti).toBeDefined();
});
it('should have GET request header from test interceptor', waitForAsync(() => {
const handle = spyOn(httpBackend, 'handle').and.callThrough();
http.get<Hero[]>('api/heroes').subscribe((heroes) => {
// HttpRequest is first arg of the first call to in-mem backend `handle`
const req: HttpRequest<Hero[]> = handle.calls.argsFor(0)[0];
const reqHeader = req.headers.get('x-test-req');
expect(reqHeader).toBe('req-test-header');
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}, failRequest);
}));
it('should have GET response header from test interceptor', waitForAsync(() => {
let gotResponse = false;
const req = new HttpRequest<any>('GET', 'api/heroes');
http.request<Hero[]>(req).subscribe(
(event) => {
if (event.type === HttpEventType.Response) {
gotResponse = true;
const resHeader = event.headers.get('x-test-res');
expect(resHeader).toBe('res-test-header');
const heroes = event.body as Hero[];
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}
},
failRequest,
() => expect(gotResponse).toBe(true, 'should have seen Response event'),
);
}));
});
describe('HttpClient passThru', () => {
let http: HttpClient;
let httpBackend: HttpClientBackendService;
let createPassThruBackend: jasmine.Spy;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {
delay,
passThruUnknownUrl: true,
}),
],
});
http = TestBed.get(HttpClient);
httpBackend = TestBed.get(HttpBackend);
createPassThruBackend = spyOn(<any>httpBackend, 'createPassThruBackend').and.callThrough();
});
beforeEach(() => {
jasmine.Ajax.install();
});
afterEach(() => {
jasmine.Ajax.uninstall();
});
it('can get heroes (no passthru)', waitForAsync(() => {
http.get<Hero[]>('api/heroes').subscribe((heroes) => {
expect(createPassThruBackend).not.toHaveBeenCalled();
expect(heroes.length).toBeGreaterThan(0, 'should have heroes');
}, failRequest);
}));
// `passthru` is NOT a collection in the data store
// so requests for it should pass thru to the "real" server
it('can GET passthru', waitForAsync(() => {
jasmine.Ajax.stubRequest('api/passthru').andReturn({
'status': 200,
'contentType': 'application/json',
'response': JSON.stringify([{id: 42, name: 'Dude'}]),
});
http.get<any[]>('api/passthru').subscribe((passthru) => {
expect(passthru.length).toBeGreaterThan(0, 'should have passthru data');
}, failRequest);
}));
it('can ADD to passthru', waitForAsync(() => {
jasmine.Ajax.stubRequest('api/passthru').andReturn({
'status': 200,
'contentType': 'application/json',
'response': JSON.stringify({id: 42, name: 'Dude'}),
});
http.post<any>('api/passthru', {name: 'Dude'}).subscribe((passthru) => {
expect(passthru).toBeDefined('should have passthru data');
expect(passthru.id).toBe(42, 'passthru object should have id 42');
}, failRequest);
}));
});
describe('Http dataEncapsulation = true', () => {
let http: HttpClient;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {
delay,
dataEncapsulation: true,
}),
],
});
http = TestBed.get(HttpClient);
});
it('can get heroes (encapsulated)', waitForAsync(() => {
http
.get<{data: any}>('api/heroes')
.pipe(map((data) => data.data as Hero[]))
.subscribe(
(heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have data.heroes'),
failRequest,
);
}));
});
describe('when using the FetchBackend', () => {
it('should be the an InMemory Service', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withFetch()),
importProvidersFrom(
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}),
),
{provide: HeroService, useClass: HttpClientHeroService},
],
});
expect(TestBed.inject(HttpBackend)).toBeInstanceOf(HttpClientBackendService);
});
it('should be a FetchBackend', () => {
// In this test, providers order matters
TestBed.configureTestingModule({
providers: [
importProvidersFrom(
HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}),
),
provideHttpClient(withFetch()),
{provide: HeroService, useClass: HttpClientHeroService},
],
});
expect(TestBed.inject(HttpBackend)).toBeInstanceOf(FetchBackend);
});
});
});
/**
* Fail a Jasmine test such that it displays the error object,
* typically passed in the error path of an Observable.subscribe()
*/
function failRequest(err: any) {
fail(JSON.stringify(err));
} | {
"end_byte": 23413,
"start_byte": 16550,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/BUILD.bazel_0_617 | load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
# Visible to //:saucelabs_unit_tests_poc target
visibility = ["//:__pkg__"],
deps = [
"//packages/common",
"//packages/common/http",
"//packages/core",
"//packages/core/testing",
"//packages/misc/angular-in-memory-web-api",
"@npm//@types/jasmine-ajax",
"@npm//jasmine-ajax",
"@npm//rxjs",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| {
"end_byte": 617,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/BUILD.bazel"
} |
angular/packages/misc/angular-in-memory-web-api/test/fixtures/hero-service.ts_0_672 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable} from 'rxjs';
import {Hero} from './hero';
export abstract class HeroService {
heroesUrl = 'api/heroes'; // URL to web api
abstract getHeroes(): Observable<Hero[]>;
abstract getHero(id: number): Observable<Hero>;
abstract addHero(name: string): Observable<Hero>;
abstract deleteHero(hero: Hero | number): Observable<Hero>;
abstract searchHeroes(term: string): Observable<Hero[]>;
abstract updateHero(hero: Hero): Observable<Hero>;
}
| {
"end_byte": 672,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/fixtures/hero-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/fixtures/hero.ts_0_346 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export class Hero {
constructor(
public id = 0,
public name = '',
) {}
clone() {
return new Hero(this.id, this.name);
}
}
| {
"end_byte": 346,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/fixtures/hero.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-override-service.ts_0_3395 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* This is an example of a Hero-oriented InMemoryDbService with method overrides.
*/
import {Injectable} from '@angular/core';
import {
getStatusText,
ParsedRequestUrl,
RequestInfo,
RequestInfoUtilities,
ResponseOptions,
STATUS,
} from 'angular-in-memory-web-api';
import {Observable} from 'rxjs';
import {HeroInMemDataService} from './hero-in-mem-data-service';
const villains = [
// deliberately using string ids that look numeric
{id: 100, name: 'Snidley Wipsnatch'},
{id: 101, name: 'Boris Badenov'},
{id: 103, name: 'Natasha Fatale'},
];
// Pseudo guid generator
function guid() {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
@Injectable()
export class HeroInMemDataOverrideService extends HeroInMemDataService {
// Overrides id generator and delivers next available `id`, starting with 1001.
genId<T extends {id: any}>(collection: T[], collectionName: string): any {
if (collectionName === 'nobodies') {
return guid();
} else if (collection) {
return 1 + collection.reduce((prev, curr) => Math.max(prev, curr.id || 0), 1000);
}
}
// HTTP GET interceptor
get(reqInfo: RequestInfo): Observable<any> | undefined {
const collectionName = reqInfo.collectionName;
if (collectionName === 'villains') {
return this.getVillains(reqInfo);
}
return undefined; // let the default GET handle all others
}
// HTTP GET interceptor handles requests for villains
private getVillains(reqInfo: RequestInfo) {
return reqInfo.utils.createResponse$(() => {
const collection = villains.slice();
const dataEncapsulation = reqInfo.utils.getConfig().dataEncapsulation;
const id = reqInfo.id;
const data = id == null ? collection : reqInfo.utils.findById(collection, id);
const options: ResponseOptions = data
? {body: dataEncapsulation ? {data} : data, status: STATUS.OK}
: {body: {error: `'Villains' with id='${id}' not found`}, status: STATUS.NOT_FOUND};
return this.finishOptions(options, reqInfo);
});
}
// parseRequestUrl override
// Do this to manipulate the request URL or the parsed result
// into something your data store can handle.
// This example turns a request for `/foo/heroes` into just `/heroes`.
// It leaves other URLs untouched and forwards to the default parser.
// It also logs the result of the default parser.
parseRequestUrl(url: string, utils: RequestInfoUtilities): ParsedRequestUrl {
const newUrl = url.replace(/\/foo\/heroes/, '/heroes');
return utils.parseRequestUrl(newUrl);
}
responseInterceptor(resOptions: ResponseOptions, reqInfo: RequestInfo) {
if (resOptions.headers) {
resOptions.headers = resOptions.headers.set('x-test', 'test-header');
}
return resOptions;
}
private finishOptions(options: ResponseOptions, {headers, url}: RequestInfo) {
options.statusText = options.status == null ? undefined : getStatusText(options.status);
options.headers = headers;
options.url = url;
return options;
}
}
| {
"end_byte": 3395,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-override-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-service.ts_0_2322 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* This is an example of a Hero-oriented InMemoryDbService.
*
* For demonstration purposes, it can return the database
* synchronously as an object (default),
* as an observable, or as a promise.
*
* Add the following line to `AppModule.imports`
* InMemoryWebApiModule.forRoot(HeroInMemDataService) // or HeroInMemDataOverrideService
*/
import {Injectable} from '@angular/core';
import {InMemoryDbService, RequestInfo} from 'angular-in-memory-web-api';
import {Observable, of} from 'rxjs';
import {delay} from 'rxjs/operators';
interface Person {
id: string | number;
name: string;
}
interface PersonResponse {
heroes: Person[];
stringers: Person[];
nobodies: Person[];
}
@Injectable()
export class HeroInMemDataService implements InMemoryDbService {
createDb(
reqInfo?: RequestInfo,
): Observable<PersonResponse> | Promise<PersonResponse> | PersonResponse {
const heroes = [
{id: 1, name: 'Windstorm'},
{id: 2, name: 'Bombasto'},
{id: 3, name: 'Magneta'},
{id: 4, name: 'Tornado'},
];
const nobodies: any[] = [];
// entities with string ids that look like numbers
const stringers = [
{id: '10', name: 'Bob String'},
{id: '20', name: 'Jill String'},
];
// default returnType
let returnType = 'object';
// let returnType = 'observable';
// let returnType = 'promise';
// demonstrate POST commands/resetDb
// this example clears the collections if the request body tells it to do so
if (reqInfo) {
const body = reqInfo.utils.getJsonBody(reqInfo.req) || {};
if (body.clear === true) {
heroes.length = 0;
nobodies.length = 0;
stringers.length = 0;
}
// 'returnType` can be 'object' | 'observable' | 'promise'
returnType = body.returnType || 'object';
}
const db = {heroes, nobodies, stringers};
switch (returnType) {
case 'observable':
return of(db).pipe(delay(10));
case 'promise':
return new Promise((resolve) => setTimeout(() => resolve(db), 10));
default:
return db;
}
}
}
| {
"end_byte": 2322,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/test/fixtures/http-client-hero-service.ts_0_2495 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
import {Hero} from './hero';
import {HeroService} from './hero-service';
const cudOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
};
@Injectable()
export class HttpClientHeroService extends HeroService {
constructor(private http: HttpClient) {
super();
}
override getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl).pipe(catchError(this.handleError));
}
// This get-by-id will 404 when id not found
override getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get<Hero>(url).pipe(catchError(this.handleError));
}
// This get-by-id does not 404; returns undefined when id not found
// getHero<Data>(id: number): Observable<Hero> {
// const url = `${this._heroesUrl}/?id=${id}`;
// return this.http.get<Hero[]>(url)
// .map(heroes => heroes[0] as Hero)
// .catch(this.handleError);
// }
override addHero(name: string): Observable<Hero> {
const hero = {name};
return this.http
.post<Hero>(this.heroesUrl, hero, cudOptions)
.pipe(catchError(this.handleError));
}
override deleteHero(hero: Hero | number): Observable<Hero> {
const id = typeof hero === 'number' ? hero : hero.id;
const url = `${this.heroesUrl}/${id}`;
return this.http.delete<Hero>(url, cudOptions).pipe(catchError(this.handleError));
}
override searchHeroes(term: string): Observable<Hero[]> {
term = term.trim();
// add safe, encoded search parameter if term is present
const options = term ? {params: new HttpParams().set('name', term)} : {};
return this.http.get<Hero[]>(this.heroesUrl, options).pipe(catchError(this.handleError));
}
override updateHero(hero: Hero): Observable<Hero> {
return this.http.put<Hero>(this.heroesUrl, hero, cudOptions).pipe(catchError(this.handleError));
}
private handleError(error: any) {
// In a real world app, we might send the error to remote logging infrastructure
// and reformat for user consumption
return throwError(error);
}
}
| {
"end_byte": 2495,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/test/fixtures/http-client-hero-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts_0_2352 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {XhrFactory} from '@angular/common';
import {HttpBackend} from '@angular/common/http';
import {ModuleWithProviders, NgModule, Type} from '@angular/core';
import {httpClientInMemBackendServiceFactory} from './http-client-in-memory-web-api-module';
import {InMemoryBackendConfig, InMemoryBackendConfigArgs, InMemoryDbService} from './interfaces';
@NgModule()
export class InMemoryWebApiModule {
/**
* Redirect BOTH Angular `Http` and `HttpClient` XHR calls
* to in-memory data store that implements `InMemoryDbService`.
* with class that implements InMemoryDbService and creates an in-memory database.
*
* Usually imported in the root application module.
* Can import in a lazy feature module too, which will shadow modules loaded earlier
*
* Note: If you use the `FetchBackend`, make sure forRoot is invoked after in the providers list
*
* @param dbCreator - Class that creates seed data for in-memory database. Must implement
* InMemoryDbService.
* @param [options]
*
* @example
* InMemoryWebApiModule.forRoot(dbCreator);
* InMemoryWebApiModule.forRoot(dbCreator, {useValue: {delay:600}});
*/
static forRoot(
dbCreator: Type<InMemoryDbService>,
options?: InMemoryBackendConfigArgs,
): ModuleWithProviders<InMemoryWebApiModule> {
return {
ngModule: InMemoryWebApiModule,
providers: [
{provide: InMemoryDbService, useClass: dbCreator},
{provide: InMemoryBackendConfig, useValue: options},
{
provide: HttpBackend,
useFactory: httpClientInMemBackendServiceFactory,
deps: [InMemoryDbService, InMemoryBackendConfig, XhrFactory],
},
],
};
}
/**
*
* Enable and configure the in-memory web api in a lazy-loaded feature module.
* Same as `forRoot`.
* This is a feel-good method so you can follow the Angular style guide for lazy-loaded modules.
*/
static forFeature(
dbCreator: Type<InMemoryDbService>,
options?: InMemoryBackendConfigArgs,
): ModuleWithProviders<InMemoryWebApiModule> {
return InMemoryWebApiModule.forRoot(dbCreator, options);
}
}
| {
"end_byte": 2352,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/in-memory-web-api.ts_0_453 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './backend-service';
export * from './http-status-codes';
export * from './http-client-backend-service';
export * from './in-memory-web-api-module';
export * from './http-client-in-memory-web-api-module';
export * from './interfaces';
| {
"end_byte": 453,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/in-memory-web-api.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts_0_3457 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {XhrFactory} from '@angular/common';
import {
HttpBackend,
HttpEvent,
HttpHeaders,
HttpParams,
HttpRequest,
HttpResponse,
HttpXhrBackend,
} from '@angular/common/http';
import {Inject, Injectable, Optional} from '@angular/core';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {BackendService} from './backend-service';
import {STATUS} from './http-status-codes';
import {
InMemoryBackendConfig,
InMemoryBackendConfigArgs,
InMemoryDbService,
ResponseOptions,
} from './interfaces';
/**
* For Angular `HttpClient` simulate the behavior of a RESTy web api
* backed by the simple in-memory data store provided by the injected `InMemoryDbService`.
* Conforms mostly to behavior described here:
* https://www.restapitutorial.com/lessons/httpmethods.html
*
* ### Usage
*
* Create an in-memory data store class that implements `InMemoryDbService`.
* Call `config` static method with this service class and optional configuration object:
* ```
* // other imports
* import { HttpClientModule } from '@angular/common/http';
* import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
*
* import { InMemHeroService, inMemConfig } from '../api/in-memory-hero.service';
* @NgModule({
* imports: [
* HttpModule,
* HttpClientInMemoryWebApiModule.forRoot(InMemHeroService, inMemConfig),
* ...
* ],
* ...
* })
* export class AppModule { ... }
* ```
*/
@Injectable()
export class HttpClientBackendService extends BackendService implements HttpBackend {
constructor(
inMemDbService: InMemoryDbService,
@Inject(InMemoryBackendConfig) @Optional() config: InMemoryBackendConfigArgs,
private xhrFactory: XhrFactory,
) {
super(inMemDbService, config);
}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
try {
return this.handleRequest(req);
} catch (error) {
const err = (error as Error).message || error;
const resOptions = this.createErrorResponseOptions(
req.url,
STATUS.INTERNAL_SERVER_ERROR,
`${err}`,
);
return this.createResponse$(() => resOptions);
}
}
protected override getJsonBody(req: HttpRequest<any>): any {
return req.body;
}
protected override getRequestMethod(req: HttpRequest<any>): string {
return (req.method || 'get').toLowerCase();
}
protected override createHeaders(headers: {[index: string]: string}): HttpHeaders {
return new HttpHeaders(headers);
}
protected override createQueryMap(search: string): Map<string, string[]> {
const map = new Map<string, string[]>();
if (search) {
const params = new HttpParams({fromString: search});
params.keys().forEach((p) => map.set(p, params.getAll(p) || []));
}
return map;
}
protected override createResponse$fromResponseOptions$(
resOptions$: Observable<ResponseOptions>,
): Observable<HttpResponse<any>> {
return resOptions$.pipe(map((opts) => new HttpResponse<any>(opts)));
}
protected override createPassThruBackend() {
try {
return new HttpXhrBackend(this.xhrFactory);
} catch (ex: any) {
ex.message = 'Cannot create passThru404 backend; ' + (ex.message || '');
throw ex;
}
}
}
| {
"end_byte": 3457,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts_0_2734 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {XhrFactory} from '@angular/common';
import {HttpBackend} from '@angular/common/http';
import {ModuleWithProviders, NgModule, Type} from '@angular/core';
import {HttpClientBackendService} from './http-client-backend-service';
import {InMemoryBackendConfig, InMemoryBackendConfigArgs, InMemoryDbService} from './interfaces';
// Internal - Creates the in-mem backend for the HttpClient module
// AoT requires factory to be exported
export function httpClientInMemBackendServiceFactory(
dbService: InMemoryDbService,
options: InMemoryBackendConfig,
xhrFactory: XhrFactory,
): HttpBackend {
return new HttpClientBackendService(dbService, options, xhrFactory) as HttpBackend;
}
@NgModule()
export class HttpClientInMemoryWebApiModule {
/**
* Redirect the Angular `HttpClient` XHR calls
* to in-memory data store that implements `InMemoryDbService`.
* with class that implements InMemoryDbService and creates an in-memory database.
*
* Usually imported in the root application module.
* Can import in a lazy feature module too, which will shadow modules loaded earlier
*
* Note: If you use the `FetchBackend`, make sure forRoot is invoked after in the providers list
*
* @param dbCreator - Class that creates seed data for in-memory database. Must implement
* InMemoryDbService.
* @param [options]
*
* @example
* HttpInMemoryWebApiModule.forRoot(dbCreator);
* HttpInMemoryWebApiModule.forRoot(dbCreator, {useValue: {delay:600}});
*/
static forRoot(
dbCreator: Type<InMemoryDbService>,
options?: InMemoryBackendConfigArgs,
): ModuleWithProviders<HttpClientInMemoryWebApiModule> {
return {
ngModule: HttpClientInMemoryWebApiModule,
providers: [
{provide: InMemoryDbService, useClass: dbCreator},
{provide: InMemoryBackendConfig, useValue: options},
{
provide: HttpBackend,
useFactory: httpClientInMemBackendServiceFactory,
deps: [InMemoryDbService, InMemoryBackendConfig, XhrFactory],
},
],
};
}
/**
*
* Enable and configure the in-memory web api in a lazy-loaded feature module.
* Same as `forRoot`.
* This is a feel-good method so you can follow the Angular style guide for lazy-loaded modules.
*/
static forFeature(
dbCreator: Type<InMemoryDbService>,
options?: InMemoryBackendConfigArgs,
): ModuleWithProviders<HttpClientInMemoryWebApiModule> {
return HttpClientInMemoryWebApiModule.forRoot(dbCreator, options);
}
}
| {
"end_byte": 2734,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.