UNPKG

@navikt/aksel

Version:

Aksel command line interface. Codemods and other utilities for Aksel users.

79 lines (78 loc) 3.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addPackageImport = void 0; exports.default = moveAndRenameImport; // add import declaration after first existing import declaration, or // at the beginning of the file const addPackageImport = ({ j, root, packageName, specifiers, }) => { const existingImport = root.find(j.ImportDeclaration); const importDecl = j.importDeclaration(specifiers.map((specifier) => j.importSpecifier(j.identifier(specifier))), j.stringLiteral(packageName)); if (existingImport.length === 0) { root.get().node.program.body.unshift(importDecl); } else { existingImport.insertBefore(importDecl); } }; exports.addPackageImport = addPackageImport; function moveAndRenameImport(j, root, { fromImport, toImport, fromName, toName, ignoreAlias = false, }) { var _a, _b; /* Does package-name exist */ const existingFromImport = root.find(j.ImportDeclaration, { source: { value: fromImport, }, }); if (!existingFromImport.length) { return null; } let localname = fromName; const existingFromImportSpecifier = existingFromImport === null || existingFromImport === void 0 ? void 0 : existingFromImport.find(j.ImportSpecifier, (node) => { if (node.imported.name === fromName) { localname = node.local.name; } return node.imported.name === fromName; }); if (!existingFromImport.length || !(existingFromImportSpecifier === null || existingFromImportSpecifier === void 0 ? void 0 : existingFromImportSpecifier.length)) { return null; } if ((existingFromImportSpecifier === null || existingFromImportSpecifier === void 0 ? void 0 : existingFromImportSpecifier.length) > 0) { existingFromImportSpecifier.remove(); } /* Remove import if its now empty */ if (!((_a = existingFromImport.get("specifiers").value) === null || _a === void 0 ? void 0 : _a.length) || ((_b = existingFromImport.get("specifiers").value) === null || _b === void 0 ? void 0 : _b.length) === 0) { existingFromImport.remove(); } /* Does package exist */ const existingImport = root.find(j.ImportDeclaration, { source: { value: toImport, }, }); /* Check if migrated name allready exist */ const existingImportSpecifier = existingImport.find(j.ImportSpecifier, { imported: { name: toName, }, }); if (existingImportSpecifier.length <= 0) { const newImportSpecifier = ignoreAlias ? j.importSpecifier(j.identifier(toName)) : j.importSpecifier(j.identifier(toName), j.identifier(localname)); if (existingImport.length > 0) { existingImport.get("specifiers").push(newImportSpecifier); } else { const newImport = j.importDeclaration([newImportSpecifier], j.stringLiteral(toImport)); const lastImport = root.find(j.ImportDeclaration).at(-1); if (lastImport.length > 0) { lastImport.insertAfter(newImport); } else { root.get().node.program.body.unshift(newImport); } } } return localname; }