@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
@@ -44,7 +44,7 @@ class RewriteRuleImpl implements RewriteRule {
44
44
 
45
45
  for (const pattern of this.before) {
46
46
  // Pass cursor to pattern.match() for context-aware capture constraints
47
- const match = await pattern.match(node, cursor);
47
+ const match = await pattern.match(node, cursor, {debug: options?.debug});
48
48
  if (match) {
49
49
  // Evaluate postMatch after structural match succeeds
50
50
  if (this.postMatch) {
@@ -123,6 +123,10 @@ class RewriteRuleImpl implements RewriteRule {
123
123
  /**
124
124
  * Creates a replacement rule using a capture context and configuration.
125
125
  *
126
+ * To see why a rule does not apply where you expected it to, call `tryOn(cursor, node, {debug: true})`,
127
+ * or set PATTERN_DEBUG=true for every pattern. Each match attempt then prints why it matched or not,
128
+ * as `PatternOptions.debug` describes.
129
+ *
126
130
  * @param builderFn Function that takes a capture context and returns before/after configuration
127
131
  * @returns A replacement rule that can be applied to AST nodes
128
132
  *
@@ -428,7 +428,7 @@ export class Template {
428
428
  }
429
429
  }
430
430
 
431
- const expression = opensWithBrace(this.templateParts) && replacedByObjectLiteral(tree, cursor);
431
+ const expression = opensWithBrace(this.templateParts) && await replacedByObjectLiteral(tree, cursor);
432
432
  const ast = await this.getTemplateTree(expression, normalizedValues);
433
433
 
434
434
  // Delegate to TemplateEngine for placeholder substitution and application
@@ -366,47 +366,51 @@ export interface PatternOptions {
366
366
  lenientTypeMatching?: boolean;
367
367
 
368
368
  /**
369
- * Enable debug logging for this pattern.
370
- * When enabled, all match attempts will log detailed information to stderr,
371
- * including the AST path traversed, mismatches encountered, and captured values.
372
- *
373
- * Can be overridden at the match() call level.
374
- * Global debug can be enabled via PATTERN_DEBUG=true environment variable.
375
- *
376
- * Precedence: match() call > pattern configure() > PATTERN_DEBUG env var
377
- *
378
- * @default undefined (inherits from environment or match() call)
369
+ * Prints to stderr why each match attempt of this pattern matched or not, as {@link DebugSetting} describes.
370
+ * A match() call's own `debug` overrides it, and it overrides the PATTERN_DEBUG=true environment variable.
379
371
  *
380
372
  * @example
381
373
  * ```typescript
382
- * // Pattern-level debug
383
- * const pat = pattern({ debug: true })`console.log(${value})`;
374
+ * // Every attempt
375
+ * const pat = pattern({debug: true})`console.log(${value})`;
384
376
  *
385
- * // Disable debug for a noisy pattern when global debug is on
386
- * const noisyPat = pattern({ debug: false })`import ${x} from ${y}`;
377
+ * // Only attempts on calls named `log`, where a visitor matches the pattern against every call
378
+ * const onLog = (tree: J) => isMethodInvocation(tree) && tree.name.simpleName === 'log';
379
+ * const logs = pattern({debug: onLog})`console.log(${value})`;
380
+ *
381
+ * // No attempt, even with PATTERN_DEBUG=true
382
+ * const quiet = pattern({debug: false})`import ${x} from ${y}`;
387
383
  * ```
388
384
  */
389
- debug?: boolean;
385
+ debug?: DebugSetting;
390
386
  }
391
387
 
388
+ /**
389
+ * Whether a match attempt prints debug output. `true` prints every attempt and `false` none, and a
390
+ * predicate decides per attempt from the node, its cursor and how the attempt ended. A failed attempt
391
+ * prints the pattern and the code with the mismatch marked and says why they differ. A successful one
392
+ * marks the captured code. Both name where the code is and where match() was called.
393
+ */
394
+ export type DebugSetting = boolean | ((tree: J, cursor: Cursor, attempt: MatchAttemptResult) => boolean);
395
+
392
396
  /**
393
397
  * Options for individual match() calls.
394
398
  */
395
399
  export interface MatchOptions {
396
400
  /**
397
- * Enable debug logging for this specific match() call.
398
- * Overrides pattern-level debug setting and global PATTERN_DEBUG env var.
401
+ * Prints to stderr why this call matched or not, as {@link DebugSetting} describes.
402
+ * Overrides the pattern's own `debug` and the PATTERN_DEBUG=true environment variable.
399
403
  *
400
404
  * @example
401
405
  * ```typescript
402
406
  * // Debug just this call
403
- * const match = await pattern.match(node, cursor, { debug: true });
407
+ * const match = await pattern.match(node, cursor, {debug: true});
404
408
  *
405
409
  * // Disable debug for this call even if pattern or global debug is on
406
- * const match = await pattern.match(node, cursor, { debug: false });
410
+ * const match = await pattern.match(node, cursor, {debug: false});
407
411
  * ```
408
412
  */
409
- debug?: boolean;
413
+ debug?: DebugSetting;
410
414
  }
411
415
 
412
416
  /**
@@ -560,6 +564,9 @@ export interface TryOnOptions {
560
564
 
561
565
  /** As {@link ApplyOptions.bindings}, for a caller that resolves the modules some other way. */
562
566
  bindings?: Record<string, string>;
567
+
568
+ /** Prints why each of the rule's patterns matched or not, as {@link PatternOptions.debug} describes. */
569
+ debug?: DebugSetting;
563
570
  }
564
571
 
565
572
  /**
@@ -729,7 +736,6 @@ export interface RewriteConfig {
729
736
 
730
737
  /**
731
738
  * Options for debugging pattern matching.
732
- * Used in Layer 1 (Core Instrumentation) to control debug output.
733
739
  */
734
740
  export interface DebugOptions {
735
741
  /**
@@ -750,7 +756,6 @@ export interface DebugOptions {
750
756
 
751
757
  /**
752
758
  * A single debug log entry collected during pattern matching.
753
- * Part of Layer 1 (Core Instrumentation).
754
759
  */
755
760
  export interface DebugLogEntry {
756
761
  /**
@@ -763,11 +768,6 @@ export interface DebugLogEntry {
763
768
  */
764
769
  scope: 'matching' | 'comparison' | 'constraint';
765
770
 
766
- /**
767
- * Path in the AST where this log entry was generated.
768
- */
769
- path: string[];
770
-
771
771
  /**
772
772
  * Human-readable message.
773
773
  */
@@ -781,7 +781,6 @@ export interface DebugLogEntry {
781
781
 
782
782
  /**
783
783
  * Detailed explanation of why a pattern failed to match.
784
- * Built by Layer 1 (Core Instrumentation) and exposed by Layer 2 (API).
785
784
  */
786
785
  export interface MatchExplanation {
787
786
  /**
@@ -789,11 +788,6 @@ export interface MatchExplanation {
789
788
  */
790
789
  reason: 'structural-mismatch' | 'constraint-failed' | 'type-mismatch' | 'kind-mismatch' | 'value-mismatch' | 'array-length-mismatch';
791
790
 
792
- /**
793
- * Path in the AST where the failure occurred (e.g., ['select', 'name']).
794
- */
795
- path: string[];
796
-
797
791
  /**
798
792
  * Human-readable description of what was expected.
799
793
  */
@@ -804,6 +798,12 @@ export interface MatchExplanation {
804
798
  */
805
799
  actual: string;
806
800
 
801
+ /** The pattern node where the pattern and the source differ, which debug output marks. */
802
+ patternElement?: J | J.Container<J>;
803
+
804
+ /** The source node where the pattern and the source differ, which debug output marks. */
805
+ targetElement?: J | J.Container<J>;
806
+
807
807
  /**
808
808
  * For constraint failures, details about which constraints failed.
809
809
  */
@@ -845,7 +845,6 @@ export interface MatchResult {
845
845
 
846
846
  /**
847
847
  * Result of a pattern match attempt with debug information.
848
- * Part of Layer 2 (Public API).
849
848
  */
850
849
  export interface MatchAttemptResult {
851
850
  /**
@@ -864,8 +863,12 @@ export interface MatchAttemptResult {
864
863
  */
865
864
  explanation?: MatchExplanation;
866
865
 
867
- /**
868
- * Debug log entries collected during matching (if debug was enabled).
869
- */
866
+ /** An entry for each capture constraint evaluated during matching, which `DebugOptions` can turn off. */
870
867
  debugLog?: DebugLogEntry[];
868
+
869
+ /** Where the matched code starts in its source file, where the cursor leads to one. */
870
+ location?: { sourcePath: string, line?: number, column?: number };
871
+
872
+ /** What debug output prints for this attempt, without colours. Set by {@link Pattern.matchWithExplanation}. */
873
+ report?: string;
871
874
  }
@@ -13,8 +13,7 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import {Cursor} from '../..';
17
- import {J, NameTree} from '../../java';
16
+ import {J} from '../../java';
18
17
  import {JS} from '../index';
19
18
  import {JavaScriptVisitor} from '../visitor';
20
19
  import {Marker, Markers} from '../../markers';
@@ -130,14 +129,7 @@ export function generateCacheKey(
130
129
  ].join('::');
131
130
  }
132
131
 
133
- abstract class IdVisitor extends JavaScriptVisitor<any> {
134
- // `JavaVisitor.visitTypeName` is a no-op stub, which leaves annotation names unreachable
135
- protected override async visitTypeName<N extends NameTree>(nameTree: N, p: any): Promise<N> {
136
- return (await this.visit(nameTree, p)) as N;
137
- }
138
- }
139
-
140
- class RandomizeIdVisitor extends IdVisitor {
132
+ class RandomizeIdVisitor extends JavaScriptVisitor<any> {
141
133
  readonly minted = new Set<string>();
142
134
 
143
135
  protected override async postVisit(tree: J, p: any): Promise<J | undefined> {
@@ -147,7 +139,7 @@ class RandomizeIdVisitor extends IdVisitor {
147
139
  }
148
140
  }
149
141
 
150
- class CollectIdVisitor extends IdVisitor {
142
+ class CollectIdVisitor extends JavaScriptVisitor<any> {
151
143
  readonly ids = new Set<string>();
152
144
 
153
145
  protected override async postVisit(tree: J, p: any): Promise<J | undefined> {
@@ -156,7 +148,7 @@ class CollectIdVisitor extends IdVisitor {
156
148
  }
157
149
  }
158
150
 
159
- class RetainIdVisitor extends IdVisitor {
151
+ class RetainIdVisitor extends JavaScriptVisitor<any> {
160
152
  private readonly seen = new Set<string>();
161
153
 
162
154
  constructor(private readonly retainable: ReadonlySet<string>) {
@@ -130,7 +130,7 @@ export namespace JS {
130
130
  */
131
131
  export interface Alias extends JS, Expression {
132
132
  readonly kind: typeof Kind.Alias;
133
- readonly propertyName: J.RightPadded<J.Identifier>;
133
+ readonly propertyName: J.RightPadded<J.Identifier | J.Literal>;
134
134
  readonly alias: Expression;
135
135
  }
136
136
 
@@ -985,5 +985,10 @@ export function isObjectBindingPattern(tree: any): tree is JS.ObjectBindingPatte
985
985
  return tree?.kind === JS.Kind.ObjectBindingPattern;
986
986
  }
987
987
 
988
+ /** The name a module export is known by, whether spelled as an identifier or as a string literal (`"a-b"`). */
989
+ export function moduleExportName(name: J.Identifier | J.Literal): string {
990
+ return name.kind === J.Kind.Identifier ? name.simpleName : String(name.value);
991
+ }
992
+
988
993
  TypedTree.registerTypeGetter(JS.Kind.PropertyAssignment, (tree: JS.PropertyAssignment) => TypedTree.getType(tree.initializer));
989
994
  TypedTree.registerTypeGetter(JS.Kind.FunctionType, (tree: JS.FunctionType) => TypedTree.getType(tree.returnType.element))
package/src/json/tree.ts CHANGED
@@ -291,8 +291,7 @@ export function isMember(json: Json): json is Json.Member {
291
291
  }
292
292
 
293
293
  /**
294
- * Gets the key name from a Json.Member.
295
- * Handles both string literals (quoted keys) and identifiers (unquoted keys).
294
+ * Gets the key name from a Json.Member, with a quoted key's escapes decoded.
296
295
  *
297
296
  * @param member The JSON member to extract the key name from
298
297
  * @returns The key name as a string, or undefined if extraction fails
@@ -300,12 +299,15 @@ export function isMember(json: Json): json is Json.Member {
300
299
  export function getMemberKeyName(member: Json.Member): string | undefined {
301
300
  const key = member.key.element;
302
301
  if (isLiteral(key)) {
303
- const source = key.source;
304
- // Remove quotes from string literal
305
- if (source.startsWith('"') && source.endsWith('"')) {
306
- return source.slice(1, -1);
302
+ if (key.source.startsWith('"')) {
303
+ // Decoded from source, since LSTs serialized by older Java JSON parsers keep a string's escapes in `value`.
304
+ try {
305
+ return JSON.parse(key.source);
306
+ } catch {
307
+ // a JSON5 escape such as `\x41`, which JSON.parse rejects
308
+ }
307
309
  }
308
- return source;
310
+ return String(key.value);
309
311
  } else if (isIdentifier(key)) {
310
312
  return key.name;
311
313
  }
@@ -60,36 +60,42 @@ export class GetObject {
60
60
  );
61
61
 
62
62
  if (pageChannel) {
63
- // The main thread answers each GetObject with the next page this traversal hands over
64
- pageChannel.onServe(async (request, sink) => {
65
- const objId = request.id;
66
- if (!localObjects.has(objId)) {
67
- sink([{state: RpcObjectState.DELETE}, {state: RpcObjectState.END_OF_OBJECT}]);
68
- return;
69
- }
70
- const objectOrGenerator = localObjects.get(objId)!;
71
- if (typeof objectOrGenerator === 'function') {
72
- localObjects.set(objId, await objectOrGenerator(objId));
73
- }
74
- const after = localObjects.get(objId);
75
- const before = remoteObjects.get(objId);
76
- const savedRefCount = localRefs.snapshot();
77
- latestTransfer = {id: objId, refCount: savedRefCount};
78
- try {
79
- new RpcSendQueue(localRefs, request.sourceFileType, trace())
80
- .drainEvery(batchSize, sink)
81
- .generate(after, before);
82
- remoteObjects.set(objId, after);
83
- } catch (e: any) {
84
- // An abort is rolled back by the AbortGetObject that follows it
85
- if (!(e instanceof PageAbortedError)) {
86
- remoteObjects.delete(objId);
87
- localRefs.rollbackTo(savedRefCount);
88
- latestTransfer = undefined;
63
+ // The main thread answers each GetObject with the next page this traversal hands over.
64
+ // One metrics row covers the whole transfer, however many pages it takes.
65
+ pageChannel.onServe((params, sink) => withMetrics<typeof params, void>(
66
+ "GetObject",
67
+ metricsCsv,
68
+ context => async request => {
69
+ const objId = request.id;
70
+ if (!localObjects.has(objId)) {
71
+ sink([{state: RpcObjectState.DELETE}, {state: RpcObjectState.END_OF_OBJECT}]);
72
+ return;
73
+ }
74
+ const objectOrGenerator = localObjects.get(objId)!;
75
+ if (typeof objectOrGenerator === 'function') {
76
+ localObjects.set(objId, await objectOrGenerator(objId));
77
+ }
78
+ const after = localObjects.get(objId);
79
+ context.target = extractSourcePath(after);
80
+ const before = remoteObjects.get(objId);
81
+ const savedRefCount = localRefs.snapshot();
82
+ latestTransfer = {id: objId, refCount: savedRefCount};
83
+ try {
84
+ new RpcSendQueue(localRefs, request.sourceFileType, trace())
85
+ .drainEvery(batchSize, sink)
86
+ .generate(after, before);
87
+ remoteObjects.set(objId, after);
88
+ } catch (e: any) {
89
+ // An abort is rolled back by the AbortGetObject that follows it
90
+ if (!(e instanceof PageAbortedError)) {
91
+ remoteObjects.delete(objId);
92
+ localRefs.rollbackTo(savedRefCount);
93
+ latestTransfer = undefined;
94
+ }
95
+ throw e;
89
96
  }
90
- throw e;
91
97
  }
92
- });
98
+ )(params));
93
99
  }
94
100
 
95
101
  connection.onRequest(
@@ -17,7 +17,11 @@ import * as rpc from "vscode-jsonrpc/node";
17
17
  import * as path from "path";
18
18
  import * as fs from "fs";
19
19
  import * as os from "os";
20
+ import * as nodeModule from "module";
21
+ import {createRequire} from "module";
22
+ import {pathToFileURL} from "url";
20
23
  import {spawn} from "child_process";
24
+ import * as semver from "semver";
21
25
  import {withMetrics} from "./metrics";
22
26
  import {RecipeMarketplace} from "../../marketplace";
23
27
  import {getPlatformCommand} from "../../shell-utils";
@@ -127,13 +131,19 @@ export class InstallRecipes {
127
131
  resolvedPath = request.recipes;
128
132
  }
129
133
 
134
+ const manifest = packageManifest(resolvedPath);
135
+ if (manifest) {
136
+ checkHostVersion(manifest, hostVersion(), logger);
137
+ }
138
+
130
139
  let recipeModule;
131
140
  try {
132
- // Pre-load core modules that are used by recipes but loaded lazily
133
- // This ensures they're in require.cache before setupSharedDependencies runs
134
- preloadCoreModules(logger);
135
-
136
- setupSharedDependencies(resolvedPath, logger);
141
+ if (!resolveSharedDependenciesFromHost()) {
142
+ // Pre-load core modules that are used by recipes but loaded lazily
143
+ // This ensures they're in require.cache before setupSharedDependencies runs
144
+ preloadCoreModules(logger);
145
+ setupSharedDependencies(resolvedPath, logger);
146
+ }
137
147
  recipeModule = require(resolvedPath);
138
148
  } catch (e: any) {
139
149
  throw new Error(`Failed to load recipe module from ${resolvedPath}: ${e.stack}`);
@@ -169,6 +179,86 @@ export class InstallRecipes {
169
179
  }
170
180
  }
171
181
 
182
+ const INCOMPATIBLE_RECIPE_BUNDLE = 1001;
183
+
184
+ /**
185
+ * Throws when this host's version is outside the package's peer range for @openrewrite/rewrite.
186
+ * A development build of the host (0.0.0, or a prerelease snapshot) only warns.
187
+ * A plain dependency's range only records the version the package was built against, so it is not checked.
188
+ */
189
+ export function checkHostVersion(manifest: { name?: string, version?: string, peerDependencies?: Record<string, string> },
190
+ hostVersion: string, logger?: rpc.Logger): void {
191
+ const range = manifest.peerDependencies?.['@openrewrite/rewrite'];
192
+ if (!range || !semver.validRange(range) || semver.satisfies(hostVersion, range, {includePrerelease: true})) {
193
+ return;
194
+ }
195
+ const message = `${manifest.name}@${manifest.version} requires @openrewrite/rewrite ${range}, but this host runs ${hostVersion}`;
196
+ if (hostVersion === '0.0.0' || semver.prerelease(hostVersion)) {
197
+ logger?.warn(message);
198
+ } else {
199
+ // RewriteRpc on the Java side turns this code and data into an IncompatibleRecipeBundleException.
200
+ // data is a string because that side's JSON-RPC library cannot decode an object there.
201
+ throw new rpc.ResponseError(INCOMPATIBLE_RECIPE_BUNDLE, message, JSON.stringify(
202
+ {packageName: manifest.name, packageVersion: manifest.version, requiredRange: range, hostVersion}));
203
+ }
204
+ }
205
+
206
+ function hostVersion(): string {
207
+ const root = findPackageRoot(__filename, '@openrewrite/rewrite');
208
+ return root ? JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version : '0.0.0';
209
+ }
210
+
211
+ /**
212
+ * The package.json of the package a module belongs to, the nearest one above its entry file.
213
+ */
214
+ function packageManifest(modulePath: string): any {
215
+ let dir: string;
216
+ try {
217
+ dir = path.dirname(require.resolve(modulePath));
218
+ } catch {
219
+ return undefined; // Loading the module reports why it does not resolve
220
+ }
221
+ for (; dir !== path.dirname(dir); dir = path.dirname(dir)) {
222
+ const file = path.join(dir, 'package.json');
223
+ if (fs.existsSync(file)) {
224
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
225
+ }
226
+ }
227
+ return undefined;
228
+ }
229
+
230
+ const SHARED_DEPENDENCIES = ['@openrewrite/rewrite', 'vscode-jsonrpc', 'mutative'];
231
+ let sharedDependencyHook: boolean | undefined;
232
+
233
+ /**
234
+ * Resolves the shared dependencies, and their subpaths, from this file for every require and import
235
+ * in the process. A recipe package then gets the host's instances whatever copies it has on disk.
236
+ * Returns false on a Node without module.registerHooks.
237
+ */
238
+ function resolveSharedDependenciesFromHost(): boolean {
239
+ if (sharedDependencyHook !== undefined) {
240
+ return sharedDependencyHook;
241
+ }
242
+ if (typeof nodeModule.registerHooks !== 'function') {
243
+ return sharedDependencyHook = false;
244
+ }
245
+ let resolvingFromHost = false; // require.resolve re-enters the hook on some Node versions
246
+ nodeModule.registerHooks({
247
+ resolve(specifier, context, nextResolve) {
248
+ if (resolvingFromHost || !SHARED_DEPENDENCIES.some(d => specifier === d || specifier.startsWith(d + '/'))) {
249
+ return nextResolve(specifier, context);
250
+ }
251
+ resolvingFromHost = true;
252
+ try {
253
+ return {url: pathToFileURL(require.resolve(specifier)).href, shortCircuit: true};
254
+ } finally {
255
+ resolvingFromHost = false;
256
+ }
257
+ }
258
+ });
259
+ return sharedDependencyHook = true;
260
+ }
261
+
172
262
  /**
173
263
  * Pre-loads core modules that are typically loaded lazily by recipes.
174
264
  * This ensures they're in require.cache before setupSharedDependencies runs,
@@ -203,73 +293,43 @@ function preloadCoreModules(logger?: rpc.Logger) {
203
293
  * Ensures dynamically loaded modules share the same class instances as the host
204
294
  * by mapping require.cache entries. This prevents instanceof failures when the
205
295
  * same package is installed in multiple node_modules directories.
296
+ *
297
+ * The target's copy is located by a require rooted at the target's entry file, so
298
+ * the mapped keys are the paths Node looks up when the target loads it.
206
299
  */
207
300
  function setupSharedDependencies(targetModulePath: string, logger?: rpc.Logger) {
208
301
  const sharedDeps = ['@openrewrite/rewrite', 'vscode-jsonrpc', 'mutative'];
209
- // For local-path installs, targetModulePath is the package dir itself.
210
- let targetDir: string;
302
+ let targetRequire: NodeJS.Require;
211
303
  try {
212
- targetDir = fs.statSync(targetModulePath).isDirectory()
213
- ? targetModulePath
214
- : path.dirname(targetModulePath);
304
+ targetRequire = createRequire(require.resolve(targetModulePath));
215
305
  } catch {
216
- targetDir = path.dirname(targetModulePath);
306
+ return; // Loading the target reports why it does not resolve
217
307
  }
218
308
 
219
309
  sharedDeps.forEach(depName => {
220
310
  try {
221
- // Step 1: Find where this package is currently loaded from (host)
222
- const hostPackageEntry = require.resolve(depName);
223
-
224
- // Step 2: Find the package root by looking for package.json
225
- let hostPackageRoot = path.dirname(hostPackageEntry);
226
- while (hostPackageRoot !== path.dirname(hostPackageRoot)) {
227
- const packageJsonPath = path.join(hostPackageRoot, 'package.json');
228
- if (fs.existsSync(packageJsonPath)) {
229
- try {
230
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
231
- if (pkg.name === depName) {
232
- break; // Found the package root
233
- }
234
- } catch (e) {
235
- // Not a valid package.json, continue
236
- }
311
+ const hostPackageRoot = findPackageRoot(require.resolve(depName), depName);
312
+ if (!hostPackageRoot) {
313
+ if (logger) {
314
+ logger.warn(`[setupSharedDependencies] Could not find the host's package root for ${depName}`);
237
315
  }
238
- hostPackageRoot = path.dirname(hostPackageRoot);
316
+ return;
239
317
  }
240
318
 
241
319
  if (logger) {
242
320
  logger.info(`[setupSharedDependencies] Host package root for ${depName}: ${hostPackageRoot}`);
243
321
  }
244
322
 
245
- // Step 3: Find where the target's node_modules has this package
246
- // We explicitly look in node_modules to avoid finding npm-linked global packages
247
323
  let targetPackageRoot: string | undefined;
248
-
249
- // Walk up from targetDir looking for node_modules containing this package
250
- let searchDir = targetDir;
251
- while (searchDir !== path.dirname(searchDir)) {
252
- const nodeModulesPath = path.join(searchDir, 'node_modules', ...depName.split('/'));
253
- if (fs.existsSync(nodeModulesPath)) {
254
- const packageJsonPath = path.join(nodeModulesPath, 'package.json');
255
- if (fs.existsSync(packageJsonPath)) {
256
- try {
257
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
258
- if (pkg.name === depName) {
259
- targetPackageRoot = nodeModulesPath;
260
- break;
261
- }
262
- } catch (e) {
263
- // Not a valid package.json, continue
264
- }
265
- }
266
- }
267
- searchDir = path.dirname(searchDir);
324
+ try {
325
+ targetPackageRoot = findPackageRoot(targetRequire.resolve(depName), depName);
326
+ } catch {
327
+ // Logged below
268
328
  }
269
329
 
270
330
  if (!targetPackageRoot) {
271
331
  if (logger) {
272
- logger.warn(`[setupSharedDependencies] Could not find ${depName} in target's node_modules`);
332
+ logger.warn(`[setupSharedDependencies] Could not resolve ${depName} from ${targetModulePath}`);
273
333
  }
274
334
  return; // Can't map this package
275
335
  }
@@ -286,7 +346,7 @@ function setupSharedDependencies(targetModulePath: string, logger?: rpc.Logger)
286
346
  return;
287
347
  }
288
348
 
289
- // Step 4: Map all cached modules from host package to target package
349
+ // Map all cached modules from host package to target package
290
350
  const hostPrefix = hostPackageRoot + path.sep;
291
351
 
292
352
  let mappedCount = 0;
@@ -312,3 +372,19 @@ function setupSharedDependencies(targetModulePath: string, logger?: rpc.Logger)
312
372
  }
313
373
  });
314
374
  }
375
+
376
+ /**
377
+ * The closest directory above a resolved module file whose package.json is named packageName.
378
+ */
379
+ function findPackageRoot(moduleFile: string, packageName: string): string | undefined {
380
+ for (let dir = path.dirname(moduleFile); dir !== path.dirname(dir); dir = path.dirname(dir)) {
381
+ try {
382
+ if (JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).name === packageName) {
383
+ return dir;
384
+ }
385
+ } catch {
386
+ // No readable package.json here
387
+ }
388
+ }
389
+ return undefined;
390
+ }
@@ -174,22 +174,21 @@ export class PrepareRecipe {
174
174
  const wireEntry = this.conditionWireEntry(visitor.check, phase);
175
175
  if (wireEntry) {
176
176
  preconditions.push(wireEntry);
177
- recipe = Object.assign(
178
- Object.create(Object.getPrototypeOf(recipe)),
179
- recipe,
180
- phase === "edit" ?
181
- {
182
- async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
183
- return visitor.v;
184
- }
185
- } :
186
- {
187
- async scanner(acc: any): Promise<TreeVisitor<any, ExecutionContext>> {
188
- const checkVisitor = await (recipe as ScanningRecipe<any>).scanner(acc);
189
- return (checkVisitor as Check<any>).v;
190
- }
177
+ if (phase === "edit") {
178
+ recipe = PrepareRecipe.withOverrides(recipe, {
179
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
180
+ return visitor.v;
191
181
  }
192
- )
182
+ });
183
+ } else {
184
+ const scanner = (recipe as ScanningRecipe<any>).scanner;
185
+ recipe = PrepareRecipe.withOverrides(recipe, {
186
+ async scanner(this: ScanningRecipe<any>, acc: any): Promise<TreeVisitor<any, ExecutionContext>> {
187
+ const scanVisitor = await scanner.call(this, acc);
188
+ return scanVisitor instanceof Check ? scanVisitor.v : scanVisitor;
189
+ }
190
+ });
191
+ }
193
192
  }
194
193
  await this.visitorTypePrecondition(preconditions, visitor.v);
195
194
  } else {
@@ -198,6 +197,10 @@ export class PrepareRecipe {
198
197
  return recipe;
199
198
  }
200
199
 
200
+ private static withOverrides(recipe: Recipe, overrides: object): Recipe {
201
+ return Object.assign(Object.create(Object.getPrototypeOf(recipe)), recipe, overrides);
202
+ }
203
+
201
204
  /**
202
205
  * Translate a precondition condition (operand) to a wire entry.
203
206
  *