@openrewrite/recipes-angular 1.35.0 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/index.d.ts +8 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +38 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/libraries/components/package-version.d.ts +1 -1
  6. package/dist/libraries/components/package-version.d.ts.map +1 -1
  7. package/dist/libraries/components/package-version.js +1 -1
  8. package/dist/libraries/components/package-version.js.map +1 -1
  9. package/dist/migration/add-static-false-to-view-queries.d.ts.map +1 -1
  10. package/dist/migration/add-static-false-to-view-queries.js +16 -13
  11. package/dist/migration/add-static-false-to-view-queries.js.map +1 -1
  12. package/dist/migration/angular-version.d.ts +22 -2
  13. package/dist/migration/angular-version.d.ts.map +1 -1
  14. package/dist/migration/angular-version.js +65 -18
  15. package/dist/migration/angular-version.js.map +1 -1
  16. package/dist/migration/jasmine-to-vitest/add-vitest-imports.d.ts +11 -0
  17. package/dist/migration/jasmine-to-vitest/add-vitest-imports.d.ts.map +1 -0
  18. package/dist/migration/jasmine-to-vitest/add-vitest-imports.js +76 -0
  19. package/dist/migration/jasmine-to-vitest/add-vitest-imports.js.map +1 -0
  20. package/dist/migration/jasmine-to-vitest/migrate-fake-async.d.ts +14 -0
  21. package/dist/migration/jasmine-to-vitest/migrate-fake-async.d.ts.map +1 -0
  22. package/dist/migration/jasmine-to-vitest/migrate-fake-async.js +225 -0
  23. package/dist/migration/jasmine-to-vitest/migrate-fake-async.js.map +1 -0
  24. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.d.ts +11 -0
  25. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.d.ts.map +1 -0
  26. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.js +379 -0
  27. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.js.map +1 -0
  28. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.d.ts +18 -0
  29. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.d.ts.map +1 -0
  30. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.js +446 -0
  31. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.js.map +1 -0
  32. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.d.ts +11 -0
  33. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.d.ts.map +1 -0
  34. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.js +209 -0
  35. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.js.map +1 -0
  36. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.d.ts +11 -0
  37. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.d.ts.map +1 -0
  38. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.js +567 -0
  39. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.js.map +1 -0
  40. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.d.ts +16 -0
  41. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.d.ts.map +1 -0
  42. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.js +90 -0
  43. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.js.map +1 -0
  44. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.d.ts +11 -0
  45. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.d.ts.map +1 -0
  46. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.js +142 -0
  47. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.js.map +1 -0
  48. package/dist/migration/jasmine-to-vitest/support.d.ts +88 -0
  49. package/dist/migration/jasmine-to-vitest/support.d.ts.map +1 -0
  50. package/dist/migration/jasmine-to-vitest/support.js +561 -0
  51. package/dist/migration/jasmine-to-vitest/support.js.map +1 -0
  52. package/dist/migration/upgrade-to-angular-10.d.ts.map +1 -1
  53. package/dist/migration/upgrade-to-angular-10.js +3 -2
  54. package/dist/migration/upgrade-to-angular-10.js.map +1 -1
  55. package/dist/migration/upgrade-to-angular-11.d.ts.map +1 -1
  56. package/dist/migration/upgrade-to-angular-11.js +3 -2
  57. package/dist/migration/upgrade-to-angular-11.js.map +1 -1
  58. package/dist/migration/upgrade-to-angular-12.d.ts.map +1 -1
  59. package/dist/migration/upgrade-to-angular-12.js +3 -2
  60. package/dist/migration/upgrade-to-angular-12.js.map +1 -1
  61. package/dist/migration/upgrade-to-angular-13.d.ts.map +1 -1
  62. package/dist/migration/upgrade-to-angular-13.js +3 -2
  63. package/dist/migration/upgrade-to-angular-13.js.map +1 -1
  64. package/dist/migration/upgrade-to-angular-14.d.ts.map +1 -1
  65. package/dist/migration/upgrade-to-angular-14.js +3 -2
  66. package/dist/migration/upgrade-to-angular-14.js.map +1 -1
  67. package/dist/migration/upgrade-to-angular-15.d.ts.map +1 -1
  68. package/dist/migration/upgrade-to-angular-15.js +3 -2
  69. package/dist/migration/upgrade-to-angular-15.js.map +1 -1
  70. package/dist/migration/upgrade-to-angular-16.d.ts.map +1 -1
  71. package/dist/migration/upgrade-to-angular-16.js +3 -2
  72. package/dist/migration/upgrade-to-angular-16.js.map +1 -1
  73. package/dist/migration/upgrade-to-angular-17.d.ts.map +1 -1
  74. package/dist/migration/upgrade-to-angular-17.js +3 -2
  75. package/dist/migration/upgrade-to-angular-17.js.map +1 -1
  76. package/dist/migration/upgrade-to-angular-18.d.ts.map +1 -1
  77. package/dist/migration/upgrade-to-angular-18.js +3 -2
  78. package/dist/migration/upgrade-to-angular-18.js.map +1 -1
  79. package/dist/migration/upgrade-to-angular-19.d.ts.map +1 -1
  80. package/dist/migration/upgrade-to-angular-19.js +3 -2
  81. package/dist/migration/upgrade-to-angular-19.js.map +1 -1
  82. package/dist/migration/upgrade-to-angular-20.d.ts.map +1 -1
  83. package/dist/migration/upgrade-to-angular-20.js +3 -2
  84. package/dist/migration/upgrade-to-angular-20.js.map +1 -1
  85. package/dist/migration/upgrade-to-angular-21.d.ts.map +1 -1
  86. package/dist/migration/upgrade-to-angular-21.js +3 -2
  87. package/dist/migration/upgrade-to-angular-21.js.map +1 -1
  88. package/dist/migration/upgrade-to-angular-22.d.ts.map +1 -1
  89. package/dist/migration/upgrade-to-angular-22.js +3 -2
  90. package/dist/migration/upgrade-to-angular-22.js.map +1 -1
  91. package/dist/migration/upgrade-to-angular-8.d.ts.map +1 -1
  92. package/dist/migration/upgrade-to-angular-8.js +3 -2
  93. package/dist/migration/upgrade-to-angular-8.js.map +1 -1
  94. package/dist/migration/upgrade-to-angular-9.d.ts.map +1 -1
  95. package/dist/migration/upgrade-to-angular-9.js +3 -2
  96. package/dist/migration/upgrade-to-angular-9.js.map +1 -1
  97. package/package.json +1 -1
  98. package/src/index.ts +24 -0
  99. package/src/libraries/components/package-version.ts +2 -2
  100. package/src/migration/add-static-false-to-view-queries.ts +16 -12
  101. package/src/migration/angular-version.ts +65 -16
  102. package/src/migration/jasmine-to-vitest/add-vitest-imports.ts +51 -0
  103. package/src/migration/jasmine-to-vitest/migrate-fake-async.ts +211 -0
  104. package/src/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.ts +346 -0
  105. package/src/migration/jasmine-to-vitest/migrate-jasmine-matchers.ts +410 -0
  106. package/src/migration/jasmine-to-vitest/migrate-jasmine-misc.ts +190 -0
  107. package/src/migration/jasmine-to-vitest/migrate-jasmine-spies.ts +533 -0
  108. package/src/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.ts +72 -0
  109. package/src/migration/jasmine-to-vitest/migrate-jasmine-types.ts +97 -0
  110. package/src/migration/jasmine-to-vitest/support.ts +516 -0
  111. package/src/migration/upgrade-to-angular-10.ts +4 -3
  112. package/src/migration/upgrade-to-angular-11.ts +4 -3
  113. package/src/migration/upgrade-to-angular-12.ts +4 -3
  114. package/src/migration/upgrade-to-angular-13.ts +4 -3
  115. package/src/migration/upgrade-to-angular-14.ts +4 -3
  116. package/src/migration/upgrade-to-angular-15.ts +4 -3
  117. package/src/migration/upgrade-to-angular-16.ts +4 -3
  118. package/src/migration/upgrade-to-angular-17.ts +4 -3
  119. package/src/migration/upgrade-to-angular-18.ts +4 -3
  120. package/src/migration/upgrade-to-angular-19.ts +4 -3
  121. package/src/migration/upgrade-to-angular-20.ts +4 -3
  122. package/src/migration/upgrade-to-angular-21.ts +4 -3
  123. package/src/migration/upgrade-to-angular-22.ts +4 -3
  124. package/src/migration/upgrade-to-angular-8.ts +4 -3
  125. package/src/migration/upgrade-to-angular-9.ts +4 -3
