_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_factory_linker_1.ts_0_2210 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileFactoryFunction,
ConstantPool,
FactoryTarget,
outputAst as o,
R3DeclareFactoryMetadata,
R3DependencyMetadata,
R3FactoryMetadata,
R3PartialDeclaration,
} from '@angular/compiler';
import {AstObject} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {getDependency, parseEnum, wrapReference} from './util';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareFactory()` call expressions.
*/
export class PartialFactoryLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
): LinkedDefinition {
const meta = toR3FactoryMeta(metaObj);
return compileFactoryFunction(meta);
}
}
/**
* Derives the `R3FactoryMetadata` structure from the AST object.
*/
export function toR3FactoryMeta<TExpression>(
metaObj: AstObject<R3DeclareFactoryMetadata, TExpression>,
): R3FactoryMetadata {
const typeExpr = metaObj.getValue('type');
const typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new FatalLinkerError(
typeExpr.expression,
'Unsupported type, its name could not be determined',
);
}
return {
name: typeName,
type: wrapReference(typeExpr.getOpaque()),
typeArgumentCount: 0,
target: parseEnum(metaObj.getValue('target'), FactoryTarget),
deps: getDependencies(metaObj, 'deps'),
};
}
function getDependencies<TExpression>(
metaObj: AstObject<R3DeclareFactoryMetadata, TExpression>,
propName: keyof R3DeclareFactoryMetadata,
): R3DependencyMetadata[] | null | 'invalid' {
if (!metaObj.has(propName)) {
return null;
}
const deps = metaObj.getValue(propName);
if (deps.isArray()) {
return deps.getArray().map((dep) => getDependency(dep.getObject()));
}
if (deps.isString()) {
return 'invalid';
}
return null;
}
| {
"end_byte": 2210,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_factory_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_ng_module_linker_1.ts_0_4713 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileNgModule,
ConstantPool,
outputAst as o,
R3DeclareNgModuleMetadata,
R3NgModuleMetadata,
R3NgModuleMetadataKind,
R3PartialDeclaration,
R3Reference,
R3SelectorScopeMode,
} from '@angular/compiler';
import {AstObject, AstValue} from '../../ast/ast_value';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {wrapReference} from './util';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareNgModule()` call expressions.
*/
export class PartialNgModuleLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
constructor(
/**
* If true then emit the additional declarations, imports, exports, etc in the NgModule
* definition. These are only used by JIT compilation.
*/
private emitInline: boolean,
) {}
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
): LinkedDefinition {
const meta = toR3NgModuleMeta(metaObj, this.emitInline);
return compileNgModule(meta);
}
}
/**
* Derives the `R3NgModuleMetadata` structure from the AST object.
*/
export function toR3NgModuleMeta<TExpression>(
metaObj: AstObject<R3DeclareNgModuleMetadata, TExpression>,
supportJit: boolean,
): R3NgModuleMetadata {
const wrappedType = metaObj.getOpaque('type');
const meta: R3NgModuleMetadata = {
kind: R3NgModuleMetadataKind.Global,
type: wrapReference(wrappedType),
bootstrap: [],
declarations: [],
publicDeclarationTypes: null,
includeImportTypes: true,
imports: [],
exports: [],
selectorScopeMode: supportJit ? R3SelectorScopeMode.Inline : R3SelectorScopeMode.Omit,
containsForwardDecls: false,
schemas: [],
id: metaObj.has('id') ? metaObj.getOpaque('id') : null,
};
// Each of `bootstrap`, `declarations`, `imports` and `exports` are normally an array. But if any
// of the references are not yet declared, then the arrays must be wrapped in a function to
// prevent errors at runtime when accessing the values.
// The following blocks of code will unwrap the arrays from such functions, because
// `R3NgModuleMetadata` expects arrays of `R3Reference` objects.
// Further, since the `ɵɵdefineNgModule()` will also suffer from the forward declaration problem,
// we must update the `containsForwardDecls` property if a function wrapper was found.
if (metaObj.has('bootstrap')) {
const bootstrap = metaObj.getValue('bootstrap');
if (bootstrap.isFunction()) {
meta.containsForwardDecls = true;
meta.bootstrap = wrapReferences(unwrapForwardRefs(bootstrap));
} else meta.bootstrap = wrapReferences(bootstrap as AstValue<TExpression[], TExpression>);
}
if (metaObj.has('declarations')) {
const declarations = metaObj.getValue('declarations');
if (declarations.isFunction()) {
meta.containsForwardDecls = true;
meta.declarations = wrapReferences(unwrapForwardRefs(declarations));
} else meta.declarations = wrapReferences(declarations as AstValue<TExpression[], TExpression>);
}
if (metaObj.has('imports')) {
const imports = metaObj.getValue('imports');
if (imports.isFunction()) {
meta.containsForwardDecls = true;
meta.imports = wrapReferences(unwrapForwardRefs(imports));
} else meta.imports = wrapReferences(imports as AstValue<TExpression[], TExpression>);
}
if (metaObj.has('exports')) {
const exports = metaObj.getValue('exports');
if (exports.isFunction()) {
meta.containsForwardDecls = true;
meta.exports = wrapReferences(unwrapForwardRefs(exports));
} else meta.exports = wrapReferences(exports as AstValue<TExpression[], TExpression>);
}
if (metaObj.has('schemas')) {
const schemas = metaObj.getValue('schemas');
meta.schemas = wrapReferences(schemas as AstValue<TExpression[], TExpression>);
}
return meta;
}
/**
* Extract an array from the body of the function.
*
* If `field` is `function() { return [exp1, exp2, exp3]; }` then we return `[exp1, exp2, exp3]`.
*
*/
function unwrapForwardRefs<TExpression>(
field: AstValue<unknown, TExpression>,
): AstValue<TExpression[], TExpression> {
return (field as AstValue<Function, TExpression>).getFunctionReturnValue();
}
/**
* Wrap the array of expressions into an array of R3 references.
*/
function wrapReferences<TExpression>(values: AstValue<TExpression[], TExpression>): R3Reference[] {
return values.getArray().map((i) => wrapReference(i.getOpaque()));
}
| {
"end_byte": 4713,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_ng_module_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/util.ts_0_4364 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
createMayBeForwardRefExpression,
ForwardRefHandling,
MaybeForwardRefExpression,
outputAst as o,
R3DeclareDependencyMetadata,
R3DependencyMetadata,
R3Reference,
} from '@angular/compiler';
import {AstObject, AstValue} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import semver from 'semver';
export const PLACEHOLDER_VERSION = '0.0.0-PLACEHOLDER';
export function wrapReference<TExpression>(wrapped: o.WrappedNodeExpr<TExpression>): R3Reference {
return {value: wrapped, type: wrapped};
}
/**
* Parses the value of an enum from the AST value's symbol name.
*/
export function parseEnum<TExpression, TEnum>(
value: AstValue<unknown, TExpression>,
Enum: TEnum,
): TEnum[keyof TEnum] {
const symbolName = value.getSymbolName();
if (symbolName === null) {
throw new FatalLinkerError(value.expression, 'Expected value to have a symbol name');
}
const enumValue = Enum[symbolName as keyof typeof Enum];
if (enumValue === undefined) {
throw new FatalLinkerError(value.expression, `Unsupported enum value for ${Enum}`);
}
return enumValue;
}
/**
* Parse a dependency structure from an AST object.
*/
export function getDependency<TExpression>(
depObj: AstObject<R3DeclareDependencyMetadata, TExpression>,
): R3DependencyMetadata {
const isAttribute = depObj.has('attribute') && depObj.getBoolean('attribute');
const token = depObj.getOpaque('token');
// Normally `attribute` is a string literal and so its `attributeNameType` is the same string
// literal. If the `attribute` is some other expression, the `attributeNameType` would be the
// `unknown` type. It is not possible to generate this when linking, since it only deals with JS
// and not typings. When linking the existence of the `attributeNameType` only acts as a marker to
// change the injection instruction that is generated, so we just pass the literal string
// `"unknown"`.
const attributeNameType = isAttribute ? o.literal('unknown') : null;
return {
token,
attributeNameType,
host: depObj.has('host') && depObj.getBoolean('host'),
optional: depObj.has('optional') && depObj.getBoolean('optional'),
self: depObj.has('self') && depObj.getBoolean('self'),
skipSelf: depObj.has('skipSelf') && depObj.getBoolean('skipSelf'),
};
}
/**
* Return an `R3ProviderExpression` that represents either the extracted type reference expression
* from a `forwardRef` function call, or the type itself.
*
* For example, the expression `forwardRef(function() { return FooDir; })` returns `FooDir`. Note
* that this expression is required to be wrapped in a closure, as otherwise the forward reference
* would be resolved before initialization.
*
* If there is no forwardRef call expression then we just return the opaque type.
*/
export function extractForwardRef<TExpression>(
expr: AstValue<unknown, TExpression>,
): MaybeForwardRefExpression<o.WrappedNodeExpr<TExpression>> {
if (!expr.isCallExpression()) {
return createMayBeForwardRefExpression(expr.getOpaque(), ForwardRefHandling.None);
}
const callee = expr.getCallee();
if (callee.getSymbolName() !== 'forwardRef') {
throw new FatalLinkerError(
callee.expression,
'Unsupported expression, expected a `forwardRef()` call or a type reference',
);
}
const args = expr.getArguments();
if (args.length !== 1) {
throw new FatalLinkerError(
expr,
'Unsupported `forwardRef(fn)` call, expected a single argument',
);
}
const wrapperFn = args[0] as AstValue<Function, TExpression>;
if (!wrapperFn.isFunction()) {
throw new FatalLinkerError(
wrapperFn,
'Unsupported `forwardRef(fn)` call, expected its argument to be a function',
);
}
return createMayBeForwardRefExpression(
wrapperFn.getFunctionReturnValue().getOpaque(),
ForwardRefHandling.Unwrapped,
);
}
const STANDALONE_IS_DEFAULT_RANGE = new semver.Range(`>= 19.0.0 || ${PLACEHOLDER_VERSION}`, {
includePrerelease: true,
});
export function getDefaultStandaloneValue(version: string): boolean {
return STANDALONE_IS_DEFAULT_RANGE.test(version);
}
| {
"end_byte": 4364,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/util.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_injectable_linker_1.ts_0_2486 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileInjectable,
ConstantPool,
createMayBeForwardRefExpression,
ForwardRefHandling,
outputAst as o,
R3DeclareInjectableMetadata,
R3InjectableMetadata,
R3PartialDeclaration,
} from '@angular/compiler';
import {AstObject} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {extractForwardRef, getDependency, wrapReference} from './util';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareInjectable()` call expressions.
*/
export class PartialInjectableLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
): LinkedDefinition {
const meta = toR3InjectableMeta(metaObj);
return compileInjectable(meta, /* resolveForwardRefs */ false);
}
}
/**
* Derives the `R3InjectableMetadata` structure from the AST object.
*/
export function toR3InjectableMeta<TExpression>(
metaObj: AstObject<R3DeclareInjectableMetadata, TExpression>,
): R3InjectableMetadata {
const typeExpr = metaObj.getValue('type');
const typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new FatalLinkerError(
typeExpr.expression,
'Unsupported type, its name could not be determined',
);
}
const meta: R3InjectableMetadata = {
name: typeName,
type: wrapReference(typeExpr.getOpaque()),
typeArgumentCount: 0,
providedIn: metaObj.has('providedIn')
? extractForwardRef(metaObj.getValue('providedIn'))
: createMayBeForwardRefExpression(o.literal(null), ForwardRefHandling.None),
};
if (metaObj.has('useClass')) {
meta.useClass = extractForwardRef(metaObj.getValue('useClass'));
}
if (metaObj.has('useFactory')) {
meta.useFactory = metaObj.getOpaque('useFactory');
}
if (metaObj.has('useExisting')) {
meta.useExisting = extractForwardRef(metaObj.getValue('useExisting'));
}
if (metaObj.has('useValue')) {
meta.useValue = extractForwardRef(metaObj.getValue('useValue'));
}
if (metaObj.has('deps')) {
meta.deps = metaObj.getArray('deps').map((dep) => getDependency(dep.getObject()));
}
return meta;
}
| {
"end_byte": 2486,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_injectable_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_class_metadata_async_linker_1.ts_0_2020 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileOpaqueAsyncClassMetadata,
ConstantPool,
R3ClassMetadata,
R3DeclareClassMetadataAsync,
} from '@angular/compiler';
import {AstObject, AstValue} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkedDefinition, PartialLinker} from './partial_linker';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareClassMetadataAsync()` call expressions.
*/
export class PartialClassMetadataAsyncLinkerVersion1<TExpression>
implements PartialLinker<TExpression>
{
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3DeclareClassMetadataAsync, TExpression>,
): LinkedDefinition {
const resolveMetadataKey = 'resolveMetadata';
const resolveMetadata = metaObj.getValue(resolveMetadataKey) as unknown as AstValue<
Function,
TExpression
>;
if (!resolveMetadata.isFunction()) {
throw new FatalLinkerError(
resolveMetadata,
`Unsupported \`${resolveMetadataKey}\` value. Expected a function.`,
);
}
const dependencyResolverFunction = metaObj.getOpaque('resolveDeferredDeps');
const deferredSymbolNames = resolveMetadata
.getFunctionParameters()
.map((p) => p.getSymbolName()!);
const returnValue = resolveMetadata.getFunctionReturnValue<R3ClassMetadata>().getObject();
const metadata: R3ClassMetadata = {
type: metaObj.getOpaque('type'),
decorators: returnValue.getOpaque('decorators'),
ctorParameters: returnValue.getOpaque('ctorParameters'),
propDecorators: returnValue.getOpaque('propDecorators'),
};
return {
expression: compileOpaqueAsyncClassMetadata(
metadata,
dependencyResolverFunction,
deferredSymbolNames,
),
statements: [],
};
}
}
| {
"end_byte": 2020,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_class_metadata_async_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_linker_selector.ts_0_6129 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import semver from 'semver';
import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system';
import {Logger} from '../../../../src/ngtsc/logging';
import {createGetSourceFile} from '../get_source_file';
import {LinkerEnvironment} from '../linker_environment';
import {PartialClassMetadataAsyncLinkerVersion1} from './partial_class_metadata_async_linker_1';
import {PartialClassMetadataLinkerVersion1} from './partial_class_metadata_linker_1';
import {PartialComponentLinkerVersion1} from './partial_component_linker_1';
import {PartialDirectiveLinkerVersion1} from './partial_directive_linker_1';
import {PartialFactoryLinkerVersion1} from './partial_factory_linker_1';
import {PartialInjectableLinkerVersion1} from './partial_injectable_linker_1';
import {PartialInjectorLinkerVersion1} from './partial_injector_linker_1';
import {PartialLinker} from './partial_linker';
import {PartialNgModuleLinkerVersion1} from './partial_ng_module_linker_1';
import {PartialPipeLinkerVersion1} from './partial_pipe_linker_1';
import {PLACEHOLDER_VERSION} from './util';
export const ɵɵngDeclareDirective = 'ɵɵngDeclareDirective';
export const ɵɵngDeclareClassMetadata = 'ɵɵngDeclareClassMetadata';
export const ɵɵngDeclareComponent = 'ɵɵngDeclareComponent';
export const ɵɵngDeclareFactory = 'ɵɵngDeclareFactory';
export const ɵɵngDeclareInjectable = 'ɵɵngDeclareInjectable';
export const ɵɵngDeclareInjector = 'ɵɵngDeclareInjector';
export const ɵɵngDeclareNgModule = 'ɵɵngDeclareNgModule';
export const ɵɵngDeclarePipe = 'ɵɵngDeclarePipe';
export const ɵɵngDeclareClassMetadataAsync = 'ɵɵngDeclareClassMetadataAsync';
export const declarationFunctions = [
ɵɵngDeclareDirective,
ɵɵngDeclareClassMetadata,
ɵɵngDeclareComponent,
ɵɵngDeclareFactory,
ɵɵngDeclareInjectable,
ɵɵngDeclareInjector,
ɵɵngDeclareNgModule,
ɵɵngDeclarePipe,
ɵɵngDeclareClassMetadataAsync,
];
export interface LinkerRange<TExpression> {
range: semver.Range;
linker: PartialLinker<TExpression>;
}
/**
* Create a mapping between partial-declaration call name and collections of partial-linkers.
*
* Each collection of partial-linkers will contain a version range that will be matched against the
* `minVersion` of the partial-declaration. (Additionally, a partial-linker may modify its behaviour
* internally based on the `version` property of the declaration.)
*
* Versions should be sorted in ascending order. The most recent partial-linker will be used as the
* fallback linker if none of the other version ranges match. For example:
*
* ```
* {range: getRange('<=', '13.0.0'), linker PartialDirectiveLinkerVersion2(...) },
* {range: getRange('<=', '13.1.0'), linker PartialDirectiveLinkerVersion3(...) },
* {range: getRange('<=', '14.0.0'), linker PartialDirectiveLinkerVersion4(...) },
* {range: LATEST_VERSION_RANGE, linker: new PartialDirectiveLinkerVersion1(...)},
* ```
*
* If the `LATEST_VERSION_RANGE` is `<=15.0.0` then the fallback linker would be
* `PartialDirectiveLinkerVersion1` for any version greater than `15.0.0`.
*
* When there is a change to a declaration interface that requires a new partial-linker, the
* `minVersion` of the partial-declaration should be updated, the new linker implementation should
* be added to the end of the collection, and the version of the previous linker should be updated.
*/
export function createLinkerMap<TStatement, TExpression>(
environment: LinkerEnvironment<TStatement, TExpression>,
sourceUrl: AbsoluteFsPath,
code: string,
): Map<string, LinkerRange<TExpression>[]> {
const linkers = new Map<string, LinkerRange<TExpression>[]>();
const LATEST_VERSION_RANGE = getRange('<=', PLACEHOLDER_VERSION);
linkers.set(ɵɵngDeclareDirective, [
{range: LATEST_VERSION_RANGE, linker: new PartialDirectiveLinkerVersion1(sourceUrl, code)},
]);
linkers.set(ɵɵngDeclareClassMetadataAsync, [
{range: LATEST_VERSION_RANGE, linker: new PartialClassMetadataAsyncLinkerVersion1()},
]);
linkers.set(ɵɵngDeclareClassMetadata, [
{range: LATEST_VERSION_RANGE, linker: new PartialClassMetadataLinkerVersion1()},
]);
linkers.set(ɵɵngDeclareComponent, [
{
range: LATEST_VERSION_RANGE,
linker: new PartialComponentLinkerVersion1(
createGetSourceFile(sourceUrl, code, environment.sourceFileLoader),
sourceUrl,
code,
),
},
]);
linkers.set(ɵɵngDeclareFactory, [
{range: LATEST_VERSION_RANGE, linker: new PartialFactoryLinkerVersion1()},
]);
linkers.set(ɵɵngDeclareInjectable, [
{range: LATEST_VERSION_RANGE, linker: new PartialInjectableLinkerVersion1()},
]);
linkers.set(ɵɵngDeclareInjector, [
{range: LATEST_VERSION_RANGE, linker: new PartialInjectorLinkerVersion1()},
]);
linkers.set(ɵɵngDeclareNgModule, [
{
range: LATEST_VERSION_RANGE,
linker: new PartialNgModuleLinkerVersion1(environment.options.linkerJitMode),
},
]);
linkers.set(ɵɵngDeclarePipe, [
{range: LATEST_VERSION_RANGE, linker: new PartialPipeLinkerVersion1()},
]);
return linkers;
}
/**
* A helper that selects the appropriate `PartialLinker` for a given declaration.
*
* The selection is made from a database of linker instances, chosen if their given semver range
* satisfies the `minVersion` of the partial declaration to be linked.
*
* Note that the ranges are checked in order, and the first matching range will be selected. So
* ranges should be most restrictive first. In practice, since ranges are always `<=X.Y.Z` this
* means that ranges should be in ascending order.
*
* Note that any "pre-release" versions are stripped from ranges. Therefore if a `minVersion` is
* `11.1.0-next.1` then this would match `11.1.0-next.2` and also `12.0.0-next.1`. (This is
* different to standard semver range checking, where pre-release versions do not cross full version
* boundaries.)
*/
export class PartialLinkerSelector<TExpression> {
constructor(
pr | {
"end_byte": 6129,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_linker_selector.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_linker_selector.ts_6130_9280 | vate readonly linkers: Map<string, LinkerRange<TExpression>[]>,
private readonly logger: Logger,
private readonly unknownDeclarationVersionHandling: 'ignore' | 'warn' | 'error',
) {}
/**
* Returns true if there are `PartialLinker` classes that can handle functions with this name.
*/
supportsDeclaration(functionName: string): boolean {
return this.linkers.has(functionName);
}
/**
* Returns the `PartialLinker` that can handle functions with the given name and version.
* Throws an error if there is none.
*/
getLinker(functionName: string, minVersion: string, version: string): PartialLinker<TExpression> {
if (!this.linkers.has(functionName)) {
throw new Error(`Unknown partial declaration function ${functionName}.`);
}
const linkerRanges = this.linkers.get(functionName)!;
if (version === PLACEHOLDER_VERSION) {
// Special case if the `version` is the same as the current compiler version.
// This helps with compliance tests where the version placeholders have not been replaced.
return linkerRanges[linkerRanges.length - 1].linker;
}
const declarationRange = getRange('>=', minVersion);
for (const {range: linkerRange, linker} of linkerRanges) {
if (semver.intersects(declarationRange, linkerRange)) {
return linker;
}
}
const message =
`This application depends upon a library published using Angular version ${version}, ` +
`which requires Angular version ${minVersion} or newer to work correctly.\n` +
`Consider upgrading your application to use a more recent version of Angular.`;
if (this.unknownDeclarationVersionHandling === 'error') {
throw new Error(message);
} else if (this.unknownDeclarationVersionHandling === 'warn') {
this.logger.warn(`${message}\nAttempting to continue using this version of Angular.`);
}
// No linker was matched for this declaration, so just use the most recent one.
return linkerRanges[linkerRanges.length - 1].linker;
}
}
/**
* Compute a semver Range from the `version` and comparator.
*
* The range is computed as any version greater/less than or equal to the given `versionStr`
* depending upon the `comparator` (ignoring any prerelease versions).
*
* @param comparator a string that determines whether the version specifies a minimum or a maximum
* range.
* @param versionStr the version given in the partial declaration
* @returns A semver range for the provided `version` and comparator.
*/
function getRange(comparator: '<=' | '>=', versionStr: string): semver.Range {
// If the provided version is exactly `0.0.0` then we are known to be running with an unpublished
// version of angular and assume that all ranges are compatible.
if (versionStr === '0.0.0' && (PLACEHOLDER_VERSION as string) === '0.0.0') {
return new semver.Range('*.*.*');
}
const version = new semver.SemVer(versionStr);
// Wipe out any prerelease versions
version.prerelease = [];
return new semver.Range(`${comparator}${version.format()}`);
}
| {
"end_byte": 9280,
"start_byte": 6130,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_linker_selector.ts"
} |
angular/packages/compiler-cli/private/babel.d.ts_0_1684 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// The following modules are declared to work around a limitation in tsc_wrapped's `strict_deps`
// check. Since Babel uses scoped packages, the corresponding lookup for declaration files in the
// `node_modules/@types/` directory follows a special strategy: the `@types` package has to be
// named `{scope}__{package}`, e.g. `@types/babel__generator`. When `tsc` performs module
// resolution for the `@babel/generator` module specifier, it will first try the `paths` mappings
// but resolution through path mappings does _not_ apply this special naming convention rule for
// `@types` packages, `tsc` only applies that rule in its `@types` resolution step. Consequently,
// the path mapping into Bazel's private `node_modules` directory fails to resolve, causing `tsc`
// to find the nearest `node_modules` directory in an ancestor directory of the origin source
// file. This finds the `node_modules` directory in the workspace, _not_ Bazel's private copy of
// `node_modules` and therefore the `@types` end up being resolved from a `node_modules` tree
// that is not governed by Bazel, and therefore not expected by the `strict_deps` rule.
// Declaring the modules here allows `strict_deps` to always find a declaration of the modules
// in an input file to the compilation, therefore accepting the module import.
declare module '@babel/core' {
export * from '@types/babel__core';
}
declare module '@babel/generator' {
export { default } from '@types/babel__generator';
}
| {
"end_byte": 1684,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/babel.d.ts"
} |
angular/packages/compiler-cli/private/bazel.ts_0_364 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview The API from compiler-cli that the `@angular/bazel`
* package requires for ngc-wrapped.
*/
export {PerfPhase} from '../src/ngtsc/perf';
| {
"end_byte": 364,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/bazel.ts"
} |
angular/packages/compiler-cli/private/tooling.ts_0_1239 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview
* This file is used as a private API channel to shared Angular FW APIs with @angular/cli.
*
* Any changes to this file should be discussed with the Angular CLI team.
*/
import ts from 'typescript';
import {angularJitApplicationTransform} from '../src/ngtsc/transform/jit/index';
/**
* Known values for global variables in `@angular/core` that Terser should set using
* https://github.com/terser-js/terser#conditional-compilation
*/
export const GLOBAL_DEFS_FOR_TERSER = {
ngDevMode: false,
ngI18nClosureMode: false,
};
export const GLOBAL_DEFS_FOR_TERSER_WITH_AOT = {
...GLOBAL_DEFS_FOR_TERSER,
ngJitMode: false,
};
/**
* JIT transform used by the Angular CLI.
*
* NOTE: Signature is explicitly captured here to highlight the
* contract various Angular CLI versions are relying on.
*/
export const constructorParametersDownlevelTransform = (
program: ts.Program,
isCore = false,
): ts.TransformerFactory<ts.SourceFile> => {
return angularJitApplicationTransform(program, isCore);
};
| {
"end_byte": 1239,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/tooling.ts"
} |
angular/packages/compiler-cli/private/migrations.ts_0_914 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview The API from compiler-cli that the `@angular/core`
* package requires for migration schematics.
*/
export {forwardRefResolver} from '../src/ngtsc/annotations';
export {AbsoluteFsPath} from '../src/ngtsc/file_system';
export {Reference} from '../src/ngtsc/imports';
export {
DynamicValue,
PartialEvaluator,
ResolvedValue,
ResolvedValueMap,
StaticInterpreter,
} from '../src/ngtsc/partial_evaluator';
export {reflectObjectLiteral, TypeScriptReflectionHost} from '../src/ngtsc/reflection';
export {
PotentialImport,
PotentialImportKind,
PotentialImportMode,
TemplateTypeChecker,
} from '../src/ngtsc/typecheck/api';
export {ImportManager} from '../src/ngtsc/translator';
| {
"end_byte": 914,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/migrations.ts"
} |
angular/packages/compiler-cli/private/localize.ts_0_456 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview The API from compiler-cli that the `@angular/localize`
* package requires.
*/
export * from '../src/ngtsc/logging';
export * from '../src/ngtsc/file_system';
export {SourceFile, SourceFileLoader} from '../src/ngtsc/sourcemaps';
| {
"end_byte": 456,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/localize.ts"
} |
angular/packages/compiler-cli/private/README.md_0_726 | This is a directory defining the `@angular/compiler-cli/private` entry-point. The entry-point can be used to
expose code that is needed by other Angular framework packages, without having to expose code through the primary
entry-point.
The primary entry-point has a couple of downsides when it comes to cross-package imports:
* It exports various other things that will end up creating additional type dependencies. e.g. when
the Angular localize package relies on it, it might end up accidentally relying on `@types/node`.
* The primary entry-point has a larger build graph, slowing down local development as much more things
can invalidate the dependent targets. A smaller subset leads to faster incremental builds. | {
"end_byte": 726,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/README.md"
} |
angular/packages/compiler-cli/private/BUILD.bazel_0_829 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "private",
srcs = glob(["*.ts"]),
deps = [
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/logging",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/sourcemaps",
"//packages/compiler-cli/src/ngtsc/transform/jit",
"//packages/compiler-cli/src/ngtsc/translator",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"@npm//typescript",
],
)
| {
"end_byte": 829,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/private/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/BUILD.bazel_0_534 | load("//tools:defaults.bzl", "nodejs_binary")
package(default_visibility = ["//visibility:public"])
nodejs_binary(
name = "ngc_bin",
data = [
"//packages/compiler-cli",
"@npm//chokidar",
"@npm//reflect-metadata",
],
entry_point = "//packages/compiler-cli:src/main.ts",
)
nodejs_binary(
name = "ng_xi18n",
data = [
"//packages/compiler-cli",
"@npm//chokidar",
"@npm//reflect-metadata",
],
entry_point = "//packages/compiler-cli:src/extract_i18n.ts",
)
| {
"end_byte": 534,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/BUILD.bazel_0_316 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "app",
srcs = glob(
[
"src/**/*.ts",
],
),
module_name = "app_built",
tags = [],
deps = [
"//packages/core",
"@npm//rxjs",
],
)
| {
"end_byte": 316,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/module_spec.ts_0_2190 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
forwardRef,
Injectable,
InjectionToken,
Injector,
NgModule,
ɵcreateInjector as createInjector,
} from '@angular/core';
import {AOT_TOKEN, AotModule, AotService} from 'app_built/src/module';
describe('NgModule', () => {
describe('AOT', () => {
let injector: Injector;
beforeEach(() => {
injector = createInjector(AotModule);
});
it('works', () => {
expect(injector.get(AotService) instanceof AotService).toBeTruthy();
});
it('merges imports and exports', () => {
expect(injector.get(AOT_TOKEN)).toEqual('exports');
});
});
describe('JIT', () => {
@Injectable({providedIn: null})
class Service {}
@NgModule({
providers: [Service],
})
class JitModule {}
@NgModule({
imports: [JitModule],
})
class JitAppModule {}
it('works', () => {
createInjector(JitAppModule);
});
it('throws an error on circular module dependencies', () => {
@NgModule({
imports: [forwardRef(() => BModule)],
})
class AModule {}
@NgModule({
imports: [AModule],
})
class BModule {}
expect(() => createInjector(AModule)).toThrowError(
'NG0200: Circular dependency in DI detected for AModule. ' +
'Dependency path: AModule > BModule > AModule. ' +
'Find more at https://angular.dev/errors/NG0200',
);
});
it('merges imports and exports', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@NgModule({
providers: [{provide: TOKEN, useValue: 'provided from A'}],
})
class AModule {}
@NgModule({
providers: [{provide: TOKEN, useValue: 'provided from B'}],
})
class BModule {}
@NgModule({
imports: [AModule],
exports: [BModule],
})
class CModule {}
const injector = createInjector(CModule);
expect(injector.get(TOKEN)).toEqual('provided from B');
});
});
});
| {
"end_byte": 2190,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/module_spec.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/BUILD.bazel_0_539 | 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/integrationtest/bazel/injector_def/ivy_build/app",
"//packages/core",
"//packages/private/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
| {
"end_byte": 539,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/test/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/src/module.ts_0_793 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, InjectionToken, NgModule} from '@angular/core';
export const AOT_TOKEN = new InjectionToken<string>('TOKEN');
@Injectable()
export class AotService {}
@NgModule({
providers: [AotService],
})
export class AotServiceModule {}
@NgModule({
providers: [{provide: AOT_TOKEN, useValue: 'imports'}],
})
export class AotImportedModule {}
@NgModule({
providers: [{provide: AOT_TOKEN, useValue: 'exports'}],
})
export class AotExportedModule {}
@NgModule({
imports: [AotServiceModule, AotImportedModule],
exports: [AotExportedModule],
})
export class AotModule {}
| {
"end_byte": 793,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injector_def/ivy_build/app/src/module.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/lib2/module.ts_0_770 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injector, NgModule} from '@angular/core';
import {Lib1Module, Service} from 'lib1_built/module';
@Component({
selector: 'lib2-cmp',
template: '{{instance1}}:{{instance2}}',
standalone: false,
})
export class Lib2Cmp {
instance1: number = -1;
instance2: number = -1;
constructor(service: Service, injector: Injector) {
this.instance1 = service.instance;
this.instance2 = injector.get(Service).instance;
}
}
@NgModule({
declarations: [Lib2Cmp],
exports: [Lib2Cmp],
imports: [Lib1Module],
})
export class Lib2Module {}
| {
"end_byte": 770,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/lib2/module.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/lib2/BUILD.bazel_0_376 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "lib2",
srcs = glob(
[
"**/*.ts",
],
),
module_name = "lib2_built",
deps = [
"//packages/compiler-cli/integrationtest/bazel/injectable_def/lib1",
"//packages/core",
"@npm//rxjs",
],
)
| {
"end_byte": 376,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/lib2/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/BUILD.bazel_0_539 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "app",
testonly = True,
srcs = glob(
[
"src/**/*.ts",
],
),
module_name = "app_built",
deps = [
"//packages/compiler-cli/integrationtest/bazel/injectable_def/lib2",
"//packages/core",
"//packages/platform-browser",
"//packages/platform-server",
"//packages/router",
"@npm//reflect-metadata",
"@npm//rxjs",
],
)
| {
"end_byte": 539,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/BUILD.bazel_0_726 | 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/integrationtest/bazel/injectable_def/app",
"//packages/core",
"//packages/core/testing",
"//packages/platform-server",
"//packages/private/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
"//packages/platform-server",
"//packages/platform-server/testing",
"//packages/private/testing",
],
)
| {
"end_byte": 726,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/BUILD.bazel"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/app_spec.ts_0_5988 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injectable, INJECTOR, NgModule} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {renderModule} from '@angular/platform-server';
import {BasicAppModule} from 'app_built/src/basic';
import {DepAppModule} from 'app_built/src/dep';
import {HierarchyAppModule} from 'app_built/src/hierarchy';
import {RootAppModule} from 'app_built/src/root';
import {SelfAppModule} from 'app_built/src/self';
import {StringAppModule} from 'app_built/src/string';
import {TokenAppModule} from 'app_built/src/token';
describe('ngInjectableDef Bazel Integration', () => {
it('works in AOT', (done) => {
renderModule(BasicAppModule, {
document: '<id-app></id-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>0:0<\//);
done();
});
});
it('@Self() works in component hierarchies', (done) => {
renderModule(HierarchyAppModule, {
document: '<hierarchy-app></hierarchy-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>false<\//);
done();
});
});
it('@Optional() Self() resolves to @Injectable() scoped service', (done) => {
renderModule(SelfAppModule, {
document: '<self-app></self-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>true<\//);
done();
});
});
it('InjectionToken ngInjectableDef works', (done) => {
renderModule(TokenAppModule, {
document: '<token-app></token-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>fromToken<\//);
done();
});
});
it('APP_ROOT_SCOPE works', (done) => {
renderModule(RootAppModule, {
document: '<root-app></root-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>true:false<\//);
done();
});
});
it('can inject dependencies', (done) => {
renderModule(DepAppModule, {
document: '<dep-app></dep-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>true<\//);
done();
});
});
it('string tokens work', (done) => {
renderModule(StringAppModule, {
document: '<string-app></string-app>',
url: '/',
}).then((html) => {
expect(html).toMatch(/>works<\//);
done();
});
});
it('allows provider override in JIT for root-scoped @Injectables', () => {
@Injectable({
providedIn: 'root',
useValue: new Service('default'),
})
class Service {
constructor(readonly value: string) {}
}
TestBed.configureTestingModule({});
TestBed.overrideProvider(Service, {useValue: new Service('overridden')});
expect(TestBed.inject(Service).value).toEqual('overridden');
});
it('allows provider override in JIT for module-scoped @Injectables', () => {
@NgModule()
class Module {}
@Injectable({
providedIn: Module,
useValue: new Service('default'),
})
class Service {
constructor(readonly value: string) {}
}
TestBed.configureTestingModule({
imports: [Module],
});
TestBed.overrideProvider(Service, {useValue: new Service('overridden')});
expect(TestBed.inject(Service).value).toEqual('overridden');
});
it('does not override existing ɵprov', () => {
@Injectable({
providedIn: 'root',
useValue: new Service(false),
})
class Service {
constructor(public value: boolean) {}
static ɵprov = {
providedIn: 'root',
factory: () => new Service(true),
token: Service,
};
}
TestBed.configureTestingModule({});
expect(TestBed.inject(Service).value).toEqual(true);
});
it('does not override existing ɵprov in case of inheritance', () => {
@Injectable({
providedIn: 'root',
useValue: new ParentService(false),
})
class ParentService {
constructor(public value: boolean) {}
}
// ChildServices extends ParentService but does not have @Injectable
class ChildService extends ParentService {}
TestBed.configureTestingModule({});
// We are asserting that system throws an error, rather than taking the inherited annotation.
expect(() => TestBed.inject(ChildService).value).toThrowError(/ChildService/);
});
it('uses legacy `ngInjectable` property even if it inherits from a class that has `ɵprov` property', () => {
@Injectable({
providedIn: 'root',
useValue: new ParentService('parent'),
})
class ParentService {
constructor(public value: string) {}
}
// ChildServices extends ParentService but does not have @Injectable
class ChildService extends ParentService {
constructor(value: string) {
super(value);
}
static ngInjectableDef = {
providedIn: 'root',
factory: () => new ChildService('child'),
token: ChildService,
};
}
TestBed.configureTestingModule({});
// We are asserting that system throws an error, rather than taking the inherited
// annotation.
expect(TestBed.inject(ChildService).value).toEqual('child');
});
it('NgModule injector understands requests for INJECTABLE', () => {
TestBed.configureTestingModule({
providers: [{provide: 'foo', useValue: 'bar'}],
});
expect(TestBed.inject(INJECTOR).get('foo')).toEqual('bar');
});
it('Component injector understands requests for INJECTABLE', () => {
@Component({
selector: 'test-cmp',
template: 'test',
providers: [{provide: 'foo', useValue: 'bar'}],
standalone: false,
})
class TestCmp {}
TestBed.configureTestingModule({
declarations: [TestCmp],
});
const fixture = TestBed.createComponent(TestCmp);
expect(fixture.componentRef.injector.get(INJECTOR).get('foo')).toEqual('bar');
});
});
| {
"end_byte": 5988,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/test/app_spec.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/root_service.ts_0_310 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class Service {}
| {
"end_byte": 310,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/root_service.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/string.ts_0_940 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Inject, Injectable, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
@Component({
selector: 'string-app',
template: '{{data}}',
standalone: false,
})
export class AppComponent {
data: string;
constructor(service: Service) {
this.data = service.data;
}
}
@NgModule({
imports: [BrowserModule, ServerModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [{provide: 'someStringToken', useValue: 'works'}],
})
export class StringAppModule {}
@Injectable({providedIn: StringAppModule})
export class Service {
constructor(@Inject('someStringToken') readonly data: string) {}
}
| {
"end_byte": 940,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/string.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/root_lazy.ts_0_905 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule, Optional, Self} from '@angular/core';
import {RouterModule} from '@angular/router';
import {Service} from './root_service';
@Component({
selector: 'lazy-route',
template: '{{service}}:{{serviceInLazyInjector}}',
standalone: false,
})
export class RouteComponent {
service: boolean;
serviceInLazyInjector: boolean;
constructor(@Optional() service: Service, @Optional() @Self() lazyService: Service) {
this.service = !!service;
this.serviceInLazyInjector = !!lazyService;
}
}
@NgModule({
declarations: [RouteComponent],
imports: [RouterModule.forChild([{path: '', pathMatch: 'prefix', component: RouteComponent}])],
})
export class LazyModule {}
| {
"end_byte": 905,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/root_lazy.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/root.ts_0_991 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
import {RouterModule} from '@angular/router';
import {LazyModule} from './root_lazy';
@Component({
selector: 'root-app',
template: '<router-outlet></router-outlet>',
standalone: false,
})
export class AppComponent {}
export function children(): any {
console.error('children', LazyModule);
return LazyModule;
}
@NgModule({
imports: [
BrowserModule,
ServerModule,
RouterModule.forRoot([{path: '', pathMatch: 'prefix', loadChildren: children}], {
initialNavigation: 'enabledBlocking',
}),
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class RootAppModule {}
| {
"end_byte": 991,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/root.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/basic.ts_0_701 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
import {Lib2Module} from 'lib2_built/module';
@Component({
selector: 'id-app',
template: '<lib2-cmp></lib2-cmp>',
standalone: false,
})
export class AppComponent {}
@NgModule({
imports: [Lib2Module, BrowserModule, ServerModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class BasicAppModule {}
| {
"end_byte": 701,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/basic.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/self.ts_0_994 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injectable, NgModule, Optional, Self} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
@Injectable()
export class NormalService {
constructor(@Optional() @Self() readonly shakeable: ShakeableService | null) {}
}
@Component({
selector: 'self-app',
template: '{{found}}',
standalone: false,
})
export class AppComponent {
found: boolean;
constructor(service: NormalService) {
this.found = !!service.shakeable;
}
}
@NgModule({
imports: [BrowserModule, ServerModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [NormalService],
})
export class SelfAppModule {}
@Injectable({providedIn: SelfAppModule})
export class ShakeableService {}
| {
"end_byte": 994,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/self.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/hierarchy.ts_0_995 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injectable, NgModule, Optional, Self} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
@Injectable()
export class Service {}
@Component({
selector: 'hierarchy-app',
template: '<child-cmp></child-cmp>',
providers: [Service],
standalone: false,
})
export class AppComponent {}
@Component({
selector: 'child-cmp',
template: '{{found}}',
standalone: false,
})
export class ChildComponent {
found: boolean;
constructor(@Optional() @Self() service: Service | null) {
this.found = !!service;
}
}
@NgModule({
imports: [BrowserModule, ServerModule],
declarations: [AppComponent, ChildComponent],
bootstrap: [AppComponent],
})
export class HierarchyAppModule {}
| {
"end_byte": 995,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/hierarchy.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/index.ts_0_242 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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 {RootAppModule} from './root';
| {
"end_byte": 242,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/index.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/token.ts_0_1231 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
forwardRef,
Inject,
inject,
Injectable,
InjectionToken,
NgModule,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
export interface IService {
readonly dep: {readonly data: string};
}
@NgModule({})
export class TokenModule {}
export const TOKEN = new InjectionToken('test', {
providedIn: TokenModule,
factory: () => new Service(inject(Dep)),
});
@Component({
selector: 'token-app',
template: '{{data}}',
standalone: false,
})
export class AppComponent {
data: string;
constructor(@Inject(TOKEN) service: IService) {
this.data = service.dep.data;
}
}
@NgModule({
imports: [BrowserModule, ServerModule, TokenModule],
providers: [forwardRef(() => Dep)],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class TokenAppModule {}
@Injectable()
export class Dep {
readonly data = 'fromToken';
}
export class Service {
constructor(readonly dep: Dep) {}
}
| {
"end_byte": 1231,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/token.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/dep.ts_0_942 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injectable, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
@Injectable()
export class NormalService {}
@Component({
selector: 'dep-app',
template: '{{found}}',
standalone: false,
})
export class AppComponent {
found: boolean;
constructor(service: ShakeableService) {
this.found = !!service.normal;
}
}
@NgModule({
imports: [BrowserModule, ServerModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [NormalService],
})
export class DepAppModule {}
@Injectable({providedIn: DepAppModule})
export class ShakeableService {
constructor(readonly normal: NormalService) {}
}
| {
"end_byte": 942,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/app/src/dep.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/lib1/module.ts_0_433 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, NgModule} from '@angular/core';
@NgModule({})
export class Lib1Module {}
@Injectable({
providedIn: Lib1Module,
})
export class Service {
static instanceCount = 0;
instance = Service.instanceCount++;
}
| {
"end_byte": 433,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/lib1/module.ts"
} |
angular/packages/compiler-cli/integrationtest/bazel/injectable_def/lib1/BUILD.bazel_0_299 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "lib1",
srcs = glob(
[
"**/*.ts",
],
),
module_name = "lib1_built",
deps = [
"//packages/core",
"@npm//rxjs",
],
)
| {
"end_byte": 299,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/integrationtest/bazel/injectable_def/lib1/BUILD.bazel"
} |
angular/packages/compiler-cli/src/perform_compile.ts_0_7912 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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,
AbsoluteFsPath,
createFileSystemTsReadDirectoryFn,
FileSystem,
getFileSystem,
ReadonlyFileSystem,
} from '../src/ngtsc/file_system';
import {NgCompilerOptions} from './ngtsc/core/api';
import {replaceTsWithNgInErrors} from './ngtsc/diagnostics';
import * as api from './transformers/api';
import * as ng from './transformers/entry_points';
import {createMessageDiagnostic} from './transformers/util';
const defaultFormatHost: ts.FormatDiagnosticsHost = {
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
getCanonicalFileName: (fileName) => fileName,
getNewLine: () => ts.sys.newLine,
};
export function formatDiagnostics(
diags: ReadonlyArray<ts.Diagnostic>,
host: ts.FormatDiagnosticsHost = defaultFormatHost,
): string {
if (diags && diags.length) {
return diags
.map((diagnostic) =>
replaceTsWithNgInErrors(ts.formatDiagnosticsWithColorAndContext([diagnostic], host)),
)
.join('');
} else {
return '';
}
}
/** Used to read configuration files. */
export type ConfigurationHost = Pick<
ReadonlyFileSystem,
'readFile' | 'exists' | 'lstat' | 'resolve' | 'join' | 'dirname' | 'extname' | 'pwd' | 'readdir'
>;
export interface ParsedConfiguration {
project: string;
options: api.CompilerOptions;
rootNames: string[];
projectReferences?: readonly ts.ProjectReference[] | undefined;
emitFlags: api.EmitFlags;
errors: ts.Diagnostic[];
}
export function calcProjectFileAndBasePath(
project: string,
host: ConfigurationHost = getFileSystem(),
): {projectFile: AbsoluteFsPath; basePath: AbsoluteFsPath} {
const absProject = host.resolve(project);
const projectIsDir = host.lstat(absProject).isDirectory();
const projectFile = projectIsDir ? host.join(absProject, 'tsconfig.json') : absProject;
const projectDir = projectIsDir ? absProject : host.dirname(absProject);
const basePath = host.resolve(projectDir);
return {projectFile, basePath};
}
export function readConfiguration(
project: string,
existingOptions?: api.CompilerOptions,
host: ConfigurationHost = getFileSystem(),
): ParsedConfiguration {
try {
const fs = getFileSystem();
const readConfigFile = (configFile: string) =>
ts.readConfigFile(configFile, (file) => host.readFile(host.resolve(file)));
const readAngularCompilerOptions = (
configFile: string,
parentOptions: NgCompilerOptions = {},
): NgCompilerOptions => {
const {config, error} = readConfigFile(configFile);
if (error) {
// Errors are handled later on by 'parseJsonConfigFileContent'
return parentOptions;
}
// we are only interested into merging 'angularCompilerOptions' as
// other options like 'compilerOptions' are merged by TS
let existingNgCompilerOptions = {...config.angularCompilerOptions, ...parentOptions};
if (!config.extends) {
return existingNgCompilerOptions;
}
const extendsPaths: string[] =
typeof config.extends === 'string' ? [config.extends] : config.extends;
// Call readAngularCompilerOptions recursively to merge NG Compiler options
// Reverse the array so the overrides happen from right to left.
return [...extendsPaths].reverse().reduce((prevOptions, extendsPath) => {
const extendedConfigPath = getExtendedConfigPath(configFile, extendsPath, host, fs);
return extendedConfigPath === null
? prevOptions
: readAngularCompilerOptions(extendedConfigPath, prevOptions);
}, existingNgCompilerOptions);
};
const {projectFile, basePath} = calcProjectFileAndBasePath(project, host);
const configFileName = host.resolve(host.pwd(), projectFile);
const {config, error} = readConfigFile(projectFile);
if (error) {
return {
project,
errors: [error],
rootNames: [],
options: {},
emitFlags: api.EmitFlags.Default,
};
}
const existingCompilerOptions: api.CompilerOptions = {
genDir: basePath,
basePath,
...readAngularCompilerOptions(configFileName),
...existingOptions,
};
const parseConfigHost = createParseConfigHost(host, fs);
const {
options,
errors,
fileNames: rootNames,
projectReferences,
} = ts.parseJsonConfigFileContent(
config,
parseConfigHost,
basePath,
existingCompilerOptions,
configFileName,
);
let emitFlags = api.EmitFlags.Default;
if (!(options['skipMetadataEmit'] || options['flatModuleOutFile'])) {
emitFlags |= api.EmitFlags.Metadata;
}
if (options['skipTemplateCodegen']) {
emitFlags = emitFlags & ~api.EmitFlags.Codegen;
}
return {project: projectFile, rootNames, projectReferences, options, errors, emitFlags};
} catch (e) {
const errors: ts.Diagnostic[] = [
{
category: ts.DiagnosticCategory.Error,
messageText: (e as Error).stack ?? (e as Error).message,
file: undefined,
start: undefined,
length: undefined,
source: 'angular',
code: api.UNKNOWN_ERROR_CODE,
},
];
return {project: '', errors, rootNames: [], options: {}, emitFlags: api.EmitFlags.Default};
}
}
function createParseConfigHost(host: ConfigurationHost, fs = getFileSystem()): ts.ParseConfigHost {
return {
fileExists: host.exists.bind(host),
readDirectory: createFileSystemTsReadDirectoryFn(fs),
readFile: host.readFile.bind(host),
useCaseSensitiveFileNames: fs.isCaseSensitive(),
};
}
function getExtendedConfigPath(
configFile: string,
extendsValue: string,
host: ConfigurationHost,
fs: FileSystem,
): AbsoluteFsPath | null {
const result = getExtendedConfigPathWorker(configFile, extendsValue, host, fs);
if (result !== null) {
return result;
}
// Try to resolve the paths with a json extension append a json extension to the file in case if
// it is missing and the resolution failed. This is to replicate TypeScript behaviour, see:
// https://github.com/microsoft/TypeScript/blob/294a5a7d784a5a95a8048ee990400979a6bc3a1c/src/compiler/commandLineParser.ts#L2806
return getExtendedConfigPathWorker(configFile, `${extendsValue}.json`, host, fs);
}
function getExtendedConfigPathWorker(
configFile: string,
extendsValue: string,
host: ConfigurationHost,
fs: FileSystem,
): AbsoluteFsPath | null {
if (extendsValue.startsWith('.') || fs.isRooted(extendsValue)) {
const extendedConfigPath = host.resolve(host.dirname(configFile), extendsValue);
if (host.exists(extendedConfigPath)) {
return extendedConfigPath;
}
} else {
const parseConfigHost = createParseConfigHost(host, fs);
// Path isn't a rooted or relative path, resolve like a module.
const {resolvedModule} = ts.nodeModuleNameResolver(
extendsValue,
configFile,
{moduleResolution: ts.ModuleResolutionKind.Node10, resolveJsonModule: true},
parseConfigHost,
);
if (resolvedModule) {
return absoluteFrom(resolvedModule.resolvedFileName);
}
}
return null;
}
export interface PerformCompilationResult {
diagnostics: ReadonlyArray<ts.Diagnostic>;
program?: api.Program;
emitResult?: ts.EmitResult;
}
export function exitCodeFromResult(diags: ReadonlyArray<ts.Diagnostic> | undefined): number {
if (!diags) return 0;
if (diags.every((diag) => diag.category !== ts.DiagnosticCategory.Error)) {
// If we have a result and didn't get any errors, we succeeded.
return 0;
}
// Return 2 if any of the errors were unknown.
return diags.some((d) => d.source === 'angular' && d.code === api.UNKNOWN_ERROR_CODE) ? 2 : 1;
} | {
"end_byte": 7912,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/perform_compile.ts"
} |
angular/packages/compiler-cli/src/perform_compile.ts_7914_11476 | export function performCompilation<CbEmitRes extends ts.EmitResult = ts.EmitResult>({
rootNames,
options,
host,
oldProgram,
emitCallback,
mergeEmitResultsCallback,
gatherDiagnostics = defaultGatherDiagnostics,
customTransformers,
emitFlags = api.EmitFlags.Default,
forceEmit = false,
modifiedResourceFiles = null,
}: {
rootNames: string[];
options: api.CompilerOptions;
host?: api.CompilerHost;
oldProgram?: api.Program;
emitCallback?: api.TsEmitCallback<CbEmitRes>;
mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback<CbEmitRes>;
gatherDiagnostics?: (program: api.Program) => ReadonlyArray<ts.Diagnostic>;
customTransformers?: api.CustomTransformers;
emitFlags?: api.EmitFlags;
forceEmit?: boolean;
modifiedResourceFiles?: Set<string> | null;
}): PerformCompilationResult {
let program: api.Program | undefined;
let emitResult: ts.EmitResult | undefined;
let allDiagnostics: Array<ts.Diagnostic> = [];
try {
if (!host) {
host = ng.createCompilerHost({options});
}
if (modifiedResourceFiles) {
host.getModifiedResourceFiles = () => modifiedResourceFiles;
}
program = ng.createProgram({rootNames, host, options, oldProgram});
const beforeDiags = Date.now();
allDiagnostics.push(...gatherDiagnostics(program!));
if (options.diagnostics) {
const afterDiags = Date.now();
allDiagnostics.push(
createMessageDiagnostic(`Time for diagnostics: ${afterDiags - beforeDiags}ms.`),
);
}
if (!hasErrors(allDiagnostics)) {
emitResult = program!.emit({
emitCallback,
mergeEmitResultsCallback,
customTransformers,
emitFlags,
forceEmit,
});
allDiagnostics.push(...emitResult.diagnostics);
return {diagnostics: allDiagnostics, program, emitResult};
}
return {diagnostics: allDiagnostics, program};
} catch (e) {
// We might have a program with unknown state, discard it.
program = undefined;
allDiagnostics.push({
category: ts.DiagnosticCategory.Error,
messageText: (e as Error).stack ?? (e as Error).message,
code: api.UNKNOWN_ERROR_CODE,
file: undefined,
start: undefined,
length: undefined,
});
return {diagnostics: allDiagnostics, program};
}
}
export function defaultGatherDiagnostics(program: api.Program): ReadonlyArray<ts.Diagnostic> {
const allDiagnostics: Array<ts.Diagnostic> = [];
function checkDiagnostics(diags: ReadonlyArray<ts.Diagnostic> | undefined) {
if (diags) {
allDiagnostics.push(...diags);
return !hasErrors(diags);
}
return true;
}
let checkOtherDiagnostics = true;
// Check parameter diagnostics
checkOtherDiagnostics =
checkOtherDiagnostics &&
checkDiagnostics([...program.getTsOptionDiagnostics(), ...program.getNgOptionDiagnostics()]);
// Check syntactic diagnostics
checkOtherDiagnostics =
checkOtherDiagnostics && checkDiagnostics(program.getTsSyntacticDiagnostics());
// Check TypeScript semantic and Angular structure diagnostics
checkOtherDiagnostics =
checkOtherDiagnostics &&
checkDiagnostics([
...program.getTsSemanticDiagnostics(),
...program.getNgStructuralDiagnostics(),
]);
// Check Angular semantic diagnostics
checkOtherDiagnostics =
checkOtherDiagnostics && checkDiagnostics(program.getNgSemanticDiagnostics());
return allDiagnostics;
}
function hasErrors(diags: ReadonlyArray<ts.Diagnostic>) {
return diags.some((d) => d.category === ts.DiagnosticCategory.Error);
} | {
"end_byte": 11476,
"start_byte": 7914,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/perform_compile.ts"
} |
angular/packages/compiler-cli/src/main.ts_0_7006 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 yargs from 'yargs';
import {
exitCodeFromResult,
formatDiagnostics,
ParsedConfiguration,
performCompilation,
readConfiguration,
} from './perform_compile';
import {createPerformWatchHost, performWatchCompilation} from './perform_watch';
import * as api from './transformers/api';
export function main(
args: string[],
consoleError: (s: string) => void = console.error,
config?: NgcParsedConfiguration,
customTransformers?: api.CustomTransformers,
programReuse?: {
program: api.Program | undefined;
},
modifiedResourceFiles?: Set<string> | null,
): number {
let {
project,
rootNames,
options,
errors: configErrors,
watch,
emitFlags,
} = config || readNgcCommandLineAndConfiguration(args);
if (configErrors.length) {
return reportErrorsAndExit(configErrors, /*options*/ undefined, consoleError);
}
if (watch) {
const result = watchMode(project, options, consoleError);
return reportErrorsAndExit(result.firstCompileResult, options, consoleError);
}
let oldProgram: api.Program | undefined;
if (programReuse !== undefined) {
oldProgram = programReuse.program;
}
const {diagnostics: compileDiags, program} = performCompilation({
rootNames,
options,
emitFlags,
oldProgram,
customTransformers,
modifiedResourceFiles,
});
if (programReuse !== undefined) {
programReuse.program = program;
}
return reportErrorsAndExit(compileDiags, options, consoleError);
}
export function mainDiagnosticsForTest(
args: string[],
config?: NgcParsedConfiguration,
programReuse?: {program: api.Program | undefined},
modifiedResourceFiles?: Set<string> | null,
): {
exitCode: number;
diagnostics: ReadonlyArray<ts.Diagnostic>;
} {
let {
rootNames,
options,
errors: configErrors,
emitFlags,
} = config || readNgcCommandLineAndConfiguration(args);
if (configErrors.length) {
return {
exitCode: exitCodeFromResult(configErrors),
diagnostics: configErrors,
};
}
let oldProgram: api.Program | undefined;
if (programReuse !== undefined) {
oldProgram = programReuse.program;
}
const {diagnostics: compileDiags, program} = performCompilation({
rootNames,
options,
emitFlags,
oldProgram,
modifiedResourceFiles,
});
if (programReuse !== undefined) {
programReuse.program = program;
}
return {
exitCode: exitCodeFromResult(compileDiags),
diagnostics: compileDiags,
};
}
export interface NgcParsedConfiguration extends ParsedConfiguration {
watch?: boolean;
}
export function readNgcCommandLineAndConfiguration(args: string[]): NgcParsedConfiguration {
const options: api.CompilerOptions = {};
const parsedArgs = yargs(args)
.parserConfiguration({'strip-aliased': true})
.option('i18nFile', {type: 'string'})
.option('i18nFormat', {type: 'string'})
.option('locale', {type: 'string'})
.option('missingTranslation', {type: 'string', choices: ['error', 'warning', 'ignore']})
.option('outFile', {type: 'string'})
.option('watch', {type: 'boolean', alias: ['w']})
.parseSync();
if (parsedArgs.i18nFile) options.i18nInFile = parsedArgs.i18nFile;
if (parsedArgs.i18nFormat) options.i18nInFormat = parsedArgs.i18nFormat;
if (parsedArgs.locale) options.i18nInLocale = parsedArgs.locale;
if (parsedArgs.missingTranslation)
options.i18nInMissingTranslations =
parsedArgs.missingTranslation as api.CompilerOptions['i18nInMissingTranslations'];
const config = readCommandLineAndConfiguration(args, options, [
'i18nFile',
'i18nFormat',
'locale',
'missingTranslation',
'watch',
]);
return {...config, watch: parsedArgs.watch};
}
export function readCommandLineAndConfiguration(
args: string[],
existingOptions: api.CompilerOptions = {},
ngCmdLineOptions: string[] = [],
): ParsedConfiguration {
let cmdConfig = ts.parseCommandLine(args);
const project = cmdConfig.options.project || '.';
const cmdErrors = cmdConfig.errors.filter((e) => {
if (typeof e.messageText === 'string') {
const msg = e.messageText;
return !ngCmdLineOptions.some((o) => msg.indexOf(o) >= 0);
}
return true;
});
if (cmdErrors.length) {
return {
project,
rootNames: [],
options: cmdConfig.options,
errors: cmdErrors,
emitFlags: api.EmitFlags.Default,
};
}
const config = readConfiguration(project, cmdConfig.options);
const options = {...config.options, ...existingOptions};
if (options.locale) {
options.i18nInLocale = options.locale;
}
return {
project,
rootNames: config.rootNames,
options,
errors: config.errors,
emitFlags: config.emitFlags,
};
}
function getFormatDiagnosticsHost(options?: api.CompilerOptions): ts.FormatDiagnosticsHost {
const basePath = options ? options.basePath : undefined;
return {
getCurrentDirectory: () => basePath || ts.sys.getCurrentDirectory(),
// We need to normalize the path separators here because by default, TypeScript
// compiler hosts use posix canonical paths. In order to print consistent diagnostics,
// we also normalize the paths.
getCanonicalFileName: (fileName) => fileName.replace(/\\/g, '/'),
getNewLine: () => {
// Manually determine the proper new line string based on the passed compiler
// options. There is no public TypeScript function that returns the corresponding
// new line string. see: https://github.com/Microsoft/TypeScript/issues/29581
if (options && options.newLine !== undefined) {
return options.newLine === ts.NewLineKind.LineFeed ? '\n' : '\r\n';
}
return ts.sys.newLine;
},
};
}
function reportErrorsAndExit(
allDiagnostics: ReadonlyArray<ts.Diagnostic>,
options?: api.CompilerOptions,
consoleError: (s: string) => void = console.error,
): number {
const errorsAndWarnings = allDiagnostics.filter(
(d) => d.category !== ts.DiagnosticCategory.Message,
);
printDiagnostics(errorsAndWarnings, options, consoleError);
return exitCodeFromResult(allDiagnostics);
}
export function watchMode(
project: string,
options: api.CompilerOptions,
consoleError: (s: string) => void,
) {
return performWatchCompilation(
createPerformWatchHost(
project,
(diagnostics) => {
printDiagnostics(diagnostics, options, consoleError);
},
options,
undefined,
),
);
}
function printDiagnostics(
diagnostics: ReadonlyArray<ts.Diagnostic>,
options: api.CompilerOptions | undefined,
consoleError: (s: string) => void,
): void {
if (diagnostics.length === 0) {
return;
}
const formatHost = getFormatDiagnosticsHost(options);
consoleError(formatDiagnostics(diagnostics, formatHost));
}
| {
"end_byte": 7006,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/main.ts"
} |
angular/packages/compiler-cli/src/perform_watch.ts_0_4307 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as chokidar from 'chokidar';
import * as path from 'path';
import ts from 'typescript';
import {
exitCodeFromResult,
ParsedConfiguration,
performCompilation,
PerformCompilationResult,
readConfiguration,
} from './perform_compile';
import * as api from './transformers/api';
import {createCompilerHost} from './transformers/entry_points';
import {createMessageDiagnostic} from './transformers/util';
function totalCompilationTimeDiagnostic(timeInMillis: number): ts.Diagnostic {
let duration: string;
if (timeInMillis > 1000) {
duration = `${(timeInMillis / 1000).toPrecision(2)}s`;
} else {
duration = `${timeInMillis}ms`;
}
return {
category: ts.DiagnosticCategory.Message,
messageText: `Total time: ${duration}`,
code: api.DEFAULT_ERROR_CODE,
source: api.SOURCE,
file: undefined,
start: undefined,
length: undefined,
};
}
export enum FileChangeEvent {
Change,
CreateDelete,
CreateDeleteDir,
}
export interface PerformWatchHost<CbEmitRes extends ts.EmitResult = ts.EmitResult> {
reportDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic>): void;
readConfiguration(): ParsedConfiguration;
createCompilerHost(options: api.CompilerOptions): api.CompilerHost;
createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback<CbEmitRes> | undefined;
onFileChange(
options: api.CompilerOptions,
listener: (event: FileChangeEvent, fileName: string) => void,
ready: () => void,
): {close: () => void};
setTimeout(callback: () => void, ms: number): any;
clearTimeout(timeoutId: any): void;
}
export function createPerformWatchHost<CbEmitRes extends ts.EmitResult = ts.EmitResult>(
configFileName: string,
reportDiagnostics: (diagnostics: ReadonlyArray<ts.Diagnostic>) => void,
existingOptions?: ts.CompilerOptions,
createEmitCallback?: (options: api.CompilerOptions) => api.TsEmitCallback<CbEmitRes> | undefined,
): PerformWatchHost {
return {
reportDiagnostics: reportDiagnostics,
createCompilerHost: (options) => createCompilerHost({options}),
readConfiguration: () => readConfiguration(configFileName, existingOptions),
createEmitCallback: (options) => (createEmitCallback ? createEmitCallback(options) : undefined),
onFileChange: (options, listener, ready: () => void) => {
if (!options.basePath) {
reportDiagnostics([
{
category: ts.DiagnosticCategory.Error,
messageText: 'Invalid configuration option. baseDir not specified',
source: api.SOURCE,
code: api.DEFAULT_ERROR_CODE,
file: undefined,
start: undefined,
length: undefined,
},
]);
return {close: () => {}};
}
const watcher = chokidar.watch(options.basePath, {
// ignore .dotfiles, .js and .map files.
// can't ignore other files as we e.g. want to recompile if an `.html` file changes as well.
ignored: (path) =>
/((^[\/\\])\..)|(\.js$)|(\.map$)|(\.metadata\.json|node_modules)/.test(path),
ignoreInitial: true,
persistent: true,
});
watcher.on('all', (event: string, path: string) => {
switch (event) {
case 'change':
listener(FileChangeEvent.Change, path);
break;
case 'unlink':
case 'add':
listener(FileChangeEvent.CreateDelete, path);
break;
case 'unlinkDir':
case 'addDir':
listener(FileChangeEvent.CreateDeleteDir, path);
break;
}
});
watcher.on('ready', ready);
return {close: () => watcher.close(), ready};
},
setTimeout: (ts.sys.clearTimeout && ts.sys.setTimeout) || setTimeout,
clearTimeout: (ts.sys.setTimeout && ts.sys.clearTimeout) || clearTimeout,
};
}
interface CacheEntry {
exists?: boolean;
sf?: ts.SourceFile;
content?: string;
}
interface QueuedCompilationInfo {
timerHandle: any;
modifiedResourceFiles: Set<string>;
}
/**
* The logic in this function is adapted from `tsc.ts` from TypeScript.
*/ | {
"end_byte": 4307,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/perform_watch.ts"
} |
angular/packages/compiler-cli/src/perform_watch.ts_4308_11839 | export function performWatchCompilation(host: PerformWatchHost): {
close: () => void;
ready: (cb: () => void) => void;
firstCompileResult: ReadonlyArray<ts.Diagnostic>;
} {
let cachedProgram: api.Program | undefined; // Program cached from last compilation
let cachedCompilerHost: api.CompilerHost | undefined; // CompilerHost cached from last compilation
let cachedOptions: ParsedConfiguration | undefined; // CompilerOptions cached from last compilation
let timerHandleForRecompilation: QueuedCompilationInfo | undefined; // Handle for 0.25s wait timer to trigger recompilation
const ignoreFilesForWatch = new Set<string>();
const fileCache = new Map<string, CacheEntry>();
const firstCompileResult = doCompilation();
// Watch basePath, ignoring .dotfiles
let resolveReadyPromise: () => void;
const readyPromise = new Promise<void>((resolve) => (resolveReadyPromise = resolve));
// Note: ! is ok as options are filled after the first compilation
// Note: ! is ok as resolvedReadyPromise is filled by the previous call
const fileWatcher = host.onFileChange(
cachedOptions!.options,
watchedFileChanged,
resolveReadyPromise!,
);
return {close, ready: (cb) => readyPromise.then(cb), firstCompileResult};
function cacheEntry(fileName: string): CacheEntry {
fileName = path.normalize(fileName);
let entry = fileCache.get(fileName);
if (!entry) {
entry = {};
fileCache.set(fileName, entry);
}
return entry;
}
function close() {
fileWatcher.close();
if (timerHandleForRecompilation) {
host.clearTimeout(timerHandleForRecompilation.timerHandle);
timerHandleForRecompilation = undefined;
}
}
// Invoked to perform initial compilation or re-compilation in watch mode
function doCompilation(): ReadonlyArray<ts.Diagnostic> {
if (!cachedOptions) {
cachedOptions = host.readConfiguration();
}
if (cachedOptions.errors && cachedOptions.errors.length) {
host.reportDiagnostics(cachedOptions.errors);
return cachedOptions.errors;
}
const startTime = Date.now();
if (!cachedCompilerHost) {
cachedCompilerHost = host.createCompilerHost(cachedOptions.options);
const originalWriteFileCallback = cachedCompilerHost.writeFile;
cachedCompilerHost.writeFile = function (
fileName: string,
data: string,
writeByteOrderMark: boolean,
onError?: (message: string) => void,
sourceFiles: ReadonlyArray<ts.SourceFile> = [],
) {
ignoreFilesForWatch.add(path.normalize(fileName));
return originalWriteFileCallback(fileName, data, writeByteOrderMark, onError, sourceFiles);
};
const originalFileExists = cachedCompilerHost.fileExists;
cachedCompilerHost.fileExists = function (fileName: string) {
const ce = cacheEntry(fileName);
if (ce.exists == null) {
ce.exists = originalFileExists.call(this, fileName);
}
return ce.exists!;
};
const originalGetSourceFile = cachedCompilerHost.getSourceFile;
cachedCompilerHost.getSourceFile = function (
fileName: string,
languageVersion: ts.ScriptTarget,
) {
const ce = cacheEntry(fileName);
if (!ce.sf) {
ce.sf = originalGetSourceFile.call(this, fileName, languageVersion);
}
return ce.sf!;
};
const originalReadFile = cachedCompilerHost.readFile;
cachedCompilerHost.readFile = function (fileName: string) {
const ce = cacheEntry(fileName);
if (ce.content == null) {
ce.content = originalReadFile.call(this, fileName);
}
return ce.content!;
};
// Provide access to the file paths that triggered this rebuild
cachedCompilerHost.getModifiedResourceFiles = function () {
if (timerHandleForRecompilation === undefined) {
return undefined;
}
return timerHandleForRecompilation.modifiedResourceFiles;
};
}
ignoreFilesForWatch.clear();
const oldProgram = cachedProgram;
// We clear out the `cachedProgram` here as a
// program can only be used as `oldProgram` 1x
cachedProgram = undefined;
const compileResult = performCompilation({
rootNames: cachedOptions.rootNames,
options: cachedOptions.options,
host: cachedCompilerHost,
oldProgram: oldProgram,
emitCallback: host.createEmitCallback(cachedOptions.options),
});
if (compileResult.diagnostics.length) {
host.reportDiagnostics(compileResult.diagnostics);
}
const endTime = Date.now();
if (cachedOptions.options.diagnostics) {
const totalTime = (endTime - startTime) / 1000;
host.reportDiagnostics([totalCompilationTimeDiagnostic(endTime - startTime)]);
}
const exitCode = exitCodeFromResult(compileResult.diagnostics);
if (exitCode == 0) {
cachedProgram = compileResult.program;
host.reportDiagnostics([
createMessageDiagnostic('Compilation complete. Watching for file changes.'),
]);
} else {
host.reportDiagnostics([
createMessageDiagnostic('Compilation failed. Watching for file changes.'),
]);
}
return compileResult.diagnostics;
}
function resetOptions() {
cachedProgram = undefined;
cachedCompilerHost = undefined;
cachedOptions = undefined;
}
function watchedFileChanged(event: FileChangeEvent, fileName: string) {
const normalizedPath = path.normalize(fileName);
if (
cachedOptions &&
event === FileChangeEvent.Change &&
// TODO(chuckj): validate that this is sufficient to skip files that were written.
// This assumes that the file path we write is the same file path we will receive in the
// change notification.
normalizedPath === path.normalize(cachedOptions.project)
) {
// If the configuration file changes, forget everything and start the recompilation timer
resetOptions();
} else if (
event === FileChangeEvent.CreateDelete ||
event === FileChangeEvent.CreateDeleteDir
) {
// If a file was added or removed, reread the configuration
// to determine the new list of root files.
cachedOptions = undefined;
}
if (event === FileChangeEvent.CreateDeleteDir) {
fileCache.clear();
} else {
fileCache.delete(normalizedPath);
}
if (!ignoreFilesForWatch.has(normalizedPath)) {
// Ignore the file if the file is one that was written by the compiler.
startTimerForRecompilation(normalizedPath);
}
}
// Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
// operations (such as saving all modified files in an editor) a chance to complete before we kick
// off a new compilation.
function startTimerForRecompilation(changedPath: string) {
if (timerHandleForRecompilation) {
host.clearTimeout(timerHandleForRecompilation.timerHandle);
} else {
timerHandleForRecompilation = {
modifiedResourceFiles: new Set<string>(),
timerHandle: undefined,
};
}
timerHandleForRecompilation.timerHandle = host.setTimeout(recompile, 250);
timerHandleForRecompilation.modifiedResourceFiles.add(changedPath);
}
function recompile() {
host.reportDiagnostics([
createMessageDiagnostic('File change detected. Starting incremental compilation.'),
]);
doCompilation();
timerHandleForRecompilation = undefined;
}
} | {
"end_byte": 11839,
"start_byte": 4308,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/perform_watch.ts"
} |
angular/packages/compiler-cli/src/extract_i18n.ts_0_1442 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Extract i18n messages from source code
*/
import yargs from 'yargs';
import {main, readCommandLineAndConfiguration} from './main';
import {ParsedConfiguration} from './perform_compile';
import * as api from './transformers/api';
export function mainXi18n(
args: string[],
consoleError: (msg: string) => void = console.error,
): number {
const config = readXi18nCommandLineAndConfiguration(args);
return main(args, consoleError, config, undefined, undefined, undefined);
}
function readXi18nCommandLineAndConfiguration(args: string[]): ParsedConfiguration {
const options: api.CompilerOptions = {};
const parsedArgs = yargs(args)
.option('i18nFormat', {type: 'string'})
.option('locale', {type: 'string'})
.option('outFile', {type: 'string'})
.parseSync();
if (parsedArgs.outFile) options.i18nOutFile = parsedArgs.outFile;
if (parsedArgs.i18nFormat) options.i18nOutFormat = parsedArgs.i18nFormat;
if (parsedArgs.locale) options.i18nOutLocale = parsedArgs.locale;
const config = readCommandLineAndConfiguration(args, options, [
'outFile',
'i18nFormat',
'locale',
]);
// only emit the i18nBundle but nothing else.
return {...config, emitFlags: api.EmitFlags.I18nBundle};
}
| {
"end_byte": 1442,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/extract_i18n.ts"
} |
angular/packages/compiler-cli/src/typescript_support.ts_0_2284 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {compareVersions} from './version_helpers';
/**
* Minimum supported TypeScript version
* ∀ supported typescript version v, v >= MIN_TS_VERSION
*
* Note: this check is disabled in g3, search for
* `angularCompilerOptions.disableTypeScriptVersionCheck` config param value in g3.
*/
const MIN_TS_VERSION = '5.5.0';
/**
* Supremum of supported TypeScript versions
* ∀ supported typescript version v, v < MAX_TS_VERSION
* MAX_TS_VERSION is not considered as a supported TypeScript version
*
* Note: this check is disabled in g3, search for
* `angularCompilerOptions.disableTypeScriptVersionCheck` config param value in g3.
*/
const MAX_TS_VERSION = '5.7.0';
/**
* The currently used version of TypeScript, which can be adjusted for testing purposes using
* `setTypeScriptVersionForTesting` and `restoreTypeScriptVersionForTesting` below.
*/
let tsVersion = ts.version;
export function setTypeScriptVersionForTesting(version: string): void {
tsVersion = version;
}
export function restoreTypeScriptVersionForTesting(): void {
tsVersion = ts.version;
}
/**
* Checks whether a given version ∈ [minVersion, maxVersion[.
* An error will be thrown when the given version ∉ [minVersion, maxVersion[.
*
* @param version The version on which the check will be performed
* @param minVersion The lower bound version. A valid version needs to be greater than minVersion
* @param maxVersion The upper bound version. A valid version needs to be strictly less than
* maxVersion
*
* @throws Will throw an error if the given version ∉ [minVersion, maxVersion[
*/
export function checkVersion(version: string, minVersion: string, maxVersion: string) {
if (compareVersions(version, minVersion) < 0 || compareVersions(version, maxVersion) >= 0) {
throw new Error(
`The Angular Compiler requires TypeScript >=${minVersion} and <${maxVersion} but ${version} was found instead.`,
);
}
}
export function verifySupportedTypeScriptVersion(): void {
checkVersion(tsVersion, MIN_TS_VERSION, MAX_TS_VERSION);
}
| {
"end_byte": 2284,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/typescript_support.ts"
} |
angular/packages/compiler-cli/src/version.ts_0_405 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the compiler-cli package.
*/
import {Version} from '@angular/compiler';
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 405,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/version.ts"
} |
angular/packages/compiler-cli/src/version_helpers.ts_0_3165 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Converts a `string` version into an array of numbers
* @example
* toNumbers('2.0.1'); // returns [2, 0, 1]
*/
export function toNumbers(value: string): number[] {
// Drop any suffixes starting with `-` so that versions like `1.2.3-rc.5` are treated as `1.2.3`.
const suffixIndex = value.lastIndexOf('-');
return value
.slice(0, suffixIndex === -1 ? value.length : suffixIndex)
.split('.')
.map((segment) => {
const parsed = parseInt(segment, 10);
if (isNaN(parsed)) {
throw Error(`Unable to parse version string ${value}.`);
}
return parsed;
});
}
/**
* Compares two arrays of positive numbers with lexicographical order in mind.
*
* However - unlike lexicographical order - for arrays of different length we consider:
* [1, 2, 3] = [1, 2, 3, 0] instead of [1, 2, 3] < [1, 2, 3, 0]
*
* @param a The 'left hand' array in the comparison test
* @param b The 'right hand' in the comparison test
* @returns {-1|0|1} The comparison result: 1 if a is greater, -1 if b is greater, 0 is the two
* arrays are equals
*/
export function compareNumbers(a: number[], b: number[]): -1 | 0 | 1 {
const max = Math.max(a.length, b.length);
const min = Math.min(a.length, b.length);
for (let i = 0; i < min; i++) {
if (a[i] > b[i]) return 1;
if (a[i] < b[i]) return -1;
}
if (min !== max) {
const longestArray = a.length === max ? a : b;
// The result to return in case the to arrays are considered different (1 if a is greater,
// -1 if b is greater)
const comparisonResult = a.length === max ? 1 : -1;
// Check that at least one of the remaining elements is greater than 0 to consider that the two
// arrays are different (e.g. [1, 0] and [1] are considered the same but not [1, 0, 1] and [1])
for (let i = min; i < max; i++) {
if (longestArray[i] > 0) {
return comparisonResult;
}
}
}
return 0;
}
/**
* Checks if a TypeScript version is:
* - greater or equal than the provided `low` version,
* - lower or equal than an optional `high` version.
*
* @param version The TypeScript version
* @param low The minimum version
* @param high The maximum version
*/
export function isVersionBetween(version: string, low: string, high?: string): boolean {
const tsNumbers = toNumbers(version);
if (high !== undefined) {
return (
compareNumbers(toNumbers(low), tsNumbers) <= 0 &&
compareNumbers(toNumbers(high), tsNumbers) >= 0
);
}
return compareNumbers(toNumbers(low), tsNumbers) <= 0;
}
/**
* Compares two versions
*
* @param v1 The 'left hand' version in the comparison test
* @param v2 The 'right hand' version in the comparison test
* @returns {-1|0|1} The comparison result: 1 if v1 is greater, -1 if v2 is greater, 0 is the two
* versions are equals
*/
export function compareVersions(v1: string, v2: string): -1 | 0 | 1 {
return compareNumbers(toNumbers(v1), toNumbers(v2));
}
| {
"end_byte": 3165,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/version_helpers.ts"
} |
angular/packages/compiler-cli/src/bin/ngc.ts_0_823 | #!/usr/bin/env node
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Must be imported first, because Angular decorators throw on load.
import 'reflect-metadata';
import {NodeJSFileSystem, setFileSystem} from '../ngtsc/file_system';
import {main} from '../main';
async function runNgcComamnd() {
process.title = 'Angular Compiler (ngc)';
const args = process.argv.slice(2);
// We are running the real compiler so run against the real file-system
setFileSystem(new NodeJSFileSystem());
process.exitCode = main(args, undefined, undefined, undefined, undefined, undefined);
}
runNgcComamnd().catch((e) => {
console.error(e);
process.exitCode = 1;
});
| {
"end_byte": 823,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/bin/ngc.ts"
} |
angular/packages/compiler-cli/src/bin/ng_xi18n.ts_0_679 | #!/usr/bin/env node
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Must be imported first, because Angular decorators throw on load.
import 'reflect-metadata';
import {NodeJSFileSystem, setFileSystem} from '../ngtsc/file_system';
import {mainXi18n} from '../extract_i18n';
process.title = 'Angular i18n Message Extractor (ng-xi18n)';
const args = process.argv.slice(2);
// We are running the real compiler so run against the real file-system
setFileSystem(new NodeJSFileSystem());
process.exitCode = mainXi18n(args);
| {
"end_byte": 679,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/bin/ng_xi18n.ts"
} |
angular/packages/compiler-cli/src/transformers/program.ts_0_617 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgtscProgram} from '../ngtsc/program';
import {CompilerHost, CompilerOptions, Program} from './api';
export function createProgram({
rootNames,
options,
host,
oldProgram,
}: {
rootNames: ReadonlyArray<string>;
options: CompilerOptions;
host: CompilerHost;
oldProgram?: Program;
}): Program {
return new NgtscProgram(rootNames, options, host, oldProgram as NgtscProgram | undefined);
}
| {
"end_byte": 617,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/program.ts"
} |
angular/packages/compiler-cli/src/transformers/i18n.ts_0_2177 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MessageBundle, Serializer, Xliff, Xliff2, Xmb} from '@angular/compiler';
import * as path from 'path';
import ts from 'typescript';
import {CompilerOptions} from './api';
export function i18nGetExtension(formatName: string): string {
const format = formatName.toLowerCase();
switch (format) {
case 'xmb':
return 'xmb';
case 'xlf':
case 'xlif':
case 'xliff':
case 'xlf2':
case 'xliff2':
return 'xlf';
}
throw new Error(`Unsupported format "${formatName}"`);
}
export function i18nExtract(
formatName: string | null,
outFile: string | null,
host: ts.CompilerHost,
options: CompilerOptions,
bundle: MessageBundle,
pathResolve: (...segments: string[]) => string = path.resolve,
): string[] {
formatName = formatName || 'xlf';
// Checks the format and returns the extension
const ext = i18nGetExtension(formatName);
const content = i18nSerialize(bundle, formatName, options);
const dstFile = outFile || `messages.${ext}`;
const dstPath = pathResolve(options.outDir || options.basePath!, dstFile);
host.writeFile(dstPath, content, false, undefined, []);
return [dstPath];
}
export function i18nSerialize(
bundle: MessageBundle,
formatName: string,
options: CompilerOptions,
): string {
const format = formatName.toLowerCase();
let serializer: Serializer;
switch (format) {
case 'xmb':
serializer = new Xmb();
break;
case 'xliff2':
case 'xlf2':
serializer = new Xliff2();
break;
case 'xlf':
case 'xliff':
default:
serializer = new Xliff();
}
return bundle.write(serializer, getPathNormalizer(options.basePath));
}
function getPathNormalizer(basePath?: string) {
// normalize source paths by removing the base path and always using "/" as a separator
return (sourcePath: string) => {
sourcePath = basePath ? path.relative(basePath, sourcePath) : sourcePath;
return sourcePath.split(path.sep).join('/');
};
}
| {
"end_byte": 2177,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/i18n.ts"
} |
angular/packages/compiler-cli/src/transformers/api.ts_0_6357 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ExtendedTsCompilerHost, NgCompilerOptions} from '../ngtsc/core/api';
export const DEFAULT_ERROR_CODE = 100;
export const UNKNOWN_ERROR_CODE = 500;
export const SOURCE = 'angular' as 'angular';
export function isTsDiagnostic(diagnostic: any): diagnostic is ts.Diagnostic {
return diagnostic != null && diagnostic.source !== 'angular';
}
export interface CompilerOptions extends NgCompilerOptions, ts.CompilerOptions {
// Write statistics about compilation (e.g. total time, ...)
// Note: this is the --diagnostics command line option from TS (which is @internal
// on ts.CompilerOptions interface).
diagnostics?: boolean;
// Absolute path to a directory where generated file structure is written.
// If unspecified, generated files will be written alongside sources.
// @deprecated - no effect
genDir?: string;
// Path to the directory containing the tsconfig.json file.
basePath?: string;
// Don't produce .metadata.json files (they don't work for bundled emit with --out)
skipMetadataEmit?: boolean;
// Produce an error if the metadata written for a class would produce an error if used.
strictMetadataEmit?: boolean;
// Don't produce .ngfactory.js or .ngstyle.js files
skipTemplateCodegen?: boolean;
// A prefix to insert in generated private symbols, e.g. for "my_prefix_" we
// would generate private symbols named like `ɵmy_prefix_a`.
flatModulePrivateSymbolPrefix?: string;
// Whether to generate code for library code.
// Default is true.
generateCodeForLibraries?: boolean;
// Modify how angular annotations are emitted to improve tree-shaking.
// Default is static fields.
// decorators: Leave the Decorators in-place. This makes compilation faster.
// TypeScript will emit calls to the __decorate helper.
// `--emitDecoratorMetadata` can be used for runtime reflection.
// However, the resulting code will not properly tree-shake.
// static fields: Replace decorators with a static field in the class.
// Allows advanced tree-shakers like Closure Compiler to remove
// unused classes.
annotationsAs?: 'decorators' | 'static fields';
// Print extra information while running the compiler
trace?: boolean;
// Whether to enable lowering expressions lambdas and expressions in a reference value
// position.
disableExpressionLowering?: boolean;
// Import format if different from `i18nFormat`
i18nInFormat?: string;
// Path to the translation file
i18nInFile?: string;
// How to handle missing messages
i18nInMissingTranslations?: 'error' | 'warning' | 'ignore';
/**
* Whether to replace the `templateUrl` and `styleUrls` property in all
* @Component decorators with inlined contents in `template` and `styles`
* properties.
* When enabled, the .js output of ngc will have no lazy-loaded `templateUrl`
* or `styleUrl`s. Note that this requires that resources be available to
* load statically at compile-time.
*/
enableResourceInlining?: boolean;
/** @internal */
collectAllErrors?: boolean;
/**
* Whether NGC should generate re-exports for external symbols which are referenced
* in Angular metadata (e.g. @Component, @Inject, @ViewChild). This can be enabled in
* order to avoid dynamically generated module dependencies which can break strict
* dependency enforcements. This is not enabled by default.
* Read more about this here: https://github.com/angular/angular/issues/25644.
*/
createExternalSymbolFactoryReexports?: boolean;
}
export interface CompilerHost extends ts.CompilerHost, ExtendedTsCompilerHost {
/**
* Converts a module name that is used in an `import` to a file path.
* I.e. `path/to/containingFile.ts` containing `import {...} from 'module-name'`.
*/
moduleNameToFileName?(moduleName: string, containingFile: string): string | null;
/**
* Converts a file name into a representation that should be stored in a summary file.
* This has to include changing the suffix as well.
* E.g.
* `some_file.ts` -> `some_file.d.ts`
*
* @param referringSrcFileName the source file that refers to fileName
*/
toSummaryFileName?(fileName: string, referringSrcFileName: string): string;
/**
* Converts a fileName that was processed by `toSummaryFileName` back into a real fileName
* given the fileName of the library that is referring to it.
*/
fromSummaryFileName?(fileName: string, referringLibFileName: string): string;
/**
* Produce an AMD module name for the source file. Used in Bazel.
*
* An AMD module can have an arbitrary name, so that it is require'd by name
* rather than by path. See https://requirejs.org/docs/whyamd.html#namedmodules
*/
amdModuleName?(sf: ts.SourceFile): string | undefined;
}
export enum EmitFlags {
DTS = 1 << 0,
JS = 1 << 1,
Metadata = 1 << 2,
I18nBundle = 1 << 3,
Codegen = 1 << 4,
Default = DTS | JS | Codegen,
All = DTS | JS | Metadata | I18nBundle | Codegen,
}
export interface CustomTransformers {
beforeTs?: ts.TransformerFactory<ts.SourceFile>[];
afterTs?: ts.TransformerFactory<ts.SourceFile>[];
}
export interface TsEmitArguments {
program: ts.Program;
host: CompilerHost;
options: CompilerOptions;
targetSourceFile?: ts.SourceFile;
writeFile?: ts.WriteFileCallback;
cancellationToken?: ts.CancellationToken;
emitOnlyDtsFiles?: boolean;
customTransformers?: ts.CustomTransformers;
}
export interface TsEmitCallback<T extends ts.EmitResult> {
(args: TsEmitArguments): T;
}
export interface TsMergeEmitResultsCallback<T extends ts.EmitResult> {
(results: T[]): T;
}
export interface LazyRoute {
route: string;
module: {name: string; filePath: string};
referencedModule: {name: string; filePath: string};
}
export interface EmitOptions<CbEmitRes extends ts.EmitResult> {
emitFlags?: EmitFlags;
forceEmit?: boolean;
cancellationToken?: ts.CancellationToken;
customTransformers?: CustomTransformers;
emitCallback?: TsEmitCallback<CbEmitRes>;
mergeEmitResultsCallback?: TsMergeEmitResultsCallback<CbEmitRes>;
}
| {
"end_byte": 6357,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/api.ts"
} |
angular/packages/compiler-cli/src/transformers/api.ts_6359_9736 | xport interface Program {
/**
* Retrieve the TypeScript program used to produce semantic diagnostics and emit the sources.
*
* Angular structural information is required to produce the program.
*/
getTsProgram(): ts.Program;
/**
* Retrieve options diagnostics for the TypeScript options used to create the program. This is
* faster than calling `getTsProgram().getOptionsDiagnostics()` since it does not need to
* collect Angular structural information to produce the errors.
*/
getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<ts.Diagnostic>;
/**
* Retrieve options diagnostics for the Angular options used to create the program.
*/
getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken): ReadonlyArray<ts.Diagnostic>;
/**
* Retrieve the syntax diagnostics from TypeScript. This is faster than calling
* `getTsProgram().getSyntacticDiagnostics()` since it does not need to collect Angular structural
* information to produce the errors.
*/
getTsSyntacticDiagnostics(
sourceFile?: ts.SourceFile,
cancellationToken?: ts.CancellationToken,
): ReadonlyArray<ts.Diagnostic>;
/**
* Retrieve the diagnostics for the structure of an Angular application is correctly formed.
* This includes validating Angular annotations and the syntax of referenced and imbedded HTML
* and CSS.
*
* Note it is important to displaying TypeScript semantic diagnostics along with Angular
* structural diagnostics as an error in the program structure might cause errors detected in
* semantic analysis and a semantic error might cause errors in specifying the program structure.
*
* Angular structural information is required to produce these diagnostics.
*/
getNgStructuralDiagnostics(
cancellationToken?: ts.CancellationToken,
): ReadonlyArray<ts.Diagnostic>;
/**
* Retrieve the semantic diagnostics from TypeScript. This is equivalent to calling
* `getTsProgram().getSemanticDiagnostics()` directly and is included for completeness.
*/
getTsSemanticDiagnostics(
sourceFile?: ts.SourceFile,
cancellationToken?: ts.CancellationToken,
): ReadonlyArray<ts.Diagnostic>;
/**
* Retrieve the Angular semantic diagnostics.
*
* Angular structural information is required to produce these diagnostics.
*/
getNgSemanticDiagnostics(
fileName?: string,
cancellationToken?: ts.CancellationToken,
): ReadonlyArray<ts.Diagnostic>;
/**
* Load Angular structural information asynchronously. If this method is not called then the
* Angular structural information, including referenced HTML and CSS files, are loaded
* synchronously. If the supplied Angular compiler host returns a promise from `loadResource()`
* will produce a diagnostic error message or, `getTsProgram()` or `emit` to throw.
*/
loadNgStructureAsync(): Promise<void>;
/**
* This method is obsolete and always returns an empty array.
*/
listLazyRoutes(entryRoute?: string): LazyRoute[];
/**
* Emit the files requested by emitFlags implied by the program.
*
* Angular structural information is required to emit files.
*/
emit<CbEmitRes extends ts.EmitResult>(opts?: EmitOptions<CbEmitRes> | undefined): ts.EmitResult;
/**
* @internal
*/
getEmittedSourceFiles(): Map<string, ts.SourceFile>;
}
| {
"end_byte": 9736,
"start_byte": 6359,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/api.ts"
} |
angular/packages/compiler-cli/src/transformers/entry_points.ts_0_297 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {createCompilerHost} from './compiler_host';
export {createProgram} from './program';
| {
"end_byte": 297,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/entry_points.ts"
} |
angular/packages/compiler-cli/src/transformers/util.ts_0_958 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {DEFAULT_ERROR_CODE, SOURCE} from './api';
export function error(msg: string): never {
throw new Error(`Internal error: ${msg}`);
}
export function createMessageDiagnostic(messageText: string): ts.Diagnostic {
return {
file: undefined,
start: undefined,
length: undefined,
category: ts.DiagnosticCategory.Message,
messageText,
code: DEFAULT_ERROR_CODE,
source: SOURCE,
};
}
/**
* Strip multiline comment start and end markers from the `commentText` string.
*
* This will also strip the JSDOC comment start marker (`/**`).
*/
export function stripComment(commentText: string): string {
return commentText
.replace(/^\/\*\*?/, '')
.replace(/\*\/$/, '')
.trim();
}
| {
"end_byte": 958,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/util.ts"
} |
angular/packages/compiler-cli/src/transformers/compiler_host.ts_0_782 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {CompilerHost, CompilerOptions} from './api';
let wrapHostForTest: ((host: ts.CompilerHost) => ts.CompilerHost) | null = null;
export function setWrapHostForTest(
wrapFn: ((host: ts.CompilerHost) => ts.CompilerHost) | null,
): void {
wrapHostForTest = wrapFn;
}
export function createCompilerHost({
options,
tsHost = ts.createCompilerHost(options, true),
}: {
options: CompilerOptions;
tsHost?: ts.CompilerHost;
}): CompilerHost {
if (wrapHostForTest !== null) {
tsHost = wrapHostForTest(tsHost);
}
return tsHost;
}
| {
"end_byte": 782,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/compiler_host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/tsc_plugin.ts_0_6403 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {
CompilationTicket,
freshCompilationTicket,
incrementalFromStateTicket,
NgCompiler,
NgCompilerHost,
} from './core';
import {NgCompilerOptions, UnifiedModulesHost} from './core/api';
import {AbsoluteFsPath, NodeJSFileSystem, resolve, setFileSystem} from './file_system';
import {PatchedProgramIncrementalBuildStrategy} from './incremental';
import {ActivePerfRecorder, PerfPhase} from './perf';
import {TsCreateProgramDriver} from './program_driver';
import {untagAllTsFiles} from './shims';
import {OptimizeFor} from './typecheck/api';
// The following is needed to fix a the chicken-and-egg issue where the sync (into g3) script will
// refuse to accept this file unless the following string appears:
// import * as plugin from '@bazel/concatjs/internal/tsc_wrapped/plugin_api';
/**
* A `ts.CompilerHost` which also returns a list of input files, out of which the `ts.Program`
* should be created.
*
* Currently mirrored from @bazel/concatjs/internal/tsc_wrapped/plugin_api (with the naming of
* `fileNameToModuleName` corrected).
*/
export interface PluginCompilerHost extends ts.CompilerHost, Partial<UnifiedModulesHost> {
readonly inputFiles: ReadonlyArray<string>;
}
/**
* Mirrors the plugin interface from tsc_wrapped which is currently under active development. To
* enable progress to be made in parallel, the upstream interface isn't implemented directly.
* Instead, `TscPlugin` here is structurally assignable to what tsc_wrapped expects.
*/
interface TscPlugin {
readonly name: string;
wrapHost(
host: ts.CompilerHost & Partial<UnifiedModulesHost>,
inputFiles: ReadonlyArray<string>,
options: ts.CompilerOptions,
): PluginCompilerHost;
setupCompilation(
program: ts.Program,
oldProgram?: ts.Program,
): {
ignoreForDiagnostics: Set<ts.SourceFile>;
ignoreForEmit: Set<ts.SourceFile>;
};
getDiagnostics(file?: ts.SourceFile): ts.Diagnostic[];
getOptionDiagnostics(): ts.Diagnostic[];
getNextProgram(): ts.Program;
createTransformers(): ts.CustomTransformers;
}
/**
* A plugin for `tsc_wrapped` which allows Angular compilation from a plain `ts_library`.
*/
export class NgTscPlugin implements TscPlugin {
name = 'ngtsc';
private options: NgCompilerOptions | null = null;
private host: NgCompilerHost | null = null;
private _compiler: NgCompiler | null = null;
get compiler(): NgCompiler {
if (this._compiler === null) {
throw new Error('Lifecycle error: setupCompilation() must be called first.');
}
return this._compiler;
}
constructor(private ngOptions: {}) {
setFileSystem(new NodeJSFileSystem());
}
wrapHost(
host: ts.CompilerHost & Partial<UnifiedModulesHost>,
inputFiles: readonly string[],
options: ts.CompilerOptions,
): PluginCompilerHost {
// TODO(alxhub): Eventually the `wrapHost()` API will accept the old `ts.Program` (if one is
// available). When it does, its `ts.SourceFile`s need to be re-tagged to enable proper
// incremental compilation.
this.options = {...this.ngOptions, ...options} as NgCompilerOptions;
this.host = NgCompilerHost.wrap(host, inputFiles, this.options, /* oldProgram */ null);
return this.host;
}
setupCompilation(
program: ts.Program,
oldProgram?: ts.Program,
): {
ignoreForDiagnostics: Set<ts.SourceFile>;
ignoreForEmit: Set<ts.SourceFile>;
} {
// TODO(alxhub): we provide a `PerfRecorder` to the compiler, but because we're not driving the
// compilation, the information captured within it is incomplete, and may not include timings
// for phases such as emit.
//
// Additionally, nothing actually captures the perf results here, so recording stats at all is
// somewhat moot for now :)
const perfRecorder = ActivePerfRecorder.zeroedToNow();
if (this.host === null || this.options === null) {
throw new Error('Lifecycle error: setupCompilation() before wrapHost().');
}
this.host.postProgramCreationCleanup();
const programDriver = new TsCreateProgramDriver(
program,
this.host,
this.options,
this.host.shimExtensionPrefixes,
);
const strategy = new PatchedProgramIncrementalBuildStrategy();
const oldState = oldProgram !== undefined ? strategy.getIncrementalState(oldProgram) : null;
let ticket: CompilationTicket;
const modifiedResourceFiles = new Set<AbsoluteFsPath>();
if (this.host.getModifiedResourceFiles !== undefined) {
for (const resourceFile of this.host.getModifiedResourceFiles() ?? []) {
modifiedResourceFiles.add(resolve(resourceFile));
}
}
if (oldProgram === undefined || oldState === null) {
ticket = freshCompilationTicket(
program,
this.options,
strategy,
programDriver,
perfRecorder,
/* enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
} else {
strategy.toNextBuildStrategy().getIncrementalState(oldProgram);
ticket = incrementalFromStateTicket(
oldProgram,
oldState,
program,
this.options,
strategy,
programDriver,
modifiedResourceFiles,
perfRecorder,
false,
false,
);
}
this._compiler = NgCompiler.fromTicket(ticket, this.host);
return {
ignoreForDiagnostics: this._compiler.ignoreForDiagnostics,
ignoreForEmit: this._compiler.ignoreForEmit,
};
}
getDiagnostics(file?: ts.SourceFile): ts.Diagnostic[] {
if (file === undefined) {
return this.compiler.getDiagnostics();
}
return this.compiler.getDiagnosticsForFile(file, OptimizeFor.WholeProgram);
}
getOptionDiagnostics(): ts.Diagnostic[] {
return this.compiler.getOptionDiagnostics();
}
getNextProgram(): ts.Program {
return this.compiler.getCurrentProgram();
}
createTransformers(): ts.CustomTransformers {
// The plugin consumer doesn't know about our perf tracing system, so we consider the emit phase
// as beginning now.
this.compiler.perfRecorder.phase(PerfPhase.TypeScriptEmit);
return this.compiler.prepareEmit().transformers;
}
}
| {
"end_byte": 6403,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/tsc_plugin.ts"
} |
angular/packages/compiler-cli/src/ngtsc/program.ts_0_9015 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HtmlParser, MessageBundle} from '@angular/compiler';
import ts from 'typescript';
import * as api from '../transformers/api';
import {i18nExtract} from '../transformers/i18n';
import {verifySupportedTypeScriptVersion} from '../typescript_support';
import {
CompilationTicket,
freshCompilationTicket,
incrementalFromCompilerTicket,
NgCompiler,
NgCompilerHost,
} from './core';
import {NgCompilerOptions} from './core/api';
import {DocEntry} from './docs';
import {absoluteFrom, AbsoluteFsPath, getFileSystem, resolve} from './file_system';
import {TrackedIncrementalBuildStrategy} from './incremental';
import {IndexedComponent} from './indexer';
import {ActivePerfRecorder, PerfCheckpoint as PerfCheckpoint, PerfEvent, PerfPhase} from './perf';
import {TsCreateProgramDriver} from './program_driver';
import {DeclarationNode} from './reflection';
import {retagAllTsFiles} from './shims';
import {OptimizeFor} from './typecheck/api';
/**
* Entrypoint to the Angular Compiler (Ivy+) which sits behind the `api.Program` interface, allowing
* it to be a drop-in replacement for the legacy View Engine compiler to tooling such as the
* command-line main() function or the Angular CLI.
*/
export class NgtscProgram implements api.Program {
readonly compiler: NgCompiler;
/**
* The primary TypeScript program, which is used for analysis and emit.
*/
private tsProgram: ts.Program;
private host: NgCompilerHost;
private incrementalStrategy: TrackedIncrementalBuildStrategy;
constructor(
rootNames: ReadonlyArray<string>,
private options: NgCompilerOptions,
delegateHost: api.CompilerHost,
oldProgram?: NgtscProgram,
) {
const perfRecorder = ActivePerfRecorder.zeroedToNow();
perfRecorder.phase(PerfPhase.Setup);
// First, check whether the current TS version is supported.
if (!options.disableTypeScriptVersionCheck) {
verifySupportedTypeScriptVersion();
}
// In local compilation mode there are almost always (many) emit errors due to imports that
// cannot be resolved. So we should emit regardless.
if (options.compilationMode === 'experimental-local') {
options.noEmitOnError = false;
}
const reuseProgram = oldProgram?.compiler.getCurrentProgram();
this.host = NgCompilerHost.wrap(delegateHost, rootNames, options, reuseProgram ?? null);
if (reuseProgram !== undefined) {
// Prior to reusing the old program, restore shim tagging for all its `ts.SourceFile`s.
// TypeScript checks the `referencedFiles` of `ts.SourceFile`s for changes when evaluating
// incremental reuse of data from the old program, so it's important that these match in order
// to get the most benefit out of reuse.
retagAllTsFiles(reuseProgram);
}
this.tsProgram = perfRecorder.inPhase(PerfPhase.TypeScriptProgramCreate, () =>
ts.createProgram(this.host.inputFiles, options, this.host, reuseProgram),
);
perfRecorder.phase(PerfPhase.Unaccounted);
perfRecorder.memory(PerfCheckpoint.TypeScriptProgramCreate);
this.host.postProgramCreationCleanup();
const programDriver = new TsCreateProgramDriver(
this.tsProgram,
this.host,
this.options,
this.host.shimExtensionPrefixes,
);
this.incrementalStrategy =
oldProgram !== undefined
? oldProgram.incrementalStrategy.toNextBuildStrategy()
: new TrackedIncrementalBuildStrategy();
const modifiedResourceFiles = new Set<AbsoluteFsPath>();
if (this.host.getModifiedResourceFiles !== undefined) {
const strings = this.host.getModifiedResourceFiles();
if (strings !== undefined) {
for (const fileString of strings) {
modifiedResourceFiles.add(absoluteFrom(fileString));
}
}
}
let ticket: CompilationTicket;
if (oldProgram === undefined) {
ticket = freshCompilationTicket(
this.tsProgram,
options,
this.incrementalStrategy,
programDriver,
perfRecorder,
/* enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
} else {
ticket = incrementalFromCompilerTicket(
oldProgram.compiler,
this.tsProgram,
this.incrementalStrategy,
programDriver,
modifiedResourceFiles,
perfRecorder,
);
}
// Create the NgCompiler which will drive the rest of the compilation.
this.compiler = NgCompiler.fromTicket(ticket, this.host);
}
getTsProgram(): ts.Program {
return this.tsProgram;
}
getReuseTsProgram(): ts.Program {
return this.compiler.getCurrentProgram();
}
getTsOptionDiagnostics(
cancellationToken?: ts.CancellationToken | undefined,
): readonly ts.Diagnostic[] {
return this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptDiagnostics, () =>
this.tsProgram.getOptionsDiagnostics(cancellationToken),
);
}
getTsSyntacticDiagnostics(
sourceFile?: ts.SourceFile | undefined,
cancellationToken?: ts.CancellationToken | undefined,
): readonly ts.Diagnostic[] {
return this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptDiagnostics, () => {
const ignoredFiles = this.compiler.ignoreForDiagnostics;
let res: readonly ts.Diagnostic[];
if (sourceFile !== undefined) {
if (ignoredFiles.has(sourceFile)) {
return [];
}
res = this.tsProgram.getSyntacticDiagnostics(sourceFile, cancellationToken);
} else {
const diagnostics: ts.Diagnostic[] = [];
for (const sf of this.tsProgram.getSourceFiles()) {
if (!ignoredFiles.has(sf)) {
diagnostics.push(...this.tsProgram.getSyntacticDiagnostics(sf, cancellationToken));
}
}
res = diagnostics;
}
return res;
});
}
getTsSemanticDiagnostics(
sourceFile?: ts.SourceFile | undefined,
cancellationToken?: ts.CancellationToken | undefined,
): readonly ts.Diagnostic[] {
// No TS semantic check should be done in local compilation mode, as it is always full of errors
// due to cross file imports.
if (this.options.compilationMode === 'experimental-local') {
return [];
}
return this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptDiagnostics, () => {
const ignoredFiles = this.compiler.ignoreForDiagnostics;
let res: readonly ts.Diagnostic[];
if (sourceFile !== undefined) {
if (ignoredFiles.has(sourceFile)) {
return [];
}
res = this.tsProgram.getSemanticDiagnostics(sourceFile, cancellationToken);
} else {
const diagnostics: ts.Diagnostic[] = [];
for (const sf of this.tsProgram.getSourceFiles()) {
if (!ignoredFiles.has(sf)) {
diagnostics.push(...this.tsProgram.getSemanticDiagnostics(sf, cancellationToken));
}
}
res = diagnostics;
}
return res;
});
}
getNgOptionDiagnostics(
cancellationToken?: ts.CancellationToken | undefined,
): readonly ts.Diagnostic[] {
return this.compiler.getOptionDiagnostics();
}
getNgStructuralDiagnostics(
cancellationToken?: ts.CancellationToken | undefined,
): readonly ts.Diagnostic[] {
return [];
}
getNgSemanticDiagnostics(
fileName?: string | undefined,
cancellationToken?: ts.CancellationToken | undefined,
): readonly ts.Diagnostic[] {
let sf: ts.SourceFile | undefined = undefined;
if (fileName !== undefined) {
sf = this.tsProgram.getSourceFile(fileName);
if (sf === undefined) {
// There are no diagnostics for files which don't exist in the program - maybe the caller
// has stale data?
return [];
}
}
if (sf === undefined) {
return this.compiler.getDiagnostics();
} else {
return this.compiler.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram);
}
}
/**
* Ensure that the `NgCompiler` has properly analyzed the program, and allow for the asynchronous
* loading of any resources during the process.
*
* This is used by the Angular CLI to allow for spawning (async) child compilations for things
* like SASS files used in `styleUrls`.
*/
loadNgStructureAsync(): Promise<void> {
return this.compiler.analyzeAsync();
}
listLazyRoutes(entryRoute?: string | undefined): api.LazyRoute[] {
return [];
}
private emitXi18n(): void {
const ctx = new MessageBundle(
new HtmlParser(),
[],
{},
this.options.i18nOutLocale ?? null,
this.options.i18nPreserveWhitespaceForLegacyExtraction,
);
this.compiler.xi18n(ctx);
i18nExtract(
this.options.i18nOutFormat ?? null,
this.options.i18nOutFile ?? null,
this.host,
this.options,
ctx,
resolve,
);
} | {
"end_byte": 9015,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program.ts"
} |
angular/packages/compiler-cli/src/ngtsc/program.ts_9019_14499 | emit<CbEmitRes extends ts.EmitResult>(
opts?: api.EmitOptions<CbEmitRes> | undefined,
): ts.EmitResult {
// Check if emission of the i18n messages bundle was requested.
if (
opts !== undefined &&
opts.emitFlags !== undefined &&
opts.emitFlags & api.EmitFlags.I18nBundle
) {
this.emitXi18n();
// `api.EmitFlags` is a View Engine compiler concept. We only pay attention to the absence of
// the other flags here if i18n emit was requested (since this is usually done in the xi18n
// flow, where we don't want to emit JS at all).
if (!(opts.emitFlags & api.EmitFlags.JS)) {
return {
diagnostics: [],
emitSkipped: true,
emittedFiles: [],
};
}
}
const forceEmit = opts?.forceEmit ?? false;
this.compiler.perfRecorder.memory(PerfCheckpoint.PreEmit);
const res = this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptEmit, () => {
const {transformers} = this.compiler.prepareEmit();
const ignoreFiles = this.compiler.ignoreForEmit;
const emitCallback = (opts?.emitCallback ??
defaultEmitCallback) as api.TsEmitCallback<CbEmitRes>;
const writeFile: ts.WriteFileCallback = (
fileName: string,
data: string,
writeByteOrderMark: boolean,
onError: ((message: string) => void) | undefined,
sourceFiles: ReadonlyArray<ts.SourceFile> | undefined,
) => {
if (sourceFiles !== undefined) {
// Record successful writes for any `ts.SourceFile` (that's not a declaration file)
// that's an input to this write.
for (const writtenSf of sourceFiles) {
if (writtenSf.isDeclarationFile) {
continue;
}
this.compiler.incrementalCompilation.recordSuccessfulEmit(writtenSf);
}
}
this.host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
};
const customTransforms = opts && opts.customTransformers;
const beforeTransforms = transformers.before || [];
const afterDeclarationsTransforms = transformers.afterDeclarations;
if (customTransforms !== undefined && customTransforms.beforeTs !== undefined) {
beforeTransforms.push(...customTransforms.beforeTs);
}
const emitResults: CbEmitRes[] = [];
for (const targetSourceFile of this.tsProgram.getSourceFiles()) {
if (targetSourceFile.isDeclarationFile || ignoreFiles.has(targetSourceFile)) {
continue;
}
if (!forceEmit && this.compiler.incrementalCompilation.safeToSkipEmit(targetSourceFile)) {
this.compiler.perfRecorder.eventCount(PerfEvent.EmitSkipSourceFile);
continue;
}
this.compiler.perfRecorder.eventCount(PerfEvent.EmitSourceFile);
emitResults.push(
emitCallback({
targetSourceFile,
program: this.tsProgram,
host: this.host,
options: this.options,
emitOnlyDtsFiles: false,
writeFile,
customTransformers: {
before: beforeTransforms,
after: customTransforms && customTransforms.afterTs,
afterDeclarations: afterDeclarationsTransforms,
} as any,
}),
);
}
this.compiler.perfRecorder.memory(PerfCheckpoint.Emit);
// Run the emit, including a custom transformer that will downlevel the Ivy decorators in
// code.
return ((opts && opts.mergeEmitResultsCallback) || mergeEmitResults)(emitResults);
});
// Record performance analysis information to disk if we've been asked to do so.
if (this.options.tracePerformance !== undefined) {
const perf = this.compiler.perfRecorder.finalize();
getFileSystem().writeFile(
getFileSystem().resolve(this.options.tracePerformance),
JSON.stringify(perf, null, 2),
);
}
return res;
}
getIndexedComponents(): Map<DeclarationNode, IndexedComponent> {
return this.compiler.getIndexedComponents();
}
/**
* Gets information for the current program that may be used to generate API
* reference documentation. This includes Angular-specific information, such
* as component inputs and outputs.
*
* @param entryPoint Path to the entry point for the package for which API
* docs should be extracted.
*/
getApiDocumentation(
entryPoint: string,
privateModules: Set<string>,
): {entries: DocEntry[]; symbols: Map<string, string>} {
return this.compiler.getApiDocumentation(entryPoint, privateModules);
}
getEmittedSourceFiles(): Map<string, ts.SourceFile> {
throw new Error('Method not implemented.');
}
}
const defaultEmitCallback: api.TsEmitCallback<ts.EmitResult> = ({
program,
targetSourceFile,
writeFile,
cancellationToken,
emitOnlyDtsFiles,
customTransformers,
}) =>
program.emit(
targetSourceFile,
writeFile,
cancellationToken,
emitOnlyDtsFiles,
customTransformers,
);
function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult {
const diagnostics: ts.Diagnostic[] = [];
let emitSkipped = false;
const emittedFiles: string[] = [];
for (const er of emitResults) {
diagnostics.push(...er.diagnostics);
emitSkipped = emitSkipped || er.emitSkipped;
emittedFiles.push(...(er.emittedFiles || []));
}
return {diagnostics, emitSkipped, emittedFiles};
} | {
"end_byte": 14499,
"start_byte": 9019,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program.ts"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/BUILD.bazel_0_356 | package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "cycles",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
module_name = "@angular/compiler-cli/src/ngtsc/cycles",
deps = [
"//packages/compiler-cli/src/ngtsc/perf",
"@npm//typescript",
],
)
| {
"end_byte": 356,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/index.ts_0_323 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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 {Cycle, CycleAnalyzer, CycleHandlingStrategy} from './src/analyzer';
export {ImportGraph} from './src/imports';
| {
"end_byte": 323,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/test/imports_spec.ts_0_2943 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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, getFileSystem, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {NOOP_PERF_RECORDER} from '../../perf';
import {ImportGraph} from '../src/imports';
import {importPath, makeProgramFromGraph} from './util';
runInEachFileSystem(() => {
describe('ImportGraph', () => {
let _: typeof absoluteFrom;
beforeEach(() => (_ = absoluteFrom));
describe('importsOf()', () => {
it('should record imports of a simple program', () => {
const {program, graph} = makeImportGraph('a:b;b:c;c');
const a = getSourceFileOrError(program, _('/a.ts'));
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
expect(importsToString(graph.importsOf(a))).toBe('b');
expect(importsToString(graph.importsOf(b))).toBe('c');
});
});
describe('findPath()', () => {
it('should be able to compute the path between two source files if there is a cycle', () => {
const {program, graph} = makeImportGraph('a:*b,*c;b:*e,*f;c:*g,*h;e:f;f;g:e;h:g');
const a = getSourceFileOrError(program, _('/a.ts'));
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
const e = getSourceFileOrError(program, _('/e.ts'));
expect(importPath(graph.findPath(a, a)!)).toBe('a');
expect(importPath(graph.findPath(a, b)!)).toBe('a,b');
expect(importPath(graph.findPath(c, e)!)).toBe('c,g,e');
expect(graph.findPath(e, c)).toBe(null);
expect(graph.findPath(b, c)).toBe(null);
});
it('should handle circular dependencies within the path between `from` and `to`', () => {
// a -> b -> c -> d
// ^----/ |
// ^---------/
const {program, graph} = makeImportGraph('a:b;b:a,c;c:a,d;d');
const a = getSourceFileOrError(program, _('/a.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
const d = getSourceFileOrError(program, _('/d.ts'));
expect(importPath(graph.findPath(a, d)!)).toBe('a,b,c,d');
});
});
});
function makeImportGraph(graph: string): {program: ts.Program; graph: ImportGraph} {
const {program} = makeProgramFromGraph(getFileSystem(), graph);
return {
program,
graph: new ImportGraph(program.getTypeChecker(), NOOP_PERF_RECORDER),
};
}
function importsToString(imports: Set<ts.SourceFile>): string {
const fs = getFileSystem();
return Array.from(imports)
.map((sf) => fs.basename(sf.fileName).replace('.ts', ''))
.sort()
.join(',');
}
});
| {
"end_byte": 2943,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/test/imports_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/test/analyzer_spec.ts_0_4872 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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, getFileSystem, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {NOOP_PERF_RECORDER} from '../../perf';
import {Cycle, CycleAnalyzer} from '../src/analyzer';
import {ImportGraph} from '../src/imports';
import {importPath, makeProgramFromGraph} from './util';
runInEachFileSystem(() => {
describe('cycle analyzer', () => {
let _: typeof absoluteFrom;
beforeEach(() => (_ = absoluteFrom));
it("should not detect a cycle when there isn't one", () => {
const {program, analyzer} = makeAnalyzer('a:b,c;b;c');
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
expect(analyzer.wouldCreateCycle(b, c)).toBe(null);
expect(analyzer.wouldCreateCycle(c, b)).toBe(null);
});
it('should detect a simple cycle between two files', () => {
const {program, analyzer} = makeAnalyzer('a:b;b');
const a = getSourceFileOrError(program, _('/a.ts'));
const b = getSourceFileOrError(program, _('/b.ts'));
expect(analyzer.wouldCreateCycle(a, b)).toBe(null);
const cycle = analyzer.wouldCreateCycle(b, a);
expect(cycle).toBeInstanceOf(Cycle);
expect(importPath(cycle!.getPath())).toEqual('b,a,b');
});
it('should deal with cycles', () => {
// a -> b -> c -> d
// ^---------/
const {program, analyzer} = makeAnalyzer('a:b;b:c;c:d;d:b');
const a = getSourceFileOrError(program, _('/a.ts'));
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
const d = getSourceFileOrError(program, _('/d.ts'));
expect(analyzer.wouldCreateCycle(a, b)).toBe(null);
expect(analyzer.wouldCreateCycle(a, c)).toBe(null);
expect(analyzer.wouldCreateCycle(a, d)).toBe(null);
expect(analyzer.wouldCreateCycle(b, a)).not.toBe(null);
expect(analyzer.wouldCreateCycle(b, c)).not.toBe(null);
expect(analyzer.wouldCreateCycle(b, d)).not.toBe(null);
});
it('should detect a cycle with a re-export in the chain', () => {
const {program, analyzer} = makeAnalyzer('a:*b;b:c;c');
const a = getSourceFileOrError(program, _('/a.ts'));
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
expect(analyzer.wouldCreateCycle(a, c)).toBe(null);
const cycle = analyzer.wouldCreateCycle(c, a);
expect(cycle).toBeInstanceOf(Cycle);
expect(importPath(cycle!.getPath())).toEqual('c,a,b,c');
});
it('should detect a cycle in a more complex program', () => {
const {program, analyzer} = makeAnalyzer('a:*b,*c;b:*e,*f;c:*g,*h;e:f;f:c;g;h:g');
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
const e = getSourceFileOrError(program, _('/e.ts'));
const f = getSourceFileOrError(program, _('/f.ts'));
const g = getSourceFileOrError(program, _('/g.ts'));
expect(analyzer.wouldCreateCycle(b, g)).toBe(null);
const cycle = analyzer.wouldCreateCycle(g, b);
expect(cycle).toBeInstanceOf(Cycle);
expect(importPath(cycle!.getPath())).toEqual('g,b,f,c,g');
});
it('should detect a cycle caused by a synthetic edge', () => {
const {program, analyzer} = makeAnalyzer('a:b,c;b;c');
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
expect(analyzer.wouldCreateCycle(b, c)).toBe(null);
analyzer.recordSyntheticImport(c, b);
const cycle = analyzer.wouldCreateCycle(b, c);
expect(cycle).toBeInstanceOf(Cycle);
expect(importPath(cycle!.getPath())).toEqual('b,c,b');
});
it('should not consider type-only imports', () => {
const {program, analyzer} = makeAnalyzer('a:b,c!;b;c');
const a = getSourceFileOrError(program, _('/a.ts'));
const b = getSourceFileOrError(program, _('/b.ts'));
const c = getSourceFileOrError(program, _('/c.ts'));
expect(analyzer.wouldCreateCycle(c, a)).toBe(null);
const cycle = analyzer.wouldCreateCycle(b, a);
expect(cycle).toBeInstanceOf(Cycle);
expect(importPath(cycle!.getPath())).toEqual('b,a,b');
});
});
function makeAnalyzer(graph: string): {program: ts.Program; analyzer: CycleAnalyzer} {
const {program} = makeProgramFromGraph(getFileSystem(), graph);
return {
program,
analyzer: new CycleAnalyzer(new ImportGraph(program.getTypeChecker(), NOOP_PERF_RECORDER)),
};
}
});
| {
"end_byte": 4872,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/test/analyzer_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/test/util.ts_0_2326 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {getFileSystem, PathManipulation} from '../../file_system';
import {TestFile} from '../../file_system/testing';
import {makeProgram} from '../../testing';
/**
* Construct a TS program consisting solely of an import graph, from a string-based representation
* of the graph.
*
* The `graph` string consists of semicolon separated files, where each file is specified
* as a name and (optionally) a list of comma-separated imports or exports. For example:
*
* "a:b,c;b;c"
*
* specifies a program with three files (a.ts, b.ts, c.ts) where a.ts imports from both b.ts and
* c.ts.
*
* A more complicated example has a dependency from b.ts to c.ts: "a:b,c;b:c;c".
*
* A * preceding a file name in the list of imports indicates that the dependency should be an
* "export" and not an "import" dependency. For example:
*
* "a:*b,c;b;c"
*
* represents a program where a.ts exports from b.ts and imports from c.ts.
*
* An import can be suffixed with ! to make it a type-only import.
*/
export function makeProgramFromGraph(
fs: PathManipulation,
graph: string,
): {
program: ts.Program;
host: ts.CompilerHost;
options: ts.CompilerOptions;
} {
const files: TestFile[] = graph.split(';').map((fileSegment) => {
const [name, importList] = fileSegment.split(':');
const contents =
(importList ? importList.split(',') : [])
.map((i) => {
if (i.startsWith('*')) {
const sym = i.slice(1);
return `export {${sym}} from './${sym}';`;
} else if (i.endsWith('!')) {
const sym = i.slice(0, -1);
return `import type {${sym}} from './${sym}';`;
} else {
return `import {${i}} from './${i}';`;
}
})
.join('\n') + `export const ${name} = '${name}';\n`;
return {
name: fs.resolve(`/${name}.ts`),
contents,
};
});
return makeProgram(files);
}
export function importPath(files: ts.SourceFile[]): string {
const fs = getFileSystem();
return files.map((sf) => fs.basename(sf.fileName).replace('.ts', '')).join(',');
}
| {
"end_byte": 2326,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/test/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/test/BUILD.bazel_0_711 | 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/cycles",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/testing",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 711,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/src/imports.ts_0_5358 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {PerfPhase, PerfRecorder} from '../../perf';
/**
* A cached graph of imports in the `ts.Program`.
*
* The `ImportGraph` keeps track of dependencies (imports) of individual `ts.SourceFile`s. Only
* dependencies within the same program are tracked; imports into packages on NPM are not.
*/
export class ImportGraph {
private imports = new Map<ts.SourceFile, Set<ts.SourceFile>>();
constructor(
private checker: ts.TypeChecker,
private perf: PerfRecorder,
) {}
/**
* List the direct (not transitive) imports of a given `ts.SourceFile`.
*
* This operation is cached.
*/
importsOf(sf: ts.SourceFile): Set<ts.SourceFile> {
if (!this.imports.has(sf)) {
this.imports.set(sf, this.scanImports(sf));
}
return this.imports.get(sf)!;
}
/**
* Find an import path from the `start` SourceFile to the `end` SourceFile.
*
* This function implements a breadth first search that results in finding the
* shortest path between the `start` and `end` points.
*
* @param start the starting point of the path.
* @param end the ending point of the path.
* @returns an array of source files that connect the `start` and `end` source files, or `null` if
* no path could be found.
*/
findPath(start: ts.SourceFile, end: ts.SourceFile): ts.SourceFile[] | null {
if (start === end) {
// Escape early for the case where `start` and `end` are the same.
return [start];
}
const found = new Set<ts.SourceFile>([start]);
const queue: Found[] = [new Found(start, null)];
while (queue.length > 0) {
const current = queue.shift()!;
const imports = this.importsOf(current.sourceFile);
for (const importedFile of imports) {
if (!found.has(importedFile)) {
const next = new Found(importedFile, current);
if (next.sourceFile === end) {
// We have hit the target `end` path so we can stop here.
return next.toPath();
}
found.add(importedFile);
queue.push(next);
}
}
}
return null;
}
/**
* Add a record of an import from `sf` to `imported`, that's not present in the original
* `ts.Program` but will be remembered by the `ImportGraph`.
*/
addSyntheticImport(sf: ts.SourceFile, imported: ts.SourceFile): void {
if (isLocalFile(imported)) {
this.importsOf(sf).add(imported);
}
}
private scanImports(sf: ts.SourceFile): Set<ts.SourceFile> {
return this.perf.inPhase(PerfPhase.CycleDetection, () => {
const imports = new Set<ts.SourceFile>();
// Look through the source file for import and export statements.
for (const stmt of sf.statements) {
if (
(!ts.isImportDeclaration(stmt) && !ts.isExportDeclaration(stmt)) ||
stmt.moduleSpecifier === undefined
) {
continue;
}
if (
ts.isImportDeclaration(stmt) &&
stmt.importClause !== undefined &&
isTypeOnlyImportClause(stmt.importClause)
) {
// Exclude type-only imports as they are always elided, so they don't contribute to
// cycles.
continue;
}
const symbol = this.checker.getSymbolAtLocation(stmt.moduleSpecifier);
if (symbol === undefined || symbol.valueDeclaration === undefined) {
// No symbol could be found to skip over this import/export.
continue;
}
const moduleFile = symbol.valueDeclaration;
if (ts.isSourceFile(moduleFile) && isLocalFile(moduleFile)) {
// Record this local import.
imports.add(moduleFile);
}
}
return imports;
});
}
}
function isLocalFile(sf: ts.SourceFile): boolean {
return !sf.isDeclarationFile;
}
function isTypeOnlyImportClause(node: ts.ImportClause): boolean {
// The clause itself is type-only (e.g. `import type {foo} from '...'`).
if (node.isTypeOnly) {
return true;
}
// All the specifiers in the cause are type-only (e.g. `import {type a, type b} from '...'`).
if (
node.namedBindings !== undefined &&
ts.isNamedImports(node.namedBindings) &&
node.namedBindings.elements.every((specifier) => specifier.isTypeOnly)
) {
return true;
}
return false;
}
/**
* A helper class to track which SourceFiles are being processed when searching for a path in
* `getPath()` above.
*/
class Found {
constructor(
readonly sourceFile: ts.SourceFile,
readonly parent: Found | null,
) {}
/**
* Back track through this found SourceFile and its ancestors to generate an array of
* SourceFiles that form am import path between two SourceFiles.
*/
toPath(): ts.SourceFile[] {
const array: ts.SourceFile[] = [];
let current: Found | null = this;
while (current !== null) {
array.push(current.sourceFile);
current = current.parent;
}
// Pushing and then reversing, O(n), rather than unshifting repeatedly, O(n^2), avoids
// manipulating the array on every iteration: https://stackoverflow.com/a/26370620
return array.reverse();
}
}
| {
"end_byte": 5358,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/src/imports.ts"
} |
angular/packages/compiler-cli/src/ngtsc/cycles/src/analyzer.ts_0_5283 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ImportGraph} from './imports';
/**
* Analyzes a `ts.Program` for cycles.
*/
export class CycleAnalyzer {
/**
* Cycle detection is requested with the same `from` source file for all used directives and pipes
* within a component, which makes it beneficial to cache the results as long as the `from` source
* file has not changed. This avoids visiting the import graph that is reachable from multiple
* directives/pipes more than once.
*/
private cachedResults: CycleResults | null = null;
constructor(private importGraph: ImportGraph) {}
/**
* Check for a cycle to be created in the `ts.Program` by adding an import between `from` and
* `to`.
*
* @returns a `Cycle` object if an import between `from` and `to` would create a cycle; `null`
* otherwise.
*/
wouldCreateCycle(from: ts.SourceFile, to: ts.SourceFile): Cycle | null {
// Try to reuse the cached results as long as the `from` source file is the same.
if (this.cachedResults === null || this.cachedResults.from !== from) {
this.cachedResults = new CycleResults(from, this.importGraph);
}
// Import of 'from' -> 'to' is illegal if an edge 'to' -> 'from' already exists.
return this.cachedResults.wouldBeCyclic(to) ? new Cycle(this.importGraph, from, to) : null;
}
/**
* Record a synthetic import from `from` to `to`.
*
* This is an import that doesn't exist in the `ts.Program` but will be considered as part of the
* import graph for cycle creation.
*/
recordSyntheticImport(from: ts.SourceFile, to: ts.SourceFile): void {
this.cachedResults = null;
this.importGraph.addSyntheticImport(from, to);
}
}
const NgCyclicResult = Symbol('NgCyclicResult');
type CyclicResultMarker = {
__brand: 'CyclicResultMarker';
};
type CyclicSourceFile = ts.SourceFile & {[NgCyclicResult]?: CyclicResultMarker};
/**
* Stores the results of cycle detection in a memory efficient manner. A symbol is attached to
* source files that indicate what the cyclic analysis result is, as indicated by two markers that
* are unique to this instance. This alleviates memory pressure in large import graphs, as each
* execution is able to store its results in the same memory location (i.e. in the symbol
* on the source file) as earlier executions.
*/
class CycleResults {
private readonly cyclic = {} as CyclicResultMarker;
private readonly acyclic = {} as CyclicResultMarker;
constructor(
readonly from: ts.SourceFile,
private importGraph: ImportGraph,
) {}
wouldBeCyclic(sf: ts.SourceFile): boolean {
const cached = this.getCachedResult(sf);
if (cached !== null) {
// The result for this source file has already been computed, so return its result.
return cached;
}
if (sf === this.from) {
// We have reached the source file that we want to create an import from, which means that
// doing so would create a cycle.
return true;
}
// Assume for now that the file will be acyclic; this prevents infinite recursion in the case
// that `sf` is visited again as part of an existing cycle in the graph.
this.markAcyclic(sf);
const imports = this.importGraph.importsOf(sf);
for (const imported of imports) {
if (this.wouldBeCyclic(imported)) {
this.markCyclic(sf);
return true;
}
}
return false;
}
/**
* Returns whether the source file is already known to be cyclic, or `null` if the result is not
* yet known.
*/
private getCachedResult(sf: CyclicSourceFile): boolean | null {
const result = sf[NgCyclicResult];
if (result === this.cyclic) {
return true;
} else if (result === this.acyclic) {
return false;
} else {
// Either the symbol is missing or its value does not correspond with one of the current
// result markers. As such, the result is unknown.
return null;
}
}
private markCyclic(sf: CyclicSourceFile): void {
sf[NgCyclicResult] = this.cyclic;
}
private markAcyclic(sf: CyclicSourceFile): void {
sf[NgCyclicResult] = this.acyclic;
}
}
/**
* Represents an import cycle between `from` and `to` in the program.
*
* This class allows us to do the work to compute the cyclic path between `from` and `to` only if
* needed.
*/
export class Cycle {
constructor(
private importGraph: ImportGraph,
readonly from: ts.SourceFile,
readonly to: ts.SourceFile,
) {}
/**
* Compute an array of source-files that illustrates the cyclic path between `from` and `to`.
*
* Note that a `Cycle` will not be created unless a path is available between `to` and `from`,
* so `findPath()` will never return `null`.
*/
getPath(): ts.SourceFile[] {
return [this.from, ...this.importGraph.findPath(this.to, this.from)!];
}
}
/**
* What to do if a cycle is detected.
*/
export const enum CycleHandlingStrategy {
/** Add "remote scoping" code to avoid creating a cycle. */
UseRemoteScoping,
/** Fail the compilation with an error. */
Error,
}
| {
"end_byte": 5283,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/cycles/src/analyzer.ts"
} |
angular/packages/compiler-cli/src/ngtsc/program_driver/README.md_0_2512 | # The Program Driver interface
`ProgramDriver` is a small but important interface which allows the template type-checking machinery to request changes to the current `ts.Program`, and to receive a new `ts.Program` with those changes applied. This is used to add template type-checking code to the current `ts.Program`, eventually allowing for diagnostics to be produced within that code. This operation is abstracted behind this interface because different clients create `ts.Program`s differently. The Language Service, for example, creates `ts.Program`s from the current editor state on request, while the TS compiler API creates them explicitly.
When running using the TS APIs, it's important that each new `ts.Program` be created incrementally from the previous `ts.Program`. Under a normal compilation, this means that programs alternate between template type checking programs and user programs:
* `ts.Program#1` is created from user input (the user's source files).
* `ts.Program#2` is created incrementally on top of #1 for template type-checking, and adds private TCB code.
* `ts.Program#3` is created incrementally on top of #2 when the user makes changes to files on disk (incremental build).
* `ts.Program#4` is created incrementally on top of #3 to adjust template type-checking code according to the user's changes.
The `TsCreateProgramDriver` performs this operation for template type-checking `ts.Program`s built by the command-line compiler or by the CLI. The latest template type-checking program is then exposed via the `NgCompiler`'s `getCurrentProgram()` operation, and new user programs are expected to be created incrementally on top of the previous template type-checking program.
## Programs and the compiler as a service
Not all clients of the compiler follow the incremental tick-tock scenario above. When the compiler is used as a service, new `ts.Program`s may be generated in response to various queries, either directly to `NgCompiler` or via the `TemplateTypeChecker`. Internally, the compiler will use the current `ProgramDriver` to create these additional `ts.Program`s as needed.
Incremental builds (new user code changes) may also require changing the `ts.Program`, using the compiler's incremental ticket process. If the `TsCreateProgramDriver` is used, the client is responsible for ensuring that any new incremental `ts.Program`s are created on top of the current program from the previous compilation, which can be obtained via `NgCompiler`'s `getCurrentProgram()`. | {
"end_byte": 2512,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program_driver/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/program_driver/BUILD.bazel_0_477 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "program_driver",
srcs = ["index.ts"] + glob([
"src/*.ts",
]),
module_name = "@angular/compiler-cli/src/ngtsc/program_driver",
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/util",
"@npm//typescript",
],
)
| {
"end_byte": 477,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program_driver/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/program_driver/index.ts_0_301 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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 {TsCreateProgramDriver} from './src/ts_create_program_driver';
| {
"end_byte": 301,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program_driver/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.ts_0_7174 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {copyFileShimData, retagAllTsFiles, ShimReferenceTagger, untagAllTsFiles} from '../../shims';
import {RequiredDelegations, toUnredirectedSourceFile} from '../../util/src/typescript';
import {
FileUpdate,
MaybeSourceFileWithOriginalFile,
NgOriginalFile,
ProgramDriver,
UpdateMode,
} from './api';
/**
* Delegates all methods of `ts.CompilerHost` to a delegate, with the exception of
* `getSourceFile`, `fileExists` and `writeFile` which are implemented in `TypeCheckProgramHost`.
*
* If a new method is added to `ts.CompilerHost` which is not delegated, a type error will be
* generated for this class.
*/
export class DelegatingCompilerHost
implements
Omit<RequiredDelegations<ts.CompilerHost>, 'getSourceFile' | 'fileExists' | 'writeFile'>
{
createHash;
directoryExists;
getCancellationToken;
getCanonicalFileName;
getCurrentDirectory;
getDefaultLibFileName;
getDefaultLibLocation;
getDirectories;
getEnvironmentVariable;
getNewLine;
getParsedCommandLine;
getSourceFileByPath;
readDirectory;
readFile;
realpath;
resolveModuleNames;
resolveTypeReferenceDirectives;
trace;
useCaseSensitiveFileNames;
getModuleResolutionCache;
hasInvalidatedResolutions;
resolveModuleNameLiterals;
resolveTypeReferenceDirectiveReferences;
// jsDocParsingMode is not a method like the other elements above
// TODO: ignore usage can be dropped once 5.2 support is dropped
get jsDocParsingMode() {
// @ts-ignore
return this.delegate.jsDocParsingMode;
}
set jsDocParsingMode(mode) {
// @ts-ignore
this.delegate.jsDocParsingMode = mode;
}
constructor(protected delegate: ts.CompilerHost) {
// Excluded are 'getSourceFile', 'fileExists' and 'writeFile', which are actually implemented by
// `TypeCheckProgramHost` below.
this.createHash = this.delegateMethod('createHash');
this.directoryExists = this.delegateMethod('directoryExists');
this.getCancellationToken = this.delegateMethod('getCancellationToken');
this.getCanonicalFileName = this.delegateMethod('getCanonicalFileName');
this.getCurrentDirectory = this.delegateMethod('getCurrentDirectory');
this.getDefaultLibFileName = this.delegateMethod('getDefaultLibFileName');
this.getDefaultLibLocation = this.delegateMethod('getDefaultLibLocation');
this.getDirectories = this.delegateMethod('getDirectories');
this.getEnvironmentVariable = this.delegateMethod('getEnvironmentVariable');
this.getNewLine = this.delegateMethod('getNewLine');
this.getParsedCommandLine = this.delegateMethod('getParsedCommandLine');
this.getSourceFileByPath = this.delegateMethod('getSourceFileByPath');
this.readDirectory = this.delegateMethod('readDirectory');
this.readFile = this.delegateMethod('readFile');
this.realpath = this.delegateMethod('realpath');
this.resolveModuleNames = this.delegateMethod('resolveModuleNames');
this.resolveTypeReferenceDirectives = this.delegateMethod('resolveTypeReferenceDirectives');
this.trace = this.delegateMethod('trace');
this.useCaseSensitiveFileNames = this.delegateMethod('useCaseSensitiveFileNames');
this.getModuleResolutionCache = this.delegateMethod('getModuleResolutionCache');
this.hasInvalidatedResolutions = this.delegateMethod('hasInvalidatedResolutions');
this.resolveModuleNameLiterals = this.delegateMethod('resolveModuleNameLiterals');
this.resolveTypeReferenceDirectiveReferences = this.delegateMethod(
'resolveTypeReferenceDirectiveReferences',
);
}
private delegateMethod<M extends keyof ts.CompilerHost>(name: M): ts.CompilerHost[M] {
return this.delegate[name] !== undefined
? (this.delegate[name] as any).bind(this.delegate)
: undefined;
}
}
/**
* A `ts.CompilerHost` which augments source files.
*/
class UpdatedProgramHost extends DelegatingCompilerHost {
/**
* Map of source file names to `ts.SourceFile` instances.
*/
private sfMap: Map<string, ts.SourceFile>;
/**
* The `ShimReferenceTagger` responsible for tagging `ts.SourceFile`s loaded via this host.
*
* The `UpdatedProgramHost` is used in the creation of a new `ts.Program`. Even though this new
* program is based on a prior one, TypeScript will still start from the root files and enumerate
* all source files to include in the new program. This means that just like during the original
* program's creation, these source files must be tagged with references to per-file shims in
* order for those shims to be loaded, and then cleaned up afterwards. Thus the
* `UpdatedProgramHost` has its own `ShimReferenceTagger` to perform this function.
*/
private shimTagger: ShimReferenceTagger;
constructor(
sfMap: Map<string, ts.SourceFile>,
private originalProgram: ts.Program,
delegate: ts.CompilerHost,
private shimExtensionPrefixes: string[],
) {
super(delegate);
this.shimTagger = new ShimReferenceTagger(this.shimExtensionPrefixes);
this.sfMap = sfMap;
}
getSourceFile(
fileName: string,
languageVersionOrOptions: ts.ScriptTarget | ts.CreateSourceFileOptions,
onError?: ((message: string) => void) | undefined,
shouldCreateNewSourceFile?: boolean | undefined,
): ts.SourceFile | undefined {
// Try to use the same `ts.SourceFile` as the original program, if possible. This guarantees
// that program reuse will be as efficient as possible.
let delegateSf: ts.SourceFile | undefined = this.originalProgram.getSourceFile(fileName);
if (delegateSf === undefined) {
// Something went wrong and a source file is being requested that's not in the original
// program. Just in case, try to retrieve it from the delegate.
delegateSf = this.delegate.getSourceFile(
fileName,
languageVersionOrOptions,
onError,
shouldCreateNewSourceFile,
)!;
}
if (delegateSf === undefined) {
return undefined;
}
// Look for replacements.
let sf: ts.SourceFile;
if (this.sfMap.has(fileName)) {
sf = this.sfMap.get(fileName)!;
copyFileShimData(delegateSf, sf);
} else {
sf = delegateSf;
}
// TypeScript doesn't allow returning redirect source files. To avoid unforeseen errors we
// return the original source file instead of the redirect target.
sf = toUnredirectedSourceFile(sf);
this.shimTagger.tag(sf);
return sf;
}
postProgramCreationCleanup(): void {
this.shimTagger.finalize();
}
writeFile(): never {
throw new Error(`TypeCheckProgramHost should never write files`);
}
fileExists(fileName: string): boolean {
return this.sfMap.has(fileName) || this.delegate.fileExists(fileName);
}
}
/**
* Updates a `ts.Program` instance with a new one that incorporates specific changes, using the
* TypeScript compiler APIs for incremental program creation.
*/ | {
"end_byte": 7174,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.ts"
} |
angular/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.ts_7175_9747 | export class TsCreateProgramDriver implements ProgramDriver {
/**
* A map of source file paths to replacement `ts.SourceFile`s for those paths.
*
* Effectively, this tracks the delta between the user's program (represented by the
* `originalHost`) and the template type-checking program being managed.
*/
private sfMap = new Map<string, ts.SourceFile>();
private program: ts.Program;
constructor(
private originalProgram: ts.Program,
private originalHost: ts.CompilerHost,
private options: ts.CompilerOptions,
private shimExtensionPrefixes: string[],
) {
this.program = this.originalProgram;
}
readonly supportsInlineOperations = true;
getProgram(): ts.Program {
return this.program;
}
updateFiles(contents: Map<AbsoluteFsPath, FileUpdate>, updateMode: UpdateMode): void {
if (contents.size === 0) {
// No changes have been requested. Is it safe to skip updating entirely?
// If UpdateMode is Incremental, then yes. If UpdateMode is Complete, then it's safe to skip
// only if there are no active changes already (that would be cleared by the update).
if (updateMode !== UpdateMode.Complete || this.sfMap.size === 0) {
// No changes would be made to the `ts.Program` anyway, so it's safe to do nothing here.
return;
}
}
if (updateMode === UpdateMode.Complete) {
this.sfMap.clear();
}
for (const [filePath, {newText, originalFile}] of contents.entries()) {
const sf = ts.createSourceFile(filePath, newText, ts.ScriptTarget.Latest, true);
if (originalFile !== null) {
(sf as MaybeSourceFileWithOriginalFile)[NgOriginalFile] = originalFile;
}
this.sfMap.set(filePath, sf);
}
const host = new UpdatedProgramHost(
this.sfMap,
this.originalProgram,
this.originalHost,
this.shimExtensionPrefixes,
);
const oldProgram = this.program;
// Retag the old program's `ts.SourceFile`s with shim tags, to allow TypeScript to reuse the
// most data.
retagAllTsFiles(oldProgram);
this.program = ts.createProgram({
host,
rootNames: this.program.getRootFileNames(),
options: this.options,
oldProgram,
});
host.postProgramCreationCleanup();
// Only untag the old program. The new program needs to keep the tagged files, because as of
// TS 5.5 not having the files tagged while producing diagnostics can lead to errors. See:
// https://github.com/microsoft/TypeScript/pull/58398
untagAllTsFiles(oldProgram);
}
} | {
"end_byte": 9747,
"start_byte": 7175,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.ts"
} |
angular/packages/compiler-cli/src/ngtsc/program_driver/src/api.ts_0_2489 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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';
export interface FileUpdate {
/**
* The source file text.
*/
newText: string;
/**
* Represents the source file from the original program that is being updated. If the file update
* targets a shim file then this is null, as shim files do not have an associated original file.
*/
originalFile: ts.SourceFile | null;
}
export const NgOriginalFile = Symbol('NgOriginalFile');
/**
* If an updated file has an associated original source file, then the original source file
* is attached to the updated file using the `NgOriginalFile` symbol.
*/
export interface MaybeSourceFileWithOriginalFile extends ts.SourceFile {
[NgOriginalFile]?: ts.SourceFile;
}
export interface ProgramDriver {
/**
* Whether this strategy supports modifying user files (inline modifications) in addition to
* modifying type-checking shims.
*/
readonly supportsInlineOperations: boolean;
/**
* Retrieve the latest version of the program, containing all the updates made thus far.
*/
getProgram(): ts.Program;
/**
* Incorporate a set of changes to either augment or completely replace the type-checking code
* included in the type-checking program.
*/
updateFiles(contents: Map<AbsoluteFsPath, FileUpdate>, updateMode: UpdateMode): void;
/**
* Retrieve a string version for a given `ts.SourceFile`, which much change when the contents of
* the file have changed.
*
* If this method is present, the compiler will use these versions in addition to object identity
* for `ts.SourceFile`s to determine what's changed between two incremental programs. This is
* valuable for some clients (such as the Language Service) that treat `ts.SourceFile`s as mutable
* objects.
*/
getSourceFileVersion?(sf: ts.SourceFile): string;
}
export enum UpdateMode {
/**
* A complete update creates a completely new overlay of type-checking code on top of the user's
* original program, which doesn't include type-checking code from previous calls to
* `updateFiles`.
*/
Complete,
/**
* An incremental update changes the contents of some files in the type-checking program without
* reverting any prior changes.
*/
Incremental,
}
| {
"end_byte": 2489,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/program_driver/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/README.md_0_5358 | # What is the 'core' package?
This package contains the core functionality of the Angular compiler. It provides APIs for the implementor of a TypeScript compiler to provide Angular compilation as well.
It supports the 'ngc' command-line tool and the Angular CLI (via the `NgtscProgram`), as well as an experimental integration with `tsc_wrapped` and the `ts_library` Bazel rule via `NgTscPlugin`.
# Angular compilation
Angular compilation involves the translation of Angular decorators into static definition fields. At build time, this is done during the overall process of TypeScript compilation, where TypeScript code is type-checked and then downleveled to JavaScript code. Along the way, diagnostics specific to Angular can also be produced.
## Compilation flow
Any use of the TypeScript compiler APIs follows a multi-step process:
1. A `ts.CompilerHost` is created.
2. That `ts.CompilerHost`, plus a set of "root files", is used to create a `ts.Program`.
3. The `ts.Program` is used to gather various kinds of diagnostics.
4. Eventually, the `ts.Program` is asked to `emit`, and JavaScript code is produced.
A compiler which integrates Angular compilation into this process follows a very similar flow, with a few extra steps:
1. A `ts.CompilerHost` is created.
2. That `ts.CompilerHost` is wrapped in an `NgCompilerHost`, which adds Angular specific files to the compilation.
3. A `ts.Program` is created from the `NgCompilerHost` and its augmented set of root files.
4. A `CompilationTicket` is created, optionally incorporating any state from a previous compilation run.
4. An `NgCompiler` is created using the `CompilationTicket`.
5. Diagnostics can be gathered from the `ts.Program` as normal, as well as from the `NgCompiler`.
6. Prior to `emit`, `NgCompiler.prepareEmit` is called to retrieve the Angular transformers which need to be fed to `ts.Program.emit`.
7. `emit` is called on the `ts.Program` with the Angular transformers from above, which produces JavaScript code with Angular extensions.
# `NgCompiler` and incremental compilation
The Angular compiler is capable of incremental compilation, where information from a previous compilation is used to accelerate the next compilation. During compilation, the compiler produces two major kinds of information: local information (such as component and directive metadata) and global information (such as reified NgModule scopes). Incremental compilation is managed in two ways:
1. For most changes, a new `NgCompiler` can selectively inherit local information from a previous instance, and only needs to recompute it where an underlying TypeScript file has change. Global information is always recomputed from scratch in this case.
2. For specific changes, such as those in component resources, an `NgCompiler` can be reused in its entirety, and updated to incorporate the effects of such changes without needing to recompute any other information.
Note that these two modes differ in terms of whether a new `NgCompiler` instance is needed or whether a previous one can reused. To prevent leaking this implementation complexity and shield consumers from having to manage the lifecycle of `NgCompiler` so specifically, this process is abstracted via `CompilationTicket`s. Consumers first obtain a `CompilationTicket` (depending on the nature of the incoming change), and then use this ticket to retrieve an `NgCompiler` instance. In creating the `CompilationTicket`, the compiler can decide whether to reuse an old `NgCompiler` instance or to create a new one.
## Asynchronous compilation
In some compilation environments (such as the Webpack-driven compilation inside the Angular CLI), various inputs to the compilation are only producible in an asynchronous fashion. For example, SASS compilation of `styleUrls` that link to SASS files requires spawning a child Webpack compilation. To support this, Angular has an asynchronous interface for loading such resources.
If this interface is used, an additional asynchronous step after `NgCompiler` creation is to call `NgCompiler.analyzeAsync` and await its `Promise`. After this operation completes, all resources have been loaded and the rest of the `NgCompiler` API can be used synchronously.
# Wrapping the `ts.CompilerHost`
Angular compilation generates a number of synthetic files (files which did not exist originally as inputs), depending on configuration. Such files can include:
* A flat module index file, if requested.
* The `__ng_typecheck__.ts` file, which supports template type-checking code.
These files don't exist on disk, but need to appear as such to the `ts.Program`. This is accomplished by wrapping the `ts.CompilerHost` (which abstracts the outside world to the `ts.Program`) in an implementation which provides these synthetic files. This is the primary function of `NgCompilerHost`.
# API definitions
The `core` package contains separate API definitions, which are used across the compiler. Of note is the interface `NgCompilerOptions`, which unifies various supported compilation options across Angular and TypeScript itself. It's assignable to `ts.CompilerOptions`, and implemented by the legacy `CompilerOptions` type in `//packages/compiler-cli/src/transformers/api.ts`.
The various types of options are split out into distinct interfaces according to their purpose and level of support.
| {
"end_byte": 5358,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/core/BUILD.bazel_0_2633 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "core",
srcs = ["index.ts"] + glob([
"src/*.ts",
]),
module_name = "@angular/compiler-cli/src/ngtsc/core",
deps = [
":api",
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/annotations/common",
"//packages/compiler-cli/src/ngtsc/cycles",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/docs",
"//packages/compiler-cli/src/ngtsc/entry_point",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/incremental:api",
"//packages/compiler-cli/src/ngtsc/incremental/semantic_graph",
"//packages/compiler-cli/src/ngtsc/indexer",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/resource",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/shims:api",
"//packages/compiler-cli/src/ngtsc/transform",
"//packages/compiler-cli/src/ngtsc/transform/jit",
"//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"//packages/compiler-cli/src/ngtsc/typecheck/diagnostics",
"//packages/compiler-cli/src/ngtsc/typecheck/extended",
"//packages/compiler-cli/src/ngtsc/typecheck/extended/api",
"//packages/compiler-cli/src/ngtsc/typecheck/template_semantics",
"//packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api",
"//packages/compiler-cli/src/ngtsc/util",
"//packages/compiler-cli/src/ngtsc/validation",
"//packages/compiler-cli/src/ngtsc/xi18n",
"@npm//@types/semver",
"@npm//semver",
"@npm//typescript",
],
)
ts_library(
name = "api",
srcs = glob(["api/**/*.ts"]),
deps = [
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/shims:api",
"@npm//typescript",
],
)
| {
"end_byte": 2633,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/core/index.ts_0_279 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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/compiler';
export {NgCompilerHost} from './src/host';
| {
"end_byte": 279,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/test/BUILD.bazel_0_947 | 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/core",
"//packages/compiler-cli/src/ngtsc/core:api",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 947,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts_0_7698 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 as _,
FileSystem,
getFileSystem,
getSourceFileOrError,
NgtscCompilerHost,
setFileSystem,
} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {IncrementalBuildStrategy, NoopIncrementalBuildStrategy} from '../../incremental';
import {ProgramDriver, TsCreateProgramDriver} from '../../program_driver';
import {ClassDeclaration, isNamedClassDeclaration} from '../../reflection';
import {OptimizeFor} from '../../typecheck/api';
import {NgCompilerOptions} from '../api';
import {freshCompilationTicket, NgCompiler, resourceChangeTicket} from '../src/compiler';
import {NgCompilerHost} from '../src/host';
function makeFreshCompiler(
host: NgCompilerHost,
options: NgCompilerOptions,
program: ts.Program,
programStrategy: ProgramDriver,
incrementalStrategy: IncrementalBuildStrategy,
enableTemplateTypeChecker: boolean,
usePoisonedData: boolean,
): NgCompiler {
const ticket = freshCompilationTicket(
program,
options,
incrementalStrategy,
programStrategy,
/* perfRecorder */ null,
enableTemplateTypeChecker,
usePoisonedData,
);
return NgCompiler.fromTicket(ticket, host);
}
runInEachFileSystem(() => {
describe('NgCompiler', () => {
let fs: FileSystem;
beforeEach(() => {
fs = getFileSystem();
fs.ensureDir(_('/node_modules/@angular/core'));
fs.writeFile(
_('/node_modules/@angular/core/index.d.ts'),
`
export declare const Component: any;
`,
);
});
it('should also return template diagnostics when asked for component diagnostics', () => {
const COMPONENT = _('/cmp.ts');
fs.writeFile(
COMPONENT,
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
templateUrl: './template.html',
})
export class Cmp {}
`,
);
fs.writeFile(_('/template.html'), `{{does_not_exist.foo}}`);
const options: NgCompilerOptions = {
strictTemplates: true,
};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const compiler = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const diags = compiler.getDiagnosticsForFile(
getSourceFileOrError(program, COMPONENT),
OptimizeFor.SingleFile,
);
expect(diags.length).toBe(1);
expect(diags[0].messageText).toContain('does_not_exist');
});
describe('getComponentsWithTemplateFile', () => {
it('should return the component(s) using a template file', () => {
const templateFile = _('/template.html');
fs.writeFile(templateFile, `This is the template, used by components CmpA and CmpC`);
const cmpAFile = _('/cmp-a.ts');
fs.writeFile(
cmpAFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-a',
templateUrl: './template.html',
})
export class CmpA {}
`,
);
const cmpBFile = _('/cmp-b.ts');
fs.writeFile(
cmpBFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-b',
template: 'CmpB does not use an external template',
})
export class CmpB {}
`,
);
const cmpCFile = _('/cmp-c.ts');
fs.writeFile(
cmpCFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-c',
templateUrl: './template.html',
})
export class CmpC {}
`,
);
const options: NgCompilerOptions = {};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(
baseHost,
[cmpAFile, cmpBFile, cmpCFile],
options,
/* oldProgram */ null,
);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const CmpC = getClass(getSourceFileOrError(program, cmpCFile), 'CmpC');
const compiler = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const components = compiler.getComponentsWithTemplateFile(templateFile);
expect(components).toEqual(new Set([CmpA, CmpC]));
});
});
describe('getComponentsWithStyle', () => {
it('should return the component(s) using a style file', () => {
const styleFile = _('/style.css');
fs.writeFile(styleFile, `/* This is the style, used by components CmpA and CmpC */`);
const cmpAFile = _('/cmp-a.ts');
fs.writeFile(
cmpAFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-a',
template: '',
styleUrls: ['./style.css'],
})
export class CmpA {}
`,
);
const cmpBFile = _('/cmp-b.ts');
fs.writeFile(
cmpBFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-b',
template: '',
styles: ['/* CmpB does not use external style */'],
})
export class CmpB {}
`,
);
const cmpCFile = _('/cmp-c.ts');
fs.writeFile(
cmpCFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-c',
template: '',
styleUrls: ['./style.css']
})
export class CmpC {}
`,
);
const options: NgCompilerOptions = {};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(
baseHost,
[cmpAFile, cmpBFile, cmpCFile],
options,
/* oldProgram */ null,
);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const CmpC = getClass(getSourceFileOrError(program, cmpCFile), 'CmpC');
const compiler = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const components = compiler.getComponentsWithStyleFile(styleFile);
expect(components).toEqual(new Set([CmpA, CmpC]));
});
}); | {
"end_byte": 7698,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts_7704_15401 | describe('getComponentResources', () => {
it('should return the component resources', () => {
const styleFile = _('/style.css');
fs.writeFile(styleFile, `/* This is the template, used by components CmpA */`);
const styleFile2 = _('/style2.css');
fs.writeFile(styleFile2, `/* This is the template, used by components CmpA */`);
const templateFile = _('/template.ng.html');
fs.writeFile(templateFile, `This is the template, used by components CmpA`);
const cmpAFile = _('/cmp-a.ts');
fs.writeFile(
cmpAFile,
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp-a',
templateUrl: './template.ng.html',
styleUrls: ['./style.css', '../../style2.css'],
})
export class CmpA {}
`,
);
const options: NgCompilerOptions = {};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(baseHost, [cmpAFile], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const compiler = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const resources = compiler.getComponentResources(CmpA);
expect(resources).not.toBeNull();
const {template, styles} = resources!;
expect(template!.path).toEqual(templateFile);
expect(styles.size).toEqual(2);
const actualPaths = new Set(Array.from(styles).map((r) => r.path));
expect(actualPaths).toEqual(new Set([styleFile, styleFile2]));
});
it('does not return component style resources if not an array of strings', () => {
const styleFile = _('/style.css');
fs.writeFile(styleFile, `/* This is the template, used by components CmpA */`);
const styleFile2 = _('/style2.css');
fs.writeFile(styleFile2, `/* This is the template, used by components CmpA */`);
const cmpAFile = _('/cmp-a.ts');
fs.writeFile(
cmpAFile,
`
import {Component} from '@angular/core';
const STYLES = ['./style.css', '../../style2.css'];
@Component({
selector: 'cmp-a',
template: '',
styleUrls: STYLES,
})
export class CmpA {}
`,
);
const options: NgCompilerOptions = {};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(baseHost, [cmpAFile], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const CmpA = getClass(getSourceFileOrError(program, cmpAFile), 'CmpA');
const compiler = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const resources = compiler.getComponentResources(CmpA);
expect(resources).not.toBeNull();
const {styles} = resources!;
expect(styles.size).toEqual(0);
});
});
describe('getResourceDependencies', () => {
it('should return resource dependencies of a component source file', () => {
const COMPONENT = _('/cmp.ts');
fs.writeFile(
COMPONENT,
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
templateUrl: './template.html',
styleUrls: ['./style.css'],
})
export class Cmp {}
`,
);
fs.writeFile(_('/template.html'), `<h1>Resource</h1>`);
fs.writeFile(_('/style.css'), `h1 { }`);
const options: NgCompilerOptions = {
strictTemplates: true,
};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const compiler = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const deps = compiler.getResourceDependencies(getSourceFileOrError(program, COMPONENT));
expect(deps.length).toBe(2);
expect(deps).toEqual(
jasmine.arrayContaining([
jasmine.stringMatching(/\/template.html$/),
jasmine.stringMatching(/\/style.css$/),
]),
);
});
});
describe('resource-only changes', () => {
it('should reuse the full compilation state for a resource-only change', () => {
const COMPONENT = _('/cmp.ts');
const TEMPLATE = _('/template.html');
fs.writeFile(
COMPONENT,
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
templateUrl: './template.html',
})
export class Cmp {}
`,
);
fs.writeFile(TEMPLATE, `<h1>Resource</h1>`);
const options: NgCompilerOptions = {
strictTemplates: true,
};
const baseHost = new NgtscCompilerHost(getFileSystem(), options);
const host = NgCompilerHost.wrap(baseHost, [COMPONENT], options, /* oldProgram */ null);
const program = ts.createProgram({host, options, rootNames: host.inputFiles});
const compilerA = makeFreshCompiler(
host,
options,
program,
new TsCreateProgramDriver(program, host, options, []),
new NoopIncrementalBuildStrategy(),
/** enableTemplateTypeChecker */ false,
/* usePoisonedData */ false,
);
const componentSf = getSourceFileOrError(program, COMPONENT);
// There should be no diagnostics for the component.
expect(compilerA.getDiagnosticsForFile(componentSf, OptimizeFor.WholeProgram).length).toBe(
0,
);
// Change the resource file and introduce an error.
fs.writeFile(TEMPLATE, `<h1>Resource</h2>`);
// Perform a resource-only incremental step.
const resourceTicket = resourceChangeTicket(compilerA, new Set([TEMPLATE]));
const compilerB = NgCompiler.fromTicket(resourceTicket, host);
// A resource-only update should reuse the same compiler instance.
expect(compilerB).toBe(compilerA);
// The new template error should be reported in component diagnostics.
expect(compilerB.getDiagnosticsForFile(componentSf, OptimizeFor.WholeProgram).length).toBe(
1,
);
});
});
});
});
function getClass(sf: ts.SourceFile, name: string): ClassDeclaration<ts.ClassDeclaration> {
for (const stmt of sf.statements) {
if (isNamedClassDeclaration(stmt) && stmt.name.text === name) {
return stmt;
}
}
throw new Error(`Class ${name} not found in file: ${sf.fileName}: ${sf.text}`);
} | {
"end_byte": 15401,
"start_byte": 7704,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/test/compiler_test.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/index.ts_0_338 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use 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/adapter';
export * from './src/interfaces';
export * from './src/options';
export * from './src/public_options';
| {
"end_byte": 338,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/src/adapter.ts_0_4217 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {ExtendedTsCompilerHost, UnifiedModulesHost} from './interfaces';
/**
* Names of methods from `ExtendedTsCompilerHost` that need to be provided by the
* `NgCompilerAdapter`.
*/
export type ExtendedCompilerHostMethods =
// Used to normalize filenames for the host system. Important for proper case-sensitive file
// handling.
| 'getCanonicalFileName'
// An optional method of `ts.CompilerHost` where an implementer can override module resolution.
| 'resolveModuleNames'
// Retrieve the current working directory. Unlike in `ts.ModuleResolutionHost`, this is a
// required method.
| 'getCurrentDirectory'
// Additional methods of `ExtendedTsCompilerHost` related to resource files (e.g. HTML
// templates). These are optional.
| 'getModifiedResourceFiles'
| 'readResource'
| 'resourceNameToFileName'
| 'transformResource';
/**
* Adapter for `NgCompiler` that allows it to be used in various circumstances, such as
* command-line `ngc`, as a plugin to `ts_library` in Bazel, or from the Language Service.
*
* `NgCompilerAdapter` is a subset of the `NgCompilerHost` implementation of `ts.CompilerHost`
* which is relied upon by `NgCompiler`. A consumer of `NgCompiler` can therefore use the
* `NgCompilerHost` or implement `NgCompilerAdapter` itself.
*/
export interface NgCompilerAdapter
// getCurrentDirectory is removed from `ts.ModuleResolutionHost` because it's optional, and
// incompatible with the `ts.CompilerHost` version which isn't. The combination of these two
// still satisfies `ts.ModuleResolutionHost`.
extends Omit<ts.ModuleResolutionHost, 'getCurrentDirectory'>,
Pick<ExtendedTsCompilerHost, 'getCurrentDirectory' | ExtendedCompilerHostMethods>,
SourceFileTypeIdentifier {
/**
* A path to a single file which represents the entrypoint of an Angular Package Format library,
* if the current program is one.
*
* This is used to emit a flat module index if requested, and can be left `null` if that is not
* required.
*/
readonly entryPoint: AbsoluteFsPath | null;
/**
* An array of `ts.Diagnostic`s that occurred during construction of the `ts.Program`.
*/
readonly constructionDiagnostics: ts.Diagnostic[];
/**
* A `Set` of `ts.SourceFile`s which are internal to the program and should not be emitted as JS
* files.
*
* Often these are shim files such as `ngtypecheck` shims used for template type-checking in
* command-line ngc.
*/
readonly ignoreForEmit: Set<ts.SourceFile>;
/**
* A specialized interface provided in some environments (such as Bazel) which overrides how
* import specifiers are generated.
*
* If not required, this can be `null`.
*/
readonly unifiedModulesHost: UnifiedModulesHost | null;
/**
* Resolved list of root directories explicitly set in, or inferred from, the tsconfig.
*/
readonly rootDirs: ReadonlyArray<AbsoluteFsPath>;
}
export interface SourceFileTypeIdentifier {
/**
* Distinguishes between shim files added by Angular to the compilation process (both those
* intended for output, like ngfactory files, as well as internal shims like ngtypecheck files)
* and original files in the user's program.
*
* This is mostly used to limit type-checking operations to only user files. It should return
* `true` if a file was written by the user, and `false` if a file was added by the compiler.
*/
isShim(sf: ts.SourceFile): boolean;
/**
* Distinguishes between resource files added by Angular to the project and original files in the
* user's program.
*
* This is necessary only for the language service because it adds resource files as root files
* when they are read. This is done to indicate to TS Server that these resources are part of the
* project and ensures that projects are retained properly when navigating around the workspace.
*/
isResource(sf: ts.SourceFile): boolean;
}
| {
"end_byte": 4217,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/src/adapter.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/src/public_options.ts_0_4076 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ExtendedTemplateDiagnosticName} from '../../../../ngtsc/diagnostics';
/**
* Options supported by the legacy View Engine compiler, which are still consumed by the Angular Ivy
* compiler for backwards compatibility.
*
* These are expected to be removed at some point in the future.
*
* @publicApi
*/
export interface LegacyNgcOptions {
/**
* generate all possible generated files
* @deprecated This option is not used anymore.
*/
allowEmptyCodegenFiles?: boolean;
/**
* Whether to type check the entire template.
*
* This flag currently controls a couple aspects of template type-checking, including
* whether embedded views are checked.
*
* For maximum type-checking, set this to `true`, and set `strictTemplates` to `true`.
*
* It is an error for this flag to be `false`, while `strictTemplates` is set to `true`.
*
* @deprecated The `fullTemplateTypeCheck` option has been superseded by the more granular
* `strictTemplates` family of compiler options. Usage of `fullTemplateTypeCheck` is therefore
* deprecated, `strictTemplates` and its related options should be used instead.
*/
fullTemplateTypeCheck?: boolean;
/**
* Whether to generate a flat module index of the given name and the corresponding
* flat module metadata. This option is intended to be used when creating flat
* modules similar to how `@angular/core` and `@angular/common` are packaged.
* When this option is used the `package.json` for the library should refer to the
* generated flat module index instead of the library index file. When using this
* option only one .metadata.json file is produced that contains all the metadata
* necessary for symbols exported from the library index.
* In the generated .ngfactory.ts files flat module index is used to import symbols
* including both the public API from the library index as well as shrouded internal
* symbols.
* By default the .ts file supplied in the `files` field is assumed to be the
* library index. If more than one is specified, uses `libraryIndex` to select the
* file to use. If more than one .ts file is supplied and no `libraryIndex` is supplied
* an error is produced.
* A flat module index .d.ts and .js will be created with the given `flatModuleOutFile`
* name in the same location as the library index .d.ts file is emitted.
* For example, if a library uses `public_api.ts` file as the library index of the
* module the `tsconfig.json` `files` field would be `["public_api.ts"]`. The
* `flatModuleOutFile` options could then be set to, for example `"index.js"`, which
* produces `index.d.ts` and `index.metadata.json` files. The library's
* `package.json`'s `module` field would be `"index.js"` and the `typings` field would
* be `"index.d.ts"`.
*/
flatModuleOutFile?: string;
/**
* Preferred module id to use for importing flat module. References generated by `ngc`
* will use this module name when importing symbols from the flat module. This is only
* meaningful when `flatModuleOutFile` is also supplied. It is otherwise ignored.
*/
flatModuleId?: string;
/**
* Always report errors a parameter is supplied whose injection type cannot
* be determined. When this value option is not provided or is `false`, constructor
* parameters of classes marked with `@Injectable` whose type cannot be resolved will
* produce a warning. With this option `true`, they produce an error. When this option is
* not provided is treated as if it were `false`.
*/
strictInjectionParameters?: boolean;
/**
* Whether to remove blank text nodes from compiled templates. It is `false` by default starting
* from Angular 6.
*/
preserveWhitespaces?: boolean;
}
/**
* Options related to template type-checking and its strictness.
*
* @publicApi
*/ | {
"end_byte": 4076,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/src/public_options.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/src/public_options.ts_4077_11014 | export interface StrictTemplateOptions {
/**
* If `true`, implies all template strictness flags below (unless individually disabled).
*
* This flag is a superset of the deprecated `fullTemplateTypeCheck` option.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is `true`.
*/
strictTemplates?: boolean;
/**
* Whether to check the type of a binding to a directive/component input against the type of the
* field on the directive/component.
*
* For example, if this is `false` then the expression `[input]="expr"` will have `expr` type-
* checked, but not the assignment of the resulting type to the `input` property of whichever
* directive or component is receiving the binding. If set to `true`, both sides of the assignment
* are checked.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set.
*/
strictInputTypes?: boolean;
/**
* Whether to check if the input binding attempts to assign to a restricted field (readonly,
* private, or protected) on the directive/component.
*
* Defaults to `false`, even if "fullTemplateTypeCheck", "strictTemplates" and/or
* "strictInputTypes" is set. Note that if `strictInputTypes` is not set, or set to `false`, this
* flag has no effect.
*
* Tracking issue for enabling this by default: https://github.com/angular/angular/issues/38400
*/
strictInputAccessModifiers?: boolean;
/**
* Whether to use strict null types for input bindings for directives.
*
* If this is `true`, applications that are compiled with TypeScript's `strictNullChecks` enabled
* will produce type errors for bindings which can evaluate to `undefined` or `null` where the
* inputs's type does not include `undefined` or `null` in its type. If set to `false`, all
* binding expressions are wrapped in a non-null assertion operator to effectively disable strict
* null checks.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set. Note that if `strictInputTypes` is
* not set, or set to `false`, this flag has no effect.
*/
strictNullInputTypes?: boolean;
/**
* Whether to check text attributes that happen to be consumed by a directive or component.
*
* For example, in a template containing `<input matInput disabled>` the `disabled` attribute ends
* up being consumed as an input with type `boolean` by the `matInput` directive. At runtime, the
* input will be set to the attribute's string value, which is an empty string for attributes
* without a value, so with this flag set to `true`, an error would be reported. If set to
* `false`, text attributes will never report an error.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set. Note that if `strictInputTypes` is
* not set, or set to `false`, this flag has no effect.
*/
strictAttributeTypes?: boolean;
/**
* Whether to use a strict type for null-safe navigation operations.
*
* If this is `false`, then the return type of `a?.b` or `a?()` will be `any`. If set to `true`,
* then the return type of `a?.b` for example will be the same as the type of the ternary
* expression `a != null ? a.b : a`.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set.
*/
strictSafeNavigationTypes?: boolean;
/**
* Whether to infer the type of local references.
*
* If this is `true`, the type of a `#ref` variable on a DOM node in the template will be
* determined by the type of `document.createElement` for the given DOM node. If set to `false`,
* the type of `ref` for DOM nodes will be `any`.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set.
*/
strictDomLocalRefTypes?: boolean;
/**
* Whether to infer the type of the `$event` variable in event bindings for directive outputs or
* animation events.
*
* If this is `true`, the type of `$event` will be inferred based on the generic type of
* `EventEmitter`/`Subject` of the output. If set to `false`, the `$event` variable will be of
* type `any`.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set.
*/
strictOutputEventTypes?: boolean;
/**
* Whether to infer the type of the `$event` variable in event bindings to DOM events.
*
* If this is `true`, the type of `$event` will be inferred based on TypeScript's
* `HTMLElementEventMap`, with a fallback to the native `Event` type. If set to `false`, the
* `$event` variable will be of type `any`.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set.
*/
strictDomEventTypes?: boolean;
/**
* Whether to include the generic type of components when type-checking the template.
*
* If no component has generic type parameters, this setting has no effect.
*
* If a component has generic type parameters and this setting is `true`, those generic parameters
* will be included in the context type for the template. If `false`, any generic parameters will
* be set to `any` in the template context type.
*
* Defaults to `false`, even if "fullTemplateTypeCheck" is set.
*/
strictContextGenerics?: boolean;
/**
* Whether object or array literals defined in templates use their inferred type, or are
* interpreted as `any`.
*
* Defaults to `false` unless `fullTemplateTypeCheck` or `strictTemplates` are set.
*/
strictLiteralTypes?: boolean;
}
/**
* A label referring to a `ts.DiagnosticCategory` or `'suppress'`, meaning the associated diagnostic
* should not be displayed at all.
*
* @publicApi
*/
export enum DiagnosticCategoryLabel {
/** Treat the diagnostic as a warning, don't fail the compilation. */
Warning = 'warning',
/** Treat the diagnostic as a hard error, fail the compilation. */
Error = 'error',
/** Ignore the diagnostic altogether. */
Suppress = 'suppress',
}
/**
* Options which control how diagnostics are emitted from the compiler.
*
* @publicApi
*/
export interface DiagnosticOptions {
/** Options which control how diagnostics are emitted from the compiler. */
extendedDiagnostics?: {
/**
* The category to use for configurable diagnostics which are not overridden by `checks`. Uses
* `warning` by default.
*/
defaultCategory?: DiagnosticCategoryLabel;
/**
* A map of each extended template diagnostic's name to its category. This can be expanded in
* the future with more information for each check or for additional diagnostics not part of the
* extended template diagnostics system.
*/
checks?: {[Name in ExtendedTemplateDiagnosticName]?: DiagnosticCategoryLabel};
};
/**
* If enabled, non-standalone declarations are prohibited and result in build errors.
*/
strictStandalone?: boolean;
}
/**
* Options which control behavior useful for "monorepo" build cases using Bazel (such as the
* internal Google monorepo, g3).
*
* @publicApi
*/ | {
"end_byte": 11014,
"start_byte": 4077,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/src/public_options.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/src/public_options.ts_11015_17236 | export interface BazelAndG3Options {
/**
* Enables the generation of alias re-exports of directives/pipes that are visible from an
* NgModule from that NgModule's file.
*
* This option should be disabled for application builds or for Angular Package Format libraries
* (where NgModules along with their directives/pipes are exported via a single entrypoint).
*
* For other library compilations which are intended to be path-mapped into an application build
* (or another library), enabling this option enables the resulting deep imports to work
* correctly.
*
* A consumer of such a path-mapped library will write an import like:
*
* ```typescript
* import {LibModule} from 'lib/deep/path/to/module';
* ```
*
* The compiler will attempt to generate imports of directives/pipes from that same module
* specifier (the compiler does not rewrite the user's given import path, unlike View Engine).
*
* ```typescript
* import {LibDir, LibCmp, LibPipe} from 'lib/deep/path/to/module';
* ```
*
* It would be burdensome for users to have to re-export all directives/pipes alongside each
* NgModule to support this import model. Enabling this option tells the compiler to generate
* private re-exports alongside the NgModule of all the directives/pipes it makes available, to
* support these future imports.
*/
generateDeepReexports?: boolean;
/**
* The `.d.ts` file for NgModules contain type pointers to their declarations, imports, and
* exports. Without this flag, the generated type definition will include
* components/directives/pipes/NgModules that are declared or imported locally in the NgModule and
* not necessarily exported to consumers.
*
* With this flag set, the type definition generated in the `.d.ts` for an NgModule will be
* filtered to only list those types which are publicly exported by the NgModule.
*/
onlyPublishPublicTypingsForNgModules?: boolean;
/**
* Insert JSDoc type annotations needed by Closure Compiler
*/
annotateForClosureCompiler?: boolean;
/**
* Specifies whether Angular compiler should rely on explicit imports
* via `@Component.deferredImports` field for `@defer` blocks and generate
* dynamic imports only for types from that list.
*
* This flag is needed to enable stricter behavior internally to make sure
* that local compilation with specific internal configuration can support
* `@defer` blocks.
*/
onlyExplicitDeferDependencyImports?: boolean;
/**
* Generates extra imports in local compilation mode which imply the extra imports generated in
* full mode compilation (e.g., imports for statically resolved component dependencies). These
* extra imports are needed for bundling purposes in g3.
*/
generateExtraImportsInLocalMode?: boolean;
}
/**
* Options related to i18n compilation support.
*
* @publicApi
*/
export interface I18nOptions {
/**
* Locale of the imported translations
*/
i18nInLocale?: string;
/**
* Export format (xlf, xlf2 or xmb) when the xi18n operation is requested.
*/
i18nOutFormat?: string;
/**
* Path to the extracted message file to emit when the xi18n operation is requested.
*/
i18nOutFile?: string;
/**
* Locale of the application (used when xi18n is requested).
*/
i18nOutLocale?: string;
/**
* Render `$localize` messages with legacy format ids.
*
* The default value for now is `true`.
*
* Use this option when use are using the `$localize` based localization messages but
* have not migrated the translation files to use the new `$localize` message id format.
*/
enableI18nLegacyMessageIdFormat?: boolean;
/**
* Whether translation variable name should contain external message id
* (used by Closure Compiler's output of `goog.getMsg` for transition period)
*/
i18nUseExternalIds?: boolean;
/**
* If templates are stored in external files (e.g. via `templateUrl`) then we need to decide
* whether or not to normalize the line-endings (from `\r\n` to `\n`) when processing ICU
* expressions.
*
* Ideally we would always normalize, but for backward compatibility this flag allows the template
* parser to avoid normalizing line endings in ICU expressions.
*
* If `true` then we will normalize ICU expression line endings.
* The default is `false`, but this will be switched in a future major release.
*/
i18nNormalizeLineEndingsInICUs?: boolean;
/**
* Whether or not to preserve whitespace when extracting messages with the legacy (View Engine)
* pipeline.
*
* Defaults to `true`.
*/
i18nPreserveWhitespaceForLegacyExtraction?: boolean;
}
/**
* Options that specify compilation target.
*
* @publicApi
*/
export interface TargetOptions {
/**
* Specifies the compilation mode to use. The following modes are available:
* - 'full': generates fully AOT compiled code using Ivy instructions.
* - 'partial': generates code in a stable, but intermediate form suitable for publication to NPM.
* - 'experimental-local': generates code based on each individual source file without using its
* dependencies. This mode is suitable only for fast edit/refresh during development. It will be
* eventually replaced by the value `local` once the feature is ready to be public.
*
* The default value is 'full'.
*/
compilationMode?: 'full' | 'partial' | 'experimental-local';
}
/**
* Miscellaneous options that don't fall into any other category
*
* @publicApi
*/
export interface MiscOptions {
/**
* Whether the compiler should avoid generating code for classes that haven't been exported.
* Defaults to `true`.
*/
compileNonExportedClasses?: boolean;
/**
* Disable TypeScript Version Check.
*/
disableTypeScriptVersionCheck?: boolean;
/**
* Enables the runtime check to guard against rendering a component without first loading its
* NgModule.
*
* This check is only applied to the current compilation unit, i.e., a component imported from
* another library without option set will not issue error if rendered in orphan way.
*/
forbidOrphanComponents?: boolean;
} | {
"end_byte": 17236,
"start_byte": 11015,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/src/public_options.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts_0_4698 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
/**
* A host backed by a build system which has a unified view of the module namespace.
*
* Such a build system supports the `fileNameToModuleName` method provided by certain build system
* integrations (such as the integration with Bazel). See the docs on `fileNameToModuleName` for
* more details.
*/
export interface UnifiedModulesHost {
/**
* Converts a file path to a module name that can be used as an `import ...`.
*
* For example, such a host might determine that `/absolute/path/to/monorepo/lib/importedFile.ts`
* should be imported using a module specifier of `monorepo/lib/importedFile`.
*/
fileNameToModuleName(importedFilePath: string, containingFilePath: string): string;
}
/**
* A host which additionally tracks and produces "resources" (HTML templates, CSS
* files, etc).
*/
export interface ResourceHost {
/**
* Converts a file path for a resource that is used in a source file or another resource
* into a filepath.
*
* The optional `fallbackResolve` method can be used as a way to attempt a fallback resolution if
* the implementation's `resourceNameToFileName` resolution fails.
*/
resourceNameToFileName(
resourceName: string,
containingFilePath: string,
fallbackResolve?: (url: string, fromFile: string) => string | null,
): string | null;
/**
* Load a referenced resource either statically or asynchronously. If the host returns a
* `Promise<string>` it is assumed the user of the corresponding `Program` will call
* `loadNgStructureAsync()`. Returning `Promise<string>` outside `loadNgStructureAsync()` will
* cause a diagnostics error or an exception to be thrown.
*/
readResource(fileName: string): Promise<string> | string;
/**
* Get the absolute paths to the changed files that triggered the current compilation
* or `undefined` if this is not an incremental build.
*/
getModifiedResourceFiles?(): Set<string> | undefined;
/**
* Transform an inline or external resource asynchronously.
* It is assumed the consumer of the corresponding `Program` will call
* `loadNgStructureAsync()`. Using outside `loadNgStructureAsync()` will
* cause a diagnostics error or an exception to be thrown.
* Only style resources are currently supported.
*
* @param data The resource data to transform.
* @param context Information regarding the resource such as the type and containing file.
* @returns A promise of either the transformed resource data or null if no transformation occurs.
*/
transformResource?(
data: string,
context: ResourceHostContext,
): Promise<TransformResourceResult | null>;
}
/**
* Contextual information used by members of the ResourceHost interface.
*/
export interface ResourceHostContext {
/**
* The type of the component resource. Templates are not yet supported.
* * Resources referenced via a component's `styles` or `styleUrls` properties are of
* type `style`.
*/
readonly type: 'style';
/**
* The absolute path to the resource file. If the resource is inline, the value will be null.
*/
readonly resourceFile: string | null;
/**
* The absolute path to the file that contains the resource or reference to the resource.
*/
readonly containingFile: string;
/**
* For style resources, the placement of the style within the containing file with lower numbers
* being before higher numbers.
* The value is primarily used by the Angular CLI to create a deterministic identifier for each
* style in HMR scenarios.
* This is undefined for templates.
*/
readonly order?: number;
/**
* The name of the class that defines the component using the resource.
* This allows identifying the source usage of a resource in cases where multiple components are
* contained in a single source file.
*/
className: string;
}
/**
* The successful transformation result of the `ResourceHost.transformResource` function.
* This interface may be expanded in the future to include diagnostic information and source mapping
* support.
*/
export interface TransformResourceResult {
/**
* The content generated by the transformation.
*/
content: string;
}
/**
* A `ts.CompilerHost` interface which supports some number of optional methods in addition to the
* core interface.
*/
export interface ExtendedTsCompilerHost
extends ts.CompilerHost,
Partial<ResourceHost>,
Partial<UnifiedModulesHost> {}
| {
"end_byte": 4698,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/api/src/options.ts_0_4188 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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 {
BazelAndG3Options,
DiagnosticOptions,
I18nOptions,
LegacyNgcOptions,
MiscOptions,
StrictTemplateOptions,
TargetOptions,
} from './public_options';
/**
* Non-public options which are useful during testing of the compiler.
*/
export interface TestOnlyOptions {
/**
* Whether to use the CompilerHost's fileNameToModuleName utility (if available) to generate
* import module specifiers. This is false by default, and exists to support running ngtsc
* within Google. This option is internal and is used by the ng_module.bzl rule to switch
* behavior between Bazel and Blaze.
*
* @internal
*/
_useHostForImportGeneration?: boolean;
/**
* Enable the Language Service APIs for template type-checking for tests.
*/
_enableTemplateTypeChecker?: boolean;
/**
* Whether components that are poisoned should still be processed.
* E.g. for generation of type check blocks and diagnostics.
*/
_compilePoisonedComponents?: boolean;
/**
* An option to enable ngtsc's internal performance tracing.
*
* This should be a path to a JSON file where trace information will be written. This is sensitive
* to the compiler's working directory, and should likely be an absolute path.
*
* This is currently not exposed to users as the trace format is still unstable.
*/
tracePerformance?: string;
}
/**
* Internal only options for compiler.
*/
export interface InternalOptions {
/**
* Enables the full usage of TestBed APIs within Angular unit tests by emitting class metadata
* for each Angular related class.
*
* This is only intended to be used by the Angular CLI.
* Defaults to true if not specified.
*
* @internal
*/
supportTestBed?: boolean;
/**
* Enables the usage of the JIT compiler in combination with AOT compiled code by emitting
* selector scope information for NgModules.
*
* This is only intended to be used by the Angular CLI.
* Defaults to true if not specified.
*
* @internal
*/
supportJitMode?: boolean;
/**
* Whether block syntax is enabled in the compiler. Defaults to true.
* Used in the language service to disable the new syntax for projects that aren't on v17.
*
* @internal
*/
_enableBlockSyntax?: boolean;
/**
* Whether `@let` syntax is enabled in the compiler.
* Defaults to false while the feature is being developed.
*
* @internal
*/
_enableLetSyntax?: boolean;
/**
* Enables the use of `<link>` elements for component styleUrls instead of inlining the file
* content.
* This option is intended to be used with a development server that processes and serves
* the files on-demand for an application.
*
* @internal
*/
externalRuntimeStyles?: boolean;
/**
* Detected version of `@angular/core` in the workspace. Used by the
* compiler to adjust the output depending on the available symbols.
*
* @internal
*/
_angularCoreVersion?: string;
/**
* Whether to enable the necessary code generation for hot module reloading.
*
* @internal
*/
_enableHmr?: boolean;
}
/**
* A merged interface of all of the various Angular compiler options, as well as the standard
* `ts.CompilerOptions`.
*
* Also includes a few miscellaneous options.
*/
export interface NgCompilerOptions
extends ts.CompilerOptions,
LegacyNgcOptions,
BazelAndG3Options,
DiagnosticOptions,
StrictTemplateOptions,
TestOnlyOptions,
I18nOptions,
TargetOptions,
InternalOptions,
MiscOptions {
// Replace the index signature type from `ts.CompilerOptions` as it is more strict than it needs
// to be and would conflict with some types from the other interfaces. This is ok because Angular
// compiler options are actually separate from TS compiler options in the `tsconfig.json` and we
// have full control over the structure of Angular's compiler options.
[prop: string]: any;
}
| {
"end_byte": 4188,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/api/src/options.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/feature_detection.ts_0_1040 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Note: semver isn't available internally so this import will be commented out.
// When adding more dependencies here, the caretaker may have to update a patch internally.
import semver from 'semver';
/**
* Whether a version of `@angular/core` supports a specific feature.
* @param coreVersion Current version of core.
* @param minVersion Minimum required version for the feature.
*/
export function coreVersionSupportsFeature(coreVersion: string, minVersion: string): boolean {
// A version of `0.0.0-PLACEHOLDER` usually means that core is at head so it supports
// all features. Use string interpolation prevent the placeholder from being replaced
// with the current version during build time.
if (coreVersion === `0.0.0-${'PLACEHOLDER'}`) {
return true;
}
return semver.satisfies(coreVersion, minVersion);
}
| {
"end_byte": 1040,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/feature_detection.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/core_version.ts_0_1067 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ExternalReference} from '@angular/compiler';
import ts from 'typescript';
export function coreHasSymbol(program: ts.Program, symbol: ExternalReference): boolean | null {
const checker = program.getTypeChecker();
for (const sf of program.getSourceFiles().filter(isMaybeCore)) {
const sym = checker.getSymbolAtLocation(sf);
if (sym === undefined || sym.exports === undefined) {
continue;
}
if (!sym.exports.has('ɵɵtemplate' as ts.__String)) {
// This is not @angular/core.
continue;
}
return sym.exports.has(symbol.name as ts.__String);
}
// No @angular/core file found, so we have no information.
return null;
}
export function isMaybeCore(sf: ts.SourceFile): boolean {
return (
sf.isDeclarationFile &&
sf.fileName.includes('@angular/core') &&
sf.fileName.endsWith('index.d.ts')
);
}
| {
"end_byte": 1067,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/core_version.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/host.ts_0_5850 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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, ngErrorCode} from '../../diagnostics';
import {findFlatIndexEntryPoint, FlatIndexGenerator} from '../../entry_point';
import {AbsoluteFsPath, resolve} from '../../file_system';
import {isShim, ShimAdapter, ShimReferenceTagger} from '../../shims';
import {PerFileShimGenerator, TopLevelShimGenerator} from '../../shims/api';
import {TypeCheckShimGenerator} from '../../typecheck';
import {normalizeSeparators} from '../../util/src/path';
import {getRootDirs, isNonDeclarationTsPath, RequiredDelegations} from '../../util/src/typescript';
import {
ExtendedTsCompilerHost,
NgCompilerAdapter,
NgCompilerOptions,
UnifiedModulesHost,
} from '../api';
// A persistent source of bugs in CompilerHost delegation has been the addition by TS of new,
// optional methods on ts.CompilerHost. Since these methods are optional, it's not a type error that
// the delegating host doesn't implement or delegate them. This causes subtle runtime failures. No
// more. This infrastructure ensures that failing to delegate a method is a compile-time error.
/**
* Delegates all methods of `ExtendedTsCompilerHost` to a delegate, with the exception of
* `getSourceFile` and `fileExists` which are implemented in `NgCompilerHost`.
*
* If a new method is added to `ts.CompilerHost` which is not delegated, a type error will be
* generated for this class.
*/
export class DelegatingCompilerHost
implements Omit<RequiredDelegations<ExtendedTsCompilerHost>, 'getSourceFile' | 'fileExists'>
{
createHash;
directoryExists;
fileNameToModuleName;
getCancellationToken;
getCanonicalFileName;
getCurrentDirectory;
getDefaultLibFileName;
getDefaultLibLocation;
getDirectories;
getEnvironmentVariable;
getModifiedResourceFiles;
getNewLine;
getParsedCommandLine;
getSourceFileByPath;
readDirectory;
readFile;
readResource;
transformResource;
realpath;
resolveModuleNames;
resolveTypeReferenceDirectives;
resourceNameToFileName;
trace;
useCaseSensitiveFileNames;
writeFile;
getModuleResolutionCache;
hasInvalidatedResolutions;
resolveModuleNameLiterals;
resolveTypeReferenceDirectiveReferences;
// jsDocParsingMode is not a method like the other elements above
// TODO: ignore usage can be dropped once 5.2 support is dropped
get jsDocParsingMode() {
// @ts-ignore
return this.delegate.jsDocParsingMode;
}
set jsDocParsingMode(mode) {
// @ts-ignore
this.delegate.jsDocParsingMode = mode;
}
constructor(protected delegate: ExtendedTsCompilerHost) {
// Excluded are 'getSourceFile' and 'fileExists', which are actually implemented by
// NgCompilerHost
// below.
this.createHash = this.delegateMethod('createHash');
this.directoryExists = this.delegateMethod('directoryExists');
this.fileNameToModuleName = this.delegateMethod('fileNameToModuleName');
this.getCancellationToken = this.delegateMethod('getCancellationToken');
this.getCanonicalFileName = this.delegateMethod('getCanonicalFileName');
this.getCurrentDirectory = this.delegateMethod('getCurrentDirectory');
this.getDefaultLibFileName = this.delegateMethod('getDefaultLibFileName');
this.getDefaultLibLocation = this.delegateMethod('getDefaultLibLocation');
this.getDirectories = this.delegateMethod('getDirectories');
this.getEnvironmentVariable = this.delegateMethod('getEnvironmentVariable');
this.getModifiedResourceFiles = this.delegateMethod('getModifiedResourceFiles');
this.getNewLine = this.delegateMethod('getNewLine');
this.getParsedCommandLine = this.delegateMethod('getParsedCommandLine');
this.getSourceFileByPath = this.delegateMethod('getSourceFileByPath');
this.readDirectory = this.delegateMethod('readDirectory');
this.readFile = this.delegateMethod('readFile');
this.readResource = this.delegateMethod('readResource');
this.transformResource = this.delegateMethod('transformResource');
this.realpath = this.delegateMethod('realpath');
this.resolveModuleNames = this.delegateMethod('resolveModuleNames');
this.resolveTypeReferenceDirectives = this.delegateMethod('resolveTypeReferenceDirectives');
this.resourceNameToFileName = this.delegateMethod('resourceNameToFileName');
this.trace = this.delegateMethod('trace');
this.useCaseSensitiveFileNames = this.delegateMethod('useCaseSensitiveFileNames');
this.writeFile = this.delegateMethod('writeFile');
this.getModuleResolutionCache = this.delegateMethod('getModuleResolutionCache');
this.hasInvalidatedResolutions = this.delegateMethod('hasInvalidatedResolutions');
this.resolveModuleNameLiterals = this.delegateMethod('resolveModuleNameLiterals');
this.resolveTypeReferenceDirectiveReferences = this.delegateMethod(
'resolveTypeReferenceDirectiveReferences',
);
}
private delegateMethod<M extends keyof ExtendedTsCompilerHost>(
name: M,
): ExtendedTsCompilerHost[M] {
return this.delegate[name] !== undefined
? (this.delegate[name] as any).bind(this.delegate)
: undefined;
}
}
/**
* A wrapper around `ts.CompilerHost` (plus any extension methods from `ExtendedTsCompilerHost`).
*
* In order for a consumer to include Angular compilation in their TypeScript compiler, the
* `ts.Program` must be created with a host that adds Angular-specific files (e.g.
* the template type-checking file, etc) to the compilation. `NgCompilerHost` is the
* host implementation which supports this.
*
* The interface implementations here ensure that `NgCompilerHost` fully delegates to
* `ExtendedTsCompilerHost` methods whenever present.
*/ | {
"end_byte": 5850,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/host.ts_5851_13307 | export class NgCompilerHost
extends DelegatingCompilerHost
implements RequiredDelegations<ExtendedTsCompilerHost>, ExtendedTsCompilerHost, NgCompilerAdapter
{
readonly entryPoint: AbsoluteFsPath | null = null;
readonly constructionDiagnostics: ts.Diagnostic[];
readonly inputFiles: ReadonlyArray<string>;
readonly rootDirs: ReadonlyArray<AbsoluteFsPath>;
constructor(
delegate: ExtendedTsCompilerHost,
inputFiles: ReadonlyArray<string>,
rootDirs: ReadonlyArray<AbsoluteFsPath>,
private shimAdapter: ShimAdapter,
private shimTagger: ShimReferenceTagger,
entryPoint: AbsoluteFsPath | null,
diagnostics: ts.Diagnostic[],
) {
super(delegate);
this.entryPoint = entryPoint;
this.constructionDiagnostics = diagnostics;
this.inputFiles = [...inputFiles, ...shimAdapter.extraInputFiles];
this.rootDirs = rootDirs;
if (this.resolveModuleNames === undefined) {
// In order to reuse the module resolution cache during the creation of the type-check
// program, we'll need to provide `resolveModuleNames` if the delegate did not provide one.
this.resolveModuleNames = this.createCachedResolveModuleNamesFunction();
}
}
/**
* Retrieves a set of `ts.SourceFile`s which should not be emitted as JS files.
*
* Available after this host is used to create a `ts.Program` (which causes all the files in the
* program to be enumerated).
*/
get ignoreForEmit(): Set<ts.SourceFile> {
return this.shimAdapter.ignoreForEmit;
}
/**
* Retrieve the array of shim extension prefixes for which shims were created for each original
* file.
*/
get shimExtensionPrefixes(): string[] {
return this.shimAdapter.extensionPrefixes;
}
/**
* Performs cleanup that needs to happen after a `ts.Program` has been created using this host.
*/
postProgramCreationCleanup(): void {
this.shimTagger.finalize();
}
/**
* Create an `NgCompilerHost` from a delegate host, an array of input filenames, and the full set
* of TypeScript and Angular compiler options.
*/
static wrap(
delegate: ts.CompilerHost,
inputFiles: ReadonlyArray<string>,
options: NgCompilerOptions,
oldProgram: ts.Program | null,
): NgCompilerHost {
const topLevelShimGenerators: TopLevelShimGenerator[] = [];
const perFileShimGenerators: PerFileShimGenerator[] = [];
const rootDirs = getRootDirs(delegate, options as ts.CompilerOptions);
perFileShimGenerators.push(new TypeCheckShimGenerator());
let diagnostics: ts.Diagnostic[] = [];
const normalizedTsInputFiles: AbsoluteFsPath[] = [];
for (const inputFile of inputFiles) {
if (!isNonDeclarationTsPath(inputFile)) {
continue;
}
normalizedTsInputFiles.push(resolve(inputFile));
}
let entryPoint: AbsoluteFsPath | null = null;
if (options.flatModuleOutFile != null && options.flatModuleOutFile !== '') {
entryPoint = findFlatIndexEntryPoint(normalizedTsInputFiles);
if (entryPoint === null) {
// This error message talks specifically about having a single .ts file in "files". However
// the actual logic is a bit more permissive. If a single file exists, that will be taken,
// otherwise the highest level (shortest path) "index.ts" file will be used as the flat
// module entry point instead. If neither of these conditions apply, the error below is
// given.
//
// The user is not informed about the "index.ts" option as this behavior is deprecated -
// an explicit entrypoint should always be specified.
diagnostics.push({
category: ts.DiagnosticCategory.Error,
code: ngErrorCode(ErrorCode.CONFIG_FLAT_MODULE_NO_INDEX),
file: undefined,
start: undefined,
length: undefined,
messageText:
'Angular compiler option "flatModuleOutFile" requires one and only one .ts file in the "files" field.',
});
} else {
const flatModuleId = options.flatModuleId || null;
const flatModuleOutFile = normalizeSeparators(options.flatModuleOutFile);
const flatIndexGenerator = new FlatIndexGenerator(
entryPoint,
flatModuleOutFile,
flatModuleId,
);
topLevelShimGenerators.push(flatIndexGenerator);
}
}
const shimAdapter = new ShimAdapter(
delegate,
normalizedTsInputFiles,
topLevelShimGenerators,
perFileShimGenerators,
oldProgram,
);
const shimTagger = new ShimReferenceTagger(
perFileShimGenerators.map((gen) => gen.extensionPrefix),
);
return new NgCompilerHost(
delegate,
inputFiles,
rootDirs,
shimAdapter,
shimTagger,
entryPoint,
diagnostics,
);
}
/**
* Check whether the given `ts.SourceFile` is a shim file.
*
* If this returns false, the file is user-provided.
*/
isShim(sf: ts.SourceFile): boolean {
return isShim(sf);
}
/**
* Check whether the given `ts.SourceFile` is a resource file.
*
* This simply returns `false` for the compiler-cli since resource files are not added as root
* files to the project.
*/
isResource(sf: ts.SourceFile): boolean {
return false;
}
getSourceFile(
fileName: string,
languageVersionOrOptions: ts.ScriptTarget | ts.CreateSourceFileOptions,
onError?: ((message: string) => void) | undefined,
shouldCreateNewSourceFile?: boolean | undefined,
): ts.SourceFile | undefined {
// Is this a previously known shim?
const shimSf = this.shimAdapter.maybeGenerate(resolve(fileName));
if (shimSf !== null) {
// Yes, so return it.
return shimSf;
}
// No, so it's a file which might need shims (or a file which doesn't exist).
const sf = this.delegate.getSourceFile(
fileName,
languageVersionOrOptions,
onError,
shouldCreateNewSourceFile,
);
if (sf === undefined) {
return undefined;
}
this.shimTagger.tag(sf);
return sf;
}
fileExists(fileName: string): boolean {
// Consider the file as existing whenever
// 1) it really does exist in the delegate host, or
// 2) at least one of the shim generators recognizes it
// Note that we can pass the file name as branded absolute fs path because TypeScript
// internally only passes POSIX-like paths.
//
// Also note that the `maybeGenerate` check below checks for both `null` and `undefined`.
return (
this.delegate.fileExists(fileName) ||
this.shimAdapter.maybeGenerate(resolve(fileName)) != null
);
}
get unifiedModulesHost(): UnifiedModulesHost | null {
return this.fileNameToModuleName !== undefined ? (this as UnifiedModulesHost) : null;
}
private createCachedResolveModuleNamesFunction(): ts.CompilerHost['resolveModuleNames'] {
const moduleResolutionCache = ts.createModuleResolutionCache(
this.getCurrentDirectory(),
this.getCanonicalFileName.bind(this),
);
return (moduleNames, containingFile, reusedNames, redirectedReference, options) => {
return moduleNames.map((moduleName) => {
const module = ts.resolveModuleName(
moduleName,
containingFile,
options,
this,
moduleResolutionCache,
redirectedReference,
);
return module.resolvedModule;
});
};
}
} | {
"end_byte": 13307,
"start_byte": 5851,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_0_7800 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {R3Identifiers} from '@angular/compiler';
import ts from 'typescript';
import {
ComponentDecoratorHandler,
DirectiveDecoratorHandler,
InjectableDecoratorHandler,
NgModuleDecoratorHandler,
NoopReferencesRegistry,
PipeDecoratorHandler,
ReferencesRegistry,
} from '../../annotations';
import {InjectableClassRegistry, JitDeclarationRegistry} from '../../annotations/common';
import {CycleAnalyzer, CycleHandlingStrategy, ImportGraph} from '../../cycles';
import {
COMPILER_ERRORS_WITH_GUIDES,
ERROR_DETAILS_PAGE_BASE_URL,
ErrorCode,
isFatalDiagnosticError,
ngErrorCode,
} from '../../diagnostics';
import {DocEntry, DocsExtractor} from '../../docs';
import {checkForPrivateExports, ReferenceGraph} from '../../entry_point';
import {
absoluteFromSourceFile,
AbsoluteFsPath,
LogicalFileSystem,
resolve,
} from '../../file_system';
import {
AbsoluteModuleStrategy,
AliasingHost,
AliasStrategy,
DefaultImportTracker,
DeferredSymbolTracker,
ImportedSymbolsTracker,
ImportRewriter,
LocalCompilationExtraImportsTracker,
LocalIdentifierStrategy,
LogicalProjectStrategy,
ModuleResolver,
NoopImportRewriter,
PrivateExportAliasingHost,
R3SymbolsImportRewriter,
Reference,
ReferenceEmitStrategy,
ReferenceEmitter,
RelativePathStrategy,
UnifiedModulesAliasingHost,
UnifiedModulesStrategy,
} from '../../imports';
import {
IncrementalBuildStrategy,
IncrementalCompilation,
IncrementalState,
} from '../../incremental';
import {SemanticSymbol} from '../../incremental/semantic_graph';
import {generateAnalysis, IndexedComponent, IndexingContext} from '../../indexer';
import {
ComponentResources,
CompoundMetadataReader,
CompoundMetadataRegistry,
DirectiveMeta,
DtsMetadataReader,
ExportedProviderStatusResolver,
HostDirectivesResolver,
LocalMetadataRegistry,
MetadataReader,
MetadataReaderWithIndex,
PipeMeta,
ResourceRegistry,
} from '../../metadata';
import {NgModuleIndexImpl} from '../../metadata/src/ng_module_index';
import {PartialEvaluator} from '../../partial_evaluator';
import {
ActivePerfRecorder,
DelegatingPerfRecorder,
PerfCheckpoint,
PerfEvent,
PerfPhase,
} from '../../perf';
import {FileUpdate, ProgramDriver, UpdateMode} from '../../program_driver';
import {DeclarationNode, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {AdapterResourceLoader} from '../../resource';
import {
ComponentScopeReader,
CompoundComponentScopeReader,
LocalModuleScopeRegistry,
MetadataDtsModuleScopeResolver,
TypeCheckScopeRegistry,
} from '../../scope';
import {StandaloneComponentScopeReader} from '../../scope/src/standalone';
import {
aliasTransformFactory,
CompilationMode,
declarationTransformFactory,
DecoratorHandler,
DtsTransformRegistry,
ivyTransformFactory,
TraitCompiler,
} from '../../transform';
import {TemplateTypeCheckerImpl} from '../../typecheck';
import {OptimizeFor, TemplateTypeChecker, TypeCheckingConfig} from '../../typecheck/api';
import {
ALL_DIAGNOSTIC_FACTORIES,
ExtendedTemplateCheckerImpl,
SUPPORTED_DIAGNOSTIC_NAMES,
} from '../../typecheck/extended';
import {ExtendedTemplateChecker} from '../../typecheck/extended/api';
import {TemplateSemanticsChecker} from '../../typecheck/template_semantics/api/api';
import {TemplateSemanticsCheckerImpl} from '../../typecheck/template_semantics/src/template_semantics_checker';
import {getSourceFileOrNull, isDtsPath, toUnredirectedSourceFile} from '../../util/src/typescript';
import {SourceFileValidator} from '../../validation';
import {Xi18nContext} from '../../xi18n';
import {DiagnosticCategoryLabel, NgCompilerAdapter, NgCompilerOptions} from '../api';
import {coreHasSymbol} from './core_version';
import {coreVersionSupportsFeature} from './feature_detection';
import {angularJitApplicationTransform} from '../../transform/jit';
import {untagAllTsFiles} from '../../shims';
/**
* State information about a compilation which is only generated once some data is requested from
* the `NgCompiler` (for example, by calling `getDiagnostics`).
*/
interface LazyCompilationState {
isCore: boolean;
traitCompiler: TraitCompiler;
reflector: TypeScriptReflectionHost;
metaReader: MetadataReader;
scopeRegistry: LocalModuleScopeRegistry;
typeCheckScopeRegistry: TypeCheckScopeRegistry;
exportReferenceGraph: ReferenceGraph | null;
dtsTransforms: DtsTransformRegistry;
aliasingHost: AliasingHost | null;
refEmitter: ReferenceEmitter;
templateTypeChecker: TemplateTypeChecker;
resourceRegistry: ResourceRegistry;
extendedTemplateChecker: ExtendedTemplateChecker | null;
templateSemanticsChecker: TemplateSemanticsChecker | null;
sourceFileValidator: SourceFileValidator | null;
jitDeclarationRegistry: JitDeclarationRegistry;
supportJitMode: boolean;
/**
* Only available in local compilation mode when option `generateExtraImportsInLocalMode` is set.
*/
localCompilationExtraImportsTracker: LocalCompilationExtraImportsTracker | null;
}
/**
* Discriminant type for a `CompilationTicket`.
*/
export enum CompilationTicketKind {
Fresh,
IncrementalTypeScript,
IncrementalResource,
}
/**
* Begin an Angular compilation operation from scratch.
*/
export interface FreshCompilationTicket {
kind: CompilationTicketKind.Fresh;
options: NgCompilerOptions;
incrementalBuildStrategy: IncrementalBuildStrategy;
programDriver: ProgramDriver;
enableTemplateTypeChecker: boolean;
usePoisonedData: boolean;
tsProgram: ts.Program;
perfRecorder: ActivePerfRecorder;
}
/**
* Begin an Angular compilation operation that incorporates changes to TypeScript code.
*/
export interface IncrementalTypeScriptCompilationTicket {
kind: CompilationTicketKind.IncrementalTypeScript;
options: NgCompilerOptions;
newProgram: ts.Program;
incrementalBuildStrategy: IncrementalBuildStrategy;
incrementalCompilation: IncrementalCompilation;
programDriver: ProgramDriver;
enableTemplateTypeChecker: boolean;
usePoisonedData: boolean;
perfRecorder: ActivePerfRecorder;
}
export interface IncrementalResourceCompilationTicket {
kind: CompilationTicketKind.IncrementalResource;
compiler: NgCompiler;
modifiedResourceFiles: Set<string>;
perfRecorder: ActivePerfRecorder;
}
/**
* A request to begin Angular compilation, either starting from scratch or from a known prior state.
*
* `CompilationTicket`s are used to initialize (or update) an `NgCompiler` instance, the core of the
* Angular compiler. They abstract the starting state of compilation and allow `NgCompiler` to be
* managed independently of any incremental compilation lifecycle.
*/
export type CompilationTicket =
| FreshCompilationTicket
| IncrementalTypeScriptCompilationTicket
| IncrementalResourceCompilationTicket;
/**
* Create a `CompilationTicket` for a brand new compilation, using no prior state.
*/
export function freshCompilationTicket(
tsProgram: ts.Program,
options: NgCompilerOptions,
incrementalBuildStrategy: IncrementalBuildStrategy,
programDriver: ProgramDriver,
perfRecorder: ActivePerfRecorder | null,
enableTemplateTypeChecker: boolean,
usePoisonedData: boolean,
): CompilationTicket {
return {
kind: CompilationTicketKind.Fresh,
tsProgram,
options,
incrementalBuildStrategy,
programDriver,
enableTemplateTypeChecker,
usePoisonedData,
perfRecorder: perfRecorder ?? ActivePerfRecorder.zeroedToNow(),
};
}
/**
* Create a `CompilationTicket` as efficiently as possible, based on a previous `NgCompiler`
* instance and a new `ts.Program`.
*/ | {
"end_byte": 7800,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_7801_11155 | export function incrementalFromCompilerTicket(
oldCompiler: NgCompiler,
newProgram: ts.Program,
incrementalBuildStrategy: IncrementalBuildStrategy,
programDriver: ProgramDriver,
modifiedResourceFiles: Set<AbsoluteFsPath>,
perfRecorder: ActivePerfRecorder | null,
): CompilationTicket {
const oldProgram = oldCompiler.getCurrentProgram();
const oldState = oldCompiler.incrementalStrategy.getIncrementalState(oldProgram);
if (oldState === null) {
// No incremental step is possible here, since no IncrementalState was found for the old
// program.
return freshCompilationTicket(
newProgram,
oldCompiler.options,
incrementalBuildStrategy,
programDriver,
perfRecorder,
oldCompiler.enableTemplateTypeChecker,
oldCompiler.usePoisonedData,
);
}
if (perfRecorder === null) {
perfRecorder = ActivePerfRecorder.zeroedToNow();
}
const incrementalCompilation = IncrementalCompilation.incremental(
newProgram,
versionMapFromProgram(newProgram, programDriver),
oldProgram,
oldState,
modifiedResourceFiles,
perfRecorder,
);
return {
kind: CompilationTicketKind.IncrementalTypeScript,
enableTemplateTypeChecker: oldCompiler.enableTemplateTypeChecker,
usePoisonedData: oldCompiler.usePoisonedData,
options: oldCompiler.options,
incrementalBuildStrategy,
incrementalCompilation,
programDriver,
newProgram,
perfRecorder,
};
}
/**
* Create a `CompilationTicket` directly from an old `ts.Program` and associated Angular compilation
* state, along with a new `ts.Program`.
*/
export function incrementalFromStateTicket(
oldProgram: ts.Program,
oldState: IncrementalState,
newProgram: ts.Program,
options: NgCompilerOptions,
incrementalBuildStrategy: IncrementalBuildStrategy,
programDriver: ProgramDriver,
modifiedResourceFiles: Set<AbsoluteFsPath>,
perfRecorder: ActivePerfRecorder | null,
enableTemplateTypeChecker: boolean,
usePoisonedData: boolean,
): CompilationTicket {
if (perfRecorder === null) {
perfRecorder = ActivePerfRecorder.zeroedToNow();
}
const incrementalCompilation = IncrementalCompilation.incremental(
newProgram,
versionMapFromProgram(newProgram, programDriver),
oldProgram,
oldState,
modifiedResourceFiles,
perfRecorder,
);
return {
kind: CompilationTicketKind.IncrementalTypeScript,
newProgram,
options,
incrementalBuildStrategy,
incrementalCompilation,
programDriver,
enableTemplateTypeChecker,
usePoisonedData,
perfRecorder,
};
}
export function resourceChangeTicket(
compiler: NgCompiler,
modifiedResourceFiles: Set<string>,
): IncrementalResourceCompilationTicket {
return {
kind: CompilationTicketKind.IncrementalResource,
compiler,
modifiedResourceFiles,
perfRecorder: ActivePerfRecorder.zeroedToNow(),
};
}
/**
* The heart of the Angular Ivy compiler.
*
* The `NgCompiler` provides an API for performing Angular compilation within a custom TypeScript
* compiler. Each instance of `NgCompiler` supports a single compilation, which might be
* incremental.
*
* `NgCompiler` is lazy, and does not perform any of the work of the compilation until one of its
* output methods (e.g. `getDiagnostics`) is called.
*
* See the README.md for more information.
*/ | {
"end_byte": 11155,
"start_byte": 7801,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_11156_20150 | export class NgCompiler {
/**
* Lazily evaluated state of the compilation.
*
* This is created on demand by calling `ensureAnalyzed`.
*/
private compilation: LazyCompilationState | null = null;
/**
* Any diagnostics related to the construction of the compilation.
*
* These are diagnostics which arose during setup of the host and/or program.
*/
private constructionDiagnostics: ts.Diagnostic[] = [];
/**
* Non-template diagnostics related to the program itself. Does not include template
* diagnostics because the template type checker memoizes them itself.
*
* This is set by (and memoizes) `getNonTemplateDiagnostics`.
*/
private nonTemplateDiagnostics: ts.Diagnostic[] | null = null;
private closureCompilerEnabled: boolean;
private currentProgram: ts.Program;
private entryPoint: ts.SourceFile | null;
private moduleResolver: ModuleResolver;
private resourceManager: AdapterResourceLoader;
private cycleAnalyzer: CycleAnalyzer;
readonly ignoreForDiagnostics: Set<ts.SourceFile>;
readonly ignoreForEmit: Set<ts.SourceFile>;
readonly enableTemplateTypeChecker: boolean;
private readonly enableBlockSyntax: boolean;
private readonly enableLetSyntax: boolean;
private readonly angularCoreVersion: string | null;
private readonly enableHmr: boolean;
/**
* `NgCompiler` can be reused for multiple compilations (for resource-only changes), and each
* new compilation uses a fresh `PerfRecorder`. Thus, classes created with a lifespan of the
* `NgCompiler` use a `DelegatingPerfRecorder` so the `PerfRecorder` they write to can be updated
* with each fresh compilation.
*/
private delegatingPerfRecorder: DelegatingPerfRecorder;
/**
* Convert a `CompilationTicket` into an `NgCompiler` instance for the requested compilation.
*
* Depending on the nature of the compilation request, the `NgCompiler` instance may be reused
* from a previous compilation and updated with any changes, it may be a new instance which
* incrementally reuses state from a previous compilation, or it may represent a fresh
* compilation entirely.
*/
static fromTicket(ticket: CompilationTicket, adapter: NgCompilerAdapter) {
switch (ticket.kind) {
case CompilationTicketKind.Fresh:
return new NgCompiler(
adapter,
ticket.options,
ticket.tsProgram,
ticket.programDriver,
ticket.incrementalBuildStrategy,
IncrementalCompilation.fresh(
ticket.tsProgram,
versionMapFromProgram(ticket.tsProgram, ticket.programDriver),
),
ticket.enableTemplateTypeChecker,
ticket.usePoisonedData,
ticket.perfRecorder,
);
case CompilationTicketKind.IncrementalTypeScript:
return new NgCompiler(
adapter,
ticket.options,
ticket.newProgram,
ticket.programDriver,
ticket.incrementalBuildStrategy,
ticket.incrementalCompilation,
ticket.enableTemplateTypeChecker,
ticket.usePoisonedData,
ticket.perfRecorder,
);
case CompilationTicketKind.IncrementalResource:
const compiler = ticket.compiler;
compiler.updateWithChangedResources(ticket.modifiedResourceFiles, ticket.perfRecorder);
return compiler;
}
}
private constructor(
private adapter: NgCompilerAdapter,
readonly options: NgCompilerOptions,
private inputProgram: ts.Program,
readonly programDriver: ProgramDriver,
readonly incrementalStrategy: IncrementalBuildStrategy,
readonly incrementalCompilation: IncrementalCompilation,
enableTemplateTypeChecker: boolean,
readonly usePoisonedData: boolean,
private livePerfRecorder: ActivePerfRecorder,
) {
this.delegatingPerfRecorder = new DelegatingPerfRecorder(this.perfRecorder);
this.usePoisonedData = usePoisonedData || !!options._compilePoisonedComponents;
this.enableTemplateTypeChecker =
enableTemplateTypeChecker || !!options._enableTemplateTypeChecker;
// TODO(crisbeto): remove this flag and base `enableBlockSyntax` on the `angularCoreVersion`.
this.enableBlockSyntax = options['_enableBlockSyntax'] ?? true;
this.enableLetSyntax = options['_enableLetSyntax'] ?? true;
this.angularCoreVersion = options['_angularCoreVersion'] ?? null;
this.enableHmr = !!options['_enableHmr'];
this.constructionDiagnostics.push(
...this.adapter.constructionDiagnostics,
...verifyCompatibleTypeCheckOptions(this.options),
);
this.currentProgram = inputProgram;
this.closureCompilerEnabled = !!this.options.annotateForClosureCompiler;
this.entryPoint =
adapter.entryPoint !== null ? getSourceFileOrNull(inputProgram, adapter.entryPoint) : null;
const moduleResolutionCache = ts.createModuleResolutionCache(
this.adapter.getCurrentDirectory(),
// doen't retain a reference to `this`, if other closures in the constructor here reference
// `this` internally then a closure created here would retain them. This can cause major
// memory leak issues since the `moduleResolutionCache` is a long-lived object and finds its
// way into all kinds of places inside TS internal objects.
this.adapter.getCanonicalFileName.bind(this.adapter),
);
this.moduleResolver = new ModuleResolver(
inputProgram,
this.options,
this.adapter,
moduleResolutionCache,
);
this.resourceManager = new AdapterResourceLoader(adapter, this.options);
this.cycleAnalyzer = new CycleAnalyzer(
new ImportGraph(inputProgram.getTypeChecker(), this.delegatingPerfRecorder),
);
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, inputProgram);
this.ignoreForDiagnostics = new Set(
inputProgram.getSourceFiles().filter((sf) => this.adapter.isShim(sf)),
);
this.ignoreForEmit = this.adapter.ignoreForEmit;
let dtsFileCount = 0;
let nonDtsFileCount = 0;
for (const sf of inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
dtsFileCount++;
} else {
nonDtsFileCount++;
}
}
livePerfRecorder.eventCount(PerfEvent.InputDtsFile, dtsFileCount);
livePerfRecorder.eventCount(PerfEvent.InputTsFile, nonDtsFileCount);
}
get perfRecorder(): ActivePerfRecorder {
return this.livePerfRecorder;
}
private updateWithChangedResources(
changedResources: Set<string>,
perfRecorder: ActivePerfRecorder,
): void {
this.livePerfRecorder = perfRecorder;
this.delegatingPerfRecorder.target = perfRecorder;
perfRecorder.inPhase(PerfPhase.ResourceUpdate, () => {
if (this.compilation === null) {
// Analysis hasn't happened yet, so no update is necessary - any changes to resources will
// be captured by the initial analysis pass itself.
return;
}
this.resourceManager.invalidate();
const classesToUpdate = new Set<DeclarationNode>();
for (const resourceFile of changedResources) {
for (const templateClass of this.getComponentsWithTemplateFile(resourceFile)) {
classesToUpdate.add(templateClass);
}
for (const styleClass of this.getComponentsWithStyleFile(resourceFile)) {
classesToUpdate.add(styleClass);
}
}
for (const clazz of classesToUpdate) {
this.compilation.traitCompiler.updateResources(clazz);
if (!ts.isClassDeclaration(clazz)) {
continue;
}
this.compilation.templateTypeChecker.invalidateClass(clazz);
}
});
}
/**
* Get the resource dependencies of a file.
*
* If the file is not part of the compilation, an empty array will be returned.
*/
getResourceDependencies(file: ts.SourceFile): string[] {
this.ensureAnalyzed();
return this.incrementalCompilation.depGraph.getResourceDependencies(file);
}
/**
* Get all Angular-related diagnostics for this compilation.
*/
getDiagnostics(): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [...this.getNonTemplateDiagnostics()];
// Type check code may throw fatal diagnostic errors if e.g. the type check
// block cannot be generated. Gracefully return the associated diagnostic.
// Note: If a fatal diagnostic is raised, do not repeat the same diagnostics
// by running the extended template checking code, which will attempt to
// generate the same TCB.
try {
diagnostics.push(...this.getTemplateDiagnostics(), ...this.runAdditionalChecks());
} catch (err: unknown) {
if (!isFatalDiagnosticError(err)) {
throw err;
}
diagnostics.push(err.toDiagnostic());
}
return this.addMessageTextDetails(diagnostics);
}
/**
* Get all Angular-related diagnostics for this compilation.
*
* If a `ts.SourceFile` is passed, only diagnostics related to that file are returned.
*/ | {
"end_byte": 20150,
"start_byte": 11156,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_20153_27145 | getDiagnosticsForFile(file: ts.SourceFile, optimizeFor: OptimizeFor): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [
...this.getNonTemplateDiagnostics().filter((diag) => diag.file === file),
];
// Type check code may throw fatal diagnostic errors if e.g. the type check
// block cannot be generated. Gracefully return the associated diagnostic.
// Note: If a fatal diagnostic is raised, do not repeat the same diagnostics
// by running the extended template checking code, which will attempt to
// generate the same TCB.
try {
diagnostics.push(
...this.getTemplateDiagnosticsForFile(file, optimizeFor),
...this.runAdditionalChecks(file),
);
} catch (err: unknown) {
if (!isFatalDiagnosticError(err)) {
throw err;
}
diagnostics.push(err.toDiagnostic());
}
return this.addMessageTextDetails(diagnostics);
}
/**
* Get all `ts.Diagnostic`s currently available that pertain to the given component.
*/
getDiagnosticsForComponent(component: ts.ClassDeclaration): ts.Diagnostic[] {
const compilation = this.ensureAnalyzed();
const ttc = compilation.templateTypeChecker;
const diagnostics: ts.Diagnostic[] = [];
// Type check code may throw fatal diagnostic errors if e.g. the type check
// block cannot be generated. Gracefully return the associated diagnostic.
// Note: If a fatal diagnostic is raised, do not repeat the same diagnostics
// by running the extended template checking code, which will attempt to
// generate the same TCB.
try {
diagnostics.push(...ttc.getDiagnosticsForComponent(component));
const {extendedTemplateChecker, templateSemanticsChecker} = compilation;
if (templateSemanticsChecker !== null) {
diagnostics.push(...templateSemanticsChecker.getDiagnosticsForComponent(component));
}
if (this.options.strictTemplates && extendedTemplateChecker !== null) {
diagnostics.push(...extendedTemplateChecker.getDiagnosticsForComponent(component));
}
} catch (err: unknown) {
if (!isFatalDiagnosticError(err)) {
throw err;
}
diagnostics.push(err.toDiagnostic());
}
return this.addMessageTextDetails(diagnostics);
}
/**
* Add Angular.io error guide links to diagnostics for this compilation.
*/
private addMessageTextDetails(diagnostics: ts.Diagnostic[]): ts.Diagnostic[] {
return diagnostics.map((diag) => {
if (diag.code && COMPILER_ERRORS_WITH_GUIDES.has(ngErrorCode(diag.code))) {
return {
...diag,
messageText:
diag.messageText +
`. Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/NG${ngErrorCode(diag.code)}`,
};
}
return diag;
});
}
/**
* Get all setup-related diagnostics for this compilation.
*/
getOptionDiagnostics(): ts.Diagnostic[] {
return this.constructionDiagnostics;
}
/**
* Get the current `ts.Program` known to this `NgCompiler`.
*
* Compilation begins with an input `ts.Program`, and during template type-checking operations new
* `ts.Program`s may be produced using the `ProgramDriver`. The most recent such `ts.Program` to
* be produced is available here.
*
* This `ts.Program` serves two key purposes:
*
* * As an incremental starting point for creating the next `ts.Program` based on files that the
* user has changed (for clients using the TS compiler program APIs).
*
* * As the "before" point for an incremental compilation invocation, to determine what's changed
* between the old and new programs (for all compilations).
*/
getCurrentProgram(): ts.Program {
return this.currentProgram;
}
getTemplateTypeChecker(): TemplateTypeChecker {
if (!this.enableTemplateTypeChecker) {
throw new Error(
'The `TemplateTypeChecker` does not work without `enableTemplateTypeChecker`.',
);
}
return this.ensureAnalyzed().templateTypeChecker;
}
/**
* Retrieves the `ts.Declaration`s for any component(s) which use the given template file.
*/
getComponentsWithTemplateFile(templateFilePath: string): ReadonlySet<DeclarationNode> {
const {resourceRegistry} = this.ensureAnalyzed();
return resourceRegistry.getComponentsWithTemplate(resolve(templateFilePath));
}
/**
* Retrieves the `ts.Declaration`s for any component(s) which use the given template file.
*/
getComponentsWithStyleFile(styleFilePath: string): ReadonlySet<DeclarationNode> {
const {resourceRegistry} = this.ensureAnalyzed();
return resourceRegistry.getComponentsWithStyle(resolve(styleFilePath));
}
/**
* Retrieves external resources for the given component.
*/
getComponentResources(classDecl: DeclarationNode): ComponentResources | null {
if (!isNamedClassDeclaration(classDecl)) {
return null;
}
const {resourceRegistry} = this.ensureAnalyzed();
const styles = resourceRegistry.getStyles(classDecl);
const template = resourceRegistry.getTemplate(classDecl);
if (template === null) {
return null;
}
return {styles, template};
}
getMeta(classDecl: DeclarationNode): PipeMeta | DirectiveMeta | null {
if (!isNamedClassDeclaration(classDecl)) {
return null;
}
const ref = new Reference(classDecl);
const {metaReader} = this.ensureAnalyzed();
const meta = metaReader.getPipeMetadata(ref) ?? metaReader.getDirectiveMetadata(ref);
if (meta === null) {
return null;
}
return meta;
}
/**
* Perform Angular's analysis step (as a precursor to `getDiagnostics` or `prepareEmit`)
* asynchronously.
*
* Normally, this operation happens lazily whenever `getDiagnostics` or `prepareEmit` are called.
* However, certain consumers may wish to allow for an asynchronous phase of analysis, where
* resources such as `styleUrls` are resolved asynchronously. In these cases `analyzeAsync` must
* be called first, and its `Promise` awaited prior to calling any other APIs of `NgCompiler`.
*/
async analyzeAsync(): Promise<void> {
if (this.compilation !== null) {
return;
}
await this.perfRecorder.inPhase(PerfPhase.Analysis, async () => {
this.compilation = this.makeCompilation();
const promises: Promise<void>[] = [];
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
continue;
}
let analysisPromise = this.compilation.traitCompiler.analyzeAsync(sf);
if (analysisPromise !== undefined) {
promises.push(analysisPromise);
}
}
await Promise.all(promises);
this.perfRecorder.memory(PerfCheckpoint.Analysis);
this.resolveCompilation(this.compilation.traitCompiler);
});
}
/**
* Fetch transformers and other information which is necessary for a consumer to `emit` the
* program with Angular-added definitions.
*/ | {
"end_byte": 27145,
"start_byte": 20153,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_27148_35152 | prepareEmit(): {
transformers: ts.CustomTransformers;
} {
const compilation = this.ensureAnalyzed();
// Untag all the files, otherwise TS 5.4 may end up emitting
// references to typecheck files (see #56945 and #57135).
untagAllTsFiles(this.inputProgram);
const coreImportsFrom = compilation.isCore ? getR3SymbolsFile(this.inputProgram) : null;
let importRewriter: ImportRewriter;
if (coreImportsFrom !== null) {
importRewriter = new R3SymbolsImportRewriter(coreImportsFrom.fileName);
} else {
importRewriter = new NoopImportRewriter();
}
const defaultImportTracker = new DefaultImportTracker();
const before = [
ivyTransformFactory(
compilation.traitCompiler,
compilation.reflector,
importRewriter,
defaultImportTracker,
compilation.localCompilationExtraImportsTracker,
this.delegatingPerfRecorder,
compilation.isCore,
this.closureCompilerEnabled,
),
aliasTransformFactory(compilation.traitCompiler.exportStatements),
defaultImportTracker.importPreservingTransformer(),
];
// If there are JIT declarations, wire up the JIT transform and efficiently
// run it against the target declarations.
if (compilation.supportJitMode && compilation.jitDeclarationRegistry.jitDeclarations.size > 0) {
const {jitDeclarations} = compilation.jitDeclarationRegistry;
const jitDeclarationsArray = Array.from(jitDeclarations);
const jitDeclarationOriginalNodes = new Set(
jitDeclarationsArray.map((d) => ts.getOriginalNode(d)),
);
const sourceFilesWithJit = new Set(
jitDeclarationsArray.map((d) => d.getSourceFile().fileName),
);
before.push((ctx) => {
const reflectionHost = new TypeScriptReflectionHost(this.inputProgram.getTypeChecker());
const jitTransform = angularJitApplicationTransform(
this.inputProgram,
compilation.isCore,
(node) => {
// Class may be synthetic at this point due to Ivy transform.
node = ts.getOriginalNode(node, ts.isClassDeclaration);
return reflectionHost.isClass(node) && jitDeclarationOriginalNodes.has(node);
},
)(ctx);
return (sourceFile) => {
if (!sourceFilesWithJit.has(sourceFile.fileName)) {
return sourceFile;
}
return jitTransform(sourceFile);
};
});
}
const afterDeclarations: ts.TransformerFactory<ts.SourceFile>[] = [];
// In local compilation mode we don't make use of .d.ts files for Angular compilation, so their
// transformation can be ditched.
if (
this.options.compilationMode !== 'experimental-local' &&
compilation.dtsTransforms !== null
) {
afterDeclarations.push(
declarationTransformFactory(
compilation.dtsTransforms,
compilation.reflector,
compilation.refEmitter,
importRewriter,
),
);
}
// Only add aliasing re-exports to the .d.ts output if the `AliasingHost` requests it.
if (compilation.aliasingHost !== null && compilation.aliasingHost.aliasExportsInDts) {
afterDeclarations.push(aliasTransformFactory(compilation.traitCompiler.exportStatements));
}
return {transformers: {before, afterDeclarations} as ts.CustomTransformers};
}
/**
* Run the indexing process and return a `Map` of all indexed components.
*
* See the `indexing` package for more details.
*/
getIndexedComponents(): Map<DeclarationNode, IndexedComponent> {
const compilation = this.ensureAnalyzed();
const context = new IndexingContext();
compilation.traitCompiler.index(context);
return generateAnalysis(context);
}
/**
* Gets information for the current program that may be used to generate API
* reference documentation. This includes Angular-specific information, such
* as component inputs and outputs.
*
* @param entryPoint Path to the entry point for the package for which API
* docs should be extracted.
*
* @returns A map of symbols with their associated module, eg: ApplicationRef => @angular/core
*/
getApiDocumentation(
entryPoint: string,
privateModules: Set<string>,
): {entries: DocEntry[]; symbols: Map<string, string>} {
const compilation = this.ensureAnalyzed();
const checker = this.inputProgram.getTypeChecker();
const docsExtractor = new DocsExtractor(checker, compilation.metaReader);
const entryPointSourceFile = this.inputProgram.getSourceFiles().find((sourceFile) => {
// TODO: this will need to be more specific than `.includes`, but the exact path comparison
// will be easier to figure out when the pipeline is running end-to-end.
return sourceFile.fileName.includes(entryPoint);
});
if (!entryPointSourceFile) {
throw new Error(`Entry point "${entryPoint}" not found in program sources.`);
}
// TODO: Technically the current directory is not the root dir.
// Should probably be derived from the config.
const rootDir = this.inputProgram.getCurrentDirectory();
return docsExtractor.extractAll(entryPointSourceFile, rootDir, privateModules);
}
/**
* Collect i18n messages into the `Xi18nContext`.
*/
xi18n(ctx: Xi18nContext): void {
// Note that the 'resolve' phase is not strictly necessary for xi18n, but this is not currently
// optimized.
const compilation = this.ensureAnalyzed();
compilation.traitCompiler.xi18n(ctx);
}
/**
* Emits the JavaScript module that can be used to replace the metadata of a class during HMR.
* @param node Class for which to generate the update module.
*/
emitHmrUpdateModule(node: DeclarationNode): string | null {
const {traitCompiler, reflector} = this.ensureAnalyzed();
if (!reflector.isClass(node)) {
return null;
}
const callback = traitCompiler.compileHmrUpdateCallback(node);
if (callback === null) {
return null;
}
const sourceFile = node.getSourceFile();
const printer = ts.createPrinter();
const nodeText = printer.printNode(ts.EmitHint.Unspecified, callback, sourceFile);
return ts.transpileModule(nodeText, {
compilerOptions: this.options,
fileName: sourceFile.fileName,
reportDiagnostics: false,
}).outputText;
}
private ensureAnalyzed(this: NgCompiler): LazyCompilationState {
if (this.compilation === null) {
this.analyzeSync();
}
return this.compilation!;
}
private analyzeSync(): void {
this.perfRecorder.inPhase(PerfPhase.Analysis, () => {
this.compilation = this.makeCompilation();
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
continue;
}
this.compilation.traitCompiler.analyzeSync(sf);
}
this.perfRecorder.memory(PerfCheckpoint.Analysis);
this.resolveCompilation(this.compilation.traitCompiler);
});
}
private resolveCompilation(traitCompiler: TraitCompiler): void {
this.perfRecorder.inPhase(PerfPhase.Resolve, () => {
traitCompiler.resolve();
// At this point, analysis is complete and the compiler can now calculate which files need to
// be emitted, so do that.
this.incrementalCompilation.recordSuccessfulAnalysis(traitCompiler);
this.perfRecorder.memory(PerfCheckpoint.Resolve);
});
}
private get fullTemplateTypeCheck(): boolean {
// Determine the strictness level of type checking based on compiler options. As
// `strictTemplates` is a superset of `fullTemplateTypeCheck`, the former implies the latter.
// Also see `verifyCompatibleTypeCheckOptions` where it is verified that `fullTemplateTypeCheck`
// is not disabled when `strictTemplates` is enabled.
const strictTemplates = !!this.options.strictTemplates;
return strictTemplates || !!this.options.fullTemplateTypeCheck;
} | {
"end_byte": 35152,
"start_byte": 27148,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_35156_44145 | private getTypeCheckingConfig(): TypeCheckingConfig {
// Determine the strictness level of type checking based on compiler options. As
// `strictTemplates` is a superset of `fullTemplateTypeCheck`, the former implies the latter.
// Also see `verifyCompatibleTypeCheckOptions` where it is verified that `fullTemplateTypeCheck`
// is not disabled when `strictTemplates` is enabled.
const strictTemplates = !!this.options.strictTemplates;
const useInlineTypeConstructors = this.programDriver.supportsInlineOperations;
// Check whether the loaded version of `@angular/core` in the `ts.Program` supports unwrapping
// writable signals for type-checking. If this check fails to find a suitable .d.ts file, fall
// back to version detection. Only Angular versions greater than 17.2 have the necessary symbols
// to type check signals in two-way bindings. We also allow version 0.0.0 in case somebody is
// using Angular at head.
let allowSignalsInTwoWayBindings =
coreHasSymbol(this.inputProgram, R3Identifiers.unwrapWritableSignal) ??
(this.angularCoreVersion === null ||
coreVersionSupportsFeature(this.angularCoreVersion, '>= 17.2.0-0'));
// First select a type-checking configuration, based on whether full template type-checking is
// requested.
let typeCheckingConfig: TypeCheckingConfig;
if (this.fullTemplateTypeCheck) {
typeCheckingConfig = {
applyTemplateContextGuards: strictTemplates,
checkQueries: false,
checkTemplateBodies: true,
alwaysCheckSchemaInTemplateBodies: true,
checkTypeOfInputBindings: strictTemplates,
honorAccessModifiersForInputBindings: false,
checkControlFlowBodies: true,
strictNullInputBindings: strictTemplates,
checkTypeOfAttributes: strictTemplates,
// Even in full template type-checking mode, DOM binding checks are not quite ready yet.
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: strictTemplates,
checkTypeOfAnimationEvents: strictTemplates,
// Checking of DOM events currently has an adverse effect on developer experience,
// e.g. for `<input (blur)="update($event.target.value)">` enabling this check results in:
// - error TS2531: Object is possibly 'null'.
// - error TS2339: Property 'value' does not exist on type 'EventTarget'.
checkTypeOfDomEvents: strictTemplates,
checkTypeOfDomReferences: strictTemplates,
// Non-DOM references have the correct type in View Engine so there is no strictness flag.
checkTypeOfNonDomReferences: true,
// Pipes are checked in View Engine so there is no strictness flag.
checkTypeOfPipes: true,
strictSafeNavigationTypes: strictTemplates,
useContextGenericType: strictTemplates,
strictLiteralTypes: true,
enableTemplateTypeChecker: this.enableTemplateTypeChecker,
useInlineTypeConstructors,
// Warnings for suboptimal type inference are only enabled if in Language Service mode
// (providing the full TemplateTypeChecker API) and if strict mode is not enabled. In strict
// mode, the user is in full control of type inference.
suggestionsForSuboptimalTypeInference: this.enableTemplateTypeChecker && !strictTemplates,
controlFlowPreventingContentProjection:
this.options.extendedDiagnostics?.defaultCategory || DiagnosticCategoryLabel.Warning,
unusedStandaloneImports:
this.options.extendedDiagnostics?.defaultCategory || DiagnosticCategoryLabel.Warning,
allowSignalsInTwoWayBindings,
};
} else {
typeCheckingConfig = {
applyTemplateContextGuards: false,
checkQueries: false,
checkTemplateBodies: false,
checkControlFlowBodies: false,
// Enable deep schema checking in "basic" template type-checking mode only if Closure
// compilation is requested, which is a good proxy for "only in google3".
alwaysCheckSchemaInTemplateBodies: this.closureCompilerEnabled,
checkTypeOfInputBindings: false,
strictNullInputBindings: false,
honorAccessModifiersForInputBindings: false,
checkTypeOfAttributes: false,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: false,
checkTypeOfAnimationEvents: false,
checkTypeOfDomEvents: false,
checkTypeOfDomReferences: false,
checkTypeOfNonDomReferences: false,
checkTypeOfPipes: false,
strictSafeNavigationTypes: false,
useContextGenericType: false,
strictLiteralTypes: false,
enableTemplateTypeChecker: this.enableTemplateTypeChecker,
useInlineTypeConstructors,
// In "basic" template type-checking mode, no warnings are produced since most things are
// not checked anyways.
suggestionsForSuboptimalTypeInference: false,
controlFlowPreventingContentProjection:
this.options.extendedDiagnostics?.defaultCategory || DiagnosticCategoryLabel.Warning,
unusedStandaloneImports:
this.options.extendedDiagnostics?.defaultCategory || DiagnosticCategoryLabel.Warning,
allowSignalsInTwoWayBindings,
};
}
// Apply explicitly configured strictness flags on top of the default configuration
// based on "fullTemplateTypeCheck".
if (this.options.strictInputTypes !== undefined) {
typeCheckingConfig.checkTypeOfInputBindings = this.options.strictInputTypes;
typeCheckingConfig.applyTemplateContextGuards = this.options.strictInputTypes;
}
if (this.options.strictInputAccessModifiers !== undefined) {
typeCheckingConfig.honorAccessModifiersForInputBindings =
this.options.strictInputAccessModifiers;
}
if (this.options.strictNullInputTypes !== undefined) {
typeCheckingConfig.strictNullInputBindings = this.options.strictNullInputTypes;
}
if (this.options.strictOutputEventTypes !== undefined) {
typeCheckingConfig.checkTypeOfOutputEvents = this.options.strictOutputEventTypes;
typeCheckingConfig.checkTypeOfAnimationEvents = this.options.strictOutputEventTypes;
}
if (this.options.strictDomEventTypes !== undefined) {
typeCheckingConfig.checkTypeOfDomEvents = this.options.strictDomEventTypes;
}
if (this.options.strictSafeNavigationTypes !== undefined) {
typeCheckingConfig.strictSafeNavigationTypes = this.options.strictSafeNavigationTypes;
}
if (this.options.strictDomLocalRefTypes !== undefined) {
typeCheckingConfig.checkTypeOfDomReferences = this.options.strictDomLocalRefTypes;
}
if (this.options.strictAttributeTypes !== undefined) {
typeCheckingConfig.checkTypeOfAttributes = this.options.strictAttributeTypes;
}
if (this.options.strictContextGenerics !== undefined) {
typeCheckingConfig.useContextGenericType = this.options.strictContextGenerics;
}
if (this.options.strictLiteralTypes !== undefined) {
typeCheckingConfig.strictLiteralTypes = this.options.strictLiteralTypes;
}
if (
this.options.extendedDiagnostics?.checks?.controlFlowPreventingContentProjection !== undefined
) {
typeCheckingConfig.controlFlowPreventingContentProjection =
this.options.extendedDiagnostics.checks.controlFlowPreventingContentProjection;
}
if (this.options.extendedDiagnostics?.checks?.unusedStandaloneImports !== undefined) {
typeCheckingConfig.unusedStandaloneImports =
this.options.extendedDiagnostics.checks.unusedStandaloneImports;
}
return typeCheckingConfig;
}
private getTemplateDiagnostics(): ReadonlyArray<ts.Diagnostic> {
const compilation = this.ensureAnalyzed();
const diagnostics: ts.Diagnostic[] = [];
// Get diagnostics for all files.
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile || this.adapter.isShim(sf)) {
continue;
}
diagnostics.push(
...compilation.templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram),
);
}
const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
return diagnostics;
}
private getTemplateDiagnosticsForFile(
sf: ts.SourceFile,
optimizeFor: OptimizeFor,
): ReadonlyArray<ts.Diagnostic> {
const compilation = this.ensureAnalyzed();
// Get the diagnostics.
const diagnostics: ts.Diagnostic[] = [];
if (!sf.isDeclarationFile && !this.adapter.isShim(sf)) {
diagnostics.push(...compilation.templateTypeChecker.getDiagnosticsForFile(sf, optimizeFor));
}
const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
return diagnostics;
} | {
"end_byte": 44145,
"start_byte": 35156,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_44149_45984 | private getNonTemplateDiagnostics(): ts.Diagnostic[] {
if (this.nonTemplateDiagnostics === null) {
const compilation = this.ensureAnalyzed();
this.nonTemplateDiagnostics = [...compilation.traitCompiler.diagnostics];
if (this.entryPoint !== null && compilation.exportReferenceGraph !== null) {
this.nonTemplateDiagnostics.push(
...checkForPrivateExports(
this.entryPoint,
this.inputProgram.getTypeChecker(),
compilation.exportReferenceGraph,
),
);
}
}
return this.nonTemplateDiagnostics;
}
private runAdditionalChecks(sf?: ts.SourceFile): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
const compilation = this.ensureAnalyzed();
const {extendedTemplateChecker, templateSemanticsChecker, sourceFileValidator} = compilation;
const files = sf ? [sf] : this.inputProgram.getSourceFiles();
for (const sf of files) {
if (sourceFileValidator !== null) {
const sourceFileDiagnostics = sourceFileValidator.getDiagnosticsForFile(sf);
if (sourceFileDiagnostics !== null) {
diagnostics.push(...sourceFileDiagnostics);
}
}
if (templateSemanticsChecker !== null) {
diagnostics.push(
...compilation.traitCompiler.runAdditionalChecks(sf, (clazz, handler) => {
return handler.templateSemanticsCheck?.(clazz, templateSemanticsChecker) || null;
}),
);
}
if (this.options.strictTemplates && extendedTemplateChecker !== null) {
diagnostics.push(
...compilation.traitCompiler.runAdditionalChecks(sf, (clazz, handler) => {
return handler.extendedTemplateCheck?.(clazz, extendedTemplateChecker) || null;
}),
);
}
}
return diagnostics;
} | {
"end_byte": 45984,
"start_byte": 44149,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_45988_55205 | private makeCompilation(): LazyCompilationState {
const isCore = isAngularCorePackage(this.inputProgram);
// Note: If this compilation builds `@angular/core`, we always build in full compilation
// mode. Code inside the core package is always compatible with itself, so it does not
// make sense to go through the indirection of partial compilation
let compilationMode: CompilationMode = CompilationMode.FULL;
if (!isCore) {
switch (this.options.compilationMode) {
case 'full':
compilationMode = CompilationMode.FULL;
break;
case 'partial':
compilationMode = CompilationMode.PARTIAL;
break;
case 'experimental-local':
compilationMode = CompilationMode.LOCAL;
break;
}
}
const checker = this.inputProgram.getTypeChecker();
const reflector = new TypeScriptReflectionHost(
checker,
compilationMode === CompilationMode.LOCAL,
);
// Construct the ReferenceEmitter.
let refEmitter: ReferenceEmitter;
let aliasingHost: AliasingHost | null = null;
if (
this.adapter.unifiedModulesHost === null ||
(!this.options['_useHostForImportGeneration'] &&
!this.options['_useHostForImportAndAliasGeneration'])
) {
let localImportStrategy: ReferenceEmitStrategy;
// The strategy used for local, in-project imports depends on whether TS has been configured
// with rootDirs. If so, then multiple directories may be mapped in the same "module
// namespace" and the logic of `LogicalProjectStrategy` is required to generate correct
// imports which may cross these multiple directories. Otherwise, plain relative imports are
// sufficient.
if (
this.options.rootDir !== undefined ||
(this.options.rootDirs !== undefined && this.options.rootDirs.length > 0)
) {
// rootDirs logic is in effect - use the `LogicalProjectStrategy` for in-project relative
// imports.
localImportStrategy = new LogicalProjectStrategy(
reflector,
new LogicalFileSystem([...this.adapter.rootDirs], this.adapter),
);
} else {
// Plain relative imports are all that's needed.
localImportStrategy = new RelativePathStrategy(reflector);
}
// The CompilerHost doesn't have fileNameToModuleName, so build an NPM-centric reference
// resolution strategy.
refEmitter = new ReferenceEmitter([
// First, try to use local identifiers if available.
new LocalIdentifierStrategy(),
// Next, attempt to use an absolute import.
new AbsoluteModuleStrategy(this.inputProgram, checker, this.moduleResolver, reflector),
// Finally, check if the reference is being written into a file within the project's .ts
// sources, and use a relative import if so. If this fails, ReferenceEmitter will throw
// an error.
localImportStrategy,
]);
// If an entrypoint is present, then all user imports should be directed through the
// entrypoint and private exports are not needed. The compiler will validate that all
// publicly visible directives/pipes are importable via this entrypoint.
if (this.entryPoint === null && this.options.generateDeepReexports === true) {
// No entrypoint is present and deep re-exports were requested, so configure the aliasing
// system to generate them.
aliasingHost = new PrivateExportAliasingHost(reflector);
}
} else {
// The CompilerHost supports fileNameToModuleName, so use that to emit imports.
refEmitter = new ReferenceEmitter([
// First, try to use local identifiers if available.
new LocalIdentifierStrategy(),
// Then use aliased references (this is a workaround to StrictDeps checks).
...(this.options['_useHostForImportAndAliasGeneration'] ? [new AliasStrategy()] : []),
// Then use fileNameToModuleName to emit imports.
new UnifiedModulesStrategy(reflector, this.adapter.unifiedModulesHost),
]);
if (this.options['_useHostForImportAndAliasGeneration']) {
aliasingHost = new UnifiedModulesAliasingHost(this.adapter.unifiedModulesHost);
}
}
const evaluator = new PartialEvaluator(
reflector,
checker,
this.incrementalCompilation.depGraph,
);
const dtsReader = new DtsMetadataReader(checker, reflector);
const localMetaRegistry = new LocalMetadataRegistry();
const localMetaReader: MetadataReaderWithIndex = localMetaRegistry;
const depScopeReader = new MetadataDtsModuleScopeResolver(dtsReader, aliasingHost);
const metaReader = new CompoundMetadataReader([localMetaReader, dtsReader]);
const ngModuleIndex = new NgModuleIndexImpl(metaReader, localMetaReader);
const ngModuleScopeRegistry = new LocalModuleScopeRegistry(
localMetaReader,
metaReader,
depScopeReader,
refEmitter,
aliasingHost,
);
const standaloneScopeReader = new StandaloneComponentScopeReader(
metaReader,
ngModuleScopeRegistry,
depScopeReader,
);
const scopeReader: ComponentScopeReader = new CompoundComponentScopeReader([
ngModuleScopeRegistry,
standaloneScopeReader,
]);
const semanticDepGraphUpdater = this.incrementalCompilation.semanticDepGraphUpdater;
const metaRegistry = new CompoundMetadataRegistry([localMetaRegistry, ngModuleScopeRegistry]);
const injectableRegistry = new InjectableClassRegistry(reflector, isCore);
const hostDirectivesResolver = new HostDirectivesResolver(metaReader);
const exportedProviderStatusResolver = new ExportedProviderStatusResolver(metaReader);
const importTracker = new ImportedSymbolsTracker();
const typeCheckScopeRegistry = new TypeCheckScopeRegistry(
scopeReader,
metaReader,
hostDirectivesResolver,
);
// If a flat module entrypoint was specified, then track references via a `ReferenceGraph` in
// order to produce proper diagnostics for incorrectly exported directives/pipes/etc. If there
// is no flat module entrypoint then don't pay the cost of tracking references.
let referencesRegistry: ReferencesRegistry;
let exportReferenceGraph: ReferenceGraph | null = null;
if (this.entryPoint !== null) {
exportReferenceGraph = new ReferenceGraph();
referencesRegistry = new ReferenceGraphAdapter(exportReferenceGraph);
} else {
referencesRegistry = new NoopReferencesRegistry();
}
const dtsTransforms = new DtsTransformRegistry();
const resourceRegistry = new ResourceRegistry();
const deferredSymbolsTracker = new DeferredSymbolTracker(
this.inputProgram.getTypeChecker(),
this.options.onlyExplicitDeferDependencyImports ?? false,
);
let localCompilationExtraImportsTracker: LocalCompilationExtraImportsTracker | null = null;
if (compilationMode === CompilationMode.LOCAL && this.options.generateExtraImportsInLocalMode) {
localCompilationExtraImportsTracker = new LocalCompilationExtraImportsTracker(checker);
}
// Cycles are handled in full and local compilation modes by "remote scoping".
// "Remote scoping" does not work well with tree shaking for libraries.
// So in partial compilation mode, when building a library, a cycle will cause an error.
const cycleHandlingStrategy =
compilationMode === CompilationMode.PARTIAL
? CycleHandlingStrategy.Error
: CycleHandlingStrategy.UseRemoteScoping;
const strictCtorDeps = this.options.strictInjectionParameters || false;
const supportJitMode = this.options['supportJitMode'] ?? true;
const supportTestBed = this.options['supportTestBed'] ?? true;
const externalRuntimeStyles = this.options['externalRuntimeStyles'] ?? false;
// Libraries compiled in partial mode could potentially be used with TestBed within an
// application. Since this is not known at library compilation time, support is required to
// prevent potential downstream application testing breakage.
if (supportTestBed === false && compilationMode === CompilationMode.PARTIAL) {
throw new Error(
'TestBed support ("supportTestBed" option) cannot be disabled in partial compilation mode.',
);
}
if (supportJitMode === false && compilationMode === CompilationMode.PARTIAL) {
throw new Error(
'JIT mode support ("supportJitMode" option) cannot be disabled in partial compilation mode.',
);
}
// Currently forbidOrphanComponents depends on the code generated behind ngJitMode flag. Until
// we come up with a better design for these flags, it is necessary to have the JIT mode in
// order for forbidOrphanComponents to be able to work properly.
if (supportJitMode === false && this.options.forbidOrphanComponents) {
throw new Error(
'JIT mode support ("supportJitMode" option) cannot be disabled when forbidOrphanComponents is set to true',
);
}
const jitDeclarationRegistry = new JitDeclarationRegistry();
// Set up the IvyCompilation, which manages state for the Ivy transformer. | {
"end_byte": 55205,
"start_byte": 45988,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_55210_63076 | const handlers: DecoratorHandler<unknown, unknown, SemanticSymbol | null, unknown>[] = [
new ComponentDecoratorHandler(
reflector,
evaluator,
metaRegistry,
metaReader,
scopeReader,
this.adapter,
ngModuleScopeRegistry,
typeCheckScopeRegistry,
resourceRegistry,
isCore,
strictCtorDeps,
this.resourceManager,
this.adapter.rootDirs,
this.options.preserveWhitespaces || false,
this.options.i18nUseExternalIds !== false,
this.options.enableI18nLegacyMessageIdFormat !== false,
this.usePoisonedData,
this.options.i18nNormalizeLineEndingsInICUs === true,
this.moduleResolver,
this.cycleAnalyzer,
cycleHandlingStrategy,
refEmitter,
referencesRegistry,
this.incrementalCompilation.depGraph,
injectableRegistry,
semanticDepGraphUpdater,
this.closureCompilerEnabled,
this.delegatingPerfRecorder,
hostDirectivesResolver,
importTracker,
supportTestBed,
compilationMode,
deferredSymbolsTracker,
!!this.options.forbidOrphanComponents,
this.enableBlockSyntax,
this.enableLetSyntax,
externalRuntimeStyles,
localCompilationExtraImportsTracker,
jitDeclarationRegistry,
this.options.i18nPreserveWhitespaceForLegacyExtraction ?? true,
!!this.options.strictStandalone,
this.enableHmr,
),
// TODO(alxhub): understand why the cast here is necessary (something to do with `null`
// not being assignable to `unknown` when wrapped in `Readonly`).
new DirectiveDecoratorHandler(
reflector,
evaluator,
metaRegistry,
ngModuleScopeRegistry,
metaReader,
injectableRegistry,
refEmitter,
referencesRegistry,
isCore,
strictCtorDeps,
semanticDepGraphUpdater,
this.closureCompilerEnabled,
this.delegatingPerfRecorder,
importTracker,
supportTestBed,
compilationMode,
jitDeclarationRegistry,
!!this.options.strictStandalone,
) as Readonly<DecoratorHandler<unknown, unknown, SemanticSymbol | null, unknown>>,
// Pipe handler must be before injectable handler in list so pipe factories are printed
// before injectable factories (so injectable factories can delegate to them)
new PipeDecoratorHandler(
reflector,
evaluator,
metaRegistry,
ngModuleScopeRegistry,
injectableRegistry,
isCore,
this.delegatingPerfRecorder,
supportTestBed,
compilationMode,
!!this.options.generateExtraImportsInLocalMode,
!!this.options.strictStandalone,
),
new InjectableDecoratorHandler(
reflector,
evaluator,
isCore,
strictCtorDeps,
injectableRegistry,
this.delegatingPerfRecorder,
supportTestBed,
compilationMode,
),
new NgModuleDecoratorHandler(
reflector,
evaluator,
metaReader,
metaRegistry,
ngModuleScopeRegistry,
referencesRegistry,
exportedProviderStatusResolver,
semanticDepGraphUpdater,
isCore,
refEmitter,
this.closureCompilerEnabled,
this.options.onlyPublishPublicTypingsForNgModules ?? false,
injectableRegistry,
this.delegatingPerfRecorder,
supportTestBed,
supportJitMode,
compilationMode,
localCompilationExtraImportsTracker,
jitDeclarationRegistry,
),
];
const traitCompiler = new TraitCompiler(
handlers,
reflector,
this.delegatingPerfRecorder,
this.incrementalCompilation,
this.options.compileNonExportedClasses !== false,
compilationMode,
dtsTransforms,
semanticDepGraphUpdater,
this.adapter,
);
// Template type-checking may use the `ProgramDriver` to produce new `ts.Program`(s). If this
// happens, they need to be tracked by the `NgCompiler`.
const notifyingDriver = new NotifyingProgramDriverWrapper(
this.programDriver,
(program: ts.Program) => {
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
},
);
const typeCheckingConfig = this.getTypeCheckingConfig();
const templateTypeChecker = new TemplateTypeCheckerImpl(
this.inputProgram,
notifyingDriver,
traitCompiler,
typeCheckingConfig,
refEmitter,
reflector,
this.adapter,
this.incrementalCompilation,
metaReader,
localMetaReader,
ngModuleIndex,
scopeReader,
typeCheckScopeRegistry,
this.delegatingPerfRecorder,
);
// Only construct the extended template checker if the configuration is valid and usable.
const extendedTemplateChecker =
this.constructionDiagnostics.length === 0
? new ExtendedTemplateCheckerImpl(
templateTypeChecker,
checker,
ALL_DIAGNOSTIC_FACTORIES,
this.options,
)
: null;
const templateSemanticsChecker =
this.constructionDiagnostics.length === 0
? new TemplateSemanticsCheckerImpl(templateTypeChecker)
: null;
const sourceFileValidator =
this.constructionDiagnostics.length === 0
? new SourceFileValidator(reflector, importTracker, templateTypeChecker, typeCheckingConfig)
: null;
return {
isCore,
traitCompiler,
reflector,
scopeRegistry: ngModuleScopeRegistry,
dtsTransforms,
exportReferenceGraph,
metaReader,
typeCheckScopeRegistry,
aliasingHost,
refEmitter,
templateTypeChecker,
resourceRegistry,
extendedTemplateChecker,
localCompilationExtraImportsTracker,
jitDeclarationRegistry,
templateSemanticsChecker,
sourceFileValidator,
supportJitMode,
};
}
}
/**
* Determine if the given `Program` is @angular/core.
*/
export function isAngularCorePackage(program: ts.Program): boolean {
// Look for its_just_angular.ts somewhere in the program.
const r3Symbols = getR3SymbolsFile(program);
if (r3Symbols === null) {
return false;
}
// Look for the constant ITS_JUST_ANGULAR in that file.
return r3Symbols.statements.some((stmt) => {
// The statement must be a variable declaration statement.
if (!ts.isVariableStatement(stmt)) {
return false;
}
// It must be exported.
const modifiers = ts.getModifiers(stmt);
if (
modifiers === undefined ||
!modifiers.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword)
) {
return false;
}
// It must declare ITS_JUST_ANGULAR.
return stmt.declarationList.declarations.some((decl) => {
// The declaration must match the name.
if (!ts.isIdentifier(decl.name) || decl.name.text !== 'ITS_JUST_ANGULAR') {
return false;
}
// It must initialize the variable to true.
if (decl.initializer === undefined || decl.initializer.kind !== ts.SyntaxKind.TrueKeyword) {
return false;
}
// This definition matches.
return true;
});
});
}
/**
* Find the 'r3_symbols.ts' file in the given `Program`, or return `null` if it wasn't there.
*/
function getR3SymbolsFile(program: ts.Program): ts.SourceFile | null {
return (
program.getSourceFiles().find((file) => file.fileName.indexOf('r3_symbols.ts') >= 0) || null
);
}
/**
* Since "strictTemplates" is a true superset of type checking capabilities compared to
* "fullTemplateTypeCheck", it is required that the latter is not explicitly disabled if the
* former is enabled.
*/ | {
"end_byte": 63076,
"start_byte": 55210,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/core/src/compiler.ts_63077_68364 | function* verifyCompatibleTypeCheckOptions(
options: NgCompilerOptions,
): Generator<ts.Diagnostic, void, void> {
if (options.fullTemplateTypeCheck === false && options.strictTemplates === true) {
yield makeConfigDiagnostic({
category: ts.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK,
messageText: `
Angular compiler option "strictTemplates" is enabled, however "fullTemplateTypeCheck" is disabled.
Having the "strictTemplates" flag enabled implies that "fullTemplateTypeCheck" is also enabled, so
the latter can not be explicitly disabled.
One of the following actions is required:
1. Remove the "fullTemplateTypeCheck" option.
2. Remove "strictTemplates" or set it to 'false'.
More information about the template type checking compiler options can be found in the documentation:
https://angular.dev/tools/cli/template-typecheck
`.trim(),
});
}
if (options.extendedDiagnostics && options.strictTemplates === false) {
yield makeConfigDiagnostic({
category: ts.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_IMPLIES_STRICT_TEMPLATES,
messageText: `
Angular compiler option "extendedDiagnostics" is configured, however "strictTemplates" is disabled.
Using "extendedDiagnostics" requires that "strictTemplates" is also enabled.
One of the following actions is required:
1. Remove "strictTemplates: false" to enable it.
2. Remove "extendedDiagnostics" configuration to disable them.
`.trim(),
});
}
const allowedCategoryLabels = Array.from(Object.values(DiagnosticCategoryLabel)) as string[];
const defaultCategory = options.extendedDiagnostics?.defaultCategory;
if (defaultCategory && !allowedCategoryLabels.includes(defaultCategory)) {
yield makeConfigDiagnostic({
category: ts.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL,
messageText: `
Angular compiler option "extendedDiagnostics.defaultCategory" has an unknown diagnostic category: "${defaultCategory}".
Allowed diagnostic categories are:
${allowedCategoryLabels.join('\n')}
`.trim(),
});
}
for (const [checkName, category] of Object.entries(options.extendedDiagnostics?.checks ?? {})) {
if (!SUPPORTED_DIAGNOSTIC_NAMES.has(checkName)) {
yield makeConfigDiagnostic({
category: ts.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CHECK,
messageText: `
Angular compiler option "extendedDiagnostics.checks" has an unknown check: "${checkName}".
Allowed check names are:
${Array.from(SUPPORTED_DIAGNOSTIC_NAMES).join('\n')}
`.trim(),
});
}
if (!allowedCategoryLabels.includes(category)) {
yield makeConfigDiagnostic({
category: ts.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL,
messageText: `
Angular compiler option "extendedDiagnostics.checks['${checkName}']" has an unknown diagnostic category: "${category}".
Allowed diagnostic categories are:
${allowedCategoryLabels.join('\n')}
`.trim(),
});
}
}
}
function makeConfigDiagnostic({
category,
code,
messageText,
}: {
category: ts.DiagnosticCategory;
code: ErrorCode;
messageText: string;
}): ts.Diagnostic {
return {
category,
code: ngErrorCode(code),
file: undefined,
start: undefined,
length: undefined,
messageText,
};
}
class ReferenceGraphAdapter implements ReferencesRegistry {
constructor(private graph: ReferenceGraph) {}
add(source: DeclarationNode, ...references: Reference<DeclarationNode>[]): void {
for (const {node} of references) {
let sourceFile = node.getSourceFile();
if (sourceFile === undefined) {
sourceFile = ts.getOriginalNode(node).getSourceFile();
}
// Only record local references (not references into .d.ts files).
if (sourceFile === undefined || !isDtsPath(sourceFile.fileName)) {
this.graph.add(source, node);
}
}
}
}
class NotifyingProgramDriverWrapper implements ProgramDriver {
getSourceFileVersion: ProgramDriver['getSourceFileVersion'];
constructor(
private delegate: ProgramDriver,
private notifyNewProgram: (program: ts.Program) => void,
) {
this.getSourceFileVersion = this.delegate.getSourceFileVersion?.bind(this);
}
get supportsInlineOperations() {
return this.delegate.supportsInlineOperations;
}
getProgram(): ts.Program {
return this.delegate.getProgram();
}
updateFiles(contents: Map<AbsoluteFsPath, FileUpdate>, updateMode: UpdateMode): void {
this.delegate.updateFiles(contents, updateMode);
this.notifyNewProgram(this.delegate.getProgram());
}
}
function versionMapFromProgram(
program: ts.Program,
driver: ProgramDriver,
): Map<AbsoluteFsPath, string> | null {
if (driver.getSourceFileVersion === undefined) {
return null;
}
const versions = new Map<AbsoluteFsPath, string>();
for (const possiblyRedirectedSourceFile of program.getSourceFiles()) {
const sf = toUnredirectedSourceFile(possiblyRedirectedSourceFile);
versions.set(absoluteFromSourceFile(sf), driver.getSourceFileVersion(sf));
}
return versions;
} | {
"end_byte": 68364,
"start_byte": 63077,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/core/src/compiler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/incremental/api.ts_0_2046 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of 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';
/**
* Interface of the incremental build engine.
*
* `AnalysisT` is a generic type representing a unit of work. This is generic to avoid a cyclic
* dependency between the incremental engine API definition and its consumer(s).
* `FileTypeCheckDataT` is a generic type representing template type-checking data for a particular
* input file, which is generic for the same reason.
*/
export interface IncrementalBuild<AnalysisT, FileTypeCheckDataT> {
/**
* Retrieve the prior analysis work, if any, done for the given source file.
*/
priorAnalysisFor(sf: ts.SourceFile): AnalysisT[] | null;
/**
* Retrieve the prior type-checking work, if any, that's been done for the given source file.
*/
priorTypeCheckingResultsFor(fileSf: ts.SourceFile): FileTypeCheckDataT | null;
/**
* Reports that template type-checking has completed successfully, with a map of type-checking
* data for each user file which can be reused in a future incremental iteration.
*/
recordSuccessfulTypeCheck(results: Map<AbsoluteFsPath, FileTypeCheckDataT>): void;
}
/**
* Tracks dependencies between source files or resources in the application.
*/
export interface DependencyTracker<T extends {fileName: string} = ts.SourceFile> {
/**
* Record that the file `from` depends on the file `on`.
*/
addDependency(from: T, on: T): void;
/**
* Record that the file `from` depends on the resource file `on`.
*/
addResourceDependency(from: T, on: AbsoluteFsPath): void;
/**
* Record that the given file contains unresolvable dependencies.
*
* In practice, this means that the dependency graph cannot provide insight into the effects of
* future changes on that file.
*/
recordDependencyAnalysisFailure(file: T): void;
}
| {
"end_byte": 2046,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/incremental/README.md_0_4835 | # Incremental Compilation
The `incremental` package contains logic related to incremental compilation in ngtsc. Its goal is to
ensure that the compiler's incremental performance is largely O(number of files changed in that
iteration) instead of O(size of the program as a whole), by allowing the compiler to optimize away
as much work as possible without sacrificing the correctness of its output.
An incremental compilation receives information about the prior compilation, including
its `ts.Program` and the result of ngtsc's analyses of each class in that program. Depending on the
nature of any changes made to files in the program between its prior and current versions, and on
the semantic effect of those changes, ngtsc may perform 3 different optimizations as it processes
the new build:
* It can reuse analysis work performed in the previous program
ngtsc receives the analyses of all decorated classes performed as part of the previous compilation,
and can reuse that work for a class if it can prove that the results are not stale.
* It can skip emitting a file
Emitting a file is a very expensive operation in TypeScript, involving the execution of many
internal TS transforms (downleveling, module system, etc) as well as the synthesis of a large text
buffer for the final JS output. Skipping emit of a file is the most effective optimizations ngtsc
can do. It's also one of the most challenging. Even if ngtsc's _analysis_ of a specific file is not
stale, that file may still need to be re-emitted if other changes in the program impact its
semantics. For example, a change to a component selector affects other components which use that
selector in their templates, even though no direct dependency exists between them.
* It can reuse template type-checking code
Template type-checking code is generated using semantic information extracted from the user's
program. This generation can be expensive, and ngtsc attempts to reuse previous results as much as
possible. This optimization can be thought of as a special case of the above re-emit optimization,
since template type-checking code is a particular flavor of "emit" for a component.
Due to the way that template type-checking works (creation of a second `ts.Program`
with `.ngtypecheck` files containing template type-checking blocks, or TCBs), reuse of template
type-checking code is critical for good performance. Not only is generation of these TCBs expensive,
but forcing TypeScript to re-parse and re-analyze every `.ngtypecheck` file on each incremental
change would be costly as well.
The `incremental` package is dedicated to allowing ngtsc to make these important optimizations
safely.
During an incremental compilation, the compiler begins with a process called "reconciliation",
focused on understanding the differences between the incoming, new `ts.Program` and the
last `ts.Program`. In TypeScript, an unchanged file will have its `ts.SourceFile` AST completely
reused. Reconciliation therefore examines the `ts.SourceFile`s of both the old and new programs, and
identifies files which have been added, removed, or changed. This information feeds in to the rest
of the incremental compilation process.
## Reuse of analysis results
Angular's process of understanding an individual component, directive, or other decorated class is
known as "analysis". Analysis is always performed on a class-by-class basis, so the analysis of a
component only takes into consideration information present in the `@Component` decorator, and not
for example in the `@NgModule` which declares the component.
However, analysis _can_ depend on information outside of the decorated class's file. This can happen
in two ways:
* External resources, such as templates or stylesheets, are covered by analysis.
* The partial evaluation of expressions within a class's metadata may descend into symbols imported
from other files.
For example, a directive's selector may be determined via an imported constant:
```typescript
import {Directive} from '@angular/core';
import {DIR_SELECTOR} from './selectors';
@Directive({
selector: DIR_SELECTOR,
})
export class Dir {}
```
The analysis of this directive _depends on_ the value of `DIR_SELECTOR` from `selectors.ts`.
Consequently, if `selectors.ts` changes, `Dir` needs to be re-analyzed, even if `dir.ts` has not
changed.
The `incremental` system provides a mechanism which tracks such dependencies at the file level. The
partial evaluation system records dependencies for any given evaluation operation when an import
boundary is crossed, building up a file-to-file dependency graph. This graph is then transmitted to
the next incremental compilation, where it can be used to determine, based on the set of files
physically changed on disk, which files have _logically_ changed and need to be re-analyzed.
| {
"end_byte": 4835,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/README.md"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.