1 import type { TSESLint, TSESTree } from "@typescript-eslint/utils"
2 import { AST_NODE_TYPES } from "@typescript-eslint/utils"
3 import { createRule } from "../../create-rule"
4 import { FRAMEWORK_UTILS_SOURCE } from "../../constants"
5
6 type MessageIds = "useMedusaError" | "replaceWithMedusaError"
7
8 /** The framework class to throw instead of a generic error. */
9 const MEDUSA_ERROR = "MedusaError"
10
11 /**
12 * Neutral default error type used in the suggested rewrite. The developer is
13 * expected to pick a more specific `MedusaError.Types.*` (e.g. `NOT_FOUND`,
14 * `INVALID_DATA`) — that's why this is a suggestion, not an autofix.
15 */
16 const DEFAULT_ERROR_TYPE = `${MEDUSA_ERROR}.Types.UNEXPECTED_STATE`
17
18 /**
19 * Built-in JavaScript error constructors. Throwing any of these in Medusa code
20 * loses the structured `type` that Medusa relies on to map errors to HTTP
21 * statuses and consistent client responses. Use `MedusaError` instead.
22 */
23 const GENERIC_ERROR_NAMES: ReadonlySet<string> = new Set([
24 "Error",
25 "TypeError",
26 "RangeError",
27 "SyntaxError",
28 "ReferenceError",
29 "EvalError",
30 "URIError",
31 "AggregateError",
32 ])
33
34 export const rule = createRule<[], MessageIds>({
35 name: "use-medusa-error-not-generic-error",
36 meta: {
37 type: "suggestion",
38 docs: {
39 description:
40 "Throw `MedusaError` rather than a generic `Error`. `MedusaError` carries a `type` that Medusa maps to the right HTTP status and a consistent client response.",
41 },
42 hasSuggestions: true,
43 messages: {
44 useMedusaError:
45 "Throw `MedusaError` instead of a generic `{{ name }}`. Use `new MedusaError(MedusaError.Types.X, \"...\")` so the error maps to the correct HTTP status.",
46 replaceWithMedusaError:
47 "Replace with `new MedusaError({{ type }}, ...)` (pick the appropriate `MedusaError.Types.*`).",
48 },
49 schema: [],
50 },
51 defaultOptions: [],
52 create(context) {
53 const sourceCode = context.sourceCode ?? context.getSourceCode()
54
55 // Track the `@medusajs/framework/utils` import so the suggestion can add
56 // `MedusaError` to it (or insert a new import) when it isn't already
57 // imported. Imports sit above throw statements in source order, so this is
58 // fully resolved by the time any `ThrowStatement` is visited.
59 let utilsImportNode: TSESTree.ImportDeclaration | null = null
60 let medusaErrorImported = false
61
62 return {
63 ImportDeclaration(node) {
64 if (node.source.value !== FRAMEWORK_UTILS_SOURCE) {
65 return
66 }
67 utilsImportNode = node
68 for (const specifier of node.specifiers) {
69 if (
70 specifier.type === AST_NODE_TYPES.ImportSpecifier &&
71 specifier.imported.type === AST_NODE_TYPES.Identifier &&
72 specifier.imported.name === MEDUSA_ERROR
73 ) {
74 medusaErrorImported = true
75 }
76 }
77 },
78
79 ThrowStatement(node) {
80 const arg = node.argument
81 if (
82 arg.type !== AST_NODE_TYPES.NewExpression ||
83 arg.callee.type !== AST_NODE_TYPES.Identifier ||
84 !GENERIC_ERROR_NAMES.has(arg.callee.name)
85 ) {
86 return
87 }
88
89 const newExpr = arg
90 const calleeName = arg.callee.name
91
92 context.report({
93 node: newExpr,
94 messageId: "useMedusaError",
95 data: { name: calleeName },
96 suggest: [
97 {
98 messageId: "replaceWithMedusaError",
99 data: { type: DEFAULT_ERROR_TYPE },
100 fix(fixer) {
101 const argsText = newExpr.arguments
102 .map((a) => sourceCode.getText(a))
103 .join(", ")
104 const newArgs = argsText
105 ? `${DEFAULT_ERROR_TYPE}, ${argsText}`
106 : DEFAULT_ERROR_TYPE
107 const fixes = [
108 fixer.replaceText(newExpr, `new ${MEDUSA_ERROR}(${newArgs})`),
109 ]
110
111 if (!medusaErrorImported) {
112 fixes.push(addMedusaErrorImport(fixer))
113 }
114
115 return fixes
116 },
117 },
118 ],
119 })
120 },
121 }
122
123 function addMedusaErrorImport(fixer: TSESLint.RuleFixer): TSESLint.RuleFix {
124 if (utilsImportNode) {
125 const namedSpecifiers = utilsImportNode.specifiers.filter(
126 (s): s is TSESTree.ImportSpecifier =>
127 s.type === AST_NODE_TYPES.ImportSpecifier
128 )
129 if (namedSpecifiers.length > 0) {
130 const last = namedSpecifiers[namedSpecifiers.length - 1]
131 return fixer.insertTextAfter(last, `, ${MEDUSA_ERROR}`)
132 }
133 // Default/namespace-only import from utils — prepend a separate named
134 // import line rather than rewriting the existing one.
135 return fixer.insertTextBefore(
136 utilsImportNode,
137 `import { ${MEDUSA_ERROR} } from "${FRAMEWORK_UTILS_SOURCE}"\n`
138 )
139 }
140
141 // No utils import at all — add one at the top of the file.
142 const firstNode = sourceCode.ast.body[0]
143 const importText = `import { ${MEDUSA_ERROR} } from "${FRAMEWORK_UTILS_SOURCE}"\n`
144 return firstNode
145 ? fixer.insertTextBefore(firstNode, importText)
146 : fixer.insertTextBeforeRange([0, 0], importText)
147 }
148 },
149 })
150
151 export default rule