UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

581 lines (580 loc) 25.7 kB
"use strict"; var __extends = (this && this.__extends)/* istanbul ignore next */ || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign)/* istanbul ignore next */ || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; var __awaiter = (this && this.__awaiter)/* istanbul ignore next */ || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator)/* istanbul ignore next */ || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __read = (this && this.__read)/* istanbul ignore next */ || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread)/* istanbul ignore next */ || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; var __values = (this && this.__values)/* istanbul ignore next */ || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; }; Object.defineProperty(exports, "__esModule", { value: true }); var ts = require("typescript"); var errors = require("./../../errors"); var manipulation_1 = require("./../../manipulation"); var textSeek_1 = require("./../../manipulation/textSeek"); var structureToTexts_1 = require("./../../structureToTexts"); var utils_1 = require("./../../utils"); var callBaseFill_1 = require("./../callBaseFill"); var base_1 = require("./../base"); var common_1 = require("./../common"); var statement_1 = require("./../statement"); var FileSystemRefreshResult_1 = require("./FileSystemRefreshResult"); // todo: not sure why I need to explicitly type this in order to get VS to not complain... (TS 2.4.1) exports.SourceFileBase = base_1.TextInsertableNode(statement_1.StatementedNode(common_1.Node)); var SourceFile = /** @class */ (function (_super) { __extends(SourceFile, _super); /** * Initializes a new instance. * @internal * @param global - Global container. * @param node - Underlying node. */ function SourceFile(global, node) { var _this = // start hack :( _super.call(this, global, node, undefined) || this; /** @internal */ _this._isSaved = false; _this.sourceFile = _this; return _this; // end hack } /** * Fills the node from a structure. * @param structure - Structure to fill. */ SourceFile.prototype.fill = function (structure) { callBaseFill_1.callBaseFill(exports.SourceFileBase.prototype, this, structure); if (structure.imports != null) this.addImports(structure.imports); if (structure.exports != null) this.addExports(structure.exports); return this; }; /** * @internal * * WARNING: This should only be called by the compiler factory! */ SourceFile.prototype.replaceCompilerNodeFromFactory = function (compilerNode) { _super.prototype.replaceCompilerNodeFromFactory.call(this, compilerNode); this.global.resetProgram(); // make sure the program has the latest source file this._isSaved = false; }; /** * Gets the file path. */ SourceFile.prototype.getFilePath = function () { return this.compilerNode.fileName; }; /** * Gets the file path's base name. */ SourceFile.prototype.getBaseName = function () { return utils_1.FileUtils.getBaseName(this.getFilePath()); }; /** * Gets the directory that the source file is contained in. */ SourceFile.prototype.getDirectory = function () { return this.global.compilerFactory.getDirectory(this.getDirectoryPath()); }; /** * Gets the directory path that the source file is contained in. */ SourceFile.prototype.getDirectoryPath = function () { return utils_1.FileUtils.getDirPath(this.compilerNode.fileName); }; /** * Copy this source file to a new file. * @param filePath - A new file path. Can be relative to the original file or an absolute path. */ SourceFile.prototype.copy = function (filePath) { var absoluteFilePath = utils_1.FileUtils.getStandardizedAbsolutePath(filePath, this.getDirectoryPath()); return this.global.compilerFactory.createSourceFileFromText(absoluteFilePath, this.getFullText()); }; /** * Asynchronously deletes the file from the file system. */ SourceFile.prototype.delete = function () { return __awaiter(this, void 0, void 0, function () { var filePath; return __generator(this, function (_a) { switch (_a.label) { case 0: filePath = this.getFilePath(); this.forget(); return [4 /*yield*/, this.global.fileSystem.delete(filePath)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Synchronously deletes the file from the file system. */ SourceFile.prototype.deleteSync = function () { var filePath = this.getFilePath(); this.forget(); this.global.fileSystem.deleteSync(filePath); }; /** * Asynchronously saves this file with any changes. */ SourceFile.prototype.save = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, utils_1.FileUtils.ensureDirectoryExists(this.global.fileSystem, this.getDirectoryPath())]; case 1: _a.sent(); return [4 /*yield*/, this.global.fileSystem.writeFile(this.getFilePath(), this.getFullText())]; case 2: _a.sent(); this._isSaved = true; return [2 /*return*/]; } }); }); }; /** * Synchronously saves this file with any changes. */ SourceFile.prototype.saveSync = function () { utils_1.FileUtils.ensureDirectoryExistsSync(this.global.fileSystem, this.getDirectoryPath()); this.global.fileSystem.writeFileSync(this.getFilePath(), this.getFullText()); this._isSaved = true; }; /** * Gets any referenced files. */ SourceFile.prototype.getReferencedFiles = function () { var _this = this; // todo: add tests var dirPath = this.getDirectoryPath(); return (this.compilerNode.referencedFiles || []) .map(function (f) { return _this.global.compilerFactory.getSourceFileFromFilePath(utils_1.FileUtils.pathJoin(dirPath, f.fileName)); }) .filter(function (f) { return f != null; }); }; /** * Gets the source files for any type reference directives. */ SourceFile.prototype.getTypeReferenceDirectives = function () { var _this = this; // todo: add tests var dirPath = this.getDirectoryPath(); return (this.compilerNode.typeReferenceDirectives || []) .map(function (f) { return _this.global.compilerFactory.getSourceFileFromFilePath(utils_1.FileUtils.pathJoin(dirPath, f.fileName)); }) .filter(function (f) { return f != null; }); }; /** * Gets the source file language variant. */ SourceFile.prototype.getLanguageVariant = function () { return this.compilerNode.languageVariant; }; /** * Gets if this is a declaration file. */ SourceFile.prototype.isDeclarationFile = function () { return this.compilerNode.isDeclarationFile; }; /** * Gets if this source file has been saved or if the latest changes have been saved. */ SourceFile.prototype.isSaved = function () { return this._isSaved; }; /** * Sets if this source file has been saved. * @internal */ SourceFile.prototype.setIsSaved = function (value) { this._isSaved = value; }; /** * Add an import. * @param structure - Structure that represents the import. */ SourceFile.prototype.addImport = function (structure) { return this.addImports([structure])[0]; }; /** * Add imports. * @param structures - Structures that represent the imports. */ SourceFile.prototype.addImports = function (structures) { var imports = this.getImports(); var insertIndex = imports.length === 0 ? 0 : imports[imports.length - 1].getChildIndex() + 1; return this.insertImports(insertIndex, structures); }; /** * Insert an import. * @param index - Index to insert at. * @param structure - Structure that represents the import. */ SourceFile.prototype.insertImport = function (index, structure) { return this.insertImports(index, [structure])[0]; }; /** * Insert imports into a file. * @param index - Index to insert at. * @param structures - Structures that represent the imports to insert. */ SourceFile.prototype.insertImports = function (index, structures) { var _this = this; var newLineChar = this.global.manipulationSettings.getNewLineKind(); var indentationText = this.getChildIndentationText(); var texts = structures.map(function (structure) { // todo: pass the StructureToText to the method below var writer = _this.getWriter(); var structureToText = new structureToTexts_1.ImportDeclarationStructureToText(writer); structureToText.writeText(structure); return writer.toString(); }); return this._insertMainChildren(index, texts, structures, ts.SyntaxKind.ImportDeclaration, undefined, { previousBlanklineWhen: function (previousMember) { return !(utils_1.TypeGuards.isImportDeclaration(previousMember)); }, nextBlanklineWhen: function (nextMember) { return !(utils_1.TypeGuards.isImportDeclaration(nextMember)); }, separatorNewlineWhen: function () { return false; } }); }; /** * Gets the first import declaration that matches a condition, or undefined if it doesn't exist. * @param condition - Condition to get the import by. */ SourceFile.prototype.getImport = function (condition) { return utils_1.ArrayUtils.find(this.getImports(), condition); }; /** * Gets the first import declaration that matches a condition, or throws if it doesn't exist. * @param condition - Condition to get the import by. */ SourceFile.prototype.getImportOrThrow = function (condition) { return errors.throwIfNullOrUndefined(this.getImport(condition), "Expected to find an import with the provided condition."); }; /** * Get the file's import declarations. */ SourceFile.prototype.getImports = function () { // todo: remove type assertion return this.getChildSyntaxListOrThrow().getChildrenOfKind(ts.SyntaxKind.ImportDeclaration); }; /** * Add an export. * @param structure - Structure that represents the export. */ SourceFile.prototype.addExport = function (structure) { return this.addExports([structure])[0]; }; /** * Add exports. * @param structures - Structures that represent the exports. */ SourceFile.prototype.addExports = function (structures) { // always insert at end of file because of export {Identifier}; statements return this.insertExports(this.getChildSyntaxListOrThrow().getChildCount(), structures); }; /** * Insert an export. * @param index - Index to insert at. * @param structure - Structure that represents the export. */ SourceFile.prototype.insertExport = function (index, structure) { return this.insertExports(index, [structure])[0]; }; /** * Insert exports into a file. * @param index - Index to insert at. * @param structures - Structures that represent the exports to insert. */ SourceFile.prototype.insertExports = function (index, structures) { var newLineChar = this.global.manipulationSettings.getNewLineKind(); var quoteType = this.global.manipulationSettings.getQuoteType(); var indentationText = this.getChildIndentationText(); var texts = structures.map(function (structure) { var hasModuleSpecifier = structure.moduleSpecifier != null && structure.moduleSpecifier.length > 0; var code = indentationText + "export"; if (structure.namedExports != null && structure.namedExports.length > 0) { var namedExportsCode = structure.namedExports.map(function (n) { var namedExportCode = n.name; if (n.alias != null) namedExportCode += " as " + n.alias; return namedExportCode; }).join(", "); code += " {" + namedExportsCode + "}"; } else if (!hasModuleSpecifier) code += " {}"; else code += " *"; if (hasModuleSpecifier) code += " from " + quoteType + structure.moduleSpecifier + quoteType; code += ";"; return code; }); return this._insertMainChildren(index, texts, structures, ts.SyntaxKind.ExportDeclaration, undefined, { previousBlanklineWhen: function (previousMember) { return !(utils_1.TypeGuards.isExportDeclaration(previousMember)); }, nextBlanklineWhen: function (nextMember) { return !(utils_1.TypeGuards.isExportDeclaration(nextMember)); }, separatorNewlineWhen: function () { return false; } }); }; /** * Gets the first export declaration that matches a condition, or undefined if it doesn't exist. * @param condition - Condition to get the export by. */ SourceFile.prototype.getExport = function (condition) { return utils_1.ArrayUtils.find(this.getExports(), condition); }; /** * Gets the first export declaration that matches a condition, or throws if it doesn't exist. * @param condition - Condition to get the export by. */ SourceFile.prototype.getExportOrThrow = function (condition) { return errors.throwIfNullOrUndefined(this.getExport(condition), "Expected to find an export with the provided condition."); }; /** * Get the file's export declarations. */ SourceFile.prototype.getExports = function () { // todo: remove type assertion return this.getChildSyntaxListOrThrow().getChildrenOfKind(ts.SyntaxKind.ExportDeclaration); }; /** * Gets the default export symbol of the file. */ SourceFile.prototype.getDefaultExportSymbol = function () { var sourceFileSymbol = this.getSymbol(); // will be undefined when the source file doesn't have an export if (sourceFileSymbol == null) return undefined; return sourceFileSymbol.getExportByName("default"); }; /** * Gets the default export symbol of the file or throws if it doesn't exist. */ SourceFile.prototype.getDefaultExportSymbolOrThrow = function () { return errors.throwIfNullOrUndefined(this.getDefaultExportSymbol(), "Expected to find a default export symbol"); }; /** * Gets the syntactic, semantic, and declaration diagnostics. */ SourceFile.prototype.getDiagnostics = function () { return __spread(this.global.program.getSyntacticDiagnostics(this), this.global.program.getSemanticDiagnostics(this), this.global.program.getDeclarationDiagnostics(this)); }; /** * Gets the pre-emit diagnostics. */ SourceFile.prototype.getPreEmitDiagnostics = function () { return this.global.program.getPreEmitDiagnostics(this); }; /** * Removes any "export default"; */ SourceFile.prototype.removeDefaultExport = function (defaultExportSymbol) { defaultExportSymbol = defaultExportSymbol || this.getDefaultExportSymbol(); if (defaultExportSymbol == null) return this; var declaration = defaultExportSymbol.getDeclarations()[0]; if (declaration.compilerNode.kind === ts.SyntaxKind.ExportAssignment) manipulation_1.removeChildrenWithFormatting({ children: [declaration], getSiblingFormatting: function () { return manipulation_1.FormattingKind.Newline; } }); else if (utils_1.TypeGuards.isModifierableNode(declaration)) { declaration.toggleModifier("default", false); declaration.toggleModifier("export", false); } return this; }; SourceFile.prototype.unindent = function (positionRangeOrPos, times) { if (times === void 0) { times = 1; } return this.indent(positionRangeOrPos, times * -1); }; SourceFile.prototype.indent = function (positionRangeOrPos, times) { if (times === void 0) { times = 1; } if (times === 0) return this; var sourceFileText = this.getFullText(); var positionRange = typeof positionRangeOrPos === "number" ? [positionRangeOrPos, positionRangeOrPos] : positionRangeOrPos; errors.throwIfRangeOutOfRange(positionRange, [0, sourceFileText.length], "positionRange"); var startLinePos = textSeek_1.getPreviousMatchingPos(sourceFileText, positionRange[0], function (char) { return char === "\n"; }); var endLinePos = textSeek_1.getNextMatchingPos(sourceFileText, positionRange[1], function (char) { return char === "\r" || char === "\n"; }); var indentText = this.global.manipulationSettings.getIndentationText(); var unindentRegex = times > 0 ? undefined : new RegExp(getDeindentRegexText()); var pos = startLinePos; var newLines = []; try { for (var _a = __values(sourceFileText.substring(startLinePos, endLinePos).split("\n")), _b = _a.next(); !_b.done; _b = _a.next()) { var line = _b.value; if (this.isInStringAtPos(pos)) newLines.push(line); else if (times > 0) newLines.push(utils_1.StringUtils.repeat(indentText, times) + line); else newLines.push(line.replace(unindentRegex, "")); pos += line.length; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_b && !_b.done && (_c = _a.return)) _c.call(_a); } finally { if (e_1) throw e_1.error; } } manipulation_1.replaceSourceFileTextForFormatting({ sourceFile: this, newText: sourceFileText.substring(0, startLinePos) + newLines.join("\n") + sourceFileText.substring(endLinePos) }); return this; function getDeindentRegexText() { var isSpaces = /^ +$/; var text = "^"; for (var i = 0; i < Math.abs(times); i++) { text += "("; if (isSpaces.test(indentText)) { // the optional string makes it possible to unindent when a line doesn't have the full number of spaces for (var j = 0; j < indentText.length; j++) text += " ?"; } else text += indentText; text += "|\t)?"; } return text; } var e_1, _c; }; /** * Emits the source file. */ SourceFile.prototype.emit = function (options) { return this.global.program.emit(__assign({ targetSourceFile: this }, options)); }; /** * Formats the source file text using the internal TypeScript formatting API. */ SourceFile.prototype.formatText = function (settings) { if (settings === void 0) { settings = {}; } manipulation_1.replaceSourceFileTextForFormatting({ sourceFile: this, newText: this.global.languageService.getFormattedDocumentText(this.getFilePath(), settings) }); }; /** * Refresh the source file from the file system. * * WARNING: When updating from the file system, this will "forget" any previously navigated nodes. * @returns What action ended up taking place. */ SourceFile.prototype.refreshFromFileSystem = function () { return __awaiter(this, void 0, void 0, function () { var fileReadResult; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, utils_1.FileUtils.readFileOrNotExists(this.global.fileSystem, this.getFilePath(), this.global.getEncoding())]; case 1: fileReadResult = _a.sent(); return [2 /*return*/, this._refreshFromFileSystemInternal(fileReadResult)]; } }); }); }; /** * Synchronously refreshes the source file from the file system. * * WARNING: When updating from the file system, this will "forget" any previously navigated nodes. * @returns What action ended up taking place. */ SourceFile.prototype.refreshFromFileSystemSync = function () { var fileReadResult = utils_1.FileUtils.readFileOrNotExistsSync(this.global.fileSystem, this.getFilePath(), this.global.getEncoding()); return this._refreshFromFileSystemInternal(fileReadResult); }; SourceFile.prototype._refreshFromFileSystemInternal = function (fileReadResult) { if (fileReadResult === false) { this.forget(); return FileSystemRefreshResult_1.FileSystemRefreshResult.Deleted; } var fileText = fileReadResult; if (fileText === this.getFullText()) return FileSystemRefreshResult_1.FileSystemRefreshResult.NoChange; this.replaceText([0, this.getEnd()], fileText); return FileSystemRefreshResult_1.FileSystemRefreshResult.Updated; }; return SourceFile; }(exports.SourceFileBase)); exports.SourceFile = SourceFile;