GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: Add `meta.languages` support to rules (#20571) · eslint/eslint@586ec2f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs
    • _examples/custom-rule-tutorial-code
      • enforce-foo-bar.js
    • src/extend
      • custom-rule-tutorial.md
      • custom-rules.md
  • lib
    • config
      • config.js
    • linter
      • linter.js
  • messages
    • rule-unsupported-language.js
  • tests
    • lib
      • config
        • config.js
      • linter
        • linter.js
    • messages
      • messages.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/_examples/custom-rule-tutorial-code/enforce-foo-bar.js‎

Copy file name to clipboardExpand all lines: docs/_examples/custom-rule-tutorial-code/enforce-foo-bar.js
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ module.exports = {
1515
},
1616
fixable: "code",
1717
schema: [],
18+
languages: ["js/js"],
1819
},
1920
create(context) {
2021
return {
Collapse file

‎docs/src/extend/custom-rule-tutorial.md‎

Copy file name to clipboardExpand all lines: docs/src/extend/custom-rule-tutorial.md
+5-1Lines changed: 5 additions & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ Before writing the rule, add some metadata to the rule object. ESLint uses this
9090

9191
Start by exporting an object with a `meta` property containing the rule's metadata, such as the rule type, documentation, and fixability. In this case, the rule type is "problem," the description is "Enforce that a variable named `foo` can only be assigned a value of 'bar'.", and the rule is fixable by modifying the code.
9292

93+
Because this rule targets JavaScript, we also add `languages: ["js/js"]` to declare that it only applies to the built-in JavaScript language. ESLint will throw an error if this rule is enabled for a non-JavaScript language.
94+
9395
```javascript
9496
// enforce-foo-bar.js
9597

@@ -102,6 +104,7 @@ module.exports = {
102104
},
103105
fixable: "code",
104106
schema: [],
107+
languages: ["js/js"],
105108
},
106109
create(context) {
107110
return {
@@ -136,7 +139,8 @@ module.exports = {
136139
description: "Enforce that a variable named `foo` can only be assigned a value of 'bar'."
137140
},
138141
fixable: "code",
139-
schema: []
142+
schema: [],
143+
languages: ["js/js"]
140144
},
141145
create(context) {
142146
return {
Collapse file

‎docs/src/extend/custom-rules.md‎

Copy file name to clipboardExpand all lines: docs/src/extend/custom-rules.md
+37Lines changed: 37 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,43 @@ The source file for a rule exports an object with the following properties. Both
6767

6868
- `defaultOptions`: (`array`) Specifies [default options](#option-defaults) for the rule. If present, any user-provided options in their config will be merged on top of them recursively.
6969

70+
- `languages`: (`array`) Specifies the languages the rule is designed to work with. Each entry is a string in the format `"plugin/language"` (e.g., `"js/js"`, `"markdown/gfm"`). Special values:
71+
- `"*"` — the rule works with any language.
72+
- `"plugin/*"` — the rule works with any language provided by the given plugin.
73+
74+
If `languages` is not specified, the rule is assumed to work with all languages. When `languages` is specified and none of the entries matches the active language, ESLint throws an error.
75+
76+
```js
77+
// Rule only runs when the active language is the built-in JavaScript language
78+
meta: {
79+
languages: ["js/js"],
80+
}
81+
82+
// Rule runs with any language from the "markdown" plugin
83+
meta: {
84+
languages: ["markdown/*"],
85+
}
86+
87+
// Rule runs with any language
88+
meta: {
89+
languages: ["*"],
90+
}
91+
```
92+
93+
Language identifiers are matched in the following order:
94+
1. **Wildcard `"*"`** — matches any language.
95+
2. **Direct string match** — the entry exactly equals the active language string (e.g., `"test/lang"`).
96+
3. **`"plugin/*"` wildcard** — matches any language whose plugin name (or `meta.namespace`) equals the plugin part of the entry.
97+
4. **Namespace match** — a plugin registered under a different name may be matched when its `meta.namespace` equals the plugin part of the entry.
98+
99+
```js
100+
// Rule runs with a specific language from a plugin whose meta.namespace is "markdown"
101+
// (e.g., the plugin is registered as "md" but declares meta.namespace = "markdown")
102+
meta: {
103+
languages: ["markdown/gfm"],
104+
}
105+
```
106+
70107
- `deprecated`: (`boolean | DeprecatedInfo`) Indicates whether the rule has been deprecated. You may omit the `deprecated` property if the rule has not been deprecated.
71108
There is a dedicated page for the [DeprecatedInfo](./rule-deprecation)
72109

Collapse file

‎lib/config/config.js‎

Copy file name to clipboardExpand all lines: lib/config/config.js
+129Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,76 @@ function splitPluginIdentifier(identifier) {
228228
};
229229
}
230230

231+
/**
232+
* Normalizes a language name by replacing the built-in `@/` plugin prefix with `js/`.
233+
* @param {string} languageName The language name to normalize.
234+
* @returns {string} The normalized language name.
235+
*/
236+
function normalizeLanguageName(languageName) {
237+
return languageName.startsWith("@/")
238+
? `js/${languageName.slice(2)}`
239+
: languageName;
240+
}
241+
242+
/**
243+
* Checks if a rule's `meta.languages` supports the given language.
244+
* @param {Array<string>|undefined} ruleLangs The rule's `meta.languages` array.
245+
* @param {string} configLanguageName The normalized language name from the config (e.g., "js/js").
246+
* @param {Array<string>} validPluginNames The valid plugin name aliases for the config's plugin
247+
* (normalized plugin name plus its `meta.namespace` if defined).
248+
* @returns {boolean} True if the rule supports the language, false otherwise.
249+
*/
250+
function doesRuleSupportLanguage(
251+
ruleLangs,
252+
configLanguageName,
253+
validPluginNames,
254+
) {
255+
// If no languages specified, works with all languages (backward compatible)
256+
if (!ruleLangs) {
257+
return true;
258+
}
259+
260+
const { objectName: configLangPart } =
261+
splitPluginIdentifier(configLanguageName);
262+
263+
for (const langEntry of ruleLangs) {
264+
// Skip non-string entries
265+
if (typeof langEntry !== "string") {
266+
continue;
267+
}
268+
269+
// "*" matches any language
270+
if (langEntry === "*") {
271+
return true;
272+
}
273+
274+
// Direct match
275+
if (langEntry === configLanguageName) {
276+
return true;
277+
}
278+
279+
const { pluginName: rulePluginPart, objectName: ruleLangPart } =
280+
splitPluginIdentifier(langEntry);
281+
282+
// "plugin/*" wildcard - matches any language from that plugin (by name or namespace)
283+
if (ruleLangPart === "*") {
284+
if (validPluginNames.includes(rulePluginPart)) {
285+
return true;
286+
}
287+
} else {
288+
// Match by plugin name or namespace, with exact language part
289+
if (
290+
validPluginNames.includes(rulePluginPart) &&
291+
ruleLangPart === configLangPart
292+
) {
293+
return true;
294+
}
295+
}
296+
}
297+
298+
return false;
299+
}
300+
231301
/**
232302
* Returns the name of an object in the config by reading its `meta` key.
233303
* @param {Object} object The object to check.
@@ -572,12 +642,30 @@ class Config {
572642
* @throws {TypeError} If the rulesConfig is not provided or is invalid.
573643
* @throws {InvalidRuleOptionsSchemaError} If a rule's `meta.schema` is invalid.
574644
* @throws {TypeError} If a rule is not found in the plugins.
645+
* @throws {TypeError} If a rule does not support the current language.
575646
*/
576647
validateRulesConfig(rulesConfig) {
577648
if (!rulesConfig) {
578649
throw new TypeError("Config is required for validation.");
579650
}
580651

652+
// Normalize "@/" prefix to "js/" for matching and user-facing messages
653+
const normalizedLanguageName = normalizeLanguageName(
654+
this.#languageName,
655+
);
656+
657+
// Compute valid plugin name aliases for the config's language plugin once
658+
const { pluginName: configPluginName } = splitPluginIdentifier(
659+
normalizedLanguageName,
660+
);
661+
const configPlugin =
662+
this.plugins[configPluginName] ??
663+
(configPluginName === "js" ? this.plugins["@"] : void 0);
664+
const validPluginNames = configPlugin?.meta?.namespace
665+
? [configPluginName, configPlugin.meta.namespace]
666+
: [configPluginName];
667+
const unsupportedLanguageRules = [];
668+
581669
for (const [ruleId, ruleOptions] of Object.entries(rulesConfig)) {
582670
// check for edge case
583671
if (ruleId === "__proto__") {
@@ -603,6 +691,34 @@ class Config {
603691
throwRuleNotFoundError(parseRuleId(ruleId), this);
604692
}
605693

694+
// Validate meta.languages structure if present (only for enabled rules)
695+
if (rule.meta?.languages !== void 0) {
696+
if (!Array.isArray(rule.meta.languages)) {
697+
throw new TypeError(
698+
`Key "rules": Key "${ruleId}": Key "meta": Key "languages": Expected an array.`,
699+
);
700+
}
701+
702+
for (const lang of rule.meta.languages) {
703+
if (typeof lang !== "string") {
704+
throw new TypeError(
705+
`Key "rules": Key "${ruleId}": Key "meta": Key "languages": Expected each element to be a string.`,
706+
);
707+
}
708+
}
709+
}
710+
711+
// Check if the rule supports the current language
712+
if (
713+
!doesRuleSupportLanguage(
714+
rule.meta?.languages,
715+
normalizedLanguageName,
716+
validPluginNames,
717+
)
718+
) {
719+
unsupportedLanguageRules.push(ruleId);
720+
}
721+
606722
const validateRule = getOrCreateValidator(rule, ruleId);
607723

608724
if (validateRule) {
@@ -634,6 +750,19 @@ class Config {
634750
}
635751
}
636752
}
753+
754+
if (unsupportedLanguageRules.length > 0) {
755+
const error = new TypeError(
756+
`Key "rules": The following rules do not support the language "${normalizedLanguageName}":\n${unsupportedLanguageRules.map(ruleId => `\t- "${ruleId}"`).join("\n")}`,
757+
);
758+
759+
error.messageTemplate = "rule-unsupported-language";
760+
error.messageData = {
761+
ruleIds: unsupportedLanguageRules,
762+
language: normalizedLanguageName,
763+
};
764+
throw error;
765+
}
637766
}
638767

639768
/**
Collapse file

‎lib/linter/linter.js‎

Copy file name to clipboardExpand all lines: lib/linter/linter.js
+16Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,22 @@ class Linter {
12021202
throw err;
12031203
}
12041204

1205+
/*
1206+
* If the rule does not support the current language, report a
1207+
* specific, actionable error message.
1208+
*/
1209+
if (
1210+
err.messageTemplate ===
1211+
"rule-unsupported-language"
1212+
) {
1213+
report.addError({
1214+
ruleId,
1215+
message: `Inline configuration for rule "${ruleId}" is invalid:\n\tRule does not support the language "${err.messageData.language}". Use a config block with "files" to apply the rule only to supported files, or disable it.\n`,
1216+
loc,
1217+
});
1218+
return;
1219+
}
1220+
12051221
let baseMessage = err.message
12061222
.slice(
12071223
err.message.startsWith('Key "rules":')
Collapse file

‎messages/rule-unsupported-language.js‎

Copy file name to clipboard
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"use strict";
2+
3+
module.exports = function ({ ruleIds, language }) {
4+
return `
5+
The following rules do not support the language "${language}":
6+
${ruleIds.map(id => `\t- "${id}"`).join("\n")}
7+
8+
To fix this error, either:
9+
- Remove the rule from your configuration, or set its severity to "off".
10+
- Use the "files" option to apply the rule only to files of the supported language, for example:
11+
{
12+
files: ["**/*.js"],
13+
rules: { "${ruleIds[0]}": "error" }
14+
}
15+
16+
See https://eslint.org/docs/latest/use/configure/rules for more information.
17+
`.trimStart();
18+
};

0 commit comments

Comments
0 (0)
You are visitor 01402605 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.