added fonts

This commit is contained in:
guus committed 2025-07-02 11:28:41 +02:00
1 parent 4134e3a234
commit 142d2986b6
9079 files changed
+1498421 -2

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
export declare enum MessageSeverity {
Warning = 1,
Error = 2
}
interface LintMessage {
ruleId: string | null;
severity: 1 | 2;
message: string;
line: number;
column: number;
}
export interface LintResult {
filePath: string;
messages: LintMessage[];
errorCount: number;
warningCount: number;
output?: string;
source?: string;
}
export declare function formatResults(baseDir: string, results: LintResult[], format: (r: LintResult[]) => string | Promise<string>): Promise<{
output: string;
outputWithMessages: string;
totalNextPluginErrorCount: number;
totalNextPluginWarningCount: number;
}>;
export {};
+97
View File
@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
MessageSeverity: null,
formatResults: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
MessageSeverity: function() {
return MessageSeverity;
},
formatResults: function() {
return formatResults;
}
});
const _picocolors = require("../picocolors");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var MessageSeverity = /*#__PURE__*/ function(MessageSeverity) {
MessageSeverity[MessageSeverity["Warning"] = 1] = "Warning";
MessageSeverity[MessageSeverity["Error"] = 2] = "Error";
return MessageSeverity;
}({});
function pluginCount(messages) {
let nextPluginWarningCount = 0;
let nextPluginErrorCount = 0;
for(let i = 0; i < messages.length; i++){
const { severity, ruleId } = messages[i];
if (ruleId == null ? void 0 : ruleId.includes('@next/next')) {
if (severity === 1) {
nextPluginWarningCount += 1;
} else {
nextPluginErrorCount += 1;
}
}
}
return {
nextPluginErrorCount,
nextPluginWarningCount
};
}
function formatMessage(dir, messages, filePath) {
let fileName = _path.default.posix.normalize(_path.default.relative(dir, filePath).replace(/\\/g, '/'));
if (!fileName.startsWith('.')) {
fileName = './' + fileName;
}
let output = '\n' + (0, _picocolors.cyan)(fileName);
for(let i = 0; i < messages.length; i++){
const { message, severity, line, column, ruleId } = messages[i];
output = output + '\n';
if (line && column) {
output = output + (0, _picocolors.yellow)(line.toString()) + ':' + (0, _picocolors.yellow)(column.toString()) + ' ';
}
if (severity === 1) {
output += (0, _picocolors.yellow)((0, _picocolors.bold)('Warning')) + ': ';
} else {
output += (0, _picocolors.red)((0, _picocolors.bold)('Error')) + ': ';
}
output += message;
if (ruleId) {
output += ' ' + (0, _picocolors.gray)((0, _picocolors.bold)(ruleId));
}
}
return output;
}
async function formatResults(baseDir, results, format) {
let totalNextPluginErrorCount = 0;
let totalNextPluginWarningCount = 0;
let resultsWithMessages = results.filter(({ messages })=>messages == null ? void 0 : messages.length);
// Track number of Next.js plugin errors and warnings
resultsWithMessages.forEach(({ messages })=>{
const res = pluginCount(messages);
totalNextPluginErrorCount += res.nextPluginErrorCount;
totalNextPluginWarningCount += res.nextPluginWarningCount;
});
// Use user defined formatter or Next.js's built-in custom formatter
const output = format ? await format(resultsWithMessages) : resultsWithMessages.map(({ messages, filePath })=>formatMessage(baseDir, messages, filePath)).join('\n');
return {
output: output,
outputWithMessages: resultsWithMessages.length > 0 ? output + `\n\n${(0, _picocolors.cyan)('info')} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/app/api-reference/config/eslint#disabling-rules` : '',
totalNextPluginErrorCount,
totalNextPluginWarningCount
};
}
//# sourceMappingURL=customFormatter.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/eslint/customFormatter.ts"],"sourcesContent":["import { bold, cyan, gray, red, yellow } from '../picocolors'\nimport path from 'path'\n\n// eslint-disable-next-line no-shadow\nexport enum MessageSeverity {\n Warning = 1,\n Error = 2,\n}\n\ninterface LintMessage {\n ruleId: string | null\n severity: 1 | 2\n message: string\n line: number\n column: number\n}\n\nexport interface LintResult {\n filePath: string\n messages: LintMessage[]\n errorCount: number\n warningCount: number\n output?: string\n source?: string\n}\n\nfunction pluginCount(messages: LintMessage[]): {\n nextPluginErrorCount: number\n nextPluginWarningCount: number\n} {\n let nextPluginWarningCount = 0\n let nextPluginErrorCount = 0\n\n for (let i = 0; i < messages.length; i++) {\n const { severity, ruleId } = messages[i]\n\n if (ruleId?.includes('@next/next')) {\n if (severity === MessageSeverity.Warning) {\n nextPluginWarningCount += 1\n } else {\n nextPluginErrorCount += 1\n }\n }\n }\n\n return {\n nextPluginErrorCount,\n nextPluginWarningCount,\n }\n}\n\nfunction formatMessage(\n dir: string,\n messages: LintMessage[],\n filePath: string\n): string {\n let fileName = path.posix.normalize(\n path.relative(dir, filePath).replace(/\\\\/g, '/')\n )\n\n if (!fileName.startsWith('.')) {\n fileName = './' + fileName\n }\n\n let output = '\\n' + cyan(fileName)\n\n for (let i = 0; i < messages.length; i++) {\n const { message, severity, line, column, ruleId } = messages[i]\n\n output = output + '\\n'\n\n if (line && column) {\n output =\n output +\n yellow(line.toString()) +\n ':' +\n yellow(column.toString()) +\n ' '\n }\n\n if (severity === MessageSeverity.Warning) {\n output += yellow(bold('Warning')) + ': '\n } else {\n output += red(bold('Error')) + ': '\n }\n\n output += message\n\n if (ruleId) {\n output += ' ' + gray(bold(ruleId))\n }\n }\n\n return output\n}\n\nexport async function formatResults(\n baseDir: string,\n results: LintResult[],\n format: (r: LintResult[]) => string | Promise<string>\n): Promise<{\n output: string\n outputWithMessages: string\n totalNextPluginErrorCount: number\n totalNextPluginWarningCount: number\n}> {\n let totalNextPluginErrorCount = 0\n let totalNextPluginWarningCount = 0\n let resultsWithMessages = results.filter(({ messages }) => messages?.length)\n\n // Track number of Next.js plugin errors and warnings\n resultsWithMessages.forEach(({ messages }) => {\n const res = pluginCount(messages)\n totalNextPluginErrorCount += res.nextPluginErrorCount\n totalNextPluginWarningCount += res.nextPluginWarningCount\n })\n\n // Use user defined formatter or Next.js's built-in custom formatter\n const output = format\n ? await format(resultsWithMessages)\n : resultsWithMessages\n .map(({ messages, filePath }) =>\n formatMessage(baseDir, messages, filePath)\n )\n .join('\\n')\n\n return {\n output: output,\n outputWithMessages:\n resultsWithMessages.length > 0\n ? output +\n `\\n\\n${cyan(\n 'info'\n )} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/app/api-reference/config/eslint#disabling-rules`\n : '',\n totalNextPluginErrorCount,\n totalNextPluginWarningCount,\n }\n}\n"],"names":["MessageSeverity","formatResults","pluginCount","messages","nextPluginWarningCount","nextPluginErrorCount","i","length","severity","ruleId","includes","formatMessage","dir","filePath","fileName","path","posix","normalize","relative","replace","startsWith","output","cyan","message","line","column","yellow","toString","bold","red","gray","baseDir","results","format","totalNextPluginErrorCount","totalNextPluginWarningCount","resultsWithMessages","filter","forEach","res","map","join","outputWithMessages"],"mappings":";;;;;;;;;;;;;;;IAIYA,eAAe;eAAfA;;IA4FUC,aAAa;eAAbA;;;4BAhGwB;6DAC7B;;;;;;AAGV,IAAA,AAAKD,yCAAAA;;;WAAAA;;AAsBZ,SAASE,YAAYC,QAAuB;IAI1C,IAAIC,yBAAyB;IAC7B,IAAIC,uBAAuB;IAE3B,IAAK,IAAIC,IAAI,GAAGA,IAAIH,SAASI,MAAM,EAAED,IAAK;QACxC,MAAM,EAAEE,QAAQ,EAAEC,MAAM,EAAE,GAAGN,QAAQ,CAACG,EAAE;QAExC,IAAIG,0BAAAA,OAAQC,QAAQ,CAAC,eAAe;YAClC,IAAIF,gBAAsC;gBACxCJ,0BAA0B;YAC5B,OAAO;gBACLC,wBAAwB;YAC1B;QACF;IACF;IAEA,OAAO;QACLA;QACAD;IACF;AACF;AAEA,SAASO,cACPC,GAAW,EACXT,QAAuB,EACvBU,QAAgB;IAEhB,IAAIC,WAAWC,aAAI,CAACC,KAAK,CAACC,SAAS,CACjCF,aAAI,CAACG,QAAQ,CAACN,KAAKC,UAAUM,OAAO,CAAC,OAAO;IAG9C,IAAI,CAACL,SAASM,UAAU,CAAC,MAAM;QAC7BN,WAAW,OAAOA;IACpB;IAEA,IAAIO,SAAS,OAAOC,IAAAA,gBAAI,EAACR;IAEzB,IAAK,IAAIR,IAAI,GAAGA,IAAIH,SAASI,MAAM,EAAED,IAAK;QACxC,MAAM,EAAEiB,OAAO,EAAEf,QAAQ,EAAEgB,IAAI,EAAEC,MAAM,EAAEhB,MAAM,EAAE,GAAGN,QAAQ,CAACG,EAAE;QAE/De,SAASA,SAAS;QAElB,IAAIG,QAAQC,QAAQ;YAClBJ,SACEA,SACAK,IAAAA,kBAAM,EAACF,KAAKG,QAAQ,MACpB,MACAD,IAAAA,kBAAM,EAACD,OAAOE,QAAQ,MACtB;QACJ;QAEA,IAAInB,gBLine truncated
+22
View File
@@ -0,0 +1,22 @@
export declare const getESLintStrictValue: (cwd: string) => Promise<{
title: string;
recommended: boolean;
config: {
extends: string | string[];
};
}>;
export declare const getESLintPromptValues: (cwd: string) => Promise<({
title: string;
recommended: boolean;
config: {
extends: string | string[];
};
} | {
title: string;
config: {
extends: string;
};
} | {
title: string;
config: null;
})[]>;
+61
View File
@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getESLintPromptValues: null,
getESLintStrictValue: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getESLintPromptValues: function() {
return getESLintPromptValues;
},
getESLintStrictValue: function() {
return getESLintStrictValue;
}
});
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const getESLintStrictValue = async (cwd)=>{
const tsConfigLocation = await (0, _findup.default)('tsconfig.json', {
cwd
});
const hasTSConfig = tsConfigLocation !== undefined;
return {
title: 'Strict',
recommended: true,
config: {
extends: hasTSConfig ? [
'next/core-web-vitals',
'next/typescript'
] : 'next/core-web-vitals'
}
};
};
const getESLintPromptValues = async (cwd)=>{
return [
await getESLintStrictValue(cwd),
{
title: 'Base',
config: {
extends: 'next'
}
},
{
title: 'Cancel',
config: null
}
];
};
//# sourceMappingURL=getESLintPromptValues.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/eslint/getESLintPromptValues.ts"],"sourcesContent":["import findUp from 'next/dist/compiled/find-up'\n\nexport const getESLintStrictValue = async (cwd: string) => {\n const tsConfigLocation = await findUp('tsconfig.json', { cwd })\n const hasTSConfig = tsConfigLocation !== undefined\n\n return {\n title: 'Strict',\n recommended: true,\n config: {\n extends: hasTSConfig\n ? ['next/core-web-vitals', 'next/typescript']\n : 'next/core-web-vitals',\n },\n }\n}\n\nexport const getESLintPromptValues = async (cwd: string) => {\n return [\n await getESLintStrictValue(cwd),\n {\n title: 'Base',\n config: {\n extends: 'next',\n },\n },\n {\n title: 'Cancel',\n config: null,\n },\n ]\n}\n"],"names":["getESLintPromptValues","getESLintStrictValue","cwd","tsConfigLocation","findUp","hasTSConfig","undefined","title","recommended","config","extends"],"mappings":";;;;;;;;;;;;;;;IAiBaA,qBAAqB;eAArBA;;IAfAC,oBAAoB;eAApBA;;;+DAFM;;;;;;AAEZ,MAAMA,uBAAuB,OAAOC;IACzC,MAAMC,mBAAmB,MAAMC,IAAAA,eAAM,EAAC,iBAAiB;QAAEF;IAAI;IAC7D,MAAMG,cAAcF,qBAAqBG;IAEzC,OAAO;QACLC,OAAO;QACPC,aAAa;QACbC,QAAQ;YACNC,SAASL,cACL;gBAAC;gBAAwB;aAAkB,GAC3C;QACN;IACF;AACF;AAEO,MAAML,wBAAwB,OAAOE;IAC1C,OAAO;QACL,MAAMD,qBAAqBC;QAC3B;YACEK,OAAO;YACPE,QAAQ;gBACNC,SAAS;YACX;QACF;QACA;YACEH,OAAO;YACPE,QAAQ;QACV;KACD;AACH"}
+9
View File
@@ -0,0 +1,9 @@
export type ConfigAvailable = {
exists: boolean;
emptyEslintrc?: boolean;
emptyPkgJsonConfig?: boolean;
firstTimeSetup?: true;
};
export declare function hasEslintConfiguration(eslintrcFile: string | null, packageJsonConfig: {
eslintConfig: any;
} | null): Promise<ConfigAvailable>;
+37
View File
@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "hasEslintConfiguration", {
enumerable: true,
get: function() {
return hasEslintConfiguration;
}
});
const _fs = require("fs");
async function hasEslintConfiguration(eslintrcFile, packageJsonConfig) {
const configObject = {
exists: false,
emptyEslintrc: false,
emptyPkgJsonConfig: false
};
if (eslintrcFile) {
const content = await _fs.promises.readFile(eslintrcFile, {
encoding: 'utf8'
}).then((txt)=>txt.trim().replace(/\n/g, ''), ()=>null);
if (content === '' || content === '{}' || content === '---' || content === 'module.exports = {}') {
configObject.emptyEslintrc = true;
} else {
configObject.exists = true;
}
} else if (packageJsonConfig == null ? void 0 : packageJsonConfig.eslintConfig) {
if (Object.keys(packageJsonConfig.eslintConfig).length) {
configObject.exists = true;
} else {
configObject.emptyPkgJsonConfig = true;
}
}
return configObject;
}
//# sourceMappingURL=hasEslintConfiguration.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/eslint/hasEslintConfiguration.ts"],"sourcesContent":["import { promises as fs } from 'fs'\n\nexport type ConfigAvailable = {\n exists: boolean\n emptyEslintrc?: boolean\n emptyPkgJsonConfig?: boolean\n firstTimeSetup?: true\n}\n\nexport async function hasEslintConfiguration(\n eslintrcFile: string | null,\n packageJsonConfig: { eslintConfig: any } | null\n): Promise<ConfigAvailable> {\n const configObject = {\n exists: false,\n emptyEslintrc: false,\n emptyPkgJsonConfig: false,\n }\n\n if (eslintrcFile) {\n const content = await fs.readFile(eslintrcFile, { encoding: 'utf8' }).then(\n (txt) => txt.trim().replace(/\\n/g, ''),\n () => null\n )\n\n if (\n content === '' ||\n content === '{}' ||\n content === '---' ||\n content === 'module.exports = {}'\n ) {\n configObject.emptyEslintrc = true\n } else {\n configObject.exists = true\n }\n } else if (packageJsonConfig?.eslintConfig) {\n if (Object.keys(packageJsonConfig.eslintConfig).length) {\n configObject.exists = true\n } else {\n configObject.emptyPkgJsonConfig = true\n }\n }\n return configObject\n}\n"],"names":["hasEslintConfiguration","eslintrcFile","packageJsonConfig","configObject","exists","emptyEslintrc","emptyPkgJsonConfig","content","fs","readFile","encoding","then","txt","trim","replace","eslintConfig","Object","keys","length"],"mappings":";;;;+BASsBA;;;eAAAA;;;oBATS;AASxB,eAAeA,uBACpBC,YAA2B,EAC3BC,iBAA+C;IAE/C,MAAMC,eAAe;QACnBC,QAAQ;QACRC,eAAe;QACfC,oBAAoB;IACtB;IAEA,IAAIL,cAAc;QAChB,MAAMM,UAAU,MAAMC,YAAE,CAACC,QAAQ,CAACR,cAAc;YAAES,UAAU;QAAO,GAAGC,IAAI,CACxE,CAACC,MAAQA,IAAIC,IAAI,GAAGC,OAAO,CAAC,OAAO,KACnC,IAAM;QAGR,IACEP,YAAY,MACZA,YAAY,QACZA,YAAY,SACZA,YAAY,uBACZ;YACAJ,aAAaE,aAAa,GAAG;QAC/B,OAAO;YACLF,aAAaC,MAAM,GAAG;QACxB;IACF,OAAO,IAAIF,qCAAAA,kBAAmBa,YAAY,EAAE;QAC1C,IAAIC,OAAOC,IAAI,CAACf,kBAAkBa,YAAY,EAAEG,MAAM,EAAE;YACtDf,aAAaC,MAAM,GAAG;QACxB,OAAO;YACLD,aAAaG,kBAAkB,GAAG;QACpC;IACF;IACA,OAAOH;AACT"}
+23
View File
@@ -0,0 +1,23 @@
import type { EventLintCheckCompleted } from '../../telemetry/events/build';
declare function lint(baseDir: string, lintDirs: string[], eslintrcFile: string | null, pkgJsonPath: string | null, { lintDuringBuild, eslintOptions, reportErrorsOnly, maxWarnings, formatter, outputFile, }: {
lintDuringBuild: boolean;
eslintOptions: any;
reportErrorsOnly: boolean;
maxWarnings: number;
formatter: string | null;
outputFile: string | null;
}): Promise<string | null | {
output: string | null;
isError: boolean;
eventInfo: EventLintCheckCompleted;
}>;
export declare function runLintCheck(baseDir: string, lintDirs: string[], opts: {
lintDuringBuild?: boolean;
eslintOptions?: any;
reportErrorsOnly?: boolean;
maxWarnings?: number;
formatter?: string | null;
outputFile?: string | null;
strict?: boolean;
}): ReturnType<typeof lint>;
export {};
+360
View File
@@ -0,0 +1,360 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "runLintCheck", {
enumerable: true,
get: function() {
return runLintCheck;
}
});
const _fs = require("fs");
const _picocolors = require("../picocolors");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _semver = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/semver"));
const _commentjson = /*#__PURE__*/ _interop_require_wildcard(require("next/dist/compiled/comment-json"));
const _customFormatter = require("./customFormatter");
const _writeDefaultConfig = require("./writeDefaultConfig");
const _hasEslintConfiguration = require("./hasEslintConfiguration");
const _writeOutputFile = require("./writeOutputFile");
const _findpagesdir = require("../find-pages-dir");
const _installdependencies = require("../install-dependencies");
const _hasnecessarydependencies = require("../has-necessary-dependencies");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
const _iserror = /*#__PURE__*/ _interop_require_wildcard(require("../is-error"));
const _getpkgmanager = require("../helpers/get-pkg-manager");
const _getESLintPromptValues = require("./getESLintPromptValues");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
// 0 is off, 1 is warn, 2 is error. See https://eslint.org/docs/user-guide/configuring/rules#configuring-rules
const VALID_SEVERITY = [
'off',
'warn',
'error'
];
function isValidSeverity(severity) {
return VALID_SEVERITY.includes(severity);
}
const requiredPackages = [
{
file: 'eslint',
pkg: 'eslint',
exportsRestrict: false
},
{
file: 'eslint-config-next',
pkg: 'eslint-config-next',
exportsRestrict: false
}
];
async function cliPrompt(cwd) {
console.log((0, _picocolors.bold)(`${(0, _picocolors.cyan)('?')} How would you like to configure ESLint? https://nextjs.org/docs/app/api-reference/config/eslint`));
try {
const cliSelect = (await Promise.resolve(require('next/dist/compiled/cli-select'))).default;
const { value } = await cliSelect({
values: await (0, _getESLintPromptValues.getESLintPromptValues)(cwd),
valueRenderer: ({ title, recommended }, selected)=>{
const name = selected ? (0, _picocolors.bold)((0, _picocolors.underline)((0, _picocolors.cyan)(title))) : title;
return name + (recommended ? (0, _picocolors.bold)((0, _picocolors.yellow)(' (recommended)')) : '');
},
selected: (0, _picocolors.cyan)('❯ '),
unselected: ' '
});
return {
config: (value == null ? void 0 : value.config) ?? null
};
} catch {
return {
config: null
};
}
}
async function lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, { lintDuringBuild = false, eslintOptions = null, reportErrorsOnly = false, maxWarnings = -1, formatter = null, outputFile = null }) {
try {
var _mod_CLIEngine, _ESLint_getErrorResults;
// Load ESLint after we're sure it exists:
const deps = await (0, _hasnecessarydependencies.hasNecessaryDependencies)(baseDir, requiredPackages);
const packageManager = (0, _getpkgmanager.getPkgManager)(baseDir);
if (deps.missing.some((dep)=>dep.pkg === 'eslint')) {
_log.error(`ESLint must be installed${lintDuringBuild ? ' in order to run during builds:' : ':'} ${(0, _picocolors.bold)((0, _picocolors.cyan)((packageManager === 'yarn' ? 'yarn add --dev' : packageManager === 'pnpm' ? 'pnpm install --save-dev' : 'npm install --save-dev') + ' eslint'))}`);
return null;
}
const mod = await Promise.resolve(require(deps.resolved.get('eslint')));
// If V9 config was found, use flat config, or else use legacy.
const useFlatConfig = eslintrcFile ? _path.default.basename(eslintrcFile).startsWith('eslint.config.') : false;
let ESLint;
// loadESLint is >= 8.57.0
// PR https://github.com/eslint/eslint/pull/18098
// Release https://github.com/eslint/eslint/releases/tag/v8.57.0
if ('loadESLint' in mod) {
// By default, configType is `flat`. If `useFlatConfig` is false, the return value is `LegacyESLint`.
// https://github.com/eslint/eslint/blob/1def4cdfab1f067c5089df8b36242cdf912b0eb6/lib/types/index.d.ts#L1609-L1613
ESLint = await mod.loadESLint({
useFlatConfig
});
} else {
// eslint < 8.57.0, use legacy ESLint
ESLint = mod.ESLint;
}
let eslintVersion = (ESLint == null ? void 0 : ESLint.version) ?? ((_mod_CLIEngine = mod.CLIEngine) == null ? void 0 : _mod_CLIEngine.version);
if (!eslintVersion || _semver.default.lt(eslintVersion, '7.0.0')) {
return `${(0, _picocolors.red)('error')} - Your project has an older version of ESLint installed${eslintVersion ? ' (' + eslintVersion + ')' : ''}. Please upgrade to ESLint version 7 or above`;
}
let options = {
useEslintrc: true,
baseConfig: {},
errorOnUnmatchedPattern: false,
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx'
],
cache: true,
...eslintOptions
};
if (_semver.default.gte(eslintVersion, '9.0.0') && useFlatConfig) {
for (const option of [
'useEslintrc',
'extensions',
'ignorePath',
'reportUnusedDisableDirectives',
'resolvePluginsRelativeTo',
'rulePaths',
'inlineConfig',
'maxWarnings'
]){
if (option in options) {
delete options[option];
}
}
}
let eslint = new ESLint(options);
let nextEslintPluginIsEnabled = false;
const nextRulesEnabled = new Map();
for (const configFile of [
eslintrcFile,
pkgJsonPath
]){
if (!configFile) continue;
const completeConfig = await eslint.calculateConfigForFile(configFile);
if (!completeConfig) continue;
const plugins = completeConfig.plugins;
const hasNextPlugin = // in ESLint < 9, `plugins` value is string[]
Array.isArray(plugins) ? plugins.includes('@next/next') : '@next/next' in plugins;
if (hasNextPlugin) {
nextEslintPluginIsEnabled = true;
for (const [name, [severity]] of Object.entries(completeConfig.rules)){
if (!name.startsWith('@next/next/')) {
continue;
}
if (typeof severity === 'number' && severity >= 0 && severity < VALID_SEVERITY.length) {
nextRulesEnabled.set(name, VALID_SEVERITY[severity]);
} else if (typeof severity === 'string' && isValidSeverity(severity)) {
nextRulesEnabled.set(name, severity);
}
}
break;
}
}
const pagesDir = (0, _findpagesdir.findPagesDir)(baseDir).pagesDir;
const pagesDirRules = pagesDir ? [
'@next/next/no-html-link-for-pages'
] : [];
if (nextEslintPluginIsEnabled) {
let updatedPagesDir = false;
for (const rule of pagesDirRules){
var _options_baseConfig_rules, _options_baseConfig_rules1;
if (!((_options_baseConfig_rules = options.baseConfig.rules) == null ? void 0 : _options_baseConfig_rules[rule]) && !((_options_baseConfig_rules1 = options.baseConfig.rules) == null ? void 0 : _options_baseConfig_rules1[rule.replace('@next/next', '@next/babel-plugin-next')])) {
if (!options.baseConfig.rules) {
options.baseConfig.rules = {};
}
options.baseConfig.rules[rule] = [
1,
pagesDir
];
updatedPagesDir = true;
}
}
if (updatedPagesDir) {
eslint = new ESLint(options);
}
} else {
_log.warn('');
_log.warn('The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/app/api-reference/config/eslint#migrating-existing-config');
}
const lintStart = process.hrtime();
let results = await eslint.lintFiles(lintDirs);
let selectedFormatter = null;
if (options.fix) await ESLint.outputFixes(results);
if (reportErrorsOnly) results = await ESLint.getErrorResults(results) // Only return errors if --quiet flag is used
;
if (formatter) selectedFormatter = await eslint.loadFormatter(formatter);
const formattedResult = await (0, _customFormatter.formatResults)(baseDir, results, selectedFormatter == null ? void 0 : selectedFormatter.format);
const lintEnd = process.hrtime(lintStart);
const totalWarnings = results.reduce((sum, file)=>sum + file.warningCount, 0);
if (outputFile) await (0, _writeOutputFile.writeOutputFile)(outputFile, formattedResult.output);
return {
output: formattedResult.outputWithMessages,
isError: ((_ESLint_getErrorResults = ESLint.getErrorResults(results)) == null ? void 0 : _ESLint_getErrorResults.length) > 0 || maxWarnings >= 0 && totalWarnings > maxWarnings,
eventInfo: {
durationInSeconds: lintEnd[0],
eslintVersion: eslintVersion,
lintedFilesCount: results.length,
lintFix: !!options.fix,
nextEslintPluginVersion: nextEslintPluginIsEnabled && deps.resolved.has('eslint-config-next') ? require(_path.default.join(_path.default.dirname(deps.resolved.get('eslint-config-next')), 'package.json')).version : null,
nextEslintPluginErrorsCount: formattedResult.totalNextPluginErrorCount,
nextEslintPluginWarningsCount: formattedResult.totalNextPluginWarningCount,
nextRulesEnabled: Object.fromEntries(nextRulesEnabled)
}
};
} catch (err) {
if (lintDuringBuild) {
_log.error(`ESLint: ${(0, _iserror.default)(err) && err.message ? err.message.replace(/\n/g, ' ') : err}`);
return null;
} else {
throw (0, _iserror.getProperError)(err);
}
}
}
async function runLintCheck(baseDir, lintDirs, opts) {
const { lintDuringBuild = false, eslintOptions = null, reportErrorsOnly = false, maxWarnings = -1, formatter = null, outputFile = null, strict = false } = opts;
try {
// Find user's .eslintrc file
// See: https://eslint.org/docs/user-guide/configuring/configuration-files#configuration-file-formats
const eslintrcFile = await (0, _findup.default)([
// eslint v9
'eslint.config.js',
'eslint.config.mjs',
'eslint.config.cjs',
// TS extensions require to install a separate package `jiti`.
// https://eslint.org/docs/latest/use/configure/configuration-files#typescript-configuration-files
'eslint.config.ts',
'eslint.config.mts',
'eslint.config.cts',
// eslint <= v8
'.eslintrc.js',
'.eslintrc.cjs',
'.eslintrc.yaml',
'.eslintrc.yml',
'.eslintrc.json',
'.eslintrc'
], {
cwd: baseDir
}) ?? null;
const pkgJsonPath = await (0, _findup.default)('package.json', {
cwd: baseDir
}) ?? null;
let packageJsonConfig = null;
if (pkgJsonPath) {
const pkgJsonContent = await _fs.promises.readFile(pkgJsonPath, {
encoding: 'utf8'
});
packageJsonConfig = _commentjson.parse(pkgJsonContent);
}
const config = await (0, _hasEslintConfiguration.hasEslintConfiguration)(eslintrcFile, packageJsonConfig);
let deps;
if (config.exists) {
// Run if ESLint config exists
return await lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, {
lintDuringBuild,
eslintOptions,
reportErrorsOnly,
maxWarnings,
formatter,
outputFile
});
} else {
// Display warning if no ESLint configuration is present inside
// config file during "next build", no warning is shown when
// no eslintrc file is present
if (lintDuringBuild) {
if (config.emptyPkgJsonConfig || config.emptyEslintrc) {
_log.warn(`No ESLint configuration detected. Run ${(0, _picocolors.bold)((0, _picocolors.cyan)('next lint'))} to begin setup`);
}
return null;
} else {
// Ask user what config they would like to start with for first time "next lint" setup
const { config: selectedConfig } = strict ? await (0, _getESLintPromptValues.getESLintStrictValue)(baseDir) : await cliPrompt(baseDir);
if (selectedConfig == null) {
// Show a warning if no option is selected in prompt
_log.warn('If you set up ESLint yourself, we recommend adding the Next.js ESLint plugin. See https://nextjs.org/docs/app/api-reference/config/eslint#migrating-existing-config');
return null;
} else {
// Check if necessary deps installed, and install any that are missing
deps = await (0, _hasnecessarydependencies.hasNecessaryDependencies)(baseDir, requiredPackages);
if (deps.missing.length > 0) {
deps.missing.forEach((dep)=>{
if (dep.pkg === 'eslint') {
// pin to v9 to avoid breaking changes
dep.pkg = 'eslint@^9';
}
});
await (0, _installdependencies.installDependencies)(baseDir, deps.missing, true);
}
// Write default ESLint config.
// Check for /pages and src/pages is to make sure this happens in Next.js folder
if ([
'app',
'src/app',
'pages',
'src/pages'
].some((dir)=>(0, _fs.existsSync)(_path.default.join(baseDir, dir)))) {
await (0, _writeDefaultConfig.writeDefaultConfig)(baseDir, config, selectedConfig, eslintrcFile, pkgJsonPath, packageJsonConfig);
}
}
_log.ready(`ESLint has successfully been configured. Run ${(0, _picocolors.bold)((0, _picocolors.cyan)('next lint'))} again to view warnings and errors.`);
return null;
}
}
} catch (err) {
throw err;
}
}
//# sourceMappingURL=runLintCheck.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/eslint/runLintCheck.ts"],"sourcesContent":["import { promises as fs, existsSync } from 'fs'\nimport { bold, cyan, red, underline, yellow } from '../picocolors'\nimport path from 'path'\n\nimport findUp from 'next/dist/compiled/find-up'\nimport semver from 'next/dist/compiled/semver'\nimport * as CommentJson from 'next/dist/compiled/comment-json'\n\nimport { formatResults } from './customFormatter'\nimport type { LintResult } from './customFormatter'\nimport { writeDefaultConfig } from './writeDefaultConfig'\nimport { hasEslintConfiguration } from './hasEslintConfiguration'\nimport { writeOutputFile } from './writeOutputFile'\n\nimport { findPagesDir } from '../find-pages-dir'\nimport { installDependencies } from '../install-dependencies'\nimport { hasNecessaryDependencies } from '../has-necessary-dependencies'\n\nimport * as Log from '../../build/output/log'\nimport type { EventLintCheckCompleted } from '../../telemetry/events/build'\nimport isError, { getProperError } from '../is-error'\nimport { getPkgManager } from '../helpers/get-pkg-manager'\nimport {\n getESLintStrictValue,\n getESLintPromptValues,\n} from './getESLintPromptValues'\n\ntype Config = {\n plugins: string[]\n rules: { [key: string]: Array<number | string> }\n}\n\n// 0 is off, 1 is warn, 2 is error. See https://eslint.org/docs/user-guide/configuring/rules#configuring-rules\nconst VALID_SEVERITY = ['off', 'warn', 'error'] as const\ntype Severity = (typeof VALID_SEVERITY)[number]\n\nfunction isValidSeverity(severity: string): severity is Severity {\n return VALID_SEVERITY.includes(severity as Severity)\n}\n\nconst requiredPackages = [\n { file: 'eslint', pkg: 'eslint', exportsRestrict: false },\n {\n file: 'eslint-config-next',\n pkg: 'eslint-config-next',\n exportsRestrict: false,\n },\n]\n\nasync function cliPrompt(cwd: string): Promise<{ config?: any }> {\n console.log(\n bold(\n `${cyan(\n '?'\n )} How would you like to configure ESLint? https://nextjs.org/docs/app/api-reference/config/eslint`\n )\n )\n\n try {\n const cliSelect = (\n await Promise.resolve(require('next/dist/compiled/cli-select'))\n ).default\n const { value } = await cliSelect({\n values: await getESLintPromptValues(cwd),\n valueRenderer: (\n {\n title,\n recommended,\n }: { title: string; recommended?: boolean; config: any },\n selected: boolean\n ) => {\n const name = selected ? bold(underline(cyan(title))) : title\n return name + (recommended ? bold(yellow(' (recommended)')) : '')\n },\n selected: cyan('❯ '),\n unselected: ' ',\n })\n\n return { config: value?.config ?? null }\n } catch {\n return { config: null }\n }\n}\n\nasync function lint(\n baseDir: string,\n lintDirs: string[],\n eslintrcFile: string | null,\n pkgJsonPath: string | null,\n {\n lintDuringBuild = false,\n eslintOptions = null,\n reportErrorsOnly = false,\n maxWarnings = -1,\n formatter = null,\n outputFile = null,\n }: {\n lintDuringBuild: boolean\n eslintOptions: any\n reportErrorsOnly: boolean\n maxWarnings: number\n formatter: string | null\n outputFile: string | null\n }\n): Promise<\n | string\n | null\n | {\n output: string | null\n isError: boolean\n eventInfo: EventLintCheckCompleted\n }\n> {\n try {\n // Load ESLint after we're sure it exists:\n const deps = await hasNecessaryDependencies(baseDir, requiredPackages)\n const packageManager = getPkgManager(baseDir)\n\n if (deps.missing.some((dep) => dep.pkg === 'eslint')) {\n Log.error(\n `ESLint must be installed${\n lintDuringBuild ? ' in order to run during builds:' : ':'\n } ${bold(\n cyan(\n (packageManager === 'yarn'\n ? 'yarn add --dev'\n : packageManager === 'pnpm'\n ? 'pnpm install --save-dev'\n : 'npm install --save-dev') + ' eslint'\n )\n )}`\n )\n return null\n }\n\n const mod = await Promise.resolve(require(deps.resolved.get('eslint')!))\n\n // If V9 config was found, use flat config, or else use legacy.\n const useFlatConfig = eslintrcFile\n ? // eslintrcFile is absolute path\n path.basename(eslintrcFile).startsWith('eslint.config.')\n : false\n\n let ESLint\n // loadESLint is >= 8.57.0\n // PR https://github.com/eslint/eslint/pull/18098\n // Release https://github.com/eslint/eslint/releases/tag/v8.57.0\n if ('loadESLint' in mod) {\n // By default, configType is `flat`. If `useFlatConfig` is false, the return value is `LegacyESLint`.\n // https://github.com/eslint/eslint/blob/1def4cdfab1f067c5089df8b36242cdf912b0eb6/lib/types/index.d.ts#L1609-L1613\n ESLint = await mod.loadESLint({\n useFlatConfig,\n })\n } else {\n // eslint < 8.57.0, use legacy ESLinLine truncated
+4
View File
@@ -0,0 +1,4 @@
import type { ConfigAvailable } from './hasEslintConfiguration';
export declare function writeDefaultConfig(baseDir: string, { exists, emptyEslintrc, emptyPkgJsonConfig }: ConfigAvailable, selectedConfig: any, eslintrcFile: string | null, pkgJsonPath: string | null, packageJsonConfig: {
eslintConfig: any;
} | null): Promise<void>;
+87
View File
@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "writeDefaultConfig", {
enumerable: true,
get: function() {
return writeDefaultConfig;
}
});
const _fs = require("fs");
const _picocolors = require("../picocolors");
const _os = /*#__PURE__*/ _interop_require_default(require("os"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _commentjson = /*#__PURE__*/ _interop_require_wildcard(require("next/dist/compiled/comment-json"));
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
async function writeDefaultConfig(baseDir, { exists, emptyEslintrc, emptyPkgJsonConfig }, selectedConfig, eslintrcFile, pkgJsonPath, packageJsonConfig) {
if (!exists && emptyEslintrc && eslintrcFile) {
const ext = _path.default.extname(eslintrcFile);
let newFileContent;
if (ext === '.yaml' || ext === '.yml') {
newFileContent = "extends: 'next'";
} else {
newFileContent = _commentjson.stringify(selectedConfig, null, 2);
if (ext === '.js') {
newFileContent = 'module.exports = ' + newFileContent;
}
}
await _fs.promises.writeFile(eslintrcFile, newFileContent + _os.default.EOL);
_log.info(`We detected an empty ESLint configuration file (${(0, _picocolors.bold)(_path.default.basename(eslintrcFile))}) and updated it for you!`);
} else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {
packageJsonConfig.eslintConfig = selectedConfig;
if (pkgJsonPath) await _fs.promises.writeFile(pkgJsonPath, _commentjson.stringify(packageJsonConfig, null, 2) + _os.default.EOL);
_log.info(`We detected an empty ${(0, _picocolors.bold)('eslintConfig')} field in package.json and updated it for you!`);
} else if (!exists) {
await _fs.promises.writeFile(_path.default.join(baseDir, '.eslintrc.json'), _commentjson.stringify(selectedConfig, null, 2) + _os.default.EOL);
console.log((0, _picocolors.green)(`We created the ${(0, _picocolors.bold)('.eslintrc.json')} file for you and included your selected configuration.`));
}
}
//# sourceMappingURL=writeDefaultConfig.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/eslint/writeDefaultConfig.ts"],"sourcesContent":["import { promises as fs } from 'fs'\nimport { bold, green } from '../picocolors'\nimport os from 'os'\nimport path from 'path'\nimport * as CommentJson from 'next/dist/compiled/comment-json'\nimport type { ConfigAvailable } from './hasEslintConfiguration'\n\nimport * as Log from '../../build/output/log'\n\nexport async function writeDefaultConfig(\n baseDir: string,\n { exists, emptyEslintrc, emptyPkgJsonConfig }: ConfigAvailable,\n selectedConfig: any,\n eslintrcFile: string | null,\n pkgJsonPath: string | null,\n packageJsonConfig: { eslintConfig: any } | null\n) {\n if (!exists && emptyEslintrc && eslintrcFile) {\n const ext = path.extname(eslintrcFile)\n\n let newFileContent\n if (ext === '.yaml' || ext === '.yml') {\n newFileContent = \"extends: 'next'\"\n } else {\n newFileContent = CommentJson.stringify(selectedConfig, null, 2)\n\n if (ext === '.js') {\n newFileContent = 'module.exports = ' + newFileContent\n }\n }\n\n await fs.writeFile(eslintrcFile, newFileContent + os.EOL)\n\n Log.info(\n `We detected an empty ESLint configuration file (${bold(\n path.basename(eslintrcFile)\n )}) and updated it for you!`\n )\n } else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {\n packageJsonConfig.eslintConfig = selectedConfig\n\n if (pkgJsonPath)\n await fs.writeFile(\n pkgJsonPath,\n CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL\n )\n\n Log.info(\n `We detected an empty ${bold(\n 'eslintConfig'\n )} field in package.json and updated it for you!`\n )\n } else if (!exists) {\n await fs.writeFile(\n path.join(baseDir, '.eslintrc.json'),\n CommentJson.stringify(selectedConfig, null, 2) + os.EOL\n )\n\n console.log(\n green(\n `We created the ${bold(\n '.eslintrc.json'\n )} file for you and included your selected configuration.`\n )\n )\n }\n}\n"],"names":["writeDefaultConfig","baseDir","exists","emptyEslintrc","emptyPkgJsonConfig","selectedConfig","eslintrcFile","pkgJsonPath","packageJsonConfig","ext","path","extname","newFileContent","CommentJson","stringify","fs","writeFile","os","EOL","Log","info","bold","basename","eslintConfig","join","console","log","green"],"mappings":";;;;+BASsBA;;;eAAAA;;;oBATS;4BACH;2DACb;6DACE;qEACY;6DAGR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEd,eAAeA,mBACpBC,OAAe,EACf,EAAEC,MAAM,EAAEC,aAAa,EAAEC,kBAAkB,EAAmB,EAC9DC,cAAmB,EACnBC,YAA2B,EAC3BC,WAA0B,EAC1BC,iBAA+C;IAE/C,IAAI,CAACN,UAAUC,iBAAiBG,cAAc;QAC5C,MAAMG,MAAMC,aAAI,CAACC,OAAO,CAACL;QAEzB,IAAIM;QACJ,IAAIH,QAAQ,WAAWA,QAAQ,QAAQ;YACrCG,iBAAiB;QACnB,OAAO;YACLA,iBAAiBC,aAAYC,SAAS,CAACT,gBAAgB,MAAM;YAE7D,IAAII,QAAQ,OAAO;gBACjBG,iBAAiB,sBAAsBA;YACzC;QACF;QAEA,MAAMG,YAAE,CAACC,SAAS,CAACV,cAAcM,iBAAiBK,WAAE,CAACC,GAAG;QAExDC,KAAIC,IAAI,CACN,CAAC,gDAAgD,EAAEC,IAAAA,gBAAI,EACrDX,aAAI,CAACY,QAAQ,CAAChB,eACd,yBAAyB,CAAC;IAEhC,OAAO,IAAI,CAACJ,UAAUE,sBAAsBI,mBAAmB;QAC7DA,kBAAkBe,YAAY,GAAGlB;QAEjC,IAAIE,aACF,MAAMQ,YAAE,CAACC,SAAS,CAChBT,aACAM,aAAYC,SAAS,CAACN,mBAAmB,MAAM,KAAKS,WAAE,CAACC,GAAG;QAG9DC,KAAIC,IAAI,CACN,CAAC,qBAAqB,EAAEC,IAAAA,gBAAI,EAC1B,gBACA,8CAA8C,CAAC;IAErD,OAAO,IAAI,CAACnB,QAAQ;QAClB,MAAMa,YAAE,CAACC,SAAS,CAChBN,aAAI,CAACc,IAAI,CAACvB,SAAS,mBACnBY,aAAYC,SAAS,CAACT,gBAAgB,MAAM,KAAKY,WAAE,CAACC,GAAG;QAGzDO,QAAQC,GAAG,CACTC,IAAAA,iBAAK,EACH,CAAC,eAAe,EAAEN,IAAAA,gBAAI,EACpB,kBACA,uDAAuD,CAAC;IAGhE;AACF"}
+8
View File
@@ -0,0 +1,8 @@
/**
* Create a file with eslint output data
*/
export declare function writeOutputFile(
/** The name file that needs to be created */
outputFile: string,
/** The data that needs to be inserted into the file */
outputData: string): Promise<void>;
+90
View File
@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "writeOutputFile", {
enumerable: true,
get: function() {
return writeOutputFile;
}
});
const _fs = require("fs");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
const _iserror = /*#__PURE__*/ _interop_require_default(require("../../lib/is-error"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Check if a given file path is a directory or not.
* Returns `true` if the path is a directory.
*/ function isDirectory(/** The path to a file to check. */ filePath) {
return _fs.promises.stat(filePath).then((stat)=>stat.isDirectory()).catch((error)=>{
if ((0, _iserror.default)(error) && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) {
return false;
}
throw error;
});
}
async function writeOutputFile(/** The name file that needs to be created */ outputFile, /** The data that needs to be inserted into the file */ outputData) {
const filePath = _path.default.resolve(process.cwd(), outputFile);
if (await isDirectory(filePath)) {
_log.error(`Cannot write to output file path, it is a directory: ${filePath}`);
} else {
try {
await _fs.promises.mkdir(_path.default.dirname(filePath), {
recursive: true
});
await _fs.promises.writeFile(filePath, outputData);
_log.info(`The output file has been created: ${filePath}`);
} catch (err) {
_log.error(`There was a problem writing the output file: ${filePath}`);
console.error(err);
}
}
}
//# sourceMappingURL=writeOutputFile.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/eslint/writeOutputFile.ts"],"sourcesContent":["import { promises as fs } from 'fs'\nimport path from 'path'\nimport * as Log from '../../build/output/log'\nimport isError from '../../lib/is-error'\n\n/**\n * Check if a given file path is a directory or not.\n * Returns `true` if the path is a directory.\n */\nfunction isDirectory(\n /** The path to a file to check. */\n filePath: string\n): Promise<boolean> {\n return fs\n .stat(filePath)\n .then((stat) => stat.isDirectory())\n .catch((error) => {\n if (\n isError(error) &&\n (error.code === 'ENOENT' || error.code === 'ENOTDIR')\n ) {\n return false\n }\n throw error\n })\n}\n/**\n * Create a file with eslint output data\n */\nexport async function writeOutputFile(\n /** The name file that needs to be created */\n outputFile: string,\n /** The data that needs to be inserted into the file */\n outputData: string\n): Promise<void> {\n const filePath = path.resolve(process.cwd(), outputFile)\n\n if (await isDirectory(filePath)) {\n Log.error(\n `Cannot write to output file path, it is a directory: ${filePath}`\n )\n } else {\n try {\n await fs.mkdir(path.dirname(filePath), { recursive: true })\n await fs.writeFile(filePath, outputData)\n Log.info(`The output file has been created: ${filePath}`)\n } catch (err) {\n Log.error(`There was a problem writing the output file: ${filePath}`)\n console.error(err)\n }\n }\n}\n"],"names":["writeOutputFile","isDirectory","filePath","fs","stat","then","catch","error","isError","code","outputFile","outputData","path","resolve","process","cwd","Log","mkdir","dirname","recursive","writeFile","info","err","console"],"mappings":";;;;+BA6BsBA;;;eAAAA;;;oBA7BS;6DACd;6DACI;gEACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB;;;CAGC,GACD,SAASC,YACP,kCAAkC,GAClCC,QAAgB;IAEhB,OAAOC,YAAE,CACNC,IAAI,CAACF,UACLG,IAAI,CAAC,CAACD,OAASA,KAAKH,WAAW,IAC/BK,KAAK,CAAC,CAACC;QACN,IACEC,IAAAA,gBAAO,EAACD,UACPA,CAAAA,MAAME,IAAI,KAAK,YAAYF,MAAME,IAAI,KAAK,SAAQ,GACnD;YACA,OAAO;QACT;QACA,MAAMF;IACR;AACJ;AAIO,eAAeP,gBACpB,2CAA2C,GAC3CU,UAAkB,EAClB,qDAAqD,GACrDC,UAAkB;IAElB,MAAMT,WAAWU,aAAI,CAACC,OAAO,CAACC,QAAQC,GAAG,IAAIL;IAE7C,IAAI,MAAMT,YAAYC,WAAW;QAC/Bc,KAAIT,KAAK,CACP,CAAC,qDAAqD,EAAEL,UAAU;IAEtE,OAAO;QACL,IAAI;YACF,MAAMC,YAAE,CAACc,KAAK,CAACL,aAAI,CAACM,OAAO,CAAChB,WAAW;gBAAEiB,WAAW;YAAK;YACzD,MAAMhB,YAAE,CAACiB,SAAS,CAAClB,UAAUS;YAC7BK,KAAIK,IAAI,CAAC,CAAC,kCAAkC,EAAEnB,UAAU;QAC1D,EAAE,OAAOoB,KAAK;YACZN,KAAIT,KAAK,CAAC,CAAC,6CAA6C,EAAEL,UAAU;YACpEqB,QAAQhB,KAAK,CAACe;QAChB;IACF;AACF"}