|
| 1 | +import { getNodeImportStatements } from '@nodejs/codemod-utils/ast-grep/import-statement'; |
| 2 | +import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call'; |
| 3 | +import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path'; |
| 4 | +import type { SgRoot, Edit, SgNode } from '@codemod.com/jssg-types/main'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Classes of the http module |
| 8 | + */ |
| 9 | +const CLASS_NAMES = [ |
| 10 | + 'Agent', |
| 11 | + 'ClientRequest', |
| 12 | + 'IncomingMessage', |
| 13 | + 'OutgoingMessage', |
| 14 | + 'Server', |
| 15 | + 'ServerResponse', |
| 16 | +]; |
| 17 | + |
| 18 | +/** |
| 19 | + * Transform function that converts deprecated node:http classes to use the `new` keyword |
| 20 | + * |
| 21 | + * Handles: |
| 22 | + * 1. `http.Agent()` → `new http.Agent()` |
| 23 | + * 2. `http.ClientRequest()` → `new http.ClientRequest()` |
| 24 | + * 3. `http.IncomingMessage()` → `new http.IncomingMessage()` |
| 25 | + * 4. `http.OutgoingMessage()` → `new http.OutgoingMessage()` |
| 26 | + * 5. `http.Server()` → `new http.Server()` |
| 27 | + * 6. `http.ServerResponse() → `new http.ServerResponse()` |
| 28 | + */ |
| 29 | +export default function transform(root: SgRoot): string | null { |
| 30 | + const rootNode = root.root(); |
| 31 | + const edits: Edit[] = []; |
| 32 | + |
| 33 | + const importNodes = getNodeImportStatements(root, 'http'); |
| 34 | + const requireNodes = getNodeRequireCalls(root, 'http'); |
| 35 | + const allStatementNodes = [...importNodes, ...requireNodes]; |
| 36 | + const classes = new Set<string>(getHttpClassBasePaths(allStatementNodes)); |
| 37 | + |
| 38 | + for (const cls of classes) { |
| 39 | + const classesWithoutNew = rootNode.findAll({ |
| 40 | + rule: { |
| 41 | + not: { follows: { pattern: 'new' } }, |
| 42 | + pattern: `${cls}($$$ARGS)`, |
| 43 | + }, |
| 44 | + }); |
| 45 | + |
| 46 | + for (const clsWithoutNew of classesWithoutNew) { |
| 47 | + edits.push(clsWithoutNew.replace(`new ${clsWithoutNew.text()}`)); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if (edits.length === 0) return null; |
| 52 | + |
| 53 | + return rootNode.commitEdits(edits); |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Get the base path of the http classes |
| 58 | + * |
| 59 | + * @param statements - The import & require statements to search for the http classes |
| 60 | + * @returns The base path of the http classes |
| 61 | + */ |
| 62 | +function* getHttpClassBasePaths(statements: SgNode[]) { |
| 63 | + for (const cls of CLASS_NAMES) { |
| 64 | + for (const stmt of statements) { |
| 65 | + const resolvedPath = resolveBindingPath(stmt, `$.${cls}`); |
| 66 | + if (resolvedPath) { |
| 67 | + yield resolvedPath; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments