@ts-ast-parser/core
Version:
Reflects a simplified version of the TypeScript AST for generating documentation
91 lines • 2.8 kB
JavaScript
import ts from 'typescript';
/**
* Internal class to enqueue any error during the analysis.
*
* There are two types of errors the analyser can throw:
*
* - **Config errors**: Errors because of invalid compiler options
* - **Syntactic/Semantic errors**: Errors thrown by the TypeScript compiler when parsing the code
*/
export class AnalyserDiagnostic {
constructor(system) {
Object.defineProperty(this, "_diagnostics", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "_formatDiagnosticHost", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this._formatDiagnosticHost = {
getCanonicalFileName: (name) => name,
getCurrentDirectory: () => system.getCurrentDirectory(),
getNewLine: () => system.newLine,
};
}
/**
* Formats syntactic and semantic errors found during the analysis
*
* @param errors
* @returns The diagnostics formatted
*/
format(errors) {
return ts.formatDiagnosticsWithColorAndContext(errors, this._formatDiagnosticHost);
}
/**
* Used to retrieve all the errors the analyser has encountered
*
* @returns All the errors
*/
getAll() {
return Array.from(ts.sortAndDeduplicateDiagnostics(this._diagnostics));
}
/**
* Checks whether there are errors or not
*
* @returns True if there are no errors, otherwise false
*/
isEmpty() {
return !this._diagnostics.length;
}
/**
* A message may be a chain of multiple messages. This helps provide better
* context for an error. This function flattens the chain of messages
*
* @param diagnostic - The error to flatten
* @returns The messages flattened
*/
flatten(diagnostic) {
return ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
}
/**
* Adds a new diagnostic error
*
* @param node - The node where the error was found
* @param message - The error message
*/
addOne(node, message) {
const error = {
file: node?.getSourceFile(),
start: node?.getStart(),
length: node?.getWidth(),
category: ts.DiagnosticCategory.Error,
messageText: message,
code: 1000000,
};
this._diagnostics.push(error);
}
/**
* Adds multiple syntactic/semantic errors
*
* @param diagnostics - An array of syntactic/semantic errors
*/
addMany(diagnostics) {
this._diagnostics.push(...diagnostics);
}
}
//# sourceMappingURL=analyser-diagnostic.js.map