|
| 1 | +import {CodeFixContextBase, Diagnostics, DiagnosticWithLocation, textChanges} from "../_namespaces/ts"; |
| 2 | +import {codeFixAll, createCodeFixAction, registerCodeFix} from "../_namespaces/ts.codefix"; |
| 3 | +import {ChangeTracker} from "../textChanges"; |
| 4 | + |
| 5 | + |
| 6 | +const fixId = "fixMissingReferenceDirectivesForIsolatedDeclarations"; |
| 7 | +const errorCodes = [ |
| 8 | + Diagnostics.Declaration_emit_for_this_expression_requires_adding_a_type_reference_directive_to_0_with_isolatedDeclarations, |
| 9 | + Diagnostics.Declaration_emit_for_this_expression_requires_adding_a_path_reference_directive_to_0_with_isolatedDeclarations |
| 10 | +].map((diag) => diag.code); |
| 11 | + |
| 12 | +registerCodeFix({ |
| 13 | + errorCodes, |
| 14 | + fixIds: [fixId], |
| 15 | + getCodeActions(context) { |
| 16 | + const {span, sourceFile, program} = context; |
| 17 | + const diags = program.getDeclarationDiagnostics(sourceFile); |
| 18 | + const diagOnNode = diags.find((diag) => diag.start === span.start); |
| 19 | + if (diagOnNode) { |
| 20 | + const changes = textChanges.ChangeTracker.with(context, (changeTracker) => fixDiag(context, diagOnNode, changeTracker)); |
| 21 | + return [ |
| 22 | + createCodeFixAction( |
| 23 | + fixId, |
| 24 | + changes, |
| 25 | + Diagnostics.Add_triple_slash_directives_for_import_resolution, |
| 26 | + fixId, |
| 27 | + // TODO: ADD |
| 28 | + Diagnostics.Add_triple_slash_directives_for_import_resolution)]; |
| 29 | + } |
| 30 | + }, |
| 31 | + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { |
| 32 | + fixDiag(context, diag, changes) |
| 33 | + }), |
| 34 | +}); |
| 35 | + |
| 36 | +function fixDiag(context: CodeFixContextBase, diag: DiagnosticWithLocation, changeTracker: ChangeTracker) { |
| 37 | + const messageText = diag.messageText as string; |
| 38 | + const first = messageText.indexOf("'"); |
| 39 | + const last = messageText.lastIndexOf("'"); |
| 40 | + const tripleSlashType = diag.code === Diagnostics.Declaration_emit_for_this_expression_requires_adding_a_type_reference_directive_to_0_with_isolatedDeclarations.code ? 'types' : 'path' |
| 41 | + changeTracker.insertText(context.sourceFile, 0, `/// <reference ${tripleSlashType}='${messageText.substring(first + 1, last)}' />\n`); |
| 42 | +} |
0 commit comments