@openrewrite/recipes-nodejs 0.58.0 → 0.60.0

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 (132) hide show
  1. package/dist/migrate/angular-animations/remove-angular-animations-providers.d.ts.map +1 -1
  2. package/dist/migrate/angular-animations/remove-angular-animations-providers.js +6 -26
  3. package/dist/migrate/angular-animations/remove-angular-animations-providers.js.map +1 -1
  4. package/dist/migrate/builtin-binding-visitor.d.ts.map +1 -1
  5. package/dist/migrate/builtin-binding-visitor.js +6 -22
  6. package/dist/migrate/builtin-binding-visitor.js.map +1 -1
  7. package/dist/migrate/crypto-rsa-pss-key-pair-options.js +1 -4
  8. package/dist/migrate/crypto-rsa-pss-key-pair-options.js.map +1 -1
  9. package/dist/migrate/exports-folder-mappings.d.ts.map +1 -1
  10. package/dist/migrate/exports-folder-mappings.js +6 -19
  11. package/dist/migrate/exports-folder-mappings.js.map +1 -1
  12. package/dist/migrate/express-request-id/replace-express-request-id.d.ts.map +1 -1
  13. package/dist/migrate/express-request-id/replace-express-request-id.js +2 -5
  14. package/dist/migrate/express-request-id/replace-express-request-id.js.map +1 -1
  15. package/dist/migrate/find-aead-decipheriv-without-auth-tag-length.d.ts.map +1 -1
  16. package/dist/migrate/find-aead-decipheriv-without-auth-tag-length.js +2 -3
  17. package/dist/migrate/find-aead-decipheriv-without-auth-tag-length.js.map +1 -1
  18. package/dist/migrate/find-dns-lookup-options-coercion.js +2 -2
  19. package/dist/migrate/find-dns-lookup-options-coercion.js.map +1 -1
  20. package/dist/migrate/find-duplex-to-web-type.d.ts.map +1 -1
  21. package/dist/migrate/find-duplex-to-web-type.js +2 -3
  22. package/dist/migrate/find-duplex-to-web-type.js.map +1 -1
  23. package/dist/migrate/find-stream-thenable-implementations.js +4 -5
  24. package/dist/migrate/find-stream-thenable-implementations.js.map +1 -1
  25. package/dist/migrate/fs-extra/find-fs-extra-manual-migrations.d.ts +1 -0
  26. package/dist/migrate/fs-extra/find-fs-extra-manual-migrations.d.ts.map +1 -1
  27. package/dist/migrate/fs-extra/find-fs-extra-manual-migrations.js +10 -2
  28. package/dist/migrate/fs-extra/find-fs-extra-manual-migrations.js.map +1 -1
  29. package/dist/migrate/fs-extra/fs-extra-support.d.ts +0 -1
  30. package/dist/migrate/fs-extra/fs-extra-support.d.ts.map +1 -1
  31. package/dist/migrate/fs-extra/fs-extra-support.js +0 -4
  32. package/dist/migrate/fs-extra/fs-extra-support.js.map +1 -1
  33. package/dist/migrate/fs-extra/migrate-fs-extra-to-node-fs.d.ts.map +1 -1
  34. package/dist/migrate/fs-extra/migrate-fs-extra-to-node-fs.js +3 -2
  35. package/dist/migrate/fs-extra/migrate-fs-extra-to-node-fs.js.map +1 -1
  36. package/dist/migrate/fs-extra/replace-fs-extra-move.js +2 -2
  37. package/dist/migrate/fs-extra/replace-fs-extra-move.js.map +1 -1
  38. package/dist/migrate/fs-extra/replace-fs-extra-native-methods.d.ts +2 -0
  39. package/dist/migrate/fs-extra/replace-fs-extra-native-methods.d.ts.map +1 -1
  40. package/dist/migrate/fs-extra/replace-fs-extra-native-methods.js +58 -6
  41. package/dist/migrate/fs-extra/replace-fs-extra-native-methods.js.map +1 -1
  42. package/dist/migrate/fs-extra/replace-fs-extra-read-json.js +1 -1
  43. package/dist/migrate/fs-extra/replace-fs-extra-read-json.js.map +1 -1
  44. package/dist/migrate/fs-stats-constructor.d.ts.map +1 -1
  45. package/dist/migrate/fs-stats-constructor.js +1 -12
  46. package/dist/migrate/fs-stats-constructor.js.map +1 -1
  47. package/dist/migrate/hpagent/hpagent-support.d.ts +0 -1
  48. package/dist/migrate/hpagent/hpagent-support.d.ts.map +1 -1
  49. package/dist/migrate/hpagent/hpagent-support.js +3 -7
  50. package/dist/migrate/hpagent/hpagent-support.js.map +1 -1
  51. package/dist/migrate/hpagent/replace-hpagent.d.ts.map +1 -1
  52. package/dist/migrate/hpagent/replace-hpagent.js +8 -12
  53. package/dist/migrate/hpagent/replace-hpagent.js.map +1 -1
  54. package/dist/migrate/increase-node-engine-version.d.ts.map +1 -1
  55. package/dist/migrate/increase-node-engine-version.js +7 -26
  56. package/dist/migrate/increase-node-engine-version.js.map +1 -1
  57. package/dist/migrate/json-edits.d.ts +4 -9
  58. package/dist/migrate/json-edits.d.ts.map +1 -1
  59. package/dist/migrate/json-edits.js +46 -60
  60. package/dist/migrate/json-edits.js.map +1 -1
  61. package/dist/migrate/options-literal.d.ts.map +1 -1
  62. package/dist/migrate/options-literal.js +1 -2
  63. package/dist/migrate/options-literal.js.map +1 -1
  64. package/dist/migrate/package-json-support.d.ts +2 -1
  65. package/dist/migrate/package-json-support.d.ts.map +1 -1
  66. package/dist/migrate/package-json-support.js +14 -12
  67. package/dist/migrate/package-json-support.js.map +1 -1
  68. package/dist/migrate/path/remove-path-dependency.d.ts.map +1 -1
  69. package/dist/migrate/path/remove-path-dependency.js +4 -25
  70. package/dist/migrate/path/remove-path-dependency.js.map +1 -1
  71. package/dist/migrate/promisify-on-promise.js +3 -3
  72. package/dist/migrate/promisify-on-promise.js.map +1 -1
  73. package/dist/migrate/prop-types/remove-prop-types.d.ts.map +1 -1
  74. package/dist/migrate/prop-types/remove-prop-types.js +7 -25
  75. package/dist/migrate/prop-types/remove-prop-types.js.map +1 -1
  76. package/dist/migrate/source-map-support/enable-source-maps-at-launch.d.ts.map +1 -1
  77. package/dist/migrate/source-map-support/enable-source-maps-at-launch.js +14 -64
  78. package/dist/migrate/source-map-support/enable-source-maps-at-launch.js.map +1 -1
  79. package/dist/migrate/source-map-support/find-source-map-support-manual-migrations.d.ts.map +1 -1
  80. package/dist/migrate/source-map-support/find-source-map-support-manual-migrations.js +9 -38
  81. package/dist/migrate/source-map-support/find-source-map-support-manual-migrations.js.map +1 -1
  82. package/dist/migrate/source-map-support/replace-source-map-support-api.d.ts.map +1 -1
  83. package/dist/migrate/source-map-support/replace-source-map-support-api.js +1 -1
  84. package/dist/migrate/source-map-support/replace-source-map-support-api.js.map +1 -1
  85. package/dist/migrate/source-map-support/replace-source-map-support-register-in-mocha-config.js +1 -1
  86. package/dist/migrate/source-map-support/replace-source-map-support-register-in-mocha-config.js.map +1 -1
  87. package/dist/migrate/source-map-support/replace-source-map-support-register-in-package-json.d.ts.map +1 -1
  88. package/dist/migrate/source-map-support/replace-source-map-support-register-in-package-json.js +37 -88
  89. package/dist/migrate/source-map-support/replace-source-map-support-register-in-package-json.js.map +1 -1
  90. package/dist/migrate/source-map-support/source-map-support-support.d.ts.map +1 -1
  91. package/dist/migrate/source-map-support/source-map-support-support.js +3 -16
  92. package/dist/migrate/source-map-support/source-map-support-support.js.map +1 -1
  93. package/dist/migrate/stream-internal-modules.d.ts.map +1 -1
  94. package/dist/migrate/stream-internal-modules.js +2 -10
  95. package/dist/migrate/stream-internal-modules.js.map +1 -1
  96. package/dist/migrate/tls-internal-modules.d.ts.map +1 -1
  97. package/dist/migrate/tls-internal-modules.js +2 -10
  98. package/dist/migrate/tls-internal-modules.js.map +1 -1
  99. package/package.json +2 -2
  100. package/src/migrate/angular-animations/remove-angular-animations-providers.ts +7 -23
  101. package/src/migrate/builtin-binding-visitor.ts +10 -28
  102. package/src/migrate/crypto-rsa-pss-key-pair-options.ts +2 -11
  103. package/src/migrate/exports-folder-mappings.ts +18 -19
  104. package/src/migrate/express-request-id/replace-express-request-id.ts +3 -7
  105. package/src/migrate/find-aead-decipheriv-without-auth-tag-length.ts +3 -4
  106. package/src/migrate/find-dns-lookup-options-coercion.ts +3 -3
  107. package/src/migrate/find-duplex-to-web-type.ts +3 -4
  108. package/src/migrate/find-stream-thenable-implementations.ts +5 -7
  109. package/src/migrate/fs-extra/find-fs-extra-manual-migrations.ts +12 -4
  110. package/src/migrate/fs-extra/fs-extra-support.ts +0 -5
  111. package/src/migrate/fs-extra/migrate-fs-extra-to-node-fs.ts +3 -2
  112. package/src/migrate/fs-extra/replace-fs-extra-move.ts +3 -3
  113. package/src/migrate/fs-extra/replace-fs-extra-native-methods.ts +75 -8
  114. package/src/migrate/fs-extra/replace-fs-extra-read-json.ts +3 -3
  115. package/src/migrate/fs-stats-constructor.ts +2 -13
  116. package/src/migrate/hpagent/hpagent-support.ts +2 -7
  117. package/src/migrate/hpagent/replace-hpagent.ts +7 -8
  118. package/src/migrate/increase-node-engine-version.ts +10 -36
  119. package/src/migrate/json-edits.ts +48 -64
  120. package/src/migrate/options-literal.ts +2 -3
  121. package/src/migrate/package-json-support.ts +15 -12
  122. package/src/migrate/path/remove-path-dependency.ts +6 -23
  123. package/src/migrate/promisify-on-promise.ts +4 -4
  124. package/src/migrate/prop-types/remove-prop-types.ts +9 -25
  125. package/src/migrate/source-map-support/enable-source-maps-at-launch.ts +14 -52
  126. package/src/migrate/source-map-support/find-source-map-support-manual-migrations.ts +11 -34
  127. package/src/migrate/source-map-support/replace-source-map-support-api.ts +2 -1
  128. package/src/migrate/source-map-support/replace-source-map-support-register-in-mocha-config.ts +2 -2
  129. package/src/migrate/source-map-support/replace-source-map-support-register-in-package-json.ts +53 -98
  130. package/src/migrate/source-map-support/source-map-support-support.ts +6 -19
  131. package/src/migrate/stream-internal-modules.ts +4 -13
  132. package/src/migrate/tls-internal-modules.ts +4 -13
