@ng-native/migrate 0.0.0 → 0.3.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.
@@ -0,0 +1,363 @@
1
+ /**
2
+ * 0.3.0 made `Tracking`'s `available` a getter, as `Haptics`, `Fonts` and `SplashScreen` have it:
3
+ * the answer is known at once and never changes. A call to it is now a call to a boolean.
4
+ *
5
+ * In each file that imports `Tracking` from `@ng-native/expo/tracking`, a `.available()` is
6
+ * rewritten to `.available` where what it is read from is known to be a `Tracking`: `inject(Tracking)`
7
+ * itself, `this.` a member of the enclosing class that holds one, or a name whose nearest
8
+ * declaration holds one. Holding one means initialised with `inject(Tracking)` or typed `Tracking`.
9
+ * A component's template, inline or in the file its `templateUrl` names, reads that component's own
10
+ * members, so it is rewritten for those alone. `.available()` on anything else is left alone, so
11
+ * another service's `available()` keeps its call. A namespace import is noted rather than followed.
12
+ */
13
+ const { applied, scriptKind, SOURCE, typescript } = require('./move-imports.cjs');
14
+ const { files } = require('./host.cjs');
15
+
16
+ const ENTRY = '@ng-native/expo/tracking';
17
+
18
+ /** The local names `Tracking` is imported as, and the namespace import, if the file has one. */
19
+ function imported(ts, source) {
20
+ const types = new Set();
21
+ let namespace = null;
22
+ for (const statement of source.statements) {
23
+ if (!ts.isImportDeclaration(statement) || statement.moduleSpecifier.text !== ENTRY) continue;
24
+ const bindings = statement.importClause?.namedBindings;
25
+ if (bindings && ts.isNamespaceImport(bindings)) namespace = statement;
26
+ for (const element of bindings && ts.isNamedImports(bindings) ? bindings.elements : []) {
27
+ if ((element.propertyName ?? element.name).text === 'Tracking') types.add(element.name.text);
28
+ }
29
+ }
30
+ return { types, namespace };
31
+ }
32
+
33
+ /** Whether `node` is `inject(Tracking)`. */
34
+ const isInjected = (ts, node, types) =>
35
+ ts.isCallExpression(node) &&
36
+ ts.isIdentifier(node.expression) &&
37
+ node.expression.text === 'inject' &&
38
+ node.arguments.length === 1 &&
39
+ ts.isIdentifier(node.arguments[0]) &&
40
+ types.has(node.arguments[0].text);
41
+
42
+ /** Whether a variable, property or parameter holds a `Tracking`. */
43
+ function holds(ts, declaration, types) {
44
+ const { type, initializer } = declaration;
45
+ if (type && ts.isTypeReferenceNode(type) && types.has(type.typeName.getText())) return true;
46
+ return Boolean(initializer && isInjected(ts, initializer, types));
47
+ }
48
+
49
+ const isStatic = (ts, node) =>
50
+ Boolean(ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword));
51
+
52
+ /**
53
+ * The members of a class that hold a `Tracking`, apart by whether `this` reaches them from an
54
+ * instance or from the class itself: properties, and constructor parameter properties.
55
+ */
56
+ function classHolders(ts, cls, types) {
57
+ const names = { instance: new Set(), static: new Set() };
58
+ for (const member of cls.members) {
59
+ if (
60
+ ts.isPropertyDeclaration(member) &&
61
+ ts.isIdentifier(member.name) &&
62
+ holds(ts, member, types)
63
+ ) {
64
+ names[isStatic(ts, member) ? 'static' : 'instance'].add(member.name.text);
65
+ }
66
+ if (!ts.isConstructorDeclaration(member)) continue;
67
+ for (const parameter of member.parameters) {
68
+ const property = ts.getModifiers(parameter)?.length && ts.isIdentifier(parameter.name);
69
+ if (property && holds(ts, parameter, types)) names.instance.add(parameter.name.text);
70
+ }
71
+ }
72
+ return names;
73
+ }
74
+
75
+ /** A class member whose own `this` is the class's: a method, accessor, constructor or field. */
76
+ const isMember = (ts, node) =>
77
+ (ts.isClassDeclaration(node.parent) || ts.isClassExpression(node.parent)) &&
78
+ (ts.isMethodDeclaration(node) ||
79
+ ts.isConstructorDeclaration(node) ||
80
+ ts.isGetAccessorDeclaration(node) ||
81
+ ts.isSetAccessorDeclaration(node) ||
82
+ ts.isPropertyDeclaration(node) ||
83
+ ts.isClassStaticBlockDeclaration(node));
84
+
85
+ /**
86
+ * The class `this` is in at `node`, and whether it is the class itself rather than an instance, or
87
+ * null where `this` is something else: inside a plain function or an object literal's method, which
88
+ * bind a `this` of their own. An arrow function keeps the `this` around it.
89
+ */
90
+ function thisOf(ts, node) {
91
+ for (let at = node.parent; at; at = at.parent) {
92
+ if (isMember(ts, at)) {
93
+ return { cls: at.parent, static: ts.isClassStaticBlockDeclaration(at) || isStatic(ts, at) };
94
+ }
95
+ if (ts.isFunctionLike(at) && !ts.isArrowFunction(at)) return null;
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /** What a binding of a name is when only its shape is known: a pattern, a catch, a function. */
101
+ const ELSE = Symbol('something else');
102
+
103
+ /** Whether a binding name, or any name inside a destructuring pattern, is `name`. */
104
+ function binds(ts, nameNode, name) {
105
+ if (ts.isIdentifier(nameNode)) return nameNode.text === name;
106
+ return nameNode.elements.some(
107
+ (element) => !ts.isOmittedExpression(element) && binds(ts, element.name, name),
108
+ );
109
+ }
110
+
111
+ /** A variable or parameter binding `name`: itself if bound plainly, `ELSE` if destructured. */
112
+ const bound = (ts, declaration, name) => (ts.isIdentifier(declaration.name) ? declaration : ELSE);
113
+
114
+ /** The bindings of `name` a list of variable declarations makes, as `bound` answers. */
115
+ function inDeclarations(ts, list, name) {
116
+ const found = list.declarations.find((d) => binds(ts, d.name, name));
117
+ return found && bound(ts, found);
118
+ }
119
+
120
+ /** The bindings of `name` a block's statements make: variables, and functions and classes. */
121
+ function inStatements(ts, statements, name) {
122
+ for (const statement of statements) {
123
+ if (ts.isVariableStatement(statement)) {
124
+ const found = inDeclarations(ts, statement.declarationList, name);
125
+ if (found) return found;
126
+ }
127
+ const named = ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement);
128
+ if (named && statement.name?.text === name) return ELSE;
129
+ }
130
+ return undefined;
131
+ }
132
+
133
+ /** A function's own name, if it is an expression's, and its parameters. */
134
+ function inFunction(ts, node, name) {
135
+ if (ts.isFunctionExpression(node) && node.name?.text === name) return ELSE;
136
+ const parameter = node.parameters.find((p) => binds(ts, p.name, name));
137
+ return parameter && bound(ts, parameter);
138
+ }
139
+
140
+ /** A `for`, `for...of` or `for...in` loop's own variables. */
141
+ function inLoop(ts, node, name) {
142
+ const { initializer } = node;
143
+ if (!initializer || !ts.isVariableDeclarationList(initializer)) return undefined;
144
+ return inDeclarations(ts, initializer, name);
145
+ }
146
+
147
+ /** A `catch` clause's binding. */
148
+ const inCatch = (ts, node, name) =>
149
+ node.variableDeclaration && binds(ts, node.variableDeclaration.name, name) ? ELSE : undefined;
150
+
151
+ const isLoop = (ts, node) =>
152
+ ts.isForStatement(node) || ts.isForOfStatement(node) || ts.isForInStatement(node);
153
+
154
+ const isBlock = (ts, node) => ts.isSourceFile(node) || ts.isBlock(node) || ts.isModuleBlock(node);
155
+
156
+ /**
157
+ * The binding of `name` the scope `node` opens, if it makes one there: the declaration when it is a
158
+ * plain variable or parameter, `ELSE` for one only its shape is known of (a destructured name, a
159
+ * catch binding, a function or class), which is never a `Tracking` this can tell.
160
+ */
161
+ function declaredIn(ts, node, name) {
162
+ if (ts.isFunctionLike(node)) return inFunction(ts, node, name);
163
+ if (isLoop(ts, node)) return inLoop(ts, node, name);
164
+ if (ts.isCatchClause(node)) return inCatch(ts, node, name);
165
+ return isBlock(ts, node) ? inStatements(ts, node.statements, name) : undefined;
166
+ }
167
+
168
+ /** Whether the nearest binding of the name `identifier` reads holds a `Tracking`. */
169
+ function identifierHolds(ts, identifier, types) {
170
+ for (let at = identifier.parent; at; at = at.parent) {
171
+ const declaration = declaredIn(ts, at, identifier.text);
172
+ if (declaration === ELSE) return false;
173
+ if (declaration) return holds(ts, declaration, types);
174
+ }
175
+ return false;
176
+ }
177
+
178
+ /** Whether `receiver` is a `Tracking`, as this file can tell. */
179
+ function isTracking(ts, receiver, types) {
180
+ if (isInjected(ts, receiver, types)) return true;
181
+ if (ts.isIdentifier(receiver)) return identifierHolds(ts, receiver, types);
182
+ if (!ts.isPropertyAccessExpression(receiver)) return false;
183
+ if (receiver.expression.kind !== ts.SyntaxKind.ThisKeyword) return false;
184
+ const self = thisOf(ts, receiver);
185
+ if (!self) return false;
186
+ const names = classHolders(ts, self.cls, types);
187
+ return (self.static ? names.static : names.instance).has(receiver.name.text);
188
+ }
189
+
190
+ /** Each `x.available()` in the code whose `x` is a `Tracking`, as an edit dropping the call. */
191
+ function codeEdits(ts, source, types) {
192
+ const edits = [];
193
+ const visit = (node) => {
194
+ const callee = ts.isCallExpression(node) && node.arguments.length === 0 && node.expression;
195
+ const target =
196
+ callee && ts.isPropertyAccessExpression(callee) && callee.name.text === 'available';
197
+ if (target && isTracking(ts, callee.expression, types)) {
198
+ edits.push({ start: callee.getEnd(), end: node.getEnd(), text: '' });
199
+ }
200
+ ts.forEachChild(node, visit);
201
+ };
202
+ visit(source);
203
+ return edits;
204
+ }
205
+
206
+ /**
207
+ * A template declaring `name` itself: `@let`, a `@for` or `*ngFor` item or `let` alias, a
208
+ * `#` reference, an `as` alias, or an `ng-template`'s `let-`. Such a name may be something other
209
+ * than the component's member wherever it is in scope.
210
+ */
211
+ const declaration = (name) =>
212
+ new RegExp(
213
+ `@let\\s+${name}\\b|\\blet[\\s-]+${name}\\b|#${name}\\b|\\bas\\s+${name}\\b|@for\\s*\\(\\s*${name}\\s+of\\b`,
214
+ );
215
+ const declares = (text, name) => declaration(name).test(text);
216
+
217
+ /**
218
+ * A template with `name.available()` read as a property, for each name that holds a `Tracking` and
219
+ * that the template does not declare for itself, and the names it left for that reason.
220
+ */
221
+ function inTemplate(text, names) {
222
+ let next = text;
223
+ const left = [];
224
+ for (const name of new Set(names)) {
225
+ if (declares(text, name)) {
226
+ if (new RegExp(`\\b${name}\\.available\\(\\s*\\)`).test(text)) left.push(name);
227
+ continue;
228
+ }
229
+ next = next.replace(new RegExp(`\\b${name}\\.available\\(\\s*\\)`, 'g'), `${name}.available`);
230
+ }
231
+ return { text: next, left };
232
+ }
233
+
234
+ /** The line of a template file where it first declares `name` for itself. */
235
+ const declarationLine = (text, name) =>
236
+ text.slice(0, text.search(declaration(name))).split('\n').length;
237
+
238
+ /** The note for a name a template declares for itself, which it leaves to the developer. */
239
+ const localNote = (where, name) =>
240
+ `${where}: The template declares a ${name} of its own, so it was left as it is. ` +
241
+ `Where it reads the component's Tracking, read ${name}.available without calling it.`;
242
+
243
+ /** The object literal a class's `@Component(...)` decorator is given, if it has one. */
244
+ function componentMetadata(ts, cls, components) {
245
+ for (const decorator of ts.getDecorators(cls) ?? []) {
246
+ const call = decorator.expression;
247
+ if (!ts.isCallExpression(call) || !components.has(call.expression.getText())) continue;
248
+ const [metadata] = call.arguments;
249
+ if (metadata && ts.isObjectLiteralExpression(metadata)) return metadata;
250
+ }
251
+ return null;
252
+ }
253
+
254
+ /** A workspace path with `./` and `../` resolved. */
255
+ function normalise(path) {
256
+ const parts = [];
257
+ for (const part of path.split('/')) {
258
+ if (part === '..') parts.pop();
259
+ else if (part !== '.' && part !== '') parts.push(part);
260
+ }
261
+ return parts.join('/');
262
+ }
263
+
264
+ /** The names `Component` is imported from `@angular/core` as. */
265
+ function componentNames(ts, source) {
266
+ const names = new Set();
267
+ for (const statement of source.statements) {
268
+ if (!ts.isImportDeclaration(statement) || statement.moduleSpecifier.text !== '@angular/core') {
269
+ continue;
270
+ }
271
+ const bindings = statement.importClause?.namedBindings;
272
+ for (const element of bindings && ts.isNamedImports(bindings) ? bindings.elements : []) {
273
+ if ((element.propertyName ?? element.name).text === 'Component') names.add(element.name.text);
274
+ }
275
+ }
276
+ return names;
277
+ }
278
+
279
+ /** One component's inline template as an edit, and the template file it names, with its holders. */
280
+ function componentTemplate(ts, source, file, metadata, names, dir, found) {
281
+ for (const property of metadata.properties) {
282
+ if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name)) continue;
283
+ const value = property.initializer;
284
+ if (!ts.isStringLiteralLike(value)) continue;
285
+ if (property.name.text === 'templateUrl') found.urls.push([normalise(dir + value.text), names]);
286
+ if (property.name.text !== 'template') continue;
287
+ const { text, left } = inTemplate(value.getText(), names);
288
+ const line = source.getLineAndCharacterOfPosition(property.getStart()).line + 1;
289
+ for (const name of left) found.notes.push(localNote(`${file}:${line}`, name));
290
+ if (text !== value.getText()) {
291
+ found.edits.push({ start: value.getStart(), end: value.getEnd(), text });
292
+ }
293
+ }
294
+ }
295
+
296
+ /** Each component's inline template edits, and the template files it names, with its holders. */
297
+ function templates(ts, source, file, types) {
298
+ const found = { edits: [], urls: [], notes: [] };
299
+ const dir = file.includes('/') ? file.slice(0, file.lastIndexOf('/') + 1) : '';
300
+ const components = componentNames(ts, source);
301
+ const visit = (node) => {
302
+ const cls = ts.isClassDeclaration(node) || ts.isClassExpression(node);
303
+ const metadata = cls && componentMetadata(ts, node, components);
304
+ // A template reads the instance's members.
305
+ const names = metadata ? classHolders(ts, node, types).instance : null;
306
+ if (names?.size) componentTemplate(ts, source, file, metadata, names, dir, found);
307
+ ts.forEachChild(node, visit);
308
+ };
309
+ visit(source);
310
+ return found;
311
+ }
312
+
313
+ /** The note for a namespace import, whose names cannot be followed through. */
314
+ function namespaceNote(file, source, statement) {
315
+ const line = source.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
316
+ return (
317
+ `${file}:${line}: A namespace import of '${ENTRY}' cannot be followed automatically. ` +
318
+ "Tracking's available is now a property: read it as tracking.available, without calling it."
319
+ );
320
+ }
321
+
322
+ /** Rewrites one source file, and answers the template files it names, each with its holders. */
323
+ function rewriteSource(ts, host, file, text, notes) {
324
+ const source = ts.createSourceFile(
325
+ file,
326
+ text,
327
+ ts.ScriptTarget.Latest,
328
+ true,
329
+ scriptKind(ts, file),
330
+ );
331
+ const { types, namespace } = imported(ts, source);
332
+ if (namespace) notes.push(namespaceNote(file, source, namespace));
333
+ if (!types.size) return [];
334
+ const { edits, urls, notes: local } = templates(ts, source, file, types);
335
+ notes.push(...local);
336
+ edits.push(...codeEdits(ts, source, types));
337
+ if (edits.length) host.write(file, applied(text, edits));
338
+ return urls;
339
+ }
340
+
341
+ /** @param {import('./host.cjs').Host} host */
342
+ function trackingAvailableGetter(host) {
343
+ const ts = typescript();
344
+ const notes = [];
345
+ const named = new Map();
346
+ for (const file of files(host)) {
347
+ const text = SOURCE.test(file) ? host.read(file) : null;
348
+ if (text === null || !text.includes(ENTRY)) continue;
349
+ for (const [url, names] of rewriteSource(ts, host, file, text, notes)) {
350
+ named.set(url, [...(named.get(url) ?? []), ...names]);
351
+ }
352
+ }
353
+ for (const [url, names] of named) {
354
+ const text = host.read(url);
355
+ if (text === null) continue;
356
+ const { text: next, left } = inTemplate(text, names);
357
+ for (const name of left) notes.push(localNote(`${url}:${declarationLine(text, name)}`, name));
358
+ if (next !== text) host.write(url, next);
359
+ }
360
+ return notes;
361
+ }
362
+
363
+ module.exports = { trackingAvailableGetter };