Previously, if a matching rootDir ended with a slash then the path
returned from `logicalPathOfFile()` would not start with a slash,
which is inconsistent.
PR Close#29627
The defineInjector function specifies its providers and imports array to
be optional, so if no providers/imports are present these keys may be
omitted. This commit updates the compiler to only generate the keys when
necessary.
PR Close#29598
Prior to this change, a module's imports and exports would be used verbatim
as an injectors' imports. This is detrimental for tree-shaking, as a
module's exports could reference declarations that would then prevent such
declarations from being eligible for tree-shaking.
Since an injector actually only needs NgModule references as its imports,
we may safely filter out any declarations from the list of module exports.
This makes them eligible for tree-shaking once again.
PR Close#29598
Prior to this change, all module metadata would be included in the
`defineNgModule` call that is set as the `ngModuleDef` field of module
types. Part of the metadata is scope information like declarations,
imports and exports that is used for computing the transitive module
scope in JIT environments, preventing those references from being
tree-shaken for production builds.
This change moves the metadata for scope computations to a pure function
call that patches the scope references onto the module type. Because the
function is marked pure, it may be tree-shaken out during production builds
such that references to declarations and exports are dropped, which in turn
allows for tree-shaken any declaration that is not otherwise referenced.
Fixes#28077, FW-1035
PR Close#29598
In ES2015, classes could have been emitted as a variable declaration
initialized with a class expression. In certain situations, an intermediary
variable suffixed with `_1` is present such that the variable
declaration's initializer becomes a binary expression with its rhs being
the class expression, and its lhs being the identifier of the intermediate
variable. This structure was not recognized, resulting in such classes not
being considered as a class in `Esm2015ReflectionHost`.
As a consequence, the analysis of functions/methods that return a
`ModuleWithProviders` object did not take the methods of such classes into
account.
Another edge-case with such intermediate variable was that static
properties would not be considered as class members. A testcase was added
to prevent regressions.
Fixes#29078
PR Close#29119
Currently there is no support in ngtsc for imports of the form:
```
import * as core from `@angular/core`
export function forRoot(): core.ModuleWithProviders;
```
This commit modifies the `ReflectionHost.getImportOfIdentifier(id)`
method, so that it supports this kind of return type.
PR Close#27675
This commit introduces a mechanism for incremental compilation to the ngtsc
compiler.
Previously, incremental information was used in the construction of the
ts.Program for subsequent compilations, but was not used in ngtsc itself.
This commit adds an IncrementalState class, which tracks state between ngtsc
compilations. Currently, this supports skipping the TypeScript emit step
when the compiler can prove the contents of emit have not changed.
This is implemented for @Injectables as well as for files which don't
contain any Angular decorated types. These are the only files which can be
proven to be safe today.
See ngtsc/incremental/README.md for more details.
PR Close#29380
This commit adds support for compiling the same program repeatedly in a way
that's similar to how incremental builds work in a tool such as the CLI.
* support is added to the compiler entrypoint for reuse of the Program
object between compilations. This is the basis of the compiler's
incremental compilation model.
* support is added to wrap the CompilerHost the compiler creates and cache
ts.SourceFiles in between compilations.
* support is added to track when files are emitted, for assertion purposes.
* an 'exclude' section is added to the base tsconfig to prevent .d.ts
outputs from the first compilation from becoming inputs to any subsequent
compilations.
PR Close#29380
This commit adds a `tracePerformance` option for tsconfig.json. When
specified, it causes a JSON file with timing information from the ngtsc
compiler to be emitted at the specified path.
This tracing system is used to instrument the analysis/emit phases of
compilation, and will be useful in debugging future integration work with
@angular/cli.
See ngtsc/perf/README.md for more details.
PR Close#29380
Currently, ngtsc decides to use remote scoping if the compilation of a
component may create a cyclic import. This happens if there are two
components in a scope (say, A and B) and A directly uses B. During
compilation of B ngtsc will then note that if B were to use A, a cycle would
be generated, and so it will opt to use remote scoping for B.
ngtsc already uses the R3TargetBinder to correctly track the imports that
are actually required, for future cycle tracking. This commit expands that
usage to not trigger remote scoping unless B actually does consume A in its
template.
PR Close#29404
Currently when building an Angular project with `ngtsc`
and `flatModuleOutFile` enabled, the Ngtsc build will fail
if there are multiple source files as root file names.
Ngtsc and NGC currently determine the entry-point for multiple
root file names by looking for files ending with `/index.ts`.
This functionality is technically deprecated, but still supported
and currently breaks on Windows as the root file names are not
guaranteed to be normalized POSIX-like paths.
In order to make this logic more reliable in the future, this commit
also switches the shim generators and entry-point logic to the branded
path types. This ensures that we don't break this in the future.
PR Close#29453
Previously, several `ngtsc` and `ngcc` APIs dealing with class
declaration nodes used inconsistent types. For example, some methods of
the `DecoratorHandler` interface expected a `ts.Declaration` argument,
but actual `DecoratorHandler` implementations specified a stricter
`ts.ClassDeclaration` type.
As a result, the stricter methods would operate under the incorrect
assumption that their arguments were of type `ts.ClassDeclaration`,
while the actual arguments might be of different types (e.g. `ngcc`
would call them with `ts.FunctionDeclaration` or
`ts.VariableDeclaration` arguments, when compiling ES5 code).
Additionally, since we need those class declarations to be referenced in
other parts of the program, `ngtsc`/`ngcc` had to either repeatedly
check for `ts.isIdentifier(node.name)` or assume there was a `name`
identifier and use `node.name!`. While this assumption happens to be
true in the current implementation, working around type-checking is
error-prone (e.g. the assumption might stop being true in the future).
This commit fixes this by introducing a new type to be used for such
class declarations (`ts.Declaration & {name: ts.Identifier}`) and using
it consistently throughput the code.
PR Close#29209
Previously, only directives and services with generic type parameters
would emit `any` as generic type when emitting Ivy metadata into .d.ts
files. Pipes can also have generic type parameters but did not emit
`any` for all type parameters, resulting in the omission of those
parameters which causes compilation errors.
This commit adds support for pipes with generic type arguments and emits
`any` as generic type in the Ivy metadata.
Fixes#29400
PR Close#29403
Previously we only compiled the typings files, in ngcc, if there was
an ES2015 formatted bundle avaiable. This turns out to be an artificial
constraint and we can also support typings compilation via ES5 formats
too.
This commit changes the ngcc compiler to attempt typings compilation
via ES5 if necessary. The order of the formats to consider is now:
FESM2015, FESM5, ESM2015, ESM5.
FW-1122
PR Close#29092
This fix is for a bug in the ngtsc PartialEvaluator, which statically
evaluates expressions.
Sometimes, evaluating a reference requires resolving a function which is
declared in another module, and thus no function body is available. To
support this case, the PartialEvaluator has the concept of a foreign
function resolver.
This allows the interpretation of expressions like:
const router = RouterModule.forRoot([]);
even though the definition of the 'forRoot' function has no body. In
ngtsc today, this will be resolved to a Reference to RouterModule itself,
via the ModuleWithProviders foreign function resolver.
However, the PartialEvaluator also associates any Identifiers in the path
of this resolution with the Reference. This is done so that if the user
writes
const x = imported.y;
'x' can be generated as a local identifier instead of adding an import for
'y'.
This was at the heart of a bug. In the above case with 'router', the
PartialEvaluator added the identifier 'router' to the Reference generated
(through FFR) to RouterModule.
This is not correct. References that result from FFR expressions may not
have the same value at runtime as they do at compile time (indeed, this is
not the case for ModuleWithProviders). The Reference generated via FFR is
"synthetic" in the sense that it's constructed based on a useful
interpretation of the code, not an accurate representation of the runtime
value. Therefore, it may not be legal to refer to the Reference via the
'router' identifier.
This commit adds the ability to mark such a Reference as 'synthetic', which
allows the PartialEvaluator to not add the 'router' identifier down the
line. Tests are included for both the PartialEvaluator itself as well as the
resultant buggy behavior in ngtsc overall.
PR Close#29387
The `resolve` phase (run after all handlers have analyzed) was
introduced in 7d954dffd, but `ngcc` was not updated to run the handlers'
`resolve()` methods. As a result, certain operations (such as listing
directives used in component templates) would not be performed by
`ngcc`.
This commit fixes it by running the `resolve()` methods once analysis
has been completed.
PR Close#28963
Currently if an Angular library has multiple unnamed module re-exports, NGC will
generate incorrect metdata if the project is using the flat-module bundle option.
e.g.
_public-api.ts_
```ts
export * from '@mypkg/secondary1';
export * from '@mypkg/secondary2';
```
There are clearly two unnamed re-exports in the `public-api.ts` file. NGC right now
accidentally overwrites all previous re-exports with the last one. Resulting in the
generated metadata only containing a reference to `@mypkg/secondary2`.
This is problematic as it is common for primary library entry-points to have
multiple re-exports (e.g. Material re-exporting all public symbols; or flex-layout
exporting all public symbols from their secondary entry-points).
Currently Angular Material works around this issue by manually creating
a metadata file that declares the re-exports from all unnamed re-exports.
(see: https://github.com/angular/material2/blob/master/tools/package-tools/build-release.ts#L78-L85)
This workaround works fine currently, but is no longer easily integrated when
building the package output with Bazel. In order to be able to build such
libraries with Bazel (Material/flex-layout), we need to make sure that NGC
generates the proper flat-module metadata bundle.
PR Close#29360
Previously, ngtsc would resolve forward references while evaluating the
bootstrap, declaration, imports, and exports fields of NgModule types.
However, when generating the resulting ngModuleDef, the forward nature of
these references was not taken into consideration, and so the generated JS
code would incorrectly reference types not yet declared.
This commit fixes this issue by introducing function closures in the
NgModuleDef type, similarly to how NgComponentDef uses them for forward
declarations of its directives and pipes arrays. ngtsc will then generate
closures when required, and the runtime will unwrap them if present.
PR Close#29198
This fixes an issue with commit b6f6b117. In this commit, default imports
processed in a type-to-value conversion were recorded as non-local imports
with a '*' name, and the ImportManager generated a new default import for
them. When transpiled to ES2015 modules, this resulted in the following
correct code:
import i3 from './module';
// somewhere in the file, a value reference of i3:
{type: i3}
However, when the AST with this synthetic import and reference was
transpiled to non-ES2015 modules (for example, to commonjs) an issue
appeared:
var module_1 = require('./module');
{type: i3}
TypeScript renames the imported identifier from i3 to module_1, but doesn't
substitute later references to i3. This is because the import and reference
are both synthetic, and never went through the TypeScript AST step of
"binding" which associates the reference to its import. This association is
important during emit when the identifiers might change.
Synthetic (transformer-added) imports will never be bound properly. The only
possible solution is to reuse the user's original import and the identifier
from it, which will be properly downleveled. The issue with this approach
(which prompted the fix in b6f6b117) is that if the import is only used in a
type position, TypeScript will mark it for deletion in the generated JS,
even though additional non-type usages are added in the transformer. This
again would leave a dangling import.
To work around this, it's necessary for the compiler to keep track of
identifiers that it emits which came from default imports, and tell TS not
to remove those imports during transpilation. A `DefaultImportTracker` class
is implemented to perform this tracking. It implements a
`DefaultImportRecorder` interface, which is used to record two significant
pieces of information:
* when a WrappedNodeExpr is generated which refers to a default imported
value, the ts.Identifier is associated to the ts.ImportDeclaration via
the recorder.
* when that WrappedNodeExpr is later emitted as part of the statement /
expression translators, the fact that the ts.Identifier was used is
also recorded.
Combined, this tracking gives the `DefaultImportTracker` enough information
to implement another TS transformer, which can recognize default imports
which were used in the output of the Ivy transform and can prevent them
from being elided. This is done by creating a new ts.ImportDeclaration for
the imports with the same ts.ImportClause. A test verifies that this works.
PR Close#29266
Prior to this change default selector for Components was not applied in case selector is missing or defined as an empty string. This update aligns this behavior between Ivy and VE: now default selector is used for Components when it's needed. Directives with empty selector are not allowed and trigger a compile-time error in both Ivy and VE.
PR Close#29239
Prior to this change the code didn't take into account the fact that decorators can be aliases while importing into a script. As a result, these decorators were not recognized by Angular and various failures happened because of that. Now we take aliases into account and resolve decorator name properly.
PR Close#29195
`getCurrentDirectory` directory doesn't return a posix separated normalized path. While `rootDir` and `rootDirs` should return posix separated paths, it's best to not assume as other paths within the compiler options can be returned not posix separated such as `basePath`
See: https://github.com/Microsoft/TypeScript/blob/master/src/compiler/sys.ts#L635
This partially fixes#29140, however there needs to be a change in the CLI as well to handle this, as at the moment we are leaking devkit paths which is not correct.
Fixes#29140
PR Close#29151
Sometimes declarations are not exported publicly but are exported under
a private name. In this case, rather than adding a completely new
export to the entry point, we should create an export that aliases the
private name back to the original public name.
This is important when the typings files have been rolled-up using a tool
such as the [API Extractor](https://api-extractor.com/). In this case
the internal type of an aliased private export will be removed completely
from the typings file, so there is no "original" type to re-export.
For example:
If there are the following TS files:
**entry-point.ts**
```ts
export {Internal as External} from './internal';
```
**internal.ts**
```ts
export class Internal {
foo(): void;
}
```
Then the API Extractor might roll up the .d.ts files into:
```ts
export declare class External {
foo(): void;
}
```
In this case ngcc should add an export so the file looks like:
```ts
export declare class External {
foo(): void;
}
export {External as Internal};
```
PR Close#28735
ngsummary files were generated with an export for each class declaration.
However, some Angular code declares classes (class Foo) and exports them
(export {Foo}) separately, which was causing incomplete summary files.
This commit expands the set of symbol names for which summary exports will
be generated, fixing this issue.
PR Close#29193
Previously, when the NgModule scope resolver discovered semantic errors
within a users NgModules, it would throw assertion errors. TODOs in the
codebase indicated these should become ts.Diagnostics eventually.
Besides producing better-looking errors, there is another reason to make
this change asap: these assertions were shadowing actual errors, via an
interesting mechanism:
1) a component would produce a ts.Diagnostic during its analyze() step
2) as a result, it wouldn't register component metadata with the scope
resolver
3) the NgModule for the component references it in exports, which was
detected as an invalid export (no metadata registering it as a
component).
4) the resulting assertion error would crash the compiler, hiding the
real cause of the problem (an invalid component).
This commit should mitigate this problem by converting scoping errors to
proper ts.Diagnostics. Additionally, we should consider registering some
marker indicating a class is a directive/component/pipe without actually
requiring full metadata to be produced for it, which would allow suppression
of errors like "invalid export" for such invalid types.
PR Close#29191
This commit refactors and expands ngtsc's support for generating imports of
values from imports of types (this is used for example when importing a
class referenced in a type annotation in a constructor).
Previously, this logic handled "import {Foo} from" and "import * as foo
from" style imports, but failed on imports of default values ("import
Foo from"). This commit moves the type-to-value logic to a separate file and
expands it to cover the default import case. Doing this also required
augmenting the ImportManager to track default as well as non-default import
generation. The APIs were made a little cleaner at the same time.
PR Close#29146
In the TypeScript compiler API, emit() can be performed either on a single
ts.SourceFile or on the entire ts.Program simultaneously.
ngtsc previously used whole-program emit, which was convenient to use while
spinning up the project but has a significant drawback: it causes a type
checking operation to occur for the whole program, including .d.ts files.
In large Bazel environments (such as Google's codebase), an ngtsc invocation
can have a few .ts files and thousands of .d.ts inputs. This unwanted type
checking is therefore a significant drain on performance.
This commit switches ngtsc to emit each .ts file individually, avoiding the
unwanted type checking.
PR Close#29147
When processing a JavaScript program, TS may come across a symbol that has
been imported from a TypeScript typings file.
In this case the compiler may pass the ReflectionHost a `prototype` symbol
as an export of the class.
This pseudo-member symbol has no declarations, which previously caused the
code in `Esm5ReflectionHost.reflectMembers()` to crash.
Now we just quietly ignore such a symbol and leave `Esm2015ReflectionHost`
to deal with it.
(As it happens `Esm2015ReflectionHost` also quietly ignores this symbol).
PR Close#29158
For the template type checking to work correctly, it needs to know
what attributes are bound to expressions or directives, which may
require expressions in the template to be evaluated in a different
scope.
In inline templates, there are attributes that are now marked as
"Template" attributes. We need to ensure that the template
type checking code looks at these "bound" attributes as well as the
"input" attributes.
PR Close#29041
ngtsc occasionally converts a type reference (such as the type of a
parameter in a constructor) to a value reference (argument to a
directiveInject call). TypeScript has a bad habit of sometimes removing
the import statement associated with this type reference, because it's a
type only import when it initially looks at the file.
A solution to this is to always add an import to refer to a type position
value that's imported, and not rely on the existing import.
PR Close#29111
When ngtsc generates a .ngfactory shim, it does so based on the contents of
an original file in the program. Occasionally these original files have
comments at the top which are load-bearing (e.g. they contain jsdoc
annotations which are significant to downstream bundling tools). The
generated factory shims should preserve this comment.
This commit adds a step to the ngfactory generator to preserve the top-level
comment from the original source file.
FW-1006 #resolve
FW-1095 #resolve
PR Close#29065