@openrewrite/recipes-nodejs 0.55.0 → 0.56.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/index.js +22 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/migrate/casts.d.ts +4 -0
  5. package/dist/migrate/casts.d.ts.map +1 -0
  6. package/dist/migrate/casts.js +53 -0
  7. package/dist/migrate/casts.js.map +1 -0
  8. package/dist/migrate/child-process-channel.d.ts +9 -0
  9. package/dist/migrate/child-process-channel.d.ts.map +1 -0
  10. package/dist/migrate/child-process-channel.js +65 -0
  11. package/dist/migrate/child-process-channel.js.map +1 -0
  12. package/dist/migrate/exports-folder-mappings.d.ts +9 -0
  13. package/dist/migrate/exports-folder-mappings.d.ts.map +1 -0
  14. package/dist/migrate/exports-folder-mappings.js +118 -0
  15. package/dist/migrate/exports-folder-mappings.js.map +1 -0
  16. package/dist/migrate/find-dns-lookup-options-coercion.d.ts +9 -0
  17. package/dist/migrate/find-dns-lookup-options-coercion.d.ts.map +1 -0
  18. package/dist/migrate/find-dns-lookup-options-coercion.js +270 -0
  19. package/dist/migrate/find-dns-lookup-options-coercion.js.map +1 -0
  20. package/dist/migrate/find-err-invalid-callback.d.ts +9 -0
  21. package/dist/migrate/find-err-invalid-callback.d.ts.map +1 -0
  22. package/dist/migrate/find-err-invalid-callback.js +61 -0
  23. package/dist/migrate/find-err-invalid-callback.js.map +1 -0
  24. package/dist/migrate/find-process-multiple-resolves.d.ts +9 -0
  25. package/dist/migrate/find-process-multiple-resolves.d.ts.map +1 -0
  26. package/dist/migrate/find-process-multiple-resolves.js +58 -0
  27. package/dist/migrate/find-process-multiple-resolves.js.map +1 -0
  28. package/dist/migrate/find-stream-thenable-implementations.d.ts +9 -0
  29. package/dist/migrate/find-stream-thenable-implementations.d.ts.map +1 -0
  30. package/dist/migrate/find-stream-thenable-implementations.js +123 -0
  31. package/dist/migrate/find-stream-thenable-implementations.js.map +1 -0
  32. package/dist/migrate/find-tls-parse-cert-string.d.ts +9 -0
  33. package/dist/migrate/find-tls-parse-cert-string.d.ts.map +1 -0
  34. package/dist/migrate/find-tls-parse-cert-string.js +206 -0
  35. package/dist/migrate/find-tls-parse-cert-string.js.map +1 -0
  36. package/dist/migrate/hpagent/hpagent-support.d.ts.map +1 -1
  37. package/dist/migrate/hpagent/hpagent-support.js +6 -2
  38. package/dist/migrate/hpagent/hpagent-support.js.map +1 -1
  39. package/dist/migrate/module-bindings.d.ts.map +1 -1
  40. package/dist/migrate/module-bindings.js +1 -1
  41. package/dist/migrate/module-bindings.js.map +1 -1
  42. package/dist/migrate/process-exit-code.d.ts.map +1 -1
  43. package/dist/migrate/process-exit-code.js +16 -11
  44. package/dist/migrate/process-exit-code.js.map +1 -1
  45. package/dist/migrate/process-multiple-resolves.d.ts +9 -0
  46. package/dist/migrate/process-multiple-resolves.d.ts.map +1 -0
  47. package/dist/migrate/process-multiple-resolves.js +72 -0
  48. package/dist/migrate/process-multiple-resolves.js.map +1 -0
  49. package/dist/migrate/prop-types/remove-prop-types.d.ts +8 -4
  50. package/dist/migrate/prop-types/remove-prop-types.d.ts.map +1 -1
  51. package/dist/migrate/prop-types/remove-prop-types.js +62 -40
  52. package/dist/migrate/prop-types/remove-prop-types.js.map +1 -1
  53. package/dist/migrate/repl-classes-with-new.d.ts +9 -0
  54. package/dist/migrate/repl-classes-with-new.d.ts.map +1 -0
  55. package/dist/migrate/repl-classes-with-new.js +74 -0
  56. package/dist/migrate/repl-classes-with-new.js.map +1 -0
  57. package/dist/migrate/source-map-support/replace-source-map-support-api.d.ts.map +1 -1
  58. package/dist/migrate/source-map-support/replace-source-map-support-api.js +1 -1
  59. package/dist/migrate/source-map-support/replace-source-map-support-api.js.map +1 -1
  60. package/dist/migrate/upgrade-node-18.d.ts +8 -0
  61. package/dist/migrate/upgrade-node-18.d.ts.map +1 -0
  62. package/dist/migrate/upgrade-node-18.js +58 -0
  63. package/dist/migrate/upgrade-node-18.js.map +1 -0
  64. package/dist/migrate/upgrade-node-20.d.ts +1 -1
  65. package/dist/migrate/upgrade-node-20.d.ts.map +1 -1
  66. package/dist/migrate/upgrade-node-20.js +3 -6
  67. package/dist/migrate/upgrade-node-20.js.map +1 -1
  68. package/dist/migrate/upgrade-node-22.d.ts.map +1 -1
  69. package/dist/migrate/upgrade-node-22.js +2 -0
  70. package/dist/migrate/upgrade-node-22.js.map +1 -1
  71. package/dist/migrate/upgrade-node-24.d.ts.map +1 -1
  72. package/dist/migrate/upgrade-node-24.js +8 -0
  73. package/dist/migrate/upgrade-node-24.js.map +1 -1
  74. package/dist/migrate/upgrade-node-26.d.ts.map +1 -1
  75. package/dist/migrate/upgrade-node-26.js +4 -0
  76. package/dist/migrate/upgrade-node-26.js.map +1 -1
  77. package/dist/migrate/util-type-checking.d.ts.map +1 -1
  78. package/dist/migrate/util-type-checking.js +24 -2
  79. package/dist/migrate/util-type-checking.js.map +1 -1
  80. package/dist/resources/advisories-npm.csv +207 -27
  81. package/package.json +2 -2
  82. package/src/index.ts +22 -0
  83. package/src/migrate/casts.ts +57 -0
  84. package/src/migrate/child-process-channel.ts +61 -0
  85. package/src/migrate/exports-folder-mappings.ts +113 -0
  86. package/src/migrate/find-dns-lookup-options-coercion.ts +292 -0
  87. package/src/migrate/find-err-invalid-callback.ts +43 -0
  88. package/src/migrate/find-process-multiple-resolves.ts +42 -0
  89. package/src/migrate/find-stream-thenable-implementations.ts +116 -0
  90. package/src/migrate/find-tls-parse-cert-string.ts +179 -0
  91. package/src/migrate/hpagent/hpagent-support.ts +8 -4
  92. package/src/migrate/module-bindings.ts +2 -2
  93. package/src/migrate/process-exit-code.ts +19 -14
  94. package/src/migrate/process-multiple-resolves.ts +72 -0
  95. package/src/migrate/prop-types/remove-prop-types.ts +77 -45
  96. package/src/migrate/repl-classes-with-new.ts +66 -0
  97. package/src/migrate/source-map-support/replace-source-map-support-api.ts +2 -1
  98. package/src/migrate/upgrade-node-18.ts +52 -0
  99. package/src/migrate/upgrade-node-20.ts +3 -8
  100. package/src/migrate/upgrade-node-22.ts +2 -0
  101. package/src/migrate/upgrade-node-24.ts +8 -0
  102. package/src/migrate/upgrade-node-26.ts +4 -0
  103. package/src/migrate/util-type-checking.ts +32 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openrewrite/recipes-nodejs",
