• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    const fixName = "disableJsDiagnostics";
4    const fixId = "disableJsDiagnostics";
5    const errorCodes = mapDefined(Object.keys(Diagnostics) as readonly (keyof typeof Diagnostics)[], key => {
6        const diag = Diagnostics[key];
7        return diag.category === DiagnosticCategory.Error ? diag.code : undefined;
8    });
9
10    registerCodeFix({
11        errorCodes,
12        getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) {
13            const { sourceFile, program, span, host, formatContext } = context;
14
15            if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
16                return undefined;
17            }
18
19            const newLineCharacter = sourceFile.checkJsDirective ? "" : getNewLineOrDefaultFromHost(host, formatContext.options);
20            const fixes: CodeFixAction[] = [
21                // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file.
22                createCodeFixActionWithoutFixAll(
23                    fixName,
24                    [createFileTextChanges(sourceFile.fileName, [
25                        createTextChange(sourceFile.checkJsDirective
26                            ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end)
27                            : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`),
28                    ])],
29                    Diagnostics.Disable_checking_for_this_file),
30            ];
31
32            if (textChanges.isValidLocationToAddComment(sourceFile, span.start)) {
33                fixes.unshift(createCodeFixAction(fixName, textChanges.ChangeTracker.with(context, t => makeChange(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId, Diagnostics.Add_ts_ignore_to_all_error_messages));
34            }
35
36            return fixes;
37        },
38        fixIds: [fixId],
39        getAllCodeActions: context => {
40            const seenLines = new Set<number>();
41            return codeFixAll(context, errorCodes, (changes, diag) => {
42                if (textChanges.isValidLocationToAddComment(diag.file, diag.start)) {
43                    makeChange(changes, diag.file, diag.start, seenLines);
44                }
45            });
46        },
47    });
48
49    function makeChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, seenLines?: Set<number>) {
50        const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position);
51        // Only need to add `// @ts-ignore` for a line once.
52        if (!seenLines || tryAddToSet(seenLines, lineNumber)) {
53            changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore");
54        }
55    }
56}
57