|
| 1 | +import { TS_ESLINT } from "@/lib/constants"; |
| 2 | +import type { Linter } from "eslint"; |
| 3 | +import type { ParserOptions } from "@typescript-eslint/types"; |
| 4 | + |
| 5 | +const PARSER_NAME = "@typescript-eslint/parser"; |
| 6 | + |
| 7 | +interface ESLintPlugin { |
| 8 | + rules: Linter.RulesRecord; |
| 9 | + config: Linter.Config; |
| 10 | +} |
| 11 | + |
| 12 | +export interface DemoLintResult { |
| 13 | + messages: Linter.LintMessage[]; |
| 14 | + fixReport: Linter.FixReport; |
| 15 | +} |
| 16 | + |
| 17 | +export interface DemoLinter { |
| 18 | + lint( |
| 19 | + code: string, |
| 20 | + parserOptions: ParserOptions, |
| 21 | + rules: Linter.RulesRecord |
| 22 | + ): DemoLintResult; |
| 23 | +} |
| 24 | + |
| 25 | +function loadPlugin(): Promise<ESLintPlugin> { |
| 26 | + return import("@typescript-eslint/eslint-plugin"); |
| 27 | +} |
| 28 | + |
| 29 | +function loadParser() { |
| 30 | + return import(`@/lib/parser`); |
| 31 | +} |
| 32 | + |
| 33 | +async function loadESLinter() { |
| 34 | + return import("eslint/lib/linter/linter"); |
| 35 | +} |
| 36 | + |
| 37 | +export async function loadDemoLinter(): Promise<DemoLinter> { |
| 38 | + const plugins = loadPlugin(); |
| 39 | + const parser = loadParser(); |
| 40 | + const ESLinter = loadESLinter(); |
| 41 | + |
| 42 | + const linter = new (await ESLinter).Linter(); |
| 43 | + |
| 44 | + const rules = Object.entries((await plugins).rules).reduce( |
| 45 | + (rules, [name, rule]) => ({ |
| 46 | + ...rules, |
| 47 | + [`${TS_ESLINT}/${name}`]: rule, |
| 48 | + }) |
| 49 | + ); |
| 50 | + |
| 51 | + linter.defineParser(PARSER_NAME, await parser); |
| 52 | + linter.defineRules(rules); |
| 53 | + |
| 54 | + return { |
| 55 | + lint( |
| 56 | + code: string, |
| 57 | + parserOptions: ParserOptions, |
| 58 | + rules: Linter.RulesRecord |
| 59 | + ): DemoLintResult { |
| 60 | + const messages: Linter.LintMessage[] = linter.verify(code, { |
| 61 | + parser: PARSER_NAME, |
| 62 | + parserOptions, |
| 63 | + rules, |
| 64 | + }); |
| 65 | + const fixReport: Linter.FixReport = linter.verifyAndFix(code, { |
| 66 | + parser: PARSER_NAME, |
| 67 | + parserOptions, |
| 68 | + rules, |
| 69 | + }); |
| 70 | + return { messages, fixReport }; |
| 71 | + }, |
| 72 | + }; |
| 73 | +} |
0 commit comments