3
- "version": "0.55.0",
3
+ "version": "0.56.1",
4
4
  "license": "Moderne Proprietary",
5
5
  "description": "OpenRewrite recipes for Node.js library migrations.",
6
6
  "homepage": "https://github.com/moderneinc/rewrite-node",
@@ -25,7 +25,7 @@
25
25
  "ci:test": "jest"
26
26
  },
27
27
  "dependencies": {
28
- "@openrewrite/rewrite": "^8.96.0",
28
+ "@openrewrite/rewrite": "^8.97.1",
29
29
  "mutative": "^1.1.0",
30
30
  "semver": "^7.7.3"
31
31
  },
package/src/index.ts CHANGED
@@ -23,8 +23,10 @@ import {ReplaceZlibBytesRead} from "./migrate/zlib-bytes-read";
23
23
  import {ReplaceFsTruncateWithFd} from "./migrate/fs-truncate";
24
24
  import {ReplaceOutgoingMessageHeaders} from "./migrate/outgoing-message-headers";
25
25
  import {ReplaceTlsInternalModules} from "./migrate/tls-internal-modules";
26
+ import {ReplaceTlsServerSetOptions} from "./migrate/tls-server-set-options";
26
27
  import {ReplaceStreamInternalModules} from "./migrate/stream-internal-modules";
27
28
  import {RemoveNetSetSimultaneousAccepts} from "./migrate/net-set-simultaneous-accepts";
29
+ import {UpgradeNode18} from "./migrate/upgrade-node-18";
28
30
  import {UpgradeNode20} from "./migrate/upgrade-node-20";
29
31
  import {UpgradeNode22} from "./migrate/upgrade-node-22";
30
32
  import {UpgradeNode24} from "./migrate/upgrade-node-24";
@@ -36,6 +38,12 @@ import {FindCryptoDefaultEncoding} from "./migrate/find-crypto-default-encoding"
36
38
  import {FindPunycodeUsage} from "./migrate/find-punycode-usage";
37
39
  import {FindProcessAssert} from "./migrate/find-process-assert";
38
40
  import {FindTlsSecurePair} from "./migrate/find-tls-secure-pair";
41
+ import {FindTlsParseCertString} from "./migrate/find-tls-parse-cert-string";
42
+ import {FindDnsLookupOptionsCoercion} from "./migrate/find-dns-lookup-options-coercion";
43
+ import {FindErrInvalidCallback} from "./migrate/find-err-invalid-callback";
44
+ import {FindStreamThenableImplementations} from "./migrate/find-stream-thenable-implementations";
45
+ import {FindProcessMultipleResolves} from "./migrate/find-process-multiple-resolves";
46
+ import {ReplaceExportsFolderMappings} from "./migrate/exports-folder-mappings";
39
47
  import {FindTimersActive} from "./migrate/find-timers-active";
40
48
  import {ReplaceServerResponseWriteHeader} from "./migrate/server-response-write-header";
41
49
  import {FindAeadDecipherivWithoutAuthTagLength} from "./migrate/find-aead-decipheriv-without-auth-tag-length";
@@ -43,6 +51,9 @@ import {FindDuplexToWebType} from "./migrate/find-duplex-to-web-type";
43
51
  import {FindModuleRegister} from "./migrate/find-module-register";
44
52
  import {FindFsRmdirRecursive} from "./migrate/find-fs-rmdir-recursive";
45
53
  import {ReplaceRsaPssKeyPairOptions} from "./migrate/crypto-rsa-pss-key-pair-options";
