@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
@@ -75,6 +75,11 @@ export class JavaVisitor<P> extends TreeVisitor<J, P> {
75
75
  return nameTree;
76
76
  }
77
77
 
78
+ /** Visits a tree in a type-name position, then gives it to `visitTypeName`. */
79
+ private async visitNameTree<N extends NameTree>(nameTree: N, p: P): Promise<N> {
80
+ return this.visitTypeName(await this.visitDefined<N>(nameTree, p), p);
81
+ }
82
+
78
83
  /**
79
84
  * Visits the children of `tree` through `visit` under a cursor that holds it, where a visit made it of the tree
80
85
  * on the cursor, and puts the given cursor back after with the messages they left.
@@ -119,7 +124,7 @@ export class JavaVisitor<P> extends TreeVisitor<J, P> {
119
124
  const updates = await this.visitChildrenOf(annotation, async () => ({
120
125
  prefix: await this.visitSpace(annotation.prefix, p),
121
126
  markers: await this.visitMarkers(annotation.markers, p),
122
- annotationType: await this.visitTypeName(annotation.annotationType, p),
127
+ annotationType: await this.visitNameTree(annotation.annotationType, p),
123
128
  arguments: await this.visitOptionalContainer(annotation.arguments, p)
124
129
  }));
125
130
  return updateIfChanged(annotation, updates);
@@ -914,7 +919,7 @@ export class JavaVisitor<P> extends TreeVisitor<J, P> {
914
919
  const updates: any = await this.visitChildrenOf(parameterizedType, async () => ({
915
920
  prefix: await this.visitSpace(parameterizedType.prefix, p),
916
921
  markers: await this.visitMarkers(parameterizedType.markers, p),
917
- class: await this.visitTypeName(parameterizedType.class, p),
922
+ class: await this.visitNameTree(parameterizedType.class, p),
918
923
  typeParameters: await this.visitOptionalContainer(parameterizedType.typeParameters, p),
919
924
  type: await this.visitType(parameterizedType.type, p)
920
925
  }));
@@ -1268,7 +1273,7 @@ export class JavaVisitor<P> extends TreeVisitor<J, P> {
1268
1273
  bound: await this.visitOptionalLeftPadded(wildcard.bound, p)
1269
1274
  };
1270
1275
  if (wildcard.boundedType) {
1271
- updates.boundedType = await this.visitTypeName(wildcard.boundedType, p);
1276
+ updates.boundedType = await this.visitNameTree(wildcard.boundedType, p);
1272
1277
  }
1273
1278
  return updateIfChanged(wildcard, updates);
1274
1279
  });
@@ -1,6 +1,6 @@
1
1
  import {JavaScriptVisitor} from "./visitor";
2
- import {ElementRemovalFormatter, emptySpace, isIdentifier, J, NameTree, rightPadded, singleSpace, space, Statement, TrailingComma, Type} from "../java";
3
- import {isObjectBindingPattern, JS, JSX} from "./tree";
2
+ import {Comment, ElementRemovalFormatter, emptySpace, isIdentifier, J, rightPadded, singleSpace, space, Statement, TextComment, TrailingComma, Type} from "../java";
3
+ import {isObjectBindingPattern, JS, JSX, moduleExportName} from "./tree";
4
4
  import {randomId, UUID} from "../uuid";
5
5
  import {TypeVisitor} from "../java/type-visitor";
6
6
  import {mapAsync, updateIfChanged} from "../util";
@@ -323,6 +323,26 @@ function readModuleSyntax(cu: JS.CompilationUnit): "esm" | "commonjs" | "none" {
323
323
  return esm ? "esm" : commonJs ? "commonjs" : "none";
324
324
  }
325
325
 
326
+ /**
327
+ * `cu` without an empty `export {};`, which only marks a file without imports as a module, as
328
+ * `RemoveImport` leaves one. An import makes it redundant. One carrying a comment is kept.
329
+ */
330
+ function withoutModuleMarker(cu: JS.CompilationUnit): JS.CompilationUnit {
331
+ const statements = cu.statements.filter(({element}) => !isModuleMarker(element));
332
+ return statements.length === cu.statements.length ? cu : {...cu, statements};
333
+ }
334
+
335
+ function isModuleMarker(element: J | undefined): boolean {
336
+ if (element?.kind !== JS.Kind.ExportDeclaration) {
337
+ return false;
338
+ }
339
+ const declaration = element as JS.ExportDeclaration;
340
+ return declaration.prefix.comments.length === 0 && declaration.modifiers.length === 0 &&
341
+ !declaration.typeOnly.element && declaration.moduleSpecifier === undefined &&
342
+ declaration.exportClause?.kind === JS.Kind.NamedExports &&
343
+ (declaration.exportClause as JS.NamedExports).elements.elements.every(e => e.element.kind === J.Kind.Empty);
344
+ }
345
+
326
346
  /** An import or any export form. */
