hades-cli
Version:
Hades CLI developer tool
72 lines (71 loc) • 2.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImportDriver = void 0;
class ImportDriver {
/**
* Create import in file
*
* @param sourceFile
* @param modules
* @param path
*/
static createImportItems(sourceFile, items, path) {
const itemsToImport = ImportDriver.getUniqueImportItems(sourceFile, items);
const importPaths = ImportDriver.getImportPaths(sourceFile);
if (itemsToImport.length > 0) {
// if exist path add item to import
if (importPaths.includes(path)) {
// check this import not exist yet
const importElement = sourceFile.getImportDeclaration(path);
const itemsToImportChecked = [];
for (let itemToImport of itemsToImport) {
let existItem = false;
for (let importedElement of (importElement === null || importElement === void 0 ? void 0 : importElement.getNamedImports()) ? importElement === null || importElement === void 0 ? void 0 : importElement.getNamedImports() : []) {
if (importedElement.getName() === itemToImport)
existItem = true;
}
if (!existItem)
itemsToImportChecked.push(itemToImport);
}
// add import after check that is not repeated
if (itemsToImportChecked.length > 0)
importElement === null || importElement === void 0 ? void 0 : importElement.addNamedImports(itemsToImportChecked);
}
// create new import
else {
sourceFile.addImportDeclaration({
namedImports: itemsToImport,
moduleSpecifier: path
});
}
}
}
/**
* From the items array, only non-repeating items are returned.
*
* @param sourceFile
* @param moduleNames
*/
static getUniqueImportItems(sourceFile, items) {
// get import to avoid duplicities
const imports = sourceFile.getImportDeclarations();
// get names imported
const itemsImported = imports.flatMap(i => i.getNamedImports().map(j => j.getName()));
// filter only items where is not imported
return items.filter(item => !itemsImported.includes(item));
}
/**
* Return import paths from source
*
* @param sourceFile
*/
static getImportPaths(sourceFile) {
const imports = sourceFile.getImportDeclarations();
let paths = [];
for (const importObj of imports) {
paths.push(importObj.getModuleSpecifier().getLiteralValue());
}
return paths;
}
}
exports.ImportDriver = ImportDriver;