next-lint.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env node
  2. "use strict";
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.nextLint = void 0;
  7. var _fs = require("fs");
  8. var _indexJs = _interopRequireDefault(require("next/dist/compiled/arg/index.js"));
  9. var _path = require("path");
  10. var _chalk = _interopRequireDefault(require("next/dist/compiled/chalk"));
  11. var _constants = require("../lib/constants");
  12. var _runLintCheck = require("../lib/eslint/runLintCheck");
  13. var _utils = require("../server/lib/utils");
  14. var _storage = require("../telemetry/storage");
  15. var _config = _interopRequireDefault(require("../server/config"));
  16. var _constants1 = require("../shared/lib/constants");
  17. var _events = require("../telemetry/events");
  18. var _compileError = require("../lib/compile-error");
  19. var _isError = _interopRequireDefault(require("../lib/is-error"));
  20. var _getProjectDir = require("../lib/get-project-dir");
  21. function _interopRequireDefault(obj) {
  22. return obj && obj.__esModule ? obj : {
  23. default: obj
  24. };
  25. }
  26. var ref, ref1, ref2, ref3;
  27. const eslintOptions = (args, defaultCacheLocation)=>({
  28. overrideConfigFile: args["--config"] || null,
  29. extensions: (ref = args["--ext"]) != null ? ref : [
  30. ".js",
  31. ".jsx",
  32. ".ts",
  33. ".tsx"
  34. ],
  35. resolvePluginsRelativeTo: args["--resolve-plugins-relative-to"] || null,
  36. rulePaths: (ref1 = args["--rulesdir"]) != null ? ref1 : [],
  37. fix: (ref2 = args["--fix"]) != null ? ref2 : false,
  38. fixTypes: (ref3 = args["--fix-type"]) != null ? ref3 : null,
  39. ignorePath: args["--ignore-path"] || null,
  40. ignore: !Boolean(args["--no-ignore"]),
  41. allowInlineConfig: !Boolean(args["--no-inline-config"]),
  42. reportUnusedDisableDirectives: args["--report-unused-disable-directives"] || null,
  43. cache: !Boolean(args["--no-cache"]),
  44. cacheLocation: args["--cache-location"] || defaultCacheLocation,
  45. cacheStrategy: args["--cache-strategy"] || "metadata",
  46. errorOnUnmatchedPattern: args["--error-on-unmatched-pattern"] ? Boolean(args["--error-on-unmatched-pattern"]) : false
  47. });
  48. const nextLint = async (argv)=>{
  49. var ref7;
  50. const validArgs = {
  51. // Types
  52. "--help": Boolean,
  53. "--base-dir": String,
  54. "--dir": [
  55. String
  56. ],
  57. "--file": [
  58. String
  59. ],
  60. "--strict": Boolean,
  61. // Aliases
  62. "-h": "--help",
  63. "-b": "--base-dir",
  64. "-d": "--dir"
  65. };
  66. const validEslintArgs = {
  67. // Types
  68. "--config": String,
  69. "--ext": [
  70. String
  71. ],
  72. "--resolve-plugins-relative-to": String,
  73. "--rulesdir": [
  74. String
  75. ],
  76. "--fix": Boolean,
  77. "--fix-type": [
  78. String
  79. ],
  80. "--ignore-path": String,
  81. "--no-ignore": Boolean,
  82. "--quiet": Boolean,
  83. "--max-warnings": Number,
  84. "--no-inline-config": Boolean,
  85. "--report-unused-disable-directives": String,
  86. "--cache": Boolean,
  87. "--no-cache": Boolean,
  88. "--cache-location": String,
  89. "--cache-strategy": String,
  90. "--error-on-unmatched-pattern": Boolean,
  91. "--format": String,
  92. "--output-file": String,
  93. // Aliases
  94. "-c": "--config",
  95. "-f": "--format",
  96. "-o": "--output-file"
  97. };
  98. let args;
  99. try {
  100. args = (0, _indexJs).default({
  101. ...validArgs,
  102. ...validEslintArgs
  103. }, {
  104. argv
  105. });
  106. } catch (error) {
  107. if ((0, _isError).default(error) && error.code === "ARG_UNKNOWN_OPTION") {
  108. return (0, _utils).printAndExit(error.message, 1);
  109. }
  110. throw error;
  111. }
  112. if (args["--help"]) {
  113. (0, _utils).printAndExit(`
  114. Description
  115. Run ESLint on every file in specified directories.
  116. If not configured, ESLint will be set up for the first time.
  117. Usage
  118. $ next lint <baseDir> [options]
  119. <baseDir> represents the directory of the Next.js application.
  120. If no directory is provided, the current directory will be used.
  121. Options
  122. Basic configuration:
  123. -h, --help List this help
  124. -d, --dir Array Include directory, or directories, to run ESLint - default: 'pages', 'components', and 'lib'
  125. --file Array Include file, or files, to run ESLint
  126. -c, --config path::String Use this configuration file, overriding all other config options
  127. --ext [String] Specify JavaScript file extensions - default: .js, .jsx, .ts, .tsx
  128. --resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
  129. Initial setup:
  130. --strict Creates an .eslintrc.json file using the Next.js strict configuration (only possible if no .eslintrc.json file is present)
  131. Specifying rules:
  132. --rulesdir [path::String] Use additional rules from this directory
  133. Fixing problems:
  134. --fix Automatically fix problems
  135. --fix-type Array Specify the types of fixes to apply (problem, suggestion, layout)
  136. Ignoring files:
  137. --ignore-path path::String Specify path of ignore file
  138. --no-ignore Disable use of ignore files and patterns
  139. Handling warnings:
  140. --quiet Report errors only - default: false
  141. --max-warnings Int Number of warnings to trigger nonzero exit code - default: -1
  142. Output:
  143. -o, --output-file path::String Specify file to write report to
  144. -f, --format String Use a specific output format - default: Next.js custom formatter
  145. Inline configuration comments:
  146. --no-inline-config Prevent comments from changing config or rules
  147. --report-unused-disable-directives Adds reported errors for unused eslint-disable directives ("error" | "warn" | "off")
  148. Caching:
  149. --no-cache Disable caching
  150. --cache-location path::String Path to the cache file or directory - default: .eslintcache
  151. --cache-strategy String Strategy to use for detecting changed files in the cache, either metadata or content - default: metadata
  152. Miscellaneous:
  153. --error-on-unmatched-pattern Show errors when any file patterns are unmatched - default: false
  154. `, 0);
  155. }
  156. const baseDir = (0, _getProjectDir).getProjectDir(args._[0]);
  157. // Check if the provided directory exists
  158. if (!(0, _fs).existsSync(baseDir)) {
  159. (0, _utils).printAndExit(`> No such directory exists as the project root: ${baseDir}`);
  160. }
  161. const nextConfig = await (0, _config).default(_constants1.PHASE_PRODUCTION_BUILD, baseDir);
  162. var ref4;
  163. const files = (ref4 = args["--file"]) != null ? ref4 : [];
  164. var ref5;
  165. const dirs = (ref5 = args["--dir"]) != null ? ref5 : (ref7 = nextConfig.eslint) == null ? void 0 : ref7.dirs;
  166. const filesToLint = [
  167. ...dirs != null ? dirs : [],
  168. ...files
  169. ];
  170. const pathsToLint = (filesToLint.length ? filesToLint : _constants.ESLINT_DEFAULT_DIRS).reduce((res, d)=>{
  171. const currDir = (0, _path).join(baseDir, d);
  172. if (!(0, _fs).existsSync(currDir)) return res;
  173. res.push(currDir);
  174. return res;
  175. }, []);
  176. const reportErrorsOnly = Boolean(args["--quiet"]);
  177. var ref6;
  178. const maxWarnings = (ref6 = args["--max-warnings"]) != null ? ref6 : -1;
  179. const formatter = args["--format"] || null;
  180. const strict = Boolean(args["--strict"]);
  181. const outputFile = args["--output-file"] || null;
  182. const distDir = (0, _path).join(baseDir, nextConfig.distDir);
  183. const defaultCacheLocation = (0, _path).join(distDir, "cache", "eslint/");
  184. (0, _runLintCheck).runLintCheck(baseDir, pathsToLint, {
  185. lintDuringBuild: false,
  186. eslintOptions: eslintOptions(args, defaultCacheLocation),
  187. reportErrorsOnly: reportErrorsOnly,
  188. maxWarnings,
  189. formatter,
  190. outputFile,
  191. strict,
  192. hasAppDir: !!nextConfig.experimental.appDir
  193. }).then(async (lintResults)=>{
  194. const lintOutput = typeof lintResults === "string" ? lintResults : lintResults == null ? void 0 : lintResults.output;
  195. if (typeof lintResults !== "string" && (lintResults == null ? void 0 : lintResults.eventInfo)) {
  196. const telemetry = new _storage.Telemetry({
  197. distDir
  198. });
  199. telemetry.record((0, _events).eventLintCheckCompleted({
  200. ...lintResults.eventInfo,
  201. buildLint: false
  202. }));
  203. await telemetry.flush();
  204. }
  205. if (typeof lintResults !== "string" && (lintResults == null ? void 0 : lintResults.isError) && lintOutput) {
  206. throw new _compileError.CompileError(lintOutput);
  207. }
  208. if (lintOutput) {
  209. (0, _utils).printAndExit(lintOutput, 0);
  210. } else if (lintResults && !lintOutput) {
  211. (0, _utils).printAndExit(_chalk.default.green("\u2714 No ESLint warnings or errors"), 0);
  212. }
  213. }).catch((err)=>{
  214. (0, _utils).printAndExit(err.message);
  215. });
  216. };
  217. exports.nextLint = nextLint;
  218. //# sourceMappingURL=next-lint.js.map