From 2ac48c1d165bfba0e2803b70970230c42e3b372f Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Thu, 19 Nov 2026 11:11:17 +0530 Subject: [PATCH 1/2] feat(DEP0192): migrate internal TLS imports to node:tls Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- package-lock.json | 14 + .../README.md | 16 + .../codemod.yaml | 25 + .../package.json | 24 + .../src/workflow.ts | 695 ++++++++++++++++++ .../tests/already-migrated/expected.mjs | 2 + .../tests/already-migrated/input.mjs | 2 + .../tests/cjs-destructuring/expected.js | 2 + .../tests/cjs-destructuring/input.js | 2 + .../tests/cjs-direct-property/expected.js | 2 + .../tests/cjs-direct-property/input.js | 2 + .../consolidate-existing-tls/expected.mjs | 1 + .../tests/consolidate-existing-tls/input.mjs | 2 + .../tests/dynamic-import/expected.mjs | 6 + .../tests/dynamic-import/input.mjs | 6 + .../tests/esm-aliases/expected.mjs | 1 + .../tests/esm-aliases/input.mjs | 2 + .../tests/esm-named/expected.mjs | 1 + .../tests/esm-named/input.mjs | 1 + .../tests/esm-node-prefix/expected.mjs | 1 + .../tests/esm-node-prefix/input.mjs | 1 + .../tests/mixed-internal-exports/expected.mjs | 2 + .../tests/mixed-internal-exports/input.mjs | 1 + .../tests/re-exports/expected.mjs | 2 + .../tests/re-exports/input.mjs | 2 + .../tests/typescript/expected.ts | 3 + .../tests/typescript/input.ts | 4 + .../tests/unresolved-cases/expected.mjs | 2 + .../tests/unresolved-cases/input.mjs | 2 + .../workflow.yaml | 25 + 30 files changed, 851 insertions(+) create mode 100644 recipes/tls-internal-modules-to-node-tls/README.md create mode 100644 recipes/tls-internal-modules-to-node-tls/codemod.yaml create mode 100644 recipes/tls-internal-modules-to-node-tls/package.json create mode 100644 recipes/tls-internal-modules-to-node-tls/src/workflow.ts create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/already-migrated/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/already-migrated/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/expected.js create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/input.js create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/expected.js create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/input.js create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/esm-named/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/esm-named/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/re-exports/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/re-exports/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/expected.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/input.mjs create mode 100644 recipes/tls-internal-modules-to-node-tls/workflow.yaml diff --git a/package-lock.json b/package-lock.json index 287f3675..f5f49e90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -589,6 +589,10 @@ "resolved": "recipes/timers-deprecations", "link": true }, + "node_modules/@nodejs/tls-internal-modules-to-node-tls": { + "resolved": "recipes/tls-internal-modules-to-node-tls", + "link": true + }, "node_modules/@nodejs/tls-create-secure-pair-to-tls-socket": { "resolved": "recipes/tls-create-secure-pair-to-tls-socket", "link": true @@ -1299,6 +1303,16 @@ "@codemod.com/jssg-types": "^1.6.3" } }, + "recipes/tls-internal-modules-to-node-tls": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@nodejs/codemod-utils": "*" + }, + "devDependencies": { + "@codemod.com/jssg-types": "^1.6.3" + } + }, "recipes/tls-create-secure-pair-to-tls-socket": { "name": "@nodejs/tls-create-secure-pair-to-tls-socket", "dependencies": { diff --git a/recipes/tls-internal-modules-to-node-tls/README.md b/recipes/tls-internal-modules-to-node-tls/README.md new file mode 100644 index 00000000..34731b7b --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/README.md @@ -0,0 +1,16 @@ +# @nodejs/tls-internal-modules-to-node-tls + +Migrates legacy imports of internal Node.js TLS modules (`_tls_common`, `_tls_wrap`) to the public `node:tls` module as introduced under [DEP0192](https://nodejs.org/api/deprecations.html#dep0192-requirenode_tls_common-and-requirenode_tls_wrap). + +## Supported Modules and Exports + +- `_tls_common` / `node:_tls_common`: `SecureContext`, `createSecureContext` +- `_tls_wrap` / `node:_tls_wrap`: `TLSSocket`, `Server`, `createServer`, `connect` + +## Behavior + +- Replaces module specifiers with `node:tls` when accessing supported public exports. +- Supports ESM named imports, CommonJS destructuring, direct property access, dynamic imports, and re-exports. +- Preserves local aliases and handles TypeScript type annotations. +- Consolidates multiple imports targeting `node:tls`. +- Skips internal-only exports (e.g. `translatePeerCertificate`), escaped namespace objects, and unknown properties, reporting them for manual review. diff --git a/recipes/tls-internal-modules-to-node-tls/codemod.yaml b/recipes/tls-internal-modules-to-node-tls/codemod.yaml new file mode 100644 index 00000000..a734ac8f --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/codemod.yaml @@ -0,0 +1,25 @@ +schema_version: "1.0" +name: "@nodejs/tls-internal-modules-to-node-tls" +version: "1.0.0" +description: "Handle DEP0192 by migrating internal TLS module imports (_tls_common, _tls_wrap) to node:tls." +author: Vishal Raj +license: MIT +workflow: workflow.yaml +category: migration +repository: https://github.com/nodejs/userland-migrations + +targets: + languages: + - javascript + - typescript + +keywords: + - transformation + - migration + - nodejs + - tls + - dep0192 + +registry: + access: public + visibility: public diff --git a/recipes/tls-internal-modules-to-node-tls/package.json b/recipes/tls-internal-modules-to-node-tls/package.json new file mode 100644 index 00000000..565e5e6a --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/package.json @@ -0,0 +1,24 @@ +{ + "name": "@nodejs/tls-internal-modules-to-node-tls", + "version": "1.0.0", + "description": "Handle DEP0192 by migrating internal TLS modules (_tls_common, _tls_wrap) to node:tls", + "type": "module", + "scripts": { + "test": "npx codemod jssg test -l typescript ./src/workflow.ts" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/userland-migrations.git", + "directory": "recipes/tls-internal-modules-to-node-tls", + "bugs": "https://github.com/nodejs/userland-migrations/issues" + }, + "author": "Vishal Raj", + "license": "MIT", + "homepage": "https://github.com/nodejs/userland-migrations/blob/main/recipes/tls-internal-modules-to-node-tls/README.md", + "devDependencies": { + "@codemod.com/jssg-types": "^1.6.3" + }, + "dependencies": { + "@nodejs/codemod-utils": "*" + } +} diff --git a/recipes/tls-internal-modules-to-node-tls/src/workflow.ts b/recipes/tls-internal-modules-to-node-tls/src/workflow.ts new file mode 100644 index 00000000..8475d1e4 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/src/workflow.ts @@ -0,0 +1,695 @@ +import type { + Edit, + Range, + SgNode, + SgRoot, +} from '@codemod.com/jssg-types/main'; +import type Js from '@codemod.com/jssg-types/langs/javascript'; +import { + getNodeImportStatements, + getNodeImportCalls, +} from '@nodejs/codemod-utils/ast-grep/import-statement'; +import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call'; +import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines'; + +/** + * Public exports supported by each internal TLS module under DEP0192. + */ +const MODULE_EXPORTS: Record> = { + _tls_common: new Set(['SecureContext', 'createSecureContext']), + _tls_wrap: new Set(['TLSSocket', 'Server', 'createServer', 'connect']), +}; + +const TARGET_MODULES = Object.keys(MODULE_EXPORTS); + +function getInternalModuleName(specifier: string): string | null { + const cleaned = specifier.replace(/^node:/, ''); + if (cleaned in MODULE_EXPORTS) { + return cleaned; + } + return null; +} + +function getUnquotedText(node: SgNode): string { + return node.text().replace(/^['"`]|['"`]$/g, ''); +} + +function warn(root: SgRoot, node: SgNode, message: string): void { + const { start } = node.range(); + console.warn( + `${root.filename()}:${start.line + 1}:${start.column + 1}: ${message}`, + ); +} + +type SpecifierInfo = { + node: SgNode; + text: string; + imported: string; + local: string; +}; + +type ImportStatementInfo = { + statement: SgNode; + sourceNode: SgNode; + rawSource: string; + internalMod: string; + isTypeOnly: boolean; + supported: SpecifierInfo[]; + unsupported: SpecifierInfo[]; +}; + +/** + * Handle DEP0192: migrate internal Node.js TLS modules (_tls_common, _tls_wrap) to node:tls. + */ +export default function transform(root: SgRoot): string | null { + const rootNode = root.root(); + const edits: Edit[] = []; + const linesToRemove: Range[] = []; + + // 1. Process ESM import statements using getNodeImportStatements utility + processImportStatements(root, rootNode, edits, linesToRemove); + + // 2. Process ESM export statements (re-exports) + processExportStatements(root, rootNode, edits); + + // 3. Process CommonJS require calls using getNodeRequireCalls utility + processRequireCalls(root, rootNode, edits); + + // 4. Process dynamic import(...) calls using getNodeImportCalls utility + processDynamicImports(root, rootNode, edits); + + if (edits.length === 0 && linesToRemove.length === 0) { + return null; + } + + const transformed = rootNode.commitEdits(edits); + if (linesToRemove.length > 0) { + return removeLines(transformed, linesToRemove); + } + + return transformed; +} + +/** + * Handle ESM import statements: + * - Uses getNodeImportStatements from @nodejs/codemod-utils for target and tls imports + * - Replaces specifier with 'node:tls' when exports are supported + * - Consolidates multiple compatible imports targeting 'node:tls' + * - Splits mixed imports (retaining unsupported exports in the internal module) + * - Skips and reports namespace and unsupported imports + */ +function processImportStatements( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], + linesToRemove: Range[], +): void { + // Find pre-existing node:tls imports using the workspace utility and type import matching + const existingTlsStmts = [ + ...getNodeImportStatements(root, 'tls'), + ...rootNode.findAll({ + rule: { + kind: 'import_statement', + has: { + field: 'source', + kind: 'string', + has: { + kind: 'string_fragment', + regex: '^(node:)?tls$', + }, + }, + pattern: 'import type $$$IMPORTS from $SOURCE', + }, + }), + ]; + + const existingTlsImports: { + statement: SgNode; + isTypeOnly: boolean; + namedImports: SgNode | null; + }[] = existingTlsStmts.map((stmt) => ({ + statement: stmt, + isTypeOnly: stmt.text().startsWith('import type'), + namedImports: stmt.find({ rule: { kind: 'named_imports' } }), + })); + + const internalImports: ImportStatementInfo[] = []; + + for (const mod of TARGET_MODULES) { + const statements = [ + ...getNodeImportStatements(root, mod), + ...rootNode.findAll({ + rule: { + kind: 'import_statement', + has: { + field: 'source', + kind: 'string', + has: { + kind: 'string_fragment', + regex: `^(node:)?${mod}$`, + }, + }, + pattern: 'import type $$$IMPORTS from $SOURCE', + }, + }), + ]; + + for (const stmt of statements) { + const sourceNode = stmt.field('source'); + if (!sourceNode) continue; + + const rawSource = getUnquotedText(sourceNode); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + // Check for namespace import: import * as foo from '_tls_*' + const nsImport = stmt.find({ rule: { kind: 'namespace_import' } }); + if (nsImport) { + warn( + root, + stmt, + `Namespace import '${nsImport.text()}' from '${rawSource}' is skipped; review manually (DEP0192)`, + ); + continue; + } + + const specifiers = stmt.findAll({ rule: { kind: 'import_specifier' } }); + if (specifiers.length === 0) { + warn( + root, + stmt, + `Import from '${rawSource}' without named specifiers is skipped; review manually (DEP0192)`, + ); + continue; + } + + const isTypeOnly = stmt.text().startsWith('import type'); + const supported: SpecifierInfo[] = []; + const unsupported: SpecifierInfo[] = []; + + for (const spec of specifiers) { + const nameNode = spec.field('name'); + const aliasNode = spec.field('alias'); + const imported = nameNode ? nameNode.text() : spec.text(); + const local = aliasNode ? aliasNode.text() : imported; + + if (MODULE_EXPORTS[internalMod].has(imported)) { + supported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + } else { + unsupported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + warn( + root, + spec, + `Internal-only export '${imported}' from '${rawSource}' cannot be migrated to 'node:tls' (DEP0192)`, + ); + } + } + + if (supported.length > 0) { + internalImports.push({ + statement: stmt, + sourceNode, + rawSource, + internalMod, + isTypeOnly, + supported, + unsupported, + }); + } + } + } + + if (internalImports.length === 0) return; + + // Group internal imports by type-only status + const valueInternal = internalImports.filter((i) => !i.isTypeOnly); + const typeInternal = internalImports.filter((i) => i.isTypeOnly); + + consolidateImportsGroup( + valueInternal, + existingTlsImports.find((e) => !e.isTypeOnly), + edits, + linesToRemove, + ); + + consolidateImportsGroup( + typeInternal, + existingTlsImports.find((e) => e.isTypeOnly), + edits, + linesToRemove, + ); +} + +function consolidateImportsGroup( + imports: ImportStatementInfo[], + existingTls: + | { + statement: SgNode; + isTypeOnly: boolean; + namedImports: SgNode | null; + } + | undefined, + edits: Edit[], + linesToRemove: Range[], +): void { + if (imports.length === 0) return; + + // Case 1: Consolidate into pre-existing node:tls import + if (existingTls?.namedImports) { + const existingNamedText = existingTls.namedImports.text(); + const existingSpecs = existingNamedText + .replace(/^\{\s*|\s*\}$/g, '') + .split(',') + .map((s) => s.trim()) + .filter(Boolean); + + const specsToAdd: string[] = []; + + for (const imp of imports) { + for (const sup of imp.supported) { + if (!existingSpecs.includes(sup.text)) { + specsToAdd.push(sup.text); + existingSpecs.push(sup.text); + } + } + + if (imp.unsupported.length === 0) { + linesToRemove.push(imp.statement.range()); + } else { + const named = imp.statement.find({ + rule: { kind: 'named_imports' }, + }); + if (named) { + const remaining = imp.unsupported.map((u) => u.text).join(', '); + edits.push(named.replace(`{ ${remaining} }`)); + } + } + } + + if (specsToAdd.length > 0) { + const allSpecs = [ + ...existingNamedText + .replace(/^\{\s*|\s*\}$/g, '') + .split(',') + .map((s) => s.trim()) + .filter(Boolean), + ...specsToAdd, + ].join(', '); + + edits.push(existingTls.namedImports.replace(`{ ${allSpecs} }`)); + } + return; + } + + // Case 2: No pre-existing node:tls import, but multiple or single internal imports + const [first, ...rest] = imports; + + if (rest.length === 0 && first.unsupported.length === 0) { + edits.push(first.sourceNode.replace("'node:tls'")); + return; + } + + const consolidatedSpecs: string[] = []; + for (const sup of first.supported) { + if (!consolidatedSpecs.includes(sup.text)) { + consolidatedSpecs.push(sup.text); + } + } + + for (const rem of rest) { + for (const sup of rem.supported) { + if (!consolidatedSpecs.includes(sup.text)) { + consolidatedSpecs.push(sup.text); + } + } + + if (rem.unsupported.length === 0) { + linesToRemove.push(rem.statement.range()); + } else { + const named = rem.statement.find({ + rule: { kind: 'named_imports' }, + }); + if (named) { + const remaining = rem.unsupported.map((u) => u.text).join(', '); + edits.push(named.replace(`{ ${remaining} }`)); + } + } + } + + if (first.unsupported.length === 0) { + edits.push(first.sourceNode.replace("'node:tls'")); + const named = first.statement.find({ rule: { kind: 'named_imports' } }); + if (named) { + edits.push(named.replace(`{ ${consolidatedSpecs.join(', ')} }`)); + } + } else { + const remaining = first.unsupported.map((u) => u.text).join(', '); + const typePrefix = first.isTypeOnly ? 'type ' : ''; + const firstSource = first.sourceNode.text(); + const newStmt = `import ${typePrefix}{ ${remaining} } from ${firstSource};\nimport ${typePrefix}{ ${consolidatedSpecs.join(', ')} } from 'node:tls';`; + edits.push(first.statement.replace(newStmt)); + } +} + +/** + * Handle ESM export statements (re-exports): + * - export { TLSSocket } from '_tls_wrap'; + */ +function processExportStatements( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], +): void { + const exportStatements = rootNode.findAll({ + rule: { kind: 'export_statement' }, + }); + + for (const stmt of exportStatements) { + const sourceNode = stmt.field('source'); + if (!sourceNode) continue; + + const rawSource = getUnquotedText(sourceNode); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + const specifiers = stmt.findAll({ rule: { kind: 'export_specifier' } }); + if (specifiers.length === 0) continue; + + const supported: SpecifierInfo[] = []; + const unsupported: SpecifierInfo[] = []; + + for (const spec of specifiers) { + const nameNode = spec.field('name'); + const aliasNode = spec.field('alias'); + const imported = nameNode ? nameNode.text() : spec.text(); + const local = aliasNode ? aliasNode.text() : imported; + + if (MODULE_EXPORTS[internalMod].has(imported)) { + supported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + } else { + unsupported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + warn( + root, + spec, + `Internal-only re-export '${imported}' from '${rawSource}' cannot be migrated to 'node:tls' (DEP0192)`, + ); + } + } + + if (supported.length > 0 && unsupported.length === 0) { + edits.push(sourceNode.replace("'node:tls'")); + } else if (supported.length > 0 && unsupported.length > 0) { + const remaining = unsupported.map((u) => u.text).join(', '); + const supText = supported.map((s) => s.text).join(', '); + const sourceText = sourceNode.text(); + const newStmt = `export { ${remaining} } from ${sourceText};\nexport { ${supText} } from 'node:tls';`; + edits.push(stmt.replace(newStmt)); + } + } +} + +/** + * Handle CommonJS require calls: + * - Uses getNodeRequireCalls from @nodejs/codemod-utils for target modules + * - Handles destructuring: const { TLSSocket } = require('_tls_wrap'); + * - Handles member expressions: const TLSSocket = require('_tls_wrap').TLSSocket; + * - Skips and warns on namespace objects: const tls = require('_tls_wrap'); + */ +function processRequireCalls( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], +): void { + // Member expressions: const TLSSocket = require('_tls_wrap').TLSSocket; + const memberRequires = rootNode.findAll({ + rule: { + kind: 'member_expression', + all: [ + { + has: { + field: 'object', + kind: 'call_expression', + all: [ + { + has: { + field: 'function', + kind: 'identifier', + regex: '^require$', + }, + }, + ], + }, + }, + ], + }, + }); + + for (const expr of memberRequires) { + const call = expr.field('object'); + const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const rawSource = getUnquotedText(stringArg); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + const prop = expr.field('property'); + if (prop && MODULE_EXPORTS[internalMod].has(prop.text())) { + edits.push(stringArg.replace("'node:tls'")); + } else { + warn( + root, + prop || expr, + `Unknown/internal property '${prop?.text()}' on '${rawSource}' is skipped; review manually (DEP0192)`, + ); + } + } + + // Use getNodeRequireCalls from local workspace utility for variable declarations + for (const mod of TARGET_MODULES) { + const declarators = getNodeRequireCalls(root, mod); + + for (const declarator of declarators) { + if (declarator.field('value')?.is('member_expression')) continue; + + const call = declarator.find({ + rule: { + kind: 'call_expression', + has: { field: 'function', regex: '^require$' }, + }, + }); + const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const rawSource = getUnquotedText(stringArg); + const namePattern = declarator.field('name'); + + if (namePattern?.is('object_pattern')) { + const shorthandProps = namePattern.findAll({ + rule: { kind: 'shorthand_property_identifier_pattern' }, + }); + const pairProps = namePattern.findAll({ + rule: { kind: 'pair_pattern' }, + }); + + const supportedNames: string[] = []; + const unsupportedNames: string[] = []; + + for (const sh of shorthandProps) { + const name = sh.text(); + if (MODULE_EXPORTS[mod].has(name)) { + supportedNames.push(name); + } else { + unsupportedNames.push(name); + warn( + root, + sh, + `Internal-only export '${name}' from '${rawSource}' cannot be migrated to 'node:tls' (DEP0192)`, + ); + } + } + + for (const pair of pairProps) { + const key = pair.field('key')?.text() || ''; + if (MODULE_EXPORTS[mod].has(key)) { + supportedNames.push(pair.text()); + } else { + unsupportedNames.push(pair.text()); + warn( + root, + pair, + `Internal-only export '${key}' from '${rawSource}' cannot be migrated to 'node:tls' (DEP0192)`, + ); + } + } + + if (supportedNames.length > 0 && unsupportedNames.length === 0) { + edits.push(stringArg.replace("'node:tls'")); + } else if ( + supportedNames.length > 0 && + unsupportedNames.length > 0 + ) { + const declParent = declarator.parent(); + const kind = declParent?.kind() === 'lexical_declaration' ? 'const' : 'var'; + const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});\n${kind} { ${supportedNames.join(', ')} } = require('node:tls');`; + if (declParent) { + edits.push(declParent.replace(newDecl)); + } + } + continue; + } + + // Un-destructured namespace object: const tls = require('_tls_wrap') + warn( + root, + declarator, + `Namespace object '${namePattern?.text()}' from '${rawSource}' is skipped; review manually (DEP0192)`, + ); + } + } +} + +/** + * Handle dynamic import(...) calls: + * - Uses getNodeImportCalls from @nodejs/codemod-utils for target modules + * - Handles: const { TLSSocket } = await import('_tls_wrap'); + * - Handles: import('_tls_wrap').then(m => m.connect); + */ +function processDynamicImports( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], +): void { + for (const mod of TARGET_MODULES) { + const declarators = getNodeImportCalls(root, mod); + + for (const declarator of declarators) { + const name = declarator.field('name'); + if (name?.is('object_pattern')) { + const props = name.findAll({ + rule: { + any: [ + { kind: 'shorthand_property_identifier_pattern' }, + { kind: 'pair_pattern' }, + ], + }, + }); + const allSupported = + props.length > 0 && + props.every((p) => { + const key = + p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); + return MODULE_EXPORTS[mod].has(key); + }); + + if (allSupported) { + const stringArg = declarator.find({ + rule: { kind: 'string' }, + }); + if (stringArg) { + edits.push(stringArg.replace("'node:tls'")); + } + } + } + } + } + + // Chained .then(...) calls: import('_tls_*').then(...) + const thenImports = rootNode.findAll({ + rule: { + kind: 'call_expression', + all: [ + { + has: { + field: 'function', + kind: 'member_expression', + has: { field: 'property', regex: '^then$' }, + }, + }, + ], + }, + }); + + for (const thenCall of thenImports) { + const memberFn = thenCall.field('function'); + const objectCall = memberFn?.field('object'); + if (!objectCall?.is('call_expression')) continue; + + const importFn = objectCall.field('function'); + if (importFn?.kind() !== 'import') continue; + + const stringArg = objectCall.field('arguments')?.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const rawSource = getUnquotedText(stringArg); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + const callback = thenCall.field('arguments')?.child(1); + if (!callback) continue; + + let isSupported = false; + const param = callback.field('parameters') || callback.field('parameter'); + if (param) { + const destructured = param.findAll({ + rule: { + any: [ + { kind: 'shorthand_property_identifier_pattern' }, + { kind: 'pair_pattern' }, + ], + }, + }); + if ( + destructured.length > 0 && + destructured.every((p) => { + const key = + p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); + return MODULE_EXPORTS[internalMod].has(key); + }) + ) { + isSupported = true; + } + } + + const members = callback.findAll({ + rule: { kind: 'member_expression' }, + }); + for (const m of members) { + const prop = m.field('property')?.text() || ''; + if (MODULE_EXPORTS[internalMod].has(prop)) { + isSupported = true; + break; + } + } + + if (isSupported) { + edits.push(stringArg.replace("'node:tls'")); + } else { + warn( + root, + thenCall, + `Dynamic import of '${rawSource}' without verified public exports is skipped; review manually (DEP0192)`, + ); + } + } +} diff --git a/recipes/tls-internal-modules-to-node-tls/tests/already-migrated/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/already-migrated/expected.mjs new file mode 100644 index 00000000..364817c4 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/already-migrated/expected.mjs @@ -0,0 +1,2 @@ +import { createSecureContext } from 'node:tls'; +const { TLSSocket } = require('node:tls'); diff --git a/recipes/tls-internal-modules-to-node-tls/tests/already-migrated/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/already-migrated/input.mjs new file mode 100644 index 00000000..364817c4 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/already-migrated/input.mjs @@ -0,0 +1,2 @@ +import { createSecureContext } from 'node:tls'; +const { TLSSocket } = require('node:tls'); diff --git a/recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/expected.js b/recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/expected.js new file mode 100644 index 00000000..7bce0866 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/expected.js @@ -0,0 +1,2 @@ +const { createSecureContext: makeContext } = require('node:tls'); +const { TLSSocket, Server } = require('node:tls'); diff --git a/recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/input.js b/recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/input.js new file mode 100644 index 00000000..90f6213e --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/cjs-destructuring/input.js @@ -0,0 +1,2 @@ +const { createSecureContext: makeContext } = require('_tls_common'); +const { TLSSocket, Server } = require('node:_tls_wrap'); diff --git a/recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/expected.js b/recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/expected.js new file mode 100644 index 00000000..691f029a --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/expected.js @@ -0,0 +1,2 @@ +const TLSSocket = require('node:tls').TLSSocket; +const createServer = require('node:tls').createServer; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/input.js b/recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/input.js new file mode 100644 index 00000000..4c29faaa --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/cjs-direct-property/input.js @@ -0,0 +1,2 @@ +const TLSSocket = require('_tls_wrap').TLSSocket; +const createServer = require('node:_tls_wrap').createServer; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/expected.mjs new file mode 100644 index 00000000..20462f17 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/expected.mjs @@ -0,0 +1 @@ +import { connect, createSecureContext } from 'node:tls'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/input.mjs new file mode 100644 index 00000000..0a393665 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/consolidate-existing-tls/input.mjs @@ -0,0 +1,2 @@ +import { connect } from 'node:tls'; +import { createSecureContext } from '_tls_common'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/expected.mjs new file mode 100644 index 00000000..56364e42 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/expected.mjs @@ -0,0 +1,6 @@ +async function init() { + const { TLSSocket } = await import('node:tls'); + const { SecureContext } = await import('node:tls'); + const connect = await import('node:tls').then((m) => m.connect); + return { TLSSocket, SecureContext, connect }; +} diff --git a/recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/input.mjs new file mode 100644 index 00000000..5756b68f --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/dynamic-import/input.mjs @@ -0,0 +1,6 @@ +async function init() { + const { TLSSocket } = await import('_tls_wrap'); + const { SecureContext } = await import('node:_tls_common'); + const connect = await import('_tls_wrap').then((m) => m.connect); + return { TLSSocket, SecureContext, connect }; +} diff --git a/recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/expected.mjs new file mode 100644 index 00000000..8f081f07 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/expected.mjs @@ -0,0 +1 @@ +import { createSecureContext as makeContext, TLSSocket, connect as tlsConnect } from 'node:tls'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/input.mjs new file mode 100644 index 00000000..9a548cda --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/esm-aliases/input.mjs @@ -0,0 +1,2 @@ +import { createSecureContext as makeContext } from '_tls_common'; +import { TLSSocket, connect as tlsConnect } from 'node:_tls_wrap'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/esm-named/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/esm-named/expected.mjs new file mode 100644 index 00000000..b9b4c276 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/esm-named/expected.mjs @@ -0,0 +1 @@ +import { createSecureContext } from 'node:tls'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/esm-named/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/esm-named/input.mjs new file mode 100644 index 00000000..90ec8ef1 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/esm-named/input.mjs @@ -0,0 +1 @@ +import { createSecureContext } from '_tls_common'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/expected.mjs new file mode 100644 index 00000000..15252387 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/expected.mjs @@ -0,0 +1 @@ +import { TLSSocket } from 'node:tls'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/input.mjs new file mode 100644 index 00000000..dab0f6ab --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/esm-node-prefix/input.mjs @@ -0,0 +1 @@ +import { TLSSocket } from 'node:_tls_wrap'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/expected.mjs new file mode 100644 index 00000000..c3f14b6b --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/expected.mjs @@ -0,0 +1,2 @@ +import { translatePeerCertificate } from '_tls_wrap'; +import { TLSSocket } from 'node:tls'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/input.mjs new file mode 100644 index 00000000..3e5d3d1a --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/mixed-internal-exports/input.mjs @@ -0,0 +1 @@ +import { TLSSocket, translatePeerCertificate } from '_tls_wrap'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/re-exports/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/re-exports/expected.mjs new file mode 100644 index 00000000..ccd8abab --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/re-exports/expected.mjs @@ -0,0 +1,2 @@ +export { createSecureContext } from 'node:tls'; +export { TLSSocket as CustomSocket } from 'node:tls'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/re-exports/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/re-exports/input.mjs new file mode 100644 index 00000000..8275facb --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/re-exports/input.mjs @@ -0,0 +1,2 @@ +export { createSecureContext } from '_tls_common'; +export { TLSSocket as CustomSocket } from 'node:_tls_wrap'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts b/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts new file mode 100644 index 00000000..e1c664d9 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts @@ -0,0 +1,3 @@ +import type { SecureContext, TLSSocket } from 'node:tls'; + +function check(ctx: SecureContext, socket: TLSSocket): void {} diff --git a/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts b/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts new file mode 100644 index 00000000..dcfe927e --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts @@ -0,0 +1,4 @@ +import type { SecureContext } from '_tls_common'; +import type { TLSSocket } from 'node:_tls_wrap'; + +function check(ctx: SecureContext, socket: TLSSocket): void {} diff --git a/recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/expected.mjs b/recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/expected.mjs new file mode 100644 index 00000000..9a47ec51 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/expected.mjs @@ -0,0 +1,2 @@ +const tls = require('_tls_wrap'); +import * as common from '_tls_common'; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/input.mjs b/recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/input.mjs new file mode 100644 index 00000000..9a47ec51 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/tests/unresolved-cases/input.mjs @@ -0,0 +1,2 @@ +const tls = require('_tls_wrap'); +import * as common from '_tls_common'; diff --git a/recipes/tls-internal-modules-to-node-tls/workflow.yaml b/recipes/tls-internal-modules-to-node-tls/workflow.yaml new file mode 100644 index 00000000..eda89aa2 --- /dev/null +++ b/recipes/tls-internal-modules-to-node-tls/workflow.yaml @@ -0,0 +1,25 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/codemod-com/codemod/refs/heads/main/schemas/workflow.json + +version: "1" + +nodes: + - id: apply-transforms + name: Apply AST Transformations + type: automatic + steps: + - name: Handle DEP0192 by migrating internal TLS module imports to node:tls + js-ast-grep: + js_file: src/workflow.ts + base_path: . + include: + - "**/*.js" + - "**/*.jsx" + - "**/*.mjs" + - "**/*.cjs" + - "**/*.cts" + - "**/*.mts" + - "**/*.ts" + - "**/*.tsx" + exclude: + - "**/node_modules/**" + language: typescript From cf50ed72f356b3da68f5519927cb13c5f653bbc4 Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Thu, 19 Nov 2026 21:51:32 +0530 Subject: [PATCH 2/2] refactor(tls-internal-modules-to-node-tls): address review feedback Simplify workflow.ts by leveraging @nodejs/codemod-utils directly for import statements and require calls. Replace kind() === checks with .is(), remove verbose type annotations, handle CRLF and LF newlines dynamically, and update test fixtures. Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- .../src/workflow.ts | 222 ++++++------------ .../tests/typescript/expected.ts | 2 +- .../tests/typescript/input.ts | 4 +- 3 files changed, 72 insertions(+), 156 deletions(-) diff --git a/recipes/tls-internal-modules-to-node-tls/src/workflow.ts b/recipes/tls-internal-modules-to-node-tls/src/workflow.ts index 8475d1e4..f8a09235 100644 --- a/recipes/tls-internal-modules-to-node-tls/src/workflow.ts +++ b/recipes/tls-internal-modules-to-node-tls/src/workflow.ts @@ -53,7 +53,6 @@ type ImportStatementInfo = { sourceNode: SgNode; rawSource: string; internalMod: string; - isTypeOnly: boolean; supported: SpecifierInfo[]; unsupported: SpecifierInfo[]; }; @@ -65,15 +64,16 @@ export default function transform(root: SgRoot): string | null { const rootNode = root.root(); const edits: Edit[] = []; const linesToRemove: Range[] = []; + const nl = rootNode.text().includes('\r\n') ? '\r\n' : '\n'; // 1. Process ESM import statements using getNodeImportStatements utility - processImportStatements(root, rootNode, edits, linesToRemove); + processImportStatements(root, rootNode, edits, linesToRemove, nl); // 2. Process ESM export statements (re-exports) processExportStatements(root, rootNode, edits); // 3. Process CommonJS require calls using getNodeRequireCalls utility - processRequireCalls(root, rootNode, edits); + processRequireCalls(root, rootNode, edits, nl); // 4. Process dynamic import(...) calls using getNodeImportCalls utility processDynamicImports(root, rootNode, edits); @@ -100,59 +100,22 @@ export default function transform(root: SgRoot): string | null { */ function processImportStatements( root: SgRoot, - rootNode: SgNode, + _rootNode: SgNode, edits: Edit[], linesToRemove: Range[], + nl: string, ): void { - // Find pre-existing node:tls imports using the workspace utility and type import matching - const existingTlsStmts = [ - ...getNodeImportStatements(root, 'tls'), - ...rootNode.findAll({ - rule: { - kind: 'import_statement', - has: { - field: 'source', - kind: 'string', - has: { - kind: 'string_fragment', - regex: '^(node:)?tls$', - }, - }, - pattern: 'import type $$$IMPORTS from $SOURCE', - }, - }), - ]; - - const existingTlsImports: { - statement: SgNode; - isTypeOnly: boolean; - namedImports: SgNode | null; - }[] = existingTlsStmts.map((stmt) => ({ + const existingTlsStmts = getNodeImportStatements(root, 'tls'); + + const existingTlsImports = existingTlsStmts.map((stmt) => ({ statement: stmt, - isTypeOnly: stmt.text().startsWith('import type'), namedImports: stmt.find({ rule: { kind: 'named_imports' } }), })); const internalImports: ImportStatementInfo[] = []; for (const mod of TARGET_MODULES) { - const statements = [ - ...getNodeImportStatements(root, mod), - ...rootNode.findAll({ - rule: { - kind: 'import_statement', - has: { - field: 'source', - kind: 'string', - has: { - kind: 'string_fragment', - regex: `^(node:)?${mod}$`, - }, - }, - pattern: 'import type $$$IMPORTS from $SOURCE', - }, - }), - ]; + const statements = getNodeImportStatements(root, mod); for (const stmt of statements) { const sourceNode = stmt.field('source'); @@ -183,7 +146,6 @@ function processImportStatements( continue; } - const isTypeOnly = stmt.text().startsWith('import type'); const supported: SpecifierInfo[] = []; const unsupported: SpecifierInfo[] = []; @@ -221,7 +183,6 @@ function processImportStatements( sourceNode, rawSource, internalMod, - isTypeOnly, supported, unsupported, }); @@ -231,40 +192,28 @@ function processImportStatements( if (internalImports.length === 0) return; - // Group internal imports by type-only status - const valueInternal = internalImports.filter((i) => !i.isTypeOnly); - const typeInternal = internalImports.filter((i) => i.isTypeOnly); - - consolidateImportsGroup( - valueInternal, - existingTlsImports.find((e) => !e.isTypeOnly), - edits, - linesToRemove, - ); - - consolidateImportsGroup( - typeInternal, - existingTlsImports.find((e) => e.isTypeOnly), + consolidateImports( + internalImports, + existingTlsImports[0], edits, linesToRemove, + nl, ); } -function consolidateImportsGroup( +function consolidateImports( imports: ImportStatementInfo[], existingTls: | { statement: SgNode; - isTypeOnly: boolean; namedImports: SgNode | null; } | undefined, edits: Edit[], linesToRemove: Range[], + nl: string, ): void { - if (imports.length === 0) return; - - // Case 1: Consolidate into pre-existing node:tls import + // Case 1: An existing node:tls import already exists if (existingTls?.namedImports) { const existingNamedText = existingTls.namedImports.text(); const existingSpecs = existingNamedText @@ -354,9 +303,8 @@ function consolidateImportsGroup( } } else { const remaining = first.unsupported.map((u) => u.text).join(', '); - const typePrefix = first.isTypeOnly ? 'type ' : ''; const firstSource = first.sourceNode.text(); - const newStmt = `import ${typePrefix}{ ${remaining} } from ${firstSource};\nimport ${typePrefix}{ ${consolidatedSpecs.join(', ')} } from 'node:tls';`; + const newStmt = `import { ${remaining} } from ${firstSource};${nl}import { ${consolidatedSpecs.join(', ')} } from 'node:tls';`; edits.push(first.statement.replace(newStmt)); } } @@ -385,45 +333,33 @@ function processExportStatements( const specifiers = stmt.findAll({ rule: { kind: 'export_specifier' } }); if (specifiers.length === 0) continue; - const supported: SpecifierInfo[] = []; - const unsupported: SpecifierInfo[] = []; + const supportedNames: string[] = []; + const unsupportedNames: string[] = []; for (const spec of specifiers) { const nameNode = spec.field('name'); - const aliasNode = spec.field('alias'); - const imported = nameNode ? nameNode.text() : spec.text(); - const local = aliasNode ? aliasNode.text() : imported; - - if (MODULE_EXPORTS[internalMod].has(imported)) { - supported.push({ - node: spec, - text: spec.text(), - imported, - local, - }); + const exportedName = nameNode ? nameNode.text() : spec.text(); + + if (MODULE_EXPORTS[internalMod].has(exportedName)) { + supportedNames.push(spec.text()); } else { - unsupported.push({ - node: spec, - text: spec.text(), - imported, - local, - }); + unsupportedNames.push(spec.text()); warn( root, spec, - `Internal-only re-export '${imported}' from '${rawSource}' cannot be migrated to 'node:tls' (DEP0192)`, + `Internal-only export '${exportedName}' from '${rawSource}' cannot be re-exported from 'node:tls' (DEP0192)`, ); } } - if (supported.length > 0 && unsupported.length === 0) { + if (supportedNames.length > 0 && unsupportedNames.length === 0) { edits.push(sourceNode.replace("'node:tls'")); - } else if (supported.length > 0 && unsupported.length > 0) { - const remaining = unsupported.map((u) => u.text).join(', '); - const supText = supported.map((s) => s.text).join(', '); - const sourceText = sourceNode.text(); - const newStmt = `export { ${remaining} } from ${sourceText};\nexport { ${supText} } from 'node:tls';`; - edits.push(stmt.replace(newStmt)); + } else if (supportedNames.length > 0 && unsupportedNames.length > 0) { + warn( + root, + stmt, + `Export statement from '${rawSource}' contains mixed public and internal-only exports; review manually (DEP0192)`, + ); } } } @@ -437,67 +373,47 @@ function processExportStatements( */ function processRequireCalls( root: SgRoot, - rootNode: SgNode, + _rootNode: SgNode, edits: Edit[], + nl: string, ): void { - // Member expressions: const TLSSocket = require('_tls_wrap').TLSSocket; - const memberRequires = rootNode.findAll({ - rule: { - kind: 'member_expression', - all: [ - { - has: { - field: 'object', - kind: 'call_expression', - all: [ - { - has: { - field: 'function', - kind: 'identifier', - regex: '^require$', - }, - }, - ], - }, - }, - ], - }, - }); - - for (const expr of memberRequires) { - const call = expr.field('object'); - const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); - if (!stringArg) continue; - - const rawSource = getUnquotedText(stringArg); - const internalMod = getInternalModuleName(rawSource); - if (!internalMod) continue; - - const prop = expr.field('property'); - if (prop && MODULE_EXPORTS[internalMod].has(prop.text())) { - edits.push(stringArg.replace("'node:tls'")); - } else { - warn( - root, - prop || expr, - `Unknown/internal property '${prop?.text()}' on '${rawSource}' is skipped; review manually (DEP0192)`, - ); - } - } - - // Use getNodeRequireCalls from local workspace utility for variable declarations for (const mod of TARGET_MODULES) { const declarators = getNodeRequireCalls(root, mod); for (const declarator of declarators) { - if (declarator.field('value')?.is('member_expression')) continue; + const value = declarator.field('value'); + if (!value) continue; - const call = declarator.find({ - rule: { - kind: 'call_expression', - has: { field: 'function', regex: '^require$' }, - }, - }); + // Member expressions: const TLSSocket = require('_tls_wrap').TLSSocket; + if (value.is('member_expression')) { + const call = value.find({ rule: { kind: 'call_expression' } }); + const stringArg = call?.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const prop = value.field('property'); + const propName = prop?.text() || ''; + + if (MODULE_EXPORTS[mod].has(propName)) { + edits.push(stringArg.replace("'node:tls'")); + } else { + warn( + root, + prop || value, + `Unknown/internal property '${propName}' on '${getUnquotedText(stringArg)}' is skipped; review manually (DEP0192)`, + ); + } + continue; + } + + // Call expressions with destructuring: const { TLSSocket } = require('_tls_wrap'); + const call = value.is('call_expression') + ? value + : value.find({ + rule: { + kind: 'call_expression', + has: { field: 'function', regex: '^require$' }, + }, + }); const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; @@ -550,8 +466,8 @@ function processRequireCalls( unsupportedNames.length > 0 ) { const declParent = declarator.parent(); - const kind = declParent?.kind() === 'lexical_declaration' ? 'const' : 'var'; - const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});\n${kind} { ${supportedNames.join(', ')} } = require('node:tls');`; + const kind = declParent?.is('lexical_declaration') ? 'const' : 'var'; + const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});${nl}${kind} { ${supportedNames.join(', ')} } = require('node:tls');`; if (declParent) { edits.push(declParent.replace(newDecl)); } @@ -636,7 +552,7 @@ function processDynamicImports( if (!objectCall?.is('call_expression')) continue; const importFn = objectCall.field('function'); - if (importFn?.kind() !== 'import') continue; + if (!importFn?.is('import')) continue; const stringArg = objectCall.field('arguments')?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; diff --git a/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts b/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts index e1c664d9..a796b5f7 100644 --- a/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts +++ b/recipes/tls-internal-modules-to-node-tls/tests/typescript/expected.ts @@ -1,3 +1,3 @@ -import type { SecureContext, TLSSocket } from 'node:tls'; +import { SecureContext, TLSSocket } from 'node:tls'; function check(ctx: SecureContext, socket: TLSSocket): void {} diff --git a/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts b/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts index dcfe927e..3f9e82db 100644 --- a/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts +++ b/recipes/tls-internal-modules-to-node-tls/tests/typescript/input.ts @@ -1,4 +1,4 @@ -import type { SecureContext } from '_tls_common'; -import type { TLSSocket } from 'node:_tls_wrap'; +import { SecureContext } from '_tls_common'; +import { TLSSocket } from 'node:_tls_wrap'; function check(ctx: SecureContext, socket: TLSSocket): void {}