1 import { createRule } from "../../create-rule"
2 import {
3 createWorkflowSdkBindings,
4 isInWorkflowDefinitionScope,
5 trackWorkflowSdkImports,
6 } from "../../util/workflow-scope"
7
8 type MessageIds = "throwInWorkflowConstructor"
9
10 export const rule = createRule<[], MessageIds>({
11 name: "no-throw-in-workflow-constructor",
12 meta: {
13 type: "problem",
14 docs: {
15 description:
16 "Disallow `throw` statements directly inside a `createWorkflow` constructor or a `when().then()` callback. Both run at definition time, not execution time — a bare throw there skips the compensation mechanism, leaving previously executed steps uncompensated.",
17 },
18 messages: {
19 throwInWorkflowConstructor:
20 "Do not throw inside a workflow constructor or a `when().then()` callback — both run at definition time, not execution time, so a throw here bypasses compensation for any steps that already ran. Extract the check into a validation step (as `MedusaError`) so a failure triggers compensation.",
21 },
22 schema: [],
23 },
24 defaultOptions: [],
25 create(context) {
26 const bindings = createWorkflowSdkBindings()
27
28 return {
29 ImportDeclaration(node) {
30 trackWorkflowSdkImports(node, bindings)
31 },
32
33 ThrowStatement(node) {
34 if (bindings.createWorkflow.size === 0) {
35 return
36 }
37 if (!isInWorkflowDefinitionScope(node, bindings)) {
38 return
39 }
40 context.report({
41 node,
42 messageId: "throwInWorkflowConstructor",
43 })
44 },
45 }
46 },
47 })
48
49 export default rule