327
347
  function isEsmStatement(element: J | undefined): boolean {
328
348
  // `export {a, b}`, `export * from` and `export default` are statements of their own.
@@ -488,8 +508,8 @@ function specifierBinding(specifier: JS.ImportSpecifier): { name: string; member
488
508
  return undefined;
489
509
  }
490
510
  const alias = specifier.specifier as JS.Alias;
491
- return alias.propertyName?.element?.kind === J.Kind.Identifier && alias.alias?.kind === J.Kind.Identifier
492
- ? {name: (alias.alias as J.Identifier).simpleName, member: (alias.propertyName.element as J.Identifier).simpleName}
511
+ return alias.propertyName?.element && alias.alias?.kind === J.Kind.Identifier
512
+ ? {name: (alias.alias as J.Identifier).simpleName, member: moduleExportName(alias.propertyName.element)}
493
513
  : undefined;
494
514
  }
495
515
 
@@ -908,24 +928,20 @@ export class AddImport<P> extends JavaScriptVisitor<P> {
908
928
  ? markers({kind: J.Markers.Semicolon, id: randomId()})
909
929
  : emptyMarkers;
910
930
 
911
- if (insertionIndex === 0) {
912
- // Insert at the beginning
931
+ if (insertionIndex === prologueLength(compilationUnit)) {
913
932
  // The `after` space should be empty since any semicolon is printed after it
914
- // The spacing comes from updating the next statement's prefix
915
- const updatedStatements = compilationUnit.statements.length > 0
916
- ? [
917
- rightPadded(newImport, emptySpace, semicolonMarkers),
918
- {
919
- ...compilationUnit.statements[0],
920
- element: compilationUnit.statements[0].element
921
- ? {...compilationUnit.statements[0].element, prefix: space("\n\n")}
922
- : undefined
923
- } as J.RightPadded<Statement>,
924
- ...compilationUnit.statements.slice(1)
925
- ]
926
- : [rightPadded(newImport, emptySpace, semicolonMarkers)];
927
-
928
- draft.statements = updatedStatements;
933
+ const next = compilationUnit.statements[insertionIndex];
934
+ draft.statements = [
935
+ ...compilationUnit.statements.slice(0, insertionIndex),
936
+ rightPadded(newImport, emptySpace, semicolonMarkers),
937
+ ...(next ? [{
938
+ ...next,
939
+ element: next.element
940
+ ? {...next.element, prefix: splitAtBodyStart(next.element.prefix).behind}
941
+ : undefined
942
+ } as J.RightPadded<Statement>] : []),
943
+ ...compilationUnit.statements.slice(insertionIndex + 1)
944
+ ];
929
945
  } else {
930
946
  // Insert after existing imports
931
947
  const before = compilationUnit.statements.slice(0, insertionIndex);
@@ -958,7 +974,7 @@ export class AddImport<P> extends JavaScriptVisitor<P> {
958
974
  }
959
975
  });
960
976
 
961
- return formatImport(withImport, newImport.id, p, detectBraceSpacing(compilationUnit));
977
+ return formatImport(withoutModuleMarker(withImport), newImport.id, p, detectBraceSpacing(compilationUnit));
962
978
  }
963
979
 
964
980
  /**
@@ -1728,19 +1744,9 @@ export class AddImport<P> extends JavaScriptVisitor<P> {
1728
1744
  * Determine the appropriate spacing before the import statement
1729
1745
  */
1730
1746
  private determineImportPrefix(compilationUnit: JS.CompilationUnit, insertionIndex: number): J.Space {
1731
- // If inserting at the beginning (index 0), use the prefix of the first statement
1732
- // but only the whitespace part (preserve comments on the original first statement)
1733
- if (insertionIndex === 0 && compilationUnit.statements.length > 0) {
1734
- const firstPrefix = compilationUnit.statements[0].element?.prefix;
1735
- if (firstPrefix) {
1736
- // Keep only whitespace, not comments
1737
- return {
1738
- kind: J.Kind.Space,
1739
- comments: [],
1740
- whitespace: firstPrefix.whitespace
1741
- };
1742
- }
1743
- return emptySpace;
1747
+ if (insertionIndex === prologueLength(compilationUnit) && insertionIndex < compilationUnit.statements.length) {
1748
+ const nextPrefix = compilationUnit.statements[insertionIndex].element?.prefix;
1749
+ return nextPrefix ? splitAtBodyStart(nextPrefix).ahead : emptySpace;
1744
1750
  }
1745
1751
 
1746
1752
  // If inserting after other statements, ensure we have at least one newline
@@ -1769,8 +1775,7 @@ export class AddImport<P> extends JavaScriptVisitor<P> {
1769
1775
  return lastImportIndex + 1;
1770
1776
  }
1771
1777
 
1772
- // No imports found, insert at the beginning
1773
- return 0;
1778
+ return prologueLength(compilationUnit);
1774
1779
  }
1775
1780
 
1776
1781
 
@@ -1817,14 +1822,51 @@ function newIdentifier(name: string): J.Identifier {
1817
1822
  };
1818
1823
  }
