@openrewrite/rewrite 8.97.0 → 8.97.2

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 (152) hide show
  1. package/README.md +42 -0
  2. package/dist/java/visitor.d.ts +2 -0
  3. package/dist/java/visitor.d.ts.map +1 -1
  4. package/dist/java/visitor.js +7 -3
  5. package/dist/java/visitor.js.map +1 -1
  6. package/dist/javascript/add-import.d.ts +1 -6
  7. package/dist/javascript/add-import.d.ts.map +1 -1
  8. package/dist/javascript/add-import.js +90 -58
  9. package/dist/javascript/add-import.js.map +1 -1
  10. package/dist/javascript/comparator.d.ts +16 -10
  11. package/dist/javascript/comparator.d.ts.map +1 -1
  12. package/dist/javascript/comparator.js +10 -8
  13. package/dist/javascript/comparator.js.map +1 -1
  14. package/dist/javascript/package-json-parser.d.ts +2 -0
  15. package/dist/javascript/package-json-parser.d.ts.map +1 -1
  16. package/dist/javascript/package-json-parser.js +27 -15
  17. package/dist/javascript/package-json-parser.js.map +1 -1
  18. package/dist/javascript/package-manager.d.ts +13 -4
  19. package/dist/javascript/package-manager.d.ts.map +1 -1
  20. package/dist/javascript/package-manager.js +134 -17
  21. package/dist/javascript/package-manager.js.map +1 -1
  22. package/dist/javascript/parser.d.ts +2 -0
  23. package/dist/javascript/parser.d.ts.map +1 -1
  24. package/dist/javascript/parser.js +23 -58
  25. package/dist/javascript/parser.js.map +1 -1
  26. package/dist/javascript/print.d.ts.map +1 -1
  27. package/dist/javascript/print.js +1 -1
  28. package/dist/javascript/print.js.map +1 -1
  29. package/dist/javascript/recipes/change-method-target-to-import.d.ts +4 -0
  30. package/dist/javascript/recipes/change-method-target-to-import.d.ts.map +1 -1
  31. package/dist/javascript/recipes/change-method-target-to-import.js +20 -2
  32. package/dist/javascript/recipes/change-method-target-to-import.js.map +1 -1
  33. package/dist/javascript/recipes/dependencies.d.ts +19 -0
  34. package/dist/javascript/recipes/dependencies.d.ts.map +1 -1
  35. package/dist/javascript/recipes/dependencies.js +8 -0
  36. package/dist/javascript/recipes/dependencies.js.map +1 -1
  37. package/dist/javascript/recipes/order-imports.js +3 -3
  38. package/dist/javascript/recipes/order-imports.js.map +1 -1
  39. package/dist/javascript/remove-import.d.ts.map +1 -1
  40. package/dist/javascript/remove-import.js +115 -33
  41. package/dist/javascript/remove-import.js.map +1 -1
  42. package/dist/javascript/scope.d.ts +7 -0
  43. package/dist/javascript/scope.d.ts.map +1 -1
  44. package/dist/javascript/scope.js +23 -0
  45. package/dist/javascript/scope.js.map +1 -1
  46. package/dist/javascript/templating/bindings.d.ts.map +1 -1
  47. package/dist/javascript/templating/bindings.js +0 -4
  48. package/dist/javascript/templating/bindings.js.map +1 -1
  49. package/dist/javascript/templating/comparator.d.ts +32 -79
  50. package/dist/javascript/templating/comparator.d.ts.map +1 -1
  51. package/dist/javascript/templating/comparator.js +35 -628
  52. package/dist/javascript/templating/comparator.js.map +1 -1
  53. package/dist/javascript/templating/debug.d.ts +143 -0
  54. package/dist/javascript/templating/debug.d.ts.map +1 -0
  55. package/dist/javascript/templating/debug.js +769 -0
  56. package/dist/javascript/templating/debug.js.map +1 -0
  57. package/dist/javascript/templating/engine.d.ts +12 -3
  58. package/dist/javascript/templating/engine.d.ts.map +1 -1
  59. package/dist/javascript/templating/engine.js +135 -76
  60. package/dist/javascript/templating/engine.js.map +1 -1
  61. package/dist/javascript/templating/index.d.ts +1 -1
  62. package/dist/javascript/templating/index.d.ts.map +1 -1
  63. package/dist/javascript/templating/index.js.map +1 -1
  64. package/dist/javascript/templating/pattern.d.ts +44 -35
  65. package/dist/javascript/templating/pattern.d.ts.map +1 -1
  66. package/dist/javascript/templating/pattern.js +224 -238
  67. package/dist/javascript/templating/pattern.js.map +1 -1
  68. package/dist/javascript/templating/rewrite.d.ts +4 -0
  69. package/dist/javascript/templating/rewrite.d.ts.map +1 -1
  70. package/dist/javascript/templating/rewrite.js +5 -1
  71. package/dist/javascript/templating/rewrite.js.map +1 -1
  72. package/dist/javascript/templating/template.js +1 -1
  73. package/dist/javascript/templating/template.js.map +1 -1
  74. package/dist/javascript/templating/types.d.ts +38 -35
  75. package/dist/javascript/templating/types.d.ts.map +1 -1
  76. package/dist/javascript/templating/utils.d.ts.map +1 -1
  77. package/dist/javascript/templating/utils.js +18 -9
  78. package/dist/javascript/templating/utils.js.map +1 -1
  79. package/dist/javascript/tree.d.ts +3 -1
  80. package/dist/javascript/tree.d.ts.map +1 -1
  81. package/dist/javascript/tree.js +5 -0
  82. package/dist/javascript/tree.js.map +1 -1
  83. package/dist/json/tree.d.ts +1 -2
  84. package/dist/json/tree.d.ts.map +1 -1
  85. package/dist/json/tree.js +10 -7
  86. package/dist/json/tree.js.map +1 -1
  87. package/dist/rewrite-javascript-version.txt +1 -1
  88. package/dist/rpc/request/get-object.d.ts.map +1 -1
  89. package/dist/rpc/request/get-object.js +5 -3
  90. package/dist/rpc/request/get-object.js.map +1 -1
  91. package/dist/rpc/request/install-recipes.d.ts +10 -0
  92. package/dist/rpc/request/install-recipes.d.ts.map +1 -1
  93. package/dist/rpc/request/install-recipes.js +125 -51
  94. package/dist/rpc/request/install-recipes.js.map +1 -1
  95. package/dist/rpc/request/prepare-recipe.d.ts +1 -0
  96. package/dist/rpc/request/prepare-recipe.d.ts.map +1 -1
  97. package/dist/rpc/request/prepare-recipe.js +13 -6
  98. package/dist/rpc/request/prepare-recipe.js.map +1 -1
  99. package/dist/rpc/rewrite-rpc.d.ts +1 -1
  100. package/dist/rpc/rewrite-rpc.d.ts.map +1 -1
  101. package/dist/rpc/rewrite-rpc.js +2 -3
  102. package/dist/rpc/rewrite-rpc.js.map +1 -1
  103. package/dist/rpc/worker-transport.d.ts +7 -3
  104. package/dist/rpc/worker-transport.d.ts.map +1 -1
  105. package/dist/rpc/worker-transport.js +54 -41
  106. package/dist/rpc/worker-transport.js.map +1 -1
  107. package/dist/test/rewrite-test.d.ts +1 -16
  108. package/dist/test/rewrite-test.d.ts.map +1 -1
  109. package/dist/test/rewrite-test.js +7 -58
  110. package/dist/test/rewrite-test.js.map +1 -1
  111. package/dist/util.d.ts +16 -0
  112. package/dist/util.d.ts.map +1 -1
  113. package/dist/util.js +53 -0
  114. package/dist/util.js.map +1 -1
  115. package/dist/yaml/parser.js +8 -5
  116. package/dist/yaml/parser.js.map +1 -1
  117. package/dist/yaml/print.js +9 -3
  118. package/dist/yaml/print.js.map +1 -1
  119. package/package.json +1 -1
  120. package/src/java/visitor.ts +8 -3
  121. package/src/javascript/add-import.ts +98 -64
  122. package/src/javascript/comparator.ts +66 -53
  123. package/src/javascript/package-json-parser.ts +25 -16
  124. package/src/javascript/package-manager.ts +121 -15
  125. package/src/javascript/parser.ts +29 -81
  126. package/src/javascript/print.ts +1 -2
  127. package/src/javascript/recipes/change-method-target-to-import.ts +23 -3
  128. package/src/javascript/recipes/dependencies.ts +23 -0
  129. package/src/javascript/recipes/order-imports.ts +5 -5
  130. package/src/javascript/remove-import.ts +113 -41
  131. package/src/javascript/scope.ts +23 -0
  132. package/src/javascript/templating/bindings.ts +1 -6
  133. package/src/javascript/templating/comparator.ts +76 -766
  134. package/src/javascript/templating/debug.ts +806 -0
  135. package/src/javascript/templating/engine.ts +138 -77
  136. package/src/javascript/templating/index.ts +1 -0
  137. package/src/javascript/templating/pattern.ts +267 -270
  138. package/src/javascript/templating/rewrite.ts +5 -1
  139. package/src/javascript/templating/template.ts +1 -1
  140. package/src/javascript/templating/types.ts +40 -37
  141. package/src/javascript/templating/utils.ts +4 -12
  142. package/src/javascript/tree.ts +6 -1
  143. package/src/json/tree.ts +9 -7
  144. package/src/rpc/request/get-object.ts +34 -28
  145. package/src/rpc/request/install-recipes.ts +128 -52
  146. package/src/rpc/request/prepare-recipe.ts +18 -15
  147. package/src/rpc/rewrite-rpc.ts +2 -4
  148. package/src/rpc/worker-transport.ts +63 -43
  149. package/src/test/rewrite-test.ts +2 -59
  150. package/src/util.ts +58 -0
  151. package/src/yaml/parser.ts +9 -5
  152. package/src/yaml/print.ts +9 -3
