1 import * as fs from "fs"
2 import * as path from "path"
3 import { parse } from "@typescript-eslint/typescript-estree"
4 import { createRule } from "../../create-rule"
5 import { FRAMEWORK_UTILS_SOURCE } from "../../constants"
6 import { normalizePathForComparison } from "../../util/filename"
7
8 type MessageIds = "loaderNotRegistered"
9
10 const MODULE_NAME = "Module"
11 const INDEX_CANDIDATES = [
12 "index.ts",
13 "index.tsx",
14 "index.js",
15 "index.mjs",
16 "index.cjs",
17 ]
18 const SUPPORTED_EXTENSIONS = [".ts", ".tsx", ".js", ".mjs", ".cjs"]
19
20 function stripExt(p: string): string {
21 const ext = path.extname(p)
22 return SUPPORTED_EXTENSIONS.includes(ext) ? p.slice(0, -ext.length) : p
23 }
24
25 function locateModuleIndex(filename: string): {
26 indexPath: string
27 loaderKey: string
28 } | null {
29 const posix = normalizePathForComparison(filename)
30 const match = posix.match(/^(.*\/modules\/[^/]+)\/loaders\/(.+)$/)
31 if (!match) {
32 return null
33 }
34 const moduleDir = match[1]
35 const loaderAbs = stripExt(posix)
36 for (const candidate of INDEX_CANDIDATES) {
37 const indexPath = `${moduleDir}/${candidate}`
38 if (fs.existsSync(indexPath)) {
39 return { indexPath, loaderKey: loaderAbs }
40 }
41 }
42 return null
43 }
44
45 function resolveImportSource(source: string, fromDir: string): string | null {
46 if (!source.startsWith(".")) {
47 return null
48 }
49 const resolved = normalizePathForComparison(path.resolve(fromDir, source))
50 return stripExt(resolved)
51 }
52
53 function collectRegisteredLoaders(indexPath: string): Set<string> | null {
54 let source: string
55 try {
56 source = fs.readFileSync(indexPath, "utf8")
57 } catch {
58 return null
59 }
60
61 let ast: ReturnType<typeof parse>
62 try {
63 ast = parse(source, {
64 jsx: indexPath.endsWith("x"),
65 loc: false,
66 range: false,
67 })
68 } catch {
69 return null
70 }
71
72 const moduleLocalNames = new Set<string>()
73 const importLocalToSource = new Map<string, string>()
74 const indexDir = path.dirname(indexPath)
75
76 for (const node of ast.body) {
77 if (node.type !== "ImportDeclaration") {
78 continue
79 }
80 const src = typeof node.source.value === "string" ? node.source.value : ""
81 if (src === FRAMEWORK_UTILS_SOURCE) {
82 for (const spec of node.specifiers) {
83 if (
84 spec.type === "ImportSpecifier" &&
85 spec.imported.type === "Identifier" &&
86 spec.imported.name === MODULE_NAME
87 ) {
88 moduleLocalNames.add(spec.local.name)
89 }
90 }
91 }
92 const resolved = resolveImportSource(src, indexDir)
93 if (!resolved) {
94 continue
95 }
96 for (const spec of node.specifiers) {
97 importLocalToSource.set(spec.local.name, resolved)
98 }
99 }
100
101 const registered = new Set<string>()
102
103 const walk = (node: unknown): void => {
104 if (!node || typeof node !== "object") {
105 return
106 }
107 if (Array.isArray(node)) {
108 for (const child of node) {
109 walk(child)
110 }
111 return
112 }
113 const n = node as { type?: string; [k: string]: unknown }
114 if (
115 n.type === "CallExpression" &&
116 (n as any).callee?.type === "Identifier" &&
117 moduleLocalNames.has((n as any).callee.name)
118 ) {
119 const args = (n as any).arguments as any[]
120 const second = args?.[1]
121 if (second?.type === "ObjectExpression") {
122 for (const prop of second.properties) {
123 if (
124 prop.type !== "Property" ||
125 prop.computed ||
126 !(
127 (prop.key.type === "Identifier" && prop.key.name === "loaders") ||
128 (prop.key.type === "Literal" && prop.key.value === "loaders")
129 )
130 ) {
131 continue
132 }
133 if (prop.value.type !== "ArrayExpression") {
134 continue
135 }
136 for (const el of prop.value.elements) {
137 if (el && el.type === "Identifier") {
138 const src = importLocalToSource.get(el.name)
139 if (src) {
140 registered.add(src)
141 }
142 }
143 }
144 }
145 }
146 }
147 for (const key of Object.keys(n)) {
148 if (key === "parent" || key === "loc" || key === "range") {
149 continue
150 }
151 walk(n[key])
152 }
153 }
154
155 walk(ast.body)
156 return registered
157 }
158
159 export const rule = createRule<[], MessageIds>({
160 name: "loader-must-be-exported-in-module-definition",
161 meta: {
162 type: "problem",
163 docs: {
164 description:
165 "Loader files under `src/modules/<m>/loaders/` must be registered in the module's `loaders` array.",
166 },
167 messages: {
168 loaderNotRegistered:
169 "Loader file is not registered in the module's `loaders` array in {{indexPath}}.",
170 },
171 schema: [],
172 },
173 defaultOptions: [],
174 create(context) {
175 return {
176 "Program:exit"(node) {
177 const filename = context.filename
178 if (!filename || filename === "<input>" || filename === "<text>") {
179 return
180 }
181 const located = locateModuleIndex(filename)
182 if (!located) {
183 return
184 }
185
186 const registered = collectRegisteredLoaders(located.indexPath)
187 if (!registered) {
188 return
189 }
190
191 if (registered.has(located.loaderKey)) {
192 return
193 }
194
195 context.report({
196 node,
197 messageId: "loaderNotRegistered",
198 data: { indexPath: located.indexPath },
199 })
200 },
201 }
202 },
203 })
204
205 export default rule