|
1 | 1 | import type { Edit, SgRoot, Range } from "@codemod.com/jssg-types/main"; |
2 | 2 | import { getNodeRequireCalls } from "@nodejs/codemod-utils/ast-grep/require-call"; |
3 | 3 | import { removeLines } from "@nodejs/codemod-utils/ast-grep/remove-lines"; |
| 4 | +import { removeBinding } from "@nodejs/codemod-utils/ast-grep/remove-binding"; |
4 | 5 |
|
5 | 6 | /** |
6 | 7 | * Transforms `process.mainModule` usage to `require.main`. Handles direct global access |
@@ -47,38 +48,21 @@ export default function transform(root: SgRoot): string | null { |
47 | 48 | for (const declarationNode of [...requireDeclarations, ...destructureDeclarations]) { |
48 | 49 | // Step 1: Get all requires from module nodule:process that is destructuring mainModule: |
49 | 50 | if (declarationNode.text().includes("mainModule")) { |
50 | | - const objectPattern = declarationNode.find({ |
51 | | - rule: { |
52 | | - kind: "object_pattern", |
53 | | - }, |
54 | | - }); |
55 | | - |
56 | | - if (!objectPattern) continue; |
57 | | - |
58 | | - // Step2: Handle the destructuring import: |
59 | | - const declarations = declarationNode.findAll({ |
60 | | - rule: { |
61 | | - kind: "shorthand_property_identifier_pattern", |
62 | | - }, |
63 | | - }); |
| 51 | + // @ts-ignore - ast-grep types are not fully compatible with JSSG types |
| 52 | + const result = removeBinding(declarationNode, "mainModule"); |
64 | 53 |
|
65 | | - if (declarations.length !== 0) { |
| 54 | + if (result) { |
66 | 55 | patternsToReplace.push({ |
67 | 56 | pattern: "mainModule", |
68 | 57 | }); |
69 | | - } |
70 | | - |
71 | | - // When 'mainModule' is the only item imported, remove to whole thing to avoid an empty import |
72 | | - if (declarations.length === 1) { |
73 | | - linesToRemove.push(declarationNode.range()); |
74 | | - } |
75 | 58 |
|
76 | | - if (declarations.length > 1) { |
77 | | - const restDeclarations = declarations |
78 | | - .map((d) => d.text()) |
79 | | - .filter((d) => d !== "mainModule"); |
| 59 | + if (result.edit) { |
| 60 | + edits.push(result.edit); |
| 61 | + } |
80 | 62 |
|
81 | | - edits.push(objectPattern.replace(`{ ${restDeclarations.join(", ")} }`)); |
| 63 | + if (result.lineToRemove) { |
| 64 | + linesToRemove.push(result.lineToRemove); |
| 65 | + } |
82 | 66 | } |
83 | 67 | } |
84 | 68 | } |
|
0 commit comments