Skip to content

Commit

Permalink
chore: process require property in getImportSpecifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
trivikr committed Feb 28, 2024
1 parent 9633f12 commit cbf9cf9
Showing 1 changed file with 38 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@
import { Collection, JSCodeshift, ObjectProperty, Property } from "jscodeshift";
import { Collection, Identifier, JSCodeshift, ObjectProperty, Property } from "jscodeshift";
import { OBJECT_PROPERTY_TYPE_LIST } from "../../config";
import { ImportSpecifierType } from "../types";
import { ImportSpecifierPattern, ImportSpecifierType } from "../types";
import { getRequireDeclarators } from "./getRequireDeclarators";

const getImportSpecifiersFromObjectPattern = (properties: (Property | ObjectProperty)[]) => {
const importSpecifiers = new Set<ImportSpecifierPattern>();

for (const property of properties) {
if (!OBJECT_PROPERTY_TYPE_LIST.includes(property.type)) {
continue;
}
const objectProperty = property as Property | ObjectProperty;
const key = objectProperty.key;
const value = objectProperty.value;
if (key.type === "Identifier" && value.type === "Identifier") {
importSpecifiers.add({
importedName: key.name,
localName: value.name,
});
}
}

return Array.from(importSpecifiers);
};

export const getImportSpecifiers = (
j: JSCodeshift,
source: Collection<unknown>,
Expand All @@ -12,27 +33,27 @@ export const getImportSpecifiers = (

for (const varDeclarator of getRequireDeclarators(j, source, path).nodes()) {
const declaratorId = varDeclarator.id;
const declaratorInit = varDeclarator.init;

if (declaratorId.type === "Identifier") {
const declaratorIdName = declaratorId.name;
importSpecifiers.add(declaratorIdName);
if (declaratorInit!.type === "MemberExpression") {
importSpecifiers.add({
importedName: (declaratorInit.property as Identifier).name,
localName: declaratorIdName,
});
} else {
importSpecifiers.add(declaratorIdName);
}
}

if (declaratorId.type === "ObjectPattern") {
const properties = declaratorId.properties;
for (const property of properties) {
if (!OBJECT_PROPERTY_TYPE_LIST.includes(property.type)) {
continue;
}
const objectProperty = property as Property | ObjectProperty;
const key = objectProperty.key;
const value = objectProperty.value;
if (key.type === "Identifier" && value.type === "Identifier") {
importSpecifiers.add({
importedName: key.name,
localName: value.name,
});
}
if (declaratorInit!.type !== "CallExpression") {
continue;
}
const properties = declaratorId.properties as (Property | ObjectProperty)[];
for (const importSpecifier of getImportSpecifiersFromObjectPattern(properties)) {
importSpecifiers.add(importSpecifier);
}
}
}
Expand Down

0 comments on commit cbf9cf9

Please sign in to comment.