@@ -0,0 +1,97 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ import {ExecutionContext, Recipe, TreeVisitor, randomId} from "@openrewrite/rewrite";
8
+ import {J, TextComment, isFieldAccess} from "@openrewrite/rewrite/java";
9
+ import {JS, JavaScriptParser, maybeBind} from "@openrewrite/rewrite/javascript";
10
+ import {JasmineToVitestVisitor, freshIds, isJasmineTestFile, isNamed, isTypePosition} from "./support";
11
+
12
+ /**
13
+ * @see https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/refactor/jasmine-vitest/transformers/jasmine-type.ts
14
+ */
15
+ export class MigrateJasmineTypesToVitest extends Recipe {
16
+ readonly name = "org.openrewrite.angular.migration.migrate-jasmine-types-to-vitest";
17
+ readonly displayName = "Migrate Jasmine types to Vitest";
18
+ readonly description = "Rewrites the `jasmine` namespace's types in Angular tests: `jasmine.Spy` becomes Vitest's " +
19
+ "`Mock` and `jasmine.SpyObj<T>` its `MockedObject<T>`, both imported with `import type` from `vitest`; " +
20
+ "`jasmine.Any` becomes `any`, `jasmine.ObjectContaining<T>` becomes `Partial<T>` (`object` without a type " +
21
+ "argument), and `jasmine.DoneFn` becomes `() => void`. A `/// <reference>` to the Jasmine types is removed.";
22
+
23
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
24
+ return new TypesVisitor();
25
+ }
26
+ }
27
+
28
+ /** `/// <reference types="jasmine" />` and `/// <reference path=".../@types/jasmine/index.d.ts" />`. */
29
+ const JASMINE_REFERENCE = /^\/\s*<reference\s+(types\s*=\s*["']jasmine["']|path\s*=\s*["'][^"']*@types\/jasmine\/[^"']*["'])\s*\/>\s*$/;
30
+
31
+ class TypesVisitor extends JasmineToVitestVisitor {
32
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
33
+ const visited = await super.visitJsCompilationUnit(cu, p);
34
+ // The base visitor returns a file that is not a Jasmine test unchanged.
35
+ if (!visited || visited.kind !== JS.Kind.CompilationUnit || !isJasmineTestFile(cu)) return visited;
36
+ const unit = visited as JS.CompilationUnit;
37
+ const comments = unit.prefix.comments.filter(c => !(c.kind === J.Kind.TextComment
38
+ && !(c as TextComment).multiline && JASMINE_REFERENCE.test((c as TextComment).text)));
39
+ if (comments.length === unit.prefix.comments.length) return visited;
40
+ return {...unit, prefix: {...unit.prefix, comments}} as J;
41
+ }
42
+
43
+ protected override async visitFieldAccess(fieldAccess: J.FieldAccess, p: ExecutionContext): Promise<J | undefined> {
44
+ const parent = this.cursor.parentTree()?.value;
45
+ const visited = await super.visitFieldAccess(fieldAccess, p);
46
+ if (!visited || !isFieldAccess(visited) || !isNamed(visited.target, 'jasmine') || !isTypePosition(this.cursor)) {
47
+ return visited;
48
+ }
49
+ const generic = parent?.kind === J.Kind.ParameterizedType && (parent as J.ParameterizedType).class === fieldAccess
50
+ && !!(parent as J.ParameterizedType).typeParameters?.elements.length;
51
+ switch (visited.name.element.simpleName) {
52
+ case 'Spy':
53
+ return this.vitestType(visited, 'Mock');
54
+ case 'SpyObj':
55
+ return this.vitestType(visited, 'MockedObject');
56
+ case 'Any':
57
+ return typeName(visited, 'any');
58
+ case 'ObjectContaining':
59
+ return typeName(visited, generic ? 'Partial' : 'object');
60
+ case 'DoneFn':
61
+ return {...freshIds(await parsedType('() => void')), prefix: visited.prefix} as J;
62
+ }
63
+ return visited;
64
+ }
65
+
66
+ private vitestType(f: J.FieldAccess, member: string): J {
67
+ const local = maybeBind(this, {module: 'vitest', member, typeOnly: true, onlyIfReferenced: false}) ?? member;
68
+ return typeName(f, local);
69
+ }
70
+ }
71
+
72
+ const parsedTypes = new Map<string, J>();
73
+
74
+ /** The tree the parser makes of a type, such as the function type `() => void`. */
75
+ async function parsedType(text: string): Promise<J> {
76
+ let type = parsedTypes.get(text);
77
+ if (!type) {
78
+ for await (const cu of new JavaScriptParser().parse({text: `let t: ${text};`, sourcePath: 'type.ts'})) {
79
+ const declarations = (cu as JS.CompilationUnit).statements[0].element as J.VariableDeclarations;
80
+ type = (declarations.typeExpression as JS.TypeInfo).typeIdentifier as J;
81
+ }
82
+ parsedTypes.set(text, type!);
83
+ }
84
+ return type!;
85
+ }
86
+
87
+ /** A type named in place of `jasmine.X`. The parser holds keyword types such as `any` as identifiers too. */
88
+ function typeName(f: J.FieldAccess, name: string): J.Identifier {
89
+ return {
90
+ kind: J.Kind.Identifier,
91
+ id: randomId(),
92
+ prefix: f.prefix,
93
+ markers: f.markers,
94
+ annotations: [],
95
+ simpleName: name,
96
+ } as unknown as J.Identifier;
97
+ }
@@ -0,0 +1,516 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ /**
8
+ * What the Jasmine to Vitest recipes share: which files they touch, how they read Jasmine's
9
+ * call shapes, and how they leave a `// TODO: vitest-migration:` note for a person, the way the
10
+ * Angular CLI's `refactor-jasmine-vitest` schematic does.
11
+ */
12
+
13
+ import {Cursor, ExecutionContext, printer, randomId} from "@openrewrite/rewrite";
14
+ import {Comment, J, TextComment, isIdentifier, isLiteral, isMethodInvocation} from "@openrewrite/rewrite/java";
15
+ import {JS, JavaScriptVisitor, raw, template} from "@openrewrite/rewrite/javascript";
16
+ import {create} from "mutative";
17
+
18
+ export const ANGULAR_CORE_TESTING = '@angular/core/testing';
19
+
20
+ /**
21
+ * A spec file, or a helper of one: a TypeScript source that names the `jasmine` global. A file that
22
+ * names `jest` is a Jest suite, which these recipes leave to the Jest migration. Protractor's end-to-end
23
+ * specs (`*.e2e-spec.ts`, `*.e2e.spec.ts`, under `e2e/`, or importing `protractor` or `selenium-webdriver`) keep running
24
+ * on Jasmine, so they are left too.
25
+ */
26
+ export function isJasmineTestFile(cu: JS.CompilationUnit): boolean {
27
+ const path = cu.sourcePath.replace(/\\/g, '/');
28
+ if (!/\.[cm]?tsx?$/.test(path) || /\.d\.[cm]?ts$/.test(path) || /(^|\/)node_modules\//.test(path)) {
29
+ return false;
30
+ }
31
+ if (/\.e2e[-.]spec\.[cm]?tsx?$/.test(path) || /(^|\/)e2e\//.test(path)) {
32
+ return false;
33
+ }
34
+ const names = identifierNames(cu);
35
+ if (names.has('jest') || importsEndToEndDriver(cu)) {
36
+ return false;
37
+ }
38
+ return /\.spec\.[cm]?tsx?$/.test(path) || names.has('jasmine');
39
+ }
40
+
41
+ function importsEndToEndDriver(cu: JS.CompilationUnit): boolean {
42
+ let found = false;
43
+ walk(cu, n => {
44
+ if (n.kind === J.Kind.Literal && typeof n.value === 'string' && /^(protractor|selenium-webdriver)(\/|$)/.test(n.value)) {
45
+ found = true;
46
+ }
47
+ });
48
+ return found;
49
+ }
50
+
51
+ function identifierNames(tree: any): Set<string> {
52
+ const names = new Set<string>();
53
+ walk(tree, n => {
54
+ if (n.kind === J.Kind.Identifier) {
55
+ names.add(n.simpleName);
56
+ }
57
+ });
58
+ return names;
59
+ }
60
+
61
+ /** Visits every LST node below `tree`, types and markers excepted. */
62
+ export function walk(tree: any, fn: (node: any) => boolean | void): void {
63
+ const stack = [tree];
64
+ while (stack.length) {
65
+ const n = stack.pop();
66
+ if (!n || typeof n !== 'object') continue;
67
+ if (Array.isArray(n)) {
68
+ for (let i = n.length - 1; i >= 0; i--) stack.push(n[i]);
69
+ continue;
70
+ }
71
+ if (typeof n.kind === 'string') {
72
+ if (n.kind.includes('JavaType') || n.kind.endsWith('Markers')) continue;
73
+ if (fn(n) === false) continue;
74
+ }
75
+ for (const key in n) {
76
+ if (key === 'type' || key === 'methodType' || key === 'fieldType' || key === 'variableType'
77
+ || key === 'constructorType' || key === 'markers' || key === 'prefix') continue;
78
+ const v = n[key];
79
+ if (v && typeof v === 'object') stack.push(v);
80
+ }
81
+ }
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------------------------
85
+ // Reading Jasmine shapes
86
+
87
+ /** Parentheses, `as`, `satisfies` and `<T>` casts do not change what an expression evaluates to. */
88
+ export function unwrap(e: J | undefined): J | undefined {
89
+ let current = e;
90
+ while (current) {
91
+ if (current.kind === J.Kind.Parentheses) {
92
+ current = (current as J.Parentheses<J>).tree.element;
93
+ } else if (current.kind === JS.Kind.As) {
94
+ current = (current as JS.As).left.element;
95
+ } else if (current.kind === JS.Kind.SatisfiesExpression) {
96
+ current = (current as JS.SatisfiesExpression).expression;
97
+ } else if (current.kind === J.Kind.TypeCast) {
98
+ current = (current as J.TypeCast).expression;
99
+ } else {
100
+ break;
101
+ }
102
+ }
103
+ return current;
104
+ }
105
+
106
+ export function isTransparentWrapper(n: any): boolean {
107
+ return n?.kind === J.Kind.Parentheses || n?.kind === JS.Kind.As || n?.kind === JS.Kind.SatisfiesExpression
108
+ || n?.kind === J.Kind.TypeCast;
109
+ }
110
+
111
+ export function isNamed(e: J | undefined, name: string): boolean {
112
+ return !!e && isIdentifier(e) && e.simpleName === name;
113
+ }
114
+
115
+ /** `name(...)`, a call of a global by its bare name. */
116
+ export function isGlobalCall(e: J | undefined, ...names: string[]): e is J.MethodInvocation {
117
+ return !!e && isMethodInvocation(e) && !e.select && names.includes(e.name.simpleName);
118
+ }
119
+
120
+ /** The member a `jasmine.member(...)` call names, if it is one. */
121
+ export function jasmineMethodName(e: J | undefined): string | undefined {
122
+ if (e && isMethodInvocation(e) && e.select && isNamed(e.select.element, 'jasmine')) {
123
+ return e.name.simpleName;
124
+ }
125
+ return undefined;
126
+ }
127
+
128
+ export function args(m: J.MethodInvocation): J[] {
129
+ return m.arguments.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
130
+ }
131
+
132
+ export function select(m: J.MethodInvocation): J | undefined {
133
+ return m.select?.element;
134
+ }
135
+
136
+ export function isStringLiteral(e: J | undefined): e is J.Literal {
137
+ return !!e && isLiteral(e) && typeof e.value === 'string';
138
+ }
139
+
140
+ export function isFunctionLike(e: J | undefined): boolean {
141
+ return !!e && (e.kind === JS.Kind.ArrowFunction || functionExpression(e) !== undefined);
142
+ }
143
+
144
+ /** The method declaration a `function () {}` expression is made of. */
145
+ export function functionExpression(e: J | undefined): J.MethodDeclaration | undefined {
146
+ if (e?.kind === JS.Kind.StatementExpression) {
147
+ const s = (e as JS.StatementExpression).statement;
148
+ if (s.kind === J.Kind.MethodDeclaration) return s as J.MethodDeclaration;
149
+ }
150
+ return undefined;
151
+ }
152
+
153
+ /** The parameter names of an arrow function or function expression. */
154
+ export function parameterNames(fn: J): (string | undefined)[] {
155
+ const params: J[] = fn.kind === JS.Kind.ArrowFunction
156
+ ? (fn as JS.ArrowFunction).lambda.parameters.parameters.map(p => p.element)
157
+ : functionExpression(fn)!.parameters.elements.map(p => p.element);
158
+ return params.filter(p => p.kind !== J.Kind.Empty).map(p => {
159
+ if (p.kind === J.Kind.VariableDeclarations) {
160
+ const v = (p as J.VariableDeclarations).variables;
161
+ if (v.length === 1 && isIdentifier(v[0].element.name)) return v[0].element.name.simpleName;
162
+ return undefined;
163
+ }
164
+ return isIdentifier(p) ? p.simpleName : undefined;
165
+ });
166
+ }
167
+
168
+ /** The body of an arrow function or function expression: a block, or the expression of an arrow. */
169
+ export function functionBody(fn: J): J | undefined {
170
+ if (fn.kind === JS.Kind.ArrowFunction) return (fn as JS.ArrowFunction).lambda.body;
171
+ return functionExpression(fn)?.body;
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------------------------
175
+ // Building code
176
+
177
+ /** `{ ... }` written as a template parses as a block, so it is written `(...)` and unwrapped here. */
178
+ export function unparenthesize(result: J): J {
179
+ if (result.kind === J.Kind.Parentheses) {
180
+ const p = result as J.Parentheses<J>;
181
+ return {...p.tree.element, prefix: p.prefix} as J;
182
+ }
183
+ return result;
184
+ }
185
+
186
+ export async function printTrimmed(tree: J, cursor: Cursor): Promise<string> {
187
+ const withoutPrefix = create(tree as any, (d: any) => {
188
+ d.prefix = {kind: J.Kind.Space, comments: [], whitespace: ''};
189
+ }) as J;
190
+ return (await printer(cursor).print(withoutPrefix, undefined, cursor)).trim();
191
+ }
192
+
193
+ // ---------------------------------------------------------------------------------------------
194
+ // TODO notes for a person
195
+
196
+ const TODO_PREFIX = ' TODO: vitest-migration: ';
197
+
198
+ export function todoText(message: string, url?: string): string {
199
+ return `${TODO_PREFIX}${message}${url ? ` See: ${url}` : ''}`;
200
+ }
201
+
202
+ /** What a statement-level transformation does with the statement in a block. */
203
+ export type StatementResult =
204
+ | { replace: J[] }
205
+ /** Drops the statement and leaves the given comment lines (without `//`) where it was. */
206
+ | { removeLeaving: string[] };
207
+
208
+ /**
209
+ * A visitor for test files that the Jasmine to Vitest recipes extend. It skips files that are not
210
+ * Jasmine tests, lets a recipe note a TODO on any node, and writes each note as a line comment on
211
+ * the statement that holds the node, the statement a block or the file lists directly.
212
+ */
213
+ export abstract class JasmineToVitestVisitor extends JavaScriptVisitor<ExecutionContext> {
214
+ private readonly todos = new Map<string, string[]>();
215
+
216
+ /** Notes a TODO on `node`, which is placed before the statement holding it once that is visited. */
217
+ protected todo(node: J, message: string, url?: string): void {
218
+ const notes = this.todos.get(node.id) ?? [];
219
+ notes.push(todoText(message, url));
220
+ this.todos.set(node.id, notes);
221
+ }
222
+
223
+ /** Statement-level rewrites, which can drop a statement or split it in two. */
224
+ protected async visitBlockStatement(_statement: J, _cursor: Cursor): Promise<StatementResult | undefined> {
225
+ return undefined;
226
+ }
227
+
228
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
229
+ if (!isJasmineTestFile(cu)) {
230
+ return cu;
231
+ }
232
+ const visited = await super.visitJsCompilationUnit(cu, p) as JS.CompilationUnit;
233
+ if (!visited || visited.kind !== JS.Kind.CompilationUnit) return visited;
234
+ const [statements, eof] = await this.finishStatements(visited.statements, visited.eof, visited.prefix);
235
+ if (statements === visited.statements && eof === visited.eof) return visited;
236
+ return create(visited, d => {
237
+ d.statements = statements as any;
238
+ d.eof = eof as any;
239
+ });
240
+ }
241
+
242
+ override async visitBlock(block: J.Block, p: ExecutionContext): Promise<J | undefined> {
243
+ const visited = await super.visitBlock(block, p);
244
+ if (!visited || visited.kind !== J.Kind.Block) return visited;
245
+ const b = visited as J.Block;
246
+ const [statements, end] = await this.finishStatements(b.statements, b.end);
247
+ if (statements === b.statements && end === b.end) return b;
248
+ return create(b, d => {
249
+ d.statements = statements as any;
250
+ d.end = end as any;
251
+ });
252
+ }
253
+
254
+ private async finishStatements(statements: J.RightPadded<J>[], end: J.Space, filePrefix?: J.Space): Promise<[J.RightPadded<J>[], J.Space]> {
255
+ const out: J.RightPadded<J>[] = [];
256
+ // Comment lines left by a removed statement, waiting for the next statement or the block end.
257
+ let carried: { prefix: J.Space, lines: string[] } | undefined;
258
+ for (const rp of statements) {
259
+ let statement = rp.element;
260
+ const result = await this.visitBlockStatement(statement, new Cursor(statement, this.cursor));
261
+ let replacement: J[] = [statement];
262
+ if (result && 'removeLeaving' in result) {
263
+ carried = mergeCarried(carried, statement.prefix, result.removeLeaving);
264
+ continue;
265
+ } else if (result) {
266
+ replacement = result.replace;
267
+ }
268
+ for (let i = 0; i < replacement.length; i++) {
269
+ let s = replacement[i];
270
+ if (i === 0 && s !== statement) {
271
+ // The first replacement takes the statement's place, and so its leading whitespace: a template
272
+ // reindents the result for where it thinks it is, which inside a callback such as `inject(...)`'s is not here.
273
+ s = create(s as any, (d: any) => {
274
+ d.prefix = statement.prefix;
275
+ }) as J;
276
+ }
277
+ if (i > 0) {
278
+ s = freshIds(s);
279
+ s = create(s as any, (d: any) => {
280
+ d.prefix = {kind: J.Kind.Space, comments: [], whitespace: '\n' + indentOf(statement.prefix)};
281
+ }) as J;
282
+ }
283
+ const notes = await this.collectTodos(s, out.length === 0 ? filePrefix : undefined);
284
+ if (notes.length) {
285
+ s = withLeadingComments(s, notes);
286
+ }
287
+ if (carried) {
288
+ s = create(s as any, (d: any) => {
289
+ d.prefix = prependCarried(carried!, s.prefix);
290
+ }) as J;
291
+ carried = undefined;
292
+ }
293
+ out.push(i > 0 ? freshIds({...rp, element: s}) as any : s === statement ? rp : {...rp, element: s});
294
+ }
295
+ }
296
+ const newEnd = carried ? prependCarried(carried, end) : end;
297
+ const unchanged = newEnd === end && out.length === statements.length && out.every((rp, i) => rp === statements[i]);
298
+ return unchanged ? [statements, end] : [out, newEnd];
299
+ }
300
+
301
+ private async collectTodos(statement: J, filePrefix?: J.Space): Promise<string[]> {
302
+ if (this.todos.size === 0) return [];
303
+ const found: string[] = [];
304
+ walk(statement, n => {
305
+ const notes = this.todos.get(n.id);
306
+ if (notes) {
307
+ found.push(...notes);
308
+ this.todos.delete(n.id);
309
+ }
310
+ });
311
+ if (found.length === 0) return [];
312
+ // Each note once, and none the statement already carries from an earlier run. The parser can
313
+ // hold a statement's leading comments on its leftmost node, so they are read off the text.
314
+ const existing = (filePrefix?.comments ?? []).map(c => '//' + (c as TextComment).text).join('\n') + '\n'
315
+ + await leadingCommentText(statement, this.cursor);
316
+ return [...new Set(found)].filter(n => !existing.includes('//' + n));
317
+ }
318
+ }
319
+
320
+ function indentOf(prefix: J.Space): string {
321
+ const last = prefix.comments.length ? prefix.comments[prefix.comments.length - 1].suffix : prefix.whitespace;
322
+ const nl = last.lastIndexOf('\n');
323
+ return nl >= 0 ? last.substring(nl + 1) : '';
324
+ }
325
+
326
+ function lineComment(text: string, suffix: string): TextComment {
327
+ return {kind: J.Kind.TextComment, multiline: false, text, suffix, markers: {kind: "org.openrewrite.marker.Markers", id: randomId(), markers: []}} as any;
328
+ }
329
+
330
+ /**
331
+ * Puts `// line` comments right before what `prefix` leads into, after the comments it already
332
+ * holds and on the same indentation.
333
+ */
334
+ function appendLines(prefix: J.Space, lines: string[], indent: string): J.Space {
335
+ if (!lines.length) return prefix;
336
+ const comments: Comment[] = [...prefix.comments];
337
+ const nl = '\n' + indent;
338
+ const finalSuffix = comments.length ? comments[comments.length - 1].suffix : nl;
339
+ if (comments.length) {
340
+ comments[comments.length - 1] = {...comments[comments.length - 1], suffix: nl} as any;
341
+ }
342
+ lines.forEach((l, i) => comments.push(lineComment(l, i === lines.length - 1 ? finalSuffix : nl)));
343
+ return {kind: J.Kind.Space, whitespace: prefix.whitespace, comments} as J.Space;
344
+ }
345
+
346
+ function withLeadingComments(statement: J, notes: string[]): J {
347
+ return create(statement as any, (d: any) => {
348
+ d.prefix = appendLines(statement.prefix, notes, indentOf(statement.prefix));
349
+ }) as J;
350
+ }
351
+
352
+ function mergeCarried(carried: { prefix: J.Space, lines: string[] } | undefined, prefix: J.Space, lines: string[])
353
+ : { prefix: J.Space, lines: string[] } {
354
+ if (!carried) return {prefix, lines};
355
+ return {prefix: carried.prefix, lines: [...carried.lines, ...prefix.comments.map(c => (c as TextComment).text), ...lines]};
356
+ }
357
+
358
+ /**
359
+ * Where a statement was removed: its own prefix and the lines it left, then whatever came before
360
+ * the next statement (or the end of the block), which keeps its indentation.
361
+ */
362
+ function prependCarried(carried: { prefix: J.Space, lines: string[] }, next: J.Space): J.Space {
363
+ const indent = indentOf(carried.prefix);
364
+ const nl = '\n' + indent;
365
+ const withLines = appendLines(carried.prefix, carried.lines, indent);
366
+ const comments = [...withLines.comments];
367
+ // The last line leads into what followed the removed statement.
368
+ const lastSuffix = next.whitespace.includes('\n') ? next.whitespace : nl;
369
+ comments[comments.length - 1] = {...comments[comments.length - 1], suffix: lastSuffix} as any;
370
+ comments.push(...next.comments);
371
+ return {kind: J.Kind.Space, whitespace: carried.prefix.whitespace, comments} as J.Space;
372
+ }
373
+
374
+ // ---------------------------------------------------------------------------------------------
375
+ // Templates assembled from pieces
376
+
377
+ export type Piece = string | J | J[] | ReturnType<typeof raw>;
378
+
379
+ /** A template from alternating code and trees: `code('vi.mocked(', spy, ').mock')`. */
380
+ export function code(...pieces: Piece[]): ReturnType<typeof template> {
381
+ const strings: string[] = [''];
382
+ const params: any[] = [];
383
+ for (const piece of pieces) {
384
+ if (typeof piece === 'string') {
385
+ strings[strings.length - 1] += piece;
386
+ } else {
387
+ params.push(piece);
388
+ strings.push('');
389
+ }
390
+ }
391
+ const tsa: any = [...strings];
392
+ tsa.raw = [...strings];
393
+ return template(tsa as TemplateStringsArray, ...params);
394
+ }
395
+
396
+ /** Applies a template in place of `tree`, keeping the place's leading whitespace and comments. */
397
+ export async function replaceWith(tree: J, cursor: Cursor, ...pieces: Piece[]): Promise<J> {
398
+ const result = unparenthesize((await code(...pieces).apply(tree, cursor))!);
399
+ return result;
400
+ }
401
+
402
+ export function hasMarker(tree: J, kind: string): boolean {
403
+ return tree.markers.markers.some(m => m.kind === kind);
404
+ }
405
+
406
+ /** The quote the file writes its strings with, for the string literals a recipe adds. */
407
+ export function quoteOf(cu: JS.CompilationUnit): string {
408
+ let quote: string | undefined;
409
+ walk(cu, n => {
410
+ if (quote) return false;
411
+ if (n.kind === J.Kind.Literal && typeof n.value === 'string' && typeof n.valueSource === 'string') {
412
+ const q = n.valueSource.charAt(0);
413
+ if (q === "'" || q === '"') quote = q;
414
+ }
415
+ });
416
+ return quote ?? "'";
417
+ }
418
+
419
+ export function stringLiteral(value: string, quote: string): string {
420
+ return quote + value.replace(/\\/g, '\\\\').replace(new RegExp(quote, 'g'), '\\' + quote) + quote;
421
+ }
422
+
423
+ /**
424
+ * Whether the cursor's node is part of a type, where `jasmine.Foo` names a type rather than a
425
+ * value: an annotation, a type argument, or the type of an `as` or a cast.
426
+ */
427
+ export function isTypePosition(cursor: Cursor): boolean {
428
+ let prev: any = cursor.value;
429
+ for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
430
+ const v = c.value;
431
+ const kind = v?.kind;
432
+ if (typeof kind !== 'string' || kind.endsWith('RightPadded') || kind.endsWith('LeftPadded') || kind.endsWith('Container')) {
433
+ continue;
434
+ }
435
+ if (kind === JS.Kind.TypeInfo || kind === J.Kind.ParameterizedType || kind === JS.Kind.TypeOf
436
+ || kind === J.Kind.TypeParameter || kind === JS.Kind.TypeDeclaration) return true;
437
+ if (kind === JS.Kind.As) return (v as JS.As).right === prev;
438
+ if (kind === J.Kind.TypeCast) return (v as J.TypeCast).class?.tree?.element === prev;
439
+ if (kind === J.Kind.MethodInvocation || kind === J.Kind.NewClass) {
440
+ return !!v.typeParameters?.elements?.some((e: any) => e.element === prev);
441
+ }
442
+ if (kind === J.Kind.Block || kind === JS.Kind.CompilationUnit) return false;
443
+ prev = v;
444
+ }
445
+ return false;
446
+ }
447
+
448
+ /**
449
+ * Keeps a dropped statement's leading comments: they move in front of the statement that followed
450
+ * it, or to the end of the block.
451
+ */
452
+ export function carryComments(dropped: J.Space, next: J.Space): J.Space {
453
+ if (dropped.comments.length === 0) return next;
454
+ const comments = [...dropped.comments];
455
+ comments[comments.length - 1] = {...comments[comments.length - 1], suffix: next.whitespace} as any;
456
+ return {kind: J.Kind.Space, whitespace: dropped.whitespace, comments: [...comments, ...next.comments]} as J.Space;
457
+ }
458
+
459
+ /** The block without the statements `drop` picks, their comments kept and an emptied block written `{}`. */
460
+ export function withoutStatements(block: J.Block, drop: (s: J) => boolean): J.Block {
461
+ const kept: J.RightPadded<J>[] = [];
462
+ let pending: J.Space | undefined;
463
+ for (const rp of block.statements) {
464
+ if (drop(rp.element)) {
465
+ pending = pending ? carryComments(pending, rp.element.prefix) : rp.element.prefix;
466
+ continue;
467
+ }
468
+ if (pending) {
469
+ kept.push({...rp, element: {...rp.element, prefix: carryComments(pending, rp.element.prefix)}} as any);
470
+ pending = undefined;
471
+ } else {
472
+ kept.push(rp);
473
+ }
474
+ }
475
+ let end = block.end;
476
+ if (pending) end = carryComments(pending, end);
477
+ if (kept.length === 0 && end.comments.length === 0) {
478
+ end = {kind: J.Kind.Space, comments: [], whitespace: ''} as J.Space;
479
+ }
480
+ return create(block, d => {
481
+ d.statements = kept as any;
482
+ d.end = end as any;
483
+ });
484
+ }
485
+
486
+ /** The comment lines a statement's printed text starts with. */
487
+ async function leadingCommentText(statement: J, cursor: Cursor): Promise<string> {
488
+ const text = await printer(cursor).print(statement, undefined, cursor);
489
+ const lines: string[] = [];
490
+ for (const line of text.split('\n')) {
491
+ const t = line.trim();
492
+ if (t === '' || t.startsWith('//') || t.startsWith('/*') || t.startsWith('*')) {
493
+ lines.push(t);
494
+ } else {
495
+ break;
496
+ }
497
+ }
498
+ return lines.join('\n');
499
+ }
500
+
501
+ /** A copy of `tree` whose nodes all have new ids, for a subtree used a second time. */
502
+ export function freshIds<T>(tree: T): T {
503
+ const copy = (n: any): any => {
504
+ if (!n || typeof n !== 'object') return n;
505
+ if (Array.isArray(n)) return n.map(copy);
506
+ if (typeof n.kind === 'string' && n.kind.includes('JavaType')) return n;
507
+ const out: any = {};
508
+ for (const key in n) {
509
+ const v = n[key];
510
+ out[key] = key === 'id' && typeof v === 'string' ? randomId()
511
+ : (key === 'type' || key === 'methodType' || key === 'fieldType' || key === 'variableType') ? v : copy(v);
512
+ }
513
+ return out;
514
+ };
515
+ return copy(tree);
516
+ }
@@ -13,7 +13,7 @@ import {ReplaceValidatorWithValidators} from "./replace-validator-with-validator
13
13
  import {MigrateToSolutionStyleTsconfig} from "./migrate-to-solution-style-tsconfig";