@@ -4,9 +4,9 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
  import {ExecutionContext, foundSearchResult, Recipe, TreeVisitor} from "@openrewrite/rewrite";
7
- import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
7
+ import {functionExpressionOf, isObjectLiteral, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
8
8
  import {J, Type} from "@openrewrite/rewrite/java";
9
- import {isObjectLiteral, propertyNameOf} from "./fs-extra/fs-extra-support";
9
+ import {propertyNameOf} from "./fs-extra/fs-extra-support";
10
10
 
11
11
  // The implementation methods whose returned promise Node.js 16 and 17 waited on, and Node.js 18 ignores.
12
12
  const OPTIONS = new Set(["construct", "destroy", "final", "transform", "flush"]);
@@ -48,7 +48,7 @@ export class FindStreamThenableImplementations extends Recipe {
48
48
  return n;
49
49
  }
50
50
  const options = n.arguments.elements[0]?.element;
51
- if (!isObjectLiteral(options)) {
51
+ if (!options || !isObjectLiteral(options)) {
52
52
  return n;
53
53
  }
54
54
  let changed = false;
@@ -107,10 +107,8 @@ function isAsyncImplementation(member: J): boolean {
107
107
  if (member.kind === J.Kind.MethodDeclaration) {
108
108
  return isAsync((member as J.MethodDeclaration).modifiers);
109
109
  }
110
- let value: J | undefined = (member as JS.PropertyAssignment).initializer;
111
- if (value?.kind === JS.Kind.StatementExpression) {
112
- value = (value as JS.StatementExpression).statement;
113
- }
110
+ const initializer = (member as JS.PropertyAssignment).initializer;
111
+ const value = initializer && (functionExpressionOf(initializer) ?? initializer);
114
112
  return (value?.kind === JS.Kind.ArrowFunction || value?.kind === J.Kind.MethodDeclaration) &&
115
113
  isAsync((value as JS.ArrowFunction | J.MethodDeclaration).modifiers);
116
114
  }
@@ -6,7 +6,7 @@
6
6
 
7
7
  import {Cursor, ExecutionContext, foundSearchResult, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
8
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
9
- import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
9
+ import {JavaScriptVisitor, JS, present} from "@openrewrite/rewrite/javascript";
10
10
  import {
11
11
  bindingsOf,
12
12
  FS_EXTRA_MODULES,
@@ -16,7 +16,7 @@ import {
16
16
  sourcePathOf,
17
17
  stringLiteral
18
18
  } from "./fs-extra-support";
19
- import {FD_METHODS} from "./replace-fs-extra-native-methods";
19
+ import {FD_METHODS, isCallbackUndecidable} from "./replace-fs-extra-native-methods";
20
20
 
21
21
  const MOVE = new Set(['move', 'moveSync']);
22
22
  const EMPTY_DIR = new Set(['emptyDir', 'emptydir', 'emptyDirSync', 'emptydirSync']);
@@ -47,6 +47,10 @@ export const REASONS = {
47
47
  promises: "`fse.promises` is graceful-fs' promise API. Import the method from `node:fs/promises` instead.",
48
48
  realpathNative: "`fse.realpath.native` is graceful-fs' native realpath. Use `realpath` from `node:fs/promises` " +
49
49
  "or `realpathSync.native` from `node:fs`.",
50
+ callbackUndecidable: (method: string) => `fs-extra's \`${method}\` uses the callback API only when its last ` +
51
+ "argument is a function, and that argument's type (`any`, untyped JavaScript, a union of a function and " +
52
+ `data, or a named type alias) doesn't say whether it is. Call \`${method}\` from \`node:fs\` with a ` +
53
+ "callback, or migrate the promise form without one.",
50
54
  unsupported: (method: string) => `not migrated automatically: ${method} with unsupported arguments; ` +
51
55
  "rewrite it with `node:fs` or `node:fs/promises`.",
52
56
  value: (name: string) => `fs-extra \`${name}\` is used as a value rather than called, so it can't be rewritten in place. ` +
@@ -94,8 +98,9 @@ export class FindFsExtraManualMigrations extends Recipe {
94
98
  readonly name = "org.openrewrite.node.migrate.fs-extra.find-fs-extra-manual-migrations";
95
99
  readonly displayName = "Find fs-extra usages that need manual migration";
96
100
  readonly description = "Marks every fs-extra usage the automated migration leaves in place — `move`, `emptyDir`, " +
97
- "`ensureLink`/`ensureSymlink`, `exists`, promise-form `open`, `glob` and fd-based methods, calls with " +
98
- "unsupported arguments, fs-extra used as a value, type imports, re-exports, dynamic imports, and test mocks — " +
101
+ "`ensureLink`/`ensureSymlink`, `exists`, promise-form `open`, `glob` and fd-based methods, calls whose last " +
102
+ "argument may or may not be a callback, calls with unsupported arguments, fs-extra used as a value, type " +
103
+ "imports, re-exports, dynamic imports, and test mocks — " +
99
104
  "and records each with a suggested replacement in the `FsExtraManualMigrationSteps` data table.";
100
105
 
101
106
  private readonly steps = fsExtraManualMigrationSteps();
@@ -181,6 +186,9 @@ export class FindFsExtraManualMigrations extends Recipe {
181
186
  if (EMPTY_DIR.has(member)) return this.report(m, member, REASONS.emptyDir, p);
182
187
  if (LINK.has(member)) return this.report(m, member, REASONS.link, p);
183
188
  if (member === 'exists') return this.report(m, member, REASONS.exists, p);
189
+ if (isCallbackUndecidable(member, present(m.arguments.elements).map(a => a.element))) {
190
+ return this.report(m, member, REASONS.callbackUndecidable(member), p);
191
+ }
184
192
  if (member === 'open') return this.report(m, member, REASONS.open, p);
185
193
  if (member === 'glob') return this.report(m, member, REASONS.glob, p);
186
194
  if (FD_METHODS.has(member)) return this.report(m, member, REASONS.fd(member), p);
@@ -204,11 +204,6 @@ function isStatementContainer(c: Cursor | undefined): boolean {
204
204
  return c?.value?.kind === J.Kind.Block || c?.value?.kind === JS.Kind.CompilationUnit;
205
205
  }
206
206
 
207
- /** Whether `e` is an object literal, which parses as a `J.NewClass` carrying no class name. */
208
- export function isObjectLiteral(e: J | undefined): e is J.NewClass {
209
- return e?.kind === J.Kind.NewClass && !(e as J.NewClass).class;
210
- }
211
-
212
207
  /** The name an object-literal member states, whether written bare or quoted. */
213
208
  export function propertyNameOf(prop: JS.PropertyAssignment): string | undefined {
214
209
  const name = prop.name.element;
@@ -18,8 +18,9 @@ export class MigrateFsExtraToNodeFs extends Recipe {
18
18
  "re-exports are bound from `node:fs` or `node:fs/promises` directly. `move` becomes a call to a helper " +
19
19
  "written into the same file, since `rename` alone doesn't create the destination's parent, refuse an " +
20
20
  "existing destination, or work across devices. Calls without a faithful native equivalent " +
21
- "(`ensureSymlink`, `ensureLink`, ...) are left in place and listed in the `FsExtraManualMigrationSteps` " +
22
- "data table. " +
21
+ "(`ensureSymlink`, `ensureLink`, ...), and calls whose last argument's type doesn't say whether it is a " +
22
+ "callback (`any`, untyped JavaScript, a union of a function and data, a named type alias), are left in " +
23
+ "place and listed in the `FsExtraManualMigrationSteps` data table. " +
23
24
  "`fs-extra` and `@types/fs-extra` are removed from each `package.json` that declares them, with the lock file " +
24
25
  "updated to match. They are removed even where a call listed in the data table still uses fs-extra, so " +
25
26
  "migrate those before building. " +
@@ -6,8 +6,8 @@
6
6
 
7
7
  import {Cursor, emptyMarkers, ExecutionContext, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
8
  import {emptySpace, isIdentifier, J} from "@openrewrite/rewrite/java";
9
- import {JS, raw, template} from "@openrewrite/rewrite/javascript";
10
- import {FsExtraVisitor, isFunctionLike, isObjectLiteral, propertyNameOf} from "./fs-extra-support";
9
+ import {isObjectLiteral, isTypeScript, JS, raw, template} from "@openrewrite/rewrite/javascript";
10
+ import {FsExtraVisitor, isFunctionLike, propertyNameOf} from "./fs-extra-support";
11
11
 
12
12
  const PROMISE_METHODS = new Set(['move']);
13
13
  const SYNC_METHODS = new Set(['moveSync']);
@@ -105,7 +105,7 @@ export class ReplaceFsExtraMove extends Recipe {
105
105
 
106
106
  /** Appends each helper the file needs, after the statements that call it. */
107
107
  private async withHelpers(cu: JS.CompilationUnit, p: ExecutionContext): Promise<JS.CompilationUnit> {
108
- const typeScript = /\.[cm]?tsx?$/.test(cu.sourcePath);
108
+ const typeScript = isTypeScript(cu);
109
109
  let result = cu;
110
110
  for (const helper of this.helpers.values()) {
111
111
  const declaration = await this.buildHelper(helper, typeScript, result, p);
@@ -5,8 +5,8 @@
5
5
  */
6
6
 
7
7
  import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
- import {isIdentifier, J} from "@openrewrite/rewrite/java";
9
- import {compilationUnitOf, declarationsOf, JS, maybeRebind, walk} from "@openrewrite/rewrite/javascript";
8
+ import {isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
9
+ import {compilationUnitOf, declarationsOf, isObjectLiteral, JS, maybeRebind, walk, withStringValue} from "@openrewrite/rewrite/javascript";
10
10
  import {FS_EXTRA_MODULES, FsExtraVisitor, isFunctionLike, isModuleScoped, NodeModule, nodeSpecifier} from "./fs-extra-support";
11
11
 
12
12
  /** Methods fs-extra universalifies: a promise without a callback, the callback API with one. */
@@ -36,15 +36,81 @@ const FS_METHODS = new Set([
36
36
  'createWriteStream', 'watch', 'watchFile', 'unwatchFile'
37
37
  ]);
38
38
 
39
- // An identifier argument could be data or a callback; only these names are read as callbacks.
40
- const CALLBACK_NAME = /^(cb|callback|done|next)$/i;
39
+ /**
40
+ * Arguments the `node:fs` callback API requires before the callback, where more than the one path
41
+ * or fd every other method requires: an argument in a required slot is data, so only one past them
42
+ * can be the callback.
43
+ */
44
+ const REQUIRED_ARGUMENTS = new Map([
45
+ ['appendFile', 2], ['chmod', 2], ['chown', 3], ['copyFile', 2], ['cp', 2], ['fchmod', 2], ['fchown', 3],
46
+ ['futimes', 3], ['lchmod', 2], ['lchown', 3], ['link', 2], ['lutimes', 3], ['readv', 2], ['rename', 2],
47
+ ['symlink', 2], ['utimes', 3], ['write', 2], ['writeFile', 2], ['writev', 2]
48
+ ]);
49
+
50
+ /** Expressions that evaluate to data whatever their attributed type, as no function can come out of them. */
51
+ const DATA_KINDS = new Set<string>([J.Kind.Literal, JS.Kind.TemplateExpression, J.Kind.NewArray, J.Kind.Unary]);
52
+
53
+ function isData(e: J): boolean {
54
+ if (e.kind === J.Kind.Binary) {
55
+ // Either operand of `&&` and `||` can come out of them, so those go by their type.
56
+ const op = (e as J.Binary).operator.element;
57
+ return op !== J.Binary.Type.And && op !== J.Binary.Type.Or;
58
+ }
59
+ return DATA_KINDS.has(e.kind) || isObjectLiteral(e);
60
+ }
61
+
62
+ /**
63
+ * Whether the last argument of a universalified call is its callback, by the argument's type, or
64
+ * undefined when the type can't tell: `any`, `unknown`, untyped JavaScript, a union of a function
65
+ * and data, or a named type alias, whose shape the type attribution doesn't record. fs-extra checks
66
+ * `typeof last === 'function'` at runtime, so a name says nothing.
67
+ */
68
+ function callbackArgument(e: J | undefined): boolean | undefined {
69
+ if (!e) return false;
70
+ if (isFunctionLike(e)) return true;
71
+ if (isData(e)) return false;
72
+ return isFunctionTyped(TypedTree.getType(e as TypedTree));
73
+ }
74
+
75
+ function isFunctionTyped(type: Type | undefined): boolean | undefined {
76
+ if (!type || type.kind === Type.Kind.Unknown || Type.isGenericTypeVariable(type)) return undefined;
77
+ if (Type.isUnion(type)) {
78
+ const bounds = new Set(type.bounds.filter(b => b !== Type.Primitive.Null && b !== Type.Primitive.None).map(isFunctionTyped));
79
+ return bounds.size === 1 ? [...bounds][0] : undefined;
80
+ }
81
+ if (Type.isIntersection(type)) {
82
+ const bounds = type.bounds.map(isFunctionTyped);
83
+ return bounds.includes(true) ? true : bounds.includes(undefined) ? undefined : false;
84
+ }
85
+ if (Type.isMethod(type)) return true;
86
+ // Inherited too, as a callable interface such as `jest.Mock` extends `Function`.
87
+ if (Type.isOfTypeWithName(type, true, n => n === Type.FUNCTION_TYPE_NAME || n === 'Function')) return true;
88
+ const c = Type.isParameterized(type) ? type.type : type;
89
+ // A named alias of a function type, or of an object type, or an interface with only call
90
+ // signatures, is attributed as an interface with nothing in it, so it may be either.
91
+ if (Type.isClass(c) && c.classKind === Type.Class.Kind.Interface && c.fullyQualifiedName !== Type.OBJECT_TYPE_NAME &&
92
+ c.members.length === 0 && c.methods.length === 0 && c.interfaces.length === 0 && !c.supertype) {
93
+ return undefined;
94
+ }
95
+ return false;
96
+ }
97
+
98
+ /**
99
+ * Whether a universalified call's last argument could be its callback and its type can't say, so
100
+ * neither the callback nor the promise API is known to be the one the call uses.
101
+ */
102
+ export function isCallbackUndecidable(method: string, args: J[]): boolean {
103
+ return (PROMISE_METHODS.has(method) || FD_METHODS.has(method)) &&
104
+ args.length > (REQUIRED_ARGUMENTS.get(method) ?? 1) && callbackArgument(args[args.length - 1]) === undefined;
105
+ }
41
106
 
42
107
  function isCallback(e: J | undefined): boolean {
43
- return isFunctionLike(e) || (!!e && isIdentifier(e) && CALLBACK_NAME.test(e.simpleName));
108
+ return callbackArgument(e) === true;
44
109
  }
45
110
 
46
111
  function targetModule(method: string, args: J[]): NodeModule | undefined {
47
112
  if (FS_METHODS.has(method)) return 'fs';
113
+ if (isCallbackUndecidable(method, args)) return undefined;
48
114
  const callback = isCallback(args[args.length - 1]);
49
115
  if (callback) return PROMISE_METHODS.has(method) || FD_METHODS.has(method) ? 'fs' : undefined;
50
116
  return PROMISE_METHODS.has(method) && !RESHAPED_METHODS.has(method) ? 'fs/promises' : undefined;
@@ -120,8 +186,7 @@ function retargetRequires(cu: JS.CompilationUnit): JS.CompilationUnit {
120
186
  if (targets.size !== 1 || !target) return s;
121
187
 
122
188
  const spec = nodeSpecifier(cu, target);
123
- const quote = arg.valueSource?.[0] ?? "'";
124
- const literal: J.Literal = {...arg, value: spec, valueSource: `${quote}${spec}${quote}`};
189
+ const literal = withStringValue(arg, spec);
125
190
  const newInit: J.MethodInvocation = {
126
191
  ...init!,
127
192
  arguments: {...init!.arguments, elements: [{...init!.arguments.elements[0], element: literal}]}
@@ -148,7 +213,9 @@ export class ReplaceFsExtraNativeMethods extends Recipe {
148
213
  "no callback is passed. Promise-form calls move to `node:fs/promises`; callback-form calls, `*Sync` " +
149
214
  "methods, streams, watchers and `constants` move to `node:fs`. fd-based methods, `open` and `glob` keep " +
150
215
  "their promise form on fs-extra, as `node:fs/promises` has no fd-number equivalents and its `open` and " +
151
- "`glob` resolve to a `FileHandle` and an async iterator rather than an fd and an array.";
216
+ "`glob` resolve to a `FileHandle` and an async iterator rather than an fd and an array. Whether a call " +
217
+ "passes a callback is read from its last argument's type, so a call whose last argument may or may not be " +
218
+ "a function (`any`, untyped JavaScript, a union of both, a named type alias) is left on fs-extra.";
152
219
 
153
220
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
154
221
  return new class extends FsExtraVisitor<ExecutionContext> {
@@ -6,7 +6,7 @@
6
6
 
7
7
  import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
8
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
9
- import {JS, raw, template} from "@openrewrite/rewrite/javascript";
9
+ import {isObjectLiteral, JS, raw, template} from "@openrewrite/rewrite/javascript";
10
10
  import {FsExtraVisitor} from "./fs-extra-support";
11
11
 
12
12
  const ASYNC = new Set(['readJson', 'readJSON']);
@@ -28,8 +28,8 @@ function isStringLiteral(e: J | undefined): boolean {
28
28
  * `throws`, `reviver`, and `fs` have no `readFile` counterpart.
29
29
  */
30
30
  function encodingOption(e: J): J | null {
31
- if (e.kind !== J.Kind.NewClass || (e as J.NewClass).class) return null;
32
- const statements = (e as J.NewClass).body?.statements ?? [];
31
+ if (!isObjectLiteral(e)) return null;
32
+ const statements = e.body?.statements ?? [];
33
33
  if (statements.length !== 1 || statements[0].element.kind !== JS.Kind.PropertyAssignment) return null;
34
34
  const prop = statements[0].element as JS.PropertyAssignment;
35
35
  const name = prop.name.element;
@@ -4,7 +4,7 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
  import {check, ExecutionContext, or, Recipe, TreeVisitor} from "@openrewrite/rewrite";
7
- import {JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport, template, usesType} from "@openrewrite/rewrite/javascript";
7
+ import {compilationUnitOf, isTypeScript, JavaScriptVisitor, maybeAddImport, maybeRemoveImport, template, usesType} from "@openrewrite/rewrite/javascript";
8
8
  import {J, Type} from "@openrewrite/rewrite/java";
9
9
 
10
10
  /**
@@ -18,17 +18,6 @@ export class ReplaceFsStatsConstructor extends Recipe {
18
18
 
19
19
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
20
20
  return check(or(usesType("fs.Stats"), usesType("node:fs.Stats")), new class extends JavaScriptVisitor<ExecutionContext> {
21
-
22
- private isItTypescript = false;
23
-
24
- protected visitJsCompilationUnit(compilationUnit: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
25
- const ret = super.visitJsCompilationUnit(compilationUnit, p);
26
- if (compilationUnit.sourcePath.endsWith(".ts") || compilationUnit.sourcePath.endsWith(".tsx")) {
27
- this.isItTypescript = true;
28
- }
29
- return ret;
30
- }
31
-
32
21
  protected async visitNewClass(newClass: J.NewClass, p: ExecutionContext): Promise<J | undefined> {
33
22
  const clazz = newClass.class;
34
23
  let shouldReplace = false;
@@ -57,7 +46,7 @@ export class ReplaceFsStatsConstructor extends Recipe {
57
46
  }
58
47
 
59
48
  if (shouldReplace) {
60
- if (this.isItTypescript) {
49
+ if (isTypeScript(compilationUnitOf(this)!)) {
61
50
  return await template`({
62
51
  dev: 0,
63
52
  mode: 0,
@@ -6,7 +6,7 @@
6
6
 
7
7
  import {Column, Cursor, DataTable, emptyMarkers, randomId} from "@openrewrite/rewrite";
8
8
  import {emptySpace, isIdentifier, J, rightPadded, space, Type} from "@openrewrite/rewrite/java";
9
- import {bindingNames, declarationsOf, JS, moduleExportName, scopeOf, walk} from "@openrewrite/rewrite/javascript";
9
+ import {bindingNames, declarationsOf, isObjectLiteral, JS, moduleExportName, scopeOf, walk} from "@openrewrite/rewrite/javascript";
10
10
  import {CodeStyle, DEFAULT_CODE_STYLE, indented} from "../code-style";
11
11
  import {bindingsOf, importModule, ModuleBindings, requiredModule, stringLiteral} from "../module-bindings";
12
12
 
@@ -293,11 +293,6 @@ export function propertyName(prop: JS.PropertyAssignment): string | undefined {
293
293
  return isIdentifier(name) ? name.simpleName : stringLiteral(name);
294
294
  }
295
295
 
296
- /** Whether `e` is an object literal, which parses as a `J.NewClass` carrying no class name. */
297
- export function isObjectLiteral(e: J | undefined): e is J.NewClass {
298
- return e?.kind === J.Kind.NewClass && !(e as J.NewClass).class;
299
- }
300
-
301
296
  export function objectMembers(literal: J.NewClass): J[] {
302
297
  return (literal.body?.statements ?? []).map(s => s.element).filter(s => s.kind !== J.Kind.Empty);
303
298
  }
@@ -453,7 +448,7 @@ export function resolvedSpreadLiteral(cu: JS.CompilationUnit, spread: J | undefi
453
448
  if (!isIdentifier(variable.name as J) || (variable.name as J.Identifier).simpleName !== name) continue;
454
449
  declarations++;
455
450
  const initializer = variable.initializer?.element;
456
- if (isObjectLiteral(initializer)) literal = initializer;
451
+ if (initializer && isObjectLiteral(initializer)) literal = initializer;
457
452
  }
458
453
  } else if (n?.kind === J.Kind.Assignment) {
459
454
  assigned = assigned || rootIdentifier((n as J.Assignment).variable) === name;
@@ -12,14 +12,17 @@ import {
12
12
  compilationUnitOf,
13
13
  declarationsOf,
14
14
  deconflict,
15
+ isObjectLiteral,
15
16
  isReference,
17
+ isTypeScript,
16
18
  JavaScriptParser,
17
19
  JavaScriptVisitor,
18
20
  JS,
19
21
  maybeRebind,
20
22
  maybeUnbind,
21
23
  namesUsedIn,
22
- StyleKind
24
+ StyleKind,
25
+ withStringValue
23
26
  } from "@openrewrite/rewrite/javascript";
24
27
  import {detectCodeStyle} from "../code-style";
25
28
  import {bindingsOf, importModule, requiredModule} from "../module-bindings";
@@ -43,7 +46,6 @@ import {
43
46
  isHpagentRequire,
44
47
  isKnownProxyRequestOptions,
45
48
  isMockCall,
46
- isObjectLiteral,
47
49
  isValueUse,
48
50
  ModuleBindings,
49
51
  objectMembers,
@@ -126,8 +128,7 @@ function renameBindings(target: J, targetLocals: ReadonlyMap<string, string>, me
126
128
  }
127
129
 
128
130
  function retargeted(literal: J.Literal): J.Literal {
129
- const quote = (literal.valueSource ?? "'").charAt(0);
130
- return {...literal, value: TARGET_MODULE, valueSource: `${quote}${TARGET_MODULE}${quote}`};
131
+ return withStringValue(literal, TARGET_MODULE);
131
132
  }
132
133
 
133
134
  /** `require('hpagent')` naming the new module, together with a `typeof import('hpagent')` it is cast to. */
@@ -775,9 +776,7 @@ export class ReplaceHpagent extends Recipe {
775
776
  const spied = spiedClass(m);
776
777
  if (spied && spied !== TARGET_CLASS && first && isIdentifier(first) && this.bindings.has(first.simpleName) &&
777
778
  this.bindings.get(first.simpleName) === undefined && !this.stranded.has(first.simpleName)) {
778
- const literal = args[1].element as J.Literal;
779
- const quote = (literal.valueSource ?? "'").charAt(0);
780
- const renamed = {...literal, value: TARGET_CLASS, valueSource: `${quote}${TARGET_CLASS}${quote}`};
779
+ const renamed = withStringValue(args[1].element as J.Literal, TARGET_CLASS);
781
780
  return {...m, arguments: {...m.arguments, elements: [args[0], {...args[1], element: renamed}, ...args.slice(2)]}} as J.MethodInvocation;
782
781
  }
783
782
  return m;
@@ -927,7 +926,7 @@ export class ReplaceHpagent extends Recipe {
927
926
 
928
927
  /** Appends the adapter and its options type, after the statements that use them. */
929
928
  private async withAdapter(cu: JS.CompilationUnit, p: ExecutionContext): Promise<JS.CompilationUnit> {
930
- const typeScript = !isJavaScript(cu.sourcePath);
929
+ const typeScript = isTypeScript(cu);
931
930
  const style = detectCodeStyle(await TreePrinters.print(cu));
932
931
  const sources: GeneratedDeclaration[] = [];
933
932
  if (this.adapterNeeded) sources.push(adapterSource(this.adapterName, this.typeName, this.agentClass(), typeScript, style));
@@ -4,9 +4,12 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
 
7
- import {ExecutionContext, Option, Recipe, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
8
- import {Json, JsonParser, JsonVisitor} from "@openrewrite/rewrite/json";
7
+ import {ExecutionContext, Option, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {isLiteral, Json, jsonLiteral, JsonVisitor, setAt, valueAt} from "@openrewrite/rewrite/json";
9
9
  import * as semver from "semver";
10
+ import {isPackageJson} from "./package-json-support";
11
+
12
+ const NODE_ENGINE = ['engines', 'node'];
10
13
 
11
14
  export class IncreaseNodeEngineVersion extends Recipe {
12
15
  readonly name = "org.openrewrite.node.migrate.increase-node-engine-version";
@@ -34,46 +37,17 @@ export class IncreaseNodeEngineVersion extends Recipe {
34
37
 
35
38
  return new class extends JsonVisitor<ExecutionContext> {
36
39
  protected async visitDocument(doc: Json.Document, _ctx: ExecutionContext): Promise<Json | undefined> {
37
- if (!doc.sourcePath.endsWith('package.json')) {
38
- return doc;
39
- }
40
-
41
- const content = await TreePrinters.print(doc);
42
- let packageJson: Record<string, any>;
43
- try {
44
- packageJson = JSON.parse(content);
45
- } catch {
40
+ if (!isPackageJson(doc.sourcePath)) {
46
41
  return doc;
47
42
  }
48
43
 
49
- const nodeRange = packageJson?.engines?.node;
50
- if (typeof nodeRange !== 'string') {
44
+ const range = valueAt(doc, NODE_ENGINE);
45
+ if (!range || !isLiteral(range) || typeof range.value !== 'string') {
51
46
  return doc;
52
47
  }
53
48
 
54
- const updatedRange = raiseMinimumVersion(nodeRange, targetVersion);
55
- if (updatedRange === nodeRange) {
56
- return doc;
57
- }
58
-
59
- // Targeted replacement preserves the file's original formatting (indentation,
60
- // trailing newline, key order) instead of round-tripping through JSON.stringify.
61
- const nodeMemberRegex = /("engines"\s*:\s*\{[\s\S]*?"node"\s*:\s*)"([^"]+)"/;
62
- const modifiedContent = content.replace(nodeMemberRegex, `$1${JSON.stringify(updatedRange)}`);
63
- if (modifiedContent === content) {
64
- return doc;
65
- }
66
-
67
- const parsed = await new JsonParser({}).parseOne({
68
- text: modifiedContent,
69
- sourcePath: doc.sourcePath
70
- }) as Json.Document;
71
-
72
- return {
73
- ...doc,
74
- value: parsed.value,
75
- eof: parsed.eof
76
- } as Json.Document;
49
+ const updatedRange = raiseMinimumVersion(range.value, targetVersion);
50
+ return updatedRange === range.value ? doc : setAt(doc, NODE_ENGINE, jsonLiteral(updatedRange));
77
51
  }
78
52
  };
79
53
  }
@@ -5,71 +5,55 @@
5
5
  */
6
6
 
7
7
  import {emptyMarkers, randomId} from "@openrewrite/rewrite";
8
- import {getMemberKeyName, isArray, isLiteral, isMember, Json, rightPadded, space} from "@openrewrite/rewrite/json";
9
-
10
- export function memberIndex(obj: Json.Object, key: string): number {
11
- return obj.members.findIndex(rp => isMember(rp.element) && getMemberKeyName(rp.element as Json.Member) === key);
12
- }
13
-
14
- export function memberValue(obj: Json.Object, key: string): Json.Value | undefined {
15
- const i = memberIndex(obj, key);
16
- return i < 0 ? undefined : (obj.members[i].element as Json.Member).value;
17
- }
18
-
19
- /**
20
- * Drops the padded elements `keep` rejects, handing the last one's trailing space (the space before
21
- * the closing bracket) to the new last element, so the list still closes on its own line.
22
- */
23
- export function removePadded<T extends Json>(elements: Json.RightPadded<T>[], keep: (e: T) => boolean): Json.RightPadded<T>[] {
24
- const kept = elements.filter(rp => keep(rp.element));
25
- if (kept.length === elements.length || kept.length === 0) return kept;
26
- // A removed first element leaves its prefix (the newline and indent after the bracket) to its successor.
27
- if (!keep(elements[0].element)) {
28
- kept[0] = {...kept[0], element: {...kept[0].element, prefix: elements[0].element.prefix}};
29
- }
30
- kept[kept.length - 1] = {...kept[kept.length - 1], after: elements[elements.length - 1].after};
31
- return kept;
32
- }
33
-
34
- /** Inserts `element` after index `i`, formatted like its predecessor. */
35
- export function insertPaddedAfter<T extends Json>(elements: Json.RightPadded<T>[], i: number, element: T): Json.RightPadded<T>[] {
36
- const before = elements[i];
37
- const isLast = i === elements.length - 1;
38
- // The first element sits right after the bracket, so on one line its successors need a space of their own.
39
- const prefix = i === 0 && !before.element.prefix.whitespace.includes('\n') ? space(' ') : before.element.prefix;
40
- const inserted = rightPadded({...element, prefix}, isLast ? before.after : space(''));
41
- const result = [...elements];
42
- result[i] = isLast ? {...before, after: space('')} : before;
43
- result.splice(i + 1, 0, inserted);
44
- return result;
45
- }
46
-
47
- /** An empty object or array keeps a lone `Json.Empty` so the printer has somewhere to put the inner space. */
48
- export function emptyPadded(): Json.RightPadded<Json.Empty>[] {
49
- const empty: Json.Empty = {kind: Json.Kind.Empty, id: randomId(), prefix: space(''), markers: emptyMarkers};
50
- return [rightPadded(empty, space(''))];
51
- }
52
-
53
- export function literal(value: string | boolean): Json.Literal {
54
- return {kind: Json.Kind.Literal, id: randomId(), prefix: space(' '), markers: emptyMarkers, source: JSON.stringify(value), value};
55
- }
56
-
57
- export function stringArray(values: string[]): Json.Array {
58
- return {
59
- kind: Json.Kind.Array, id: randomId(), prefix: space(' '), markers: emptyMarkers,
60
- values: values.map((v, i) => rightPadded({...literal(v), prefix: space(i === 0 ? '' : ' ')}, space('')))
8
+ import {emptySpace, getMemberKeyName, isLiteral, isMember, Json, jsonLiteral, rightPadded, space} from "@openrewrite/rewrite/json";
9
+
10
+ /** Replaces each member with what `fn` makes of it, compared by reference. */
11
+ export function mapMembers(obj: Json.Object, fn: (member: Json.Member) => Json.Member): Json.Object {
12
+ let changed = false;
13
+ const members = obj.members.map(rp => {
14
+ if (!isMember(rp.element)) return rp;
15
+ const member = fn(rp.element);
16
+ if (member === rp.element) return rp;
17
+ changed = true;
18
+ return {...rp, element: member};
19
+ });
20
+ return changed ? {...obj, members} : obj;
21
+ }
22
+
23
+ export function mapStrings(obj: Json.Object, fn: (value: string) => string): Json.Object {
24
+ return mapMembers(obj, m => {
25
+ if (!isLiteral(m.value) || typeof m.value.value !== 'string') return m;
26
+ const updated = fn(m.value.value);
27
+ return updated === m.value.value ? m : {...m, value: {...m.value, value: updated, source: JSON.stringify(updated)}};
28
+ });
29
+ }
30
+
31
+ export function replaceMember(obj: Json.Object, key: string, newKey: string, value: Json.Value): Json.Object {
32
+ return mapMembers(obj, m => getMemberKeyName(m) !== key ? m : {
33
+ ...m,
34
+ key: {...m.key, element: jsonLiteral(newKey, m.key.element.prefix)},
35
+ value: {...value, prefix: m.value.prefix}
36
+ });
37
+ }
38
+
39
+ export function insertMemberAfter(obj: Json.Object, key: string, newKey: string, value: Json.Value): Json.Object {
40
+ const i = obj.members.findIndex(rp => isMember(rp.element) && getMemberKeyName(rp.element) === key);
41
+ if (i < 0) return obj;
42
+ const before = obj.members[i];
43
+ const m = before.element as Json.Member;
44
+ const isLast = i === obj.members.length - 1;
45
+ const added: Json.Member = {
46
+ kind: Json.Kind.Member, id: randomId(), prefix: indentationOf(m.prefix), markers: emptyMarkers,
47
+ key: rightPadded(jsonLiteral(newKey), m.key.after), value: {...value, prefix: m.value.prefix}
61
48
  };
49
+ const members = [...obj.members];
50
+ members[i] = isLast ? {...before, after: emptySpace} : before;
51
+ members.splice(i + 1, 0, rightPadded(added, isLast ? before.after : emptySpace));
52
+ return {...obj, members};
62
53
  }
63
54
 
64
- export function member(key: string, value: Json.Value): Json.Member {
65
- const keyLiteral: Json.Literal = {...literal(key), prefix: space('')};
66
- return {kind: Json.Kind.Member, id: randomId(), prefix: space(''), markers: emptyMarkers, key: rightPadded(keyLiteral, space('')), value};
67
- }
68
-
69
- /** The string values of a `"key": "x"` or `"key": ["x", ...]` entry. */
70
- export function stringValues(value: Json.Value | undefined): string[] {
71
- if (!value) return [];
72
- if (isLiteral(value)) return typeof value.value === 'string' ? [value.value] : [];
73
- if (isArray(value)) return value.values.flatMap(rp => stringValues(rp.element));
74
- return [];
55
+ /** The line break and indentation a prefix ends with, without its comments, or a single space on one line. */
56
+ function indentationOf(prefix: Json.Space): Json.Space {
57
+ const line = [prefix.whitespace, ...prefix.comments.map(c => c.suffix)].filter(t => t.includes('\n')).pop();
58
+ return space(line === undefined ? ' ' : line.substring(line.lastIndexOf('\n')));
75
59
  }
@@ -4,8 +4,7 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
  import {Expression, J} from "@openrewrite/rewrite/java";
7
- import {JS} from "@openrewrite/rewrite/javascript";
8
- import {isObjectLiteral} from "./fs-extra/fs-extra-support";
7
+ import {isObjectLiteral, JS} from "@openrewrite/rewrite/javascript";
9
8
 
10
9
  /** The expression under any parentheses and TypeScript casts (`as`, `<T>`, `satisfies`). */
11
10
  export function withoutCasts(e: J | undefined): J | undefined {
@@ -35,7 +34,7 @@ export function withoutCasts(e: J | undefined): J | undefined {
35
34
  */
36
35
  export function optionsLiteral(arg: J | undefined): J.NewClass | undefined {
37
36
  const e = withoutCasts(arg);
38
- return isObjectLiteral(e) ? e : undefined;
37
+ return e && isObjectLiteral(e) ? e : undefined;
39
38
  }
40
39
 
41
40
  /** `arg` with the object literal {@link optionsLiteral} finds in it replaced by `literal`, its parentheses and casts kept. */