@openrewrite/recipes-angular 1.33.0 → 1.34.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 (50) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +35 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/libraries/components/lst.d.ts +7 -0
  6. package/dist/libraries/components/lst.d.ts.map +1 -1
  7. package/dist/libraries/components/lst.js +11 -0
  8. package/dist/libraries/components/lst.js.map +1 -1
  9. package/dist/libraries/components/package-version.d.ts +7 -2
  10. package/dist/libraries/components/package-version.d.ts.map +1 -1
  11. package/dist/libraries/components/package-version.js +5 -3
  12. package/dist/libraries/components/package-version.js.map +1 -1
  13. package/dist/libraries/components/symbols.d.ts +3 -0
  14. package/dist/libraries/components/symbols.d.ts.map +1 -1
  15. package/dist/libraries/components/symbols.js +8 -0
  16. package/dist/libraries/components/symbols.js.map +1 -1
  17. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.d.ts +127 -0
  18. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.d.ts.map +1 -0
  19. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.js +708 -0
  20. package/dist/libraries/ng-inline-svg/migrate-ng-inline-svg.js.map +1 -0
  21. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.d.ts +60 -0
  22. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.d.ts.map +1 -0
  23. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.js +472 -0
  24. package/dist/libraries/ng2-cookies/migrate-ng2-cookies.js.map +1 -0
  25. package/dist/migration/package-major.d.ts +43 -0
  26. package/dist/migration/package-major.d.ts.map +1 -0
  27. package/dist/migration/package-major.js +100 -0
  28. package/dist/migration/package-major.js.map +1 -0
  29. package/dist/migration/replace-platform-browser-dynamic.d.ts +32 -0
  30. package/dist/migration/replace-platform-browser-dynamic.d.ts.map +1 -0
  31. package/dist/migration/replace-platform-browser-dynamic.js +212 -0
  32. package/dist/migration/replace-platform-browser-dynamic.js.map +1 -0
  33. package/dist/migration/upgrade-to-angular-20.d.ts.map +1 -1
  34. package/dist/migration/upgrade-to-angular-20.js +4 -1
  35. package/dist/migration/upgrade-to-angular-20.js.map +1 -1
  36. package/dist/migration/use-angular-build-builders.d.ts +51 -0
  37. package/dist/migration/use-angular-build-builders.d.ts.map +1 -0
  38. package/dist/migration/use-angular-build-builders.js +280 -0
  39. package/dist/migration/use-angular-build-builders.js.map +1 -0
  40. package/package.json +2 -2
  41. package/src/index.ts +19 -0
  42. package/src/libraries/components/lst.ts +11 -0
  43. package/src/libraries/components/package-version.ts +7 -7
  44. package/src/libraries/components/symbols.ts +7 -0
  45. package/src/libraries/ng-inline-svg/migrate-ng-inline-svg.ts +613 -0
  46. package/src/libraries/ng2-cookies/migrate-ng2-cookies.ts +425 -0
  47. package/src/migration/package-major.ts +93 -0
  48. package/src/migration/replace-platform-browser-dynamic.ts +197 -0
  49. package/src/migration/upgrade-to-angular-20.ts +4 -1
  50. package/src/migration/use-angular-build-builders.ts +285 -0