14
14
  import {RenameFile} from "./rename-file";
15
15
  import {UpgradeToMaterial10CodeChanges} from "../libraries/material/upgrade-to-material";
16
- import {beforeAngular} from "./angular-version";
16
+ import {beforeAngular, upgradeToAngular} from "./angular-version";
17
17
 
18
18
  export class UpgradeToAngular10CodeChanges extends Recipe {
19
19
  readonly name = "org.openrewrite.angular.UpgradeToAngular10CodeChanges";
@@ -51,8 +51,9 @@ export class UpgradeToAngular10 extends Recipe {
51
51
  " It includes the Angular Material code changes of version 10.";
52
52
 
53
53
  async recipeList(): Promise<Recipe[]> {
54
- return [
54
+ return upgradeToAngular(10, [
55
55
  new UpgradeToAngular10CodeChanges(),
56
+ ], [
56
57
  // Resolve the aligned Angular, DevKit and compiler upgrades as one dependency edit.
57
58
  await upgradeAngularDependencies(10, {
58
59
  "@angular-devkit/core": "10.x",
@@ -66,6 +67,6 @@ export class UpgradeToAngular10 extends Recipe {
66
67
  "typescript": "3.9.x",
67
68
  "tslib": "2.x",
68
69
  }),
69
- ];
70
+ ]);
70
71
  }
71
72
  }
@@ -18,7 +18,7 @@ import {ReplacePreserveQueryParams} from "./replace-preserve-query-params";
18
18
  import {ReplaceAsyncWithWaitForAsync} from "./replace-async-with-wait-for-async";
19
19
  import {FindAsyncTestHelperUsage} from "../search/find-async-test-helper-usage";
20
20
  import {UpgradeToMaterial11CodeChanges} from "../libraries/material/upgrade-to-material";
21
- import {beforeAngular} from "./angular-version";
21
+ import {beforeAngular, upgradeToAngular} from "./angular-version";
22
22
 
23
23
  export class UpgradeToAngular11CodeChanges extends Recipe {
24
24
  readonly name = "org.openrewrite.angular.UpgradeToAngular11CodeChanges";
@@ -64,8 +64,9 @@ export class UpgradeToAngular11 extends Recipe {
64
64
  " It includes the Angular Material code changes of version 11.";
65
65
 
66
66
  async recipeList(): Promise<Recipe[]> {
67
- return [
67
+ return upgradeToAngular(11, [
68
68
  new UpgradeToAngular11CodeChanges(),
69
+ ], [
69
70
  // Resolve the aligned Angular, DevKit and compiler upgrades as one dependency edit.
70
71
  await upgradeAngularDependencies(11, {
71
72
  "@angular-devkit/core": "11.x",
@@ -79,6 +80,6 @@ export class UpgradeToAngular11 extends Recipe {
79
80
  "typescript": "4.0.x",
80
81
  "tslib": "2.x",
81
82
  }),
82
- ];
83
+ ]);
83
84
  }
84
85
  }