1819
1824
 
1820
- function isUseStrict(statement: J | undefined): boolean {
1825
+ function isDirective(statement: J | undefined): boolean {
1821
1826
  const expression = statement?.kind === JS.Kind.ExpressionStatement ? (statement as JS.ExpressionStatement).expression : statement;
1822
- return expression?.kind === J.Kind.Literal && (expression as J.Literal).value === 'use strict';
1827
+ return quoteOf(expression) !== undefined;
1828
+ }
1829
+
1830
+ function prologueLength(cu: JS.CompilationUnit): number {
1831
+ const statements = cu.statements;
1832
+ let length = 0;
1833
+ while (length < statements.length &&
1834
+ (statements[length].element?.kind === JS.Kind.Shebang || isDirective(statements[length].element))) {
1835
+ length++;
1836
+ }
1837
+ return length;
1838
+ }
1839
+
1840
+ // Keep comments through the last triple-slash directive ahead of the import.
1841
+ function splitAtBodyStart(prefix: J.Space): {ahead: J.Space; behind: J.Space} {
1842
+ let ahead = prefix.comments.length;
1843
+ while (ahead > 0 && !isTripleSlashDirective(prefix.comments[ahead - 1])) {
1844
+ ahead--;
1845
+ }
1846
+ return {
1847
+ ahead: {kind: J.Kind.Space, whitespace: prefix.whitespace, comments: prefix.comments.slice(0, ahead)},
1848
+ behind: {...prefix, whitespace: "\n\n", comments: prefix.comments.slice(ahead)}
1849
+ };
1850
+ }
1851
+
1852
+ const TRIPLE_SLASH_DIRECTIVES = ['<reference', '<amd-module', '<amd-dependency'];
1853
+
1854
+ function isTripleSlashDirective(comment: Comment): boolean {
1855
+ if (comment.kind !== J.Kind.TextComment || (comment as TextComment).multiline) {
1856
+ return false;
1857
+ }
1858
+ // TextComment.text excludes the leading //.
1859
+ const text = (comment as TextComment).text;
1860
+ if (!text.startsWith('/')) {
1861
+ return false;
1862
+ }
1863
+ const rest = text.slice(1).trimStart();
1864
+ return TRIPLE_SLASH_DIRECTIVES.some(directive => rest.startsWith(directive));
1823
1865
  }
1824
1866
 
1825
1867
  /**
1826
1868
  * `cu` with `statement` after its last top-level `require`. A file with none takes it first,
1827
- * after a `'use strict'` directive, which has to open the file to apply.
1869
+ * after a shebang and any directives, which have to open the file to apply.
1828
1870
  */
1829
1871
  function withRequireStatement(cu: JS.CompilationUnit, statement: Statement): JS.CompilationUnit {
1830
1872
  const statements = cu.statements;
@@ -1845,13 +1887,13 @@ function withRequireStatement(cu: JS.CompilationUnit, statement: Statement): JS.
1845
1887
  if (next === undefined) {
1846
1888
  return {...cu, statements: [...statements, {...padded, element: {...statement, prefix: space(at === 0 ? "" : "\n\n")}}]};
1847
1889
  }
1848
- // The new statement takes the place of the one it goes before, which gets a blank line of its own.
1890
+ const {ahead, behind} = splitAtBodyStart(next.prefix);
1849
1891
  return {
1850
1892
  ...cu,
1851
1893
  statements: [
1852
1894
  ...statements.slice(0, at),
1853
- {...padded, element: {...statement, prefix: space(next.prefix.whitespace)}},
1854
- {...statements[at], element: {...next, prefix: {...next.prefix, whitespace: "\n\n"}}},
1895
+ {...padded, element: {...statement, prefix: ahead}},
1896
+ {...statements[at], element: {...next, prefix: behind}},
1855
1897
  ...statements.slice(at + 1)
1856
1898
  ]
1857
1899
  };
@@ -1892,16 +1934,12 @@ export function requireBinds(
1892
1934
  }
1893
1935
 
1894
1936
  /**
1895
- * Where the file's leading requires start, after a shebang and `'use strict'`, and end. Every
1937
+ * Where the file's leading requires start, after a shebang and any directives, and end. Every
1896
1938
  * top-level statement after them runs once they are initialised, so a binding placed there is read after it.
1897
1939
  */
1898
1940
  function leadingRequires(cu: JS.CompilationUnit): {start: number; end: number} {
1899
1941
  const statements = cu.statements;
1900
- let start = 0;
1901
- while (start < statements.length &&
1902
- (statements[start].element?.kind === JS.Kind.Shebang || isUseStrict(statements[start].element))) {
1903
- start++;
1904
- }
1942
+ const start = prologueLength(cu);
1905
1943
  let end = start;
1906
1944
  while (end < statements.length && isRequireStatement(statements[end].element)) {
1907
1945
  end++;
@@ -1992,8 +2030,7 @@ function namedSpecifierImports(specifier: JS.ImportSpecifier["specifier"], key:
1992
2030
  return specifier.simpleName === key;
1993
2031
  }
1994
2032
  if (specifier.kind === JS.Kind.Alias) {
1995
- const propertyName = (specifier as JS.Alias).propertyName.element;
1996
- return isIdentifier(propertyName) && propertyName.simpleName === key;
2033
+ return moduleExportName((specifier as JS.Alias).propertyName.element) === key;
1997
2034
  }
1998
2035
  return false;
1999
2036
  }
@@ -2418,14 +2455,6 @@ export class RebindImport<P> extends JavaScriptVisitor<P> {
2418
2455
  return this.movedTypes.visit(javaType, undefined);
2419
2456
  }
2420
2457
 
2421
- /**
2422
- * A decorator and the other type-name positions reach the tree through this hook, which the
2423
- * base visitor holds closed; a reference in one of them is a reference like any other.
2424
- */
2425
- protected override async visitTypeName<N extends NameTree>(nameTree: N, p: P): Promise<N> {
2426
- return await this.visit(nameTree, p) as N;
2427
- }
2428
-
2429
2458
  /**
2430
2459
  * An export specifier's own name is the module's public surface, which its consumers read and
2431
2460
  * the rename leaves alone. See CLAUDE.md: Which name a rebind binds.
@@ -2532,11 +2561,11 @@ export class RebindImport<P> extends JavaScriptVisitor<P> {
2532
2561
  }
2533
2562
  }
2534
2563
 
2535
- /** Points `literal` at `module`, keeping its quotes. */
2536
- function respecify(literal: Draft<J.Literal>, module: string): void {
2564
+ /** Points `literal` at `name`, keeping its quotes. */
2565
+ function respecify(literal: Draft<J.Literal>, name: string): void {
2537
2566
  const quoteChar = (literal.valueSource ?? '"').startsWith("'") ? "'" : '"';
2538
- literal.value = module;
2539
- literal.valueSource = `${quoteChar}${module}${quoteChar}`;
2567
+ literal.value = name;
2568
+ literal.valueSource = `${quoteChar}${name.replace(/\\/g, '\\\\').split(quoteChar).join(`\\${quoteChar}`)}${quoteChar}`;
2540
2569
  literal.unicodeEscapes = undefined;
2541
2570
  }
2542
2571
 
@@ -2867,7 +2896,12 @@ function rewriteNamedSpecifier(
2867
2896
  // standing in for it takes that prefix.
2868
2897
  specifier.specifier = {...local, prefix: (alias ?? local).prefix, simpleName: member};
2869
2898
  } else if (alias) {
2870
- (alias.propertyName.element as Draft<J.Identifier>).simpleName = member;
2899
+ const propertyName = alias.propertyName.element;
2900
+ if (propertyName.kind === J.Kind.Literal) {
2901
+ respecify(propertyName, member);
2902
+ } else {
2903
+ propertyName.simpleName = member;
2904
+ }
2871
2905
  local.simpleName = boundName;
2872
2906
  } else {
2873
2907
  specifier.specifier = aliasing({...local, simpleName: boundName}, member) as Draft<JS.Alias>;
@@ -18,12 +18,27 @@ import {J, Type, Expression, Statement, isIdentifier} from '../java';
18
18
  import {JS, JSX} from './tree';
19
19
  import {Cursor, Tree} from "../tree";
20
20
 
21
+ // ============================================================================
22
+ // LST Tree Type Definitions
23
+ // ============================================================================
24
+
25
+ /**
26
+ * Union type representing all possible LST tree node types.
27
+ * All of these types have `markers` and `kind` properties and can appear as values in the LST tree.
28
+ * The `kind` property is always present on all LST nodes.
29
+ */
30
+ export type JTree = J | J.Container<any> | J.LeftPadded<any> | J.RightPadded<any>;
31
+
32
+ // ============================================================================
33
+ // Comparator Visitor
34
+ // ============================================================================
35
+
21
36
  /**
22
37
  * A visitor that compares two AST trees in lock step.
23
- * It takes another `J` instance as context and visits both trees simultaneously.
38
+ * It takes another LST tree node (JTree) as context and visits both trees simultaneously.
24
39
  * The visit operation is aborted when the nodes don't match.
25
40
  */
26
- export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
41
+ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<JTree> {
27
42
  /**
28
43
  * Flag indicating whether the trees match so far
29
44
  */
@@ -85,27 +100,27 @@ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
85
100
  * Can be overridden in subclasses to extract values from cursors and provide richer error messages.
86
101
  */
87
102
 
88
- protected kindMismatch() {
89
- const pattern = this.cursor?.value as any;
90
- return this.abort(pattern, 'kind-mismatch');
103
+ protected kindMismatch<T extends JTree>(): T {
104
+ const pattern = this.cursor?.value as T;
105
+ return this.abort(pattern, 'kind-mismatch') as T;
91
106
  }
92
107
 
93
- protected structuralMismatch(propertyName?: string) {
94
- const pattern = this.cursor?.value as any;
95
- return this.abort(pattern, 'structural-mismatch', propertyName);
108
+ protected structuralMismatch<T extends JTree>(propertyName?: string): T {
109
+ const pattern = this.cursor?.value as T;
110
+ return this.abort(pattern, 'structural-mismatch', propertyName) as T;
96
111
  }
97
112
 
98
- protected arrayLengthMismatch(propertyName: string) {
99
- const pattern = this.cursor?.value as any;
100
- return this.abort(pattern, 'array-length-mismatch', propertyName);
113
+ protected arrayLengthMismatch<T extends JTree>(propertyName: string): T {
114
+ const pattern = this.cursor?.value as T;
115
+ return this.abort(pattern, 'array-length-mismatch', propertyName) as T;
101
116
  }
102
117
 
103
- protected valueMismatch(propertyName?: string, expected?: any, actual?: any) {
104
- const pattern = this.cursor?.value as any;
118
+ protected valueMismatch<T extends JTree>(propertyName?: string, expected?: any, actual?: any): T {
119
+ const pattern = this.cursor?.value as T;
105
120
  // If values not provided, try to extract from cursors (only if propertyName is available)
106
121
  const expectedVal = expected !== undefined ? expected : (propertyName ? (pattern as any)?.[propertyName] : pattern);
107
122
  const actualVal = actual !== undefined ? actual : (propertyName ? (this.targetCursor?.value as any)?.[propertyName] : this.targetCursor?.value);
108
- return this.abort(pattern, 'value-mismatch', propertyName, expectedVal, actualVal);
123
+ return this.abort(pattern, 'value-mismatch', propertyName, expectedVal, actualVal) as T;
109
124
  }
110
125
 
111
126
  protected typeMismatch(propertyName?: string) {
@@ -275,12 +290,12 @@ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
275
290
  * @param other The corresponding element from the second tree
276
291
  * @returns The visited element from the first tree
277
292
  */
278
- protected async visitElement<T extends J>(j: T, other: T): Promise<T> {
293
+ protected async visitElement(j: J, other: J): Promise<J> {
279
294
  if (!this.match) return j;
280
295
 
281
296
  // Check if kinds match
282
297
  if (j.kind !== other.kind) {
283
- return this.kindMismatch();
298
+ return this.kindMismatch<J>();
284
299
  }
285
300
 
286
301
  // Iterate over all properties
@@ -296,7 +311,7 @@ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
296
311
  // Handle arrays - compare element by element
297
312
  if (Array.isArray(jValue)) {
298
313
  if (!Array.isArray(otherValue) || jValue.length !== otherValue.length) {
299
- return this.arrayLengthMismatch(key);
314
+ return this.arrayLengthMismatch<J>(key);
300
315
  }
301
316
 
302
317
  for (let i = 0; i < jValue.length; i++) {
@@ -341,12 +356,12 @@ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
341
356
  * Pushes the wrapper onto the cursor stack so captures can access it.
342
357
  * Also updates targetCursor in parallel.
343
358
  */
344
- public async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: J): Promise<J.RightPadded<T>> {
359
+ public async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: JTree): Promise<J.RightPadded<T>> {
345
360
  if (!this.match) return right;
346
361
 
347
362
  // Extract the other element if it's also a RightPadded
348
- const isRightPadded = (p as any).kind === J.Kind.RightPadded;
349
- const otherWrapper = isRightPadded ? (p as unknown) as J.RightPadded<T> : undefined;
363
+ const isRightPadded = p.kind === J.Kind.RightPadded;
364
+ const otherWrapper = isRightPadded ? p as J.RightPadded<T> : undefined;
350
365
  const otherElement = isRightPadded ? otherWrapper!.element : p;
351
366
 
352
367
  // Push wrappers onto both cursors, then compare only the elements, not markers or spacing
@@ -372,12 +387,12 @@ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
372
387
  * Pushes the wrapper onto the cursor stack so captures can access it.
373
388
  * Also updates targetCursor in parallel.
374
389
  */
375
- public async visitLeftPadded<T extends J | J.Space | number | string | boolean>(left: J.LeftPadded<T>, p: J): Promise<J.LeftPadded<T>> {
390
+ public async visitLeftPadded<T extends J | J.Space | number | string | boolean>(left: J.LeftPadded<T>, p: JTree): Promise<J.LeftPadded<T>> {
376
391
  if (!this.match) return left;
377
392
 
378
393
  // Extract the other element if it's also a LeftPadded
379
- const isLeftPadded = (p as any).kind === J.Kind.LeftPadded;
380
- const otherWrapper = isLeftPadded ? (p as unknown) as J.LeftPadded<T> : undefined;
394
+ const isLeftPadded = p.kind === J.Kind.LeftPadded;
395
+ const otherWrapper = isLeftPadded ? p as J.LeftPadded<T> : undefined;
381
396
  const otherElement = isLeftPadded ? otherWrapper!.element : p;
382
397
 
383
398
  // Push wrappers onto both cursors, then compare only the elements, not markers or spacing
@@ -403,25 +418,23 @@ export class JavaScriptComparatorVisitor extends JavaScriptVisitor<J> {
403
418
  * Pushes the wrapper onto the cursor stack so captures can access it.
404
419
  * Also updates targetCursor in parallel.
405
420
  */
406
- public async visitContainer<T extends J>(container: J.Container<T>, p: J): Promise<J.Container<T>> {
421
+ public async visitContainer<T extends J>(container: J.Container<T>, p: JTree): Promise<J.Container<T>> {
407
422
  if (!this.match) return container;
408
423
 
409
424
  // Extract the other elements if it's also a Container
410
- const isContainer = (p as any).kind === J.Kind.Container;
411
- const otherContainer = isContainer ? (p as unknown) as J.Container<T> : undefined;
425
+ const isContainer = p.kind === J.Kind.Container;
426
+ const otherContainer = isContainer ? p as J.Container<T> : undefined;
412
427
  const otherElements: J.RightPadded<T>[] = isContainer ? otherContainer!.elements : (p as any);
413
428
 
414
- // Compare elements array length
415
- if (container.elements.length !== otherElements.length) {
416
- return this.arrayLengthMismatch('elements');
417
- }
418
-
419
- // Push wrappers onto both cursors, then compare each element
429
+ // Push wrappers onto both cursors first, so that a count mismatch is reported on the container
420
430
  const savedCursor = this.cursor;
421
431
  const savedTargetCursor = this.targetCursor;
422
432
  this.cursor = new Cursor(container, this.cursor);
423
433
  this.targetCursor = otherContainer ? new Cursor(otherContainer, this.targetCursor) : this.targetCursor;
424
434
  try {
435
+ if (container.elements.length !== otherElements.length) {
436
+ return this.arrayLengthMismatch<J.Container<T>>('elements');
437
+ }
425
438
  for (let i = 0; i < container.elements.length; i++) {
426
439
  await this.visitProperty(container.elements[i], otherElements[i]);
427
440
  if (!this.match) return container;
@@ -2047,7 +2060,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2047
2060
  if (!this.match) return arrowFunction;
2048
2061
 
2049
2062
  if (other.kind !== JS.Kind.ArrowFunction) {
2050
- return this.kindMismatch();
2063
+ return this.kindMismatch<J>();
2051
2064
  }
2052
2065
 
2053
2066
  const otherArrow = other as JS.ArrowFunction;
@@ -2064,7 +2077,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2064
2077
  // Handle arrays
2065
2078
  if (Array.isArray(jValue)) {
2066
2079
  if (!Array.isArray(otherValue) || jValue.length !== otherValue.length) {
2067
- return this.arrayLengthMismatch(key);
2080
+ return this.arrayLengthMismatch<J>(key);
2068
2081
  }
2069
2082
  for (let i = 0; i < jValue.length; i++) {
2070
2083
  await this.visitProperty(jValue[i], otherValue[i]);
@@ -2080,7 +2093,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2080
2093
  const params1 = arrowFunction.lambda.parameters.parameters;
2081
2094
  const params2 = otherArrow.lambda.parameters.parameters;
2082
2095
  if (params1.length !== params2.length) {
2083
- return this.arrayLengthMismatch('lambda.parameters.parameters');
2096
+ return this.arrayLengthMismatch<J>('lambda.parameters.parameters');
2084
2097
  }
2085
2098
  for (let i = 0; i < params1.length; i++) {
2086
2099
  await this.visitProperty(params1[i], params2[i]);
@@ -2118,7 +2131,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2118
2131
  if (!this.match) return parameters;
2119
2132
 
2120
2133
  if (other.kind !== J.Kind.LambdaParameters) {
2121
- return this.kindMismatch();
2134
+ return this.kindMismatch<J>();
2122
2135
  }
2123
2136
 
2124
2137
  const otherParams = other as J.Lambda.Parameters;
@@ -2135,7 +2148,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2135
2148
  // Handle arrays
2136
2149
  if (Array.isArray(jValue)) {
2137
2150
  if (!Array.isArray(otherValue) || jValue.length !== otherValue.length) {
2138
- return this.arrayLengthMismatch(key);
2151
+ return this.arrayLengthMismatch<J>(key);
2139
2152
  }
2140
2153
  for (let i = 0; i < jValue.length; i++) {
2141
2154
  await this.visitProperty(jValue[i], otherValue[i]);
@@ -2162,7 +2175,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2162
2175
  if (!this.match) return propertyAssignment;
2163
2176
 
2164
2177
  if (other.kind !== JS.Kind.PropertyAssignment) {
2165
- return this.kindMismatch();
2178
+ return this.kindMismatch<J>();
2166
2179
  }
2167
2180
 
2168
2181
  const otherProp = other as JS.PropertyAssignment;
@@ -2195,7 +2208,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2195
2208
  return propertyAssignment;
2196
2209
  } else {
2197
2210
  // Not equivalent (e.g., { x: y })
2198
- return this.structuralMismatch('initializer');
2211
+ return this.structuralMismatch<J>('initializer');
2199
2212
  }
2200
2213
  }
2201
2214
 
@@ -2359,7 +2372,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2359
2372
  */
2360
2373
  override async visitMethodInvocation(method: J.MethodInvocation, other: J): Promise<J | undefined> {
2361
2374
  if (other.kind !== J.Kind.MethodInvocation) {
2362
- return this.kindMismatch();
2375
+ return this.kindMismatch<J>();
2363
2376
  }
2364
2377
 
2365
2378
  const otherMethod = other as J.MethodInvocation;
@@ -2385,7 +2398,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2385
2398
  // Check names unless we determined we can skip based on type FQN matching
2386
2399
  if (!canSkipNameCheck) {
2387
2400
  if (method.name.simpleName !== otherMethod.name.simpleName) {
2388
- return this.valueMismatch('name.simpleName', method.name.simpleName, otherMethod.name.simpleName);
2401
+ return this.valueMismatch<J>('name.simpleName', method.name.simpleName, otherMethod.name.simpleName);
2389
2402
  }
2390
2403
 
2391
2404
  // In strict mode, check type attribution requirements
@@ -2407,7 +2420,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2407
2420
  if (Type.isFullyQualified(methodDeclaringType) && Type.isFullyQualified(otherDeclaringType) &&
2408
2421
  !this.sameFullyQualifiedName(methodDeclaringType, otherDeclaringType) &&
2409
2422
  !this.declaresAnyCallee(methodDeclaringType)) {
2410
- return this.valueMismatch('methodType.declaringType');
2423
+ return this.valueMismatch<J>('methodType.declaringType');
2411
2424
  }
2412
2425
  }
2413
2426
  }
@@ -2418,7 +2431,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2418
2431
  !!(method.methodType!.flags & otherMethod.methodType!.flags & Type.Flag.Static);
2419
2432
  if (!canSkipNameCheck || method.select && !staticCall) {
2420
2433
  if ((method.select === undefined) !== (otherMethod.select === undefined)) {
2421
- return this.structuralMismatch('select');
2434
+ return this.structuralMismatch<J>('select');
2422
2435
  }
2423
2436
 
2424
2437
  if (method.select && otherMethod.select) {
@@ -2430,7 +2443,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2430
2443
  // A pattern that spells out no type arguments says nothing about them, as with parentheses
2431
2444
  if (method.typeParameters) {
2432
2445
  if (!otherMethod.typeParameters) {
2433
- return this.structuralMismatch('typeParameters');
2446
+ return this.structuralMismatch<J>('typeParameters');
2434
2447
  }
2435
2448
 
2436
2449
  await this.visitContainerProperty('typeParameters', method.typeParameters, otherMethod.typeParameters);
@@ -2492,13 +2505,13 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2492
2505
  }
2493
2506
 
2494
2507
  if (other.kind !== J.Kind.Identifier) {
2495
- return this.kindMismatch();
2508
+ return this.kindMismatch<J>();
2496
2509
  }
2497
2510
 
2498
2511
  const otherIdentifier = other as J.Identifier;
2499
2512
 
2500
2513
  if (identifier.simpleName !== otherIdentifier.simpleName) {
2501
- return this.denoteOneDeclaration(identifier, otherIdentifier) ? identifier : this.valueMismatch('simpleName');
2514
+ return this.denoteOneDeclaration(identifier, otherIdentifier) ? identifier : this.valueMismatch<J>('simpleName');
2502
2515
  }
2503
2516
 
2504
2517
  // For identifiers with field types, check type attribution
@@ -2572,7 +2585,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2572
2585
  // Compare typeExpression - lenient matching allows one to be undefined
2573
2586
  if ((variableDeclarations.typeExpression === undefined) !== (otherVariableDeclarations.typeExpression === undefined)) {
2574
2587
  if (!this.lenientTypeMatching) {
2575
- return this.structuralMismatch('typeExpression');
2588
+ return this.structuralMismatch<J>('typeExpression');
2576
2589
  }
2577
2590
  // In lenient mode, skip type comparison and continue
2578
2591
  } else if (variableDeclarations.typeExpression && otherVariableDeclarations.typeExpression) {
@@ -2583,7 +2596,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2583
2596
 
2584
2597
  // Compare varargs
2585
2598
  if ((variableDeclarations.varargs === undefined) !== (otherVariableDeclarations.varargs === undefined)) {
2586
- return this.structuralMismatch('varargs');
2599
+ return this.structuralMismatch<J>('varargs');
2587
2600
  }
2588
2601
 
2589
2602
  // Compare variables
@@ -2643,7 +2656,7 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2643
2656
 
2644
2657
  // Visit type parameters if present
2645
2658
  if (!!methodDeclaration.typeParameters !== !!otherMethodDeclaration.typeParameters) {
2646
- return this.structuralMismatch('typeParameters');
2659
+ return this.structuralMismatch<J>('typeParameters');
2647
2660
  }
2648
2661
 
2649
2662
  if (methodDeclaration.typeParameters && otherMethodDeclaration.typeParameters) {
@@ -2668,22 +2681,22 @@ export class JavaScriptSemanticComparatorVisitor extends JavaScriptComparatorVis
2668
2681
  if (!this.match) return methodDeclaration;
2669
2682
 
2670
2683
  // Compare parameters
2671
- await this.visitContainer(methodDeclaration.parameters, otherMethodDeclaration.parameters as any);
2684
+ await this.visitContainerProperty('parameters', methodDeclaration.parameters, otherMethodDeclaration.parameters);
2672
2685
  if (!this.match) return methodDeclaration;
2673
2686
 
2674
2687
  // Visit throws if present
2675
2688
  if (!!methodDeclaration.throws !== !!otherMethodDeclaration.throws) {
2676
- return this.structuralMismatch('throws');
2689
+ return this.structuralMismatch<J>('throws');
2677
2690
  }
2678
2691
 
2679
2692
  if (methodDeclaration.throws && otherMethodDeclaration.throws) {
2680
- await this.visitContainer(methodDeclaration.throws, otherMethodDeclaration.throws as any);
2693
+ await this.visitContainerProperty('throws', methodDeclaration.throws, otherMethodDeclaration.throws);
2681
2694
  if (!this.match) return methodDeclaration;
2682
2695
  }
2683
2696
 
2684
2697
  // Visit body if present
2685
2698
  if (!!methodDeclaration.body !== !!otherMethodDeclaration.body) {
2686
- return this.structuralMismatch('body');
2699
+ return this.structuralMismatch<J>('body');
2687
2700
  }
2688
2701
 
2689
2702
  if (methodDeclaration.body && otherMethodDeclaration.body) {