eslintrc-universal.cjs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var util = require('util');
  4. var path = require('path');
  5. var Ajv = require('ajv');
  6. var globals = require('globals');
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
  9. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  10. var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
  11. var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals);
  12. /**
  13. * @fileoverview Config file operations. This file must be usable in the browser,
  14. * so no Node-specific code can be here.
  15. * @author Nicholas C. Zakas
  16. */
  17. //------------------------------------------------------------------------------
  18. // Private
  19. //------------------------------------------------------------------------------
  20. const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
  21. RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
  22. map[value] = index;
  23. return map;
  24. }, {}),
  25. VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
  26. //------------------------------------------------------------------------------
  27. // Public Interface
  28. //------------------------------------------------------------------------------
  29. /**
  30. * Normalizes the severity value of a rule's configuration to a number
  31. * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
  32. * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
  33. * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
  34. * whose first element is one of the above values. Strings are matched case-insensitively.
  35. * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
  36. */
  37. function getRuleSeverity(ruleConfig) {
  38. const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
  39. if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
  40. return severityValue;
  41. }
  42. if (typeof severityValue === "string") {
  43. return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
  44. }
  45. return 0;
  46. }
  47. /**
  48. * Converts old-style severity settings (0, 1, 2) into new-style
  49. * severity settings (off, warn, error) for all rules. Assumption is that severity
  50. * values have already been validated as correct.
  51. * @param {Object} config The config object to normalize.
  52. * @returns {void}
  53. */
  54. function normalizeToStrings(config) {
  55. if (config.rules) {
  56. Object.keys(config.rules).forEach(ruleId => {
  57. const ruleConfig = config.rules[ruleId];
  58. if (typeof ruleConfig === "number") {
  59. config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
  60. } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
  61. ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
  62. }
  63. });
  64. }
  65. }
  66. /**
  67. * Determines if the severity for the given rule configuration represents an error.
  68. * @param {int|string|Array} ruleConfig The configuration for an individual rule.
  69. * @returns {boolean} True if the rule represents an error, false if not.
  70. */
  71. function isErrorSeverity(ruleConfig) {
  72. return getRuleSeverity(ruleConfig) === 2;
  73. }
  74. /**
  75. * Checks whether a given config has valid severity or not.
  76. * @param {number|string|Array} ruleConfig The configuration for an individual rule.
  77. * @returns {boolean} `true` if the configuration has valid severity.
  78. */
  79. function isValidSeverity(ruleConfig) {
  80. let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
  81. if (typeof severity === "string") {
  82. severity = severity.toLowerCase();
  83. }
  84. return VALID_SEVERITIES.indexOf(severity) !== -1;
  85. }
  86. /**
  87. * Checks whether every rule of a given config has valid severity or not.
  88. * @param {Object} config The configuration for rules.
  89. * @returns {boolean} `true` if the configuration has valid severity.
  90. */
  91. function isEverySeverityValid(config) {
  92. return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
  93. }
  94. /**
  95. * Normalizes a value for a global in a config
  96. * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
  97. * a global directive comment
  98. * @returns {("readable"|"writeable"|"off")} The value normalized as a string
  99. * @throws Error if global value is invalid
  100. */
  101. function normalizeConfigGlobal(configuredValue) {
  102. switch (configuredValue) {
  103. case "off":
  104. return "off";
  105. case true:
  106. case "true":
  107. case "writeable":
  108. case "writable":
  109. return "writable";
  110. case null:
  111. case false:
  112. case "false":
  113. case "readable":
  114. case "readonly":
  115. return "readonly";
  116. default:
  117. throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
  118. }
  119. }
  120. var ConfigOps = {
  121. __proto__: null,
  122. getRuleSeverity: getRuleSeverity,
  123. normalizeToStrings: normalizeToStrings,
  124. isErrorSeverity: isErrorSeverity,
  125. isValidSeverity: isValidSeverity,
  126. isEverySeverityValid: isEverySeverityValid,
  127. normalizeConfigGlobal: normalizeConfigGlobal
  128. };
  129. /**
  130. * @fileoverview Provide the function that emits deprecation warnings.
  131. * @author Toru Nagashima <http://github.com/mysticatea>
  132. */
  133. //------------------------------------------------------------------------------
  134. // Private
  135. //------------------------------------------------------------------------------
  136. // Defitions for deprecation warnings.
  137. const deprecationWarningMessages = {
  138. ESLINT_LEGACY_ECMAFEATURES:
  139. "The 'ecmaFeatures' config file property is deprecated and has no effect.",
  140. ESLINT_PERSONAL_CONFIG_LOAD:
  141. "'~/.eslintrc.*' config files have been deprecated. " +
  142. "Please use a config file per project or the '--config' option.",
  143. ESLINT_PERSONAL_CONFIG_SUPPRESS:
  144. "'~/.eslintrc.*' config files have been deprecated. " +
  145. "Please remove it or add 'root:true' to the config files in your " +
  146. "projects in order to avoid loading '~/.eslintrc.*' accidentally."
  147. };
  148. const sourceFileErrorCache = new Set();
  149. /**
  150. * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
  151. * for each unique file path, but repeated invocations with the same file path have no effect.
  152. * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
  153. * @param {string} source The name of the configuration source to report the warning for.
  154. * @param {string} errorCode The warning message to show.
  155. * @returns {void}
  156. */
  157. function emitDeprecationWarning(source, errorCode) {
  158. const cacheKey = JSON.stringify({ source, errorCode });
  159. if (sourceFileErrorCache.has(cacheKey)) {
  160. return;
  161. }
  162. sourceFileErrorCache.add(cacheKey);
  163. const rel = path__default["default"].relative(process.cwd(), source);
  164. const message = deprecationWarningMessages[errorCode];
  165. process.emitWarning(
  166. `${message} (found in "${rel}")`,
  167. "DeprecationWarning",
  168. errorCode
  169. );
  170. }
  171. /**
  172. * @fileoverview The instance of Ajv validator.
  173. * @author Evgeny Poberezkin
  174. */
  175. //-----------------------------------------------------------------------------
  176. // Helpers
  177. //-----------------------------------------------------------------------------
  178. /*
  179. * Copied from ajv/lib/refs/json-schema-draft-04.json
  180. * The MIT License (MIT)
  181. * Copyright (c) 2015-2017 Evgeny Poberezkin
  182. */
  183. const metaSchema = {
  184. id: "http://json-schema.org/draft-04/schema#",
  185. $schema: "http://json-schema.org/draft-04/schema#",
  186. description: "Core schema meta-schema",
  187. definitions: {
  188. schemaArray: {
  189. type: "array",
  190. minItems: 1,
  191. items: { $ref: "#" }
  192. },
  193. positiveInteger: {
  194. type: "integer",
  195. minimum: 0
  196. },
  197. positiveIntegerDefault0: {
  198. allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
  199. },
  200. simpleTypes: {
  201. enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
  202. },
  203. stringArray: {
  204. type: "array",
  205. items: { type: "string" },
  206. minItems: 1,
  207. uniqueItems: true
  208. }
  209. },
  210. type: "object",
  211. properties: {
  212. id: {
  213. type: "string"
  214. },
  215. $schema: {
  216. type: "string"
  217. },
  218. title: {
  219. type: "string"
  220. },
  221. description: {
  222. type: "string"
  223. },
  224. default: { },
  225. multipleOf: {
  226. type: "number",
  227. minimum: 0,
  228. exclusiveMinimum: true
  229. },
  230. maximum: {
  231. type: "number"
  232. },
  233. exclusiveMaximum: {
  234. type: "boolean",
  235. default: false
  236. },
  237. minimum: {
  238. type: "number"
  239. },
  240. exclusiveMinimum: {
  241. type: "boolean",
  242. default: false
  243. },
  244. maxLength: { $ref: "#/definitions/positiveInteger" },
  245. minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
  246. pattern: {
  247. type: "string",
  248. format: "regex"
  249. },
  250. additionalItems: {
  251. anyOf: [
  252. { type: "boolean" },
  253. { $ref: "#" }
  254. ],
  255. default: { }
  256. },
  257. items: {
  258. anyOf: [
  259. { $ref: "#" },
  260. { $ref: "#/definitions/schemaArray" }
  261. ],
  262. default: { }
  263. },
  264. maxItems: { $ref: "#/definitions/positiveInteger" },
  265. minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
  266. uniqueItems: {
  267. type: "boolean",
  268. default: false
  269. },
  270. maxProperties: { $ref: "#/definitions/positiveInteger" },
  271. minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
  272. required: { $ref: "#/definitions/stringArray" },
  273. additionalProperties: {
  274. anyOf: [
  275. { type: "boolean" },
  276. { $ref: "#" }
  277. ],
  278. default: { }
  279. },
  280. definitions: {
  281. type: "object",
  282. additionalProperties: { $ref: "#" },
  283. default: { }
  284. },
  285. properties: {
  286. type: "object",
  287. additionalProperties: { $ref: "#" },
  288. default: { }
  289. },
  290. patternProperties: {
  291. type: "object",
  292. additionalProperties: { $ref: "#" },
  293. default: { }
  294. },
  295. dependencies: {
  296. type: "object",
  297. additionalProperties: {
  298. anyOf: [
  299. { $ref: "#" },
  300. { $ref: "#/definitions/stringArray" }
  301. ]
  302. }
  303. },
  304. enum: {
  305. type: "array",
  306. minItems: 1,
  307. uniqueItems: true
  308. },
  309. type: {
  310. anyOf: [
  311. { $ref: "#/definitions/simpleTypes" },
  312. {
  313. type: "array",
  314. items: { $ref: "#/definitions/simpleTypes" },
  315. minItems: 1,
  316. uniqueItems: true
  317. }
  318. ]
  319. },
  320. format: { type: "string" },
  321. allOf: { $ref: "#/definitions/schemaArray" },
  322. anyOf: { $ref: "#/definitions/schemaArray" },
  323. oneOf: { $ref: "#/definitions/schemaArray" },
  324. not: { $ref: "#" }
  325. },
  326. dependencies: {
  327. exclusiveMaximum: ["maximum"],
  328. exclusiveMinimum: ["minimum"]
  329. },
  330. default: { }
  331. };
  332. //------------------------------------------------------------------------------
  333. // Public Interface
  334. //------------------------------------------------------------------------------
  335. var ajvOrig = (additionalOptions = {}) => {
  336. const ajv = new Ajv__default["default"]({
  337. meta: false,
  338. useDefaults: true,
  339. validateSchema: false,
  340. missingRefs: "ignore",
  341. verbose: true,
  342. schemaId: "auto",
  343. ...additionalOptions
  344. });
  345. ajv.addMetaSchema(metaSchema);
  346. // eslint-disable-next-line no-underscore-dangle
  347. ajv._opts.defaultMeta = metaSchema.id;
  348. return ajv;
  349. };
  350. /**
  351. * @fileoverview Applies default rule options
  352. * @author JoshuaKGoldberg
  353. */
  354. /**
  355. * Check if the variable contains an object strictly rejecting arrays
  356. * @param {unknown} value an object
  357. * @returns {boolean} Whether value is an object
  358. */
  359. function isObjectNotArray(value) {
  360. return typeof value === "object" && value !== null && !Array.isArray(value);
  361. }
  362. /**
  363. * Deeply merges second on top of first, creating a new {} object if needed.
  364. * @param {T} first Base, default value.
  365. * @param {U} second User-specified value.
  366. * @returns {T | U | (T & U)} Merged equivalent of second on top of first.
  367. */
  368. function deepMergeObjects(first, second) {
  369. if (second === void 0) {
  370. return first;
  371. }
  372. if (!isObjectNotArray(first) || !isObjectNotArray(second)) {
  373. return second;
  374. }
  375. const result = { ...first, ...second };
  376. for (const key of Object.keys(second)) {
  377. if (Object.prototype.propertyIsEnumerable.call(first, key)) {
  378. result[key] = deepMergeObjects(first[key], second[key]);
  379. }
  380. }
  381. return result;
  382. }
  383. /**
  384. * Deeply merges second on top of first, creating a new [] array if needed.
  385. * @param {T[] | undefined} first Base, default values.
  386. * @param {U[] | undefined} second User-specified values.
  387. * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first.
  388. */
  389. function deepMergeArrays(first, second) {
  390. if (!first || !second) {
  391. return second || first || [];
  392. }
  393. return [
  394. ...first.map((value, i) => deepMergeObjects(value, second[i])),
  395. ...second.slice(first.length)
  396. ];
  397. }
  398. /**
  399. * @fileoverview Defines a schema for configs.
  400. * @author Sylvan Mably
  401. */
  402. const baseConfigProperties = {
  403. $schema: { type: "string" },
  404. env: { type: "object" },
  405. extends: { $ref: "#/definitions/stringOrStrings" },
  406. globals: { type: "object" },
  407. overrides: {
  408. type: "array",
  409. items: { $ref: "#/definitions/overrideConfig" },
  410. additionalItems: false
  411. },
  412. parser: { type: ["string", "null"] },
  413. parserOptions: { type: "object" },
  414. plugins: { type: "array" },
  415. processor: { type: "string" },
  416. rules: { type: "object" },
  417. settings: { type: "object" },
  418. noInlineConfig: { type: "boolean" },
  419. reportUnusedDisableDirectives: { type: "boolean" },
  420. ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
  421. };
  422. const configSchema = {
  423. definitions: {
  424. stringOrStrings: {
  425. oneOf: [
  426. { type: "string" },
  427. {
  428. type: "array",
  429. items: { type: "string" },
  430. additionalItems: false
  431. }
  432. ]
  433. },
  434. stringOrStringsRequired: {
  435. oneOf: [
  436. { type: "string" },
  437. {
  438. type: "array",
  439. items: { type: "string" },
  440. additionalItems: false,
  441. minItems: 1
  442. }
  443. ]
  444. },
  445. // Config at top-level.
  446. objectConfig: {
  447. type: "object",
  448. properties: {
  449. root: { type: "boolean" },
  450. ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
  451. ...baseConfigProperties
  452. },
  453. additionalProperties: false
  454. },
  455. // Config in `overrides`.
  456. overrideConfig: {
  457. type: "object",
  458. properties: {
  459. excludedFiles: { $ref: "#/definitions/stringOrStrings" },
  460. files: { $ref: "#/definitions/stringOrStringsRequired" },
  461. ...baseConfigProperties
  462. },
  463. required: ["files"],
  464. additionalProperties: false
  465. }
  466. },
  467. $ref: "#/definitions/objectConfig"
  468. };
  469. /**
  470. * @fileoverview Defines environment settings and globals.
  471. * @author Elan Shanker
  472. */
  473. //------------------------------------------------------------------------------
  474. // Helpers
  475. //------------------------------------------------------------------------------
  476. /**
  477. * Get the object that has difference.
  478. * @param {Record<string,boolean>} current The newer object.
  479. * @param {Record<string,boolean>} prev The older object.
  480. * @returns {Record<string,boolean>} The difference object.
  481. */
  482. function getDiff(current, prev) {
  483. const retv = {};
  484. for (const [key, value] of Object.entries(current)) {
  485. if (!Object.hasOwnProperty.call(prev, key)) {
  486. retv[key] = value;
  487. }
  488. }
  489. return retv;
  490. }
  491. const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ...
  492. const newGlobals2017 = {
  493. Atomics: false,
  494. SharedArrayBuffer: false
  495. };
  496. const newGlobals2020 = {
  497. BigInt: false,
  498. BigInt64Array: false,
  499. BigUint64Array: false,
  500. globalThis: false
  501. };
  502. const newGlobals2021 = {
  503. AggregateError: false,
  504. FinalizationRegistry: false,
  505. WeakRef: false
  506. };
  507. //------------------------------------------------------------------------------
  508. // Public Interface
  509. //------------------------------------------------------------------------------
  510. /** @type {Map<string, import("../lib/shared/types").Environment>} */
  511. var environments = new Map(Object.entries({
  512. // Language
  513. builtin: {
  514. globals: globals__default["default"].es5
  515. },
  516. es6: {
  517. globals: newGlobals2015,
  518. parserOptions: {
  519. ecmaVersion: 6
  520. }
  521. },
  522. es2015: {
  523. globals: newGlobals2015,
  524. parserOptions: {
  525. ecmaVersion: 6
  526. }
  527. },
  528. es2016: {
  529. globals: newGlobals2015,
  530. parserOptions: {
  531. ecmaVersion: 7
  532. }
  533. },
  534. es2017: {
  535. globals: { ...newGlobals2015, ...newGlobals2017 },
  536. parserOptions: {
  537. ecmaVersion: 8
  538. }
  539. },
  540. es2018: {
  541. globals: { ...newGlobals2015, ...newGlobals2017 },
  542. parserOptions: {
  543. ecmaVersion: 9
  544. }
  545. },
  546. es2019: {
  547. globals: { ...newGlobals2015, ...newGlobals2017 },
  548. parserOptions: {
  549. ecmaVersion: 10
  550. }
  551. },
  552. es2020: {
  553. globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
  554. parserOptions: {
  555. ecmaVersion: 11
  556. }
  557. },
  558. es2021: {
  559. globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
  560. parserOptions: {
  561. ecmaVersion: 12
  562. }
  563. },
  564. es2022: {
  565. globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
  566. parserOptions: {
  567. ecmaVersion: 13
  568. }
  569. },
  570. es2023: {
  571. globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
  572. parserOptions: {
  573. ecmaVersion: 14
  574. }
  575. },
  576. es2024: {
  577. globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
  578. parserOptions: {
  579. ecmaVersion: 15
  580. }
  581. },
  582. // Platforms
  583. browser: {
  584. globals: globals__default["default"].browser
  585. },
  586. node: {
  587. globals: globals__default["default"].node,
  588. parserOptions: {
  589. ecmaFeatures: {
  590. globalReturn: true
  591. }
  592. }
  593. },
  594. "shared-node-browser": {
  595. globals: globals__default["default"]["shared-node-browser"]
  596. },
  597. worker: {
  598. globals: globals__default["default"].worker
  599. },
  600. serviceworker: {
  601. globals: globals__default["default"].serviceworker
  602. },
  603. // Frameworks
  604. commonjs: {
  605. globals: globals__default["default"].commonjs,
  606. parserOptions: {
  607. ecmaFeatures: {
  608. globalReturn: true
  609. }
  610. }
  611. },
  612. amd: {
  613. globals: globals__default["default"].amd
  614. },
  615. mocha: {
  616. globals: globals__default["default"].mocha
  617. },
  618. jasmine: {
  619. globals: globals__default["default"].jasmine
  620. },
  621. jest: {
  622. globals: globals__default["default"].jest
  623. },
  624. phantomjs: {
  625. globals: globals__default["default"].phantomjs
  626. },
  627. jquery: {
  628. globals: globals__default["default"].jquery
  629. },
  630. qunit: {
  631. globals: globals__default["default"].qunit
  632. },
  633. prototypejs: {
  634. globals: globals__default["default"].prototypejs
  635. },
  636. shelljs: {
  637. globals: globals__default["default"].shelljs
  638. },
  639. meteor: {
  640. globals: globals__default["default"].meteor
  641. },
  642. mongo: {
  643. globals: globals__default["default"].mongo
  644. },
  645. protractor: {
  646. globals: globals__default["default"].protractor
  647. },
  648. applescript: {
  649. globals: globals__default["default"].applescript
  650. },
  651. nashorn: {
  652. globals: globals__default["default"].nashorn
  653. },
  654. atomtest: {
  655. globals: globals__default["default"].atomtest
  656. },
  657. embertest: {
  658. globals: globals__default["default"].embertest
  659. },
  660. webextensions: {
  661. globals: globals__default["default"].webextensions
  662. },
  663. greasemonkey: {
  664. globals: globals__default["default"].greasemonkey
  665. }
  666. }));
  667. /**
  668. * @fileoverview Validates configs.
  669. * @author Brandon Mills
  670. */
  671. const ajv = ajvOrig();
  672. const ruleValidators = new WeakMap();
  673. const noop = Function.prototype;
  674. //------------------------------------------------------------------------------
  675. // Private
  676. //------------------------------------------------------------------------------
  677. let validateSchema;
  678. const severityMap = {
  679. error: 2,
  680. warn: 1,
  681. off: 0
  682. };
  683. const validated = new WeakSet();
  684. // JSON schema that disallows passing any options
  685. const noOptionsSchema = Object.freeze({
  686. type: "array",
  687. minItems: 0,
  688. maxItems: 0
  689. });
  690. //-----------------------------------------------------------------------------
  691. // Exports
  692. //-----------------------------------------------------------------------------
  693. class ConfigValidator {
  694. constructor({ builtInRules = new Map() } = {}) {
  695. this.builtInRules = builtInRules;
  696. }
  697. /**
  698. * Gets a complete options schema for a rule.
  699. * @param {Rule} rule A rule object
  700. * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`.
  701. * @returns {Object|null} JSON Schema for the rule's options.
  702. * `null` if rule wasn't passed or its `meta.schema` is `false`.
  703. */
  704. getRuleOptionsSchema(rule) {
  705. if (!rule) {
  706. return null;
  707. }
  708. if (!rule.meta) {
  709. return { ...noOptionsSchema }; // default if `meta.schema` is not specified
  710. }
  711. const schema = rule.meta.schema;
  712. if (typeof schema === "undefined") {
  713. return { ...noOptionsSchema }; // default if `meta.schema` is not specified
  714. }
  715. // `schema:false` is an allowed explicit opt-out of options validation for the rule
  716. if (schema === false) {
  717. return null;
  718. }
  719. if (typeof schema !== "object" || schema === null) {
  720. throw new TypeError("Rule's `meta.schema` must be an array or object");
  721. }
  722. // ESLint-specific array form needs to be converted into a valid JSON Schema definition
  723. if (Array.isArray(schema)) {
  724. if (schema.length) {
  725. return {
  726. type: "array",
  727. items: schema,
  728. minItems: 0,
  729. maxItems: schema.length
  730. };
  731. }
  732. // `schema:[]` is an explicit way to specify that the rule does not accept any options
  733. return { ...noOptionsSchema };
  734. }
  735. // `schema:<object>` is assumed to be a valid JSON Schema definition
  736. return schema;
  737. }
  738. /**
  739. * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
  740. * @param {options} options The given options for the rule.
  741. * @returns {number|string} The rule's severity value
  742. */
  743. validateRuleSeverity(options) {
  744. const severity = Array.isArray(options) ? options[0] : options;
  745. const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
  746. if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
  747. return normSeverity;
  748. }
  749. throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
  750. }
  751. /**
  752. * Validates the non-severity options passed to a rule, based on its schema.
  753. * @param {{create: Function}} rule The rule to validate
  754. * @param {Array} localOptions The options for the rule, excluding severity
  755. * @returns {void}
  756. */
  757. validateRuleSchema(rule, localOptions) {
  758. if (!ruleValidators.has(rule)) {
  759. try {
  760. const schema = this.getRuleOptionsSchema(rule);
  761. if (schema) {
  762. ruleValidators.set(rule, ajv.compile(schema));
  763. }
  764. } catch (err) {
  765. const errorWithCode = new Error(err.message, { cause: err });
  766. errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA";
  767. throw errorWithCode;
  768. }
  769. }
  770. const validateRule = ruleValidators.get(rule);
  771. if (validateRule) {
  772. const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions);
  773. validateRule(mergedOptions);
  774. if (validateRule.errors) {
  775. throw new Error(validateRule.errors.map(
  776. error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
  777. ).join(""));
  778. }
  779. }
  780. }
  781. /**
  782. * Validates a rule's options against its schema.
  783. * @param {{create: Function}|null} rule The rule that the config is being validated for
  784. * @param {string} ruleId The rule's unique name.
  785. * @param {Array|number} options The given options for the rule.
  786. * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
  787. * no source is prepended to the message.
  788. * @returns {void}
  789. */
  790. validateRuleOptions(rule, ruleId, options, source = null) {
  791. try {
  792. const severity = this.validateRuleSeverity(options);
  793. if (severity !== 0) {
  794. this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
  795. }
  796. } catch (err) {
  797. let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"
  798. ? `Error while processing options validation schema of rule '${ruleId}': ${err.message}`
  799. : `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
  800. if (typeof source === "string") {
  801. enhancedMessage = `${source}:\n\t${enhancedMessage}`;
  802. }
  803. const enhancedError = new Error(enhancedMessage, { cause: err });
  804. if (err.code) {
  805. enhancedError.code = err.code;
  806. }
  807. throw enhancedError;
  808. }
  809. }
  810. /**
  811. * Validates an environment object
  812. * @param {Object} environment The environment config object to validate.
  813. * @param {string} source The name of the configuration source to report in any errors.
  814. * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
  815. * @returns {void}
  816. */
  817. validateEnvironment(
  818. environment,
  819. source,
  820. getAdditionalEnv = noop
  821. ) {
  822. // not having an environment is ok
  823. if (!environment) {
  824. return;
  825. }
  826. Object.keys(environment).forEach(id => {
  827. const env = getAdditionalEnv(id) || environments.get(id) || null;
  828. if (!env) {
  829. const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
  830. throw new Error(message);
  831. }
  832. });
  833. }
  834. /**
  835. * Validates a rules config object
  836. * @param {Object} rulesConfig The rules config object to validate.
  837. * @param {string} source The name of the configuration source to report in any errors.
  838. * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
  839. * @returns {void}
  840. */
  841. validateRules(
  842. rulesConfig,
  843. source,
  844. getAdditionalRule = noop
  845. ) {
  846. if (!rulesConfig) {
  847. return;
  848. }
  849. Object.keys(rulesConfig).forEach(id => {
  850. const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
  851. this.validateRuleOptions(rule, id, rulesConfig[id], source);
  852. });
  853. }
  854. /**
  855. * Validates a `globals` section of a config file
  856. * @param {Object} globalsConfig The `globals` section
  857. * @param {string|null} source The name of the configuration source to report in the event of an error.
  858. * @returns {void}
  859. */
  860. validateGlobals(globalsConfig, source = null) {
  861. if (!globalsConfig) {
  862. return;
  863. }
  864. Object.entries(globalsConfig)
  865. .forEach(([configuredGlobal, configuredValue]) => {
  866. try {
  867. normalizeConfigGlobal(configuredValue);
  868. } catch (err) {
  869. throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
  870. }
  871. });
  872. }
  873. /**
  874. * Validate `processor` configuration.
  875. * @param {string|undefined} processorName The processor name.
  876. * @param {string} source The name of config file.
  877. * @param {function(id:string): Processor} getProcessor The getter of defined processors.
  878. * @returns {void}
  879. */
  880. validateProcessor(processorName, source, getProcessor) {
  881. if (processorName && !getProcessor(processorName)) {
  882. throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
  883. }
  884. }
  885. /**
  886. * Formats an array of schema validation errors.
  887. * @param {Array} errors An array of error messages to format.
  888. * @returns {string} Formatted error message
  889. */
  890. formatErrors(errors) {
  891. return errors.map(error => {
  892. if (error.keyword === "additionalProperties") {
  893. const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
  894. return `Unexpected top-level property "${formattedPropertyPath}"`;
  895. }
  896. if (error.keyword === "type") {
  897. const formattedField = error.dataPath.slice(1);
  898. const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
  899. const formattedValue = JSON.stringify(error.data);
  900. return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
  901. }
  902. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  903. return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
  904. }).map(message => `\t- ${message}.\n`).join("");
  905. }
  906. /**
  907. * Validates the top level properties of the config object.
  908. * @param {Object} config The config object to validate.
  909. * @param {string} source The name of the configuration source to report in any errors.
  910. * @returns {void}
  911. */
  912. validateConfigSchema(config, source = null) {
  913. validateSchema = validateSchema || ajv.compile(configSchema);
  914. if (!validateSchema(config)) {
  915. throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
  916. }
  917. if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
  918. emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
  919. }
  920. }
  921. /**
  922. * Validates an entire config object.
  923. * @param {Object} config The config object to validate.
  924. * @param {string} source The name of the configuration source to report in any errors.
  925. * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
  926. * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
  927. * @returns {void}
  928. */
  929. validate(config, source, getAdditionalRule, getAdditionalEnv) {
  930. this.validateConfigSchema(config, source);
  931. this.validateRules(config.rules, source, getAdditionalRule);
  932. this.validateEnvironment(config.env, source, getAdditionalEnv);
  933. this.validateGlobals(config.globals, source);
  934. for (const override of config.overrides || []) {
  935. this.validateRules(override.rules, source, getAdditionalRule);
  936. this.validateEnvironment(override.env, source, getAdditionalEnv);
  937. this.validateGlobals(config.globals, source);
  938. }
  939. }
  940. /**
  941. * Validate config array object.
  942. * @param {ConfigArray} configArray The config array to validate.
  943. * @returns {void}
  944. */
  945. validateConfigArray(configArray) {
  946. const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
  947. const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
  948. const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
  949. // Validate.
  950. for (const element of configArray) {
  951. if (validated.has(element)) {
  952. continue;
  953. }
  954. validated.add(element);
  955. this.validateEnvironment(element.env, element.name, getPluginEnv);
  956. this.validateGlobals(element.globals, element.name);
  957. this.validateProcessor(element.processor, element.name, getPluginProcessor);
  958. this.validateRules(element.rules, element.name, getPluginRule);
  959. }
  960. }
  961. }
  962. /**
  963. * @fileoverview Common helpers for naming of plugins, formatters and configs
  964. */
  965. const NAMESPACE_REGEX = /^@.*\//iu;
  966. /**
  967. * Brings package name to correct format based on prefix
  968. * @param {string} name The name of the package.
  969. * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
  970. * @returns {string} Normalized name of the package
  971. * @private
  972. */
  973. function normalizePackageName(name, prefix) {
  974. let normalizedName = name;
  975. /**
  976. * On Windows, name can come in with Windows slashes instead of Unix slashes.
  977. * Normalize to Unix first to avoid errors later on.
  978. * https://github.com/eslint/eslint/issues/5644
  979. */
  980. if (normalizedName.includes("\\")) {
  981. normalizedName = normalizedName.replace(/\\/gu, "/");
  982. }
  983. if (normalizedName.charAt(0) === "@") {
  984. /**
  985. * it's a scoped package
  986. * package name is the prefix, or just a username
  987. */
  988. const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
  989. scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
  990. if (scopedPackageShortcutRegex.test(normalizedName)) {
  991. normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
  992. } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
  993. /**
  994. * for scoped packages, insert the prefix after the first / unless
  995. * the path is already @scope/eslint or @scope/eslint-xxx-yyy
  996. */
  997. normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
  998. }
  999. } else if (!normalizedName.startsWith(`${prefix}-`)) {
  1000. normalizedName = `${prefix}-${normalizedName}`;
  1001. }
  1002. return normalizedName;
  1003. }
  1004. /**
  1005. * Removes the prefix from a fullname.
  1006. * @param {string} fullname The term which may have the prefix.
  1007. * @param {string} prefix The prefix to remove.
  1008. * @returns {string} The term without prefix.
  1009. */
  1010. function getShorthandName(fullname, prefix) {
  1011. if (fullname[0] === "@") {
  1012. let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
  1013. if (matchResult) {
  1014. return matchResult[1];
  1015. }
  1016. matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
  1017. if (matchResult) {
  1018. return `${matchResult[1]}/${matchResult[2]}`;
  1019. }
  1020. } else if (fullname.startsWith(`${prefix}-`)) {
  1021. return fullname.slice(prefix.length + 1);
  1022. }
  1023. return fullname;
  1024. }
  1025. /**
  1026. * Gets the scope (namespace) of a term.
  1027. * @param {string} term The term which may have the namespace.
  1028. * @returns {string} The namespace of the term if it has one.
  1029. */
  1030. function getNamespaceFromTerm(term) {
  1031. const match = term.match(NAMESPACE_REGEX);
  1032. return match ? match[0] : "";
  1033. }
  1034. var naming = {
  1035. __proto__: null,
  1036. normalizePackageName: normalizePackageName,
  1037. getShorthandName: getShorthandName,
  1038. getNamespaceFromTerm: getNamespaceFromTerm
  1039. };
  1040. /**
  1041. * @fileoverview Package exports for @eslint/eslintrc
  1042. * @author Nicholas C. Zakas
  1043. */
  1044. //-----------------------------------------------------------------------------
  1045. // Exports
  1046. //-----------------------------------------------------------------------------
  1047. const Legacy = {
  1048. environments,
  1049. // shared
  1050. ConfigOps,
  1051. ConfigValidator,
  1052. naming
  1053. };
  1054. exports.Legacy = Legacy;
  1055. //# sourceMappingURL=eslintrc-universal.cjs.map