|
| 1 | +// The method `ensureTemplateParser` is exported since ESLint Angular v14.4.0. |
| 2 | +// Any version before that requires the fallback. |
| 3 | +// See https://github.com/angular-eslint/angular-eslint/issues/888 |
| 4 | +// Copied from https://github.com/angular-eslint/angular-eslint/blob/025ad9df4006ccd482b85df93ef52a0d5ebfa29d/packages/utils/src/eslint-plugin-template/parser-services.ts#L28-L45 |
| 5 | +// Use `import { ensureTemplateParser } from "@angular-eslint/utils";` once ESLint Angular < v14.4.0 is dropped. |
| 6 | + |
| 7 | +import type { |
| 8 | + ParseSourceSpan, |
| 9 | + TmplAstElement, |
| 10 | +} from "@angular-eslint/bundled-angular-compiler"; |
| 11 | +import type { TSESLint, TSESTree } from "@typescript-eslint/utils"; |
| 12 | + |
| 13 | +export interface TemplateParserServices { |
| 14 | + convertNodeSourceSpanToLoc: ( |
| 15 | + sourceSpan: ParseSourceSpan, |
| 16 | + ) => TSESTree.SourceLocation; |
| 17 | + convertElementSourceSpanToLoc: ( |
| 18 | + context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>, |
| 19 | + node: TmplAstElement, |
| 20 | + ) => TSESTree.SourceLocation; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Utility for rule authors to ensure that their rule is correctly being used with @angular-eslint/template-parser |
| 25 | + * If @angular-eslint/template-parser is not the configured parser when the function is invoked it will throw |
| 26 | + */ |
| 27 | +export function ensureTemplateParser( |
| 28 | + context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>, |
| 29 | +): void { |
| 30 | + try { |
| 31 | + import("@angular-eslint/utils") |
| 32 | + .then(({ default: utils }) => { |
| 33 | + try { |
| 34 | + utils.ensureTemplateParser(context); |
| 35 | + } catch { |
| 36 | + ensureTemplateParserFallback(context); |
| 37 | + } |
| 38 | + }) |
| 39 | + .catch(() => { |
| 40 | + ensureTemplateParserFallback(context); |
| 41 | + }); |
| 42 | + } catch { |
| 43 | + ensureTemplateParserFallback(context); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +function ensureTemplateParserFallback( |
| 48 | + context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>, |
| 49 | +): void { |
| 50 | + if ( |
| 51 | + !(context.parserServices as unknown as TemplateParserServices) |
| 52 | + ?.convertNodeSourceSpanToLoc || |
| 53 | + !(context.parserServices as unknown as TemplateParserServices) |
| 54 | + ?.convertElementSourceSpanToLoc |
| 55 | + ) { |
| 56 | + /** |
| 57 | + * The user needs to have configured "parser" in their eslint config and set it |
| 58 | + * to @angular-eslint/template-parser |
| 59 | + */ |
| 60 | + throw new Error( |
| 61 | + "You have used a rule which requires '@angular-eslint/template-parser' to be used as the 'parser' in your ESLint config.", |
| 62 | + ); |
| 63 | + } |
| 64 | +} |
0 commit comments