1 import * as fs from "fs"
2 import * as path from "path"
3 import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils"
4 import { parse } from "@typescript-eslint/typescript-estree"
5 import { createRule } from "../../create-rule"
6 import { findProperty } from "../../util/ast"
7 import { isIndexFile, toPosix } from "../../util/filename"
8
9 type MessageIds = "duplicateName"
10
11 const SUPPORTED_EXTENSIONS = [".ts", ".tsx", ".js", ".mjs", ".cjs"]
12
13 /**
14 * Locates the `config` object literal exported from a scheduled-job file by
15 * walking the top-level statements. Mirrors `scheduled-job-config-required`'s
16 * resolution (object literal directly, or via a local `const` initializer),
17 * but works without scope analysis so it can run over a bare parsed AST from
18 * another file on disk.
19 *
20 * Handles:
21 * - `export const config = { ... }`
22 * - `export const config = base` (where `const base = { ... }`)
23 * - `const config = { ... }; export { config }`
24 * - `const c = { ... }; export { c as config }`
25 *
26 * Skips re-exports (`export { config } from "./x"`) — unresolvable locally.
27 */
28 function findConfigObject(
29 body: TSESTree.ProgramStatement[]
30 ): TSESTree.ObjectExpression | null {
31 const localObjects = new Map<string, TSESTree.ObjectExpression>()
32
33 for (const stmt of body) {
34 const decl =
35 stmt.type === AST_NODE_TYPES.ExportNamedDeclaration && stmt.declaration
36 ? stmt.declaration
37 : stmt
38 if (decl.type !== AST_NODE_TYPES.VariableDeclaration) {
39 continue
40 }
41 for (const d of decl.declarations) {
42 if (
43 d.id.type === AST_NODE_TYPES.Identifier &&
44 d.init?.type === AST_NODE_TYPES.ObjectExpression
45 ) {
46 localObjects.set(d.id.name, d.init)
47 }
48 }
49 }
50
51 const resolve = (
52 node: TSESTree.Node | null | undefined
53 ): TSESTree.ObjectExpression | null => {
54 if (!node) {
55 return null
56 }
57 if (node.type === AST_NODE_TYPES.ObjectExpression) {
58 return node
59 }
60 if (node.type === AST_NODE_TYPES.Identifier) {
61 return localObjects.get(node.name) ?? null
62 }
63 return null
64 }
65
66 for (const stmt of body) {
67 if (stmt.type !== AST_NODE_TYPES.ExportNamedDeclaration) {
68 continue
69 }
70
71 if (stmt.declaration?.type === AST_NODE_TYPES.VariableDeclaration) {
72 for (const d of stmt.declaration.declarations) {
73 if (d.id.type === AST_NODE_TYPES.Identifier && d.id.name === "config") {
74 const resolved = resolve(d.init)
75 if (resolved) {
76 return resolved
77 }
78 }
79 }
80 }
81
82 if (stmt.source) {
83 // Re-export from another module — can't resolve locally.
84 continue
85 }
86
87 for (const spec of stmt.specifiers) {
88 if (
89 spec.exported.type === AST_NODE_TYPES.Identifier &&
90 spec.exported.name === "config" &&
91 spec.local.type === AST_NODE_TYPES.Identifier
92 ) {
93 const resolved = resolve(spec.local)
94 if (resolved) {
95 return resolved
96 }
97 }
98 }
99 }
100
101 return null
102 }
103
104 /**
105 * Returns the `name` property's string-literal value and the literal node from
106 * a job file's `config` export, or `null` when there is no resolvable config,
107 * no `name` property, or the `name` value isn't a plain string literal.
108 */
109 function getConfigName(
110 program: TSESTree.Program
111 ): { value: string; node: TSESTree.Node } | null {
112 const config = findConfigObject(program.body)
113 if (!config) {
114 return null
115 }
116
117 const prop = findProperty(config, "name")
118 if (!prop) {
119 return null
120 }
121
122 if (
123 prop.value.type === AST_NODE_TYPES.Literal &&
124 typeof prop.value.value === "string"
125 ) {
126 return { value: prop.value.value, node: prop.value }
127 }
128 return null
129 }
130
131 /**
132 * Given a job file path, returns the nearest ancestor `jobs/` directory (the
133 * project's scheduled-jobs root), or `null` when the file isn't under one.
134 */
135 function locateJobsRoot(filename: string): string | null {
136 const posix = toPosix(filename)
137 const idx = posix.lastIndexOf("/jobs/")
138 if (idx === -1) {
139 return null
140 }
141 return posix.slice(0, idx + "/jobs".length)
142 }
143
144 /** Recursively collects all supported job-file paths under `root`. */
145 function collectJobFiles(root: string): string[] {
146 const out: string[] = []
147 const walk = (dir: string): void => {
148 let entries: fs.Dirent[]
149 try {
150 entries = fs.readdirSync(dir, { withFileTypes: true })
151 } catch {
152 return
153 }
154 for (const entry of entries) {
155 const abs = path.join(dir, entry.name)
156 if (entry.isDirectory()) {
157 if (entry.name === "node_modules") {
158 continue
159 }
160 walk(abs)
161 } else if (
162 entry.isFile() &&
163 SUPPORTED_EXTENSIONS.includes(path.extname(entry.name))
164 ) {
165 out.push(toPosix(abs))
166 }
167 }
168 }
169 walk(root)
170 return out
171 }
172
173 /** Parses a job file from disk and extracts its `config.name`, if any. */
174 function extractNameFromFile(filePath: string): string | null {
175 let source: string
176 try {
177 source = fs.readFileSync(filePath, "utf8")
178 } catch {
179 return null
180 }
181
182 let ast: TSESTree.Program
183 try {
184 ast = parse(source, {
185 jsx: filePath.endsWith("x"),
186 loc: false,
187 range: false,
188 }) as unknown as TSESTree.Program
189 } catch {
190 return null
191 }
192
193 return getConfigName(ast)?.value ?? null
194 }
195
196 export const rule = createRule<[], MessageIds>({
197 name: "scheduled-job-name-unique",
198 meta: {
199 type: "problem",
200 docs: {
201 description:
202 "Scheduled job `config.name` must be unique across all scheduled jobs in the project.",
203 },
204 messages: {
205 duplicateName:
206 "Scheduled job name \"{{name}}\" is already used by another job ({{otherFile}}). Each scheduled job must have a unique `name`.",
207 },
208 schema: [],
209 },
210 defaultOptions: [],
211 create(context) {
212 const sourceCode = context.sourceCode ?? context.getSourceCode()
213
214 return {
215 "Program:exit"(node: TSESTree.Program) {
216 const filename = context.filename
217 if (!filename || filename.startsWith("<")) {
218 return
219 }
220 // `index.<ext>` barrels in a jobs directory aren't job definitions.
221 if (isIndexFile(filename)) {
222 return
223 }
224
225 const current = getConfigName(sourceCode.ast ?? node)
226 if (!current) {
227 return
228 }
229
230 const jobsRoot = locateJobsRoot(filename)
231 if (!jobsRoot) {
232 return
233 }
234
235 const currentPath = toPosix(path.resolve(filename))
236
237 for (const otherPath of collectJobFiles(jobsRoot)) {
238 if (toPosix(path.resolve(otherPath)) === currentPath) {
239 continue
240 }
241 if (extractNameFromFile(otherPath) === current.value) {
242 context.report({
243 node: current.node,
244 messageId: "duplicateName",
245 data: {
246 name: current.value,
247 otherFile: path.relative(jobsRoot, otherPath) || otherPath,
248 },
249 })
250 // One report is enough — the conflict is established.
251 break
252 }
253 }
254 },
255 }
256 },
257 })
258
259 export default rule