style(ngcc): reformat of ngcc after clang update (#36447)
PR Close #36447
This commit is contained in:

committed by
Kara Erickson

parent
c8bef1259c
commit
8be8466a00
@ -12,7 +12,7 @@ import {ParsedConfiguration} from '../../..';
|
||||
import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, PipeDecoratorHandler, ReferencesRegistry, ResourceLoader} from '../../../src/ngtsc/annotations';
|
||||
import {CycleAnalyzer, ImportGraph} from '../../../src/ngtsc/cycles';
|
||||
import {isFatalDiagnosticError} from '../../../src/ngtsc/diagnostics';
|
||||
import {FileSystem, LogicalFileSystem, absoluteFrom, dirname, resolve} from '../../../src/ngtsc/file_system';
|
||||
import {absoluteFrom, dirname, FileSystem, LogicalFileSystem, resolve} from '../../../src/ngtsc/file_system';
|
||||
import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NOOP_DEFAULT_IMPORT_RECORDER, PrivateExportAliasingHost, Reexport, ReferenceEmitter} from '../../../src/ngtsc/imports';
|
||||
import {CompoundMetadataReader, CompoundMetadataRegistry, DtsMetadataReader, InjectableClassRegistry, LocalMetadataRegistry} from '../../../src/ngtsc/metadata';
|
||||
import {PartialEvaluator} from '../../../src/ngtsc/partial_evaluator';
|
||||
@ -28,7 +28,7 @@ import {EntryPointBundle} from '../packages/entry_point_bundle';
|
||||
import {DefaultMigrationHost} from './migration_host';
|
||||
import {NgccTraitCompiler} from './ngcc_trait_compiler';
|
||||
import {CompiledClass, CompiledFile, DecorationAnalyses} from './types';
|
||||
import {NOOP_DEPENDENCY_TRACKER, isWithinPackage} from './util';
|
||||
import {isWithinPackage, NOOP_DEPENDENCY_TRACKER} from './util';
|
||||
|
||||
|
||||
|
||||
@ -38,8 +38,12 @@ import {NOOP_DEPENDENCY_TRACKER, isWithinPackage} from './util';
|
||||
class NgccResourceLoader implements ResourceLoader {
|
||||
constructor(private fs: FileSystem) {}
|
||||
canPreload = false;
|
||||
preload(): undefined|Promise<void> { throw new Error('Not implemented.'); }
|
||||
load(url: string): string { return this.fs.readFile(resolve(url)); }
|
||||
preload(): undefined|Promise<void> {
|
||||
throw new Error('Not implemented.');
|
||||
}
|
||||
load(url: string): string {
|
||||
return this.fs.readFile(resolve(url));
|
||||
}
|
||||
resolve(url: string, containingFile: string): string {
|
||||
return resolve(dirname(absoluteFrom(containingFile)), url);
|
||||
}
|
||||
@ -56,7 +60,7 @@ export class DecorationAnalyzer {
|
||||
private rootDirs = this.bundle.rootDirs;
|
||||
private packagePath = this.bundle.entryPoint.package;
|
||||
private isCore = this.bundle.isCore;
|
||||
private compilerOptions = this.tsConfig !== null? this.tsConfig.options: {};
|
||||
private compilerOptions = this.tsConfig !== null ? this.tsConfig.options : {};
|
||||
|
||||
moduleResolver =
|
||||
new ModuleResolver(this.program, this.options, this.host, /* moduleResolutionCache */ null);
|
||||
@ -73,8 +77,9 @@ export class DecorationAnalyzer {
|
||||
// based on whether a bestGuessOwningModule is present in the Reference.
|
||||
new LogicalProjectStrategy(this.reflectionHost, new LogicalFileSystem(this.rootDirs)),
|
||||
]);
|
||||
aliasingHost = this.bundle.entryPoint.generateDeepReexports?
|
||||
new PrivateExportAliasingHost(this.reflectionHost): null;
|
||||
aliasingHost = this.bundle.entryPoint.generateDeepReexports ?
|
||||
new PrivateExportAliasingHost(this.reflectionHost) :
|
||||
null;
|
||||
dtsModuleScopeResolver =
|
||||
new MetadataDtsModuleScopeResolver(this.dtsMetaReader, this.aliasingHost);
|
||||
scopeRegistry = new LocalModuleScopeRegistry(
|
||||
@ -191,7 +196,9 @@ export class DecorationAnalyzer {
|
||||
});
|
||||
}
|
||||
|
||||
protected reportDiagnostics() { this.compiler.diagnostics.forEach(this.diagnosticHandler); }
|
||||
protected reportDiagnostics() {
|
||||
this.compiler.diagnostics.forEach(this.diagnosticHandler);
|
||||
}
|
||||
|
||||
protected compileFile(sourceFile: ts.SourceFile): CompiledFile {
|
||||
const constantPool = new ConstantPool();
|
||||
@ -211,7 +218,8 @@ export class DecorationAnalyzer {
|
||||
compiledClasses.push({
|
||||
name: record.node.name.text,
|
||||
decorators: this.compiler.getAllDecorators(record.node),
|
||||
declaration: record.node, compilation
|
||||
declaration: record.node,
|
||||
compilation
|
||||
});
|
||||
}
|
||||
|
||||
@ -224,7 +232,7 @@ export class DecorationAnalyzer {
|
||||
if (!exportStatements.has(sf.fileName)) {
|
||||
return [];
|
||||
}
|
||||
const exports = exportStatements.get(sf.fileName) !;
|
||||
const exports = exportStatements.get(sf.fileName)!;
|
||||
|
||||
const reexports: Reexport[] = [];
|
||||
exports.forEach(([fromModule, symbolName], asAlias) => {
|
||||
|
@ -75,10 +75,9 @@ export class ModuleWithProvidersAnalyzer {
|
||||
const dtsClass = this.host.getDtsDeclaration(containerClass.declaration.valueDeclaration);
|
||||
// Get the declaration of the matching static method
|
||||
dtsFn = dtsClass && ts.isClassDeclaration(dtsClass) ?
|
||||
dtsClass.members
|
||||
.find(
|
||||
member => ts.isMethodDeclaration(member) && ts.isIdentifier(member.name) &&
|
||||
member.name.text === fn.name) as ts.Declaration :
|
||||
dtsClass.members.find(
|
||||
member => ts.isMethodDeclaration(member) && ts.isIdentifier(member.name) &&
|
||||
member.name.text === fn.name) as ts.Declaration :
|
||||
null;
|
||||
} else {
|
||||
dtsFn = this.host.getDtsDeclaration(fn.declaration);
|
||||
@ -87,8 +86,8 @@ export class ModuleWithProvidersAnalyzer {
|
||||
throw new Error(`Matching type declaration for ${fn.declaration.getText()} is missing`);
|
||||
}
|
||||
if (!isFunctionOrMethod(dtsFn)) {
|
||||
throw new Error(
|
||||
`Matching type declaration for ${fn.declaration.getText()} is not a function: ${dtsFn.getText()}`);
|
||||
throw new Error(`Matching type declaration for ${
|
||||
fn.declaration.getText()} is not a function: ${dtsFn.getText()}`);
|
||||
}
|
||||
return dtsFn;
|
||||
}
|
||||
@ -106,12 +105,14 @@ export class ModuleWithProvidersAnalyzer {
|
||||
// to its type declaration.
|
||||
const dtsNgModule = this.host.getDtsDeclaration(ngModule.node);
|
||||
if (!dtsNgModule) {
|
||||
throw new Error(
|
||||
`No typings declaration can be found for the referenced NgModule class in ${fn.declaration.getText()}.`);
|
||||
throw new Error(`No typings declaration can be found for the referenced NgModule class in ${
|
||||
fn.declaration.getText()}.`);
|
||||
}
|
||||
if (!ts.isClassDeclaration(dtsNgModule) || !hasNameIdentifier(dtsNgModule)) {
|
||||
throw new Error(
|
||||
`The referenced NgModule in ${fn.declaration.getText()} is not a named class declaration in the typings program; instead we get ${dtsNgModule.getText()}`);
|
||||
throw new Error(`The referenced NgModule in ${
|
||||
fn.declaration
|
||||
.getText()} is not a named class declaration in the typings program; instead we get ${
|
||||
dtsNgModule.getText()}`);
|
||||
}
|
||||
|
||||
return {node: dtsNgModule, known: null, viaModule: null};
|
||||
|
@ -45,5 +45,7 @@ export class NgccReferencesRegistry implements ReferencesRegistry {
|
||||
* Create and return a mapping for the registered resolved references.
|
||||
* @returns A map of reference identifiers to reference declarations.
|
||||
*/
|
||||
getDeclarationMap(): Map<ts.Identifier, ConcreteDeclaration> { return this.map; }
|
||||
getDeclarationMap(): Map<ts.Identifier, ConcreteDeclaration> {
|
||||
return this.map;
|
||||
}
|
||||
}
|
||||
|
@ -29,7 +29,9 @@ export class NgccTraitCompiler extends TraitCompiler {
|
||||
/* compileNonExportedClasses */ true, new DtsTransformRegistry());
|
||||
}
|
||||
|
||||
get analyzedFiles(): ts.SourceFile[] { return Array.from(this.fileToClasses.keys()); }
|
||||
get analyzedFiles(): ts.SourceFile[] {
|
||||
return Array.from(this.fileToClasses.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyzes the source file in search for classes to process. For any class that is found in the
|
||||
@ -81,5 +83,7 @@ export class NgccTraitCompiler extends TraitCompiler {
|
||||
}
|
||||
|
||||
class NoIncrementalBuild implements IncrementalBuild<any> {
|
||||
priorWorkFor(sf: ts.SourceFile): any[]|null { return null; }
|
||||
priorWorkFor(sf: ts.SourceFile): any[]|null {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@ -7,10 +7,11 @@
|
||||
*/
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {AbsoluteFsPath, absoluteFromSourceFile} from '../../../src/ngtsc/file_system';
|
||||
import {absoluteFromSourceFile, AbsoluteFsPath} from '../../../src/ngtsc/file_system';
|
||||
import {ConcreteDeclaration} from '../../../src/ngtsc/reflection';
|
||||
import {NgccReflectionHost} from '../host/ngcc_host';
|
||||
import {hasNameIdentifier, isDefined} from '../utils';
|
||||
|
||||
import {NgccReferencesRegistry} from './ngcc_references_registry';
|
||||
|
||||
export interface ExportInfo {
|
||||
@ -48,7 +49,7 @@ export class PrivateDeclarationsAnalyzer {
|
||||
exports.forEach((declaration, exportedName) => {
|
||||
if (declaration.node !== null && hasNameIdentifier(declaration.node)) {
|
||||
if (privateDeclarations.has(declaration.node.name)) {
|
||||
const privateDeclaration = privateDeclarations.get(declaration.node.name) !;
|
||||
const privateDeclaration = privateDeclarations.get(declaration.node.name)!;
|
||||
if (privateDeclaration.node !== declaration.node) {
|
||||
throw new Error(`${declaration.node.name.text} is declared multiple times.`);
|
||||
}
|
||||
@ -62,7 +63,7 @@ export class PrivateDeclarationsAnalyzer {
|
||||
|
||||
return Array.from(privateDeclarations.keys()).map(id => {
|
||||
const from = absoluteFromSourceFile(id.getSourceFile());
|
||||
const declaration = privateDeclarations.get(id) !;
|
||||
const declaration = privateDeclarations.get(id)!;
|
||||
const dtsDeclaration = this.host.getDtsDeclaration(declaration.node);
|
||||
const dtsFrom = dtsDeclaration && absoluteFromSourceFile(dtsDeclaration.getSourceFile());
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
*/
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {AbsoluteFsPath, absoluteFromSourceFile, relative} from '../../../src/ngtsc/file_system';
|
||||
import {absoluteFromSourceFile, AbsoluteFsPath, relative} from '../../../src/ngtsc/file_system';
|
||||
import {DependencyTracker} from '../../../src/ngtsc/incremental/api';
|
||||
|
||||
export function isWithinPackage(packagePath: AbsoluteFsPath, sourceFile: ts.SourceFile): boolean {
|
||||
|
@ -6,8 +6,10 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {AbsoluteFsPath} from '../../../src/ngtsc/file_system';
|
||||
import {RequireCall, isReexportStatement, isRequireCall} from '../host/commonjs_umd_utils';
|
||||
import {isReexportStatement, isRequireCall, RequireCall} from '../host/commonjs_umd_utils';
|
||||
|
||||
import {DependencyHostBase} from './dependency_host';
|
||||
import {ResolvedDeepImport, ResolvedRelativeModule} from './module_resolver';
|
||||
|
||||
@ -120,5 +122,7 @@ export class CommonJsDependencyHost extends DependencyHostBase {
|
||||
* @returns false if there are definitely no require calls
|
||||
* in this file, true otherwise.
|
||||
*/
|
||||
private hasRequireCalls(source: string): boolean { return /require\(['"]/.test(source); }
|
||||
private hasRequireCalls(source: string): boolean {
|
||||
return /require\(['"]/.test(source);
|
||||
}
|
||||
}
|
||||
|
@ -7,12 +7,14 @@
|
||||
*/
|
||||
|
||||
import {DepGraph} from 'dependency-graph';
|
||||
|
||||
import {AbsoluteFsPath, FileSystem, resolve} from '../../../src/ngtsc/file_system';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {NgccConfiguration} from '../packages/configuration';
|
||||
import {EntryPoint, EntryPointFormat, SUPPORTED_FORMAT_PROPERTIES, getEntryPointFormat} from '../packages/entry_point';
|
||||
import {EntryPoint, EntryPointFormat, getEntryPointFormat, SUPPORTED_FORMAT_PROPERTIES} from '../packages/entry_point';
|
||||
import {PartiallyOrderedList} from '../utils';
|
||||
import {DependencyHost, DependencyInfo, createDependencyInfo} from './dependency_host';
|
||||
|
||||
import {createDependencyInfo, DependencyHost, DependencyInfo} from './dependency_host';
|
||||
|
||||
const builtinNodeJsModules = new Set<string>(require('module').builtinModules);
|
||||
|
||||
@ -123,7 +125,8 @@ export class DependencyResolver {
|
||||
const host = this.hosts[formatInfo.format];
|
||||
if (!host) {
|
||||
throw new Error(
|
||||
`Could not find a suitable format for computing dependencies of entry-point: '${entryPoint.path}'.`);
|
||||
`Could not find a suitable format for computing dependencies of entry-point: '${
|
||||
entryPoint.path}'.`);
|
||||
}
|
||||
const depInfo = createDependencyInfo();
|
||||
host.collectDependencies(formatInfo.path, depInfo);
|
||||
|
@ -5,8 +5,8 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {AbsoluteFsPath, FileSystem, absoluteFrom, dirname, isRoot, join, resolve} from '../../../src/ngtsc/file_system';
|
||||
import {PathMappings, isRelativePath, resolveFileWithPostfixes} from '../utils';
|
||||
import {absoluteFrom, AbsoluteFsPath, dirname, FileSystem, isRoot, join, resolve} from '../../../src/ngtsc/file_system';
|
||||
import {isRelativePath, PathMappings, resolveFileWithPostfixes} from '../utils';
|
||||
|
||||
/**
|
||||
* This is a very cut-down implementation of the TypeScript module resolution strategy.
|
||||
@ -222,7 +222,7 @@ export class ModuleResolver {
|
||||
}
|
||||
|
||||
/** The result of resolving an import to a module. */
|
||||
export type ResolvedModule = ResolvedExternalModule | ResolvedRelativeModule | ResolvedDeepImport;
|
||||
export type ResolvedModule = ResolvedExternalModule|ResolvedRelativeModule|ResolvedDeepImport;
|
||||
|
||||
/**
|
||||
* A module that is external to the package doing the importing.
|
||||
|
@ -84,5 +84,7 @@ export class UmdDependencyHost extends DependencyHostBase {
|
||||
* @returns false if there are definitely no require calls
|
||||
* in this file, true otherwise.
|
||||
*/
|
||||
private hasRequireCalls(source: string): boolean { return /require\(['"]/.test(source); }
|
||||
private hasRequireCalls(source: string): boolean {
|
||||
return /require\(['"]/.test(source);
|
||||
}
|
||||
}
|
||||
|
@ -9,10 +9,11 @@ import {AbsoluteFsPath, FileSystem, PathSegment} from '../../../src/ngtsc/file_s
|
||||
import {DependencyResolver, SortedEntryPointsInfo} from '../dependencies/dependency_resolver';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {NgccConfiguration} from '../packages/configuration';
|
||||
import {EntryPoint, INCOMPATIBLE_ENTRY_POINT, NO_ENTRY_POINT, getEntryPointInfo} from '../packages/entry_point';
|
||||
import {EntryPoint, getEntryPointInfo, INCOMPATIBLE_ENTRY_POINT, NO_ENTRY_POINT} from '../packages/entry_point';
|
||||
import {EntryPointManifest} from '../packages/entry_point_manifest';
|
||||
import {PathMappings} from '../utils';
|
||||
import {NGCC_DIRECTORY} from '../writing/new_entry_point_file_writer';
|
||||
|
||||
import {EntryPointFinder} from './interface';
|
||||
import {getBasePaths, trackDuration} from './utils';
|
||||
|
||||
|
@ -5,13 +5,14 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {AbsoluteFsPath, FileSystem, PathSegment, join, relative, relativeFrom} from '../../../src/ngtsc/file_system';
|
||||
import {AbsoluteFsPath, FileSystem, join, PathSegment, relative, relativeFrom} from '../../../src/ngtsc/file_system';
|
||||
import {DependencyResolver, SortedEntryPointsInfo} from '../dependencies/dependency_resolver';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {hasBeenProcessed} from '../packages/build_marker';
|
||||
import {NgccConfiguration} from '../packages/configuration';
|
||||
import {EntryPoint, EntryPointJsonProperty, INCOMPATIBLE_ENTRY_POINT, NO_ENTRY_POINT, getEntryPointInfo} from '../packages/entry_point';
|
||||
import {EntryPoint, EntryPointJsonProperty, getEntryPointInfo, INCOMPATIBLE_ENTRY_POINT, NO_ENTRY_POINT} from '../packages/entry_point';
|
||||
import {PathMappings} from '../utils';
|
||||
|
||||
import {EntryPointFinder} from './interface';
|
||||
import {getBasePaths} from './utils';
|
||||
|
||||
@ -76,7 +77,7 @@ export class TargetedEntryPointFinder implements EntryPointFinder {
|
||||
}
|
||||
|
||||
private processNextPath(): void {
|
||||
const path = this.unprocessedPaths.shift() !;
|
||||
const path = this.unprocessedPaths.shift()!;
|
||||
const entryPoint = this.getEntryPoint(path);
|
||||
if (entryPoint === null || !entryPoint.compiledByAngular) {
|
||||
return;
|
||||
@ -130,7 +131,7 @@ export class TargetedEntryPointFinder implements EntryPointFinder {
|
||||
// Start the search at the deepest nested `node_modules` folder that is below the `basePath`
|
||||
// but above the `entryPointPath`, if there are any.
|
||||
while (nodeModulesIndex >= 0) {
|
||||
packagePath = join(packagePath, segments.shift() !);
|
||||
packagePath = join(packagePath, segments.shift()!);
|
||||
nodeModulesIndex--;
|
||||
}
|
||||
|
||||
|
@ -30,7 +30,7 @@ import {PathMappings} from '../utils';
|
||||
*/
|
||||
export function getBasePaths(
|
||||
logger: Logger, sourceDirectory: AbsoluteFsPath,
|
||||
pathMappings: PathMappings | undefined): AbsoluteFsPath[] {
|
||||
pathMappings: PathMappings|undefined): AbsoluteFsPath[] {
|
||||
const fs = getFileSystem();
|
||||
const basePaths = [sourceDirectory];
|
||||
if (pathMappings) {
|
||||
@ -51,7 +51,8 @@ export function getBasePaths(
|
||||
basePaths.push(basePath);
|
||||
} else {
|
||||
logger.warn(
|
||||
`The basePath "${basePath}" computed from baseUrl "${baseUrl}" and path mapping "${path}" does not exist in the file-system.\n` +
|
||||
`The basePath "${basePath}" computed from baseUrl "${baseUrl}" and path mapping "${
|
||||
path}" does not exist in the file-system.\n` +
|
||||
`It will not be scanned for entry-points.`);
|
||||
}
|
||||
}));
|
||||
@ -109,8 +110,8 @@ function removeContainedPaths(value: AbsoluteFsPath, index: number, array: Absol
|
||||
* @param log The function to call with the duration of the task
|
||||
* @returns The result of calling `task`.
|
||||
*/
|
||||
export function trackDuration<T = void>(
|
||||
task: () => T extends Promise<unknown>? never : T, log: (duration: number) => void): T {
|
||||
export function trackDuration<T = void>(task: () => T extends Promise<unknown>? never : T,
|
||||
log: (duration: number) => void): T {
|
||||
const startTime = Date.now();
|
||||
const result = task();
|
||||
const duration = Math.round((Date.now() - startTime) / 100) / 10;
|
||||
|
@ -44,7 +44,7 @@ export interface UpdatePackageJsonMessage extends JsonObject {
|
||||
}
|
||||
|
||||
/** The type of messages sent from cluster workers to the cluster master. */
|
||||
export type MessageFromWorker = ErrorMessage | TaskCompletedMessage | UpdatePackageJsonMessage;
|
||||
export type MessageFromWorker = ErrorMessage|TaskCompletedMessage|UpdatePackageJsonMessage;
|
||||
|
||||
/** The type of messages sent from the cluster master to cluster workers. */
|
||||
export type MessageToWorker = ProcessTaskMessage;
|
||||
|
@ -35,8 +35,8 @@ export class ClusterExecutor implements Executor {
|
||||
if (cluster.isMaster) {
|
||||
// This process is the cluster master.
|
||||
return this.lockFile.lock(() => {
|
||||
this.logger.debug(
|
||||
`Running ngcc on ${this.constructor.name} (using ${this.workerCount} worker processes).`);
|
||||
this.logger.debug(`Running ngcc on ${this.constructor.name} (using ${
|
||||
this.workerCount} worker processes).`);
|
||||
const master = new ClusterMaster(
|
||||
this.workerCount, this.logger, this.pkgJsonUpdater, analyzeEntryPoints,
|
||||
this.createTaskCompletedCallback);
|
||||
|
@ -262,7 +262,7 @@ export class ClusterMaster {
|
||||
*/
|
||||
private wrapEventHandler<Args extends unknown[]>(fn: (...args: Args) => void|Promise<void>):
|
||||
(...args: Args) => Promise<void> {
|
||||
return async(...args: Args) => {
|
||||
return async (...args: Args) => {
|
||||
try {
|
||||
await fn(...args);
|
||||
} catch (err) {
|
||||
|
@ -12,7 +12,7 @@ import * as cluster from 'cluster';
|
||||
|
||||
import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system';
|
||||
import {JsonObject} from '../../packages/entry_point';
|
||||
import {PackageJsonChange, PackageJsonUpdate, PackageJsonUpdater, applyChange} from '../../writing/package_json_updater';
|
||||
import {applyChange, PackageJsonChange, PackageJsonUpdate, PackageJsonUpdater} from '../../writing/package_json_updater';
|
||||
|
||||
import {sendMessageToMaster} from './utils';
|
||||
|
||||
|
@ -23,14 +23,14 @@ export class Deferred<T> {
|
||||
*
|
||||
* @param value The value to resolve the promise with.
|
||||
*/
|
||||
resolve !: (value: T) => void;
|
||||
resolve!: (value: T) => void;
|
||||
|
||||
/**
|
||||
* Rejects the associated promise with the specified reason.
|
||||
*
|
||||
* @param reason The rejection reason.
|
||||
*/
|
||||
reject !: (reason: any) => void;
|
||||
reject!: (reason: any) => void;
|
||||
|
||||
/** The `Promise` instance associated with this deferred. */
|
||||
promise = new Promise<T>((resolve, reject) => {
|
||||
|
@ -30,7 +30,7 @@ export abstract class SingleProcessorExecutorBase {
|
||||
const startTime = Date.now();
|
||||
|
||||
while (!taskQueue.allTasksCompleted) {
|
||||
const task = taskQueue.getNextTask() !;
|
||||
const task = taskQueue.getNextTask()!;
|
||||
compile(task);
|
||||
taskQueue.markTaskCompleted(task);
|
||||
}
|
||||
@ -65,6 +65,6 @@ export class SingleProcessExecutorAsync extends SingleProcessorExecutorBase impl
|
||||
}
|
||||
async execute(analyzeEntryPoints: AnalyzeEntryPointsFn, createCompileFn: CreateCompileFn):
|
||||
Promise<void> {
|
||||
await this.lockFile.lock(async() => this.doExecute(analyzeEntryPoints, createCompileFn));
|
||||
await this.lockFile.lock(async () => this.doExecute(analyzeEntryPoints, createCompileFn));
|
||||
}
|
||||
}
|
||||
|
@ -66,7 +66,7 @@ export type CreateTaskCompletedCallback = (taskQueue: TaskQueue) => TaskComplete
|
||||
* A function to be called once a task has been processed.
|
||||
*/
|
||||
export type TaskCompletedCallback =
|
||||
(task: Task, outcome: TaskProcessingOutcome, message: string | null) => void;
|
||||
(task: Task, outcome: TaskProcessingOutcome, message: string|null) => void;
|
||||
|
||||
/**
|
||||
* Represents the outcome of processing a `Task`.
|
||||
|
@ -8,8 +8,9 @@
|
||||
import {FileSystem, resolve} from '../../../../src/ngtsc/file_system';
|
||||
import {Logger} from '../../logging/logger';
|
||||
import {markAsProcessed} from '../../packages/build_marker';
|
||||
import {PackageJsonFormatProperties, getEntryPointFormat} from '../../packages/entry_point';
|
||||
import {getEntryPointFormat, PackageJsonFormatProperties} from '../../packages/entry_point';
|
||||
import {PackageJsonUpdater} from '../../writing/package_json_updater';
|
||||
|
||||
import {Task, TaskCompletedCallback, TaskProcessingOutcome, TaskQueue} from './api';
|
||||
|
||||
/**
|
||||
@ -18,7 +19,7 @@ import {Task, TaskCompletedCallback, TaskProcessingOutcome, TaskQueue} from './a
|
||||
* These functions can be composed using the `composeTaskCompletedCallbacks()`
|
||||
* to create a `TaskCompletedCallback` function that can be passed to an `Executor`.
|
||||
*/
|
||||
export type TaskCompletedHandler = (task: Task, message: string | null) => void;
|
||||
export type TaskCompletedHandler = (task: Task, message: string|null) => void;
|
||||
|
||||
/**
|
||||
* Compose a group of TaskCompletedHandlers into a single TaskCompletedCallback.
|
||||
@ -30,11 +31,11 @@ export type TaskCompletedHandler = (task: Task, message: string | null) => void;
|
||||
*/
|
||||
export function composeTaskCompletedCallbacks(
|
||||
callbacks: Record<TaskProcessingOutcome, TaskCompletedHandler>): TaskCompletedCallback {
|
||||
return (task: Task, outcome: TaskProcessingOutcome, message: string | null): void => {
|
||||
return (task: Task, outcome: TaskProcessingOutcome, message: string|null): void => {
|
||||
const callback = callbacks[outcome];
|
||||
if (callback === undefined) {
|
||||
throw new Error(
|
||||
`Unknown task outcome: "${outcome}" - supported outcomes: ${JSON.stringify(Object.keys(callbacks))}`);
|
||||
throw new Error(`Unknown task outcome: "${outcome}" - supported outcomes: ${
|
||||
JSON.stringify(Object.keys(callbacks))}`);
|
||||
}
|
||||
callback(task, message);
|
||||
};
|
||||
@ -64,10 +65,11 @@ export function createMarkAsProcessedHandler(pkgJsonUpdater: PackageJsonUpdater)
|
||||
* Create a handler that will throw an error.
|
||||
*/
|
||||
export function createThrowErrorHandler(fs: FileSystem): TaskCompletedHandler {
|
||||
return (task: Task, message: string | null): void => {
|
||||
return (task: Task, message: string|null): void => {
|
||||
const format = getEntryPointFormat(fs, task.entryPoint, task.formatProperty);
|
||||
throw new Error(
|
||||
`Failed to compile entry-point ${task.entryPoint.name} (${task.formatProperty} as ${format})` +
|
||||
`Failed to compile entry-point ${task.entryPoint.name} (${task.formatProperty} as ${
|
||||
format})` +
|
||||
(message !== null ? ` due to ${message}` : ''));
|
||||
};
|
||||
}
|
||||
@ -77,11 +79,12 @@ export function createThrowErrorHandler(fs: FileSystem): TaskCompletedHandler {
|
||||
*/
|
||||
export function createLogErrorHandler(
|
||||
logger: Logger, fs: FileSystem, taskQueue: TaskQueue): TaskCompletedHandler {
|
||||
return (task: Task, message: string | null): void => {
|
||||
return (task: Task, message: string|null): void => {
|
||||
taskQueue.markAsFailed(task);
|
||||
const format = getEntryPointFormat(fs, task.entryPoint, task.formatProperty);
|
||||
logger.error(
|
||||
`Failed to compile entry-point ${task.entryPoint.name} (${task.formatProperty} as ${format})` +
|
||||
`Failed to compile entry-point ${task.entryPoint.name} (${task.formatProperty} as ${
|
||||
format})` +
|
||||
(message !== null ? ` due to ${message}` : ''));
|
||||
};
|
||||
}
|
||||
|
@ -38,9 +38,9 @@ export abstract class BaseTaskQueue implements TaskQueue {
|
||||
}
|
||||
// We are skipping this task so mark it as complete
|
||||
this.markTaskCompleted(nextTask);
|
||||
const failedTask = this.tasksToSkip.get(nextTask) !;
|
||||
this.logger.warn(
|
||||
`Skipping processing of ${nextTask.entryPoint.name} because its dependency ${failedTask.entryPoint.name} failed to compile.`);
|
||||
const failedTask = this.tasksToSkip.get(nextTask)!;
|
||||
this.logger.warn(`Skipping processing of ${nextTask.entryPoint.name} because its dependency ${
|
||||
failedTask.entryPoint.name} failed to compile.`);
|
||||
nextTask = this.computeNextTask();
|
||||
}
|
||||
return nextTask;
|
||||
@ -48,7 +48,7 @@ export abstract class BaseTaskQueue implements TaskQueue {
|
||||
|
||||
markAsFailed(task: Task) {
|
||||
if (this.dependencies.has(task)) {
|
||||
for (const dependentTask of this.dependencies.get(task) !) {
|
||||
for (const dependentTask of this.dependencies.get(task)!) {
|
||||
this.skipDependentTasks(dependentTask, task);
|
||||
}
|
||||
}
|
||||
@ -81,7 +81,7 @@ export abstract class BaseTaskQueue implements TaskQueue {
|
||||
protected skipDependentTasks(task: Task, failedTask: Task) {
|
||||
this.tasksToSkip.set(task, failedTask);
|
||||
if (this.dependencies.has(task)) {
|
||||
for (const dependentTask of this.dependencies.get(task) !) {
|
||||
for (const dependentTask of this.dependencies.get(task)!) {
|
||||
this.skipDependentTasks(dependentTask, failedTask);
|
||||
}
|
||||
}
|
||||
|
@ -49,9 +49,9 @@ export class ParallelTaskQueue extends BaseTaskQueue {
|
||||
}
|
||||
|
||||
// Unblock the tasks that are dependent upon `task`
|
||||
for (const dependentTask of this.dependencies.get(task) !) {
|
||||
for (const dependentTask of this.dependencies.get(task)!) {
|
||||
if (this.blockedTasks.has(dependentTask)) {
|
||||
const blockingTasks = this.blockedTasks.get(dependentTask) !;
|
||||
const blockingTasks = this.blockedTasks.get(dependentTask)!;
|
||||
// Remove the completed task from the lists of tasks blocking other tasks.
|
||||
blockingTasks.delete(task);
|
||||
if (blockingTasks.size === 0) {
|
||||
|
@ -10,8 +10,8 @@ import {EntryPoint} from '../../packages/entry_point';
|
||||
import {PartiallyOrderedTasks, Task, TaskDependencies} from './api';
|
||||
|
||||
/** Stringify a task for debugging purposes. */
|
||||
export const stringifyTask = (task: Task): string =>
|
||||
`{entryPoint: ${task.entryPoint.name}, formatProperty: ${task.formatProperty}, processDts: ${task.processDts}}`;
|
||||
export const stringifyTask = (task: Task): string => `{entryPoint: ${
|
||||
task.entryPoint.name}, formatProperty: ${task.formatProperty}, processDts: ${task.processDts}}`;
|
||||
|
||||
/**
|
||||
* Compute a mapping of tasks to the tasks that are dependent on them (if any).
|
||||
@ -45,7 +45,7 @@ export function computeTaskDependencies(
|
||||
// Find the earlier tasks (`candidateDependencies`) that this task depends upon.
|
||||
const deps = graph.dependenciesOf(entryPointPath);
|
||||
const taskDependencies = deps.filter(dep => candidateDependencies.has(dep))
|
||||
.map(dep => candidateDependencies.get(dep) !);
|
||||
.map(dep => candidateDependencies.get(dep)!);
|
||||
|
||||
// If this task has dependencies, add it to the dependencies and dependents maps.
|
||||
if (taskDependencies.length > 0) {
|
||||
@ -61,7 +61,7 @@ export function computeTaskDependencies(
|
||||
// dependency of other tasks), so the following should theoretically never happen, but check
|
||||
// just in case.
|
||||
if (candidateDependencies.has(entryPointPath)) {
|
||||
const otherTask = candidateDependencies.get(entryPointPath) !;
|
||||
const otherTask = candidateDependencies.get(entryPointPath)!;
|
||||
throw new Error(
|
||||
'Invariant violated: Multiple tasks are assigned generating typings for ' +
|
||||
`'${entryPointPath}':\n - ${stringifyTask(otherTask)}\n - ${stringifyTask(task)}`);
|
||||
@ -73,7 +73,7 @@ export function computeTaskDependencies(
|
||||
// This task is not generating typings so we need to add it to the dependents of the task that
|
||||
// does generate typings, if that exists
|
||||
if (candidateDependencies.has(entryPointPath)) {
|
||||
const typingsTask = candidateDependencies.get(entryPointPath) !;
|
||||
const typingsTask = candidateDependencies.get(entryPointPath)!;
|
||||
const typingsTaskDependents = getDependentsSet(dependencies, typingsTask);
|
||||
typingsTaskDependents.add(task);
|
||||
}
|
||||
@ -87,7 +87,7 @@ export function getDependentsSet(map: TaskDependencies, task: Task): Set<Task> {
|
||||
if (!map.has(task)) {
|
||||
map.set(task, new Set());
|
||||
}
|
||||
return map.get(task) !;
|
||||
return map.get(task)!;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -125,13 +125,13 @@ export function sortTasksByPriority(
|
||||
tasks: PartiallyOrderedTasks, dependencies: TaskDependencies): PartiallyOrderedTasks {
|
||||
const priorityPerTask = new Map<Task, [number, number]>();
|
||||
const computePriority = (task: Task, idx: number):
|
||||
[number, number] => [dependencies.has(task) ? dependencies.get(task) !.size : 0, idx];
|
||||
[number, number] => [dependencies.has(task) ? dependencies.get(task)!.size : 0, idx];
|
||||
|
||||
tasks.forEach((task, i) => priorityPerTask.set(task, computePriority(task, i)));
|
||||
|
||||
return tasks.slice().sort((task1, task2) => {
|
||||
const [p1, idx1] = priorityPerTask.get(task1) !;
|
||||
const [p2, idx2] = priorityPerTask.get(task2) !;
|
||||
const [p1, idx1] = priorityPerTask.get(task1)!;
|
||||
const [p2, idx2] = priorityPerTask.get(task2)!;
|
||||
|
||||
return (p2 - p1) || (idx1 - idx2);
|
||||
});
|
||||
|
@ -7,13 +7,14 @@
|
||||
*/
|
||||
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {absoluteFrom} from '../../../src/ngtsc/file_system';
|
||||
import {Declaration, Import} from '../../../src/ngtsc/reflection';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {BundleProgram} from '../packages/bundle_program';
|
||||
import {FactoryMap, getTsHelperFnFromIdentifier, isDefined, stripExtension} from '../utils';
|
||||
|
||||
import {ExportDeclaration, ExportStatement, ReexportStatement, RequireCall, findNamespaceOfIdentifier, findRequireCallReference, isExportStatement, isReexportStatement, isRequireCall} from './commonjs_umd_utils';
|
||||
import {ExportDeclaration, ExportStatement, findNamespaceOfIdentifier, findRequireCallReference, isExportStatement, isReexportStatement, isRequireCall, ReexportStatement, RequireCall} from './commonjs_umd_utils';
|
||||
import {Esm5ReflectionHost} from './esm5_host';
|
||||
import {NgccClassSymbol} from './ngcc_host';
|
||||
|
||||
|
@ -16,7 +16,12 @@ export interface ExportDeclaration {
|
||||
}
|
||||
|
||||
export interface ExportStatement extends ts.ExpressionStatement {
|
||||
expression: ts.BinaryExpression&{left: ts.PropertyAccessExpression & {expression: ts.Identifier}};
|
||||
expression: ts.BinaryExpression&{
|
||||
left: ts.PropertyAccessExpression &
|
||||
{
|
||||
expression: ts.Identifier
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@ -34,7 +39,9 @@ export interface ExportStatement extends ts.ExpressionStatement {
|
||||
* expression and can be either a `require('...')` call or an identifier (initialized via a
|
||||
* `require('...')` call).
|
||||
*/
|
||||
export interface ReexportStatement extends ts.ExpressionStatement { expression: ts.CallExpression; }
|
||||
export interface ReexportStatement extends ts.ExpressionStatement {
|
||||
expression: ts.CallExpression;
|
||||
}
|
||||
|
||||
export interface RequireCall extends ts.CallExpression {
|
||||
arguments: ts.CallExpression['arguments']&[ts.StringLiteral];
|
||||
|
@ -13,7 +13,8 @@ import {Declaration, Import} from '../../../src/ngtsc/reflection';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {BundleProgram} from '../packages/bundle_program';
|
||||
import {FactoryMap, getTsHelperFnFromIdentifier, stripExtension} from '../utils';
|
||||
import {ExportDeclaration, ExportStatement, ReexportStatement, findNamespaceOfIdentifier, findRequireCallReference, isExportStatement, isReexportStatement, isRequireCall} from './commonjs_umd_utils';
|
||||
|
||||
import {ExportDeclaration, ExportStatement, findNamespaceOfIdentifier, findRequireCallReference, isExportStatement, isReexportStatement, isRequireCall, ReexportStatement} from './commonjs_umd_utils';
|
||||
import {Esm5ReflectionHost, stripParentheses} from './esm5_host';
|
||||
|
||||
export class UmdReflectionHost extends Esm5ReflectionHost {
|
||||
@ -61,7 +62,8 @@ export class UmdReflectionHost extends Esm5ReflectionHost {
|
||||
return this.umdImportPaths.get(importParameter);
|
||||
}
|
||||
|
||||
/** Get the top level statements for a module.
|
||||
/**
|
||||
* Get the top level statements for a module.
|
||||
*
|
||||
* In UMD modules these are the body of the UMD factory function.
|
||||
*
|
||||
|
@ -52,7 +52,7 @@ export class AsyncLocker {
|
||||
if (attempts === 0) {
|
||||
this.logger.info(
|
||||
`Another process, with id ${pid}, is currently running ngcc.\n` +
|
||||
`Waiting up to ${this.retryDelay*this.retryAttempts/1000}s for it to finish.`);
|
||||
`Waiting up to ${this.retryDelay * this.retryAttempts / 1000}s for it to finish.`);
|
||||
}
|
||||
// The file is still locked by another process so wait for a bit and retry
|
||||
await new Promise(resolve => setTimeout(resolve, this.retryDelay));
|
||||
@ -60,7 +60,10 @@ export class AsyncLocker {
|
||||
}
|
||||
// If we fall out of the loop then we ran out of rety attempts
|
||||
throw new Error(
|
||||
`Timed out waiting ${this.retryAttempts * this.retryDelay/1000}s for another ngcc process, with id ${pid}, to complete.\n` +
|
||||
`(If you are sure no ngcc process is running then you should delete the lock-file at ${this.lockFile.path}.)`);
|
||||
`Timed out waiting ${
|
||||
this.retryAttempts * this.retryDelay /
|
||||
1000}s for another ngcc process, with id ${pid}, to complete.\n` +
|
||||
`(If you are sure no ngcc process is running then you should delete the lock-file at ${
|
||||
this.lockFile.path}.)`);
|
||||
}
|
||||
}
|
||||
|
@ -8,8 +8,8 @@
|
||||
import {ChildProcess, fork} from 'child_process';
|
||||
|
||||
import {AbsoluteFsPath, CachedFileSystem, FileSystem} from '../../../../src/ngtsc/file_system';
|
||||
import {LogLevel, Logger} from '../../logging/logger';
|
||||
import {LockFile, getLockFilePath} from '../lock_file';
|
||||
import {Logger, LogLevel} from '../../logging/logger';
|
||||
import {getLockFilePath, LockFile} from '../lock_file';
|
||||
|
||||
import {removeLockFile} from './util';
|
||||
|
||||
|
@ -20,14 +20,14 @@ const fs = new NodeJSFileSystem();
|
||||
|
||||
// We create a logger that has the same logging level as the parent process, since it should have
|
||||
// been passed through as one of the args
|
||||
const logLevel = parseInt(process.argv.pop() !, 10);
|
||||
const logLevel = parseInt(process.argv.pop()!, 10);
|
||||
const logger = new ConsoleLogger(logLevel);
|
||||
|
||||
// We must store the parent PID now as it changes if the parent process is killed early
|
||||
const ppid = process.ppid.toString();
|
||||
|
||||
// The path to the lock-file to remove should have been passed as one of the args
|
||||
const lockFilePath = fs.resolve(process.argv.pop() !);
|
||||
const lockFilePath = fs.resolve(process.argv.pop()!);
|
||||
|
||||
logger.debug(`Starting unlocker at process ${process.pid} on behalf of process ${ppid}`);
|
||||
logger.debug(`The lock-file path is ${lockFilePath}`);
|
||||
@ -36,4 +36,6 @@ logger.debug(`The lock-file path is ${lockFilePath}`);
|
||||
* When the parent process exits (for whatever reason) remove the loc-file if it exists and as long
|
||||
* as it was one that was created by the parent process.
|
||||
*/
|
||||
process.on('disconnect', () => { removeLockFile(fs, logger, lockFilePath, ppid); });
|
||||
process.on('disconnect', () => {
|
||||
removeLockFile(fs, logger, lockFilePath, ppid);
|
||||
});
|
||||
|
@ -57,6 +57,7 @@ export class SyncLocker {
|
||||
`ngcc is already running at process with id ${pid}.\n` +
|
||||
`If you are running multiple builds in parallel then you should pre-process your node_modules via the command line ngcc tool before starting the builds;\n` +
|
||||
`See https://v9.angular.io/guide/ivy#speeding-up-ngcc-compilation.\n` +
|
||||
`(If you are sure no ngcc process is running then you should delete the lock-file at ${this.lockFile.path}.)`);
|
||||
`(If you are sure no ngcc process is running then you should delete the lock-file at ${
|
||||
this.lockFile.path}.)`);
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,7 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {LogLevel, Logger} from './logger';
|
||||
import {Logger, LogLevel} from './logger';
|
||||
|
||||
const RESET = '\x1b[0m';
|
||||
const RED = '\x1b[31m';
|
||||
|
@ -14,7 +14,7 @@ import * as ts from 'typescript';
|
||||
|
||||
import {readConfiguration} from '../..';
|
||||
import {replaceTsWithNgInErrors} from '../../src/ngtsc/diagnostics';
|
||||
import {AbsoluteFsPath, FileSystem, absoluteFrom, dirname, getFileSystem, resolve} from '../../src/ngtsc/file_system';
|
||||
import {absoluteFrom, AbsoluteFsPath, dirname, FileSystem, getFileSystem, resolve} from '../../src/ngtsc/file_system';
|
||||
|
||||
import {CommonJsDependencyHost} from './dependencies/commonjs_dependency_host';
|
||||
import {DependencyResolver, InvalidEntryPoint} from './dependencies/dependency_resolver';
|
||||
@ -38,10 +38,10 @@ import {AsyncLocker} from './locking/async_locker';
|
||||
import {LockFileWithChildProcess} from './locking/lock_file_with_child_process';
|
||||
import {SyncLocker} from './locking/sync_locker';
|
||||
import {ConsoleLogger} from './logging/console_logger';
|
||||
import {LogLevel, Logger} from './logging/logger';
|
||||
import {Logger, LogLevel} from './logging/logger';
|
||||
import {hasBeenProcessed} from './packages/build_marker';
|
||||
import {NgccConfiguration} from './packages/configuration';
|
||||
import {EntryPoint, EntryPointJsonProperty, EntryPointPackageJson, SUPPORTED_FORMAT_PROPERTIES, getEntryPointFormat} from './packages/entry_point';
|
||||
import {EntryPoint, EntryPointJsonProperty, EntryPointPackageJson, getEntryPointFormat, SUPPORTED_FORMAT_PROPERTIES} from './packages/entry_point';
|
||||
import {makeEntryPointBundle} from './packages/entry_point_bundle';
|
||||
import {EntryPointManifest, InvalidatingEntryPointManifest} from './packages/entry_point_manifest';
|
||||
import {Transformer} from './packages/transformer';
|
||||
@ -164,12 +164,12 @@ export interface SyncNgccOptions {
|
||||
/**
|
||||
* The options to configure the ngcc compiler for asynchronous execution.
|
||||
*/
|
||||
export type AsyncNgccOptions = Omit<SyncNgccOptions, 'async'>& {async: true};
|
||||
export type AsyncNgccOptions = Omit<SyncNgccOptions, 'async'>&{async: true};
|
||||
|
||||
/**
|
||||
* The options to configure the ngcc compiler.
|
||||
*/
|
||||
export type NgccOptions = AsyncNgccOptions | SyncNgccOptions;
|
||||
export type NgccOptions = AsyncNgccOptions|SyncNgccOptions;
|
||||
|
||||
/**
|
||||
* This is the main entry-point into ngcc (aNGular Compatibility Compiler).
|
||||
@ -181,12 +181,20 @@ export type NgccOptions = AsyncNgccOptions | SyncNgccOptions;
|
||||
*/
|
||||
export function mainNgcc(options: AsyncNgccOptions): Promise<void>;
|
||||
export function mainNgcc(options: SyncNgccOptions): void;
|
||||
export function mainNgcc(
|
||||
{basePath, targetEntryPointPath, propertiesToConsider = SUPPORTED_FORMAT_PROPERTIES,
|
||||
compileAllFormats = true, createNewEntryPointFormats = false,
|
||||
logger = new ConsoleLogger(LogLevel.info), pathMappings, async = false,
|
||||
errorOnFailedEntryPoint = false, enableI18nLegacyMessageIdFormat = true,
|
||||
invalidateEntryPointManifest = false, tsConfigPath}: NgccOptions): void|Promise<void> {
|
||||
export function mainNgcc({
|
||||
basePath,
|
||||
targetEntryPointPath,
|
||||
propertiesToConsider = SUPPORTED_FORMAT_PROPERTIES,
|
||||
compileAllFormats = true,
|
||||
createNewEntryPointFormats = false,
|
||||
logger = new ConsoleLogger(LogLevel.info),
|
||||
pathMappings,
|
||||
async = false,
|
||||
errorOnFailedEntryPoint = false,
|
||||
enableI18nLegacyMessageIdFormat = true,
|
||||
invalidateEntryPointManifest = false,
|
||||
tsConfigPath
|
||||
}: NgccOptions): void|Promise<void> {
|
||||
if (!!targetEntryPointPath) {
|
||||
// targetEntryPointPath forces us to error if an entry-point fails.
|
||||
errorOnFailedEntryPoint = true;
|
||||
@ -279,7 +287,7 @@ export function mainNgcc(
|
||||
continue;
|
||||
}
|
||||
|
||||
const formatPropertiesToMarkAsProcessed = equivalentPropertiesMap.get(formatProperty) !;
|
||||
const formatPropertiesToMarkAsProcessed = equivalentPropertiesMap.get(formatProperty)!;
|
||||
tasks.push({entryPoint, formatProperty, formatPropertiesToMarkAsProcessed, processDts});
|
||||
|
||||
// Only process typings for the first property (if not already processed).
|
||||
@ -442,7 +450,7 @@ function getExecutor(
|
||||
|
||||
function getDependencyResolver(
|
||||
fileSystem: FileSystem, logger: Logger, config: NgccConfiguration,
|
||||
pathMappings: PathMappings | undefined): DependencyResolver {
|
||||
pathMappings: PathMappings|undefined): DependencyResolver {
|
||||
const moduleResolver = new ModuleResolver(fileSystem, pathMappings);
|
||||
const esmDependencyHost = new EsmDependencyHost(fileSystem, moduleResolver);
|
||||
const umdDependencyHost = new UmdDependencyHost(fileSystem, moduleResolver);
|
||||
@ -461,8 +469,8 @@ function getDependencyResolver(
|
||||
function getEntryPointFinder(
|
||||
fs: FileSystem, logger: Logger, resolver: DependencyResolver, config: NgccConfiguration,
|
||||
entryPointManifest: EntryPointManifest, basePath: AbsoluteFsPath,
|
||||
absoluteTargetEntryPointPath: AbsoluteFsPath | null,
|
||||
pathMappings: PathMappings | undefined): EntryPointFinder {
|
||||
absoluteTargetEntryPointPath: AbsoluteFsPath|null,
|
||||
pathMappings: PathMappings|undefined): EntryPointFinder {
|
||||
if (absoluteTargetEntryPointPath !== null) {
|
||||
return new TargetedEntryPointFinder(
|
||||
fs, config, logger, resolver, basePath, absoluteTargetEntryPointPath, pathMappings);
|
||||
@ -533,7 +541,7 @@ function getPropertiesToProcess(
|
||||
|
||||
const equivalentPropertiesMap = new Map<EntryPointJsonProperty, EntryPointJsonProperty[]>();
|
||||
for (const prop of propertiesToConsider) {
|
||||
const formatPath = packageJson[prop] !;
|
||||
const formatPath = packageJson[prop]!;
|
||||
const equivalentProperties = formatPathToProperties[formatPath];
|
||||
equivalentPropertiesMap.set(prop, equivalentProperties);
|
||||
}
|
||||
|
@ -102,7 +102,7 @@ function migrateProviders(metadata: ResolvedValueMap, field: string, host: Migra
|
||||
if (!metadata.has(field)) {
|
||||
return;
|
||||
}
|
||||
const providers = metadata.get(field) !;
|
||||
const providers = metadata.get(field)!;
|
||||
if (!Array.isArray(providers)) {
|
||||
return;
|
||||
}
|
||||
@ -127,10 +127,10 @@ function migrateProvider(provider: ResolvedValue, host: MigrationHost): void {
|
||||
// as the provider itself configures 'deps'. Only if 'deps' is missing will this require a
|
||||
// factory to exist on SomeClass.
|
||||
if (!provider.has('deps')) {
|
||||
migrateProviderClass(provider.get('useClass') !, host);
|
||||
migrateProviderClass(provider.get('useClass')!, host);
|
||||
}
|
||||
} else {
|
||||
migrateProviderClass(provider.get('provide') !, host);
|
||||
migrateProviderClass(provider.get('provide')!, host);
|
||||
}
|
||||
} else if (Array.isArray(provider)) {
|
||||
for (const v of provider) {
|
||||
|
@ -43,7 +43,7 @@ export function hasConstructor(host: MigrationHost, clazz: ClassDeclaration): bo
|
||||
*/
|
||||
export function createDirectiveDecorator(
|
||||
clazz: ClassDeclaration,
|
||||
metadata?: {selector: string | null, exportAs: string[] | null}): Decorator {
|
||||
metadata?: {selector: string|null, exportAs: string[]|null}): Decorator {
|
||||
const args: ts.Expression[] = [];
|
||||
if (metadata !== undefined) {
|
||||
const metaArgs: ts.PropertyAssignment[] = [];
|
||||
@ -60,7 +60,8 @@ export function createDirectiveDecorator(
|
||||
identifier: null,
|
||||
import: {name: 'Directive', from: '@angular/core'},
|
||||
node: null,
|
||||
synthesizedFor: clazz.name, args,
|
||||
synthesizedFor: clazz.name,
|
||||
args,
|
||||
};
|
||||
}
|
||||
|
||||
@ -69,7 +70,7 @@ export function createDirectiveDecorator(
|
||||
*/
|
||||
export function createComponentDecorator(
|
||||
clazz: ClassDeclaration,
|
||||
metadata: {selector: string | null, exportAs: string[] | null}): Decorator {
|
||||
metadata: {selector: string|null, exportAs: string[]|null}): Decorator {
|
||||
const metaArgs: ts.PropertyAssignment[] = [
|
||||
property('template', ''),
|
||||
];
|
||||
@ -127,5 +128,5 @@ function reifySourceFile(expr: ts.Expression): ts.Expression {
|
||||
if (!ts.isVariableStatement(stmt)) {
|
||||
throw new Error(`Expected VariableStatement, got ${ts.SyntaxKind[stmt.kind]}`);
|
||||
}
|
||||
return stmt.declarationList.declarations[0].initializer !;
|
||||
return stmt.declarationList.declarations[0].initializer!;
|
||||
}
|
||||
|
@ -6,17 +6,19 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import * as ts from 'typescript';
|
||||
import {AbsoluteFsPath, FileSystem, dirname, resolve} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {AbsoluteFsPath, dirname, FileSystem, resolve} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {patchTsGetExpandoInitializer, restoreGetExpandoInitializer} from './patch_ts_expando_initializer';
|
||||
|
||||
/**
|
||||
* An entry point bundle contains one or two programs, e.g. `src` and `dts`,
|
||||
* that are compiled via TypeScript.
|
||||
*
|
||||
* To aid with processing the program, this interface exposes the program itself,
|
||||
* as well as path and TS file of the entry-point to the program and the r3Symbols
|
||||
* file, if appropriate.
|
||||
*/
|
||||
* An entry point bundle contains one or two programs, e.g. `src` and `dts`,
|
||||
* that are compiled via TypeScript.
|
||||
*
|
||||
* To aid with processing the program, this interface exposes the program itself,
|
||||
* as well as path and TS file of the entry-point to the program and the r3Symbols
|
||||
* file, if appropriate.
|
||||
*/
|
||||
export interface BundleProgram {
|
||||
program: ts.Program;
|
||||
options: ts.CompilerOptions;
|
||||
@ -46,7 +48,7 @@ export function makeBundleProgram(
|
||||
program.getTypeChecker();
|
||||
restoreGetExpandoInitializer(originalGetExpandoInitializer);
|
||||
|
||||
const file = program.getSourceFile(path) !;
|
||||
const file = program.getSourceFile(path)!;
|
||||
const r3SymbolsFile = r3SymbolsPath && program.getSourceFile(r3SymbolsPath) || null;
|
||||
|
||||
return {program, options, host, package: pkg, path, file, r3SymbolsPath, r3SymbolsFile};
|
||||
|
@ -8,7 +8,9 @@
|
||||
import {createHash} from 'crypto';
|
||||
import {satisfies} from 'semver';
|
||||
import * as vm from 'vm';
|
||||
import {AbsoluteFsPath, FileSystem, dirname, join, resolve} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {AbsoluteFsPath, dirname, FileSystem, join, resolve} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {PackageJsonFormatPropertiesMap} from './entry_point';
|
||||
|
||||
/**
|
||||
@ -178,7 +180,7 @@ export class NgccConfiguration {
|
||||
getConfig(packagePath: AbsoluteFsPath, version: string|null): VersionedPackageConfig {
|
||||
const cacheKey = packagePath + (version !== null ? `@${version}` : '');
|
||||
if (this.cache.has(cacheKey)) {
|
||||
return this.cache.get(cacheKey) !;
|
||||
return this.cache.get(cacheKey)!;
|
||||
}
|
||||
|
||||
const projectLevelConfig =
|
||||
@ -256,7 +258,8 @@ export class NgccConfiguration {
|
||||
const theExports = {};
|
||||
const sandbox = {
|
||||
module: {exports: theExports},
|
||||
exports: theExports, require,
|
||||
exports: theExports,
|
||||
require,
|
||||
__dirname: dirname(srcPath),
|
||||
__filename: srcPath
|
||||
};
|
||||
@ -292,9 +295,8 @@ export class NgccConfiguration {
|
||||
}
|
||||
}
|
||||
|
||||
function findSatisfactoryVersion(
|
||||
configs: VersionedPackageConfig[] | undefined, version: string | null): VersionedPackageConfig|
|
||||
null {
|
||||
function findSatisfactoryVersion(configs: VersionedPackageConfig[]|undefined, version: string|null):
|
||||
VersionedPackageConfig|null {
|
||||
if (configs === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ import {NgccConfiguration, NgccEntryPointConfig} from './configuration';
|
||||
/**
|
||||
* The possible values for the format of an entry-point.
|
||||
*/
|
||||
export type EntryPointFormat = 'esm5' | 'esm2015' | 'umd' | 'commonjs';
|
||||
export type EntryPointFormat = 'esm5'|'esm2015'|'umd'|'commonjs';
|
||||
|
||||
/**
|
||||
* An object containing information about an entry-point, including paths
|
||||
@ -42,10 +42,12 @@ export interface EntryPoint extends JsonObject {
|
||||
generateDeepReexports: boolean;
|
||||
}
|
||||
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonArray | JsonObject | undefined;
|
||||
export type JsonPrimitive = string|number|boolean|null;
|
||||
export type JsonValue = JsonPrimitive|JsonArray|JsonObject|undefined;
|
||||
export interface JsonArray extends Array<JsonValue> {}
|
||||
export interface JsonObject { [key: string]: JsonValue; }
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
|
||||
export interface PackageJsonFormatPropertiesMap {
|
||||
fesm2015?: string;
|
||||
@ -97,8 +99,7 @@ export const INCOMPATIBLE_ENTRY_POINT = 'incompatible-entry-point';
|
||||
* * INCOMPATIBLE_ENTRY_POINT - the path was a non-processable entry-point that should be searched
|
||||
* for sub-entry-points
|
||||
*/
|
||||
export type GetEntryPointResult =
|
||||
EntryPoint | typeof INCOMPATIBLE_ENTRY_POINT | typeof NO_ENTRY_POINT;
|
||||
export type GetEntryPointResult = EntryPoint|typeof INCOMPATIBLE_ENTRY_POINT|typeof NO_ENTRY_POINT;
|
||||
|
||||
|
||||
/**
|
||||
@ -161,7 +162,8 @@ export function getEntryPointInfo(
|
||||
packageJson: entryPointPackageJson,
|
||||
package: packagePath,
|
||||
path: entryPointPath,
|
||||
typings: resolve(entryPointPath, typings), compiledByAngular,
|
||||
typings: resolve(entryPointPath, typings),
|
||||
compiledByAngular,
|
||||
ignoreMissingDependencies:
|
||||
entryPointConfig !== undefined ? !!entryPointConfig.ignoreMissingDependencies : false,
|
||||
generateDeepReexports:
|
||||
@ -236,7 +238,7 @@ function isUmdModule(fs: FileSystem, sourceFilePath: AbsoluteFsPath): boolean {
|
||||
}
|
||||
|
||||
function mergeConfigAndPackageJson(
|
||||
entryPointPackageJson: EntryPointPackageJson | null, entryPointConfig: NgccEntryPointConfig,
|
||||
entryPointPackageJson: EntryPointPackageJson|null, entryPointConfig: NgccEntryPointConfig,
|
||||
packagePath: AbsoluteFsPath, entryPointPath: AbsoluteFsPath): EntryPointPackageJson {
|
||||
if (entryPointPackageJson !== null) {
|
||||
return {...entryPointPackageJson, ...entryPointConfig.override};
|
||||
|
@ -48,10 +48,8 @@ export function makeEntryPointBundle(
|
||||
enableI18nLegacyMessageIdFormat: boolean = true): EntryPointBundle {
|
||||
// Create the TS program and necessary helpers.
|
||||
const rootDir = entryPoint.package;
|
||||
const options: ts.CompilerOptions = {
|
||||
allowJs: true,
|
||||
maxNodeModuleJsDepth: Infinity, rootDir, ...pathMappings
|
||||
};
|
||||
const options: ts
|
||||
.CompilerOptions = {allowJs: true, maxNodeModuleJsDepth: Infinity, rootDir, ...pathMappings};
|
||||
const srcHost = new NgccSourcesCompilerHost(fs, options, entryPoint.path);
|
||||
const dtsHost = new NgtscCompilerHost(fs, options);
|
||||
|
||||
@ -72,7 +70,12 @@ export function makeEntryPointBundle(
|
||||
return {
|
||||
entryPoint,
|
||||
format,
|
||||
rootDirs: [rootDir], isCore, isFlatCore, src, dts, enableI18nLegacyMessageIdFormat
|
||||
rootDirs: [rootDir],
|
||||
isCore,
|
||||
isFlatCore,
|
||||
src,
|
||||
dts,
|
||||
enableI18nLegacyMessageIdFormat
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -12,7 +12,7 @@ import {Logger} from '../logging/logger';
|
||||
|
||||
import {NGCC_VERSION} from './build_marker';
|
||||
import {NgccConfiguration} from './configuration';
|
||||
import {EntryPoint, INCOMPATIBLE_ENTRY_POINT, NO_ENTRY_POINT, getEntryPointInfo} from './entry_point';
|
||||
import {EntryPoint, getEntryPointInfo, INCOMPATIBLE_ENTRY_POINT, NO_ENTRY_POINT} from './entry_point';
|
||||
|
||||
/**
|
||||
* Manages reading and writing a manifest file that contains a list of all the entry-points that
|
||||
@ -63,8 +63,8 @@ export class EntryPointManifest {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.logger.debug(
|
||||
`Entry-point manifest found for ${basePath} so loading entry-point information directly.`);
|
||||
this.logger.debug(`Entry-point manifest found for ${
|
||||
basePath} so loading entry-point information directly.`);
|
||||
const startTime = Date.now();
|
||||
|
||||
const entryPoints: EntryPoint[] = [];
|
||||
@ -72,8 +72,9 @@ export class EntryPointManifest {
|
||||
const result =
|
||||
getEntryPointInfo(this.fs, this.config, this.logger, packagePath, entryPointPath);
|
||||
if (result === NO_ENTRY_POINT || result === INCOMPATIBLE_ENTRY_POINT) {
|
||||
throw new Error(
|
||||
`The entry-point manifest at ${manifestPath} contained an invalid pair of package paths: [${packagePath}, ${entryPointPath}]`);
|
||||
throw new Error(`The entry-point manifest at ${
|
||||
manifestPath} contained an invalid pair of package paths: [${packagePath}, ${
|
||||
entryPointPath}]`);
|
||||
} else {
|
||||
entryPoints.push(result);
|
||||
}
|
||||
@ -142,7 +143,9 @@ export class EntryPointManifest {
|
||||
* called.
|
||||
*/
|
||||
export class InvalidatingEntryPointManifest extends EntryPointManifest {
|
||||
readEntryPointsUsingManifest(basePath: AbsoluteFsPath): EntryPoint[]|null { return null; }
|
||||
readEntryPointsUsingManifest(basePath: AbsoluteFsPath): EntryPoint[]|null {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -58,17 +58,16 @@ export function patchTsGetExpandoInitializer(): unknown {
|
||||
}
|
||||
|
||||
// Override the function to add support for recognizing the IIFE structure used in ES5 bundles.
|
||||
(ts as any).getExpandoInitializer =
|
||||
(initializer: ts.Node, isPrototypeAssignment: boolean): ts.Expression | undefined => {
|
||||
// If the initializer is a call expression within parenthesis, unwrap the parenthesis
|
||||
// upfront such that unsupported IIFE syntax `(function(){}())` becomes `function(){}()`,
|
||||
// which is supported.
|
||||
if (ts.isParenthesizedExpression(initializer) &&
|
||||
ts.isCallExpression(initializer.expression)) {
|
||||
initializer = initializer.expression;
|
||||
}
|
||||
return originalGetExpandoInitializer(initializer, isPrototypeAssignment);
|
||||
};
|
||||
(ts as any).getExpandoInitializer = (initializer: ts.Node,
|
||||
isPrototypeAssignment: boolean): ts.Expression|undefined => {
|
||||
// If the initializer is a call expression within parenthesis, unwrap the parenthesis
|
||||
// upfront such that unsupported IIFE syntax `(function(){}())` becomes `function(){}()`,
|
||||
// which is supported.
|
||||
if (ts.isParenthesizedExpression(initializer) && ts.isCallExpression(initializer.expression)) {
|
||||
initializer = initializer.expression;
|
||||
}
|
||||
return originalGetExpandoInitializer(initializer, isPrototypeAssignment);
|
||||
};
|
||||
return originalGetExpandoInitializer;
|
||||
}
|
||||
|
||||
@ -125,16 +124,36 @@ function checkIfExpandoPropertyIsPresent(): boolean {
|
||||
const sourceFile =
|
||||
ts.createSourceFile('test.js', sourceText, ts.ScriptTarget.ES5, true, ts.ScriptKind.JS);
|
||||
const host: ts.CompilerHost = {
|
||||
getSourceFile(): ts.SourceFile | undefined{return sourceFile;},
|
||||
fileExists(): boolean{return true;},
|
||||
readFile(): string | undefined{return '';},
|
||||
getSourceFile(): ts.SourceFile |
|
||||
undefined {
|
||||
return sourceFile;
|
||||
},
|
||||
fileExists(): boolean {
|
||||
return true;
|
||||
},
|
||||
readFile(): string |
|
||||
undefined {
|
||||
return '';
|
||||
},
|
||||
writeFile() {},
|
||||
getDefaultLibFileName(): string{return '';},
|
||||
getCurrentDirectory(): string{return '';},
|
||||
getDirectories(): string[]{return [];},
|
||||
getCanonicalFileName(fileName: string): string{return fileName;},
|
||||
useCaseSensitiveFileNames(): boolean{return true;},
|
||||
getNewLine(): string{return '\n';},
|
||||
getDefaultLibFileName(): string {
|
||||
return '';
|
||||
},
|
||||
getCurrentDirectory(): string {
|
||||
return '';
|
||||
},
|
||||
getDirectories(): string[] {
|
||||
return [];
|
||||
},
|
||||
getCanonicalFileName(fileName: string): string {
|
||||
return fileName;
|
||||
},
|
||||
useCaseSensitiveFileNames(): boolean {
|
||||
return true;
|
||||
},
|
||||
getNewLine(): string {
|
||||
return '\n';
|
||||
},
|
||||
};
|
||||
const options = {noResolve: true, noLib: true, noEmit: true, allowJs: true};
|
||||
const program = ts.createProgram(['test.js'], options, host);
|
||||
|
@ -36,8 +36,7 @@ import {EntryPointBundle} from './entry_point_bundle';
|
||||
|
||||
export type TransformResult = {
|
||||
success: true; diagnostics: ts.Diagnostic[]; transformedFiles: FileToWrite[];
|
||||
} |
|
||||
{
|
||||
}|{
|
||||
success: false;
|
||||
diagnostics: ts.Diagnostic[];
|
||||
};
|
||||
@ -79,8 +78,13 @@ export class Transformer {
|
||||
const reflectionHost = new DelegatingReflectionHost(tsReflectionHost, ngccReflectionHost);
|
||||
|
||||
// Parse and analyze the files.
|
||||
const {decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
|
||||
moduleWithProvidersAnalyses, diagnostics} = this.analyzeProgram(reflectionHost, bundle);
|
||||
const {
|
||||
decorationAnalyses,
|
||||
switchMarkerAnalyses,
|
||||
privateDeclarationsAnalyses,
|
||||
moduleWithProvidersAnalyses,
|
||||
diagnostics
|
||||
} = this.analyzeProgram(reflectionHost, bundle);
|
||||
|
||||
// Bail if the analysis produced any errors.
|
||||
if (hasErrors(diagnostics)) {
|
||||
@ -162,8 +166,13 @@ export class Transformer {
|
||||
const privateDeclarationsAnalyses =
|
||||
privateDeclarationsAnalyzer.analyzeProgram(bundle.src.program);
|
||||
|
||||
return {decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
|
||||
moduleWithProvidersAnalyses, diagnostics};
|
||||
return {
|
||||
decorationAnalyses,
|
||||
switchMarkerAnalyses,
|
||||
privateDeclarationsAnalyses,
|
||||
moduleWithProvidersAnalyses,
|
||||
diagnostics
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -6,13 +6,15 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {dirname, relative} from 'canonical-path';
|
||||
import * as ts from 'typescript';
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {Reexport} from '../../../src/ngtsc/imports';
|
||||
import {Import, ImportManager} from '../../../src/ngtsc/translator';
|
||||
import {ExportInfo} from '../analysis/private_declarations_analyzer';
|
||||
import {isRequireCall} from '../host/commonjs_umd_utils';
|
||||
import {NgccReflectionHost} from '../host/ngcc_host';
|
||||
|
||||
import {Esm5RenderingFormatter} from './esm5_rendering_formatter';
|
||||
import {stripExtension} from './utils';
|
||||
|
||||
|
@ -7,20 +7,22 @@
|
||||
*/
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {FileSystem} from '../../../src/ngtsc/file_system';
|
||||
import {Reexport} from '../../../src/ngtsc/imports';
|
||||
import {CompileResult} from '../../../src/ngtsc/transform';
|
||||
import {translateType, ImportManager} from '../../../src/ngtsc/translator';
|
||||
import {ImportManager, translateType} from '../../../src/ngtsc/translator';
|
||||
import {ModuleWithProvidersAnalyses, ModuleWithProvidersInfo} from '../analysis/module_with_providers_analyzer';
|
||||
import {ExportInfo, PrivateDeclarationsAnalyses} from '../analysis/private_declarations_analyzer';
|
||||
import {DecorationAnalyses} from '../analysis/types';
|
||||
import {ModuleWithProvidersInfo, ModuleWithProvidersAnalyses} from '../analysis/module_with_providers_analyzer';
|
||||
import {PrivateDeclarationsAnalyses, ExportInfo} from '../analysis/private_declarations_analyzer';
|
||||
import {IMPORT_PREFIX} from '../constants';
|
||||
import {NgccReflectionHost} from '../host/ngcc_host';
|
||||
import {EntryPointBundle} from '../packages/entry_point_bundle';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {FileToWrite, getImportRewriter} from './utils';
|
||||
import {EntryPointBundle} from '../packages/entry_point_bundle';
|
||||
|
||||
import {RenderingFormatter} from './rendering_formatter';
|
||||
import {renderSourceAndMap} from './source_maps';
|
||||
import {FileToWrite, getImportRewriter} from './utils';
|
||||
|
||||
/**
|
||||
* A structure that captures information about what needs to be rendered
|
||||
@ -84,7 +86,7 @@ export class DtsRenderer {
|
||||
const outputText = new MagicString(dtsFile.text);
|
||||
const printer = ts.createPrinter();
|
||||
const importManager = new ImportManager(
|
||||
getImportRewriter(this.bundle.dts !.r3SymbolsFile, this.bundle.isCore, false),
|
||||
getImportRewriter(this.bundle.dts!.r3SymbolsFile, this.bundle.isCore, false),
|
||||
IMPORT_PREFIX);
|
||||
|
||||
renderInfo.classInfo.forEach(dtsClass => {
|
||||
@ -129,7 +131,7 @@ export class DtsRenderer {
|
||||
const dtsDeclaration = this.host.getDtsDeclaration(compiledClass.declaration);
|
||||
if (dtsDeclaration) {
|
||||
const dtsFile = dtsDeclaration.getSourceFile();
|
||||
const renderInfo = dtsMap.has(dtsFile) ? dtsMap.get(dtsFile) ! : new DtsRenderInfo();
|
||||
const renderInfo = dtsMap.has(dtsFile) ? dtsMap.get(dtsFile)! : new DtsRenderInfo();
|
||||
renderInfo.classInfo.push({dtsDeclaration, compilation: compiledClass.compilation});
|
||||
// Only add re-exports if the .d.ts tree is overlayed with the .js tree, as re-exports in
|
||||
// ngcc are only used to support deep imports into e.g. commonjs code. For a deep import
|
||||
@ -150,7 +152,7 @@ export class DtsRenderer {
|
||||
// Capture the ModuleWithProviders functions/methods that need updating
|
||||
if (moduleWithProvidersAnalyses !== null) {
|
||||
moduleWithProvidersAnalyses.forEach((moduleWithProvidersToFix, dtsFile) => {
|
||||
const renderInfo = dtsMap.has(dtsFile) ? dtsMap.get(dtsFile) ! : new DtsRenderInfo();
|
||||
const renderInfo = dtsMap.has(dtsFile) ? dtsMap.get(dtsFile)! : new DtsRenderInfo();
|
||||
renderInfo.moduleWithProviders = moduleWithProvidersToFix;
|
||||
dtsMap.set(dtsFile, renderInfo);
|
||||
});
|
||||
@ -167,9 +169,9 @@ export class DtsRenderer {
|
||||
`The simplest fix for this is to ensure that this class is exported from the package's entry-point.`);
|
||||
}
|
||||
});
|
||||
const dtsEntryPoint = this.bundle.dts !.file;
|
||||
const dtsEntryPoint = this.bundle.dts!.file;
|
||||
const renderInfo =
|
||||
dtsMap.has(dtsEntryPoint) ? dtsMap.get(dtsEntryPoint) ! : new DtsRenderInfo();
|
||||
dtsMap.has(dtsEntryPoint) ? dtsMap.get(dtsEntryPoint)! : new DtsRenderInfo();
|
||||
renderInfo.privateExports = privateDeclarationsAnalyses;
|
||||
dtsMap.set(dtsEntryPoint, renderInfo);
|
||||
}
|
||||
|
@ -25,14 +25,14 @@ export class Esm5RenderingFormatter extends EsmRenderingFormatter {
|
||||
addDefinitions(output: MagicString, compiledClass: CompiledClass, definitions: string): void {
|
||||
const iifeBody = getIifeBody(compiledClass.declaration);
|
||||
if (!iifeBody) {
|
||||
throw new Error(
|
||||
`Compiled class declaration is not inside an IIFE: ${compiledClass.name} in ${compiledClass.declaration.getSourceFile().fileName}`);
|
||||
throw new Error(`Compiled class declaration is not inside an IIFE: ${compiledClass.name} in ${
|
||||
compiledClass.declaration.getSourceFile().fileName}`);
|
||||
}
|
||||
|
||||
const returnStatement = iifeBody.statements.find(ts.isReturnStatement);
|
||||
if (!returnStatement) {
|
||||
throw new Error(
|
||||
`Compiled class wrapper IIFE does not have a return statement: ${compiledClass.name} in ${compiledClass.declaration.getSourceFile().fileName}`);
|
||||
throw new Error(`Compiled class wrapper IIFE does not have a return statement: ${
|
||||
compiledClass.name} in ${compiledClass.declaration.getSourceFile().fileName}`);
|
||||
}
|
||||
|
||||
const insertionPoint = returnStatement.getFullStart();
|
||||
|
@ -8,17 +8,19 @@
|
||||
import {Statement} from '@angular/compiler';
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
import {relative, dirname, AbsoluteFsPath, absoluteFromSourceFile} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {absoluteFromSourceFile, AbsoluteFsPath, dirname, relative} from '../../../src/ngtsc/file_system';
|
||||
import {NOOP_DEFAULT_IMPORT_RECORDER, Reexport} from '../../../src/ngtsc/imports';
|
||||
import {Import, ImportManager, translateStatement} from '../../../src/ngtsc/translator';
|
||||
import {isDtsPath} from '../../../src/ngtsc/util/src/typescript';
|
||||
import {CompiledClass} from '../analysis/types';
|
||||
import {NgccReflectionHost, POST_R3_MARKER, PRE_R3_MARKER, SwitchableVariableDeclaration} from '../host/ngcc_host';
|
||||
import {ModuleWithProvidersInfo} from '../analysis/module_with_providers_analyzer';
|
||||
import {ExportInfo} from '../analysis/private_declarations_analyzer';
|
||||
import {RenderingFormatter, RedundantDecoratorMap} from './rendering_formatter';
|
||||
import {stripExtension} from './utils';
|
||||
import {CompiledClass} from '../analysis/types';
|
||||
import {isAssignment} from '../host/esm2015_host';
|
||||
import {NgccReflectionHost, POST_R3_MARKER, PRE_R3_MARKER, SwitchableVariableDeclaration} from '../host/ngcc_host';
|
||||
|
||||
import {RedundantDecoratorMap, RenderingFormatter} from './rendering_formatter';
|
||||
import {stripExtension} from './utils';
|
||||
|
||||
/**
|
||||
* A RenderingFormatter that works with ECMAScript Module import and export statements.
|
||||
@ -226,7 +228,8 @@ export class EsmRenderingFormatter implements RenderingFormatter {
|
||||
info.declaration.getEnd();
|
||||
outputText.appendLeft(
|
||||
insertPoint,
|
||||
`: ${generateImportString(importManager, '@angular/core', 'ModuleWithProviders')}<${ngModule}>`);
|
||||
`: ${generateImportString(importManager, '@angular/core', 'ModuleWithProviders')}<${
|
||||
ngModule}>`);
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -296,7 +299,7 @@ function findStatement(node: ts.Node): ts.Statement|undefined {
|
||||
}
|
||||
|
||||
function generateImportString(
|
||||
importManager: ImportManager, importPath: string | null, importName: string) {
|
||||
importManager: ImportManager, importPath: string|null, importName: string) {
|
||||
const importAs = importPath ? importManager.generateNamedImport(importPath, importName) : null;
|
||||
return importAs ? `${importAs.moduleImport}.${importAs.symbol}` : `${importName}`;
|
||||
}
|
||||
|
@ -8,16 +8,18 @@
|
||||
import {ConstantPool, Expression, Statement, WrappedNodeExpr, WritePropExpr} from '@angular/compiler';
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {FileSystem} from '../../../src/ngtsc/file_system';
|
||||
import {ImportManager} from '../../../src/ngtsc/translator';
|
||||
import {CompiledClass, CompiledFile, DecorationAnalyses} from '../analysis/types';
|
||||
import {PrivateDeclarationsAnalyses} from '../analysis/private_declarations_analyzer';
|
||||
import {SwitchMarkerAnalyses, SwitchMarkerAnalysis} from '../analysis/switch_marker_analyzer';
|
||||
import {CompiledClass, CompiledFile, DecorationAnalyses} from '../analysis/types';
|
||||
import {IMPORT_PREFIX} from '../constants';
|
||||
import {FileSystem} from '../../../src/ngtsc/file_system';
|
||||
import {NgccReflectionHost} from '../host/ngcc_host';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {EntryPointBundle} from '../packages/entry_point_bundle';
|
||||
import {RenderingFormatter, RedundantDecoratorMap} from './rendering_formatter';
|
||||
|
||||
import {RedundantDecoratorMap, RenderingFormatter} from './rendering_formatter';
|
||||
import {renderSourceAndMap} from './source_maps';
|
||||
import {FileToWrite, getImportRewriter, stripExtension} from './utils';
|
||||
|
||||
@ -138,11 +140,11 @@ export class Renderer {
|
||||
if (dec.node === null) {
|
||||
return;
|
||||
}
|
||||
const decoratorArray = dec.node.parent !;
|
||||
const decoratorArray = dec.node.parent!;
|
||||
if (!decoratorsToRemove.has(decoratorArray)) {
|
||||
decoratorsToRemove.set(decoratorArray, [dec.node]);
|
||||
} else {
|
||||
decoratorsToRemove.get(decoratorArray) !.push(dec.node);
|
||||
decoratorsToRemove.get(decoratorArray)!.push(dec.node);
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -160,8 +162,9 @@ export class Renderer {
|
||||
private renderDefinitions(
|
||||
sourceFile: ts.SourceFile, compiledClass: CompiledClass, imports: ImportManager): string {
|
||||
const name = this.host.getInternalNameOfClass(compiledClass.declaration);
|
||||
const statements: Statement[] = compiledClass.compilation.map(
|
||||
c => { return createAssignmentStatement(name, c.name, c.initializer); });
|
||||
const statements: Statement[] = compiledClass.compilation.map(c => {
|
||||
return createAssignmentStatement(name, c.name, c.initializer);
|
||||
});
|
||||
return this.renderStatements(sourceFile, statements, imports);
|
||||
}
|
||||
|
||||
|
@ -8,12 +8,13 @@
|
||||
import {Statement} from '@angular/compiler';
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {Reexport} from '../../../src/ngtsc/imports';
|
||||
import {Import, ImportManager} from '../../../src/ngtsc/translator';
|
||||
import {ModuleWithProvidersInfo} from '../analysis/module_with_providers_analyzer';
|
||||
import {ExportInfo} from '../analysis/private_declarations_analyzer';
|
||||
import {CompiledClass} from '../analysis/types';
|
||||
import {SwitchableVariableDeclaration} from '../host/ngcc_host';
|
||||
import {ModuleWithProvidersInfo} from '../analysis/module_with_providers_analyzer';
|
||||
|
||||
/**
|
||||
* The collected decorators that have become redundant after the compilation
|
||||
|
@ -5,14 +5,16 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {SourceMapConverter, fromObject, generateMapFileComment} from 'convert-source-map';
|
||||
import {fromObject, generateMapFileComment, SourceMapConverter} from 'convert-source-map';
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
import {FileSystem, absoluteFromSourceFile, basename, absoluteFrom} from '../../../src/ngtsc/file_system';
|
||||
import {FileToWrite} from './utils';
|
||||
import {SourceFileLoader} from '../sourcemaps/source_file_loader';
|
||||
import {RawSourceMap} from '../sourcemaps/raw_source_map';
|
||||
|
||||
import {absoluteFrom, absoluteFromSourceFile, basename, FileSystem} from '../../../src/ngtsc/file_system';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {RawSourceMap} from '../sourcemaps/raw_source_map';
|
||||
import {SourceFileLoader} from '../sourcemaps/source_file_loader';
|
||||
|
||||
import {FileToWrite} from './utils';
|
||||
|
||||
export interface SourceMapInfo {
|
||||
source: string;
|
||||
@ -53,8 +55,8 @@ export function renderSourceAndMap(
|
||||
];
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(
|
||||
`Error when flattening the source-map "${generatedMapPath}" for "${generatedPath}": ${e.toString()}`);
|
||||
logger.error(`Error when flattening the source-map "${generatedMapPath}" for "${
|
||||
generatedPath}": ${e.toString()}`);
|
||||
return [
|
||||
{path: generatedPath, contents: generatedContent},
|
||||
{path: generatedMapPath, contents: fromObject(generatedMap).toJSON()},
|
||||
|
@ -6,17 +6,19 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {dirname, relative} from 'canonical-path';
|
||||
import * as ts from 'typescript';
|
||||
import MagicString from 'magic-string';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {Reexport} from '../../../src/ngtsc/imports';
|
||||
import {Import, ImportManager} from '../../../src/ngtsc/translator';
|
||||
import {ExportInfo} from '../analysis/private_declarations_analyzer';
|
||||
import {UmdReflectionHost} from '../host/umd_host';
|
||||
|
||||
import {Esm5RenderingFormatter} from './esm5_rendering_formatter';
|
||||
import {stripExtension} from './utils';
|
||||
import {Reexport} from '../../../src/ngtsc/imports';
|
||||
|
||||
type CommonJsConditional = ts.ConditionalExpression & {whenTrue: ts.CallExpression};
|
||||
type AmdConditional = ts.ConditionalExpression & {whenTrue: ts.CallExpression};
|
||||
type CommonJsConditional = ts.ConditionalExpression&{whenTrue: ts.CallExpression};
|
||||
type AmdConditional = ts.ConditionalExpression&{whenTrue: ts.CallExpression};
|
||||
|
||||
/**
|
||||
* A RenderingFormatter that works with UMD files, instead of `import` and `export` statements
|
||||
@ -24,7 +26,9 @@ type AmdConditional = ts.ConditionalExpression & {whenTrue: ts.CallExpression};
|
||||
* wrapper function for AMD, CommonJS and global module formats.
|
||||
*/
|
||||
export class UmdRenderingFormatter extends Esm5RenderingFormatter {
|
||||
constructor(protected umdHost: UmdReflectionHost, isCore: boolean) { super(umdHost, isCore); }
|
||||
constructor(protected umdHost: UmdReflectionHost, isCore: boolean) {
|
||||
super(umdHost, isCore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the imports to the UMD module IIFE.
|
||||
|
@ -24,11 +24,11 @@ export interface FileToWrite {
|
||||
* Create an appropriate ImportRewriter given the parameters.
|
||||
*/
|
||||
export function getImportRewriter(
|
||||
r3SymbolsFile: ts.SourceFile | null, isCore: boolean, isFlat: boolean): ImportRewriter {
|
||||
r3SymbolsFile: ts.SourceFile|null, isCore: boolean, isFlat: boolean): ImportRewriter {
|
||||
if (isCore && isFlat) {
|
||||
return new NgccFlatImportRewriter();
|
||||
} else if (isCore) {
|
||||
return new R3SymbolsImportRewriter(r3SymbolsFile !.fileName);
|
||||
return new R3SymbolsImportRewriter(r3SymbolsFile!.fileName);
|
||||
} else {
|
||||
return new NoopImportRewriter();
|
||||
}
|
||||
|
@ -8,11 +8,11 @@
|
||||
|
||||
|
||||
/**
|
||||
* A marker that indicates the start of a segment in a mapping.
|
||||
*
|
||||
* The end of a segment is indicated by the the first segment-marker of another mapping whose start
|
||||
* is greater or equal to this one.
|
||||
*/
|
||||
* A marker that indicates the start of a segment in a mapping.
|
||||
*
|
||||
* The end of a segment is indicated by the the first segment-marker of another mapping whose start
|
||||
* is greater or equal to this one.
|
||||
*/
|
||||
export interface SegmentMarker {
|
||||
readonly line: number;
|
||||
readonly column: number;
|
||||
|
@ -6,10 +6,12 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {removeComments, removeMapFileComments} from 'convert-source-map';
|
||||
import {SourceMapMappings, SourceMapSegment, decode, encode} from 'sourcemap-codec';
|
||||
import {decode, encode, SourceMapMappings, SourceMapSegment} from 'sourcemap-codec';
|
||||
|
||||
import {AbsoluteFsPath, dirname, relative} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {RawSourceMap} from './raw_source_map';
|
||||
import {SegmentMarker, compareSegments, offsetSegment} from './segment_marker';
|
||||
import {compareSegments, offsetSegment, SegmentMarker} from './segment_marker';
|
||||
|
||||
export function removeSourceMapComments(contents: string): string {
|
||||
return removeMapFileComments(removeComments(contents)).replace(/\n\n$/, '\n');
|
||||
@ -77,7 +79,8 @@ export class SourceFile {
|
||||
const sourceMap: RawSourceMap = {
|
||||
version: 3,
|
||||
file: relative(sourcePathDir, this.sourcePath),
|
||||
sources: sources.map(sf => relative(sourcePathDir, sf.sourcePath)), names,
|
||||
sources: sources.map(sf => relative(sourcePathDir, sf.sourcePath)),
|
||||
names,
|
||||
mappings: encode(mappings),
|
||||
sourcesContent: sources.map(sf => sf.contents),
|
||||
};
|
||||
@ -302,7 +305,7 @@ export function mergeMappings(generatedSource: SourceFile, ab: Mapping, bc: Mapp
|
||||
* in the `sources` parameter.
|
||||
*/
|
||||
export function parseMappings(
|
||||
rawMap: RawSourceMap | null, sources: (SourceFile | null)[],
|
||||
rawMap: RawSourceMap|null, sources: (SourceFile|null)[],
|
||||
generatedSourceStartOfLinePositions: number[]): Mapping[] {
|
||||
if (rawMap === null) {
|
||||
return [];
|
||||
@ -318,15 +321,15 @@ export function parseMappings(
|
||||
const generatedLineMappings = rawMappings[generatedLine];
|
||||
for (const rawMapping of generatedLineMappings) {
|
||||
if (rawMapping.length >= 4) {
|
||||
const originalSource = sources[rawMapping[1] !];
|
||||
const originalSource = sources[rawMapping[1]!];
|
||||
if (originalSource === null || originalSource === undefined) {
|
||||
// the original source is missing so ignore this mapping
|
||||
continue;
|
||||
}
|
||||
const generatedColumn = rawMapping[0];
|
||||
const name = rawMapping.length === 5 ? rawMap.names[rawMapping[4]] : undefined;
|
||||
const line = rawMapping[2] !;
|
||||
const column = rawMapping[3] !;
|
||||
const line = rawMapping[2]!;
|
||||
const column = rawMapping[3]!;
|
||||
const generatedSegment: SegmentMarker = {
|
||||
line: generatedLine,
|
||||
column: generatedColumn,
|
||||
@ -361,7 +364,7 @@ export function extractOriginalSegments(mappings: Mapping[]): Map<SourceFile, Se
|
||||
if (!originalSegments.has(originalSource)) {
|
||||
originalSegments.set(originalSource, []);
|
||||
}
|
||||
const segments = originalSegments.get(originalSource) !;
|
||||
const segments = originalSegments.get(originalSource)!;
|
||||
segments.push(mapping.originalSegment);
|
||||
}
|
||||
originalSegments.forEach(segmentMarkers => segmentMarkers.sort(compareSegments));
|
||||
|
@ -6,7 +6,9 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {commentRegex, fromComment, mapFileCommentRegex} from 'convert-source-map';
|
||||
import {AbsoluteFsPath, FileSystem, absoluteFrom} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {absoluteFrom, AbsoluteFsPath, FileSystem} from '../../../src/ngtsc/file_system';
|
||||
|
||||
import {RawSourceMap} from './raw_source_map';
|
||||
import {SourceFile} from './source_file';
|
||||
|
||||
@ -51,8 +53,8 @@ export class SourceFileLoader {
|
||||
// Track source file paths if we have loaded them from disk so that we don't get into an
|
||||
// infinite recursion
|
||||
if (previousPaths.includes(sourcePath)) {
|
||||
throw new Error(
|
||||
`Circular source file mapping dependency: ${previousPaths.join(' -> ')} -> ${sourcePath}`);
|
||||
throw new Error(`Circular source file mapping dependency: ${
|
||||
previousPaths.join(' -> ')} -> ${sourcePath}`);
|
||||
}
|
||||
previousPaths = previousPaths.concat([sourcePath]);
|
||||
|
||||
@ -66,7 +68,7 @@ export class SourceFileLoader {
|
||||
|
||||
let map: RawSourceMap|null = null;
|
||||
let inline = true;
|
||||
let sources: (SourceFile | null)[] = [];
|
||||
let sources: (SourceFile|null)[] = [];
|
||||
if (mapAndPath !== null) {
|
||||
const basePath = mapAndPath.mapPath || sourcePath;
|
||||
sources = this.processSources(basePath, mapAndPath.map, previousPaths);
|
||||
@ -87,7 +89,7 @@ export class SourceFileLoader {
|
||||
private loadSourceMap(sourcePath: AbsoluteFsPath, contents: string): MapAndPath|null {
|
||||
const inline = commentRegex.exec(contents);
|
||||
if (inline !== null) {
|
||||
return {map: fromComment(inline.pop() !).sourcemap, mapPath: null};
|
||||
return {map: fromComment(inline.pop()!).sourcemap, mapPath: null};
|
||||
}
|
||||
|
||||
const external = mapFileCommentRegex.exec(contents);
|
||||
|
@ -6,7 +6,8 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import * as ts from 'typescript';
|
||||
import {AbsoluteFsPath, FileSystem, absoluteFrom} from '../../src/ngtsc/file_system';
|
||||
|
||||
import {absoluteFrom, AbsoluteFsPath, FileSystem} from '../../src/ngtsc/file_system';
|
||||
import {KnownDeclaration} from '../../src/ngtsc/reflection';
|
||||
|
||||
/**
|
||||
@ -37,11 +38,11 @@ export function getOriginalSymbol(checker: ts.TypeChecker): (symbol: ts.Symbol)
|
||||
};
|
||||
}
|
||||
|
||||
export function isDefined<T>(value: T | undefined | null): value is T {
|
||||
export function isDefined<T>(value: T|undefined|null): value is T {
|
||||
return (value !== undefined) && (value !== null);
|
||||
}
|
||||
|
||||
export function getNameText(name: ts.PropertyName | ts.BindingName): string {
|
||||
export function getNameText(name: ts.PropertyName|ts.BindingName): string {
|
||||
return ts.isIdentifier(name) || ts.isLiteralExpression(name) ? name.text : name.getText();
|
||||
}
|
||||
|
||||
@ -111,10 +112,12 @@ export class FactoryMap<K, V> {
|
||||
this.internalMap.set(key, this.factory(key));
|
||||
}
|
||||
|
||||
return this.internalMap.get(key) !;
|
||||
return this.internalMap.get(key)!;
|
||||
}
|
||||
|
||||
set(key: K, value: V): void { this.internalMap.set(key, value); }
|
||||
set(key: K, value: V): void {
|
||||
this.internalMap.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -5,15 +5,16 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {AbsoluteFsPath, FileSystem, PathSegment, absoluteFrom} from '../../../../src/ngtsc/file_system';
|
||||
import {absoluteFrom, AbsoluteFsPath, FileSystem, PathSegment} from '../../../../src/ngtsc/file_system';
|
||||
import {cleanPackageJson} from '../../packages/build_marker';
|
||||
import {NGCC_BACKUP_EXTENSION} from '../in_place_file_writer';
|
||||
import {NGCC_DIRECTORY} from '../new_entry_point_file_writer';
|
||||
|
||||
import {isLocalDirectory} from './utils';
|
||||
|
||||
/**
|
||||
* Implement this interface to extend the cleaning strategies of the `PackageCleaner`.
|
||||
*/
|
||||
* Implement this interface to extend the cleaning strategies of the `PackageCleaner`.
|
||||
*/
|
||||
export interface CleaningStrategy {
|
||||
canClean(path: AbsoluteFsPath, basename: PathSegment): boolean;
|
||||
clean(path: AbsoluteFsPath, basename: PathSegment): void;
|
||||
@ -44,7 +45,9 @@ export class NgccDirectoryCleaner implements CleaningStrategy {
|
||||
canClean(path: AbsoluteFsPath, basename: PathSegment): boolean {
|
||||
return basename === NGCC_DIRECTORY && isLocalDirectory(this.fs, path);
|
||||
}
|
||||
clean(path: AbsoluteFsPath, _basename: PathSegment): void { this.fs.removeDeep(path); }
|
||||
clean(path: AbsoluteFsPath, _basename: PathSegment): void {
|
||||
this.fs.removeDeep(path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -5,11 +5,12 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {FileSystem, absoluteFrom, dirname} from '../../../src/ngtsc/file_system';
|
||||
import {absoluteFrom, dirname, FileSystem} from '../../../src/ngtsc/file_system';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {EntryPointJsonProperty} from '../packages/entry_point';
|
||||
import {EntryPointBundle} from '../packages/entry_point_bundle';
|
||||
import {FileToWrite} from '../rendering/utils';
|
||||
|
||||
import {FileWriter} from './file_writer';
|
||||
|
||||
export const NGCC_BACKUP_EXTENSION = '.__ivy_ngcc_bak';
|
||||
@ -37,7 +38,9 @@ export class InPlaceFileWriter implements FileWriter {
|
||||
`Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`);
|
||||
} else {
|
||||
this.logger.error(
|
||||
`Tried to write ${backPath} with an ngcc back up file but it already exists so not writing, nor backing up, ${file.path}.\n` +
|
||||
`Tried to write ${
|
||||
backPath} with an ngcc back up file but it already exists so not writing, nor backing up, ${
|
||||
file.path}.\n` +
|
||||
`This error may be because two or more entry-points overlap and ngcc has been asked to process some files more than once.\n` +
|
||||
`You should check other entry-points in this package and set up a config to ignore any that you are not using.`);
|
||||
}
|
||||
|
@ -6,7 +6,7 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {AbsoluteFsPath, FileSystem, absoluteFromSourceFile, dirname, join, relative} from '../../../src/ngtsc/file_system';
|
||||
import {absoluteFromSourceFile, AbsoluteFsPath, dirname, FileSystem, join, relative} from '../../../src/ngtsc/file_system';
|
||||
import {isDtsPath} from '../../../src/ngtsc/util/src/typescript';
|
||||
import {Logger} from '../logging/logger';
|
||||
import {EntryPoint, EntryPointJsonProperty} from '../packages/entry_point';
|
||||
@ -83,8 +83,8 @@ export class NewEntryPointFileWriter extends InPlaceFileWriter {
|
||||
const packageJsonPath = join(entryPoint.path, 'package.json');
|
||||
|
||||
// All format properties point to the same format-path.
|
||||
const oldFormatProp = formatProperties[0] !;
|
||||
const oldFormatPath = packageJson[oldFormatProp] !;
|
||||
const oldFormatProp = formatProperties[0]!;
|
||||
const oldFormatPath = packageJson[oldFormatProp]!;
|
||||
const oldAbsFormatPath = join(entryPoint.path, oldFormatPath);
|
||||
const newAbsFormatPath = join(ngccFolder, relative(entryPoint.package, oldAbsFormatPath));
|
||||
const newFormatPath = relative(entryPoint.path, newAbsFormatPath);
|
||||
|
@ -6,12 +6,12 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AbsoluteFsPath, FileSystem, dirname} from '../../../src/ngtsc/file_system';
|
||||
import {AbsoluteFsPath, dirname, FileSystem} from '../../../src/ngtsc/file_system';
|
||||
import {JsonObject, JsonValue} from '../packages/entry_point';
|
||||
|
||||
|
||||
export type PackageJsonChange = [string[], JsonValue, PackageJsonPropertyPositioning];
|
||||
export type PackageJsonPropertyPositioning = 'unimportant' | 'alphabetic' | {before: string};
|
||||
export type PackageJsonPropertyPositioning = 'unimportant'|'alphabetic'|{before: string};
|
||||
export type WritePackageJsonChangesFn =
|
||||
(changes: PackageJsonChange[], packageJsonPath: AbsoluteFsPath, parsedJson?: JsonObject) =>
|
||||
void;
|
||||
|
Reference in New Issue
Block a user