54
+ import {AddNewToReplClasses} from "./migrate/repl-classes-with-new";
55
+ import {ReplaceChildProcessChannel} from "./migrate/child-process-channel";
56
+ import {RemoveProcessMultipleResolves} from "./migrate/process-multiple-resolves";
46
57
  import {MigrateFsExtraToNodeFs} from "./migrate/fs-extra/migrate-fs-extra-to-node-fs";
47
58
  import {ReplaceFsExtraRemove} from "./migrate/fs-extra/replace-fs-extra-remove";
48
59
  import {ReplaceFsExtraMkdirs} from "./migrate/fs-extra/replace-fs-extra-mkdirs";
@@ -110,8 +121,10 @@ export async function activate(marketplace: RecipeMarketplace): Promise<void> {
110
121
  await marketplace.install(ReplaceFsTruncateWithFd, Migrate);
111
122
  await marketplace.install(ReplaceOutgoingMessageHeaders, Migrate);
112
123
  await marketplace.install(ReplaceTlsInternalModules, Migrate);
124
+ await marketplace.install(ReplaceTlsServerSetOptions, Migrate);
113
125
  await marketplace.install(ReplaceStreamInternalModules, Migrate);
114
126
  await marketplace.install(RemoveNetSetSimultaneousAccepts, Migrate);
127
+ await marketplace.install(UpgradeNode18, Migrate);
115
128
  await marketplace.install(UpgradeNode20, Migrate);
116
129
  await marketplace.install(UpgradeNode22, Migrate);
117
130
  await marketplace.install(UpgradeNode24, Migrate);
@@ -123,6 +136,12 @@ export async function activate(marketplace: RecipeMarketplace): Promise<void> {
123
136
  await marketplace.install(FindPunycodeUsage, Migrate);
124
137
  await marketplace.install(FindProcessAssert, Migrate);
125
138
  await marketplace.install(FindTlsSecurePair, Migrate);
139
+ await marketplace.install(FindTlsParseCertString, Migrate);
140
+ await marketplace.install(FindDnsLookupOptionsCoercion, Migrate);
141
+ await marketplace.install(FindErrInvalidCallback, Migrate);
142
+ await marketplace.install(FindStreamThenableImplementations, Migrate);
143
+ await marketplace.install(FindProcessMultipleResolves, Migrate);
144
+ await marketplace.install(ReplaceExportsFolderMappings, Migrate);
126
145
  await marketplace.install(FindTimersActive, Migrate);
127
146
  await marketplace.install(ReplaceServerResponseWriteHeader, Migrate);
128
147
  await marketplace.install(FindAeadDecipherivWithoutAuthTagLength, Migrate);
@@ -130,6 +149,9 @@ export async function activate(marketplace: RecipeMarketplace): Promise<void> {
130
149
  await marketplace.install(FindModuleRegister, Migrate);
131
150
  await marketplace.install(FindFsRmdirRecursive, Migrate);
132
151
  await marketplace.install(ReplaceRsaPssKeyPairOptions, Migrate);
152
+ await marketplace.install(AddNewToReplClasses, Migrate);
153
+ await marketplace.install(ReplaceChildProcessChannel, Migrate);
154
+ await marketplace.install(RemoveProcessMultipleResolves, Migrate);
133
155
  await marketplace.install(MigrateFsExtraToNodeFs, FsExtra);
134
156
  await marketplace.install(ReplaceFsExtraRemove, FsExtra);
135
157
  await marketplace.install(ReplaceFsExtraMkdirs, FsExtra);
@@ -0,0 +1,57 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+ import {J} from "@openrewrite/rewrite/java";
7
+ import {JS} from "@openrewrite/rewrite/javascript";
8
+
9
+ /** The expression under any parentheses and TypeScript casts (`as`, `<T>`, `satisfies`). */
10
+ export function unwrapCasts(e: J | undefined): J | undefined {
11
+ for (;;) {
12
+ switch (e?.kind) {
13
+ case JS.Kind.As:
14
+ e = (e as JS.As).left.element;
15
+ break;
16
+ case J.Kind.TypeCast:
17
+ e = (e as J.TypeCast).expression;
18
+ break;
19
+ case JS.Kind.SatisfiesExpression:
20
+ e = (e as JS.SatisfiesExpression).expression;
21
+ break;
22
+ case J.Kind.Parentheses:
23
+ e = (e as J.Parentheses<J>).tree.element;
24
+ break;
25
+ default:
26
+ return e;
27
+ }
28
+ }
29
+ }
30
+
31
+ /** `e` with the expression under its parentheses and casts replaced by `f` of it, keeping them in place. */
32
+ export function mapUnderCasts(e: J, f: (inner: J) => J): J {
33
+ const rebuild = <T extends J>(inner: J, wrap: (mapped: J) => T): J => {
34
+ const mapped = mapUnderCasts(inner, f);
35
+ return mapped === inner ? e : wrap(mapped);
36
+ };
37
+ switch (e.kind) {
38
+ case JS.Kind.As: {
39
+ const as = e as JS.As;
40
+ return rebuild(as.left.element, mapped => ({...as, left: {...as.left, element: mapped}}) as JS.As);
41
+ }
42
+ case J.Kind.TypeCast: {
43
+ const cast = e as J.TypeCast;
44
+ return rebuild(cast.expression, mapped => ({...cast, expression: mapped}) as J.TypeCast);
45
+ }
46
+ case JS.Kind.SatisfiesExpression: {
47
+ const satisfies = e as JS.SatisfiesExpression;
48
+ return rebuild(satisfies.expression, mapped => ({...satisfies, expression: mapped}) as JS.SatisfiesExpression);
49
+ }
50
+ case J.Kind.Parentheses: {
51
+ const parens = e as J.Parentheses<J>;
52
+ return rebuild(parens.tree.element, mapped => ({...parens, tree: {...parens.tree, element: mapped}}) as J.Parentheses<J>);
53
+ }
54
+ default:
55
+ return f(e);
56
+ }
57
+ }
@@ -0,0 +1,61 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+ import {check, ExecutionContext, or, Recipe, TreeVisitor} from "@openrewrite/rewrite";
7
+ import {JavaScriptVisitor, template, usesType} from "@openrewrite/rewrite/javascript";
8
+ import {J, Type} from "@openrewrite/rewrite/java";
9
+
10
+ /**
11
+ * Every `@types/node` type that is a `ChildProcess`. `spawn()` returns
12
+ * `ChildProcessWithoutNullStreams` and `spawn()` with a `stdio` tuple returns
13
+ * `ChildProcessByStdio`, so matching only `ChildProcess` would miss the common cases.
14
+ */
15
+ const CHILD_PROCESS_TYPES = [
16
+ "child_process.ChildProcess",
17
+ "child_process.ChildProcessWithoutNullStreams",
18
+ "child_process.ChildProcessByStdio",
19
+ "node:child_process.ChildProcess",
20
+ "node:child_process.ChildProcessWithoutNullStreams",
21
+ "node:child_process.ChildProcessByStdio",
22
+ ];
23
+
24
+ export class ReplaceChildProcessChannel extends Recipe {
25
+ readonly name = "org.openrewrite.node.migrate.child-process.replace-channel"
26
+ readonly displayName: string = "Replace `ChildProcess._channel` with `ChildProcess.channel`";
27
+ readonly description: string = "The `_channel` property of the child process objects returned by `spawn()` and " +
28
+ "similar functions was never intended for public use and was removed in Node.js 25 (DEP0129). The documented " +
29
+ "`channel` property holds the same IPC channel reference, so the rename is the whole fix.";
30
+ readonly tags: string[] = ["DEP0129"];
31
+
32
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
33
+ return check(or(...CHILD_PROCESS_TYPES.map(type => usesType(type))), new class extends JavaScriptVisitor<ExecutionContext> {
34
+
35
+ private isChildProcessType(type: Type | undefined): boolean {
36
+ if (!type) return false;
37
+
38
+ if (type.kind === Type.Kind.Class) {
39
+ return CHILD_PROCESS_TYPES.includes((type as Type.Class).fullyQualifiedName);
40
+ }
41
+
42
+ // `ChildProcessByStdio<I, O, E>` reaches here as its parameterized form.
43
+ if (type.kind === Type.Kind.Parameterized) {
44
+ return this.isChildProcessType((type as Type.Parameterized).type);
45
+ }
46
+
47
+ return false;
48
+ }
49
+
50
+ protected async visitFieldAccess(fieldAccess: J.FieldAccess, p: ExecutionContext): Promise<J | undefined> {
51
+ const fa = await super.visitFieldAccess(fieldAccess, p) as J.FieldAccess;
52
+
53
+ if (fa.name.element.simpleName === "_channel" && this.isChildProcessType(fa.target.type)) {
54
+ return template`${fa.target}.channel`.apply(fa, this.cursor);
55
+ }
56
+
57
+ return fa;
58
+ }
59
+ });
60
+ }
61
+ }
@@ -0,0 +1,113 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+ import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
7
+ import {getMemberKeyName, isArray, isLiteral, isMember, isObject, Json, JsonVisitor} from "@openrewrite/rewrite/json";
8
+ import {isPackageJson} from "./package-json-support";
9
+ import {removePadded} from "./json-edits";
10
+
11
+ /** Package fields holding subpath mappings, and how their subpath keys start. */
12
+ const FIELDS: Record<string, string> = {exports: ".", imports: "#"};
13
+
14
+ export class ReplaceExportsFolderMappings extends Recipe {
15
+ readonly name = "org.openrewrite.node.migrate.replace-exports-folder-mappings";
16
+ readonly displayName: string = "Replace `exports` folder mappings with subpath patterns";
17
+ readonly description: string = "Node.js 17 removed folder mappings (DEP0148): subpath keys that end in `/` in the " +
18
+ "`exports` and `imports` fields of package.json. Rewrites each one as the equivalent subpath pattern, so " +
19
+ "`\"./features/\": \"./src/features/\"` becomes `\"./features/*\": \"./src/features/*\"`, including targets " +
20
+ "nested under conditions or in fallback arrays. Where the package already declares the pattern next to the " +
21
+ "folder mapping, the folder mapping is removed.";
22
+ readonly tags: string[] = ["DEP0148"];
23
+
24
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
25
+ return new class extends JsonVisitor<ExecutionContext> {
26
+ protected async visitDocument(doc: Json.Document, _ctx: ExecutionContext): Promise<Json | undefined> {
27
+ if (!isPackageJson(doc.sourcePath) || !isObject(doc.value)) {
28
+ return doc;
29
+ }
30
+ const members = doc.value.members.map(rp => {
31
+ const m = rp.element;
32
+ const prefix = isMember(m) ? FIELDS[getMemberKeyName(m) ?? ""] : undefined;
33
+ if (!prefix || !isMember(m) || !isObject(m.value)) {
34
+ return rp;
35
+ }
36
+ const mappings = replaceFolderMappings(m.value, prefix);
37
+ return mappings === m.value ? rp : {...rp, element: {...m, value: mappings}};
38
+ });
39
+ return members.every((rp, i) => rp === (doc.value as Json.Object).members[i])
40
+ ? doc
41
+ : {...doc, value: {...doc.value, members}} as Json.Document;
42
+ }
43
+ };
44
+ }
45
+ }
46
+
47
+ /** `mappings` with each folder mapping replaced by a pattern, or removed where the pattern is already declared. */
48
+ function replaceFolderMappings(mappings: Json.Object, subpathPrefix: string): Json.Object {
49
+ const declared = new Set(mappings.members.filter(rp => isMember(rp.element))
50
+ .map(rp => getMemberKeyName(rp.element as Json.Member)));
51
+ const redundant = new Set<Json>();
52
+ let changed = false;
53
+ const members = mappings.members.map(rp => {
54
+ const m = rp.element;
55
+ const key = isMember(m) ? getMemberKeyName(m) : undefined;
56
+ if (!isMember(m) || !key?.startsWith(subpathPrefix) || !key.endsWith("/") || !isLiteral(m.key.element)) {
57
+ return rp;
58
+ }
59
+ if (declared.has(key + "*")) {
60
+ redundant.add(m);
61
+ return rp;
62
+ }
63
+ const targets = patternTargets(m.value);
64
+ if (!targets) {
65
+ return rp;
66
+ }
67
+ changed = true;
68
+ return {...rp, element: {...m, key: {...m.key, element: withString(m.key.element, key + "*")}, value: targets}};
69
+ });
70
+ if (!changed && redundant.size === 0) {
71
+ return mappings;
72
+ }
73
+ return {...mappings, members: removePadded(members, e => !redundant.has(e))};
74
+ }
75
+
76
+ /**
77
+ * The targets of a folder mapping with `*` appended to each, or undefined when one is not a folder,
78
+ * since such a mapping never resolved and the intended pattern is unclear.
79
+ */
80
+ function patternTargets(value: Json.Value): Json.Value | undefined {
81
+ if (isLiteral(value)) {
82
+ if (value.value === null) {
83
+ return value;
84
+ }
85
+ return typeof value.value === "string" && value.value.endsWith("/")
86
+ ? withString(value, value.value + "*")
87
+ : undefined;
88
+ }
89
+ if (isArray(value)) {
90
+ const values = value.values.map(rp => ({rp, target: patternTargets(rp.element)}));
91
+ return values.some(v => !v.target)
92
+ ? undefined
93
+ : {...value, values: values.map(({rp, target}) => ({...rp, element: target!}))};
94
+ }
95
+ if (isObject(value)) {
96
+ const members = value.members.map(rp => {
97
+ const m = rp.element;
98
+ if (!isMember(m)) {
99
+ return {rp, target: m};
100
+ }
101
+ const target = patternTargets(m.value);
102
+ return {rp, target: target && {...m, value: target}};
103
+ });
104
+ return members.some(v => !v.target)
105
+ ? undefined
106
+ : {...value, members: members.map(({rp, target}) => ({...rp, element: target!}))};
107
+ }
108
+ return value;
109
+ }
110
+
111
+ function withString(literal: Json.Literal, value: string): Json.Literal {
112
+ return {...literal, value, source: JSON.stringify(value)};
113
+ }
@@ -0,0 +1,292 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+ import {check, ExecutionContext, foundSearchResult, or, Recipe, TreeVisitor} from "@openrewrite/rewrite";
7
+ import {JavaScriptVisitor, JS, MethodMatcher, usesMethod, usesType} from "@openrewrite/rewrite/javascript";
8
+ import {isIdentifier, J, Type} from "@openrewrite/rewrite/java";
9
+ import {isObjectLiteral, propertyNameOf} from "./fs-extra/fs-extra-support";
10
+ import {mapUnderCasts, unwrapCasts} from "./casts";
11
+
12
+ const CALLBACK_PATTERNS = ["dns lookup(..)", "node:dns lookup(..)"];
13
+ const PROMISE_PATTERNS = ["dns/promises lookup(..)", "node:dns/promises lookup(..)"];
14
+
15
+ // Calls that resolve the host with dns.lookup(), passing it their family and hints options, unless given a `lookup`.
16
+ const CONNECTING_CALLS: [string, string, string][] = [
17
+ ...["net", "node:net"].flatMap(m => ["connect", "createConnection"].map(f => [`${m} ${f}(..)`, `net.${f}()`, m] as [string, string, string])),
18
+ ["net.Socket connect(..)", "socket.connect()", "net"],
19
+ ...["tls", "node:tls"].map(m => [`${m} connect(..)`, "tls.connect()", m] as [string, string, string]),
20
+ ...["http", "node:http", "https", "node:https"].flatMap(m => ["request", "get"].map(f =>
21
+ [`${m} ${f}(..)`, `${m.replace("node:", "")}.${f}()`, m] as [string, string, string])),
22
+ ];
23
+ const AGENTS = new Set(["http.Agent", "https.Agent"]);
24
+ const PASSED_TO_LOOKUP = new Set(["family", "hints"]);
25
+
26
+ // Literal values each option throws for since Node.js 18 but older versions accepted.
27
+ const NUMBER_LIKE = (value: unknown) => typeof value === "string" || value === false;
28
+ const BOOLEAN_LIKE = (value: unknown) => typeof value === "string" || typeof value === "number";
29
+ const REJECTED: Record<string, (value: unknown) => boolean> = {
30
+ family: NUMBER_LIKE,
31
+ hints: NUMBER_LIKE,
32
+ all: BOOLEAN_LIKE,
33
+ verbatim: BOOLEAN_LIKE,
34
+ };
35
+ // net only passes `hints || 0` on, so an empty string or false never reached dns.lookup().
36
+ const REJECTED_WHEN_PASSED: Record<string, (value: unknown) => boolean> = {
37
+ family: NUMBER_LIKE,
38
+ hints: value => typeof value === "string" && value !== "",
39
+ };
40
+
41
+ const FIXES: Record<string, string> = {
42
+ family: "Pass 0, 4 or 6 for family.",
43
+ hints: "Pass a number for hints.",
44
+ all: "Older Node.js versions read any all but true as false, so pass false to keep that behavior.",
45
+ verbatim: "Older Node.js versions ignored a verbatim that is not a boolean and used the default, so remove it to keep that behavior.",
46
+ };
47
+ const EXPECTED: Record<string, string> = {family: "number", hints: "number", all: "boolean", verbatim: "boolean"};
48
+
49
+ /** One option as passed: a literal value, or else the type of the expression. */
50
+ interface Option {
51
+ expression?: J;
52
+ type?: Type;
53
+ }
54
+
55
+ export class FindDnsLookupOptionsCoercion extends Recipe {
56
+ readonly name = "org.openrewrite.node.migrate.dns.find-lookup-options-coercion"
57
+ readonly displayName: string = "Find `dns.lookup()` options of the wrong type, and fix numeric strings";
58
+ readonly description: string = "Since Node.js 18 (DEP0153), `dns.lookup()` throws for option values that older versions " +
59
+ "silently converted, such as a string `family` or a non-boolean `all`. Finds literal values of the wrong type, " +
60
+ "and values typed as the wrong type, such as a `process.env` variable or an options object declared elsewhere, " +
61
+ "so they can be fixed by hand. A `family` or `hints` given as a string of digits, such as `'4'`, is " +
62
+ "replaced with the number, which older versions converted it to. Also checks the `family` and `hints` options of `net.connect()`, `tls.connect()`, " +
63
+ "`http.request()`, `https.request()` and `new http.Agent()`, which pass them on to `dns.lookup()`.";
64
+ readonly tags: string[] = ["DEP0153"];
65
+
66
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
67
+ const patterns = [...CALLBACK_PATTERNS, ...PROMISE_PATTERNS, ...CONNECTING_CALLS.map(([pattern]) => pattern)];
68
+ const preconditions = [...patterns.map(pattern => usesMethod(pattern)), ...[...AGENTS].map(agent => usesType(agent))];
69
+ return check(or(...preconditions), new class extends JavaScriptVisitor<ExecutionContext> {
70
+ callbackMatchers = CALLBACK_PATTERNS.map(pattern => new MethodMatcher(pattern));
71
+ promiseMatchers = PROMISE_PATTERNS.map(pattern => new MethodMatcher(pattern));
72
+ connectingMatchers = CONNECTING_CALLS.map(([pattern, label]) => ({matcher: new MethodMatcher(pattern), label}));
73
+
74
+ protected async visitMethodInvocation(m: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
75
+ let method = await super.visitMethodInvocation(m, p) as J.MethodInvocation;
76
+ const connecting = this.connectingMatchers.find(({matcher}) => matcher.matches(method.methodType));
77
+ if (connecting) {
78
+ return markPassedOptions(method, connecting.label, method.arguments.elements.map(rp => rp.element));
79
+ }
80
+ const callback = this.callbackMatchers.some(matcher => matcher.matches(method.methodType));
81
+ if (!callback && !this.promiseMatchers.some(matcher => matcher.matches(method.methodType))) {
82
+ return method;
83
+ }
84
+ const api = callback ? "dns.lookup()" : "dnsPromises.lookup()";
85
+ method = withNumericOptions(method);
86
+ const options = unwrapCasts(method.arguments.elements[1]?.element);
87
+ if (options?.kind === J.Kind.Literal && NUMBER_LIKE((options as J.Literal).value)) {
88
+ return foundSearchResult(method, `${api} throws for a string or boolean options argument ` +
89
+ `since Node.js 18. Pass 0, 4 or 6, or an options object (DEP0153).`);
90
+ }
91
+ const effective = optionsOf(options);
92
+ if (!effective) {
93
+ return method;
94
+ }
95
+ const sentences = describe(api, effective, REJECTED, callback);
96
+ return sentences.length === 0 ? method : foundSearchResult(method, `${sentences.join(" ")} (DEP0153)`);
97
+ }
98
+
99
+ protected async visitNewClass(newClass: J.NewClass, p: ExecutionContext): Promise<J | undefined> {
100
+ const n = await super.visitNewClass(newClass, p) as J.NewClass;
101
+ const type = (n.class as J.Identifier | J.FieldAccess | undefined)?.type;
102
+ if (type?.kind !== Type.Kind.Class || !AGENTS.has((type as Type.Class).fullyQualifiedName)) {
103
+ return n;
104
+ }
105
+ return markPassedOptions(n, `Requests through this ${(type as Type.Class).fullyQualifiedName}`, n.arguments.elements.map(rp => rp.element), "fail");
106
+ }
107
+ });
108
+ }
109
+ }
110
+
111
+ /** Marks a call that passes the family and hints options in `args` on to dns.lookup(). */
112
+ function markPassedOptions<T extends J>(call: T, api: string, args: J[], verb = "fails"): T {
113
+ for (const arg of args) {
114
+ const effective = optionsOf(unwrapCasts(arg));
115
+ if (!effective || effective.has("lookup")) {
116
+ continue;
117
+ }
118
+ const passed = new Map([...effective].filter(([name]) => PASSED_TO_LOOKUP.has(name)));
119
+ const sentences = describe(api, passed, REJECTED_WHEN_PASSED, true, verb);
120
+ if (sentences.length > 0) {
121
+ return foundSearchResult(call, `${sentences.join(" ")} (DEP0153)`);
122
+ }
123
+ }
124
+ return call;
125
+ }
126
+
127
+ /**
128
+ * The sentences describing the options in `effective` that Node.js 18 rejects. A `verb` other than "throws"
129
+ * says `api` passes the options on to dns.lookup().
130
+ */
131
+ function describe(api: string, effective: Map<string, Option>, rejected: Record<string, (value: unknown) => boolean>,
132
+ callback: boolean, verb = "throws"): string[] {
133
+ const passed = verb !== "throws";
134
+ const familyName = callback && ["IPv4", "IPv6"].includes(literalValue(effective.get("family")?.expression) as string);
135
+ const wrong: string[] = [];
136
+ const typed: [string, string][] = [];
137
+ for (const [name, option] of effective) {
138
+ if (!rejected[name] || (familyName && name === "family")) {
139
+ continue;
140
+ }
141
+ const value = unwrapCasts(option.expression);
142
+ if (value?.kind === J.Kind.Literal) {
143
+ if (rejected[name]((value as J.Literal).value)) {
144
+ wrong.push(name);
145
+ }
146
+ continue;
147
+ }
148
+ const actual = wrongType(option.type, EXPECTED[name]);
149
+ if (actual) {
150
+ typed.push([name, actual]);
151
+ }
152
+ }
153
+ const via = (count: number) => passed ? `, as it passes ${count > 1 ? "them" : "it"} to dns.lookup()` : "";
154
+ const sentences: string[] = [];
155
+ if (wrong.length > 0) {
156
+ sentences.push(
157
+ `${api} ${verb} for the ${wrong.join(" and ")} option${wrong.length > 1 ? "s" : ""} since Node.js 18${via(wrong.length)}.`,
158
+ ...wrong.map(name => FIXES[name]));
159
+ }
160
+ for (const [name, actual] of typed) {
161
+ sentences.push(`${api} ${verb} since Node.js 18 when the ${name} option is not a ${EXPECTED[name]}${via(1)}. ` +
162
+ `Here it is ${actual}.`, FIXES[name]);
163
+ }
164
+ if (familyName) {
165
+ sentences.push("Before Node.js 18, a family of 'IPv4' or 'IPv6' was read as 0 (any family); 18.0 to 18.3 " +
166
+ "throw for it, and 18.4 and later read it as 4 or 6, so check that the narrower lookup is intended.");
167
+ }
168
+ return sentences;
169
+ }
170
+
171
+ // A string older versions read as the same number, as `value >>> 0` does for a decimal string.
172
+ const DIGITS = /^\d{1,9}$/;
173
+
174
+ /**
175
+ * `call` with a family or hints given as a string of digits, which dns.lookup() read as that number before
176
+ * Node.js 18, replaced with the number. So is an options argument that is such a string, which was the family.
177
+ * Callers like net.connect() are left alone, as they checked the family before converting it.
178
+ */
179
+ function withNumericOptions(call: J.MethodInvocation): J.MethodInvocation {
180
+ const arg = call.arguments.elements[1]?.element;
181
+ if (!arg) {
182
+ return call;
183
+ }
184
+ const options = mapUnderCasts(arg, inner => isDigitString(inner)
185
+ ? toNumber(inner as J.Literal)
186
+ : isObjectLiteral(inner) ? withNumericMembers(inner) : inner);
187
+ if (options === arg) {
188
+ return call;
189
+ }
190
+ const elements = call.arguments.elements.map((rp, i) => i === 1 ? {...rp, element: options} : rp);
191
+ return {...call, arguments: {...call.arguments, elements}} as J.MethodInvocation;
192
+ }
193
+
194
+ /** An options object with the family and hints it ends up with replaced with numbers, where they are digit strings. */
195
+ function withNumericMembers(options: J.NewClass): J.NewClass {
196
+ const effective = effectiveOptions(options);
197
+ let changed = false;
198
+ const statements = options.body!.statements.map(rp => {
199
+ const member = rp.element;
200
+ if (member.kind !== JS.Kind.PropertyAssignment) {
201
+ return rp;
202
+ }
203
+ const assignment = member as JS.PropertyAssignment;
204
+ const name = propertyNameOf(assignment);
205
+ const value = assignment.initializer;
206
+ // Only the value the option ends up with; one a later key or spread overrides was never read.
207
+ if ((name !== "family" && name !== "hints") || !value || effective.get(name) !== value) {
208
+ return rp;
209
+ }
210
+ const numeric = mapUnderCasts(value, inner => isDigitString(inner) ? toNumber(inner as J.Literal) : inner);
211
+ if (numeric === value) {
212
+ return rp;
213
+ }
214
+ changed = true;
215
+ return {...rp, element: {...assignment, initializer: numeric}};
216
+ });
217
+ return changed ? {...options, body: {...options.body!, statements}} as J.NewClass : options;
218
+ }
219
+
220
+ function isDigitString(e: J | undefined): boolean {
221
+ return e?.kind === J.Kind.Literal && typeof (e as J.Literal).value === "string" && DIGITS.test((e as J.Literal).value as string);
222
+ }
223
+
224
+ function toNumber(literal: J.Literal): J.Literal {
225
+ const value = Number(literal.value);
226
+ return {...literal, value, valueSource: String(value), unicodeEscapes: undefined, type: Type.Primitive.Double};
227
+ }
228
+
229
+ /** The value of a literal under any casts, or undefined when `e` is not one. */
230
+ function literalValue(e: J | undefined): unknown {
231
+ const value = unwrapCasts(e);
232
+ return value?.kind === J.Kind.Literal ? (value as J.Literal).value : undefined;
233
+ }
234
+
235
+ /**
236
+ * The options an argument passes: the members of an object literal, or of the type of any other expression,
237
+ * such as a variable holding an options object. Undefined when neither is known.
238
+ */
239
+ function optionsOf(e: J | undefined): Map<string, Option> | undefined {
240
+ if (isObjectLiteral(e)) {
241
+ return new Map([...effectiveOptions(e)].map(([name, value]) => [name, {expression: value, type: typeOf(value)}]));
242
+ }
243
+ const type = typeOf(e);
244
+ if (type?.kind !== Type.Kind.Class || !(type as Type.Class).members?.length) {
245
+ return undefined;
246
+ }
247
+ return new Map((type as Type.Class).members.map(member => [member.name, {type: member.type}]));
248
+ }
249
+
250
+ function typeOf(e: J | undefined): Type | undefined {
251
+ return (unwrapCasts(e) as J & { type?: Type } | undefined)?.type;
252
+ }
253
+
254
+ /**
255
+ * How a value of `type` breaks an option expecting `expected`: "a string" when it is one, and "possibly a string"
256
+ * when it may be one. Only strings, and numbers where a boolean is expected, are reported, as older versions
257
+ * converted them; other types failed before too, or are not known.
258
+ */
259
+ function wrongType(type: Type | undefined, expected: string): string | undefined {
260
+ const kinds = (type as Type.Union | undefined)?.bounds ? (type as Type.Union).bounds : type ? [type] : [];
261
+ const rejected = (t: Type) => isPrimitive(t, "String") ||
262
+ (expected === "boolean" && ["double", "int", "long", "float", "short", "byte"].some(k => isPrimitive(t, k)));
263
+ const wrong = kinds.filter(rejected);
264
+ if (wrong.length === 0) {
265
+ return undefined;
266
+ }
267
+ const name = isPrimitive(wrong[0], "String") ? "a string" : "a number";
268
+ return wrong.length === kinds.length ? name : `possibly ${name}`;
269
+ }
270
+
271
+ function isPrimitive(type: Type, keyword: string): boolean {
272
+ return type.kind === Type.Kind.Primitive && (type as Type.Primitive).keyword === keyword;
273
+ }
274
+
275
+ /** The value each option ends up with, where a later key or a spread overrides an earlier one. */
276
+ function effectiveOptions(options: J.NewClass): Map<string, J | undefined> {
277
+ const effective = new Map<string, J | undefined>();
278
+ for (const statement of options.body?.statements ?? []) {
279
+ const member = statement.element;
280
+ const name = member.kind === JS.Kind.PropertyAssignment ? propertyNameOf(member as JS.PropertyAssignment) : undefined;
281
+ if (name) {
282
+ effective.delete(name);
283
+ effective.set(name, (member as JS.PropertyAssignment).initializer);
284
+ } else if (isIdentifier(member)) {
285
+ effective.delete(member.simpleName);
286
+ effective.set(member.simpleName, member);
287
+ } else {
288
+ effective.clear();
289
+ }
290
+ }
291
+ return effective;
292
+ }
@@ -0,0 +1,43 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+ import {ExecutionContext, foundSearchResult, Recipe, TreeVisitor} from "@openrewrite/rewrite";
7
+ import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
8
+ import {J} from "@openrewrite/rewrite/java";
9
+
10
+ const OLD_CODE = /\bERR_INVALID_CALLBACK\b/;
11
+ const MESSAGE = "ERR_INVALID_CALLBACK was removed in Node.js 18 (DEP0159). Invalid callbacks throw ERR_INVALID_ARG_TYPE instead.";
12
+ const TEMPLATE_PARTS = new Set<string>([JS.Kind.TemplateExpression, JS.Kind.TemplateExpressionSpan]);
13
+
14
+ const namesOldCode = (lit: J.Literal) => !!lit.valueSource && OLD_CODE.test(lit.valueSource);
15
+
16
+ export class FindErrInvalidCallback extends Recipe {
17
+ readonly name = "org.openrewrite.node.migrate.find-err-invalid-callback"
18
+ readonly displayName: string = "Find removed `ERR_INVALID_CALLBACK` error code usage";
19
+ readonly description: string = "The `ERR_INVALID_CALLBACK` error code was removed in Node.js 18 (DEP0159). Invalid " +
20
+ "callbacks now throw `ERR_INVALID_ARG_TYPE`, which Node.js also throws for every other argument of the wrong " +
21
+ "type. Finds strings and regular expressions that name the old code, so checks against it can be updated by " +
22
+ "hand. Code that creates the error itself, such as a polyfill, may need to keep it.";
23
+ readonly tags: string[] = ["DEP0159"];
24
+
25
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
26
+ return new class extends JavaScriptVisitor<ExecutionContext> {
27
+ protected async visitTemplateExpression(template: JS.TemplateExpression, p: ExecutionContext): Promise<J | undefined> {
28
+ const t = await super.visitTemplateExpression(template, p) as JS.TemplateExpression;
29
+ return namesOldCode(t.head) || t.spans.some(span => namesOldCode(span.element.tail))
30
+ ? foundSearchResult(t, MESSAGE)
31
+ : t;
32
+ }
33
+
34
+ protected async visitLiteral(literal: J.Literal, p: ExecutionContext): Promise<J | undefined> {
35
+ const lit = await super.visitLiteral(literal, p) as J.Literal;
36
+ // Template text is marked on the whole template, since a marker on a span's text prints inside `${}`.
37
+ return namesOldCode(lit) && !TEMPLATE_PARTS.has(this.cursor.parentTree()?.value.kind)
38
+ ? foundSearchResult(lit, MESSAGE)
39
+ : lit;
40
+ }
41
+ };
42
+ }
43
+ }