Skip to content

Commit 6ff0994

Browse files
committed
support then / catch
1 parent 736e5a1 commit 6ff0994

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed

Diff for: src/rules/valid-context-access.ts

+6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { createRule } from "../utils"
22
import { extractContextReferences } from "./reference-helpers/svelte-context"
33
import { extractSvelteLifeCycleReferences } from "./reference-helpers/svelte-lifecycle"
44
import { extractTaskReferences } from "./reference-helpers/microtask"
5+
import { isInsideOfPromiseThenOrCatch } from "../utils/promise"
56
import type { AST } from "svelte-eslint-parser"
67
import type { TSESTree } from "@typescript-eslint/types"
78

@@ -153,6 +154,11 @@ export default createRule("valid-context-access", {
153154
return
154155
}
155156

157+
if (isInsideOfPromiseThenOrCatch(currentNode)) {
158+
report(contextCallExpression)
159+
return
160+
}
161+
156162
let { parent } = currentNode
157163
while (parent) {
158164
parent = parent.parent

Diff for: src/utils/promise.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import type { TSESTree } from "@typescript-eslint/types"
2+
3+
/**
4+
* Return true if `node` is inside of `then` or `catch`.
5+
*/
6+
export function isInsideOfPromiseThenOrCatch(node: TSESTree.Node): boolean {
7+
let parent: TSESTree.Node | undefined = node.parent
8+
while (parent) {
9+
parent = parent.parent
10+
if (parent?.type !== "ExpressionStatement") {
11+
continue
12+
}
13+
const expression = parent?.expression
14+
if (expression == null || expression?.type !== "CallExpression") {
15+
return false
16+
}
17+
18+
const callee = expression.callee
19+
if (callee.type !== "MemberExpression") {
20+
return false
21+
}
22+
23+
const property = callee.property
24+
return (
25+
property.type === "Identifier" &&
26+
["then", "catch"].includes(property.name)
27+
)
28+
}
29+
30+
return false
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
- message: Do not call setContext except during component initialization.
2+
line: 5
3+
column: 5
4+
- message: Do not call setContext except during component initialization.
5+
line: 9
6+
column: 5
7+
- message: Do not call setContext except during component initialization.
8+
line: 13
9+
column: 5
10+
- message: Do not call setContext except during component initialization.
11+
line: 17
12+
column: 5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<script>
2+
import { setContext } from "svelte"
3+
4+
Promise.resolve().then(() => {
5+
setContext("answer", 42)
6+
})
7+
8+
Promise.resolve().then(function () {
9+
setContext("answer", 42)
10+
})
11+
12+
Promise.resolve().catch(() => {
13+
setContext("answer", 42)
14+
})
15+
16+
Promise.resolve().catch(function () {
17+
setContext("answer", 42)
18+
})
19+
</script>

0 commit comments

Comments
 (0)