Add lint rule for as any and bulk ignore all existing breaks

For #269213

This adds a new eslint rule for `as any` and `<any>({... })`. We'd like to remove almost all of these, however right now the first goal is to prevent them in new code. That's why with this first PR I simply add `eslint-disable` comments for all breaks

Trying to get this change in soon after branching off for release to hopefully minimize disruption during debt week work
This commit is contained in:
Matt Bierner
2025-10-02 23:38:33 -07:00
parent 96aa43fe7a
commit 360c9fd134
465 changed files with 1188 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as eslint from 'eslint';
import { TSESTree } from '@typescript-eslint/utils';
export = new class NoAnyCasts implements eslint.Rule.RuleModule {
create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener {
return {
// Detect TSTypeAssertion: <any>value
'TSTypeAssertion': (node: any) => {
const typeAssertion = node as TSESTree.TSTypeAssertion;
if (typeAssertion.typeAnnotation.type === 'TSAnyKeyword') {
context.report({
node,
message: `Avoid casting to 'any' type. Consider using a more specific type or type guards for better type safety.`
});
}
},
// Detect TSAsExpression: value as any
'TSAsExpression': (node: any) => {
const asExpression = node as TSESTree.TSAsExpression;
if (asExpression.typeAnnotation.type === 'TSAnyKeyword') {
context.report({
node,
message: `Avoid casting to 'any' type. Consider using a more specific type or type guards for better type safety.`
});
}
}
};
}
};
@@ -61,10 +61,12 @@ function checkFunctionForObservableGetCalls(
if (node.type === 'CallExpression' && isObservableGetCall(node)) {
// Flag .get() calls since we're always in a reactive context here
context.report({
// eslint-disable-next-line local/code-no-any-casts
node: node as any as ESTree.Node,
message: `Observable '.get()' should not be used in reactive context. Use '.read(${readerName})' instead to properly track dependencies or '.read(undefined)' to be explicit about an untracked read.`,
fix: (fixer) => {
const memberExpression = node.callee as TSESTree.MemberExpression;
// eslint-disable-next-line local/code-no-any-casts
return fixer.replaceText(node as any, `${context.getSourceCode().getText(memberExpression.object as any)}.read(undefined)`);
}
});
@@ -131,6 +133,7 @@ function isReactiveFunctionWithReader(callee: TSESTree.Node): boolean {
function walkChildren(node: TSESTree.Node, cb: (child: TSESTree.Node) => void) {
const keys = visitorKeys.KEYS[node.type] || [];
for (const key of keys) {
// eslint-disable-next-line local/code-no-any-casts
const child = (node as any)[key];
if (Array.isArray(child)) {
for (const item of child) {
@@ -59,6 +59,7 @@ function checkFunctionForAwaitBeforeReader(
if (awaitPositions.length > 0) {
const methodName = getMethodName(node);
context.report({
// eslint-disable-next-line local/code-no-any-casts
node: node as any as ESTree.Node,
message: `Reader method '${methodName}' should not be called after 'await'. The reader becomes invalid after async operations.`
});
@@ -33,6 +33,7 @@ export = new class implements eslint.Rule.RuleModule {
}
const name = classDeclaration.id.name;
// eslint-disable-next-line local/code-no-any-casts
const valueText = context.sourceCode.getText(<any>propertyDefinition.value);
if (valueText.includes(name + '.')) {
@@ -20,6 +20,7 @@ export = new class NoAsyncSuite implements eslint.Rule.RuleModule {
function hasAsyncSuite(node: any) {
if (isCallExpression(node) && node.arguments.length >= 2 && isFunctionExpression(node.arguments[1]) && node.arguments[1].async) {
return context.report({
// eslint-disable-next-line local/code-no-any-casts
node: node as any,
message: 'suite factory function should never be async'
});
@@ -81,6 +81,7 @@ export = new class NoUnexternalizedStrings implements eslint.Rule.RuleModule {
context.report({
loc: messageNode.loc,
messageId: 'badMessage',
// eslint-disable-next-line local/code-no-any-casts
data: { message: context.getSourceCode().getText(<any>node) }
});
}
@@ -128,6 +129,7 @@ export = new class NoUnexternalizedStrings implements eslint.Rule.RuleModule {
// report all invalid duplicates (same key, different message)
if (values.length > 1) {
for (let i = 1; i < values.length; i++) {
// eslint-disable-next-line local/code-no-any-casts
if (context.getSourceCode().getText(<any>values[i - 1].message) !== context.getSourceCode().getText(<any>values[i].message)) {
context.report({ loc: values[i].call.loc, messageId: 'duplicateKey', data: { key } });
}
@@ -32,6 +32,7 @@ export = new class ApiProviderNaming implements eslint.Rule.RuleModule {
return;
}
// eslint-disable-next-line local/code-no-any-casts
const methodName = (<any>(<TSESTree.TSMethodSignatureNonComputedName>node).key).name;
if (!ApiProviderNaming._providerFunctionNames.test(methodName)) {
@@ -40,7 +40,9 @@ export = new class ApiVsCodeInComments implements eslint.Rule.RuleModule {
}
// Types for eslint seem incorrect
// eslint-disable-next-line local/code-no-any-casts
const start = sourceCode.getLocFromIndex(startIndex + match.index) as any as estree.Position;
// eslint-disable-next-line local/code-no-any-casts
const end = sourceCode.getLocFromIndex(startIndex + match.index + match[0].length) as any as estree.Position;
context.report({
messageId: 'comment',
+1
View File
@@ -521,6 +521,7 @@ class ESRPReleaseService {
// Release service uses hex format, not base64url :roll_eyes:
x5t: getThumbprint(this.requestSigningCertificates[0], 'sha1').toString('hex'),
// Release service uses a '.' separated string, not an array of strings :roll_eyes:
// eslint-disable-next-line local/code-no-any-casts
x5c: this.requestSigningCertificates.map(c => getCertificateBuffer(c).toString('base64url')).join('.') as any,
},
payload: message,
+1
View File
@@ -112,6 +112,7 @@ async function main(): Promise<void> {
const listing = new Vinyl({
path: 'files.txt',
contents: Buffer.from(files.join('\n')),
// eslint-disable-next-line local/code-no-any-casts
stat: { mode: 0o666 } as any
});
+1
View File
@@ -150,6 +150,7 @@ export function compileTask(src: string, out: string, build: boolean, options: {
(await newContentsByFileName).clear();
this.push(null);
// eslint-disable-next-line local/code-no-any-casts
(<any>ts2tsMangler) = undefined;
});
}
+2
View File
@@ -117,6 +117,7 @@ function fromLocalWebpack(extensionPath: string, webpackConfigFileName: string,
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
// eslint-disable-next-line local/code-no-any-casts
contents: fs.createReadStream(filePath) as any
}));
@@ -215,6 +216,7 @@ function fromLocalNormal(extensionPath: string): Stream {
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
// eslint-disable-next-line local/code-no-any-casts
contents: fs.createReadStream(filePath) as any
}));
+1
View File
@@ -54,6 +54,7 @@ export async function fetchUrl(url: string, options: IFetchOptions, retries = 10
try {
const response = await fetch(url, {
...options.nodeFetchOptions,
// eslint-disable-next-line local/code-no-any-casts
signal: controller.signal as any /* Typings issue with lib.dom.d.ts */
});
if (verbose) {
+1
View File
@@ -270,6 +270,7 @@ class ClassData {
}
function isNameTakenInFile(node: ts.Node, name: string): boolean {
// eslint-disable-next-line local/code-no-any-casts
const identifiers = (<any>node.getSourceFile()).identifiers;
if (identifiers instanceof Map) {
if (identifiers.has(name)) {
+2
View File
@@ -218,6 +218,7 @@ function format(ts: typeof import('typescript'), text: string, endl: string): st
const sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
// Get the formatting edits on the input sources
// eslint-disable-next-line local/code-no-any-casts
const edits = (<any>ts).formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
// Apply the edits on the input code
@@ -324,6 +325,7 @@ function format(ts: typeof import('typescript'), text: string, endl: string): st
function getRuleProvider(options: ts.FormatCodeSettings) {
// Share this between multiple formatters using the same options.
// This represents the bulk of the space the formatter uses.
// eslint-disable-next-line local/code-no-any-casts
return (ts as any).formatting.getFormatContext(options);
}
+3
View File
@@ -40,6 +40,7 @@ function collect(ts: typeof import('typescript'), node: ts.Node, fn: (node: ts.N
}
function clone<T extends object>(object: T): T {
// eslint-disable-next-line local/code-no-any-casts
const result = {} as any as T;
for (const id in object) {
result[id] = object[id];
@@ -503,11 +504,13 @@ module _nls {
ts,
typescript,
javascriptFile.contents!.toString(),
// eslint-disable-next-line local/code-no-any-casts
(<any>javascriptFile).sourceMap,
options
);
const result = fileFrom(javascriptFile, javascript);
// eslint-disable-next-line local/code-no-any-casts
(<any>result).sourceMap = sourcemap;
if (nlsKeys) {
+1
View File
@@ -251,6 +251,7 @@ export function minifyTask(src: string, sourceMapBaseUrl?: string): (cb: any) =>
svgFilter,
svgmin(),
svgFilter.restore,
// eslint-disable-next-line local/code-no-any-casts
sourcemaps.write('./', {
sourceMappingURL,
sourceRoot: undefined,
+3
View File
@@ -251,8 +251,11 @@ function* findAllReferencesInClass(node: ts.Node): Generator<ts.Node> {
function findAllReferences(node: ts.Node): readonly SymbolAndEntries[] {
const sourceFile = node.getSourceFile();
const position = node.getStart();
// eslint-disable-next-line local/code-no-any-casts
const name: ts.Node = (ts as any).getTouchingPropertyName(sourceFile, position);
// eslint-disable-next-line local/code-no-any-casts
const options = { use: (ts as any).FindAllReferences.FindReferencesUse.References };
// eslint-disable-next-line local/code-no-any-casts
return (ts as any).FindAllReferences.Core.getReferencedSymbolsForNode(position, name, program, [sourceFile], cancellationToken, options) ?? [];
}
+3
View File
@@ -105,13 +105,16 @@ export function createReporter(id?: string): IReporter {
errorLog.onEnd();
if (emitError && errors.length > 0) {
// eslint-disable-next-line local/code-no-any-casts
if (!(errors as any).__logged__) {
errorLog.log();
}
// eslint-disable-next-line local/code-no-any-casts
(errors as any).__logged__ = true;
const err = new Error(`Found ${errors.length} errors`);
// eslint-disable-next-line local/code-no-any-casts
(err as any).__reporter__ = true;
this.emit('error', err);
} else {
+1
View File
@@ -24,6 +24,7 @@ export interface CallbackTask extends BaseTask {
export type Task = PromiseTask | StreamTask | CallbackTask;
function _isPromise(p: Promise<void> | NodeJS.ReadWriteStream): p is Promise<void> {
// eslint-disable-next-line local/code-no-any-casts
if (typeof (<any>p).then === 'function') {
return true;
}
+8
View File
@@ -307,15 +307,19 @@ const enum NodeColor {
}
function getColor(node: ts.Node): NodeColor {
// eslint-disable-next-line local/code-no-any-casts
return (<any>node).$$$color || NodeColor.White;
}
function setColor(node: ts.Node, color: NodeColor): void {
// eslint-disable-next-line local/code-no-any-casts
(<any>node).$$$color = color;
}
function markNeededSourceFile(node: ts.SourceFile): void {
// eslint-disable-next-line local/code-no-any-casts
(<any>node).$$$neededSourceFile = true;
}
function isNeededSourceFile(node: ts.SourceFile): boolean {
// eslint-disable-next-line local/code-no-any-casts
return Boolean((<any>node).$$$neededSourceFile);
}
function nodeOrParentIsBlack(node: ts.Node): boolean {
@@ -684,6 +688,7 @@ function markNodes(ts: typeof import('typescript'), languageService: ts.Language
if (nodeOrParentIsBlack(node)) {
continue;
}
// eslint-disable-next-line local/code-no-any-casts
const symbol: ts.Symbol | undefined = (<any>node).symbol;
if (!symbol) {
continue;
@@ -912,8 +917,11 @@ function getRealNodeSymbol(ts: typeof import('typescript'), checker: ts.TypeChec
// Use some TypeScript internals to avoid code duplication
type ObjectLiteralElementWithName = ts.ObjectLiteralElement & { name: ts.PropertyName; parent: ts.ObjectLiteralExpression | ts.JsxAttributes };
// eslint-disable-next-line local/code-no-any-casts
const getPropertySymbolsFromContextualType: (node: ObjectLiteralElementWithName, checker: ts.TypeChecker, contextualType: ts.Type, unionSymbolOk: boolean) => ReadonlyArray<ts.Symbol> = (<any>ts).getPropertySymbolsFromContextualType;
// eslint-disable-next-line local/code-no-any-casts
const getContainingObjectLiteralElement: (node: ts.Node) => ObjectLiteralElementWithName | undefined = (<any>ts).getContainingObjectLiteralElement;
// eslint-disable-next-line local/code-no-any-casts
const getNameFromPropertyName: (name: ts.PropertyName) => string | undefined = (<any>ts).getNameFromPropertyName;
// Go to the original declaration for cases:
+5
View File
@@ -59,6 +59,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
function file(file: Vinyl): void {
// support gulp-sourcemaps
// eslint-disable-next-line local/code-no-any-casts
if ((<any>file).sourceMap) {
emitSourceMapsInStream = false;
}
@@ -80,6 +81,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
}
function isExternalModule(sourceFile: ts.SourceFile): boolean {
// eslint-disable-next-line local/code-no-any-casts
return (<any>sourceFile).externalModuleIndicator
|| /declare\s+module\s+('|")(.+)\1/.test(sourceFile.getText());
}
@@ -221,6 +223,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
[tsSMC, inputSMC].forEach((consumer) => {
(<SourceMapConsumer & { sources: string[] }>consumer).sources.forEach((sourceFile: any) => {
// eslint-disable-next-line local/code-no-any-casts
(<any>smg)._sources.add(sourceFile);
const sourceContent = consumer.sourceContentFor(sourceFile);
if (sourceContent !== null) {
@@ -239,6 +242,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
}
}
// eslint-disable-next-line local/code-no-any-casts
(<any>vinyl).sourceMap = sourceMap;
}
}
@@ -586,6 +590,7 @@ class LanguageServiceHost implements ts.LanguageServiceHost {
let result = this._snapshots[filename];
if (!result && resolve) {
try {
// eslint-disable-next-line local/code-no-any-casts
result = new VinylScriptSnapshot(new Vinyl(<any>{
path: filename,
contents: fs.readFileSync(filename),
+2
View File
@@ -131,9 +131,11 @@ export function create(
const transpiler = !config.transpileWithEsbuild
? new TscTranspiler(logFn, printDiagnostic, projectPath, cmdLine)
: new ESBuildTranspiler(logFn, printDiagnostic, projectPath, cmdLine);
// eslint-disable-next-line local/code-no-any-casts
result = <any>(() => createTranspileStream(transpiler));
} else {
const _builder = builder.createTypeScriptBuilder({ logFn }, projectPath, cmdLine);
// eslint-disable-next-line local/code-no-any-casts
result = <any>((token: builder.CancellationToken) => createCompileStream(_builder, token));
}
+2
View File
@@ -129,6 +129,7 @@ export function fixWin32DirectoryPermissions(): NodeJS.ReadWriteStream {
export function setExecutableBit(pattern?: string | string[]): NodeJS.ReadWriteStream {
const setBit = es.mapSync<VinylFile, VinylFile>(f => {
if (!f.stat) {
// eslint-disable-next-line local/code-no-any-casts
f.stat = { isFile() { return true; } } as any;
}
f.stat!.mode = /* 100755 */ 33261;
@@ -353,6 +354,7 @@ export interface FilterStream extends NodeJS.ReadWriteStream {
}
export function filter(fn: (data: any) => boolean): FilterStream {
// eslint-disable-next-line local/code-no-any-casts
const result = <FilterStream><any>es.through(function (data) {
if (fn(data)) {
this.emit('data', data);
+1
View File
@@ -47,6 +47,7 @@ function watch(root: string): Stream {
path: changePathFull,
base: root
});
// eslint-disable-next-line local/code-no-any-casts
(<any>file).event = toChangeType(changeType);
result.emit('data', file);
}
+1
View File
@@ -82,6 +82,7 @@ async function fetchUrl(options: IFetchOptions, retries = 10, retryDelay = 1000)
try {
const response = await fetch(`https://api.github.com/repos/Microsoft/vscode-linux-build-agent/releases/tags/v${version}`, {
headers: ghApiHeaders,
// eslint-disable-next-line local/code-no-any-casts
signal: controller.signal as any /* Typings issue with lib.dom.d.ts */
});
if (response.ok && (response.status >= 200 && response.status < 300)) {
+1
View File
@@ -60,6 +60,7 @@ async function main(outputDir?: string): Promise<void> {
throw new Error('Required build env not set');
}
// eslint-disable-next-line local/code-no-any-casts
await downloadExplorerDll(outputDir, (product as any).quality, arch);
}
+1
View File
@@ -82,6 +82,7 @@ export default tseslint.config(
'local/code-no-nls-in-standalone-editor': 'warn',
'local/code-no-potentially-unsafe-disposables': 'warn',
'local/code-no-dangerous-type-assertions': 'warn',
'local/code-no-any-casts': 'warn',
'local/code-no-standalone-editor': 'warn',
'local/code-no-unexternalized-strings': 'warn',
'local/code-must-use-super-dispose': 'warn',
@@ -83,6 +83,7 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
}
return r;
}
// eslint-disable-next-line local/code-no-any-casts
const isThenable = <T>(obj: ProviderResult<T>): obj is Thenable<T> => obj && (<any>obj)['then'];
const r = next(document, position, context, token);
@@ -68,8 +68,10 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
// in the passed params the rootPath of the workspace plus the client capabilities.
connection.onInitialize((params: InitializeParams): InitializeResult => {
// eslint-disable-next-line local/code-no-any-casts
const initializationOptions = params.initializationOptions as any || {};
// eslint-disable-next-line local/code-no-any-casts
workspaceFolders = (<any>params).workspaceFolders;
if (!Array.isArray(workspaceFolders)) {
workspaceFolders = [];
@@ -166,6 +168,7 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
// The settings have changed. Is send on server activation as well.
connection.onDidChangeConfiguration(change => {
// eslint-disable-next-line local/code-no-any-casts
updateConfiguration(change.settings as any);
});
+2
View File
@@ -184,7 +184,9 @@ function refreshCompletionProviders(_: vscode.ExtensionContext) {
return [
{
// eslint-disable-next-line local/code-no-any-casts
insertText: item.insertText as any,
// eslint-disable-next-line local/code-no-any-casts
filterText: item.label as any,
range
}
+2
View File
@@ -273,7 +273,9 @@ function getAttributeQuote(editor: TextEditor, attr: Attribute): string {
*/
function findUrlToken(editor: TextEditor, node: Property, pos: Position): CssToken | undefined {
const offset = editor.document.offsetAt(pos);
// eslint-disable-next-line local/code-no-any-casts
for (let i = 0, il = (node as any).parsedValue.length, url; i < il; i++) {
// eslint-disable-next-line local/code-no-any-casts
iterateCSSToken((node as any).parsedValue[i], (token: CssToken) => {
if (token.type === 'url' && token.start <= offset && token.end >= offset) {
url = token;
+1
View File
@@ -354,6 +354,7 @@ export function getFlatNode(root: FlatNode | undefined, offset: number, includeN
|| (includeNodeBoundary && nodeStart <= offset && nodeEnd >= offset)) {
return getFlatNodeChildren(child.children) ?? child;
}
// eslint-disable-next-line local/code-no-any-casts
else if ('close' in <any>child) {
// We have an HTML node in this case.
// In case this node is an invalid unpaired HTML node,
+2
View File
@@ -14,6 +14,7 @@ export class ApiImpl implements API {
constructor(private _model: Model) { }
pickRemoteSource(options: PickRemoteSourceOptions): Promise<PickRemoteSourceResult | string | undefined> {
// eslint-disable-next-line local/code-no-any-casts
return pickRemoteSource(this._model, options as any);
}
@@ -34,6 +35,7 @@ export function registerAPICommands(extension: GitBaseExtensionImpl): Disposable
return;
}
// eslint-disable-next-line local/code-no-any-casts
return pickRemoteSource(extension.model, opts as any);
}));
+3
View File
@@ -2381,8 +2381,10 @@ export class CommandCenter {
let promptToSaveFilesBeforeCommit = config.get<'always' | 'staged' | 'never'>('promptToSaveFilesBeforeCommit');
// migration
// eslint-disable-next-line local/code-no-any-casts
if (promptToSaveFilesBeforeCommit as any === true) {
promptToSaveFilesBeforeCommit = 'always';
// eslint-disable-next-line local/code-no-any-casts
} else if (promptToSaveFilesBeforeCommit as any === false) {
promptToSaveFilesBeforeCommit = 'never';
}
@@ -5368,6 +5370,7 @@ export class CommandCenter {
};
// patch this object, so people can call methods directly
// eslint-disable-next-line local/code-no-any-casts
(this as any)[key] = result;
return result;
+1
View File
@@ -24,6 +24,7 @@ export async function ensureEmojis() {
async function loadEmojiMap() {
const context = getExtensionContext();
// eslint-disable-next-line local/code-no-any-casts
const uri = (Uri as any).joinPath(context.extensionUri, 'resources', 'emojis.json');
emojiMap = JSON.parse(new TextDecoder('utf8').decode(await workspace.fs.readFile(uri)));
}
+3
View File
@@ -308,6 +308,7 @@ export class GitError extends Error {
}, null, 2);
if (this.error) {
// eslint-disable-next-line local/code-no-any-casts
result += (<any>this.error).stack;
}
@@ -2972,7 +2973,9 @@ export class Repository {
const result = await this.exec(['rev-list', '--left-right', '--count', `${branch.name}...${branch.upstream.remote}/${branch.upstream.name}`]);
const [ahead, behind] = result.stdout.trim().split('\t');
// eslint-disable-next-line local/code-no-any-casts
(branch as any).ahead = Number(ahead) || 0;
// eslint-disable-next-line local/code-no-any-casts
(branch as any).behind = Number(behind) || 0;
} catch { }
}
+1
View File
@@ -84,6 +84,7 @@ async function createModel(context: ExtensionContext, logger: LogOutputChannel,
const git = new Git({
gitPath: info.path,
// eslint-disable-next-line local/code-no-any-casts
userAgent: `git/${info.version} (${(os as any).version?.() ?? os.type()} ${os.release()}; ${os.platform()} ${os.arch()}) vscode/${vscodeVersion} (${env.appName})`,
version: info.version,
env: environment,
+3
View File
@@ -39,6 +39,7 @@ export function combinedDisposable(disposables: IDisposable[]): IDisposable {
export const EmptyDisposable = toDisposable(() => null);
export function fireEvent<T>(event: Event<T>): Event<T> {
// eslint-disable-next-line local/code-no-any-casts
return (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]) => event(_ => (listener as any).call(thisArgs), null, disposables);
}
@@ -110,6 +111,7 @@ export function once(fn: (...args: any[]) => any): (...args: any[]) => any {
export function assign<T>(destination: T, ...sources: any[]): T {
for (const source of sources) {
// eslint-disable-next-line local/code-no-any-casts
Object.keys(source).forEach(key => (destination as any)[key] = source[key]);
}
@@ -236,6 +238,7 @@ export function readBytes(stream: Readable, bytes: number): Promise<Buffer> {
bytesRead += bytesToRead;
if (bytesRead === bytes) {
// eslint-disable-next-line local/code-no-any-casts
(stream as any).destroy(); // Will trigger the close event eventually
}
});
@@ -5,4 +5,5 @@
import { webcrypto } from 'crypto';
// eslint-disable-next-line local/code-no-any-casts
export const crypto = webcrypto as any as Crypto;
+1
View File
@@ -120,6 +120,7 @@ class FolderDetector {
}
public async getTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const taskDefinition = <any>_task.definition;
const gruntTask = taskDefinition.task;
if (gruntTask) {
+2
View File
@@ -150,8 +150,10 @@ class FolderDetector {
}
public async getTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const gulpTask = (<any>_task.definition).task;
if (gulpTask) {
// eslint-disable-next-line local/code-no-any-casts
const kind: GulpTaskDefinition = (<any>_task.definition);
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
const task = new vscode.Task(kind, this.workspaceFolder, gulpTask, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [gulpTask], options));
@@ -179,6 +179,7 @@ async function startClientWithParticipants(languageParticipants: LanguagePartici
}
return r;
}
// eslint-disable-next-line local/code-no-any-casts
const isThenable = <T>(obj: ProviderResult<T>): obj is Thenable<T> => obj && (<any>obj)['then'];
const r = next(document, position, context, token);
@@ -134,8 +134,10 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
// After the server has started the client sends an initialize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilities
connection.onInitialize((params: InitializeParams): InitializeResult => {
// eslint-disable-next-line local/code-no-any-casts
const initializationOptions = params.initializationOptions as any || {};
// eslint-disable-next-line local/code-no-any-casts
workspaceFolders = (<any>params).workspaceFolders;
if (!Array.isArray(workspaceFolders)) {
workspaceFolders = [];
@@ -540,6 +542,7 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
});
connection.languages.onLinkedEditingRange((params, token) => {
// eslint-disable-next-line local/code-no-any-casts
return <any> /* todo remove when microsoft/vscode-languageserver-node#700 fixed */ runSafe(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
+2
View File
@@ -20,6 +20,7 @@ const jupyterLanguageToMonacoLanguageMapping = new Map([
export function getPreferredLanguage(metadata?: nbformat.INotebookMetadata) {
const jupyterLanguage =
metadata?.language_info?.name ||
// eslint-disable-next-line local/code-no-any-casts
(metadata?.kernelspec as any)?.language;
// Default to python language only if the Python extension is installed.
@@ -290,6 +291,7 @@ export function jupyterCellOutputToCellOutput(output: nbformat.IOutput): Noteboo
if (fn) {
result = fn(output);
} else {
// eslint-disable-next-line local/code-no-any-casts
result = translateDisplayDataOutput(output as any);
}
return result;
+5
View File
@@ -11,13 +11,18 @@ export function deepClone<T>(obj: T): T {
}
if (obj instanceof RegExp) {
// See https://github.com/microsoft/TypeScript/issues/10990
// eslint-disable-next-line local/code-no-any-casts
return obj as any;
}
const result: any = Array.isArray(obj) ? [] : {};
// eslint-disable-next-line local/code-no-any-casts
Object.keys(<any>obj).forEach((key: string) => {
// eslint-disable-next-line local/code-no-any-casts
if ((<any>obj)[key] && typeof (<any>obj)[key] === 'object') {
// eslint-disable-next-line local/code-no-any-casts
result[key] = deepClone((<any>obj)[key]);
} else {
// eslint-disable-next-line local/code-no-any-casts
result[key] = (<any>obj)[key];
}
});
+4
View File
@@ -37,6 +37,7 @@ export function sortObjectPropertiesRecursively(obj: any): any {
}
if (obj !== undefined && obj !== null && typeof obj === 'object' && Object.keys(obj).length > 0) {
return (
// eslint-disable-next-line local/code-no-any-casts
Object.keys(obj)
.sort()
.reduce<Record<string, any>>((sortedObj, prop) => {
@@ -57,6 +58,7 @@ export function getCellMetadata(options: { cell: NotebookCell | NotebookCellData
...(cell.metadata ?? {})
} satisfies CellMetadata;
if (cell.kind === NotebookCellKindMarkup) {
// eslint-disable-next-line local/code-no-any-casts
delete (metadata as any).execution_count;
}
return metadata;
@@ -398,7 +400,9 @@ export function pruneCell(cell: nbformat.ICell): nbformat.ICell {
// Remove outputs and execution_count from non code cells
if (result.cell_type !== 'code') {
// eslint-disable-next-line local/code-no-any-casts
delete (<any>result).outputs;
// eslint-disable-next-line local/code-no-any-casts
delete (<any>result).execution_count;
} else {
// Clean outputs from code cells
@@ -37,6 +37,7 @@ suite(`Notebook Model Store Sync`, () => {
onWillSaveNotebookDocument = new AsyncEmitter<NotebookDocumentWillSaveEvent>();
sinon.stub(NotebookEdit, 'updateCellMetadata').callsFake((index, metadata) => {
// eslint-disable-next-line local/code-no-any-casts
const edit = (NotebookEdit.updateCellMetadata as any).wrappedMethod.call(NotebookEdit, index, metadata);
cellMetadataUpdates.push(edit);
return edit;
@@ -75,6 +76,7 @@ suite(`Notebook Model Store Sync`, () => {
test('Adding cell for non Jupyter Notebook will not result in any updates', async () => {
sinon.stub(notebook, 'notebookType').get(() => 'some-other-type');
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {} as any,
executionSummary: {},
index: 0,
@@ -104,6 +106,7 @@ suite(`Notebook Model Store Sync`, () => {
test('Adding cell to nbformat 4.2 notebook will result in adding empty metadata', async () => {
sinon.stub(notebook, 'metadata').get(() => ({ nbformat: 4, nbformat_minor: 2 }));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {} as any,
executionSummary: {},
index: 0,
@@ -135,6 +138,7 @@ suite(`Notebook Model Store Sync`, () => {
test('Added cell will have a cell id if nbformat is 4.5', async () => {
sinon.stub(notebook, 'metadata').get(() => ({ nbformat: 4, nbformat_minor: 5 }));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {} as any,
executionSummary: {},
index: 0,
@@ -169,6 +173,7 @@ suite(`Notebook Model Store Sync`, () => {
test('Do not add cell id if one already exists', async () => {
sinon.stub(notebook, 'metadata').get(() => ({ nbformat: 4, nbformat_minor: 5 }));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {} as any,
executionSummary: {},
index: 0,
@@ -205,6 +210,7 @@ suite(`Notebook Model Store Sync`, () => {
test('Do not perform any updates if cell id and metadata exists', async () => {
sinon.stub(notebook, 'metadata').get(() => ({ nbformat: 4, nbformat_minor: 5 }));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {} as any,
executionSummary: {},
index: 0,
@@ -242,6 +248,7 @@ suite(`Notebook Model Store Sync`, () => {
}
}));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'javascript'
} as any,
@@ -264,6 +271,7 @@ suite(`Notebook Model Store Sync`, () => {
cellChanges: [
{
cell,
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'javascript'
} as any,
@@ -292,6 +300,7 @@ suite(`Notebook Model Store Sync`, () => {
}
}));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'javascript'
} as any,
@@ -335,6 +344,7 @@ suite(`Notebook Model Store Sync`, () => {
}
}));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'javascript'
} as any,
@@ -358,6 +368,7 @@ suite(`Notebook Model Store Sync`, () => {
cellChanges: [
{
cell,
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'javascript'
} as any,
@@ -386,6 +397,7 @@ suite(`Notebook Model Store Sync`, () => {
}
}));
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'powershell'
} as any,
@@ -409,6 +421,7 @@ suite(`Notebook Model Store Sync`, () => {
cellChanges: [
{
cell,
// eslint-disable-next-line local/code-no-any-casts
document: {
languageId: 'powershell'
} as any,
@@ -443,6 +456,7 @@ suite(`Notebook Model Store Sync`, () => {
});
const cell: NotebookCell = {
// eslint-disable-next-line local/code-no-any-casts
document: {} as any,
executionSummary: {},
index: 0,
+2
View File
@@ -120,8 +120,10 @@ class FolderDetector {
}
public async getTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const jakeTask = (<any>_task.definition).task;
if (jakeTask) {
// eslint-disable-next-line local/code-no-any-casts
const kind: JakeTaskDefinition = (<any>_task.definition);
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
const task = new vscode.Task(kind, this.workspaceFolder, jakeTask, 'jake', new vscode.ShellExecution(await this._jakeCommand, [jakeTask], options));
@@ -772,6 +772,7 @@ function getSchemaId(schema: JSONSchemaSettings, settingsLocation?: Uri): string
}
function isThenable<T>(obj: ProviderResult<T>): obj is Thenable<T> {
// eslint-disable-next-line local/code-no-any-casts
return obj && (<any>obj)['then'];
}
@@ -141,6 +141,7 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
// in the passed params the rootPath of the workspace plus the client capabilities.
connection.onInitialize((params: InitializeParams): InitializeResult => {
// eslint-disable-next-line local/code-no-any-casts
const initializationOptions = params.initializationOptions as any || {};
const handledProtocols = initializationOptions?.handledSchemaProtocols;
@@ -380,6 +380,7 @@ function addNamedHeaderRendering(md: InstanceType<typeof MarkdownIt>): void {
const originalRender = md.render;
md.render = function () {
slugCounter.clear();
// eslint-disable-next-line local/code-no-any-casts
return originalRender.apply(this, arguments as any);
};
}
@@ -23,6 +23,7 @@ let documentResource = settings.settings.source;
const vscode = acquireVsCodeApi();
// eslint-disable-next-line local/code-no-any-casts
const originalState = vscode.getState() ?? {} as any;
const state = {
...originalState,
@@ -249,6 +250,7 @@ window.addEventListener('message', async event => {
}
newRoot.prepend(...styles);
// eslint-disable-next-line local/code-no-any-casts
morphdom(root, newRoot, {
childrenOnly: true,
onBeforeElUpdated: (fromEl: Element, toEl: Element) => {
@@ -434,6 +436,7 @@ function domEval(el: Element): void {
for (const key of preservedScriptAttributes) {
const val = node.getAttribute?.(key);
if (val) {
// eslint-disable-next-line local/code-no-any-casts
scriptTag.setAttribute(key, val as any);
}
}
@@ -50,6 +50,7 @@ class AddToIgnoreLinksQuickFixProvider implements vscode.CodeActionProvider {
case DiagnosticCode.link_noSuchHeaderInOwnFile:
case DiagnosticCode.link_noSuchFile:
case DiagnosticCode.link_noSuchHeaderInFile: {
// eslint-disable-next-line local/code-no-any-casts
const hrefText = (diagnostic as any).data?.hrefText;
if (hrefText) {
const fix = new vscode.CodeAction(
@@ -143,6 +143,7 @@ export class MarkdownItEngine implements IMdParser {
const frontMatterPlugin = await import('markdown-it-front-matter');
// Extract rules from front matter plugin and apply at a lower precedence
let fontMatterRule: any;
// eslint-disable-next-line local/code-no-any-casts
frontMatterPlugin.default(<any>{
block: {
ruler: {
@@ -94,6 +94,7 @@ export class MicrosoftAuthenticationTelemetryReporter implements IExperimentatio
if (typeof error === 'string') {
errorMessage = error;
} else {
// eslint-disable-next-line local/code-no-any-casts
const authError: AuthError = error as any;
// don't set error message or stack because it contains PII
errorCode = authError.errorCode;
@@ -65,6 +65,7 @@ const domEval = (container: Element) => {
for (const key of preservedScriptAttributes) {
const val = node[key] || node.getAttribute && node.getAttribute(key);
if (val) {
// eslint-disable-next-line local/code-no-any-casts
scriptTag.setAttribute(key, val as any);
}
}
@@ -127,12 +127,14 @@ suite('Notebook builtin output renderer', () => {
return text;
},
blob() {
// eslint-disable-next-line local/code-no-any-casts
return [] as any;
},
json() {
return '{ }';
},
data() {
// eslint-disable-next-line local/code-no-any-casts
return [] as any;
},
metadata: {}
+2
View File
@@ -58,8 +58,10 @@ export class NpmTaskProvider implements TaskProvider {
}
public async resolveTask(_task: Task): Promise<Task | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const npmTask = (<any>_task.definition).script;
if (npmTask) {
// eslint-disable-next-line local/code-no-any-casts
const kind: INpmTaskDefinition = (<any>_task.definition);
let packageJsonUri: Uri;
if (_task.scope === undefined || _task.scope === TaskScope.Global || _task.scope === TaskScope.Workspace) {
@@ -8,6 +8,7 @@ import cdSpec from '../../completions/cd';
import { testPaths, type ISuiteSpec } from '../helpers';
const expectedCompletions = ['-'];
// eslint-disable-next-line local/code-no-any-casts
const cdExpectedCompletions = [{ label: 'cd', description: (cdSpec as any).description }];
export const cdTestSuiteSpec: ISuiteSpec = {
name: 'cd',
@@ -77,6 +77,7 @@ export function createCodeTestSpecs(executable: string): ITestSpec[] {
const typingTests: ITestSpec[] = [];
for (let i = 1; i < executable.length; i++) {
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: executable, description: executable === codeCompletionSpec.name ? (codeCompletionSpec as any).description : (codeInsidersCompletionSpec as any).description }];
const input = `${executable.slice(0, i)}|`;
typingTests.push({ input, expectedCompletions, expectedResourceRequests: input.endsWith(' ') ? undefined : { type: 'both', cwd: testPaths.cwd } });
@@ -265,6 +266,7 @@ export function createCodeTunnelTestSpecs(executable: string): ITestSpec[] {
const typingTests: ITestSpec[] = [];
for (let i = 1; i < executable.length; i++) {
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: executable, description: executable === codeCompletionSpec.name || executable === codeTunnelCompletionSpec.name ? (codeCompletionSpec as any).description : (codeInsidersCompletionSpec as any).description }];
const input = `${executable.slice(0, i)}|`;
typingTests.push({ input, expectedCompletions, expectedResourceRequests: input.endsWith(' ') ? undefined : { type: 'both', cwd: testPaths.cwd } });
@@ -12,6 +12,7 @@ const allOptions = [
'-e',
'-n',
];
// eslint-disable-next-line local/code-no-any-casts
const echoExpectedCompletions = [{ label: 'echo', description: (echoSpec as any).description }];
export const echoTestSuiteSpec: ISuiteSpec = {
name: 'echo',
@@ -11,6 +11,7 @@ import gitSpec from '../../../completions/git';
// const gitCommitArgs = ['--', '--all', '--allow-empty', '--allow-empty-message', '--amend', '--author', '--branch', '--cleanup', '--date', '--dry-run', '--edit', '--file', '--fixup', '--gpg-sign', '--include', '--long', '--message', '--no-edit', '--no-gpg-sign', '--no-post-rewrite', '--no-signoff', '--no-status', '--no-verify', '--null', '--only', '--patch', '--pathspec-file-nul', '--pathspec-from-file', '--porcelain', '--quiet', '--reedit-message', '--reset-author', '--reuse-message', '--short', '--signoff', '--squash', '--status', '--template', '--untracked-files', '--verbose', '-C', '-F', '-S', '-a', '-am', '-c', '-e', '-i', '-m', '-n', '-o', '-p', '-q', '-s', '-t', '-u', '-v', '-z'];
// const gitMergeArgs = ['-', '--abort', '--allow-unrelated-histories', '--autostash', '--cleanup', '--commit', '--continue', '--edit', '--ff', '--ff-only', '--file', '--gpg-sign', '--log', '--no-autostash', '--no-commit', '--no-edit', '--no-ff', '--no-gpg-sign', '--no-log', '--no-overwrite-ignore', '--no-progress', '--no-rerere-autoupdate', '--no-signoff', '--no-squash', '--no-stat', '--no-summary', '--no-verify', '--no-verify-signatures', '--overwrite-ignore', '--progress', '--quiet', '--quit', '--rerere-autoupdate', '--signoff', '--squash', '--stat', '--strategy', '--strategy-option', '--summary', '--verbose', '--verify-signatures', '-F', '-S', '-X', '-e', '-m', '-n', '-q', '-s'];
// const gitAddArgs = ['--', '--all', '--chmod', '--dry-run', '--edit', '--force', '--ignore-errors', '--ignore-missing', '--ignore-removal', '--intent-to-add', '--interactive', '--no-all', '--no-ignore-removal', '--no-warn-embedded-repo', '--patch', '--pathspec-file-nul', '--pathspec-from-file', '--refresh', '--renormalize', '--update', '--verbose', '-A', '-N', '-e', '-f', '-i', '-n', '-p', '-u', '-v'];
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: 'git', description: (gitSpec as any).description }];
export const gitTestSuiteSpec: ISuiteSpec = {
@@ -51,6 +51,7 @@ const allOptions = [
'-w',
'-x',
];
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: 'ls', description: (lsSpec as any).description }];
export const lsTestSuiteSpec: ISuiteSpec = {
name: 'ls',
@@ -19,6 +19,7 @@ const allOptions = [
'-p',
'-v',
];
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: 'mkdir', description: (mkdirSpec as any).description }];
export const mkdirTestSuiteSpec: ISuiteSpec = {
name: 'mkdir',
@@ -16,6 +16,7 @@ const allOptions = [
'-r',
'-v',
];
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: 'rm', description: (rmSpec as any).description }];
export const rmTestSuiteSpec: ISuiteSpec = {
name: 'rm',
@@ -10,6 +10,7 @@ import rmdirSpec from '../../../completions/upstream/rmdir';
const allOptions = [
'-p',
];
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: 'rmdir', description: (rmdirSpec as any).description }];
export const rmdirTestSuiteSpec: ISuiteSpec = {
@@ -17,6 +17,7 @@ const allOptions = [
'-r <file>',
'-t <timestamp>',
];
// eslint-disable-next-line local/code-no-any-casts
const expectedCompletions = [{ label: 'touch', description: (touchSpec as any).description }];
export const touchTestSuiteSpec: ISuiteSpec = {
@@ -777,6 +777,7 @@ class TypeScriptCompletionItemProvider implements vscode.CompletionItemProvider<
dotAccessorContext = { range, text };
}
}
// eslint-disable-next-line local/code-no-any-casts
const isIncomplete = !!response.body.isIncomplete || (response.metadata as any)?.isIncomplete;
const entries = response.body.entries;
const metadata = response.metadata;
@@ -105,8 +105,10 @@ function toTsTriggerReason(context: vscode.SignatureHelpContext): Proto.Signatur
case vscode.SignatureHelpTriggerKind.TriggerCharacter:
if (context.triggerCharacter) {
if (context.isRetrigger) {
// eslint-disable-next-line local/code-no-any-casts
return { kind: 'retrigger', triggerCharacter: context.triggerCharacter as any };
} else {
// eslint-disable-next-line local/code-no-any-casts
return { kind: 'characterTyped', triggerCharacter: context.triggerCharacter as any };
}
} else {
@@ -183,6 +183,7 @@ class SyncedBuffer {
.filter(x => x.languages.indexOf(this.document.languageId) >= 0);
if (tsPluginsForDocument.length) {
// eslint-disable-next-line local/code-no-any-casts
(args as any).plugins = tsPluginsForDocument.map(plugin => plugin.name);
}
@@ -283,6 +283,7 @@ export class SingleTsServer extends Disposable implements ITypeScriptServer {
}
this._requestQueue.enqueue(requestInfo);
// eslint-disable-next-line local/code-no-any-casts
if (args && typeof (args as any).$traceId === 'string') {
const queueLength = this._requestQueue.length - 1;
const pendingResponses = this._pendingResponses.size;
@@ -298,6 +299,7 @@ export class SingleTsServer extends Disposable implements ITypeScriptServer {
data.pendingCommands = this.getPendingCommands();
}
// eslint-disable-next-line local/code-no-any-casts
this._telemetryReporter.logTraceEvent('TSServer.enqueueRequest', (args as any).$traceId, JSON.stringify(data));
}
this.sendNextRequests();
@@ -10,6 +10,7 @@ export function isWeb(): boolean {
}
export function isWebAndHasSharedArrayBuffers(): boolean {
// eslint-disable-next-line local/code-no-any-casts
return isWeb() && (globalThis as any)['crossOriginIsolated'];
}
@@ -29,6 +29,7 @@ function createServerHost(
const fs = apiClient?.vscode.workspace.fileSystem;
// Internals
// eslint-disable-next-line local/code-no-any-casts
const combinePaths: (path: string, ...paths: (string | undefined)[]) => string = (ts as any).combinePaths;
const byteOrderMarkIndicator = '\uFEFF';
const matchFiles: (
@@ -41,13 +42,19 @@ function createServerHost(
depth: number | undefined,
getFileSystemEntries: (path: string) => { files: readonly string[]; directories: readonly string[] },
realpath: (path: string) => string
// eslint-disable-next-line local/code-no-any-casts
) => string[] = (ts as any).matchFiles;
// eslint-disable-next-line local/code-no-any-casts
const generateDjb2Hash = (ts as any).generateDjb2Hash;
// Legacy web
// eslint-disable-next-line local/code-no-any-casts
const memoize: <T>(callback: () => T) => () => T = (ts as any).memoize;
// eslint-disable-next-line local/code-no-any-casts
const ensureTrailingDirectorySeparator: (path: string) => string = (ts as any).ensureTrailingDirectorySeparator;
// eslint-disable-next-line local/code-no-any-casts
const getDirectoryPath: (path: string) => string = (ts as any).getDirectoryPath;
// eslint-disable-next-line local/code-no-any-casts
const directorySeparator: string = (ts as any).directorySeparator;
const executingFilePath = findArgument(args, '--executingFilePath') || location + '';
const getExecutingDirectoryPath = memoize(() => memoize(() => ensureTrailingDirectorySeparator(getDirectoryPath(executingFilePath))));
@@ -13,6 +13,7 @@ import { createSys } from './serverHost';
import { findArgument, findArgumentStringArray, hasArgument, parseServerMode } from './util/args';
import { StartSessionOptions, startWorkerSession } from './workerSession';
// eslint-disable-next-line local/code-no-any-casts
const setSys: (s: ts.System) => void = (ts as any).setSys;
async function initializeSession(
@@ -31,6 +31,7 @@ export function startWorkerSession(
pathMapper: PathMapper,
logger: Logger,
): void {
// eslint-disable-next-line local/code-no-any-casts
const indent: (str: string) => string = (ts as any).server.indent;
const worker = new class WorkerSession extends ts.server.Session<{}> {
@@ -7,5 +7,6 @@ import * as vscode from 'vscode';
export function activate(_context: vscode.ExtensionContext) {
// Set context as a global as some tests depend on it
// eslint-disable-next-line local/code-no-any-casts
(global as any).testExtensionContext = _context;
}
@@ -178,6 +178,7 @@ suite('chat', () => {
await commands.executeCommand('workbench.action.chat.newChat');
const result = await commands.executeCommand('workbench.action.chat.open', { query: 'hello', blockOnResponse: true });
// eslint-disable-next-line local/code-no-any-casts
assert.strictEqual((result as any).errorDetails.code, 'rate_limited');
});
@@ -30,6 +30,7 @@ suite('vscode API - configuration', () => {
assert.strictEqual(config['config0'], true);
assert.strictEqual(config['config4'], '');
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (<any>config)['config4'] = 'valuevalue');
assert.ok(config.has('nested.config1'));
@@ -44,6 +45,7 @@ suite('vscode API - configuration', () => {
assert.ok(config.has('get'));
assert.strictEqual(config.get('get'), 'get-prop');
assert.deepStrictEqual(config['get'], config.get);
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => config['get'] = <any>'get-prop');
});
});
@@ -21,11 +21,17 @@ suite('vscode API - env', () => {
});
test('env is readonly', function () {
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (env as any).language = '234');
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (env as any).appRoot = '234');
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (env as any).appName = '234');
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (env as any).machineId = '234');
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (env as any).sessionId = '234');
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (env as any).shell = '234');
});
@@ -56,6 +56,7 @@ import assert from 'assert';
});
// Using https.globalAgent because it is shared with proxyResolver.ts and mutable.
// eslint-disable-next-line local/code-no-any-casts
(https.globalAgent as any).testCertificates = [certPEM];
resetCaches();
@@ -72,6 +73,7 @@ import assert from 'assert';
.on('error', reject);
});
} finally {
// eslint-disable-next-line local/code-no-any-casts
delete (https.globalAgent as any).testCertificates;
resetCaches();
server.close();
@@ -13,6 +13,7 @@ suite('vscode API - globalState / workspaceState', () => {
suiteSetup(async () => {
// Trigger extension activation and grab the context as some tests depend on it
await extensions.getExtension('vscode.vscode-api-tests')?.activate();
// eslint-disable-next-line local/code-no-any-casts
extensionContext = (global as any).testExtensionContext;
});
@@ -15,6 +15,7 @@ import { assertNoRpc, poll } from '../utils';
suiteSetup(async () => {
// Trigger extension activation and grab the context as some tests depend on it
await extensions.getExtension('vscode.vscode-api-tests')?.activate();
// eslint-disable-next-line local/code-no-any-casts
extensionContext = (global as any).testExtensionContext;
const config = workspace.getConfiguration('terminal.integrated');
@@ -41,11 +41,13 @@ suite('vscode API - workspace', () => {
test('textDocuments', () => {
assert.ok(Array.isArray(vscode.workspace.textDocuments));
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (<any>vscode.workspace).textDocuments = null);
});
test('rootPath', () => {
assert.ok(pathEquals(vscode.workspace.rootPath!, join(__dirname, '../../testWorkspace')));
// eslint-disable-next-line local/code-no-any-casts
assert.throws(() => (vscode.workspace as any).rootPath = 'farboo');
});
@@ -458,6 +460,7 @@ suite('vscode API - workspace', () => {
const registration = vscode.workspace.registerTextDocumentContentProvider('foo', {
provideTextDocumentContent(_uri) {
// eslint-disable-next-line local/code-no-any-casts
return <any>123;
}
});
+3
View File
@@ -254,6 +254,7 @@ function makeLoaderJsHotReloadable(loaderJsCode: string, fileChangesUrl: URL): s
}
console.log('Connecting to server to watch for changes...');
// eslint-disable-next-line local/code-no-any-casts
(fetch as any)(fileChangesUrl)
.then(async request => {
const reader = request.body.getReader();
@@ -332,6 +333,7 @@ function makeLoaderJsHotReloadable(loaderJsCode: string, fileChangesUrl: URL): s
const moduleIdStr = trimEnd(relativePath, '.js');
const requireFn: any = globalThis.require;
// eslint-disable-next-line local/code-no-any-casts
const moduleManager = (requireFn as any).moduleManager;
if (!moduleManager) {
console.log(debugSessionName, 'ignoring js change, as moduleManager is not available', relativePath);
@@ -347,6 +349,7 @@ function makeLoaderJsHotReloadable(loaderJsCode: string, fileChangesUrl: URL): s
}
// Check if we can reload
// eslint-disable-next-line local/code-no-any-casts
const g = globalThis as any;
// A frozen copy of the previous exports
+2
View File
@@ -582,6 +582,7 @@ function registerListeners(): void {
* the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
*/
const macOpenFiles: string[] = [];
// eslint-disable-next-line local/code-no-any-casts
(globalThis as any)['macOpenFiles'] = macOpenFiles;
app.on('open-file', function (event, path) {
macOpenFiles.push(path);
@@ -602,6 +603,7 @@ function registerListeners(): void {
app.on('open-url', onOpenUrl);
});
// eslint-disable-next-line local/code-no-any-casts
(globalThis as any)['getOpenUrls'] = function () {
app.removeListener('open-url', onOpenUrl);
+2
View File
@@ -20,6 +20,7 @@ import { INLSConfiguration } from './vs/nls.js';
import { IServerAPI } from './vs/server/node/remoteExtensionHostAgentServer.js';
perf.mark('code/server/start');
// eslint-disable-next-line local/code-no-any-casts
(globalThis as any).vscodeServerStartTime = performance.now();
// Do a quick parse to determine if a server or the cli needs to be started
@@ -138,6 +139,7 @@ if (shouldSpawnCli) {
console.log(output);
perf.mark('code/server/started');
// eslint-disable-next-line local/code-no-any-casts
(globalThis as any).vscodeServerListenTime = performance.now();
await getRemoteExtensionHostAgentServer();
+2
View File
@@ -131,11 +131,13 @@ export function isStandalone(): boolean {
// e.g. visible is true even in fullscreen mode where the controls are hidden
// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/visible
export function isWCOEnabled(): boolean {
// eslint-disable-next-line local/code-no-any-casts
return (navigator as any)?.windowControlsOverlay?.visible;
}
// Returns the bounding rect of the titlebar area if it is supported and defined
// See docs at https://developer.mozilla.org/en-US/docs/Web/API/WindowControlsOverlay/getTitlebarAreaRect
export function getWCOTitlebarAreaRect(targetWindow: Window): DOMRect | undefined {
// eslint-disable-next-line local/code-no-any-casts
return (targetWindow.navigator as any)?.windowControlsOverlay?.getTitlebarAreaRect();
}
+1
View File
@@ -33,6 +33,7 @@ export const BrowserFeatures = {
return KeyboardSupport.Always;
}
// eslint-disable-next-line local/code-no-any-casts
if ((<any>navigator).keyboard || browser.isSafari) {
return KeyboardSupport.FullScreen;
}
+3
View File
@@ -23,6 +23,7 @@ export interface UsbDeviceData {
}
export async function requestUsbDevice(options?: { filters?: unknown[] }): Promise<UsbDeviceData | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const usb = (navigator as any).usb;
if (!usb) {
return undefined;
@@ -59,6 +60,7 @@ export interface SerialPortData {
}
export async function requestSerialPort(options?: { filters?: unknown[] }): Promise<SerialPortData | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const serial = (navigator as any).serial;
if (!serial) {
return undefined;
@@ -87,6 +89,7 @@ export interface HidDeviceData {
}
export async function requestHidDevice(options?: { filters?: unknown[] }): Promise<HidDeviceData | undefined> {
// eslint-disable-next-line local/code-no-any-casts
const hid = (navigator as any).hid;
if (!hid) {
return undefined;
+14
View File
@@ -427,6 +427,7 @@ const DEFAULT_EVENT_MERGER: IEventMerger<Event, Event> = function (lastEvent: Ev
class TimeoutThrottledDomListener<R, E extends Event> extends Disposable {
// eslint-disable-next-line local/code-no-any-casts
constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger<R, E> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {
super();
@@ -715,6 +716,7 @@ export function getDomNodeZoomLevel(domNode: HTMLElement): number {
let testElement: HTMLElement | null = domNode;
let zoom = 1.0;
do {
// eslint-disable-next-line local/code-no-any-casts
const elementZoomLevel = (getComputedStyle(testElement) as any).zoom;
if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {
zoom *= elementZoomLevel;
@@ -1320,6 +1322,7 @@ function _$<T extends Element>(namespace: Namespace, description: string, attrs?
}
if (/^on\w+$/.test(name)) {
// eslint-disable-next-line local/code-no-any-casts
(<any>result)[name] = value;
} else if (name === 'selected') {
if (value) {
@@ -1514,6 +1517,7 @@ export function windowOpenWithSuccess(url: string, noOpener = true): boolean {
if (newTab) {
if (noOpener) {
// see `windowOpenNoOpener` for details on why this is important
// eslint-disable-next-line local/code-no-any-casts
(newTab as any).opener = null;
}
newTab.location.href = url;
@@ -1653,6 +1657,7 @@ export interface IDetectedFullscreen {
export function detectFullscreen(targetWindow: Window): IDetectedFullscreen | null {
// Browser fullscreen: use DOM APIs to detect
// eslint-disable-next-line local/code-no-any-casts
if (targetWindow.document.fullscreenElement || (<any>targetWindow.document).webkitFullscreenElement || (<any>targetWindow.document).webkitIsFullScreen) {
return { mode: DetectedFullscreenMode.DOCUMENT, guess: false };
}
@@ -2005,6 +2010,7 @@ export function h(tag: string, ...args: [] | [attributes: { $: string } & Partia
attributes = {};
children = args[0];
} else {
// eslint-disable-next-line local/code-no-any-casts
attributes = args[0] as any || {};
children = args[1];
}
@@ -2107,6 +2113,7 @@ export function svgElem(tag: string, ...args: [] | [attributes: { $: string } &
attributes = {};
children = args[0];
} else {
// eslint-disable-next-line local/code-no-any-casts
attributes = args[0] as any || {};
children = args[1];
}
@@ -2118,6 +2125,7 @@ export function svgElem(tag: string, ...args: [] | [attributes: { $: string } &
}
const tagName = match.groups['tag'] || 'div';
// eslint-disable-next-line local/code-no-any-casts
const el = document.createElementNS('http://www.w3.org/2000/svg', tagName) as any as HTMLElement;
if (match.groups['id']) {
@@ -2280,11 +2288,13 @@ export namespace n {
const obsRef = attributes.obsRef;
delete attributes.obsRef;
// eslint-disable-next-line local/code-no-any-casts
return new ObserverNodeWithElement(tag as any, ref, obsRef, elementNs, className, attributes, children);
};
}
function node<TMap extends Record<string, any>, TKey extends keyof TMap>(tag: TKey, elementNs: string | undefined = undefined): DomCreateFn<TMap[TKey], TMap[TKey]> {
// eslint-disable-next-line local/code-no-any-casts
const f = nodeNs(elementNs) as any;
return (attributes, children) => {
return f(tag, attributes, children);
@@ -2312,6 +2322,7 @@ export namespace n {
return value;
}
});
// eslint-disable-next-line local/code-no-any-casts
return result as any;
}
}
@@ -2423,12 +2434,14 @@ export abstract class ObserverNode<T extends HTMLOrSVGElement = HTMLOrSVGElement
if (isObservable(value)) {
this._deriveds.push(derived(this, reader => {
/** @description set.tabIndex */
// eslint-disable-next-line local/code-no-any-casts
this._element.tabIndex = value.read(reader) as any;
}));
} else {
this._element.tabIndex = value;
}
} else if (key.startsWith('on')) {
// eslint-disable-next-line local/code-no-any-casts
(this._element as any)[key] = value;
} else {
if (isObservable(value)) {
@@ -2513,6 +2526,7 @@ function resolve<T>(value: ValueOrList<T>, reader: IReader | undefined, cb: (val
}
return;
}
// eslint-disable-next-line local/code-no-any-casts
cb(value as any);
}
function getClassName(className: ValueOrList<string | undefined | false> | undefined, reader: IReader | undefined): string {
+1
View File
@@ -291,6 +291,7 @@ export class FastDomNode<T extends HTMLElement> {
return;
}
this._contain = contain;
// eslint-disable-next-line local/code-no-any-casts
(<any>this.domNode.style).contain = this._contain;
}
+4
View File
@@ -97,6 +97,7 @@ export class DragMouseEvent extends StandardMouseEvent {
constructor(targetWindow: Window, e: MouseEvent) {
super(targetWindow, e);
// eslint-disable-next-line local/code-no-any-casts
this.dataTransfer = (<any>e).dataTransfer;
}
}
@@ -134,6 +135,7 @@ export class StandardWheelEvent {
constructor(e: IMouseWheelEvent | null, deltaX: number = 0, deltaY: number = 0) {
this.browserEvent = e || null;
// eslint-disable-next-line local/code-no-any-casts
this.target = e ? (e.target || (<any>e).targetNode || e.srcElement) : null;
this.deltaY = deltaY;
@@ -150,7 +152,9 @@ export class StandardWheelEvent {
if (e) {
// Old (deprecated) wheel events
// eslint-disable-next-line local/code-no-any-casts
const e1 = <IWebKitMouseWheelEvent><any>e;
// eslint-disable-next-line local/code-no-any-casts
const e2 = <IGeckoMouseWheelEvent><any>e;
const devicePixelRatio = e.view?.devicePixelRatio || 1;
+2
View File
@@ -16,6 +16,7 @@ export function createTrustedTypesPolicy<Options extends TrustedTypePolicyOption
policyOptions?: Options,
): undefined | Pick<TrustedTypePolicy<Options>, 'name' | Extract<keyof Options, keyof TrustedTypePolicyOptions>>;
}
// eslint-disable-next-line local/code-no-any-casts
const monacoEnvironment: IMonacoEnvironment | undefined = (globalThis as any).MonacoEnvironment;
if (monacoEnvironment?.createTrustedTypesPolicy) {
@@ -27,6 +28,7 @@ export function createTrustedTypesPolicy<Options extends TrustedTypePolicyOption
}
}
try {
// eslint-disable-next-line local/code-no-any-casts
return (globalThis as any).trustedTypes?.createPolicy(policyName, policyOptions);
} catch (err) {
onUnexpectedError(err);
+3
View File
@@ -63,6 +63,7 @@ export interface GridBranchNode<T extends IView> {
export type GridNode<T extends IView> = GridLeafNode<T> | GridBranchNode<T>;
export function isGridBranchNode<T extends IView>(node: GridNode<T>): node is GridBranchNode<T> {
// eslint-disable-next-line local/code-no-any-casts
return !!(node as any).children;
}
@@ -869,7 +870,9 @@ function isGridBranchNodeDescriptor<T>(nodeDescriptor: GridNodeDescriptor<T>): n
}
export function sanitizeGridNodeDescriptor<T>(nodeDescriptor: GridNodeDescriptor<T>, rootNode: boolean): void {
// eslint-disable-next-line local/code-no-any-casts
if (!rootNode && (nodeDescriptor as any).groups && (nodeDescriptor as any).groups.length <= 1) {
// eslint-disable-next-line local/code-no-any-casts
(nodeDescriptor as any).groups = undefined;
}
+1
View File
@@ -193,6 +193,7 @@ export interface GridBranchNode {
export type GridNode = GridLeafNode | GridBranchNode;
export function isGridBranchNode(node: GridNode): node is GridBranchNode {
// eslint-disable-next-line local/code-no-any-casts
return !!(node as any).children;
}
+4
View File
@@ -488,17 +488,21 @@ export class Sash extends Disposable {
let isMultisashResize = false;
// eslint-disable-next-line local/code-no-any-casts
if (!(event as any).__orthogonalSashEvent) {
const orthogonalSash = this.getOrthogonalSash(event);
if (orthogonalSash) {
isMultisashResize = true;
// eslint-disable-next-line local/code-no-any-casts
(event as any).__orthogonalSashEvent = true;
orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
}
}
// eslint-disable-next-line local/code-no-any-casts
if (this.linkedSash && !(event as any).__linkedSashEvent) {
// eslint-disable-next-line local/code-no-any-casts
(event as any).__linkedSashEvent = true;
this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
}
@@ -168,9 +168,11 @@ function asListOptions<T, TFilterData, TRef>(modelProvider: () => ITreeModel<T,
dnd: options.dnd && disposableStore.add(new TreeNodeListDragAndDrop(modelProvider, options.dnd)),
multipleSelectionController: options.multipleSelectionController && {
isSelectionSingleChangeEvent(e) {
// eslint-disable-next-line local/code-no-any-casts
return options.multipleSelectionController!.isSelectionSingleChangeEvent({ ...e, element: e.element } as any);
},
isSelectionRangeChangeEvent(e) {
// eslint-disable-next-line local/code-no-any-casts
return options.multipleSelectionController!.isSelectionRangeChangeEvent({ ...e, element: e.element } as any);
}
},
@@ -1181,6 +1183,7 @@ export class FindController<T, TFilterData> extends AbstractFindController<T, TF
this.tree.refilter();
if (pattern) {
// eslint-disable-next-line local/code-no-any-casts
this.tree.focusNext(0, true, undefined, (node) => !FuzzyScore.isDefault(node.filterData as any as FuzzyScore));
}
@@ -1206,6 +1209,7 @@ export class FindController<T, TFilterData> extends AbstractFindController<T, TF
return true;
}
// eslint-disable-next-line local/code-no-any-casts
return !FuzzyScore.isDefault(node.filterData as any as FuzzyScore);
}
@@ -2234,6 +2238,7 @@ class Trait<T> {
) { }
set(nodes: ITreeNode<T, any>[], browserEvent?: UIEvent): void {
// eslint-disable-next-line local/code-no-any-casts
if (!(browserEvent as any)?.__forceEvent && equals(this.nodes, nodes)) {
return;
}
@@ -302,6 +302,7 @@ class AsyncFindController<TInput, T, TFilterData> extends FindController<T, TFil
contextViewProvider: IContextViewProvider,
options: IAbstractTreeOptions<IAsyncDataTreeNode<TInput, T>, TFilterData>,
) {
// eslint-disable-next-line local/code-no-any-casts
super(tree as any, filter, contextViewProvider, options);
// Always make sure to end the session before disposing
this.disposables.add(toDisposable(async () => {
@@ -413,6 +414,7 @@ class AsyncFindController<TInput, T, TFilterData> extends FindController<T, TFil
return true;
}
// eslint-disable-next-line local/code-no-any-casts
return !FuzzyScore.isDefault(node.filterData as any as FuzzyScore);
}
}
@@ -429,9 +431,11 @@ function asObjectTreeOptions<TInput, T, TFilterData>(options?: IAsyncDataTreeOpt
dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd),
multipleSelectionController: options.multipleSelectionController && {
isSelectionSingleChangeEvent(e) {
// eslint-disable-next-line local/code-no-any-casts
return options.multipleSelectionController!.isSelectionSingleChangeEvent({ ...e, element: e.element } as any);
},
isSelectionRangeChangeEvent(e) {
// eslint-disable-next-line local/code-no-any-casts
return options.multipleSelectionController!.isSelectionRangeChangeEvent({ ...e, element: e.element } as any);
}
},
@@ -86,6 +86,7 @@ interface CollapsedStateUpdate {
type CollapseStateUpdate = CollapsibleStateUpdate | CollapsedStateUpdate;
function isCollapsibleStateUpdate(update: CollapseStateUpdate): update is CollapsibleStateUpdate {
// eslint-disable-next-line local/code-no-any-casts
return typeof (update as any).collapsible === 'boolean';
}

Some files were not shown because too many files have changed in this diff Show More