1 import { AST_NODE_TYPES } from "@typescript-eslint/utils"
2 import { createRule } from "../../create-rule"
3 import {
4 createWorkflowSdkBindings,
5 getEnclosingFunction,
6 isWhenThenCallbackFunction,
7 trackWorkflowSdkImports,
8 } from "../../util/workflow-scope"
9
10 type MessageIds = "nestedWhenInWorkflow"
11
12 export const rule = createRule<[], MessageIds>({
13 name: "no-nested-when-in-workflow",
14 meta: {
15 type: "problem",
16 docs: {
17 description:
18 "Disallow calling `when(...)` inside a `when().then()` callback in a workflow composition function. `when` tracks its pending condition in a single shared slot rather than a stack, so the inner `.then()` clears that slot before the outer `.then()` reads it — the workflow throws a `TypeError` at server boot instead of failing at build time.",
19 },
20 messages: {
21 nestedWhenInWorkflow:
22 "Do not call `when(...)` inside another `when().then()` callback. `when` keeps its pending condition in one shared slot, so the inner `.then()` clears it before the outer `.then()` can read it — this throws `TypeError: Cannot read properties of undefined (reading 'steps')` at server boot, not at build time. Restructure into sibling `when(...).then(...)` calls instead of nesting them.",
23 },
24 schema: [],
25 },
26 defaultOptions: [],
27 create(context) {
28 const bindings = createWorkflowSdkBindings()
29
30 return {
31 ImportDeclaration(node) {
32 trackWorkflowSdkImports(node, bindings)
33 },
34
35 CallExpression(node) {
36 if (bindings.when.size === 0) {
37 return
38 }
39 if (node.callee.type !== AST_NODE_TYPES.Identifier) {
40 return
41 }
42 if (!bindings.when.has(node.callee.name)) {
43 return
44 }
45 const fn = getEnclosingFunction(node)
46 if (!fn) {
47 return
48 }
49 if (!isWhenThenCallbackFunction(fn, bindings)) {
50 return
51 }
52 context.report({
53 node,
54 messageId: "nestedWhenInWorkflow",
55 })
56 },
57 }
58 },
59 })
60
61 export default rule