|
| 1 | +const { createRule } = require("./utils.cjs"); |
| 2 | +const path = require("path"); |
| 3 | + |
| 4 | +/** @import { TSESTree } from "@typescript-eslint/utils" */ |
| 5 | +void 0; |
| 6 | + |
| 7 | +module.exports = createRule({ |
| 8 | + name: "no-direct-import", |
| 9 | + meta: { |
| 10 | + docs: { |
| 11 | + description: ``, |
| 12 | + }, |
| 13 | + messages: { |
| 14 | + noDirectImport: `This import relatively references another project; did you mean to import from a local _namespace module?`, |
| 15 | + }, |
| 16 | + schema: [], |
| 17 | + type: "problem", |
| 18 | + }, |
| 19 | + defaultOptions: [], |
| 20 | + |
| 21 | + create(context) { |
| 22 | + const containingFileName = context.filename; |
| 23 | + const containingDirectory = path.dirname(containingFileName); |
| 24 | + |
| 25 | + /** @type {(node: TSESTree.ImportDeclaration | TSESTree.TSImportEqualsDeclaration) => void} */ |
| 26 | + const check = node => { |
| 27 | + let source; |
| 28 | + if (node.type === "TSImportEqualsDeclaration") { |
| 29 | + const moduleReference = node.moduleReference; |
| 30 | + if ( |
| 31 | + moduleReference.type === "TSExternalModuleReference" |
| 32 | + && moduleReference.expression.type === "Literal" |
| 33 | + && typeof moduleReference.expression.value === "string" |
| 34 | + ) { |
| 35 | + source = moduleReference.expression; |
| 36 | + } |
| 37 | + } |
| 38 | + else { |
| 39 | + source = node.source; |
| 40 | + } |
| 41 | + |
| 42 | + if (!source) return; |
| 43 | + |
| 44 | + const p = source.value; |
| 45 | + |
| 46 | + // These appear in place of public API imports. |
| 47 | + if (p.endsWith("../typescript/typescript.js")) return; |
| 48 | + |
| 49 | + // The below is similar to https://github.com/microsoft/DefinitelyTyped-tools/blob/main/packages/eslint-plugin/src/rules/no-bad-reference.ts |
| 50 | + |
| 51 | + // Any relative path that goes to the wrong place will contain "..". |
| 52 | + if (!p.includes("..")) return; |
| 53 | + |
| 54 | + const parts = p.split("/"); |
| 55 | + let cwd = containingDirectory; |
| 56 | + for (const part of parts) { |
| 57 | + if (part === "" || part === ".") { |
| 58 | + continue; |
| 59 | + } |
| 60 | + if (part === "..") { |
| 61 | + cwd = path.dirname(cwd); |
| 62 | + } |
| 63 | + else { |
| 64 | + cwd = path.join(cwd, part); |
| 65 | + } |
| 66 | + |
| 67 | + if (path.basename(cwd) === "src") { |
| 68 | + context.report({ |
| 69 | + messageId: "noDirectImport", |
| 70 | + node: source, |
| 71 | + }); |
| 72 | + } |
| 73 | + } |
| 74 | + }; |
| 75 | + |
| 76 | + return { |
| 77 | + ImportDeclaration: check, |
| 78 | + TSImportEqualsDeclaration: check, |
| 79 | + }; |
| 80 | + }, |
| 81 | +}); |
0 commit comments