@@ -35,14 +35,12 @@ export const noTopromiseRule = ruleCreator({
35
35
conversion : 'lastValueFrom' | 'firstValueFrom' ,
36
36
callExpression : es . CallExpression ,
37
37
observableNode : es . Node ,
38
+ importDeclarations : es . ImportDeclaration [ ] ,
38
39
) {
39
40
return function * fix ( fixer : TSESLint . RuleFixer ) {
40
41
let namespace = '' ;
41
42
let functionName : string = conversion ;
42
43
43
- const { body } = context . sourceCode . ast ;
44
- const importDeclarations = body . filter ( isImportDeclaration ) ;
45
-
46
44
const rxjsImportDeclaration = importDeclarations . find ( node => node . source . value === 'rxjs' ) ;
47
45
48
46
if ( rxjsImportDeclaration ?. specifiers ?. every ( isImportNamespaceSpecifier ) ) {
@@ -69,11 +67,8 @@ export const noTopromiseRule = ruleCreator({
69
67
`\nimport { ${ functionName } } from ${ quote } rxjs${ quote } ;` ,
70
68
) ;
71
69
} else {
72
- // No imports. Add to top of file.
73
- yield fixer . insertTextBefore (
74
- body [ 0 ] ,
75
- `import { ${ functionName } } from "rxjs";\n` ,
76
- ) ;
70
+ console . warn ( 'No import declarations found. Unable to suggest a fix.' ) ;
71
+ return ;
77
72
}
78
73
79
74
yield fixer . replaceText (
@@ -91,17 +86,25 @@ export const noTopromiseRule = ruleCreator({
91
86
if ( ! couldBeObservable ( memberExpression . object ) ) {
92
87
return ;
93
88
}
89
+
90
+ const { body } = context . sourceCode . ast ;
91
+ const importDeclarations = body . filter ( isImportDeclaration ) ;
92
+ if ( ! importDeclarations . length ) {
93
+ // couldBeObservable yet no imports? Skip.
94
+ return ;
95
+ }
96
+
94
97
context . report ( {
95
98
messageId : 'forbidden' ,
96
99
node : memberExpression . property ,
97
100
suggest : [
98
101
{
99
102
messageId : 'suggestLastValueFrom' ,
100
- fix : createFix ( 'lastValueFrom' , node , memberExpression . object ) ,
103
+ fix : createFix ( 'lastValueFrom' , node , memberExpression . object , importDeclarations ) ,
101
104
} ,
102
105
{
103
106
messageId : 'suggestFirstValueFrom' ,
104
- fix : createFix ( 'firstValueFrom' , node , memberExpression . object ) ,
107
+ fix : createFix ( 'firstValueFrom' , node , memberExpression . object , importDeclarations ) ,
105
108
} ,
106
109
] ,
107
110
} ) ;
0 commit comments