@ng-native/migrate 0.16.0 → 0.17.1

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.
@@ -0,0 +1,617 @@
1
+ /**
2
+ * Rewrites reads of an engine node's fields that were renamed, for the migrations that rename
3
+ * them: `engine-node-tag` and `engine-node-fields`.
4
+ *
5
+ * A field such as `.name` or `.text` is everywhere, and a file's syntax does not say what most of
6
+ * it is read from, so a read is rewritten only where what it is read from is known to be one of
7
+ * the node types: a name whose nearest declaration is typed as one, or initialised with one;
8
+ * `this.` a field typed as one, or `this` in a class that implements one; `x as EngineNode`; a
9
+ * node's `parent`, an item of its `children` (or `childList`), and the item a `for...of` or a
10
+ * `forEach`, `map`, `filter`, `some`, `every` or `find` callback takes from them; and
11
+ * `nativeElement` of an `ElementRef<EngineNode>`. A type counts when it names one of the node
12
+ * types, as imported (an alias or a namespace import included), or an interface or type in the
13
+ * file built on one. `{ name }` destructured from a node becomes `{ tag: name }`, and an object
14
+ * literal written as one of these types has its `name` key become `tag`.
15
+ *
16
+ * Everything else is left as it is. In a file that imports one of the types, a read it cannot
17
+ * place is noted with its file and line, and so is one from a `nativeElement` anywhere, because an
18
+ * `ElementRef` holds `any` unless it is told otherwise. So is a field read from, or taken out of,
19
+ * a node cast to another type: `(node as { name?: string }).name` still compiles once the field is
20
+ * gone, and reads `undefined`.
21
+ *
22
+ * A read from a node's `props` is neither rewritten nor noted: a prop has the name the native view
23
+ * gives it, so a text input's `props['text']` is its value under any version.
24
+ */
25
+ const { applied, scriptKind, SOURCE, typescript } = require('./move-imports.cjs');
26
+ const { files } = require('./host.cjs');
27
+ const { ELSE, isStatic, nearestBinding, thisOf } = require('./scope.cjs');
28
+
29
+ /** What an expression is, as far as this migration needs to know. */
30
+ const NODE = 'node';
31
+ const NODES = 'nodes';
32
+ const REF = 'element ref';
33
+ /** Anything else, as a type written out says. */
34
+ const OTHER = 'other';
35
+
36
+ /** Types that say nothing of what a value is. */
37
+ const LOOSE = /^(any|unknown|object|Object|\{\s*\})$/;
38
+
39
+ /** Expressions whose value is never a node: literals, functions and constructed objects. */
40
+ const VALUES = [
41
+ 'isObjectLiteralExpression',
42
+ 'isArrayLiteralExpression',
43
+ 'isNewExpression',
44
+ 'isClassExpression',
45
+ 'isFunctionExpression',
46
+ 'isArrowFunction',
47
+ 'isStringLiteral',
48
+ 'isNoSubstitutionTemplateLiteral',
49
+ 'isTemplateExpression',
50
+ ];
51
+
52
+ /** `expression` without the parentheses and `!` around it. */
53
+ function unwrapped(ts, expression) {
54
+ let inner = expression;
55
+ while (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner)) {
56
+ inner = inner.expression;
57
+ }
58
+ return inner;
59
+ }
60
+
61
+ /** `x as T`, `<T>x` or `x satisfies T`. */
62
+ const isAssertion = (ts, expression) =>
63
+ ts.isAsExpression(expression) ||
64
+ ts.isTypeAssertionExpression(expression) ||
65
+ ts.isSatisfiesExpression(expression);
66
+
67
+ /** A node's children, by the name they had and the name they have. */
68
+ const CHILDREN = new Set(['children', 'childList']);
69
+
70
+ /** Array methods whose callback takes an item as its first parameter. */
71
+ const EACH = new Set(['forEach', 'map', 'flatMap', 'filter', 'some', 'every', 'find', 'findLast']);
72
+ /** Array methods that answer one item. */
73
+ const ITEM = new Set(['at', 'find', 'findLast']);
74
+ /** Array methods that answer some of the items, as an array. */
75
+ const SOME = new Set(['filter', 'slice', 'toReversed', 'toSorted']);
76
+
77
+ /** The names the node types go by in a file: as imported, aliased, or through a namespace. */
78
+ function imported(ts, source, types) {
79
+ const names = new Set();
80
+ for (const statement of source.statements) {
81
+ const wanted = ts.isImportDeclaration(statement) && types[statement.moduleSpecifier.text];
82
+ const bindings = wanted && statement.importClause?.namedBindings;
83
+ if (!bindings) continue;
84
+ if (ts.isNamespaceImport(bindings)) {
85
+ for (const type of wanted) names.add(`${bindings.name.text}.${type}`);
86
+ continue;
87
+ }
88
+ for (const element of bindings.elements) {
89
+ if (wanted.includes((element.propertyName ?? element.name).text)) {
90
+ names.add(element.name.text);
91
+ }
92
+ }
93
+ }
94
+ return names;
95
+ }
96
+
97
+ /** The types a declared type can be, less parentheses, `null` and `undefined`. */
98
+ function variants(ts, type) {
99
+ if (!type) return [];
100
+ if (ts.isParenthesizedTypeNode(type)) return variants(ts, type.type);
101
+ if (ts.isUnionTypeNode(type)) return type.types.flatMap((member) => variants(ts, member));
102
+ const empty =
103
+ type.kind === ts.SyntaxKind.UndefinedKeyword ||
104
+ (ts.isLiteralTypeNode(type) && type.literal.kind === ts.SyntaxKind.NullKeyword);
105
+ return empty ? [] : [type];
106
+ }
107
+
108
+ /** Whether every type `type` can be is true of `test`, and it can be one at all. */
109
+ function always(ts, type, test) {
110
+ const all = variants(ts, type);
111
+ return all.length > 0 && all.every(test);
112
+ }
113
+
114
+ /** Whether a type is a node: one of the node types, or an intersection with one. */
115
+ function isNodeType(ts, type, names) {
116
+ return always(ts, type, (one) => {
117
+ if (ts.isTypeReferenceNode(one)) return names.has(one.typeName.getText());
118
+ return ts.isIntersectionTypeNode(one) && one.types.some((part) => isNodeType(ts, part, names));
119
+ });
120
+ }
121
+
122
+ /** The item type of an array type, `T[]`, `readonly T[]`, `Array<T>` or `ReadonlyArray<T>`. */
123
+ function itemType(ts, type) {
124
+ if (ts.isTypeOperatorNode(type)) return itemType(ts, type.type);
125
+ if (ts.isArrayTypeNode(type)) return type.elementType;
126
+ const generic =
127
+ ts.isTypeReferenceNode(type) && /^(Readonly)?Array$/.test(type.typeName.getText());
128
+ return generic ? type.typeArguments?.[0] : undefined;
129
+ }
130
+
131
+ /** `ElementRef<T>`'s `T`. */
132
+ function refType(ts, type) {
133
+ const ref = ts.isTypeReferenceNode(type) && type.typeName.getText() === 'ElementRef';
134
+ return ref ? type.typeArguments?.[0] : undefined;
135
+ }
136
+
137
+ /** What a declared type says a value is: a node, an array of nodes, an element ref to one. */
138
+ function typeKind(ts, type, names) {
139
+ if (isNodeType(ts, type, names)) return NODE;
140
+ if (always(ts, type, (one) => isNodeType(ts, itemType(ts, one), names))) return NODES;
141
+ if (always(ts, type, (one) => isNodeType(ts, refType(ts, one), names))) return REF;
142
+ return null;
143
+ }
144
+
145
+ /** Whether a class says it implements one of the node types. */
146
+ const implementsNode = (ts, cls, names) =>
147
+ (cls.heritageClauses ?? []).some(
148
+ (clause) =>
149
+ clause.token === ts.SyntaxKind.ImplementsKeyword &&
150
+ clause.types.some((type) => names.has(type.expression.getText())),
151
+ );
152
+
153
+ /** What the file knows of each expression it asks about. */
154
+ class Reader {
155
+ constructor(ts, names) {
156
+ this.ts = ts;
157
+ this.names = names;
158
+ }
159
+
160
+ type(type) {
161
+ return typeKind(this.ts, type, this.names);
162
+ }
163
+
164
+ /** What `expression` is: `NODE`, `NODES`, `REF`, or null when this cannot tell. */
165
+ kind(expression, depth = 0) {
166
+ const ts = this.ts;
167
+ const inner = unwrapped(ts, expression);
168
+ if (depth > 32) return null;
169
+ if (isAssertion(ts, inner)) {
170
+ const said = this.type(inner.type);
171
+ if (said || !ts.isSatisfiesExpression(inner)) return said;
172
+ return this.kind(inner.expression, depth + 1);
173
+ }
174
+ if (ts.isIdentifier(inner)) return this.binding(nearestBinding(ts, inner), depth);
175
+ if (inner.kind === ts.SyntaxKind.ThisKeyword) return this.self(inner);
176
+ return this.access(inner, depth);
177
+ }
178
+
179
+ /** What a member, an item or a call answers. */
180
+ access(expression, depth) {
181
+ const ts = this.ts;
182
+ if (ts.isPropertyAccessExpression(expression)) return this.member(expression, depth);
183
+ if (ts.isElementAccessExpression(expression)) {
184
+ return this.kind(expression.expression, depth + 1) === NODES ? NODE : null;
185
+ }
186
+ return ts.isCallExpression(expression) ? this.call(expression, depth) : null;
187
+ }
188
+
189
+ /** `this`, which is a node in a class that implements a node type. */
190
+ self(expression) {
191
+ const self = thisOf(this.ts, expression);
192
+ return self && !self.static && implementsNode(this.ts, self.cls, this.names) ? NODE : null;
193
+ }
194
+
195
+ /** `x.parent`, `x.children`, `ref.nativeElement`, or `this.field`. */
196
+ member(expression, depth) {
197
+ const ts = this.ts;
198
+ const name = expression.name.text;
199
+ if (expression.expression.kind === ts.SyntaxKind.ThisKeyword) {
200
+ const self = thisOf(ts, expression);
201
+ const field = self && this.field(self.cls, name, self.static);
202
+ if (field) return field;
203
+ }
204
+ const of = this.kind(expression.expression, depth + 1);
205
+ if (of === NODE && name === 'parent') return NODE;
206
+ if (of === NODE && CHILDREN.has(name)) return NODES;
207
+ return of === REF && name === 'nativeElement' ? NODE : null;
208
+ }
209
+
210
+ /** An array method's answer, or `inject<ElementRef<EngineNode>>(ElementRef)`. */
211
+ call(expression, depth) {
212
+ const ts = this.ts;
213
+ const callee = expression.expression;
214
+ if (ts.isIdentifier(callee) && callee.text === 'inject') {
215
+ return this.type(expression.typeArguments?.[0]) === REF ? REF : null;
216
+ }
217
+ if (!ts.isPropertyAccessExpression(callee)) return null;
218
+ if (this.kind(callee.expression, depth + 1) !== NODES) return null;
219
+ if (ITEM.has(callee.name.text)) return NODE;
220
+ return SOME.has(callee.name.text) ? NODES : null;
221
+ }
222
+
223
+ /** What a class's field or getter `name` holds, from its type or its initialiser. */
224
+ field(cls, name, onClass) {
225
+ const declaration = this.fieldDeclaration(cls, name, onClass);
226
+ if (!declaration) return null;
227
+ if (declaration.type) return this.type(declaration.type);
228
+ return declaration.initializer ? this.kind(declaration.initializer, 1) : null;
229
+ }
230
+
231
+ /**
232
+ * The declaration of a class's field or getter `name`, a constructor parameter declared as a
233
+ * field (`constructor(readonly node: EngineNode)`) included.
234
+ */
235
+ fieldDeclaration(cls, name, onClass) {
236
+ const ts = this.ts;
237
+ const named = (one) => one.name && ts.isIdentifier(one.name) && one.name.text === name;
238
+ const member = cls.members.find(
239
+ (one) =>
240
+ named(one) &&
241
+ isStatic(ts, one) === onClass &&
242
+ (ts.isPropertyDeclaration(one) || ts.isGetAccessorDeclaration(one)),
243
+ );
244
+ if (member || onClass) return member;
245
+ const constructor = cls.members.find((one) => ts.isConstructorDeclaration(one));
246
+ return constructor?.parameters.find((one) => ts.getModifiers(one)?.length && named(one));
247
+ }
248
+
249
+ /** The field `this.name` reads, where `this` is a class's. */
250
+ thisField(expression) {
251
+ const self = thisOf(this.ts, expression);
252
+ return self ? this.fieldDeclaration(self.cls, expression.name.text, self.static) : undefined;
253
+ }
254
+
255
+ /** What a variable or parameter holds, from its type, its loop, its callback or its value. */
256
+ binding(declaration, depth) {
257
+ if (!declaration || declaration === ELSE) return null;
258
+ if (declaration.type) return this.type(declaration.type);
259
+ const items = this.iterated(declaration);
260
+ if (items) return this.kind(items, depth + 1) === NODES ? NODE : null;
261
+ return declaration.initializer ? this.kind(declaration.initializer, depth + 1) : null;
262
+ }
263
+
264
+ /**
265
+ * The array a declaration takes one item of: a `for...of` variable's, or the first parameter of
266
+ * a callback an array method is given.
267
+ */
268
+ iterated(declaration) {
269
+ const ts = this.ts;
270
+ if (!ts.isParameter(declaration)) {
271
+ const loop = declaration.parent?.parent;
272
+ const item = loop && ts.isForOfStatement(loop) && loop.initializer === declaration.parent;
273
+ return item ? loop.expression : null;
274
+ }
275
+ const callback = declaration.parent;
276
+ const call = callback.parent;
277
+ if (callback.parameters[0] !== declaration || !call || !ts.isCallExpression(call)) return null;
278
+ const callee = call.expression;
279
+ if (call.arguments[0] !== callback || !ts.isPropertyAccessExpression(callee)) return null;
280
+ return EACH.has(callee.name.text) ? callee.expression : null;
281
+ }
282
+
283
+ /** What an explicit type says: its kind, `OTHER` for any other type, null when it says nothing. */
284
+ says(type) {
285
+ if (!type || LOOSE.test(type.getText())) return null;
286
+ return this.type(type) ?? OTHER;
287
+ }
288
+
289
+ /**
290
+ * Whether `expression` is a node cast to another type, `node as { name?: string }`: the type it
291
+ * is read as hides the node, and a field that type declares still compiles after the rename.
292
+ */
293
+ castNode(expression, depth = 0) {
294
+ const ts = this.ts;
295
+ const inner = unwrapped(ts, expression);
296
+ if (depth > 32 || !isAssertion(ts, inner) || this.type(inner.type)) return false;
297
+ return (
298
+ this.kind(inner.expression, depth + 1) === NODE || this.castNode(inner.expression, depth + 1)
299
+ );
300
+ }
301
+
302
+ /** Whether `expression` is certainly not a node, so a `name` read from it is no tag. */
303
+ notNode(expression, depth = 0) {
304
+ const ts = this.ts;
305
+ const inner = unwrapped(ts, expression);
306
+ if (depth > 32) return false;
307
+ if (VALUES.some((is) => ts[is](inner))) return true;
308
+ if (inner.kind === ts.SyntaxKind.ThisKeyword) return Boolean(thisOf(ts, inner));
309
+ if (isAssertion(ts, inner)) return this.says(inner.type) === OTHER;
310
+ if (ts.isIdentifier(inner)) return this.notNodeBinding(nearestBinding(ts, inner), depth);
311
+ if (ts.isElementAccessExpression(inner)) return this.notNodes(inner.expression, depth + 1);
312
+ if (ts.isPropertyAccessExpression(inner)) return this.notNodeMember(inner, depth);
313
+ const items = methodOf(ts, inner, ITEM);
314
+ return Boolean(items) && this.notNodes(items, depth + 1);
315
+ }
316
+
317
+ /**
318
+ * Whether `x.y` is certainly not a node: a constructor, a node's `props`, which are keyed by the
319
+ * native view's own names and keep them, or a member typed otherwise.
320
+ */
321
+ notNodeMember(access, depth) {
322
+ const ts = this.ts;
323
+ if (access.name.text === 'constructor' || access.name.text === 'props') return true;
324
+ const of = unwrapped(ts, access.expression);
325
+ if (of.kind === ts.SyntaxKind.ThisKeyword) {
326
+ const field = this.thisField(access);
327
+ return Boolean(field) && this.notNodeBinding(field, depth);
328
+ }
329
+ const literal = isAssertion(ts, of) && ts.isTypeLiteralNode(of.type) && of.type;
330
+ const member =
331
+ literal && literal.members.find((one) => one.name?.getText() === access.name.text);
332
+ return Boolean(member) && this.says(member.type) === OTHER;
333
+ }
334
+
335
+ /** Whether a variable, parameter or field is certainly not a node. */
336
+ notNodeBinding(declaration, depth) {
337
+ if (!declaration) return true;
338
+ if (declaration === ELSE) return false;
339
+ const said = this.says(declaration.type);
340
+ if (said) return said === OTHER;
341
+ const items = this.iterated(declaration);
342
+ if (items) return this.notNodes(items, depth + 1);
343
+ return Boolean(declaration.initializer) && this.notNode(declaration.initializer, depth + 1);
344
+ }
345
+
346
+ /** Whether `expression` is certainly not an array of nodes. */
347
+ notNodes(expression, depth) {
348
+ const ts = this.ts;
349
+ const inner = unwrapped(ts, expression);
350
+ if (depth > 32) return false;
351
+ if (isAssertion(ts, inner)) return ![null, NODES].includes(this.says(inner.type));
352
+ if (ts.isCallExpression(inner)) {
353
+ const items = methodOf(ts, inner, SOME);
354
+ return Boolean(items) && this.notNodes(items, depth + 1);
355
+ }
356
+ const declaration = this.declarationOf(inner);
357
+ if (!declaration) return true;
358
+ if (declaration === ELSE) return false;
359
+ const said = this.says(declaration.type);
360
+ if (said) return said !== NODES;
361
+ return Boolean(declaration.initializer) && this.notNodes(declaration.initializer, depth + 1);
362
+ }
363
+
364
+ /** The declaration of a name, or of `this.field`, as `nearestBinding` answers; `ELSE` else. */
365
+ declarationOf(expression) {
366
+ const ts = this.ts;
367
+ if (ts.isIdentifier(expression)) return nearestBinding(ts, expression);
368
+ const own =
369
+ ts.isPropertyAccessExpression(expression) &&
370
+ expression.expression.kind === ts.SyntaxKind.ThisKeyword;
371
+ return (own && this.thisField(expression)) || ELSE;
372
+ }
373
+
374
+ /** What an object literal is written as: the type it is declared, asserted or returned as. */
375
+ written(literal) {
376
+ const ts = this.ts;
377
+ let at = literal;
378
+ while (ts.isParenthesizedExpression(at.parent)) at = at.parent;
379
+ const parent = at.parent;
380
+ if (ts.isArrayLiteralExpression(parent)) return this.written(parent) === NODES ? NODE : null;
381
+ return this.type(givenType(ts, parent, at));
382
+ }
383
+ }
384
+
385
+ /** The type `parent` gives the value `at` in it: as a declaration, an assertion or a return. */
386
+ function givenType(ts, parent, at) {
387
+ if (isAssertion(ts, parent)) return parent.type;
388
+ if (ts.isReturnStatement(parent)) return ts.getContainingFunction(parent)?.type;
389
+ if (ts.isArrowFunction(parent)) return parent.body === at ? parent.type : undefined;
390
+ const declared = ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent);
391
+ return declared && parent.initializer === at ? parent.type : undefined;
392
+ }
393
+
394
+ /** The array `call` calls one of `methods` on, as `nodes.find(...)` does. */
395
+ function methodOf(ts, call, methods) {
396
+ const callee = ts.isCallExpression(call) && call.expression;
397
+ const named = callee && ts.isPropertyAccessExpression(callee) && methods.has(callee.name.text);
398
+ return named ? callee.expression : null;
399
+ }
400
+
401
+ /** The edit that renames a property name node to `to`, keeping a string's quotes. */
402
+ function renamed(name, to) {
403
+ const start = name.getStart();
404
+ const quoted = name.getText() !== name.text;
405
+ return { start: quoted ? start + 1 : start, end: name.getEnd() - (quoted ? 1 : 0), text: to };
406
+ }
407
+
408
+ /** `{ name }` taken from a node as `{ tag: name }`, and `{ name: n }` as `{ tag: n }`. */
409
+ function destructured(ts, pattern, edits, fields) {
410
+ for (const element of pattern.elements) {
411
+ const key = element.propertyName ?? (element.dotDotDotToken ? null : element.name);
412
+ const field =
413
+ key && ts.isIdentifier(key) && Object.hasOwn(fields, key.text) && fields[key.text];
414
+ if (!field) continue;
415
+ if (element.propertyName) edits.push(renamed(key, field.to));
416
+ else edits.push({ start: key.getStart(), end: key.getStart(), text: `${field.to}: ` });
417
+ }
418
+ }
419
+
420
+ /** The renamed field a destructuring pattern takes, if any. */
421
+ function takenField(ts, pattern, fields) {
422
+ for (const element of pattern.elements) {
423
+ const key = element.propertyName ?? (element.dotDotDotToken ? null : element.name);
424
+ if (key && ts.isIdentifier(key) && Object.hasOwn(fields, key.text)) return key.text;
425
+ }
426
+ return null;
427
+ }
428
+
429
+ /** An object literal written as a node with its `name` key as `tag`. */
430
+ function literal(ts, object, edits, fields) {
431
+ for (const property of object.properties) {
432
+ const key = property.name;
433
+ const named = key && (ts.isIdentifier(key) || ts.isStringLiteral(key));
434
+ const field = named && Object.hasOwn(fields, key.text) && fields[key.text];
435
+ if (!field) continue;
436
+ if (ts.isShorthandPropertyAssignment(property)) {
437
+ edits.push({ start: key.getStart(), end: key.getStart(), text: `${field.to}: ` });
438
+ } else if (ts.isPropertyAssignment(property)) {
439
+ edits.push(renamed(key, field.to));
440
+ }
441
+ }
442
+ }
443
+
444
+ /** Where a node is in its file, as a note gives it. */
445
+ const lineOf = (source, node) => source.getLineAndCharacterOfPosition(node.getStart()).line + 1;
446
+
447
+ /** The note for a read of `old` this migration cannot tell is a node's. */
448
+ function note(file, source, access, old, field) {
449
+ const read = access.getText().replace(/\s+/g, ' ');
450
+ const at = read.lastIndexOf(old);
451
+ const instead = read.slice(0, at) + field.to + read.slice(at + old.length);
452
+ return (
453
+ `${file}:${lineOf(source, access)}: ${read} may be an engine node's ${field.what}, which is ` +
454
+ `now ${field.to}. If it is, read ${instead} instead.`
455
+ );
456
+ }
457
+
458
+ /** The note for a field taken from a node cast to another type, which still compiles. */
459
+ function castNote(file, source, node, verb, old, field) {
460
+ const text = node.getText().replace(/\s+/g, ' ');
461
+ return (
462
+ `${file}:${lineOf(source, node)}: ${text} ${verb}s ${old} from an engine node read as ` +
463
+ `another type. Its ${field.what} is now ${field.to}: ${verb} ${field.to}, and say so in the type.`
464
+ );
465
+ }
466
+
467
+ /** A `.name` or `['name']` of a renamed field: what it is read from, and the property's node. */
468
+ function fieldRead(ts, node, fields) {
469
+ if (ts.isPropertyAccessExpression(node) && Object.hasOwn(fields, node.name.text)) {
470
+ return { receiver: node.expression, key: node.name };
471
+ }
472
+ const argument = ts.isElementAccessExpression(node) && node.argumentExpression;
473
+ if (argument && ts.isStringLiteralLike(argument) && Object.hasOwn(fields, argument.text)) {
474
+ return { receiver: node.expression, key: argument };
475
+ }
476
+ return null;
477
+ }
478
+
479
+ /** Whether a `.name` is read from an `ElementRef`'s `nativeElement`. */
480
+ const fromNativeElement = (ts, receiver) =>
481
+ ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'nativeElement';
482
+
483
+ /** One read of a field: an edit where it is a node's, a note where it may be. */
484
+ function read(context, node) {
485
+ const { ts, reader, edits, notes, file, source, typed, fields } = context;
486
+ const found = fieldRead(ts, node, fields);
487
+ if (!found) return;
488
+ const field = fields[found.key.text];
489
+ if (reader.kind(found.receiver) === NODE) {
490
+ edits.push(renamed(found.key, field.to));
491
+ return;
492
+ }
493
+ if (reader.castNode(found.receiver)) {
494
+ notes.push(castNote(file, source, node, 'read', found.key.text, field));
495
+ return;
496
+ }
497
+ const unsure = fromNativeElement(ts, found.receiver) || typed;
498
+ const said =
499
+ unsure && !reader.notNode(found.receiver) && note(file, source, node, found.key.text, field);
500
+ if (said && !notes.includes(said)) {
501
+ notes.push(said);
502
+ }
503
+ }
504
+
505
+ /** The destructuring patterns and object literals that name a field as a key of a node. */
506
+ function keys(context, node) {
507
+ const { ts, reader, edits, notes, file, source, fields } = context;
508
+ const pattern =
509
+ (ts.isVariableDeclaration(node) || ts.isParameter(node)) &&
510
+ ts.isObjectBindingPattern(node.name);
511
+ if (pattern && reader.binding(node, 0) === NODE) destructured(ts, node.name, edits, fields);
512
+ else if (pattern && node.initializer && reader.castNode(node.initializer)) {
513
+ const taken = takenField(ts, node.name, fields);
514
+ if (taken) notes.push(castNote(file, source, node, 'take', taken, fields[taken]));
515
+ }
516
+ if (ts.isObjectLiteralExpression(node) && reader.written(node) === NODE) {
517
+ literal(ts, node, edits, fields);
518
+ }
519
+ }
520
+
521
+ /** A renamed field or getter of a class that implements a node type, by its new name. */
522
+ function ownField(context, node) {
523
+ const { ts, reader, edits, fields } = context;
524
+ const member = ts.isPropertyDeclaration(node) || ts.isGetAccessorDeclaration(node);
525
+ const own = member && ts.isIdentifier(node.name) && Object.hasOwn(fields, node.name.text);
526
+ if (own && ts.isClassLike(node.parent) && implementsNode(ts, node.parent, reader.names)) {
527
+ edits.push(renamed(node.name, fields[node.name.text].to));
528
+ }
529
+ }
530
+
531
+ /** Rewrites one file's reads of a node's renamed fields, and answers its notes. */
532
+ function rewrite(ts, host, file, text, { types, fields }) {
533
+ const source = ts.createSourceFile(
534
+ file,
535
+ text,
536
+ ts.ScriptTarget.Latest,
537
+ true,
538
+ scriptKind(ts, file),
539
+ );
540
+ const names = imported(ts, source, types);
541
+ localTypes(ts, source, names);
542
+ const context = {
543
+ ts,
544
+ reader: new Reader(ts, names),
545
+ edits: [],
546
+ notes: [],
547
+ file,
548
+ source,
549
+ typed: names.size > 0,
550
+ fields,
551
+ };
552
+ const visit = (node) => {
553
+ read(context, node);
554
+ keys(context, node);
555
+ ownField(context, node);
556
+ ts.forEachChild(node, visit);
557
+ };
558
+ visit(source);
559
+ if (context.edits.length) host.write(file, applied(text, context.edits));
560
+ return context.notes;
561
+ }
562
+
563
+ /** An interface or type in the file built on a node type, which is one too. */
564
+ function localType(ts, node, names) {
565
+ if (ts.isInterfaceDeclaration(node)) {
566
+ const bases = (node.heritageClauses ?? []).flatMap((clause) => clause.types);
567
+ return bases.some((base) => names.has(base.expression.getText())) ? node.name.text : null;
568
+ }
569
+ const alias = ts.isTypeAliasDeclaration(node) && isNodeType(ts, node.type, names);
570
+ return alias ? node.name.text : null;
571
+ }
572
+
573
+ /** Adds the file's own node types to `names`, until one built on another is found too. */
574
+ function localTypes(ts, source, names) {
575
+ if (!names.size) return;
576
+ let grew = true;
577
+ while (grew) {
578
+ grew = false;
579
+ const visit = (node) => {
580
+ const name = localType(ts, node, names);
581
+ if (name && !names.has(name)) {
582
+ names.add(name);
583
+ grew = true;
584
+ }
585
+ ts.forEachChild(node, visit);
586
+ };
587
+ visit(source);
588
+ }
589
+ }
590
+
591
+ /**
592
+ * A migration that renames node fields: `types` are the node types by the entry point that exports
593
+ * them, and `fields` each old name's new one, with what a note calls it.
594
+ *
595
+ * @param {{ types: Record<string, string[]>, fields: Record<string, { to: string, what: string }> }} spec
596
+ */
597
+ function nodeFieldRenames(spec) {
598
+ const word = new RegExp(`\\b(${Object.keys(spec.fields).join('|')})\\b`);
599
+ // Whether a file can read one of the fields at all, before it is parsed.
600
+ const mentions = (text) =>
601
+ text !== null &&
602
+ word.test(text) &&
603
+ (Object.keys(spec.types).some((entry) => text.includes(entry)) ||
604
+ text.includes('nativeElement'));
605
+ /** @param {import('./host.cjs').Host} host */
606
+ return (host) => {
607
+ const ts = typescript();
608
+ const notes = [];
609
+ for (const file of files(host)) {
610
+ const text = SOURCE.test(file) ? host.read(file) : null;
611
+ if (mentions(text)) notes.push(...rewrite(ts, host, file, text, spec));
612
+ }
613
+ return notes;
614
+ };
615
+ }
616
+
617
+ module.exports = { nodeFieldRenames };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-native/migrate",
3
- "version": "0.16.0",
3
+ "version": "0.17.1",
4
4
  "description": "The migrations that update an Angular Native app to a new release, for nx migrate, ng update and npx.",
5
5
  "keywords": [
6
6
  "angular",
@@ -82,4 +82,4 @@ function syncAppVersions(host) {
82
82
  ];
83
83
  }
84
84
 
85
- module.exports = { syncAppVersions };
85
+ module.exports = { syncAppVersions, formatted };