1 import type { TSESTree } from "@typescript-eslint/utils"
2 import { AST_NODE_TYPES } from "@typescript-eslint/utils"
3 import { createRule } from "../../create-rule"
4 import { findConstructor } from "../../util/ast"
5 import {
6 createMedusaServiceBindings,
7 isMedusaServiceSuper,
8 trackMedusaServiceImports,
9 } from "../../util/service-scope"
10
11 type MessageIds = "missingSuperCall"
12
13 function bodyHasSuperCall(body: TSESTree.BlockStatement): boolean {
14 for (const stmt of body.body) {
15 if (stmt.type !== AST_NODE_TYPES.ExpressionStatement) {
16 continue
17 }
18 const expr = stmt.expression
19 if (expr.type !== AST_NODE_TYPES.CallExpression) {
20 continue
21 }
22 if (expr.callee.type === AST_NODE_TYPES.Super) {
23 return true
24 }
25 }
26 return false
27 }
28
29 export const rule = createRule<[], MessageIds>({
30 name: "service-constructor-must-call-super",
31 meta: {
32 type: "problem",
33 docs: {
34 description:
35 "A service that extends `MedusaService(...)` and defines a constructor must call `super(...arguments)`.",
36 },
37 fixable: "code",
38 messages: {
39 missingSuperCall:
40 "A constructor on a class extending `MedusaService(...)` must call `super(...arguments)`.",
41 },
42 schema: [],
43 },
44 defaultOptions: [],
45 create(context) {
46 const bindings = createMedusaServiceBindings()
47
48 function checkClass(
49 node: TSESTree.ClassDeclaration | TSESTree.ClassExpression
50 ) {
51 if (!isMedusaServiceSuper(node.superClass, bindings)) {
52 return
53 }
54
55 const ctor = findConstructor(node)
56 if (!ctor) {
57 return
58 }
59
60 const value = ctor.value
61 if (value.type !== AST_NODE_TYPES.FunctionExpression) {
62 return
63 }
64
65 const body = value.body
66 if (bodyHasSuperCall(body)) {
67 return
68 }
69
70 context.report({
71 node: ctor.key,
72 messageId: "missingSuperCall",
73 fix(fixer) {
74 const openBrace = context.sourceCode.getFirstToken(body)
75 const closeBrace = context.sourceCode.getLastToken(body)
76 if (!openBrace || !closeBrace) {
77 return null
78 }
79 if (body.body.length === 0) {
80 if (openBrace.loc.end.line === closeBrace.loc.start.line) {
81 return fixer.insertTextAfter(openBrace, " super(...arguments) ")
82 }
83 const indent = " ".repeat(ctor.loc.start.column + 2)
84 return fixer.replaceTextRange(
85 [openBrace.range[1], closeBrace.range[0]],
86 `\n${indent}super(...arguments)\n${" ".repeat(
87 ctor.loc.start.column
88 )}`
89 )
90 }
91 const firstStmt = body.body[0]
92 const indent = " ".repeat(firstStmt.loc.start.column)
93 return fixer.insertTextBefore(
94 firstStmt,
95 `super(...arguments)\n${indent}`
96 )
97 },
98 })
99 }
100
101 return {
102 ImportDeclaration(node) {
103 trackMedusaServiceImports(node, bindings)
104 },
105
106 ClassDeclaration: checkClass,
107 ClassExpression: checkClass,
108 }
109 },
110 })
111
112 export default rule