ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
819 lines (818 loc) • 37.7 kB
JavaScript
"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 __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 };
}
};
};
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var typescript_1 = 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.addImportDeclarations(structure.imports);
if (structure.exports != null)
this.addExportDeclarations(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);
};
/**
* Gets the line number of the provided position.
* @param pos - Position
*/
SourceFile.prototype.getLineNumberFromPos = function (pos) {
return utils_1.StringUtils.getLineNumberFromPos(this.getFullText(), pos);
};
/**
* 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.
* @param options - Options for copying.
*/
SourceFile.prototype.copy = function (filePath, options) {
if (options === void 0) { options = {}; }
var _a = options.overwrite, overwrite = _a === void 0 ? false : _a;
var absoluteFilePath = utils_1.FileUtils.getStandardizedAbsolutePath(this.global.fileSystem, filePath, this.getDirectoryPath());
if (overwrite)
return this.global.compilerFactory.createOrOverwriteSourceFileFromText(absoluteFilePath, this.getFullText());
try {
return this.global.compilerFactory.createSourceFileFromText(absoluteFilePath, this.getFullText());
}
catch (err) {
if (err instanceof errors.InvalidOperationError)
throw new errors.InvalidOperationError("Did you mean to provide the overwrite option? " + err.message);
else
throw err;
}
};
/**
* 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 () {
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.addImportDeclaration = function (structure) {
return this.addImportDeclarations([structure])[0];
};
/**
* Add imports.
* @param structures - Structures that represent the imports.
*/
SourceFile.prototype.addImportDeclarations = function (structures) {
var imports = this.getImportDeclarations();
var insertIndex = imports.length === 0 ? 0 : imports[imports.length - 1].getChildIndex() + 1;
return this.insertImportDeclarations(insertIndex, structures);
};
/**
* Insert an import.
* @param index - Index to insert at.
* @param structure - Structure that represents the import.
*/
SourceFile.prototype.insertImportDeclaration = function (index, structure) {
return this.insertImportDeclarations(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.insertImportDeclarations = function (index, structures) {
var _this = this;
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, typescript_1.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.getImportDeclaration = function (condition) {
return utils_1.ArrayUtils.find(this.getImportDeclarations(), 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.getImportDeclarationOrThrow = function (condition) {
return errors.throwIfNullOrUndefined(this.getImportDeclaration(condition), "Expected to find an import with the provided condition.");
};
/**
* Get the file's import declarations.
*/
SourceFile.prototype.getImportDeclarations = function () {
// todo: remove type assertion
return this.getChildSyntaxListOrThrow().getChildrenOfKind(typescript_1.SyntaxKind.ImportDeclaration);
};
/**
* Add export declarations.
* @param structure - Structure that represents the export.
*/
SourceFile.prototype.addExportDeclaration = function (structure) {
return this.addExportDeclarations([structure])[0];
};
/**
* Add export declarations.
* @param structures - Structures that represent the exports.
*/
SourceFile.prototype.addExportDeclarations = function (structures) {
// always insert at end of file because of export {Identifier}; statements
return this.insertExportDeclarations(this.getChildSyntaxListOrThrow().getChildCount(), structures);
};
/**
* Insert an export declaration.
* @param index - Index to insert at.
* @param structure - Structure that represents the export.
*/
SourceFile.prototype.insertExportDeclaration = function (index, structure) {
return this.insertExportDeclarations(index, [structure])[0];
};
/**
* Insert export declarations into a file.
* @param index - Index to insert at.
* @param structures - Structures that represent the exports to insert.
*/
SourceFile.prototype.insertExportDeclarations = function (index, structures) {
var _this = this;
var texts = structures.map(function (structure) {
// todo: pass the StructureToText to the method below
var writer = _this.getWriter();
var structureToText = new structureToTexts_1.ExportDeclarationStructureToText(writer);
structureToText.writeText(structure);
return writer.toString();
});
return this._insertMainChildren(index, texts, structures, typescript_1.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 declaration by.
*/
SourceFile.prototype.getExportDeclaration = function (condition) {
return utils_1.ArrayUtils.find(this.getExportDeclarations(), condition);
};
/**
* Gets the first export declaration that matches a condition, or throws if it doesn't exist.
* @param condition - Condition to get the export declaration by.
*/
SourceFile.prototype.getExportDeclarationOrThrow = function (condition) {
return errors.throwIfNullOrUndefined(this.getExportDeclaration(condition), "Expected to find an export declaration with the provided condition.");
};
/**
* Get the file's export declarations.
*/
SourceFile.prototype.getExportDeclarations = function () {
return this.getChildSyntaxListOrThrow().getChildrenOfKind(typescript_1.SyntaxKind.ExportDeclaration);
};
/**
* Gets the export symbols of the source file.
*/
SourceFile.prototype.getExportSymbols = function () {
return this.global.typeChecker.getExportsOfModule(this.getSymbolOrThrow());
};
/**
* Gets all the declarations exported from the file.
*/
SourceFile.prototype.getExportedDeclarations = function () {
var exportSymbols = this.getExportSymbols();
return utils_1.ArrayUtils.from(getDeclarationsForSymbols());
function getDeclarationsForSymbols() {
function getDeclarationHandlingExportSpecifiers(declaration) {
var _a, _b, d, e_1_1, identifier, symbol, _c, _d, d, e_2_1, e_1, _e, e_2, _f;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
if (handledDeclarations.has(declaration))
return [2 /*return*/];
handledDeclarations.add(declaration);
if (!(declaration.getKind() === typescript_1.SyntaxKind.ExportSpecifier)) return [3 /*break*/, 9];
_g.label = 1;
case 1:
_g.trys.push([1, 6, 7, 8]);
_a = __values(declaration.getLocalTargetDeclarations()), _b = _a.next();
_g.label = 2;
case 2:
if (!!_b.done) return [3 /*break*/, 5];
d = _b.value;
return [5 /*yield**/, __values(getDeclarationHandlingExportSpecifiers(d))];
case 3:
_g.sent();
_g.label = 4;
case 4:
_b = _a.next();
return [3 /*break*/, 2];
case 5: return [3 /*break*/, 8];
case 6:
e_1_1 = _g.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 8];
case 7:
try {
if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
}
finally { if (e_1) throw e_1.error; }
return [7 /*endfinally*/];
case 8: return [3 /*break*/, 20];
case 9:
if (!(declaration.getKind() === typescript_1.SyntaxKind.ExportAssignment)) return [3 /*break*/, 18];
identifier = declaration.getExpression();
if (identifier == null || identifier.getKind() !== typescript_1.SyntaxKind.Identifier)
return [2 /*return*/];
symbol = identifier.getSymbol();
if (symbol == null)
return [2 /*return*/];
_g.label = 10;
case 10:
_g.trys.push([10, 15, 16, 17]);
_c = __values(symbol.getDeclarations()), _d = _c.next();
_g.label = 11;
case 11:
if (!!_d.done) return [3 /*break*/, 14];
d = _d.value;
return [5 /*yield**/, __values(getDeclarationHandlingExportSpecifiers(d))];
case 12:
_g.sent();
_g.label = 13;
case 13:
_d = _c.next();
return [3 /*break*/, 11];
case 14: return [3 /*break*/, 17];
case 15:
e_2_1 = _g.sent();
e_2 = { error: e_2_1 };
return [3 /*break*/, 17];
case 16:
try {
if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
}
finally { if (e_2) throw e_2.error; }
return [7 /*endfinally*/];
case 17: return [3 /*break*/, 20];
case 18: return [4 /*yield*/, declaration];
case 19:
_g.sent();
_g.label = 20;
case 20: return [2 /*return*/];
}
});
}
var handledDeclarations, exportSymbols_1, exportSymbols_1_1, symbol, _a, _b, declaration, e_3_1, e_4_1, e_4, _c, e_3, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
handledDeclarations = utils_1.createHashSet();
_e.label = 1;
case 1:
_e.trys.push([1, 12, 13, 14]);
exportSymbols_1 = __values(exportSymbols), exportSymbols_1_1 = exportSymbols_1.next();
_e.label = 2;
case 2:
if (!!exportSymbols_1_1.done) return [3 /*break*/, 11];
symbol = exportSymbols_1_1.value;
_e.label = 3;
case 3:
_e.trys.push([3, 8, 9, 10]);
_a = __values(symbol.getDeclarations()), _b = _a.next();
_e.label = 4;
case 4:
if (!!_b.done) return [3 /*break*/, 7];
declaration = _b.value;
return [5 /*yield**/, __values(getDeclarationHandlingExportSpecifiers(declaration))];
case 5:
_e.sent();
_e.label = 6;
case 6:
_b = _a.next();
return [3 /*break*/, 4];
case 7: return [3 /*break*/, 10];
case 8:
e_3_1 = _e.sent();
e_3 = { error: e_3_1 };
return [3 /*break*/, 10];
case 9:
try {
if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
}
finally { if (e_3) throw e_3.error; }
return [7 /*endfinally*/];
case 10:
exportSymbols_1_1 = exportSymbols_1.next();
return [3 /*break*/, 2];
case 11: return [3 /*break*/, 14];
case 12:
e_4_1 = _e.sent();
e_4 = { error: e_4_1 };
return [3 /*break*/, 14];
case 13:
try {
if (exportSymbols_1_1 && !exportSymbols_1_1.done && (_c = exportSymbols_1.return)) _c.call(exportSymbols_1);
}
finally { if (e_4) throw e_4.error; }
return [7 /*endfinally*/];
case 14: return [2 /*return*/];
}
});
}
};
/**
* Add export assignments.
* @param structure - Structure that represents the export.
*/
SourceFile.prototype.addExportAssignment = function (structure) {
return this.addExportAssignments([structure])[0];
};
/**
* Add export assignments.
* @param structures - Structures that represent the exports.
*/
SourceFile.prototype.addExportAssignments = function (structures) {
// always insert at end of file because of export {Identifier}; statements
return this.insertExportAssignments(this.getChildSyntaxListOrThrow().getChildCount(), structures);
};
/**
* Insert an export assignment.
* @param index - Index to insert at.
* @param structure - Structure that represents the export.
*/
SourceFile.prototype.insertExportAssignment = function (index, structure) {
return this.insertExportAssignments(index, [structure])[0];
};
/**
* Insert export assignments into a file.
* @param index - Index to insert at.
* @param structures - Structures that represent the exports to insert.
*/
SourceFile.prototype.insertExportAssignments = function (index, structures) {
var _this = this;
var texts = structures.map(function (structure) {
// todo: pass the StructureToText to the method below
var writer = _this.getWriter();
var structureToText = new structureToTexts_1.ExportAssignmentStructureToText(writer);
structureToText.writeText(structure);
return writer.toString();
});
return this._insertMainChildren(index, texts, structures, typescript_1.SyntaxKind.ExportAssignment, undefined, {
previousBlanklineWhen: function (previousMember) { return !(utils_1.TypeGuards.isExportAssignment(previousMember)); },
nextBlanklineWhen: function (nextMember) { return !(utils_1.TypeGuards.isExportAssignment(nextMember)); },
separatorNewlineWhen: function () { return false; }
});
};
/**
* Gets the first export assignment that matches a condition, or undefined if it doesn't exist.
* @param condition - Condition to get the export assignment by.
*/
SourceFile.prototype.getExportAssignment = function (condition) {
return utils_1.ArrayUtils.find(this.getExportAssignments(), condition);
};
/**
* Gets the first export assignment that matches a condition, or throws if it doesn't exist.
* @param condition - Condition to get the export assignment by.
*/
SourceFile.prototype.getExportAssignmentOrThrow = function (condition) {
return errors.throwIfNullOrUndefined(this.getExportAssignment(condition), "Expected to find an export assignment with the provided condition.");
};
/**
* Get the file's export assignments.
*/
SourceFile.prototype.getExportAssignments = function () {
return this.getChildSyntaxListOrThrow().getChildrenOfKind(typescript_1.SyntaxKind.ExportAssignment);
};
/**
* 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 === typescript_1.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_5_1) { e_5 = { error: e_5_1 }; }
finally {
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_5) throw e_5.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_5, _c;
};
/**
* Emits the source file.
*/
SourceFile.prototype.emit = function (options) {
return this.global.program.emit(__assign({ targetSourceFile: this }, options));
};
/**
* Gets the emit output of this source file.
* @param options - Emit options.
*/
SourceFile.prototype.getEmitOutput = function (options) {
if (options === void 0) { options = {}; }
return this.global.languageService.getEmitOutput(this, options.emitOnlyDtsFiles || false);
};
/**
* Formats the source file text using the internal TypeScript formatting API.
* @param settings - Format code settings.
*/
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);
};
/**
* Gets the relative path to another source file.
* @param sourceFile - Source file.
*/
SourceFile.prototype.getRelativePathToSourceFile = function (sourceFile) {
return utils_1.FileUtils.getRelativePathTo(this.getFilePath(), sourceFile.getFilePath());
};
/**
* Gets the relative path to the specified source file as a module specifier.
* @param sourceFile - Source file.
*/
SourceFile.prototype.getRelativePathToSourceFileAsModuleSpecifier = function (sourceFile) {
var sourceFilePath = sourceFile.getFilePath().replace(/\/index(\.d\.ts|\.ts|\.js)$/i, "");
return "./" + utils_1.FileUtils.getRelativePathTo(this.getFilePath(), sourceFilePath).replace(/((\.d\.ts$)|(\.[^/.]+$))/i, "");
};
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);
this.setIsSaved(true); // saved when loaded from file system
return FileSystemRefreshResult_1.FileSystemRefreshResult.Updated;
};
return SourceFile;
}(exports.SourceFileBase));
exports.SourceFile = SourceFile;