@@ -29,7 +29,8 @@ import * as fs from "fs";
29
29
  import * as fsp from "fs/promises";
30
30
  import * as path from "path";
31
31
  import * as YAML from "yaml";
32
- import {getLockFileDetectionConfig, getLockFileName, runList, runVersion} from "./package-manager";
32
+ import {getLockFileDetectionConfig, getLockFileName, PackageManagerSelectionError, runList, runVersion, selectPackageManager} from "./package-manager";
33
+ import {markupWarn} from "../markers";
33
34
  import picomatch from "picomatch";
34
35
  import {DEFAULT_DIR_EXCLUSIONS, walkDirs} from "../path-utils";
35
36
 
@@ -80,6 +81,9 @@ export class PackageJsonParser extends Parser {
80
81
  /** The NodeRuntime of each project root, by package manager and root directory, for the parser's lifetime */
81
82
  private readonly runtimes = new Map<string, NodeRuntime>();
82
83
 
84
+ private readonly selectedRoots = new Map<string, string>();
85
+ private readonly selectionFailures = new Map<string, string>();
86
+
83
87
  /** Fields to copy from package.json that contain dependency maps */
84
88
  private static readonly DEPENDENCY_FIELDS = [
85
89
  'dependencies',
@@ -173,13 +177,15 @@ export class PackageJsonParser extends Parser {
173
177
  const runtime = this.nodeRuntime(dir, marker?.packageManager);
174
178
 
175
179
  // Attach the markers to the JSON document: every one gets the NodeRuntime of its project
176
- yield {
180
+ const out: Json.Document = {
177
181
  ...jsonDoc,
178
182
  markers: {
179
183
  ...jsonDoc.markers,
180
184
  markers: [...jsonDoc.markers.markers, ...(marker ? [marker] : []), runtime]
181
185
  }
182
186
  };
187
+ const failure = this.selectionFailures.get(dir);
188
+ yield failure === undefined ? out : markupWarn(out, failure);
183
189
  }
184
190
  }
185
191
 
@@ -190,7 +196,8 @@ export class PackageJsonParser extends Parser {
190
196
  */
191
197
  private nodeRuntime(dir: string, packageManager?: PackageManager): NodeRuntime {
192
198
  const absoluteDir = path.resolve(this.relativeTo ?? '', dir);
193
- const root = packageManager === undefined ? absoluteDir : this.projectRoot(absoluteDir, packageManager);
199
+ const root = packageManager === undefined ? absoluteDir :
200
+ this.selectedRoots.get(absoluteDir) ?? this.projectRoot(absoluteDir, packageManager);
194
201
  const key = `${packageManager ?? ''}:${root}`;
195
202
  let runtime = this.runtimes.get(key);
196
203
  if (!runtime) {
@@ -222,6 +229,8 @@ export class PackageJsonParser extends Parser {
222
229
  * Creates a NodeResolutionResult marker from the package.json content and optional lock file.
223
230
  */
224
231
  private async createMarker(input: ParserInput, dir: string): Promise<NodeResolutionResult | null> {
232
+ this.selectionFailures.delete(dir);
233
+ this.selectedRoots.delete(path.resolve(this.relativeTo ?? "", dir));
225
234
  try {
226
235
  const content = parserInputRead(input);
227
236
  const packageJson = JSON.parse(content);
@@ -241,7 +250,7 @@ export class PackageJsonParser extends Parser {
241
250
  const absoluteDir = this.relativeTo && !path.isAbsolute(dir)
242
251
  ? path.resolve(this.relativeTo, dir)
243
252
  : dir;
244
- const lockResult = await this.tryReadLockFileWithWalkUp(absoluteDir, this.relativeTo);
253
+ const lockResult = await this.tryReadLockFileWithWalkUp(absoluteDir, this.relativeTo, packageJson);
245
254
  lockContent = lockResult?.content;
246
255
  packageManager = lockResult?.packageManager;
247
256
  }
@@ -285,6 +294,7 @@ export class PackageJsonParser extends Parser {
285
294
  npmrcConfigs.length > 0 ? npmrcConfigs : undefined
286
295
  );
287
296
  } catch (error) {
297
+ if (error instanceof PackageManagerSelectionError) this.selectionFailures.set(dir, error.message);
288
298
  console.warn(`Failed to create NodeResolutionResult marker: ${error}`);
289
299
  return null;
290
300
  }
@@ -464,8 +474,16 @@ export class PackageJsonParser extends Parser {
464
474
  */
465
475
  private async tryReadLockFileWithWalkUp(
466
476
  startDir: string,
467
- rootDir?: string
477
+ rootDir?: string,
478
+ manifest?: unknown
468
479
  ): Promise<{ content: PackageLockContent; packageManager: PackageManager } | undefined> {
480
+ const selected = selectPackageManager(startDir, rootDir, manifest);
481
+ if (selected) {
482
+ this.selectedRoots.set(path.resolve(startDir), selected.root);
483
+ if (selected.lockFile) return this.tryReadLockFile(selected.root, selected.packageManager);
484
+ const installed = await this.walkNodeModules(selected.root);
485
+ return {content: installed ?? {lockfileVersion: 0, packages: {}}, packageManager: selected.packageManager};
486
+ }
469
487
  // Normalize paths for comparison
470
488
  const normalizedRoot = rootDir ? path.resolve(rootDir) : undefined;
471
489
 
@@ -484,16 +502,6 @@ export class PackageJsonParser extends Parser {
484
502
  currentDir = parentDir;
485
503
  }
486
504
 
487
- // A lock file names the package manager, wherever it is on the way up. An installed
488
- // workspace member has node_modules of its own and no lock: its workspace's lock, above it,
489
- // says which package manager installed them.
490
- for (const dir of dirs) {
491
- const result = await this.tryReadLockFile(dir);
492
- if (result) {
493
- return result;
494
- }
495
- }
496
-
497
505
  // Fallback: node_modules without a lock file anywhere above (e.g., symlinked from another
498
506
  // workspace). Walk them for resolved dependency information, and assume npm.
499
507
  for (const dir of dirs) {
@@ -512,9 +520,10 @@ export class PackageJsonParser extends Parser {
512
520
  *
513
521
  * @returns Object with parsed lock file content and detected package manager, or undefined if no lock file found
514
522
  */
515
- private async tryReadLockFile(dir: string): Promise<{ content: PackageLockContent; packageManager: PackageManager } | undefined> {
523
+ private async tryReadLockFile(dir: string, selected?: PackageManager): Promise<{ content: PackageLockContent; packageManager: PackageManager } | undefined> {
516
524
  // Use shared lock file detection config (first match wins based on priority)
517
525
  for (const config of getLockFileDetectionConfig()) {
526
+ if (selected !== undefined && config.filename !== getLockFileName(selected)) continue;
518
527
  const lockPath = path.join(dir, config.filename);
519
528
  if (!fs.existsSync(lockPath)) {
520
529
  continue;
@@ -36,6 +36,8 @@ import * as os from "os";
36
36
  import {spawnSync} from "child_process";
37
37
  import {isDeepStrictEqual} from "util";
38
38
  import * as YAML from "yaml";
39
+ import * as semver from "semver";
40
+ import picomatch from "picomatch";
39
41
 
40
42
  /**
41
43
  * Configuration for each package manager.
@@ -193,30 +195,134 @@ interface InstallOptions {
193
195
  env?: Record<string, string>;
194
196
  }
195
197
 
198
+ /** A conflicting declaration must not produce a resolution graph from another manager's lock. */
199
+ export class PackageManagerSelectionError extends Error {
200
+ }
201
+
202
+ export interface PackageManagerSelection {
203
+ readonly packageManager: PackageManager;
204
+ readonly root: string;
205
+ readonly lockFile?: string;
206
+ }
207
+
208
+ function declaredPackageManager(manifest: unknown): PackageManager | undefined {
209
+ if (!manifest || typeof manifest !== "object") return undefined;
210
+ const value = (manifest as {packageManager?: unknown}).packageManager;
211
+ if (typeof value !== "string") return undefined;
212
+ const match = /^(npm|pnpm|bun|yarn)@(.+)$/.exec(value);
213
+ const version = match && semver.valid(match[2].split("+", 1)[0]);
214
+ if (!match || !version) return undefined;
215
+ switch (match[1]) {
216
+ case "npm": return PackageManager.Npm;
217
+ case "pnpm": return PackageManager.Pnpm;
218
+ case "bun": return PackageManager.Bun;
219
+ case "yarn": return semver.major(version) === 1 ? PackageManager.YarnClassic : PackageManager.YarnBerry;
220
+ default: return undefined;
221
+ }
222
+ }
223
+
224
+ function isWorkspaceMember(root: string, member: string, manifest: unknown): boolean {
225
+ let patterns: unknown = manifest && typeof manifest === "object" ?
226
+ (manifest as {workspaces?: unknown}).workspaces : undefined;
227
+ if (patterns && !Array.isArray(patterns) && typeof patterns === "object") {
228
+ patterns = (patterns as {packages?: unknown}).packages;
229
+ }
230
+ if (!Array.isArray(patterns)) {
231
+ try { patterns = YAML.parse(fs.readFileSync(path.join(root, "pnpm-workspace.yaml"), "utf8"))?.packages; }
232
+ catch { return false; }
233
+ }
234
+ if (!Array.isArray(patterns) || !patterns.every(p => typeof p === "string")) return false;
235
+ const relative = path.relative(root, member).split(path.sep).join("/");
236
+ const include = patterns.filter(p => !p.startsWith("!"));
237
+ const exclude = patterns.filter(p => p.startsWith("!")).map(p => p.slice(1));
238
+ return include.length > 0 && picomatch(include)(relative) &&
239
+ (exclude.length === 0 || !picomatch(exclude)(relative));
240
+ }
241
+
196
242
  /**
197
- * Detects the package manager used in a directory by checking for lock files.
198
- *
199
- * @param dir The directory to check
200
- * @returns The detected package manager, or undefined if none found
243
+ * Select a lock and its manager together. The nearest supported pinned declaration takes precedence over lock
244
+ * filename order, including when a workspace member inherits it. An explicit parser boundary limits the walk.
245
+ * The supplied manifest is the parser input at startDir, which may differ from the file on disk.
201
246
  */
202
- export function detectPackageManager(dir: string): PackageManager | undefined {
203
- for (const config of LOCK_FILE_DETECTION) {
204
- const lockPath = path.join(dir, config.filename);
205
- if (fs.existsSync(lockPath)) {
206
- if (typeof config.packageManager === 'function') {
207
- try {
208
- const content = fs.readFileSync(lockPath, 'utf-8');
209
- return config.packageManager(content);
210
- } catch {
211
- continue;
247
+ export function selectPackageManager(startDir: string, rootDir?: string, manifest?: unknown): PackageManagerSelection | undefined {
248
+ const dirs: string[] = [];
249
+ const stop = rootDir === undefined ? undefined : path.resolve(rootDir);
250
+ for (let dir = path.resolve(startDir); ; dir = path.dirname(dir)) {
251
+ dirs.push(dir);
252
+ if (dir === stop || path.dirname(dir) === dir) break;
253
+ }
254
+ const manifests = new Map<string, unknown>();
255
+ for (const dir of dirs) {
256
+ if (dir === dirs[0] && manifest !== undefined) manifests.set(dir, manifest);
257
+ else {
258
+ try { manifests.set(dir, JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"))); }
259
+ catch { /* A lock can still identify a project without a readable manifest. */ }
260
+ }
261
+ }
262
+ let declared: {manager: PackageManager, root: string} | undefined;
263
+ for (const dir of dirs) {
264
+ const pkg = manifests.get(dir);
265
+ const manager = declaredPackageManager(pkg);
266
+ if (manager !== undefined && (dir === dirs[0] || isWorkspaceMember(dir, dirs[0], pkg))) {
267
+ declared = {manager, root: dir};
268
+ break;
269
+ }
270
+ }
271
+ if (declared) {
272
+ // A nested declaration defines its own project unless a compatible workspace actually contains it.
273
+ let boundary = dirs.indexOf(declared.root);
274
+ for (let i = boundary + 1; i < dirs.length; i++) {
275
+ const pkg = manifests.get(dirs[i]);
276
+ const manager = declaredPackageManager(pkg);
277
+ if (manager !== undefined && manager !== declared.manager) break;
278
+ if (isWorkspaceMember(dirs[i], declared.root, pkg)) boundary = i;
279
+ }
280
+ const projectDirs = dirs.slice(0, boundary + 1);
281
+ const filename = getLockFileName(declared.manager);
282
+ for (const dir of projectDirs) {
283
+ const lockFile = path.join(dir, filename);
284
+ if (!fs.existsSync(lockFile)) continue;
285
+ if (filename === "yarn.lock") {
286
+ const actual = isYarnBerryLockFile(fs.readFileSync(lockFile, "utf8")) ?
287
+ PackageManager.YarnBerry : PackageManager.YarnClassic;
288
+ if (actual !== declared.manager) {
289
+ throw new PackageManagerSelectionError(
290
+ `packageManager selects ${declared.manager}, but ${lockFile} contains ${actual}`);
212
291
  }
213
292
  }
214
- return config.packageManager;
293
+ return {packageManager: declared.manager, root: dir, lockFile};
294
+ }
295
+ const foreign = projectDirs.flatMap(dir => LOCK_FILE_DETECTION
296
+ .map(config => path.join(dir, config.filename)).filter(file => fs.existsSync(file)));
297
+ if (foreign.length) {
298
+ throw new PackageManagerSelectionError(
299
+ `packageManager selects ${declared.manager}, but ${filename} is missing; other lock files: ${foreign.join(", ")}`);
300
+ }
301
+ return {packageManager: declared.manager, root: declared.root};
302
+ }
303
+ // Without a recognized declaration, retain the existing nearest-lock/filename precedence.
304
+ for (const dir of dirs) {
305
+ for (const config of LOCK_FILE_DETECTION) {
306
+ const lockFile = path.join(dir, config.filename);
307
+ if (!fs.existsSync(lockFile)) continue;
308
+ if (typeof config.packageManager !== "function") {
309
+ return {packageManager: config.packageManager, root: dir, lockFile};
310
+ }
311
+ try {
312
+ return {packageManager: config.packageManager(fs.readFileSync(lockFile, "utf8")), root: dir, lockFile};
313
+ } catch {
314
+ return {packageManager: PackageManager.YarnClassic, root: dir, lockFile};
315
+ }
215
316
  }
216
317
  }
217
318
  return undefined;
218
319
  }
219
320
 
321
+ /** Detect the manager selected by the declaration and locks in this directory. */
322
+ export function detectPackageManager(dir: string): PackageManager | undefined {
323
+ return selectPackageManager(dir, dir)?.packageManager;
324
+ }
325
+
220
326
  /**
221
327
  * Gets the lock file detection configuration.
222
328
  * Returns the array of lock file configs in priority order.
@@ -638,16 +638,7 @@ export class JavaScriptParserVisitor {
638
638
  // in case of `J.Unknown` its source will already contain any `;`
639
639
  return this.rightPadded(j, emptySpace, emptyMarkers);
640
640
  }
641
- let last: ts.Node | undefined = n.getChildAt(n.getChildCount(this.sourceFile) - 1, this.sourceFile)
642
- if (last && (last.kind === ts.SyntaxKind.ExpressionStatement || last.kind == ts.SyntaxKind.DoStatement) && n.kind === ts.SyntaxKind.LabeledStatement) {
643
- last = last.getLastToken(this.sourceFile);
644
- }
645
- return this.rightPadded(j, this.semicolonPrefix(n), (_ => {
646
- return last?.kind === ts.SyntaxKind.SemicolonToken ? markers({
647
- kind: J.Markers.Semicolon,
648
- id: randomId()
649
- }) : emptyMarkers;
650
- })?.(n));
641
+ return this.semicolonPadded(j, n);
651
642
  });
652
643
  }
653
644
 
@@ -843,12 +834,26 @@ export class JavaScriptParserVisitor {
843
834
  };
844
835
  }
845
836
 
846
- private semicolonPrefix = (node: ts.Node) => {
847
- let last: ts.Node | undefined = node.getChildren(this.sourceFile).slice(-1)[0];
848
- if (last && (last.kind === ts.SyntaxKind.ExpressionStatement || last.kind == ts.SyntaxKind.DoStatement)) {
849
- last = last.getLastToken(this.sourceFile);
837
+ private trailingSemicolon(node: ts.Node): ts.Node | undefined {
838
+ while (ts.isLabeledStatement(node)) {
839
+ node = node.statement;
850
840
  }
851
- return last?.kind === ts.SyntaxKind.SemicolonToken ? this.prefix(last) : emptySpace;
841
+ const last = node.getChildAt(node.getChildCount(this.sourceFile) - 1, this.sourceFile);
842
+ return last?.kind === ts.SyntaxKind.SemicolonToken ? last : undefined;
843
+ }
844
+
845
+ private semicolonPrefix = (node: ts.Node) => {
846
+ const semicolon = this.trailingSemicolon(node);
847
+ return semicolon ? this.prefix(semicolon) : emptySpace;
848
+ }
849
+
850
+ private semicolonPadded<T extends J>(element: T, node: ts.Statement): J.RightPadded<T> {
851
+ const semicolon = this.trailingSemicolon(node);
852
+ return this.rightPadded(
853
+ element,
854
+ semicolon ? this.prefix(semicolon) : emptySpace,
855
+ semicolon ? markers({kind: J.Markers.Semicolon, id: randomId()}) : emptyMarkers
856
+ );
852
857
  }
853
858
 
854
859
  private keywordPrefix = (token: ts.PunctuationSyntaxKind, findSibling: (node: ts.Node) => ts.Node | undefined) => (node: ts.Node): J.Space => {
@@ -1542,14 +1547,7 @@ export class JavaScriptParserVisitor {
1542
1547
  prefix: this.prefix(node),
1543
1548
  markers: emptyMarkers,
1544
1549
  static: this.rightPadded(true, this.prefix(this.findChildNode(node.body, ts.SyntaxKind.OpenBraceToken)!), emptyMarkers),
1545
- statements: node.body.statements.map(ce => this.rightPadded(
1546
- this.convert(ce),
1547
- ce.getLastToken()?.kind === ts.SyntaxKind.SemicolonToken ? this.prefix(ce.getLastToken()!) : emptySpace,
1548
- ce.getLastToken()?.kind === ts.SyntaxKind.SemicolonToken ? markers({
1549
- kind: J.Markers.Semicolon,
1550
- id: randomId()
1551
- }) : emptyMarkers
1552
- )),
1550
+ statements: this.semicolonPaddedStatementList(node.body.statements),
1553
1551
  end: this.prefix(node.getLastToken()!)
1554
1552
  };
1555
1553
  }
@@ -3129,8 +3127,6 @@ export class JavaScriptParserVisitor {
3129
3127
  }
3130
3128
 
3131
3129
  visitIfStatement(node: ts.IfStatement): J.If {
3132
- const semicolonAfterThen = (node.thenStatement.getChildAt(node.thenStatement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken);
3133
- const semicolonAfterElse = (node.elseStatement?.getChildAt(node.elseStatement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken);
3134
3130
  return {
3135
3131
  kind: J.Kind.If,
3136
3132
  id: randomId(),
@@ -3143,21 +3139,13 @@ export class JavaScriptParserVisitor {
3143
3139
  markers: emptyMarkers,
3144
3140
  tree: this.rightPadded(this.visit(node.expression), this.suffix(node.expression))
3145
3141
  },
3146
- thenPart: this.rightPadded(
3147
- this.convert(node.thenStatement),
3148
- semicolonAfterThen ? this.prefix(node.thenStatement.getLastToken()!) : emptySpace,
3149
- semicolonAfterThen ? markers({kind: J.Markers.Semicolon, id: randomId()}) : emptyMarkers
3150
- ),
3142
+ thenPart: this.semicolonPadded(this.convert(node.thenStatement), node.thenStatement),
3151
3143
  elsePart: node.elseStatement && {
3152
3144
  kind: J.Kind.IfElse,
3153
3145
  id: randomId(),
3154
3146
  prefix: this.prefix(this.findChildNode(node, ts.SyntaxKind.ElseKeyword)!),
3155
3147
  markers: emptyMarkers,
3156
- body: this.rightPadded(
3157
- this.convert(node.elseStatement),
3158
- semicolonAfterElse ? this.prefix(node.elseStatement.getLastToken()!) : emptySpace,
3159
- semicolonAfterElse ? markers({kind: J.Markers.Semicolon, id: randomId()}) : emptyMarkers
3160
- )
3148
+ body: this.semicolonPadded(this.convert(node.elseStatement), node.elseStatement)
3161
3149
  }
3162
3150
  };
3163
3151
  }
@@ -3168,12 +3156,7 @@ export class JavaScriptParserVisitor {
3168
3156
  id: randomId(),
3169
3157
  prefix: this.prefix(node),
3170
3158
  markers: emptyMarkers,
3171
- body: this.rightPadded(this.visit(node.statement),
3172
- this.semicolonPrefix(node.statement),
3173
- node.statement.getChildAt(node.statement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken ? markers({
3174
- kind: J.Markers.Semicolon,
3175
- id: randomId()
3176
- }) : emptyMarkers),
3159
+ body: this.semicolonPadded(this.visit(node.statement), node.statement),
3177
3160
  whileCondition: this.leftPadded(
3178
3161
  this.prefix(this.findChildNode(node, ts.SyntaxKind.WhileKeyword)!),
3179
3162
  {
@@ -3200,14 +3183,7 @@ export class JavaScriptParserVisitor {
3200
3183
  markers: emptyMarkers,
3201
3184
  tree: this.rightPadded(this.visit(node.expression), this.suffix(node.expression))
3202
3185
  },
3203
- body: this.rightPadded(
3204
- this.convert(node.statement),
3205
- this.semicolonPrefix(node.statement),
3206
- node.statement.getChildAt(node.statement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken ? markers({
3207
- kind: J.Markers.Semicolon,
3208
- id: randomId()
3209
- }) : emptyMarkers
3210
- ),
3186
+ body: this.semicolonPadded(this.convert(node.statement), node.statement),
3211
3187
  };
3212
3188
  }
3213
3189
 
@@ -3248,14 +3224,7 @@ export class JavaScriptParserVisitor {
3248
3224
  }, this.suffix(node.incrementor)) :
3249
3225
  this.rightPadded(this.newEmpty(this.prefix(this.findChildNode(node, ts.SyntaxKind.CloseParenToken)!)), emptySpace)]
3250
3226
  },
3251
- body: this.rightPadded(
3252
- this.convert(node.statement),
3253
- this.semicolonPrefix(node.statement),
3254
- node.statement.getChildAt(node.statement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken ? markers({
3255
- kind: J.Markers.Semicolon,
3256
- id: randomId()
3257
- }) : emptyMarkers
3258
- )
3227
+ body: this.semicolonPadded(this.convert(node.statement), node.statement)
3259
3228
  };
3260
3229
  }
3261
3230
 
@@ -3286,14 +3255,7 @@ export class JavaScriptParserVisitor {
3286
3255
  })(),
3287
3256
  iterable: this.rightPadded(this.visit(node.expression), this.suffix(node.expression))
3288
3257
  },
3289
- body: this.rightPadded(
3290
- this.convert(node.statement),
3291
- this.semicolonPrefix(node.statement),
3292
- node.statement.getChildAt(node.statement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken ? markers({
3293
- kind: J.Markers.Semicolon,
3294
- id: randomId()
3295
- }) : emptyMarkers
3296
- )
3258
+ body: this.semicolonPadded(this.convert(node.statement), node.statement)
3297
3259
  };
3298
3260
  }
3299
3261
 
@@ -3366,14 +3328,7 @@ export class JavaScriptParserVisitor {
3366
3328
  })(),
3367
3329
  iterable: this.rightPadded(this.visit(node.expression), this.suffix(node.expression))
3368
3330
  },
3369
- body: this.rightPadded(
3370
- this.convert(node.statement),
3371
- this.semicolonPrefix(node.statement),
3372
- node.statement.getChildAt(node.statement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken ? markers({
3373
- kind: J.Markers.Semicolon,
3374
- id: randomId()
3375
- }) : emptyMarkers
3376
- )
3331
+ body: this.semicolonPadded(this.convert(node.statement), node.statement)
3377
3332
  }
3378
3333
  };
3379
3334
  }
@@ -3421,14 +3376,7 @@ export class JavaScriptParserVisitor {
3421
3376
  markers: emptyMarkers,
3422
3377
  tree: this.rightPadded(this.visit(node.expression), this.suffix(node.expression))
3423
3378
  },
3424
- body: this.rightPadded(
3425
- this.convert(node.statement),
3426
- this.semicolonPrefix(node.statement),
3427
- node.statement.getChildAt(node.statement.getChildCount() - 1)?.kind === ts.SyntaxKind.SemicolonToken ? markers({
3428
- kind: J.Markers.Semicolon,
3429
- id: randomId()
3430
- }) : emptyMarkers
3431
- ),
3379
+ body: this.semicolonPadded(this.convert(node.statement), node.statement),
3432
3380
  };
3433
3381
  }
3434
3382
 
@@ -1958,9 +1958,8 @@ export class JavaScriptPrinter extends JavaScriptVisitor<PrintOutputCapture> {
1958
1958
 
1959
1959
  p.append(before);
1960
1960
  await this.visitRightPaddedLocal(container.elements, suffixBetween, p);
1961
- await this.afterSyntaxMarkers(container.markers, p);
1962
-
1963
1961
  p.append(after === null ? "" : after);
1962
+ await this.afterSyntaxMarkers(container.markers, p);
1964
1963
  }
1965
1964
 
1966
1965
  override async visitMarker<M extends Marker>(marker: M, p: PrintOutputCapture): Promise<M> {
@@ -24,9 +24,14 @@ import {JavaScriptVisitor} from "../visitor";
24
24
  import {MethodMatcher} from "../method-matcher";
25
25
  import {usesMethod} from "../preconditions";
26
26
  import {maybeBind, maybeUnbind} from "../binding";
27
- import {moduleScopeBindings} from "../add-import";
27
+ import {ImportStyle, moduleScopeBindings} from "../add-import";
28
28
  import {compilationUnitOf, scopeOf} from "../scope";
29
29
 
30
+ // A declarative recipe spells the style by name, since `ImportStyle`'s values are numbers. `style` chooses
31
+ // only between an import and a `require`, and the member chooses the shape, so the other `ImportStyle`
32
+ // names would add the same import as `ES6Named`.
33
+ const IMPORT_STYLES = ["ES6Named", "CommonJS"] as const;
34
+
30
35
  /**
31
36
  * Moves calls matching a method pattern onto a member imported from a module, such as `jest.fn()`
32
37
  * to `vi.fn()` with `import {vi} from "vitest"`.
@@ -38,7 +43,7 @@ export class ChangeMethodTargetToImport extends Recipe {
38
43
  readonly name = "org.openrewrite.javascript.change-method-target-to-import";
39
44
  readonly displayName = "Change method target to an import";
40
45
  readonly description = "Changes the target of calls matching a method pattern to a member imported from a module, " +
41
- "adding the import. A CommonJS file changes only where it already requires the target, and an AMD module not at all.";
46
+ "adding the import. An AMD module does not change.";
42
47
 
43
48
  @Option({
44
49
  displayName: "Method pattern",
@@ -77,20 +82,35 @@ export class ChangeMethodTargetToImport extends Recipe {
77
82
  })
78
83
  matchOverrides?: boolean;
79
84
 
85
+ @Option({
86
+ displayName: "Import style",
87
+ description: "`ES6Named` adds an ES import and `CommonJS` a `require`. " +
88
+ "Unset, a CommonJS file gets a `require`, and an ES module or plain script an ES import.",
89
+ example: "ES6Named",
90
+ valid: [...IMPORT_STYLES],
91
+ required: false
92
+ })
93
+ importStyle?: typeof IMPORT_STYLES[number];
94
+
80
95
  constructor(options?: {
81
96
  methodPattern?: string;
82
97
  targetModule?: string;
83
98
  targetMember?: string;
84
99
  targetType?: string;
85
100
  matchOverrides?: boolean;
101
+ importStyle?: typeof IMPORT_STYLES[number];
86
102
  }) {
87
103
  super(options);
104
+ if (this.importStyle != null && !IMPORT_STYLES.includes(this.importStyle)) {
105
+ throw new Error(`Unknown import style \`${this.importStyle}\`, expected one of ${IMPORT_STYLES.join(", ")}.`);
106
+ }
88
107
  }
89
108
 
90
109
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
91
110
  const matcher = new MethodMatcher(this.methodPattern, this.matchOverrides);
92
111
  const module = this.targetModule;
93
112
  const member = this.targetMember;
113
+ const style = this.importStyle == null ? undefined : ImportStyle[this.importStyle];
94
114
  // Named after the specifier, as the parser names a module object.
95
115
  const moduleObject = classNamed(module);
96
116
  const memberType = this.targetType ? classNamed(this.targetType) : Type.unknownType as Type.FullyQualified;
@@ -119,7 +139,7 @@ export class ChangeMethodTargetToImport extends Recipe {
119
139
  return m;
120
140
  }
121
141
 
122
- const name = maybeBind(this, {module, member, onlyIfReferenced: false});
142
+ const name = maybeBind(this, {module, member, onlyIfReferenced: false, style});
123
143
  if (name === undefined) {
124
144
  return m;
125
145
  }
@@ -31,6 +31,14 @@ export interface AddDependencyOptions {
31
31
  packageName: string;
32
32
  version: string;
33
33
  scope?: NpmDependencyScope;
34
+ /** Add only to a `package.json` that declared a package matching one of these globs before the cycle's edits. */
35
+ onlyIfDeclaring?: string[];
36
+ /**
37
+ * Add only to a `package.json` that resolves every `name@range` entry, e.g. `react@>=16.9.0 <18`: by the version
38
+ * its lock resolves, else when the declared constraint admits nothing outside the range. An undeclared package is
39
+ * taken from the nearest enclosing `package.json` that declares it.
40
+ */
41
+ onlyIfResolving?: string[];
34
42
  }
35
43
 
36
44
  /**
@@ -71,6 +79,21 @@ export function upgradeDependencyVersion(options: UpgradeDependencyVersionOption
71
79
  return prepareJavaRecipe("org.openrewrite.javascript.UpgradeDependencyVersion", options);
72
80
  }
73
81
 
82
+ export interface UpgradeDependencyVersionsOptions {
83
+ /** Nonempty package-name glob map. Overlapping patterns must specify the same target constraint. */
84
+ versions: Record<string, string>;
85
+ /** Verify the upgraded manifest before recovering from stale npm lock peer conflicts. Defaults to false. */
86
+ reconcileNpmPeerDependencies?: boolean;
87
+ }
88
+
89
+ /**
90
+ * Upgrade matching npm dependencies together and regenerate the lock file once.
91
+ * Delegates to `org.openrewrite.javascript.UpgradeDependencyVersions` via RPC.
92
+ */
93
+ export function upgradeDependencyVersions(options: UpgradeDependencyVersionsOptions): Promise<Recipe> {
94
+ return prepareJavaRecipe("org.openrewrite.javascript.UpgradeDependencyVersions", options);
95
+ }
96
+
74
97
  export interface ChangeDependencyOptions {
75
98
  oldPackageName: string;
76
99
  newPackageName: string;
@@ -17,8 +17,8 @@
17
17
  import {Recipe} from "../../recipe";
18
18
  import {produceAsync, TreeVisitor} from "../../visitor";
19
19
  import {ExecutionContext} from "../../execution";
20
- import {JavaScriptVisitor, JS} from "../index";
21
- import {J} from "../../java";
20
+ import {JavaScriptVisitor, JS, moduleExportName} from "../index";
21
+ import {isIdentifier, J} from "../../java";
22
22
  import {create as produce, Draft} from "mutative";
23
23
  import {SpacesStyle, styleFromSourceFile, StyleKind} from "../style";
24
24
 
@@ -121,8 +121,8 @@ export class OrderImports extends Recipe {
121
121
 
122
122
  // Namespace imports: import * as foo from 'module'
123
123
  if (import_.importClause.namedBindings?.kind === JS.Kind.Alias) {
124
- const alias = import_.importClause.namedBindings as JS.Alias;
125
- if (alias.propertyName.element.simpleName === "*") {
124
+ const propertyName = (import_.importClause.namedBindings as JS.Alias).propertyName.element;
125
+ if (isIdentifier(propertyName) && propertyName.simpleName === "*") {
126
126
  return ImportCategory.Namespace;
127
127
  }
128
128
  }
@@ -232,7 +232,7 @@ export class OrderImports extends Recipe {
232
232
  private getSpecifierSortKey(specifier: JS.ImportSpecifier): string {
233
233
  if (specifier.specifier.kind === JS.Kind.Alias) {
234
234
  // import { foo as bar } - sort by 'foo'
235
- return (specifier.specifier as JS.Alias).propertyName.element.simpleName;
235
+ return moduleExportName((specifier.specifier as JS.Alias).propertyName.element);
236
236
  } else if (specifier.specifier.kind === J.Kind.Identifier) {
237
237
  // import { foo } - sort by 'foo'
238
238
  return (specifier.specifier as J.Identifier).simpleName;