1 import path from "path"
2 import ts from "typescript"
3 import type { TSESLint, TSESTree } from "@typescript-eslint/utils"
4 import { AST_NODE_TYPES } from "@typescript-eslint/utils"
5 import { createRule } from "../../create-rule"
6 import { FRAMEWORK_UTILS_SOURCE } from "../../constants"
7 import { findVariableInScope, getReturnedExpression } from "../../util/ast"
8 import {
9 isPathInsideOrEqual,
10 normalizePathForComparison,
11 } from "../../util/filename"
12
13 type MessageIds = "crossModuleRelationship" | "unresolvableTarget"
14
15 const MODEL_IMPORT = "model"
16 const RELATION_METHODS = new Set([
17 "hasOne",
18 "belongsTo",
19 "hasMany",
20 "manyToMany",
21 ])
22
23 type ResolvedTarget =
24 | { kind: "import"; source: string }
25 | { kind: "local" }
26 | { kind: "unresolvable" }
27
28 /**
29 * Classifies what an Identifier refers to:
30 * - `import` with the source path, when the identifier resolves to an
31 * `ImportBinding`.
32 * - `local`, when it resolves to a same-file declaration (variable, class,
33 * function, etc.) — same module by definition.
34 * - `unresolvable`, when no enclosing scope binds the name.
35 */
36 function classifyIdentifier(
37 node: TSESTree.Identifier,
38 scope: TSESLint.Scope.Scope
39 ): ResolvedTarget {
40 const variable = findVariableInScope(scope, node.name)
41 if (!variable || variable.defs.length === 0) {
42 return { kind: "unresolvable" }
43 }
44 const def = variable.defs[0]
45 if (def.type === "ImportBinding") {
46 const parent = def.parent
47 if (
48 parent &&
49 parent.type === AST_NODE_TYPES.ImportDeclaration &&
50 typeof parent.source.value === "string"
51 ) {
52 return { kind: "import", source: parent.source.value }
53 }
54 return { kind: "unresolvable" }
55 }
56 return { kind: "local" }
57 }
58
59 function isRelativeImport(source: string): boolean {
60 return source.startsWith("./") || source.startsWith("../") || source === "."
61 }
62
63 function pathImplForFilename(filename: string): typeof path {
64 return filename.includes("\\") ? path.win32 : path
65 }
66
67 /**
68 * Returns the absolute path of the `modules/<name>/` directory containing the
69 * given file, or `null` if the file isn't under a recognizable module root.
70 */
71 function getModuleRoot(filename: string): string | null {
72 const norm = normalizePathForComparison(filename)
73 const match = norm.match(/^(.*\/modules\/[^/]+)\//)
74 return match ? match[1] : null
75 }
76
77 /** True when the absolute `resolved` path is inside (or equal to) `moduleRoot`. */
78 function pathStaysInModule(
79 resolved: string,
80 moduleRoot: string | null
81 ): boolean {
82 return moduleRoot === null || isPathInsideOrEqual(resolved, moduleRoot)
83 }
84
85 /**
86 * True when the relative import `source` resolved against `filename` stays
87 * within `moduleRoot`. Returns `true` (allowed) when we can't determine a
88 * module root — defensive default for files outside the expected layout.
89 */
90 function relativeImportStaysInModule(
91 filename: string,
92 source: string,
93 moduleRoot: string | null
94 ): boolean {
95 if (moduleRoot === null) {
96 return true
97 }
98 const pathImpl = pathImplForFilename(filename)
99 return pathStaysInModule(
100 pathImpl.resolve(pathImpl.dirname(filename), source),
101 moduleRoot
102 )
103 }
104
105 /**
106 * A tsconfig's `compilerOptions.paths` mapping together with the base directory
107 * its substitutions resolve against.
108 */
109 interface TsconfigPaths {
110 baseDir: string
111 paths: Record<string, string[]>
112 }
113
114 /**
115 * Parsed `paths` per absolute tsconfig path (`null` = no `paths` declared).
116 * tsconfigs don't change during a lint run, so each is read at most once.
117 */
118 const tsconfigPathsCache = new Map<string, TsconfigPaths | null>()
119
120 /**
121 * Reads `compilerOptions.paths` from a single tsconfig. Uses `ts.readConfigFile`
122 * so JSONC comments are tolerated — this is plain config reading, not type-aware
123 * linting, so the rule still works without `parserOptions.project`.
124 *
125 * Substitutions resolve against `baseUrl` when set, otherwise the tsconfig's own
126 * directory (matching TypeScript's handling of `paths` declared without a
127 * `baseUrl`). `extends` is intentionally not followed: Medusa modules declare
128 * their aliases locally.
129 */
130 function loadTsconfigPaths(configPath: string): TsconfigPaths | null {
131 const cached = tsconfigPathsCache.get(configPath)
132 if (cached !== undefined) {
133 return cached
134 }
135 let result: TsconfigPaths | null = null
136 const { config } = ts.readConfigFile(configPath, ts.sys.readFile)
137 const paths = config?.compilerOptions?.paths
138 if (paths && typeof paths === "object") {
139 const configDir = path.dirname(configPath)
140 const baseUrl = config.compilerOptions.baseUrl
141 result = {
142 baseDir: baseUrl ? path.resolve(configDir, baseUrl) : configDir,
143 paths,
144 }
145 }
146 tsconfigPathsCache.set(configPath, result)
147 return result
148 }
149
150 /** Nearest tsconfig with `paths` per start directory. */
151 const nearestTsconfigCache = new Map<string, TsconfigPaths | null>()
152
153 /**
154 * Walks up from `startDir` to the filesystem root, returning the first tsconfig
155 * that declares `compilerOptions.paths`, or `null` if none does.
156 */
157 function findTsconfigPaths(startDir: string): TsconfigPaths | null {
158 const cached = nearestTsconfigCache.get(startDir)
159 if (cached !== undefined) {
160 return cached
161 }
162 let result: TsconfigPaths | null = null
163 let dir = startDir
164 while (dir) {
165 const candidate = path.join(dir, "tsconfig.json")
166 if (ts.sys.fileExists(candidate)) {
167 const loaded = loadTsconfigPaths(candidate)
168 if (loaded) {
169 result = loaded
170 break
171 }
172 }
173 const parent = path.dirname(dir)
174 if (parent === dir) {
175 break
176 }
177 dir = parent
178 }
179 nearestTsconfigCache.set(startDir, result)
180 return result
181 }
182
183 /**
184 * Resolves `source` through a tsconfig `paths` alias to an absolute path, or
185 * `null` when no pattern matches. Supports exact (`@models`) and wildcard
186 * (`@models/*`) patterns, taking the first substitution like TypeScript does.
187 */
188 function resolveTsconfigAlias(
189 source: string,
190 cfg: TsconfigPaths
191 ): string | null {
192 for (const pattern of Object.keys(cfg.paths)) {
193 const substitution = cfg.paths[pattern]?.[0]
194 if (!substitution) {
195 continue
196 }
197 const star = pattern.indexOf("*")
198 if (star === -1) {
199 if (source === pattern) {
200 return path.resolve(cfg.baseDir, substitution)
201 }
202 continue
203 }
204 const prefix = pattern.slice(0, star)
205 const suffix = pattern.slice(star + 1)
206 if (
207 source.length >= prefix.length + suffix.length &&
208 source.startsWith(prefix) &&
209 source.endsWith(suffix)
210 ) {
211 const matched = source.slice(prefix.length, source.length - suffix.length)
212 return path.resolve(cfg.baseDir, substitution.replace("*", matched))
213 }
214 }
215 return null
216 }
217
218 /**
219 * True when `source` is a tsconfig `paths` alias (e.g. `@models`) that resolves
220 * to a location inside `moduleRoot` — i.e. an in-module reference written
221 * through an alias rather than a relative path. Returns `false` when `source`
222 * isn't a configured alias (real package imports stay flagged).
223 */
224 function aliasStaysInModule(
225 filename: string,
226 source: string,
227 moduleRoot: string | null
228 ): boolean {
229 const cfg = findTsconfigPaths(path.dirname(filename))
230 if (!cfg) {
231 return false
232 }
233 const resolved = resolveTsconfigAlias(source, cfg)
234 return resolved !== null && pathStaysInModule(resolved, moduleRoot)
235 }
236
237 export const rule = createRule<[], MessageIds>({
238 name: "link-no-cross-module-relationship",
239 meta: {
240 type: "problem",
241 docs: {
242 description:
243 "Data model relationships (`hasOne`/`belongsTo`/`hasMany`/`manyToMany`) must reference a data model defined in the same module. Use module links for cross-module references.",
244 },
245 messages: {
246 crossModuleRelationship:
247 "`model.{{method}}` references `{{name}}` imported from `{{source}}`, which is outside the current module. Use `defineLink` for cross-module relationships.",
248 unresolvableTarget:
249 "`model.{{method}}` must reference a data model defined in the same module (returning an identifier imported via a relative path or declared in the same file).",
250 },
251 schema: [],
252 },
253 defaultOptions: [],
254 create(context) {
255 const modelLocalNames = new Set<string>()
256 const moduleRoot = getModuleRoot(context.filename)
257
258 return {
259 ImportDeclaration(node) {
260 if (node.source.value !== FRAMEWORK_UTILS_SOURCE) {
261 return
262 }
263 for (const specifier of node.specifiers) {
264 if (
265 specifier.type === AST_NODE_TYPES.ImportSpecifier &&
266 specifier.imported.type === AST_NODE_TYPES.Identifier &&
267 specifier.imported.name === MODEL_IMPORT
268 ) {
269 modelLocalNames.add(specifier.local.name)
270 }
271 }
272 },
273
274 CallExpression(node) {
275 if (modelLocalNames.size === 0) {
276 return
277 }
278 const callee = node.callee
279 if (
280 callee.type !== AST_NODE_TYPES.MemberExpression ||
281 callee.computed ||
282 callee.property.type !== AST_NODE_TYPES.Identifier ||
283 !RELATION_METHODS.has(callee.property.name) ||
284 callee.object.type !== AST_NODE_TYPES.Identifier ||
285 !modelLocalNames.has(callee.object.name)
286 ) {
287 return
288 }
289 const fn = node.arguments[0]
290 if (
291 !fn ||
292 (fn.type !== AST_NODE_TYPES.ArrowFunctionExpression &&
293 fn.type !== AST_NODE_TYPES.FunctionExpression)
294 ) {
295 return
296 }
297 const method = callee.property.name
298 const returned = getReturnedExpression(fn)
299 if (!returned) {
300 return
301 }
302
303 if (returned.type !== AST_NODE_TYPES.Identifier) {
304 context.report({
305 node: returned,
306 messageId: "unresolvableTarget",
307 data: { method },
308 })
309 return
310 }
311
312 const target = classifyIdentifier(
313 returned,
314 context.sourceCode.getScope(returned)
315 )
316 if (target.kind === "local") {
317 return
318 }
319 if (target.kind === "unresolvable") {
320 context.report({
321 node: returned,
322 messageId: "unresolvableTarget",
323 data: { method },
324 })
325 return
326 }
327 const staysInModule = isRelativeImport(target.source)
328 ? relativeImportStaysInModule(
329 context.filename,
330 target.source,
331 moduleRoot
332 )
333 : aliasStaysInModule(context.filename, target.source, moduleRoot)
334 if (staysInModule) {
335 return
336 }
337
338 context.report({
339 node: returned,
340 messageId: "crossModuleRelationship",
341 data: {
342 method,
343 name: returned.name,
344 source: target.source,
345 },
346 })
347 },
348 }
349 },
350 })
351
352 export default rule