fix(compiler-cli): update type castings for JSON.parse usage (#40710)

Update usages of JSON.parse to be cast as specific types.

PR Close #40710
This commit is contained in:
Joey Perrott 2021-02-04 14:35:14 -08:00 committed by Alex Rickabaugh
parent efd4149e9e
commit b75d7cb11f
24 changed files with 159 additions and 101 deletions

View File

@ -256,7 +256,7 @@ export function getEntryPointFormat(
function loadPackageJson(
fs: ReadonlyFileSystem, packageJsonPath: AbsoluteFsPath): EntryPointPackageJson|null {
try {
return JSON.parse(fs.readFile(packageJsonPath));
return JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
} catch {
return null;
}

View File

@ -13,7 +13,7 @@ import {EntryPointWithDependencies} from '../dependencies/dependency_host';
import {NGCC_VERSION} from './build_marker';
import {NgccConfiguration} from './configuration';
import {getEntryPointInfo, isEntryPoint} from './entry_point';
import {getEntryPointInfo, isEntryPoint, PackageJsonFormatProperties} from './entry_point';
/**
* Manages reading and writing a manifest file that contains a list of all the entry-points that
@ -197,3 +197,9 @@ export interface EntryPointManifestFile {
lockFileHash: string;
entryPointPaths: EntryPointPaths[];
}
/** The JSON format of the entrypoint properties. */
export type NewEntryPointPropertiesMap = {
[Property in PackageJsonFormatProperties as `${Property}_ivy_ngcc`]?: string;
};

View File

@ -7,6 +7,7 @@
*/
import {absoluteFrom, AbsoluteFsPath, FileSystem, PathSegment} from '../../../../src/ngtsc/file_system';
import {cleanPackageJson} from '../../packages/build_marker';
import {EntryPointPackageJson} from '../../packages/entry_point';
import {NGCC_BACKUP_EXTENSION} from '../in_place_file_writer';
import {NGCC_DIRECTORY} from '../new_entry_point_file_writer';
@ -30,7 +31,7 @@ export class PackageJsonCleaner implements CleaningStrategy {
return basename === 'package.json';
}
clean(path: AbsoluteFsPath, _basename: PathSegment): void {
const packageJson = JSON.parse(this.fs.readFile(path));
const packageJson = JSON.parse(this.fs.readFile(path)) as EntryPointPackageJson;
if (cleanPackageJson(packageJson)) {
this.fs.writeFile(path, `${JSON.stringify(packageJson, null, 2)}\n`);
}

View File

@ -103,11 +103,12 @@ export class NewEntryPointFileWriter extends InPlaceFileWriter {
const sourceMapPath = (originalSrcPath + '.map') as AbsoluteFsPath;
if (this.fs.exists(sourceMapPath)) {
try {
const sourceMap = JSON.parse(this.fs.readFile(sourceMapPath));
const sourceMap =
JSON.parse(this.fs.readFile(sourceMapPath)) as {sourceRoot: string, [key: string]: any};
const newSourceMapPath = (newSrcPath + '.map') as AbsoluteFsPath;
const relativePath =
this.fs.relative(this.fs.dirname(newSourceMapPath), this.fs.dirname(sourceMapPath));
sourceMap['sourceRoot'] = this.fs.join(relativePath, sourceMap['sourceRoot'] || '.');
sourceMap.sourceRoot = this.fs.join(relativePath, sourceMap.sourceRoot || '.');
this.fs.ensureDir(this.fs.dirname(newSourceMapPath));
this.fs.writeFile(newSourceMapPath, JSON.stringify(sourceMap));
} catch (e) {

View File

@ -130,8 +130,9 @@ export class DirectPackageJsonUpdater implements PackageJsonUpdater {
// Read and parse the `package.json` content.
// NOTE: We are not using `preExistingParsedJson` (even if specified) to avoid corrupting the
// content on disk in case `preExistingParsedJson` is outdated.
const parsedJson =
this.fs.exists(packageJsonPath) ? JSON.parse(this.fs.readFile(packageJsonPath)) : {};
const parsedJson = this.fs.exists(packageJsonPath) ?
JSON.parse(this.fs.readFile(packageJsonPath)) as JsonObject :
{};
// Apply all changes to both the canonical representation (read from disk) and any pre-existing,
// in-memory representation.

View File

@ -22,6 +22,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/logging/testing",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/sourcemaps",
"//packages/compiler-cli/src/ngtsc/testing",
"//packages/compiler-cli/src/ngtsc/transform",
"//packages/compiler-cli/src/ngtsc/translator",

View File

@ -210,7 +210,7 @@ runInEachFileSystem(() => {
// Modify the manifest to prove that we use it to find the entry-points
const manifestPath = _Abs('/sub_entry_points/node_modules/__ngcc_entry_points__.json');
const manifestFile: EntryPointManifestFile = JSON.parse(fs.readFile(manifestPath));
const manifestFile = JSON.parse(fs.readFile(manifestPath)) as EntryPointManifestFile;
manifestFile.entryPointPaths.pop();
fs.writeFile(manifestPath, JSON.stringify(manifestFile));

View File

@ -16,7 +16,7 @@ import {ModuleResolver} from '../../src/dependencies/module_resolver';
import {TargetedEntryPointFinder} from '../../src/entry_point_finder/targeted_entry_point_finder';
import {NGCC_VERSION} from '../../src/packages/build_marker';
import {NgccConfiguration, ProcessedNgccPackageConfig} from '../../src/packages/configuration';
import {EntryPoint} from '../../src/packages/entry_point';
import {EntryPoint, EntryPointPackageJson} from '../../src/packages/entry_point';
import {PathMappings} from '../../src/path_mappings';
runInEachFileSystem(() => {
@ -555,7 +555,7 @@ runInEachFileSystem(() => {
// Add a build marker to the package.json
const packageJsonPath = _Abs(`${targetPath}/package.json`);
const packageJson = JSON.parse(fs.readFile(packageJsonPath));
const packageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
packageJson.__processed_by_ivy_ngcc__ = {
esm5: NGCC_VERSION,
};
@ -579,7 +579,7 @@ runInEachFileSystem(() => {
// Add build markers to the package.json
const packageJsonPath = _Abs(`${targetPath}/package.json`);
const packageJson = JSON.parse(fs.readFile(packageJsonPath));
const packageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
packageJson.__processed_by_ivy_ngcc__ = {
fesm2015: NGCC_VERSION,
esm5: NGCC_VERSION,
@ -625,7 +625,7 @@ runInEachFileSystem(() => {
// Add build markers to the package.json
const packageJsonPath = _Abs(`${targetPath}/package.json`);
const packageJson = JSON.parse(fs.readFile(packageJsonPath));
const packageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
packageJson.__processed_by_ivy_ngcc__ = {
esm5: NGCC_VERSION,
};
@ -651,7 +651,7 @@ runInEachFileSystem(() => {
// Add build markers to the package.json
const packageJsonPath = _Abs(`${targetPath}/package.json`);
const packageJson = JSON.parse(fs.readFile(packageJsonPath));
const packageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
packageJson.__processed_by_ivy_ngcc__ = {
fesm2015: NGCC_VERSION,
};

View File

@ -63,7 +63,7 @@ runInEachFileSystem(() => {
function setupAngularCoreEsm5() {
const pkgPath = _('/node_modules/@angular/core');
const pkgJsonPath = fs.join(pkgPath, 'package.json');
const pkgJson = JSON.parse(fs.readFile(pkgJsonPath));
const pkgJson = JSON.parse(fs.readFile(pkgJsonPath)) as EntryPointPackageJson;
fs.ensureDir(fs.join(pkgPath, 'fesm5'));
fs.writeFile(
@ -1390,12 +1390,13 @@ runInEachFileSystem(() => {
{basePath: '/node_modules', propertiesToConsider: ['main'], logger: new MockLogger()});
// Check that common/testing ES5 was processed
let commonTesting =
JSON.parse(fs.readFile(_('/node_modules/@angular/common/testing/package.json')));
JSON.parse(fs.readFile(_('/node_modules/@angular/common/testing/package.json'))) as
EntryPointPackageJson;
expect(hasBeenProcessed(commonTesting, 'main')).toBe(true);
expect(hasBeenProcessed(commonTesting, 'esm2015')).toBe(false);
// Modify the manifest to test that is has no effect
let manifest: EntryPointManifestFile =
JSON.parse(fs.readFile(_('/node_modules/__ngcc_entry_points__.json')));
let manifest = JSON.parse(fs.readFile(_('/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
manifest.entryPointPaths =
manifest.entryPointPaths.filter(paths => paths[1] !== '@angular/common/testing');
fs.writeFile(_('/node_modules/__ngcc_entry_points__.json'), JSON.stringify(manifest));
@ -1409,12 +1410,14 @@ runInEachFileSystem(() => {
});
// Check that common/testing ES2015 is now processed, despite the manifest not listing it
commonTesting =
JSON.parse(fs.readFile(_('/node_modules/@angular/common/testing/package.json')));
JSON.parse(fs.readFile(_('/node_modules/@angular/common/testing/package.json'))) as
EntryPointPackageJson;
expect(hasBeenProcessed(commonTesting, 'main')).toBe(true);
expect(hasBeenProcessed(commonTesting, 'esm2015')).toBe(true);
// Check that the newly computed manifest has written to disk, containing the path that we
// had removed earlier.
manifest = JSON.parse(fs.readFile(_('/node_modules/__ngcc_entry_points__.json')));
manifest = JSON.parse(fs.readFile(_('/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
expect(manifest.entryPointPaths).toContain([
'@angular/common',
'@angular/common/testing',
@ -2248,7 +2251,8 @@ runInEachFileSystem(() => {
function loadPackage(
packageName: string, basePath: AbsoluteFsPath = _('/node_modules')): EntryPointPackageJson {
return JSON.parse(fs.readFile(fs.resolve(basePath, packageName, 'package.json')));
return JSON.parse(fs.readFile(fs.resolve(basePath, packageName, 'package.json'))) as
EntryPointPackageJson;
}
function initMockFileSystem(fs: FileSystem, testFiles: Folder) {

View File

@ -85,48 +85,49 @@ runInEachFileSystem(() => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
// TODO: Determine the correct/best type for the `pkg` type.
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__).toBeUndefined();
expect(pkg.scripts).toBeUndefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015', 'fesm5']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
expect(pkg.__processed_by_ivy_ngcc__.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.esm2015).toBeUndefined();
expect(pkg.__processed_by_ivy_ngcc__.esm5).toBeUndefined();
expect(pkg.scripts.prepublishOnly).toBeDefined();
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBeUndefined();
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBeUndefined();
expect(pkg.scripts!.prepublishOnly).toBeDefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['esm2015', 'esm5']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
expect(pkg.__processed_by_ivy_ngcc__.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.esm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.esm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.scripts.prepublishOnly).toBeDefined();
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.scripts!.prepublishOnly).toBeDefined();
});
it('should update the packageJson object in-place', () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
const pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
const pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.__processed_by_ivy_ngcc__).toBeUndefined();
expect(pkg.scripts).toBeUndefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015', 'fesm5']);
expect(pkg.__processed_by_ivy_ngcc__.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.esm2015).toBeUndefined();
expect(pkg.__processed_by_ivy_ngcc__.esm5).toBeUndefined();
expect(pkg.scripts.prepublishOnly).toBeDefined();
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBeUndefined();
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBeUndefined();
expect(pkg.scripts!.prepublishOnly).toBeDefined();
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['esm2015', 'esm5']);
expect(pkg.__processed_by_ivy_ngcc__.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.esm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__.esm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.scripts.prepublishOnly).toBeDefined();
expect(pkg.__processed_by_ivy_ngcc__!.fesm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.fesm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm2015).toBe('0.0.0-PLACEHOLDER');
expect(pkg.__processed_by_ivy_ngcc__!.esm5).toBe('0.0.0-PLACEHOLDER');
expect(pkg.scripts!.prepublishOnly).toBeDefined();
});
it('should one perform one write operation for all updated properties', () => {
@ -134,7 +135,7 @@ runInEachFileSystem(() => {
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
const writeFileSpy = spyOn(fs, 'writeFile');
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
markAsProcessed(
pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015', 'fesm5', 'esm2015', 'esm5']);
@ -146,34 +147,34 @@ runInEachFileSystem(() => {
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
const prepublishOnly = 'existing script';
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
pkg.scripts = {prepublishOnly};
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
expect(pkg.scripts.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts.prepublishOnly__ivy_ngcc_bak).toBe(prepublishOnly);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.scripts!.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts!.prepublishOnly__ivy_ngcc_bak).toBe(prepublishOnly);
});
it(`should not keep backup of overwritten 'prepublishOnly' script`, () => {
const COMMON_PACKAGE_PATH = _('/node_modules/@angular/common/package.json');
const fs = getFileSystem();
const pkgUpdater = new DirectPackageJsonUpdater(fs);
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
let pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
expect(pkg.scripts.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts.prepublishOnly__ivy_ngcc_bak).toBeUndefined();
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.scripts!.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts!.prepublishOnly__ivy_ngcc_bak).toBeUndefined();
// Running again, now that there is `prepublishOnly` script (created by `ngcc`), it should
// still not back it up as `prepublishOnly__ivy_ngcc_bak`.
markAsProcessed(pkgUpdater, pkg, COMMON_PACKAGE_PATH, ['fesm2015']);
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH));
expect(pkg.scripts.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts.prepublishOnly__ivy_ngcc_bak).toBeUndefined();
pkg = JSON.parse(fs.readFile(COMMON_PACKAGE_PATH)) as EntryPointPackageJson;
expect(pkg.scripts!.prepublishOnly).toContain('This is not allowed');
expect(pkg.scripts!.prepublishOnly__ivy_ngcc_bak).toBeUndefined();
});
});

View File

@ -10,7 +10,7 @@ import {createHash} from 'crypto';
import {absoluteFrom, getFileSystem, ReadonlyFileSystem} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {loadTestFiles} from '../../../src/ngtsc/testing';
import {DEFAULT_NGCC_CONFIG, NgccConfiguration, ProcessLockingConfiguration} from '../../src/packages/configuration';
import {DEFAULT_NGCC_CONFIG, NgccConfiguration, NgccProjectConfig, ProcessLockingConfiguration, RawNgccPackageConfig} from '../../src/packages/configuration';
runInEachFileSystem(() => {
@ -567,7 +567,9 @@ runInEachFileSystem(() => {
entryPoints: {'./default-level-entry-point': {}},
};
});
afterEach(() => DEFAULT_NGCC_CONFIG.packages = JSON.parse(originalDefaultConfig));
afterEach(
() => DEFAULT_NGCC_CONFIG.packages =
JSON.parse(originalDefaultConfig) as NgccProjectConfig['packages']);
it('should return configuration for a package found in the default config', () => {
const readFileSpy = spyOn(fs, 'readFile').and.callThrough();

View File

@ -265,16 +265,18 @@ runInEachFileSystem(() => {
it('should write the ngcc version', () => {
fs.writeFile(_Abs('/project/yarn.lock'), 'LOCK FILE CONTENTS');
manifest.writeEntryPointManifest(_Abs('/project/node_modules'), []);
const file: EntryPointManifestFile =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json')));
const file =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
expect(file.ngccVersion).toEqual(NGCC_VERSION);
});
it('should write a hash of the yarn.lock file', () => {
fs.writeFile(_Abs('/project/yarn.lock'), 'LOCK FILE CONTENTS');
manifest.writeEntryPointManifest(_Abs('/project/node_modules'), []);
const file: EntryPointManifestFile =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json')));
const file =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
expect(file.lockFileHash)
.toEqual(createHash('md5').update('LOCK FILE CONTENTS').digest('hex'));
});
@ -282,8 +284,9 @@ runInEachFileSystem(() => {
it('should write a hash of the package-lock.json file', () => {
fs.writeFile(_Abs('/project/package-lock.json'), 'LOCK FILE CONTENTS');
manifest.writeEntryPointManifest(_Abs('/project/node_modules'), []);
const file: EntryPointManifestFile =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json')));
const file =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
expect(file.lockFileHash)
.toEqual(createHash('md5').update('LOCK FILE CONTENTS').digest('hex'));
});
@ -291,8 +294,9 @@ runInEachFileSystem(() => {
it('should write a hash of the project config', () => {
fs.writeFile(_Abs('/project/package-lock.json'), 'LOCK FILE CONTENTS');
manifest.writeEntryPointManifest(_Abs('/project/node_modules'), []);
const file: EntryPointManifestFile =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json')));
const file =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
expect(file.configFileHash).toEqual(config.hash);
});
@ -329,8 +333,9 @@ runInEachFileSystem(() => {
}
};
manifest.writeEntryPointManifest(_Abs('/project/node_modules'), [entryPoint1, entryPoint2]);
const file: EntryPointManifestFile =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json')));
const file =
JSON.parse(fs.readFile(_Abs('/project/node_modules/__ngcc_entry_points__.json'))) as
EntryPointManifestFile;
expect(file.entryPointPaths).toEqual([
[
'package-1',

View File

@ -11,7 +11,7 @@ import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {MockLogger} from '../../../src/ngtsc/logging/testing';
import {loadTestFiles} from '../../../src/ngtsc/testing';
import {NgccConfiguration, ProcessedNgccPackageConfig} from '../../src/packages/configuration';
import {EntryPoint, EntryPointJsonProperty, getEntryPointFormat, getEntryPointInfo, IGNORED_ENTRY_POINT, INCOMPATIBLE_ENTRY_POINT, isEntryPoint, NO_ENTRY_POINT, SUPPORTED_FORMAT_PROPERTIES} from '../../src/packages/entry_point';
import {EntryPoint, EntryPointJsonProperty, EntryPointPackageJson, getEntryPointFormat, getEntryPointInfo, IGNORED_ENTRY_POINT, INCOMPATIBLE_ENTRY_POINT, isEntryPoint, NO_ENTRY_POINT, SUPPORTED_FORMAT_PROPERTIES} from '../../src/packages/entry_point';
runInEachFileSystem(() => {
describe('getEntryPointInfo()', () => {
@ -116,8 +116,8 @@ runInEachFileSystem(() => {
]);
const config = new NgccConfiguration(fs, _('/project'));
const info: EntryPoint =
getEntryPointInfo(fs, config, new MockLogger(), SOME_PACKAGE, entryPointPath) as any;
const info = getEntryPointInfo(fs, config, new MockLogger(), SOME_PACKAGE, entryPointPath) as
EntryPoint;
expect(info.packageJson).toEqual(jasmine.objectContaining({packageVersion: '1'}));
});
@ -159,8 +159,8 @@ runInEachFileSystem(() => {
]);
const config = new NgccConfiguration(fs, _('/project'));
const info: EntryPoint =
getEntryPointInfo(fs, config, new MockLogger(), SOME_PACKAGE, entryPointPath) as any;
const info = getEntryPointInfo(fs, config, new MockLogger(), SOME_PACKAGE, entryPointPath) as
EntryPoint;
expect(info.packageJson).toEqual(jasmine.objectContaining({packageVersion: '3'}));
});
@ -233,7 +233,8 @@ runInEachFileSystem(() => {
]);
const config = new NgccConfiguration(fs, _('/project'));
const override =
JSON.parse(createPackageJson('missing_package_json', {excludes: ['name']}));
JSON.parse(createPackageJson('missing_package_json', {excludes: ['name']})) as
Partial<EntryPointPackageJson>;
spyOn(config, 'getPackageConfig')
.and.returnValue(new ProcessedNgccPackageConfig(
fs, _('/project/node_modules/some_package/'),
@ -762,7 +763,7 @@ export function createPackageJson(
typingsIsArray?: boolean,
version?: string
} = {}): string {
const packageJson: any = {
const packageJson: EntryPointPackageJson = {
name: (entryPointName === '') ? 'some_package' : `some_package/${entryPointName}`,
version,
[typingsProp]: typingsIsArray ? [`./${entryPointName}.d.ts`] : `./${entryPointName}.d.ts`,
@ -782,5 +783,6 @@ export function createPackageJson(
}
export function loadPackageJson(fs: ReadonlyFileSystem, packagePath: string) {
return JSON.parse(fs.readFile(fs.resolve(packagePath + '/package.json')));
return JSON.parse(fs.readFile(fs.resolve(packagePath + '/package.json'))) as
EntryPointPackageJson;
}

View File

@ -641,7 +641,8 @@ UndecoratedBase.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: UndecoratedBase, vie
expect(sourceFile.contents)
.toEqual(RENDERED_CONTENTS + '\n' + generateMapFileComment('file.js.map'));
expect(mapFile.path).toEqual(_('/node_modules/test-package/src/file.js.map'));
expect(JSON.parse(mapFile.contents)).toEqual(MERGED_OUTPUT_PROGRAM_MAP.toObject());
expect(JSON.parse(mapFile.contents) as any)
.toEqual(MERGED_OUTPUT_PROGRAM_MAP.toObject());
});

View File

@ -47,7 +47,7 @@ runInEachFileSystem(() => {
fs.ensureDir(fs.dirname(packageJsonPath));
fs.writeFile(packageJsonPath, JSON.stringify(packageJson));
strategy.clean(packageJsonPath, fs.basename(packageJsonPath));
const newPackageJson: EntryPointPackageJson = JSON.parse(fs.readFile(packageJsonPath));
const newPackageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
expect(newPackageJson).toEqual({name: 'test-package'});
});
@ -60,7 +60,7 @@ runInEachFileSystem(() => {
fs.ensureDir(fs.dirname(packageJsonPath));
fs.writeFile(packageJsonPath, JSON.stringify(packageJson));
strategy.clean(packageJsonPath, fs.basename(packageJsonPath));
const newPackageJson: EntryPointPackageJson = JSON.parse(fs.readFile(packageJsonPath));
const newPackageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
expect(newPackageJson).toEqual({name: 'test-package'});
});
@ -73,7 +73,7 @@ runInEachFileSystem(() => {
fs.ensureDir(fs.dirname(packageJsonPath));
fs.writeFile(packageJsonPath, JSON.stringify(packageJson));
strategy.clean(packageJsonPath, fs.basename(packageJsonPath));
const newPackageJson: EntryPointPackageJson = JSON.parse(fs.readFile(packageJsonPath));
const newPackageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
expect(newPackageJson).toEqual({name: 'test-package'});
});
@ -87,7 +87,7 @@ runInEachFileSystem(() => {
fs.ensureDir(fs.dirname(packageJsonPath));
fs.writeFile(packageJsonPath, JSON.stringify(packageJson));
strategy.clean(packageJsonPath, fs.basename(packageJsonPath));
const newPackageJson: EntryPointPackageJson = JSON.parse(fs.readFile(packageJsonPath));
const newPackageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
expect(newPackageJson).toEqual({
name: 'test-package',
scripts: {test: 'do testing'},
@ -109,7 +109,8 @@ runInEachFileSystem(() => {
fs.ensureDir(fs.dirname(packageJsonPath));
fs.writeFile(packageJsonPath, JSON.stringify(packageJson));
strategy.clean(packageJsonPath, fs.basename(packageJsonPath));
const newPackageJson: EntryPointPackageJson = JSON.parse(fs.readFile(packageJsonPath));
const newPackageJson =
JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
expect(newPackageJson).toEqual({
name: 'test-package',
scripts: {prepublishOnly: 'original', test: 'do testing'},
@ -129,7 +130,7 @@ runInEachFileSystem(() => {
fs.ensureDir(fs.dirname(packageJsonPath));
fs.writeFile(packageJsonPath, JSON.stringify(packageJson));
strategy.clean(packageJsonPath, fs.basename(packageJsonPath));
const newPackageJson: EntryPointPackageJson = JSON.parse(fs.readFile(packageJsonPath));
const newPackageJson = JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
expect(newPackageJson).toEqual({
name: 'test-package',
scripts: {

View File

@ -8,10 +8,12 @@
import {absoluteFrom, FileSystem, getFileSystem} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {MockLogger} from '../../../src/ngtsc/logging/testing';
import {RawSourceMap} from '../../../src/ngtsc/sourcemaps';
import {loadTestFiles} from '../../../src/ngtsc/testing';
import {NgccConfiguration} from '../../src/packages/configuration';
import {EntryPoint, EntryPointFormat, EntryPointJsonProperty, getEntryPointInfo, isEntryPoint} from '../../src/packages/entry_point';
import {EntryPointBundle, makeEntryPointBundle} from '../../src/packages/entry_point_bundle';
import {NewEntryPointPropertiesMap} from '../../src/packages/entry_point_manifest';
import {createModuleResolutionCache, SharedFileCache} from '../../src/packages/source_file_cache';
import {FileWriter} from '../../src/writing/file_writer';
import {NewEntryPointFileWriter} from '../../src/writing/new_entry_point_file_writer';
@ -184,7 +186,9 @@ runInEachFileSystem(() => {
}];
fileWriter.writeBundle(esm2015bundle, modifiedFiles, ['es2015']);
expect(JSON.parse(fs.readFile(_('/node_modules/test/__ivy_ngcc__/es2015/index.js.map'))))
expect(
JSON.parse(fs.readFile(_('/node_modules/test/__ivy_ngcc__/es2015/index.js.map'))) as
Partial<RawSourceMap>)
.toEqual({...sourceMap, sourceRoot: '../../es2015'});
});
@ -213,7 +217,9 @@ runInEachFileSystem(() => {
}];
fileWriter.writeBundle(esm2015bundle, modifiedFiles, ['es2015']);
expect(JSON.parse(fs.readFile(_('/node_modules/test/__ivy_ngcc__/es2015/index.js.map'))))
expect(
JSON.parse(fs.readFile(_('/node_modules/test/__ivy_ngcc__/es2015/index.js.map'))) as
Partial<RawSourceMap>)
.toEqual({...sourceMap, sourceRoot: '../../src'});
});
@ -678,7 +684,8 @@ runInEachFileSystem(() => {
},
],
['fesm5', 'module']);
const packageJsonFromFile1 = JSON.parse(fs.readFile(packageJsonPath));
const packageJsonFromFile1 =
JSON.parse(fs.readFile(packageJsonPath)) as NewEntryPointPropertiesMap;
expect(entryPoint.packageJson).toEqual(jasmine.objectContaining({
fesm5_ivy_ngcc: '__ivy_ngcc__/esm5.js',
@ -698,7 +705,8 @@ runInEachFileSystem(() => {
esm5bundle.entryPoint,
[_('/node_modules/test/index.d.ts'), _('/node_modules/test/index.d.ts.map')],
['fesm5', 'module']);
const packageJsonFromFile2 = JSON.parse(fs.readFile(packageJsonPath));
const packageJsonFromFile2 =
JSON.parse(fs.readFile(packageJsonPath)) as NewEntryPointPropertiesMap;
expect(entryPoint.packageJson).toEqual(jasmine.objectContaining({
fesm5: './esm5.js',

View File

@ -18,7 +18,7 @@ runInEachFileSystem(() => {
let updater: PackageJsonUpdater;
// Helpers
const readJson = (path: AbsoluteFsPath) => JSON.parse(fs.readFile(path));
const readJson = <T>(path: AbsoluteFsPath) => JSON.parse(fs.readFile(path)) as T;
beforeEach(() => {
_ = absoluteFrom;
@ -55,7 +55,7 @@ runInEachFileSystem(() => {
{name: jsonPath, contents: '{"foo": true, "bar": {"baz": "OK"}}'},
]);
const pkg = readJson(jsonPath);
const pkg = readJson<{foo: boolean, bar: {baz: string | number}}>(jsonPath);
const update = updater.createUpdate().addChange(['foo'], false).addChange(['bar', 'baz'], 42);
// Not updated yet.
@ -95,7 +95,7 @@ runInEachFileSystem(() => {
{name: jsonPath, contents: '{"foo": {}}'},
]);
const pkg = readJson(jsonPath);
const pkg = readJson<{foo: {bar: {baz: {qux: string}}}}>(jsonPath);
updater.createUpdate()
.addChange(['foo', 'bar', 'baz', 'qux'], 'updated')
.writeChanges(jsonPath, pkg);

View File

@ -226,7 +226,7 @@ export class SourceFileLoader {
*/
private readRawSourceMap(mapPath: AbsoluteFsPath): RawSourceMap {
this.trackPath(mapPath);
return JSON.parse(this.fs.readFile(mapPath));
return JSON.parse(this.fs.readFile(mapPath)) as RawSourceMap;
}
/**

View File

@ -584,13 +584,15 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
if (this.originalFileExists(packageFile)) {
// Once we see a package.json file, assume false until it we find the bundle index.
result = false;
const packageContent: any = JSON.parse(assert(this.context.readFile(packageFile)));
const packageContent =
JSON.parse(assert(this.context.readFile(packageFile))) as {typings: string};
if (packageContent.typings) {
const typings = path.normalize(path.join(directory, packageContent.typings));
if (DTS.test(typings)) {
const metadataFile = typings.replace(DTS, '.metadata.json');
if (this.originalFileExists(metadataFile)) {
const metadata = JSON.parse(assert(this.context.readFile(metadataFile)));
const metadata = JSON.parse(assert(this.context.readFile(metadataFile))) as
{flatModuleIndexRedirect: string, importAs: string};
if (metadata.flatModuleIndexRedirect) {
this.flatModuleIndexRedirectNames.add(typings);
// Note: don't set result = true,

View File

@ -70,8 +70,9 @@ function readMetadataFile(host: MetadataReaderHost, dtsFilePath: string): Module
return undefined;
}
try {
const metadataOrMetadatas = JSON.parse(host.readFile(metadataPath));
const metadatas: ModuleMetadata[] = metadataOrMetadatas ?
const metadataOrMetadatas =
JSON.parse(host.readFile(metadataPath)) as ModuleMetadata | ModuleMetadata[] | undefined;
const metadatas = metadataOrMetadatas ?
(Array.isArray(metadataOrMetadatas) ? metadataOrMetadatas : [metadataOrMetadatas]) :
[];
if (metadatas.length) {

View File

@ -60,7 +60,7 @@ function linkPartials(fileSystem: FileSystem, test: ComplianceTest): CompileResu
const source = fileSystem.readFile(fileName);
const sourceMapPath = fileSystem.resolve(fileName + '.map');
const sourceMap = fileSystem.exists(sourceMapPath) ?
JSON.parse(fileSystem.readFile(sourceMapPath)) :
JSON.parse(fileSystem.readFile(sourceMapPath)) as RawSourceMap :
undefined;
const {linkedSource, linkedSourceMap} =
applyLinker(builtDirectory, fileName, source, sourceMap, linkerPlugin);

View File

@ -55,9 +55,9 @@ export function* getComplianceTests(testConfigPath: string): Generator<Complianc
}
function loadTestCasesFile(
fs: ReadonlyFileSystem, testCasesPath: AbsoluteFsPath, basePath: AbsoluteFsPath): any {
fs: ReadonlyFileSystem, testCasesPath: AbsoluteFsPath, basePath: AbsoluteFsPath) {
try {
return JSON.parse(fs.readFile(testCasesPath));
return JSON.parse(fs.readFile(testCasesPath)) as {cases: TestCaseJson | TestCaseJson[]};
} catch (e) {
throw new Error(
`Failed to load test-cases at "${fs.relative(basePath, testCasesPath)}":\n ${e.message}`);
@ -298,3 +298,24 @@ export type ExtraCheck = (string|[string, ...any]);
* Options to pass to configure the compiler.
*/
export type ConfigOptions = Record<string, string|boolean|null>;
/**
* Interface espressing the type for the json object found at ../test_cases/test_case_schema.json.
*/
export interface TestCaseJson {
description: string;
compilationModeFilter?: ('fulll compile'|'linked compile')[];
inputFiles?: string[];
expectations?: {
failureMessage?: string;
files?: ExpectedFile[] | string;
expectedErrors?: {message: string, location?: string};
extraChecks?: (string | string[])[];
};
compilerOptions?: ConfigOptions;
angularCompilerOptions?: ConfigOptions;
focusTest?: boolean;
excludeTest?: boolean;
}

View File

@ -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 {MappingItem, SourceMapConsumer} from 'source-map';
import {MappingItem, RawSourceMap, SourceMapConsumer} from 'source-map';
import {NgtscTestEnvironment} from './env';
class TestSourceFile {
@ -72,7 +72,7 @@ export function getMappedSegments(
const mappings: MappingItem[] = [];
const mapContents = env.getContents(sourceMapFileName);
const sourceMapConsumer = new SourceMapConsumer(JSON.parse(mapContents));
const sourceMapConsumer = new SourceMapConsumer(JSON.parse(mapContents) as RawSourceMap);
sourceMapConsumer.eachMapping(item => {
if (!sources.has(item.source)) {
sources.set(item.source, new TestSourceFile(item.source, env.getContents(item.source)));

View File

@ -518,7 +518,7 @@ describe('TypeScriptNodeEmitter', () => {
const sourceMapBase64 = sourceMapMatch![1];
const sourceMapBuffer = Buffer.from(sourceMapBase64, 'base64');
const sourceMapText = sourceMapBuffer.toString('utf8');
const sourceMapParsed = JSON.parse(sourceMapText);
const sourceMapParsed = JSON.parse(sourceMapText) as unknown;
const consumer = new sourceMap.SourceMapConsumer(sourceMapParsed);
const mappings: any[] = [];
consumer.eachMapping((mapping: any) => {