1 import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils"
2 import { ADMIN_SDK_SOURCE } from "../../constants"
3 import { createRule } from "../../create-rule"
4 import { isDynamicUiRoutePath } from "../../util/admin-scope"
5
6 type MessageIds = "configNotDefineRouteConfig"
7
8 const DEFINE_ROUTE_CONFIG = "defineRouteConfig"
9
10 export const rule = createRule<[], MessageIds>({
11 name: "ui-route-config-via-define-route-config",
12 meta: {
13 type: "suggestion",
14 docs: {
15 description:
16 "A UI route `config` export must be initialized via `defineRouteConfig(...)`.",
17 },
18 messages: {
19 configNotDefineRouteConfig:
20 "UI route `config` export must be initialized via `defineRouteConfig(...)` from `@medusajs/admin-sdk`.",
21 },
22 schema: [],
23 },
24 defaultOptions: [],
25 create(context) {
26 // Dynamic routes (e.g. `[id]/page.tsx`) aren't added to the sidebar, so
27 // route `config` doesn't apply to them — skip the file entirely.
28 if (isDynamicUiRoutePath(context.filename)) {
29 return {}
30 }
31
32 const defineRouteConfigLocalNames = new Set<string>()
33 // The `config` identifier(s) we report on, so the warning lands on the
34 // config variable rather than its value.
35 const badConfigNodes: TSESTree.Node[] = []
36
37 function isDefineRouteConfigCall(node: TSESTree.Node | null): boolean {
38 if (!node || node.type !== AST_NODE_TYPES.CallExpression) {
39 return false
40 }
41 const callee = node.callee
42 return (
43 callee.type === AST_NODE_TYPES.Identifier &&
44 defineRouteConfigLocalNames.has(callee.name)
45 )
46 }
47
48 function declaratorName(decl: TSESTree.VariableDeclarator): string | null {
49 if (decl.id.type === AST_NODE_TYPES.Identifier) {
50 return decl.id.name
51 }
52 return null
53 }
54
55 return {
56 ImportDeclaration(node: TSESTree.ImportDeclaration) {
57 if (node.source.value !== ADMIN_SDK_SOURCE) {
58 return
59 }
60 for (const spec of node.specifiers) {
61 if (
62 spec.type === AST_NODE_TYPES.ImportSpecifier &&
63 spec.imported.type === AST_NODE_TYPES.Identifier &&
64 spec.imported.name === DEFINE_ROUTE_CONFIG
65 ) {
66 defineRouteConfigLocalNames.add(spec.local.name)
67 }
68 }
69 },
70 ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration) {
71 // export const config = defineRouteConfig(...)
72 if (
73 node.declaration &&
74 node.declaration.type === AST_NODE_TYPES.VariableDeclaration
75 ) {
76 for (const decl of node.declaration.declarations) {
77 if (declaratorName(decl) === "config" && decl.init) {
78 if (!isDefineRouteConfigCall(decl.init)) {
79 badConfigNodes.push(decl.id)
80 }
81 }
82 }
83 }
84 },
85 "Program:exit"() {
86 for (const node of badConfigNodes) {
87 context.report({ node, messageId: "configNotDefineRouteConfig" })
88 }
89 },
90 }
91 },
92 })
93
94 export default rule