-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathrxjsPipeableOperatorsOnlyRule.ts
444 lines (438 loc) · 15 KB
/
rxjsPipeableOperatorsOnlyRule.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// Original author Bowen Ni, Shino Kurian, Michael Lorton.
// Modifications mgechev.
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';
import * as ts from 'typescript';
import { subtractSets, concatSets, isObservable, returnsObservable, computeInsertionIndexForImports } from './utils';
/**
* A typed TSLint rule that inspects observable chains using patched RxJs
* operators and turns them into a pipeable operator chain.
*/
export class Rule extends Lint.Rules.TypedRule {
static metadata: Lint.IRuleMetadata = {
ruleName: 'rxjs-pipeable-operators-only',
description: `Pipeable operators offer a new way of composing observable chains and
they have advantages for both application developers and library
authors.`,
optionsDescription: '',
options: null,
typescriptOnly: true,
type: 'functionality'
};
static FAILURE_STRING = 'prefer pipeable operators.';
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, ctx => this.walk(ctx, program));
}
private walk(ctx: Lint.WalkContext<void>, program: ts.Program) {
this.removePatchedOperatorImports(ctx);
const sourceFile = ctx.sourceFile;
const typeChecker = program.getTypeChecker();
const insertionStart = computeInsertionIndexForImports(sourceFile);
let rxjsOperatorImports = findImportedRxjsOperators(sourceFile);
/**
* Creates a lint failure with suggested replacements if an observable chain
* of patched operators is found.
*
* <p>The expression
* <pre>const subs = foo.do(console.log)
* .map( x =>2*x)
* .do(console.log)
* .switchMap( y => z)
* .subscribe(fn);
* </pre>
*
* should produce a failure at the underlined section below:
* <pre>const subs = foo.do(console.log)
* ----------------
* .map( x =>2*x)
* --------------
* .do(console.log)
* ----------------
* .switchMap( y => z)
* -------------------
* .subscribe(fn);
* </pre>
* and suggest replacements that would produce text like
* <pre>const subs = foo.pipe(
* tap(console.log),
* map( x =>2*x),
* tap(console.log),
* switchMap( y => z),
* )
* .subscribe(fn);
* </pre>
*/
function checkPatchableOperatorUsage(node: ts.Node): void {
// Navigate up the expression tree until a call expression with an rxjs
// operator is found.
// If the parent expression is also an rxjs operator call expression,
// continue.
// If not, then verify that the parent is indeed an observable.
// files the node with the expression 'foo'.
// Using the example above, the traversal would stop at 'foo'.
if (!isRxjsInstanceOperatorCallExpression(node, typeChecker)) {
return ts.forEachChild(node, checkPatchableOperatorUsage);
}
const immediateParent = (node as ts.CallExpression).expression as ts.PropertyAccessExpression;
// Get the preceeding expression (specific child node) to which the
// current node was chained to. If node represents text like
// foo.do(console.log).map( x =>2*x), then preceedingNode would have the
// text foo.do(console.log).
const preceedingNode = immediateParent.expression;
// If the preceeding node is also an RxJS call then continue traversal.
if (isRxjsInstanceOperatorCallExpression(preceedingNode, typeChecker)) {
return ts.forEachChild(node, checkPatchableOperatorUsage);
}
// Some Rxjs operators have same names as array operators, and could be
// chained array operators that return an observable instead. These nodes
// should be skipped.
// eg.functionReturningArray().reduce(functionProducingObservable)
// or arrayObject.reduce(functionProducingObservable)
if (tsutils.isCallExpression(preceedingNode) || tsutils.isNewExpression(preceedingNode)) {
if (!returnsObservable(preceedingNode, typeChecker)) {
return ts.forEachChild(node, checkPatchableOperatorUsage);
}
} else if (!isObservable(typeChecker.getTypeAtLocation(preceedingNode), typeChecker)) {
return ts.forEachChild(node, checkPatchableOperatorUsage);
}
const failureStart = immediateParent.getStart(sourceFile) + immediateParent.getText(sourceFile).lastIndexOf('.');
const lastNode = findLastObservableExpression(preceedingNode, typeChecker);
const failureEnd = lastNode.getEnd();
const pipeReplacement = Lint.Replacement.appendText(preceedingNode.getEnd(), '.pipe(');
const operatorsToImport = new Set<string>();
const operatorReplacements = replaceWithPipeableOperators(preceedingNode, lastNode, operatorsToImport);
const operatorsToAdd = subtractSets(operatorsToImport, rxjsOperatorImports);
const importReplacements = createImportReplacements(operatorsToAdd, insertionStart);
rxjsOperatorImports = concatSets(rxjsOperatorImports, operatorsToAdd);
const allReplacements = [pipeReplacement, ...operatorReplacements, ...importReplacements];
ctx.addFailure(failureStart, failureEnd, Rule.FAILURE_STRING, allReplacements);
return ts.forEachChild(node, checkPatchableOperatorUsage);
}
return ts.forEachChild(ctx.sourceFile, checkPatchableOperatorUsage);
}
/**
* Generates replacements to remove imports for patched operators.
*/
private removePatchedOperatorImports(ctx: Lint.WalkContext<void>): void {
const sourceFile = ctx.sourceFile;
for (const importStatement of sourceFile.statements.filter(tsutils.isImportDeclaration)) {
const moduleSpecifier = importStatement.moduleSpecifier.getText();
if (!moduleSpecifier.startsWith(`'rxjs/operator/`) && !moduleSpecifier.startsWith(`'rxjs/add/operator/`)) {
continue;
}
const importStatementStart = importStatement.getStart(sourceFile);
const importStatementEnd = importStatement.getEnd();
ctx.addFailure(
importStatementStart,
importStatementEnd,
Rule.FAILURE_STRING,
Lint.Replacement.deleteFromTo(importStatementStart, importStatementEnd)
);
}
}
}
/**
* Returns true if the identifier of the current expression is an RxJS instance
* operator like map, switchMap etc.
*/
function isRxjsInstanceOperator(node: ts.PropertyAccessExpression) {
return 'Observable' !== node.expression.getText() && RXJS_OPERATORS.has(node.name.getText());
}
/**
* Returns true if {@link node} is a call expression containing an RxJs instance
* operator and returns an observable. eg map(fn), switchMap(fn)
*/
function isRxjsInstanceOperatorCallExpression(node: ts.Node, typeChecker: ts.TypeChecker) {
// Expression is of the form fn()
if (!tsutils.isCallExpression(node)) {
return false;
}
// Expression is of the form foo.fn
if (!tsutils.isPropertyAccessExpression(node.expression)) {
return false;
}
// fn is one of RxJs instance operators
if (!isRxjsInstanceOperator(node.expression)) {
return false;
}
// fn(): k. Checks if k is an observable. Required to distinguish between
// array operators with same name as RxJs operators.
if (!returnsObservable(node, typeChecker)) {
return false;
}
return true;
}
/**
* Finds all pipeable operators that are imported in the {@link sourceFile}.
*
* <p> Searches for import statements of the type
* <code> import {map} from 'rxjs/operators/map;</code>
* and collects the named bindings.
*/
function findImportedRxjsOperators(sourceFile: ts.SourceFile): Set<string> {
return new Set<string>(
sourceFile.statements.filter(tsutils.isImportDeclaration).reduce((current, decl) => {
if (!decl.importClause) {
return current;
}
if (!decl.moduleSpecifier.getText().startsWith(`'rxjs/operators`)) {
return current;
}
if (!decl.importClause.namedBindings) {
return current;
}
const bindings = decl.importClause.namedBindings;
if (ts.isNamedImports(bindings)) {
return [
...current,
...(Array.from(bindings.elements) || []).map(element => {
return element.name.getText();
})
];
}
return current;
}, [])
);
}
/**
* Generates an array of {@link Lint.Replacement} representing import statements
* for the {@link operatorsToAdd}.
*
* @param operatorsToAdd Set of Rxjs operators that need to be imported
* @param startIndex Position where the {@link Lint.Replacement} can be inserted
*/
function createImportReplacements(operatorsToAdd: Set<string>, startIndex: number): Lint.Replacement[] {
return [...Array.from(operatorsToAdd.values())].map(operator => {
let importPath: string;
if (NGRX_EFFECT_OPERATORS.has(operator)) {
importPath = '@ngrx/effects';
}
if (NGRX_STORE_OPERATORS.has(operator)) {
importPath = '@ngrx/store';
} else {
importPath = `rxjs/operators/${operator}`;
}
return Lint.Replacement.appendText(
startIndex,
`\nimport {${operator}} from '${importPath}';\n`
);
});
}
/**
* Returns the last chained RxJS call expression by walking up the AST.
*
* <p> For an expression like foo.map(Fn).switchMap(Fn) - the function starts
* with node = foo. node.parent - represents the property expression foo.map and
* node.parent.parent represents the call expression foo.map().
*
*/
function findLastObservableExpression(node: ts.Node, typeChecker: ts.TypeChecker): ts.Node {
let currentNode = node;
while (isAncestorRxjsOperatorCall(currentNode, typeChecker)) {
currentNode = currentNode.parent!.parent!;
}
return currentNode;
}
/**
* Returns true if the grandfather of the {@link node} is a call expression of
* an RxJs instance operator.
*/
function isAncestorRxjsOperatorCall(node: ts.Node, typeChecker: ts.TypeChecker): boolean {
// If this is the only operator in the chain.
if (!node.parent) {
return false;
}
// Do not overstep the boundary of an arrow function.
if (ts.isArrowFunction(node.parent)) {
return false;
}
if (!node.parent.parent) {
return false;
}
return isRxjsInstanceOperatorCallExpression(node.parent.parent, typeChecker);
}
/**
* Recursively generates {@link Lint.Replacement} to convert a chained rxjs call
* expression to an expression using pipeable rxjs operators.
*
* @param currentNode The node in the chained expression being processed
* @param lastNode The last node of the chained expression
* @param operatorsToImport Collects the operators encountered in the expression
* so far
* @param notStart Whether the {@link currentNode} is the first expression in
* the chain.
*/
function replaceWithPipeableOperators(
currentNode: ts.Node,
lastNode: ts.Node,
operatorsToImport: Set<string>,
notStart = false
): Lint.Replacement[] {
// Reached the root of the expression, nothing to replace.
if (!currentNode.parent || !currentNode.parent.parent) {
return [];
}
// For an arbitrary expression like
// foo.do(console.log).map( x =>2*x).do(console.log).switchMap( y => z);
// if currentNode is foo.do(console.log),
// immediateParent = foo.do(console.log).map
const immediateParent = currentNode.parent;
const immediateParentText = immediateParent.getText();
const identifierStart = immediateParentText.lastIndexOf('.');
const identifierText = immediateParentText.slice(identifierStart + 1);
let pipeableOperator = PIPEABLE_OPERATOR_MAPPING[identifierText];
if (pipeableOperator === undefined) {
pipeableOperator = identifierText;
}
if (identifierText !== 'let') {
operatorsToImport.add(pipeableOperator);
}
// Generates a replacement that would replace .map with map using absolute
// position of the text to be replaced.
const operatorReplacement = Lint.Replacement.replaceFromTo(
immediateParent.getEnd() - identifierText.length - 1,
immediateParent.getEnd(),
pipeableOperator
);
// parentNode = foo.do(console.log).map( x =>2*x)
const parentNode = currentNode.parent.parent;
const moreReplacements =
parentNode === lastNode
? [Lint.Replacement.appendText(parentNode.getEnd(), notStart ? ',)' : ')')]
: replaceWithPipeableOperators(parentNode, lastNode, operatorsToImport, true);
// Generates a replacement for adding a ',' after the call expression
const separatorReplacements = notStart ? [Lint.Replacement.appendText(currentNode.getEnd(), ',')] : [];
return [operatorReplacement, ...separatorReplacements, ...moreReplacements];
}
const NGRX_STORE_OPERATORS = new Set(['select']);
const NGRX_EFFECT_OPERATORS = new Set(['ofType']);
/**
* Set of all instance operators, including those renamed as part of lettable
* operator migration. Source:(RxJS v5)
* https://github.com/ReactiveX/rxjs/tree/stable/src/operators
*/
const RXJS_OPERATORS = new Set([
'audit',
'auditTime',
'buffer',
'bufferCount',
'bufferTime',
'bufferToggle',
'bufferWhen',
'catchError',
'combineAll',
'combineLatest',
'concat',
'concatAll',
'concatMap',
'concatMapTo',
'count',
'debounce',
'debounceTime',
'defaultIfEmpty',
'delay',
'delayWhen',
'dematerialize',
'distinct',
'distinctUntilChanged',
'distinctUntilKeyChanged',
'elementAt',
'every',
'exhaust',
'exhaustMap',
'expand',
'filter',
'finalize',
'find',
'findIndex',
'first',
'groupBy',
'ignoreElements',
'isEmpty',
'last',
'map',
'mapTo',
'materialize',
'max',
'merge',
'mergeAll',
'mergeMap',
'mergeMapTo',
'mergeScan',
'min',
'multicast',
'observeOn',
'onErrorResumeNext',
'pairwise',
'partition',
'pluck',
'publish',
'publishBehavior',
'publishLast',
'publishReplay',
'race',
'reduce',
'refCount',
'repeat',
'repeatWhen',
'retry',
'retryWhen',
'sample',
'sampleTime',
'scan',
'sequenceEqual',
'share',
'shareReplay',
'single',
'skip',
'skipLast',
'skipUntil',
'skipWhile',
'startWith',
'subscribeOn',
'switchAll',
'switchMap',
'switchMapTo',
'take',
'takeLast',
'takeUntil',
'takeWhile',
'tap',
'throttle',
'throttleTime',
'timeInterval',
'timeout',
'timeoutWith',
'timestamp',
'toArray',
'window',
'windowCount',
'windowTime',
'windowToggle',
'windowWhen',
'withLatestFrom',
'zip',
'zipAll',
'do',
'catch',
'flatMap',
'flatMapTo',
'finally',
'switch',
'let',
...Array.from(NGRX_STORE_OPERATORS),
...Array.from(NGRX_EFFECT_OPERATORS)
]);
/**
* Represents the mapping for pipeable version of some operators whose name has
* changed due to conflict with JavaScript keyword restrictions.
*/
const PIPEABLE_OPERATOR_MAPPING: { [key: string]: string } = {
let: '',
do: 'tap',
catch: 'catchError',
flatMap: 'mergeMap',
flatMapTo: 'mergeMapTo',
finally: 'finalize',
switch: 'switchAll'
};