@@ -0,0 +1,425 @@
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 {Cursor, emptyMarkers, ExecutionContext, foundSearchResult, randomId, Recipe, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {ChangeImport, JavaScriptParser, JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport} from "@openrewrite/rewrite/javascript";
9
+ import {emptySpace, isIdentifier, J, Statement, Type} from "@openrewrite/rewrite/java";
10
+ import {hasSearchResult, withoutSearchResult} from "../components/lst";
11
+ import {importedName, moduleOf, requiredModule} from "../components/symbols";
12
+ import {addDependencyByMajor, caretMajors, removeDependencyUnlessImported, singleMajorScanner} from "../../migration/package-major";
13
+ import {majorFor} from "../components/package-version";
14
+ import {ANGULAR_DECORATORS, unwrapTypeIdentifier} from "../../migration/js-support";
15
+
16
+ const NG2_COOKIES = 'ng2-cookies';
17
+ const NGX_COOKIE_SERVICE = 'ngx-cookie-service';
18
+
19
+ /** The entry points of `ng2-cookies` 1.x, and what each exports. */
20
+ const SERVICE_MODULES = ['ng2-cookies', 'ng2-cookies/index', 'ng2-cookies/cookie', 'ng2-cookies/unmanagedCookie'];
21
+ /** `Cookie` (static methods in `ng2-cookies/ng2-cookies`, an instance elsewhere) and `UnmanagedCookie` are called directly. */
22
+ const DIRECT = new Set(['Cookie', 'UnmanagedCookie']);
23
+ /** The classes that an application injects or instantiates. */
24
+ const SERVICES = ['CookieService', 'UnmanagedCookieService'];
25
+ /** The methods of `ng2-cookies`, which `ngx-cookie-service`'s `CookieService` has with the same leading parameters. */
26
+ const METHODS = new Set(['check', 'get', 'getAll', 'set', 'delete', 'deleteAll']);
27
+
28
+ /** The decorators of the classes Angular instantiates in an injection context, where `inject()` may run. */
29
+ const INJECTABLE_DECORATORS = new Set([...ANGULAR_DECORATORS, 'NgModule']);
30
+ /** `inject()` came in Angular 14. */
31
+ const FIRST_INJECT_MAJOR = 14;
32
+ /**
33
+ * The Angular majors that `ngx-cookie-service` has a release for that writes cookies as `ng2-cookies` did and is provided
34
+ * in the root injector: 3.x for Angular 9, then one release per major in step with Angular. Code is moved only where
35
+ * `MigrateNg2Cookies` adds the release of its major. The 2.x line for Angular 4 to 8 is left out: it is not provided in
36
+ * the root injector, and its `set` writes `SameSite=None` without `Secure`, which browsers reject.
37
+ */
38
+ const FIRST_MAJOR = 9;
39
+ const LAST_MAJOR = 22;
40
+
41
+ const FIELD = 'cookieService';
42
+
43
+ const LEFTOVER = "`ng2-cookies` is unmaintained. Use `CookieService` from `ngx-cookie-service`, which has the same " +
44
+ "methods; outside an instance member of an Angular class, where `inject(CookieService)` cannot provide it, or in " +
45
+ "a project whose Angular major `ngx-cookie-service` has no release for (" + FIRST_MAJOR + " to " + LAST_MAJOR + "), " +
46
+ "or not known from its `package.json`, or one that `ngx-cookie-service` could not be added to, this use was left " +
47
+ "for a hand migration.";
48
+
49
+ const isNg2Cookies = (module: string | undefined) => module === NG2_COOKIES || !!module?.startsWith(`${NG2_COOKIES}/`);
50
+
51
+ /** The `{...}` bindings of an import, as imported name and local name. */
52
+ function bindings(imp: JS.Import): {imported: string, local: string}[] {
53
+ const named = imp.importClause?.namedBindings;
54
+ if (named?.kind !== JS.Kind.NamedImports) return [];
55
+ return (named as JS.NamedImports).elements.elements.flatMap(({element}) => {
56
+ const spec = element as JS.ImportSpecifier;
57
+ const imported = importedName(spec);
58
+ const local = spec.specifier.kind === JS.Kind.Alias ? (spec.specifier as JS.Alias).alias : spec.specifier;
59
+ return imported && isIdentifier(local) ? [{imported, local: local.simpleName}] : [];
60
+ });
61
+ }
62
+
63
+ function decoratorNames(c: J.ClassDeclaration): string[] {
64
+ return c.leadingAnnotations.flatMap(a => isIdentifier(a.annotationType) ? [a.annotationType.simpleName] : []);
65
+ }
66
+
67
+ const isStatic = (modifiers: J.Modifier[]) => modifiers.some(m => m.type === J.ModifierType.Static);
68
+
69
+ /** The names of the members of a class body, its constructor's parameter properties included. */
70
+ function memberNames(c: J.ClassDeclaration): Set<string> {
71
+ const names = new Set<string>();
72
+ for (const {element} of c.body.statements) {
73
+ if (element.kind === J.Kind.VariableDeclarations) {
74
+ for (const v of (element as J.VariableDeclarations).variables) {
75
+ if (isIdentifier(v.element.name)) names.add(v.element.name.simpleName);
76
+ }
77
+ } else if (element.kind === J.Kind.MethodDeclaration) {
78
+ const method = element as J.MethodDeclaration;
79
+ names.add(method.name.simpleName);
80
+ if (method.name.simpleName === 'constructor') {
81
+ for (const {element: param} of method.parameters.elements) {
82
+ if (param.kind !== J.Kind.VariableDeclarations) continue;
83
+ for (const v of (param as J.VariableDeclarations).variables) {
84
+ if (isIdentifier(v.element.name)) names.add(v.element.name.simpleName);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
90
+ // What the class inherits, as far as type attribution knows it.
91
+ for (let t = Type.isClass(c.type) ? c.type.supertype : undefined; t; t = t.supertype) {
92
+ for (const m of [...t.members, ...t.methods]) names.add(m.name);
93
+ }
94
+ return names;
95
+ }
96
+
97
+ /** A member that holds a `CookieService`, and the index of its field in the class body, or -1 for a parameter property. */
98
+ interface ServiceMember {
99
+ name: string;
100
+ index: number;
101
+ }
102
+
103
+ /**
104
+ * The instance member of `cls` that already holds a `CookieService`, if any: a field or constructor parameter property
105
+ * whose type is one of `serviceNames`, or a field initialized with `inject(<one of them>)`.
106
+ */
107
+ function existingService(cls: J.ClassDeclaration, serviceNames: Set<string>): ServiceMember | undefined {
108
+ const typed = (vd: J.VariableDeclarations) => {
109
+ const type = unwrapTypeIdentifier(vd.typeExpression);
110
+ return !!type && isIdentifier(type) && serviceNames.has(type.simpleName);
111
+ };
112
+ const injected = (vd: J.VariableDeclarations) => vd.variables.some(({element: v}) => {
113
+ const init = v.initializer?.element;
114
+ if (init?.kind !== J.Kind.MethodInvocation) return false;
115
+ const call = init as J.MethodInvocation;
116
+ const arg = call.arguments.elements[0]?.element;
117
+ return call.name.simpleName === 'inject' && !call.select && !!arg && isIdentifier(arg) && serviceNames.has(arg.simpleName);
118
+ });
119
+ const nameOf = (vd: J.VariableDeclarations) => {
120
+ const name = vd.variables[0]?.element.name;
121
+ return name && isIdentifier(name) ? name.simpleName : undefined;
122
+ };
123
+ const statements = cls.body.statements;
124
+ for (let index = 0; index < statements.length; index++) {
125
+ const element = statements[index].element;
126
+ if (element.kind === J.Kind.VariableDeclarations) {
127
+ const vd = element as J.VariableDeclarations;
128
+ const name = nameOf(vd);
129
+ if (name && !isStatic(vd.modifiers) && (typed(vd) || injected(vd))) return {name, index};
130
+ } else if (element.kind === J.Kind.MethodDeclaration && (element as J.MethodDeclaration).name.simpleName === 'constructor') {
131
+ for (const {element: param} of (element as J.MethodDeclaration).parameters.elements) {
132
+ if (param.kind !== J.Kind.VariableDeclarations) continue;
133
+ const vd = param as J.VariableDeclarations;
134
+ // Only a parameter property, which has an access modifier or `readonly`, is a member of the instance.
135
+ const name = nameOf(vd);
136
+ if (name && vd.modifiers.length > 0 && typed(vd)) return {name, index: -1};
137
+ }
138
+ }
139
+ }
140
+ return undefined;
141
+ }
142
+
143
+ /**
144
+ * The class whose instance `this` is at the cursor: the class whose body directly holds the nearest enclosing member,
145
+ * when that member is not static and nothing but arrow functions lie between it and the cursor. A `function`
146
+ * expression or declaration in between rebinds `this`, and so gives none.
147
+ */
148
+ function instanceClass(cursor: Cursor): {cls: J.ClassDeclaration, member: J} | undefined {
149
+ const path: J[] = [];
150
+ for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
151
+ const value = c.value as J;
152
+ if (!value || typeof value.kind !== 'string') continue;
153
+ if (value.kind === J.Kind.ClassDeclaration) {
154
+ const cls = value as J.ClassDeclaration;
155
+ const member = path.find(node => cls.body.statements.some(({element}) => element === node));
156
+ // Only the class body, and the padding around it, may lie between the member and the class.
157
+ if (!member || !path.slice(path.indexOf(member) + 1).every(isBodyOrPadding)) return undefined;
158
+ const modifiers = (member as J.MethodDeclaration | J.VariableDeclarations).modifiers ?? [];
159
+ if (isStatic(modifiers)) return undefined;
160
+ // Any method declaration below the member is a `function`, with a `this` of its own.
161
+ return path.slice(0, path.indexOf(member)).some(node => node.kind === J.Kind.MethodDeclaration) ? undefined : {cls, member};
162
+ }
163
+ path.push(value);
164
+ }
165
+ return undefined;
166
+ }
167
+
168
+ /**
169
+ * Whether `field` holds its service by the time `at.member` runs: always in a method, accessor or constructor, and in a
170
+ * field initializer only when the field is declared above it, since field initializers run in the order they are
171
+ * written, and before a constructor parameter property is assigned where a class uses `useDefineForClassFields`.
172
+ */
173
+ function initializedBefore(at: {cls: J.ClassDeclaration, member: J}, field: ServiceMember): boolean {
174
+ if (at.member.kind !== J.Kind.VariableDeclarations) return true;
175
+ const index = at.cls.body.statements.findIndex(({element}) => element.id === at.member.id);
176
+ return field.index >= 0 && field.index < index;
177
+ }
178
+
179
+ const isBodyOrPadding = (node: J) => node.kind === J.Kind.Block || node.kind.endsWith('Padded') || node.kind.endsWith('Container');
180
+
181
+ function thisAccess(field: string, prefix: J.Space): J.FieldAccess {
182
+ const identifier = (name: string): J.Identifier => ({
183
+ kind: J.Kind.Identifier, id: randomId(), prefix: emptySpace, markers: emptyMarkers, annotations: [],
184
+ simpleName: name, type: undefined, fieldType: undefined,
185
+ } as J.Identifier);
186
+ return {
187
+ kind: J.Kind.FieldAccess,
188
+ id: randomId(),
189
+ prefix,
190
+ markers: emptyMarkers,
191
+ target: identifier('this'),
192
+ name: {kind: J.Kind.LeftPadded, before: emptySpace, element: identifier(field), markers: emptyMarkers},
193
+ type: undefined,
194
+ } as J.FieldAccess;
195
+ }
196
+
197
+ /** `private readonly <field> = inject(<service>);`, parsed so that its modifiers and semicolon print as written. */
198
+ async function injectField(field: string, service: string): Promise<J.RightPadded<Statement>> {
199
+ const cu = await new JavaScriptParser().parseOnly({
200
+ sourcePath: 'field.ts',
201
+ text: `class C {\n private readonly ${field} = inject(${service});\n}\n`,
202
+ }) as JS.CompilationUnit;
203
+ const cls = cu.statements[0].element as J.ClassDeclaration;
204
+ return cls.body.statements[0];
205
+ }
206
+
207
+ /** Puts `field` first in the class body, on a line of its own with the indentation of the members. */
208
+ function withFirstMember(cls: J.ClassDeclaration, field: J.RightPadded<Statement>): J.ClassDeclaration {
209
+ const first = cls.body.statements[0];
210
+ const indent = '\n' + indentOf(cls) + ' ';
211
+ // The comments before the first member are its own, so the field takes only the line break and indentation.
212
+ const whitespace = first ? first.element.prefix.whitespace.replace(/^\n*/, '\n') || indent : indent;
213
+ const added = {...field, element: {...field.element, id: randomId(), prefix: {...field.element.prefix, comments: [], whitespace}} as Statement};
214
+ const end = first ? cls.body.end : {...cls.body.end, whitespace: '\n' + indentOf(cls)};
215
+ return {...cls, body: {...cls.body, statements: [added, ...cls.body.statements], end}};
216
+ }
217
+
218
+ function indentOf(cls: J.ClassDeclaration): string {
219
+ const ws = cls.prefix.whitespace;
220
+ return ws.substring(ws.lastIndexOf('\n') + 1);
221
+ }
222
+
223
+ /**
224
+ * Migrates `ng2-cookies`, unmaintained since Angular 2, to `ngx-cookie-service`.
225
+ *
226
+ * Both write `document.cookie` alike: names and values encoded with `encodeURIComponent`, `expires` in days or as a
227
+ * `Date`, and no `path` or `domain` unless given. `ngx-cookie-service` also writes `SameSite=Lax`, which is what
228
+ * browsers assume without it. Its `CookieService` has every method of `ng2-cookies` with the same leading parameters.
229
+ *
230
+ * - The injected `CookieService` and `UnmanagedCookieService` become `ngx-cookie-service`'s `CookieService`, which is
231
+ * provided in the root injector.
232
+ * - A call on the `Cookie` or `UnmanagedCookie` object goes through a `CookieService` field of the Angular class it is
233
+ * in: one the class already has, or `private readonly cookieService = inject(CookieService)` added as its first
234
+ * member, on Angular 14 and later where `inject()` exists.
235
+ * - A call where no such field can serve (a function outside a class, a static member, a `function` that rebinds
236
+ * `this`, a class Angular does not create, or a project before Angular 14) is flagged, and so is the import while
237
+ * the file still uses it.
238
+ */
239
+ export class MigrateNg2CookiesToNgxCookieService extends ScanningRecipe<Map<string, number>> {
240
+ readonly name = "org.openrewrite.angular.ng2cookies.MigrateNg2CookiesToNgxCookieService";
241
+ readonly displayName: string = "Migrate `ng2-cookies` to `ngx-cookie-service`";
242
+ readonly description: string = "Replaces the unmaintained `ng2-cookies` with `ngx-cookie-service`, which writes cookies " +
243
+ "the same way. An injected `CookieService` or `UnmanagedCookieService` becomes `ngx-cookie-service`'s " +
244
+ "`CookieService`, and a call on the `Cookie` object goes through a `CookieService` field of the Angular class " +
245
+ "it is in, which `inject(CookieService)` provides where the class has none (Angular 14 and later). Calls " +
246
+ "that no such field can serve, such as those in a function outside a class or in a static method, are " +
247
+ "flagged for a hand migration. Only projects on Angular 9 to 22, the majors `ngx-cookie-service` has a release " +
248
+ "for, are migrated, as their `package.json` resolves or declares `@angular/core` within one major.";
249
+
250
+ /** @param requires a package that the `package.json` of a project must declare for its code to move. */
251
+ constructor(private readonly requires?: string) {
252
+ super();
253
+ }
254
+
255
+ initialValue(_ctx: ExecutionContext): Map<string, number> {
256
+ return new Map();
257
+ }
258
+
259
+ async scanner(majors: Map<string, number>): Promise<TreeVisitor<any, ExecutionContext>> {
260
+ return singleMajorScanner('@angular/core', majors, this.requires);
261
+ }
262
+
263
+ async editorWithData(majors: Map<string, number>): Promise<TreeVisitor<any, ExecutionContext>> {
264
+ const serviceMoves = await Promise.all(SERVICE_MODULES.flatMap(oldModule => SERVICES.map(oldMember =>
265
+ new ChangeImport({oldModule, oldMember, newModule: NGX_COOKIE_SERVICE, newMember: 'CookieService'}).editor())));
266
+ return new class extends JavaScriptVisitor<ExecutionContext> {
267
+ /** The local names of `Cookie` and `UnmanagedCookie`, with the module and name they are imported by. */
268
+ private direct = new Map<string, {module: string, imported: string}>();
269
+ /** The local names that a `CookieService` field may be typed with. */
270
+ private services = new Set<string>();
271
+ private canInject = false;
272
+ /** The field each class reaches the service through, and whether the recipe adds it. */
273
+ private fields = new Map<J.ClassDeclaration['id'], ServiceMember & {added: boolean, used: boolean}>();
274
+
275
+ protected async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
276
+ const imports = cu.statements.map(({element}) => element)
277
+ .filter((s): s is JS.Import => s.kind === JS.Kind.Import && isNg2Cookies(moduleOf(s as JS.Import)));
278
+ const major = majorFor(majors, cu.sourcePath);
279
+ if (imports.length === 0 || major === undefined || major < FIRST_MAJOR || major > LAST_MAJOR) return cu;
280
+
281
+ this.direct = new Map();
282
+ this.services = new Set();
283
+ this.fields = new Map();
284
+ for (const imp of imports) {
285
+ for (const {imported, local} of bindings(imp)) {
286
+ if (DIRECT.has(imported)) this.direct.set(local, {module: moduleOf(imp)!, imported});
287
+ if (SERVICES.includes(imported)) this.services.add(local);
288
+ }
289
+ }
290
+ // A `CookieService` field is reused only when it is `ngx-cookie-service`'s, and none is added where
291
+ // the name already stands for another library's.
292
+ let foreign = false;
293
+ for (const {element} of cu.statements) {
294
+ if (element.kind !== JS.Kind.Import) continue;
295
+ const module = moduleOf(element as JS.Import);
296
+ for (const {imported, local} of bindings(element as JS.Import)) {
297
+ if (module === NGX_COOKIE_SERVICE && imported === 'CookieService') this.services.add(local);
298
+ else if (local === 'CookieService' && !isNg2Cookies(module)) foreign = true;
299
+ }
300
+ }
301
+ this.canInject = major >= FIRST_INJECT_MAJOR && !foreign;
302
+
303
+ let result = await super.visitJsCompilationUnit(cu, p) as JS.CompilationUnit;
304
+ if ([...this.fields.values()].some(f => f.added && f.used)) {
305
+ maybeAddImport(this, {module: '@angular/core', member: 'inject', onlyIfReferenced: false});
306
+ maybeAddImport(this, {module: NGX_COOKIE_SERVICE, member: 'CookieService', onlyIfReferenced: false});
307
+ }
308
+ for (const {module, imported} of this.direct.values()) {
309
+ // Gone once no call is left on it.
310
+ maybeRemoveImport(this, module, imported);
311
+ }
312
+ for (const move of serviceMoves) {
313
+ result = (await move.visit<JS.CompilationUnit>(result, p, this.cursor.parent)) ?? result;
314
+ }
315
+ return result;
316
+ }
317
+
318
+ protected async visitClassDeclaration(classDecl: J.ClassDeclaration, p: ExecutionContext): Promise<J | undefined> {
319
+ if (this.direct.size > 0 && !this.fields.has(classDecl.id)) {
320
+ const existing = existingService(classDecl, this.services);
321
+ const angular = decoratorNames(classDecl).some(d => INJECTABLE_DECORATORS.has(d));
322
+ if (existing) {
323
+ this.fields.set(classDecl.id, {...existing, added: false, used: false});
324
+ } else if (angular && this.canInject) {
325
+ const taken = memberNames(classDecl);
326
+ let name = FIELD;
327
+ for (let i = 2; taken.has(name); i++) name = `${FIELD}${i}`;
328
+ // The added field is the first member, so every field initializer may use it.
329
+ this.fields.set(classDecl.id, {name, index: -1, added: true, used: false});
330
+ }
331
+ }
332
+ const c = await super.visitClassDeclaration(classDecl, p) as J.ClassDeclaration;
333
+ const field = this.fields.get(classDecl.id);
334
+ if (!c || !field?.added || !field.used) return c;
335
+ return withFirstMember(c, await injectField(field.name, 'CookieService'));
336
+ }
337
+
338
+ protected async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
339
+ const m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
340
+ const select = m?.select?.element;
341
+ if (!select || !isIdentifier(select) || !this.direct.has(select.simpleName) || !METHODS.has(m.name.simpleName)) return m;
342
+
343
+ const at = instanceClass(this.cursor);
344
+ const field = at && this.fields.get(at.cls.id);
345
+ if (!field || !field.added && !initializedBefore(at!, field)) {
346
+ return hasSearchResult(m, 'ng2-cookies') ? m : foundSearchResult(m, LEFTOVER);
347
+ }
348
+ field.used = true;
349
+ return {...m, select: {...m.select!, element: thisAccess(field.name, select.prefix)}} as J.MethodInvocation;
350
+ }
351
+ }();
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Flags what is still imported from `ng2-cookies` once the migration has run, such as a `Cookie` passed around as a
357
+ * value, which no field can stand in for.
358
+ */
359
+ export class FindNg2CookiesUsage extends Recipe {
360
+ readonly name = "org.openrewrite.angular.ng2cookies.FindNg2CookiesUsage";
361
+ readonly displayName: string = "Find `ng2-cookies` imports";
362
+ readonly description: string = "Flags each import of the unmaintained `ng2-cookies`, which `ngx-cookie-service` replaces, " +
363
+ "including a CommonJS `require`, such as in compiled JavaScript checked in beside its TypeScript.";
364
+
365
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
366
+ return new class extends JavaScriptVisitor<ExecutionContext> {
367
+ protected async visitImportDeclaration(imp: JS.Import, _p: ExecutionContext): Promise<J | undefined> {
368
+ // A full migration flags an import before the next cycle moves it, once `ngx-cookie-service` is added.
369
+ if (!isNg2Cookies(moduleOf(imp))) return withoutSearchResult(imp, LEFTOVER);
370
+ return hasSearchResult(imp, 'ng2-cookies') ? imp : foundSearchResult(imp, LEFTOVER);
371
+ }
372
+
373
+ protected async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
374
+ const m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
375
+ return m && isNg2Cookies(requiredModule(m)) && !hasSearchResult(m, 'ng2-cookies') ? foundSearchResult(m, LEFTOVER) : m;
376
+ }
377
+ }();
378
+ }
379
+ }
380
+
381
+ /** The migration, then a flag on each import of `ng2-cookies` that it could not take away. */
382
+ export class MigrateNg2CookiesCodeChanges extends Recipe {
383
+ readonly name = "org.openrewrite.angular.ng2cookies.MigrateNg2CookiesCodeChanges";
384
+ readonly displayName: string = "Migrate `ng2-cookies` to `ngx-cookie-service` (code changes)";
385
+ readonly description: string = "Runs `MigrateNg2CookiesToNgxCookieService`, then flags each import of `ng2-cookies` " +
386
+ "that a use the migration could not move still needs.";
387
+
388
+ /** @param requires a package that the `package.json` of a project must declare for its code to move. */
389
+ constructor(private readonly requires?: string) {
390
+ super();
391
+ }
392
+
393
+ async recipeList(): Promise<Recipe[]> {
394
+ return [new MigrateNg2CookiesToNgxCookieService(this.requires), new FindNg2CookiesUsage()];
395
+ }
396
+ }
397
+
398
+ /** `ngx-cookie-service` of each Angular major it has a release for. */
399
+ const NGX_COOKIE_SERVICE_VERSIONS = [{major: 9, version: '^3.1.3'}, ...caretMajors(10, LAST_MAJOR)];
400
+
401
+ /**
402
+ * `ngx-cookie-service` at the Angular major of each `package.json` that declares `ng2-cookies`, then the code changes
403
+ * where it was added, in the next cycle, and then `ng2-cookies` removed where nothing imports it any more.
404
+ */
405
+ export class MigrateNg2Cookies extends Recipe {
406
+ readonly name = "org.openrewrite.angular.ng2cookies.MigrateNg2Cookies";
407
+ readonly displayName: string = "Migrate `ng2-cookies` to `ngx-cookie-service`, flagging what is left";
408
+ readonly description: string = "Runs `MigrateNg2CookiesToNgxCookieService`, then flags each import of `ng2-cookies` " +
409
+ "that a use the migration could not move still needs. Each `package.json` that declares `ng2-cookies` gets " +
410
+ "`ngx-cookie-service` of its Angular major, from 9 to 22, and loses `ng2-cookies` once none of its sources imports it. " +
411
+ "Code moves only in a project whose `package.json` declares `ngx-cookie-service`, so not in one where npm " +
412
+ "refused to add it, such as one whose lock already has a peer conflict.";
413
+ // The code changes read the `ngx-cookie-service` this run adds, and the removal the imports they leave, so each
414
+ // lands a cycle after the step before it.
415
+ readonly causesAnotherCycle = true;
416
+
417
+ async recipeList(): Promise<Recipe[]> {
418
+ return [
419
+ ...await addDependencyByMajor(NGX_COOKIE_SERVICE, 'dependencies', [NG2_COOKIES], '@angular/core',
420
+ NGX_COOKIE_SERVICE_VERSIONS),
421
+ new MigrateNg2CookiesCodeChanges(NGX_COOKIE_SERVICE),
422
+ await removeDependencyUnlessImported(NG2_COOKIES),
423
+ ];
424
+ }
425
+ }
@@ -0,0 +1,93 @@
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} from "@openrewrite/rewrite";
8
+ import {addDependency, findNodeResolutionResult, removeDependency} from "@openrewrite/rewrite/javascript";
9
+ import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
10
+ import {declaredVersion, directoryOf} from "../libraries/components/package-version";
11
+
12
+ /** The version of a package to add for one major of the package it follows, or from that major on with `andLater`. */
13
+ export interface MajorVersion {
14
+ major: number;
15
+ version: string;
16
+ andLater?: boolean;
17
+ }
18
+
19
+ /** `^M.0.0` for each major from `first` to `last`. */
20
+ export function caretMajors(first: number, last: number): MajorVersion[] {
21
+ return Array.from({length: last - first + 1}, (_, i) => ({major: first + i, version: `^${first + i}.0.0`}));
22
+ }
23
+
24
+ /**
25
+ * One `addDependency` for each of `versions`, adding `packageName` to each `package.json` that declares a package
26
+ * matching one of `declaring`, before the cycle's edits, and resolves `following` within that major: by the version its
27
+ * lock resolves, else when every version its constraint admits is within it. A `package.json` that already declares
28
+ * `packageName` is left as it is.
29
+ */
30
+ export async function addDependencyByMajor(packageName: string, scope: 'dependencies' | 'devDependencies',
31
+ declaring: string[], following: string,
32
+ versions: MajorVersion[]): Promise<Recipe[]> {
33
+ return Promise.all(versions.map(({major, version, andLater}) => addDependency({
34
+ packageName,
35
+ version,
36
+ scope,
37
+ onlyIfDeclaring: declaring,
38
+ onlyIfResolving: [`${following}@${majorRange(major, andLater)}`],
39
+ })));
40
+ }
41
+
42
+ /**
43
+ * Removes `packageName` from each `package.json` that no source it serves still imports it from, by the nearest
44
+ * `package.json` above each source that declares it. Imports are read before the cycle's edits, so a composite that
45
+ * rewrites them in the same run must set `causesAnotherCycle` for the removal to land in the next cycle.
46
+ */
47
+ export function removeDependencyUnlessImported(packageName: string): Promise<Recipe> {
48
+ return removeDependency({packageName, unlessImporting: [packageName]});
49
+ }
50
+
51
+ /** The npm range of one major, or of it and every later one, prereleases included. */
52
+ export function majorRange(major: number, andLater = false): string {
53
+ return andLater ? `>=${major}.0.0-0` : `>=${major}.0.0-0 <${major + 1}.0.0-0`;
54
+ }
55
+
56
+ /**
57
+ * The major that `addDependencyByMajor` takes a `package.json` to resolve `packageName` at, if it can tell: the major of
58
+ * the version its lock resolves, else of a constraint that admits versions of one major only, such as `^20.1.0`,
59
+ * `~20.1.0`, `20.x` or `20.1.0`.
60
+ */
61
+ export function singleMajor(packageJson: Json.Document, packageName: string): number | undefined {
62
+ const marker = findNodeResolutionResult(packageJson);
63
+ // `peerDependencies` state a compatible range, not the version the project installs.
64
+ const resolved = marker && [...marker.dependencies, ...marker.devDependencies].find(d => d.name === packageName)?.resolved?.version;
65
+ const version = resolved ?? declaredVersion(packageJson, packageName);
66
+ const match = version?.trim().match(resolved ? /^v?(\d+)\./ : /^[\^~]?v?(\d+)(?:\.(?:\d+|x|\*)){0,2}(?:-[\w.]+)?$/);
67
+ return match ? Number(match[1]) : undefined;
68
+ }
69
+
70
+ /**
71
+ * Records the `singleMajor` of `packageName` of every `package.json` that it can tell, keyed by its directory, so that a
72
+ * code change runs where `addDependencyByMajor` adds the package it moves the code to, and nowhere else.
73
+ */
74
+ /**
75
+ * Whether a `package.json` declares `requires`, if one is given. A migration whose code changes run after the step that
76
+ * adds the package they import moves code only where that step could add it: npm refuses the edit, and the step leaves
77
+ * the `package.json` alone, in a project whose lock already has a peer conflict of its own.
78
+ */
79
+ export function declares(doc: Json.Document, requires: string | undefined): boolean {
80
+ return requires === undefined || declaredVersion(doc, requires) !== undefined;
81
+ }
82
+
83
+ export function singleMajorScanner(packageName: string, majors: Map<string, number>, requires?: string): TreeVisitor<any, ExecutionContext> {
84
+ return new class extends JsonVisitor<ExecutionContext> {
85
+ protected async visitDocument(doc: Json.Document, _p: ExecutionContext): Promise<Json | undefined> {
86
+ const path = doc.sourcePath;
87
+ const major = (path === 'package.json' || path.endsWith('/package.json')) && declares(doc, requires) ?
88
+ singleMajor(doc, packageName) : undefined;
89
+ if (major !== undefined) majors.set(directoryOf(path), major);
90
+ return doc;
91
+ }
92
+ }();
93
+ }