chore: remove some instances of TS any (#11661)

This commit is contained in:
Nikolay Vitkov 2024-01-11 15:26:02 +01:00 committed by GitHub
parent cf879b82f6
commit 864ebc86c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 80 additions and 94 deletions

View File

@ -25,10 +25,14 @@
"*.tsbuildinfo"
]
},
"build:test": {
"command": "tsc -b test/tsconfig.json"
},
"unit": {
"command": "node --test --test-reporter spec test/build",
"dependencies": [
"build"
"build",
"build:test"
]
}
},

View File

@ -76,7 +76,7 @@ function updateExecutablePath(command: string, root?: string) {
async function executeCommand(
context: BuilderContext,
command: string[],
env: Record<string, any> = {}
env: NodeJS.ProcessEnv = {}
) {
let project: JsonObject;
if (context.target) {

View File

@ -23,10 +23,10 @@ export function config(): Rule {
}
function addPuppeteerConfig(): Rule {
return (tree: Tree, context: SchematicContext) => {
return (_tree: Tree, context: SchematicContext) => {
context.logger.debug('Adding Puppeteer config file.');
return addFilesSingle(tree, context, '', {root: ''} as AngularProject, {
return addFilesSingle('', {root: ''} as AngularProject, {
// No-op here to fill types
options: {
testRunner: TestRunner.Jasmine,

View File

@ -101,8 +101,6 @@ function addE2EFile(options: SchematicsSpec): Rule {
context.logger.debug('Creating Spec file.');
return addCommonFiles(
tree,
context,
{[foundProject[0]]: foundProject[1]} as Record<string, AngularProject>,
{
options: {

View File

@ -102,7 +102,7 @@ function addCommonFiles(options: SchematicsOptions): Rule {
context.logger.debug('Adding Puppeteer base files.');
const projects = getApplicationProjects(tree);
return addCommonFilesHelper(tree, context, projects, {
return addCommonFilesHelper(projects, {
options: {
...options,
port: DEFAULT_PORT,
@ -117,7 +117,7 @@ function addOtherFiles(options: SchematicsOptions): Rule {
context.logger.debug('Adding Puppeteer additional files.');
const projects = getApplicationProjects(tree);
return addFrameworkFiles(tree, context, projects, {
return addFrameworkFiles(projects, {
options: {
...options,
port: DEFAULT_PORT,

View File

@ -7,9 +7,8 @@
import {relative, resolve} from 'path';
import {getSystemPath, normalize, strings} from '@angular-devkit/core';
import type {Rule} from '@angular-devkit/schematics';
import {
type SchematicContext,
type Tree,
apply,
applyTemplates,
chain,
@ -35,31 +34,21 @@ export interface FilesOptions {
}
export function addFilesToProjects(
tree: Tree,
context: SchematicContext,
projects: Record<string, AngularProject>,
options: FilesOptions
): any {
): Rule {
return chain(
Object.keys(projects).map(name => {
return addFilesSingle(
tree,
context,
name,
projects[name] as AngularProject,
options
);
return addFilesSingle(name, projects[name] as AngularProject, options);
})
)(tree, context);
);
}
export function addFilesSingle(
_tree: Tree,
_context: SchematicContext,
name: string,
project: AngularProject,
{options, applyPath, movePath, relativeToWorkspacePath}: FilesOptions
): any {
): Rule {
const projectPath = resolve(getSystemPath(normalize(project.root)));
const workspacePath = resolve(getSystemPath(normalize('')));
@ -87,7 +76,7 @@ export function addFilesSingle(
);
}
function getProjectBaseUrl(project: any, port: number): string {
function getProjectBaseUrl(project: AngularProject, port: number): string {
let options = {protocol: 'http', port, host: 'localhost'};
if (project.architect?.serve?.options) {
@ -119,26 +108,22 @@ function getTsConfigPath(project: AngularProject): string {
}
export function addCommonFiles(
tree: Tree,
context: SchematicContext,
projects: Record<string, AngularProject>,
filesOptions: Omit<FilesOptions, 'applyPath' | 'relativeToWorkspacePath'>
): any {
): Rule {
const options: FilesOptions = {
...filesOptions,
applyPath: './files/common',
relativeToWorkspacePath: `/`,
};
return addFilesToProjects(tree, context, projects, options);
return addFilesToProjects(projects, options);
}
export function addFrameworkFiles(
tree: Tree,
context: SchematicContext,
projects: Record<string, AngularProject>,
filesOptions: Omit<FilesOptions, 'applyPath' | 'relativeToWorkspacePath'>
): any {
): Rule {
const testRunner = filesOptions.options.testRunner;
const options: FilesOptions = {
...filesOptions,
@ -146,7 +131,7 @@ export function addFrameworkFiles(
relativeToWorkspacePath: `/`,
};
return addFilesToProjects(tree, context, projects, options);
return addFilesToProjects(projects, options);
}
export function hasE2ETester(

View File

@ -11,7 +11,7 @@ import type {AngularJson, AngularProject} from './types.js';
export function getJsonFileAsObject(
tree: Tree,
path: string
): Record<string, any> {
): Record<string, unknown> {
try {
const buffer = tree.read(path) as Buffer;
const content = buffer.toString();
@ -21,12 +21,12 @@ export function getJsonFileAsObject(
}
}
export function getObjectAsJson(object: Record<string, any>): string {
export function getObjectAsJson(object: Record<string, unknown>): string {
return JSON.stringify(object, null, 2);
}
export function getAngularConfig(tree: Tree): AngularJson {
return getJsonFileAsObject(tree, './angular.json') as AngularJson;
return getJsonFileAsObject(tree, './angular.json') as unknown as AngularJson;
}
export function getApplicationProjects(

View File

@ -39,7 +39,7 @@ export function getPackageLatestNpmVersion(name: string): Promise<NodePackage> {
return get(`https://registry.npmjs.org/${name}`, res => {
let data = '';
res.on('data', (chunk: any) => {
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
@ -183,7 +183,7 @@ export function updateAngularJsonScripts(
);
});
tree.overwrite('./angular.json', getObjectAsJson(angularJson));
tree.overwrite('./angular.json', getObjectAsJson(angularJson as any));
return tree;
}

View File

@ -28,6 +28,12 @@ export interface AngularProject {
architect: {
e2e?: PuppeteerSchematicsConfig;
puppeteer?: PuppeteerSchematicsConfig;
serve: {
options: {
ssl: string;
port: number;
};
};
};
}
export interface AngularJson {

View File

@ -35,7 +35,7 @@ export function setupHttpHooks(): void {
before(() => {
const httpsGetStub = sinon.stub(https, 'get');
httpsGetStub.returns({
on: (_: any, callback: () => void) => {
on: (_: string, callback: () => void) => {
callback();
},
} as any);
@ -83,7 +83,7 @@ export function getMultiLibraryFile(file: string): string {
export async function buildTestingTree(
command: 'ng-add' | 'e2e' | 'config',
type: 'single' | 'multi' = 'single',
userOptions?: Record<string, any>
userOptions?: Record<string, unknown>
): Promise<UnitTestTree> {
const runner = new SchematicTestRunner(
'schematics',

View File

@ -0,0 +1,10 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"rootDir": "src/",
"outDir": "build/",
"types": ["node"]
},
"include": ["src/**/*"],
"references": [{"path": "../tsconfig.json"}]
}

View File

@ -13,6 +13,5 @@
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["src/**/files/**/*"],
"references": [{"path": "./tsconfig.test.json"}]
"exclude": ["src/**/files/**/*"]
}

View File

@ -1,10 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": "test/src/",
"outDir": "test/build/",
"types": ["node"]
},
"include": ["test/src/**/*"],
"exclude": ["test/build/**/*"]
}

View File

@ -166,7 +166,7 @@ class CDPClientAdapter<T extends CDPSession | CdpConnection>
this.#closed = true;
}
isCloseError(error: any): boolean {
isCloseError(error: unknown): boolean {
return error instanceof TargetCloseError;
}
}
@ -177,7 +177,9 @@ class CDPClientAdapter<T extends CDPSession | CdpConnection>
* @internal
*/
class NoOpTransport
extends BidiMapper.EventEmitter<any>
extends BidiMapper.EventEmitter<{
bidiResponse: Bidi.ChromiumBidi.Message;
}>
implements BidiMapper.BidiTransport
{
#onMessage: (message: Bidi.ChromiumBidi.Command) => Promise<void> | void =

View File

@ -11,7 +11,7 @@ import type {
BrowserConnectOptions,
ConnectOptions,
} from '../common/ConnectOptions.js';
import {UnsupportedOperation} from '../common/Errors.js';
import {ProtocolError, UnsupportedOperation} from '../common/Errors.js';
import {debugError, DEFAULT_VIEWPORT} from '../common/util.js';
import type {BidiBrowser} from './Browser.js';
@ -85,8 +85,8 @@ async function getBiDiConnection(
},
};
}
} catch (e: any) {
if (!('name' in e && e.name === 'ProtocolError')) {
} catch (e) {
if (!(e instanceof ProtocolError)) {
// Unexpected exception not related to BiDi / CDP. Rethrow.
throw e;
}

View File

@ -26,7 +26,7 @@ export async function releaseReference(
target: client.target,
handles: [remoteReference.handle],
})
.catch((error: any) => {
.catch(error => {
// Exceptions might happen in case of a page been navigated or closed.
// Swallow these since they are harmless and we don't leak anything in this case.
debugError(error);

View File

@ -70,7 +70,7 @@ describe('BrowserContext', function () {
it('should fire target events', async () => {
const {server, context} = await getTestState();
const events: any[] = [];
const events: string[] = [];
context.on('targetcreated', target => {
events.push('CREATED: ' + target.url());
});

View File

@ -5,6 +5,7 @@
*/
import expect from 'expect';
import type {Target} from 'puppeteer-core/internal/api/Target.js';
import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js';
import {getTestState, setupTestBrowserHooks} from '../mocha-utils.js';
@ -31,7 +32,7 @@ describe('Target.createCDPSession', function () {
it('should not report created targets for custom CDP sessions', async () => {
const {browser} = await getTestState();
let called = 0;
const handler = async (target: any) => {
const handler = async (target: Target) => {
called++;
if (called > 1) {
throw new Error('Too many targets created');

View File

@ -29,7 +29,7 @@ describe('DevTools', function () {
});
});
async function launchBrowser(options: any) {
async function launchBrowser(options: typeof launchOptions) {
const {browser, close} = await launch(options, {createContext: false});
browsers.push(close);
return browser;

View File

@ -51,7 +51,7 @@ describe('extensions', function () {
});
});
async function launchBrowser(options: any) {
async function launchBrowser(options: typeof extensionOptions) {
const {browser, close} = await launch(options, {createContext: false});
browsers.push(close);
return browser;

View File

@ -167,7 +167,7 @@ describe('Page.click', function () {
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/offscreenbuttons.html');
const messages: any[] = [];
const messages: string[] = [];
page.on('console', msg => {
if (msg.type() === 'log') {
return messages.push(msg.text());

View File

@ -328,7 +328,7 @@ describe('Evaluation specs', function () {
const {page} = await getTestState();
const result = await page.evaluate(() => {
const a: Record<string, any> = {};
const a: Record<string, unknown> = {};
const b = {a};
a['b'] = b;
return a;

View File

@ -6,6 +6,7 @@
import expect from 'expect';
import type {BrowserContext} from 'puppeteer-core/internal/api/BrowserContext.js';
import type {CDPSession} from 'puppeteer-core/internal/api/CDPSession.js';
import {CDPSessionEvent} from 'puppeteer-core/internal/api/CDPSession.js';
import type {CdpTarget} from 'puppeteer-core/internal/cdp/Target.js';
@ -446,7 +447,7 @@ describe('OOPIF', function () {
const {server, page} = state;
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true);
page.on('request', (r: {respond: (arg0: {body: string}) => any}) => {
page.on('request', r => {
return r.respond({body: 'YO, GOOGLE.COM'});
});
await page.evaluate(() => {
@ -460,7 +461,7 @@ describe('OOPIF', function () {
await page.waitForSelector('iframe[src="https://google.com/"]');
const urls = page
.frames()
.map((frame: {url: () => any}) => {
.map(frame => {
return frame.url();
})
.sort();
@ -472,29 +473,22 @@ describe('OOPIF', function () {
// Setup our session listeners to observe OOPIF activity.
const session = await page.target().createCDPSession();
const networkEvents: any[] = [];
const otherSessions: any[] = [];
const networkEvents: string[] = [];
const otherSessions: CDPSession[] = [];
await session.send('Target.setAutoAttach', {
autoAttach: true,
flatten: true,
waitForDebuggerOnStart: true,
});
// TODO: Remove any.
(session as any).on(
CDPSessionEvent.SessionAttached,
async (session: {
on: (arg0: string, arg1: (params: any) => number) => void;
send: (arg0: string) => any;
}) => {
otherSessions.push(session);
session.on(CDPSessionEvent.SessionAttached, async session => {
otherSessions.push(session);
session.on('Network.requestWillBeSent', (params: any) => {
return networkEvents.push(params);
});
await session.send('Network.enable');
await session.send('Runtime.runIfWaitingForDebugger');
}
);
session.on('Network.requestWillBeSent', params => {
return networkEvents.push(params.request.url);
});
await session.send('Network.enable');
await session.send('Runtime.runIfWaitingForDebugger');
});
// Navigate to the empty page and add an OOPIF iframe with at least one request.
await page.goto(server.EMPTY_PAGE);
@ -522,10 +516,7 @@ describe('OOPIF', function () {
awaitPromise: true,
});
const requests = networkEvents.map(event => {
return event.request.url;
});
expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`);
expect(networkEvents).toContain(`http://oopifdomain:${server.PORT}/fetch`);
});
});

View File

@ -556,7 +556,7 @@ describe('Page', function () {
it('should work for different console API calls with logging functions', async () => {
const {page} = await getTestState();
const messages: any[] = [];
const messages: ConsoleMessage[] = [];
page.on('console', msg => {
return messages.push(msg);
});
@ -1260,7 +1260,7 @@ describe('Page', function () {
await page.exposeFunction(
'complexObject',
function (a: {x: any}, b: {x: any}) {
function (a: {x: number}, b: {x: number}) {
return {x: a.x + b.x};
}
);

View File

@ -103,7 +103,7 @@ export async function navigateFrame(
): Promise<void> {
await pageOrFrame.evaluate(navigateFrame, frameId, url);
function navigateFrame(frameId: string, url: any) {
function navigateFrame(frameId: string, url: string) {
const frame = document.getElementById(frameId) as HTMLIFrameElement;
frame.src = url;
return new Promise(x => {

View File

@ -6,7 +6,7 @@
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import type {Platform, TestExpectation} from './types.js';
import type {Platform, TestExpectation, MochaTestResult} from './types.js';
import {
filterByParameters,
getTestResultForFailure,
@ -110,7 +110,7 @@ describe('testIdMatchesExpectationPattern', () => {
fullTitle() {
return 'Page Page.setContent should work';
},
} as any;
} satisfies Pick<Mocha.Test, 'title' | 'file' | 'fullTitle'> as Mocha.Test;
for (const [pattern, expected] of expectations) {
assert.equal(
@ -122,11 +122,11 @@ describe('testIdMatchesExpectationPattern', () => {
});
it('with MochaTestResult', () => {
const test = {
const test: MochaTestResult = {
title: 'should work',
file: 'page.spec.ts',
fullTitle: 'Page Page.setContent should work',
} as any;
};
for (const [pattern, expected] of expectations) {
assert.equal(