Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

eslint-plugin-n

Package Overview
Dependencies
Maintainers
2
Versions
65
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

eslint-plugin-n - npm Package Compare versions

Comparing version 15.7.0 to 16.6.1

configs/recommended-module.js

55

lib/configs/_commons.js
"use strict"
module.exports = {
commonGlobals: {
// ECMAScript
ArrayBuffer: "readonly",
Atomics: "readonly",
BigInt: "readonly",
BigInt64Array: "readonly",
BigUint64Array: "readonly",
DataView: "readonly",
Float32Array: "readonly",
Float64Array: "readonly",
Int16Array: "readonly",
Int32Array: "readonly",
Int8Array: "readonly",
Map: "readonly",
Promise: "readonly",
Proxy: "readonly",
Reflect: "readonly",
Set: "readonly",
SharedArrayBuffer: "readonly",
Symbol: "readonly",
Uint16Array: "readonly",
Uint32Array: "readonly",
Uint8Array: "readonly",
Uint8ClampedArray: "readonly",
WeakMap: "readonly",
WeakSet: "readonly",
// ECMAScript (experimental)
globalThis: "readonly",
// ECMA-402
Intl: "readonly",
// Web Standard
TextDecoder: "readonly",
TextEncoder: "readonly",
URL: "readonly",
URLSearchParams: "readonly",
WebAssembly: "readonly",
clearInterval: "readonly",
clearTimeout: "readonly",
console: "readonly",
queueMicrotask: "readonly",
setInterval: "readonly",
setTimeout: "readonly",
// Node.js
Buffer: "readonly",
GLOBAL: "readonly",
clearImmediate: "readonly",
global: "readonly",
process: "readonly",
root: "readonly",
setImmediate: "readonly",
},
commonRules: {

@@ -60,0 +5,0 @@ "n/no-deprecated-api": "error",

26

lib/configs/recommended-module.js
"use strict"
const { commonGlobals, commonRules } = require("./_commons")
const globals = require("globals")
const { commonRules } = require("./_commons")
module.exports = {
// eslintrc config: https://eslint.org/docs/latest/use/configure/configuration-files
module.exports.eslintrc = {
env: {
node: true,
},
globals: {
...commonGlobals,
...globals.es2021,
__dirname: "off",

@@ -16,6 +21,5 @@ __filename: "off",

ecmaFeatures: { globalReturn: false },
ecmaVersion: 2019,
ecmaVersion: 2021,
sourceType: "module",
},
plugins: ["n"],
rules: {

@@ -29,1 +33,13 @@ ...commonRules,

}
// flat config: https://eslint.org/docs/latest/use/configure/configuration-files-new
module.exports.flat = {
languageOptions: {
sourceType: "module",
globals: {
...globals.node,
...module.exports.eslintrc.globals,
},
},
rules: module.exports.eslintrc.rules,
}
"use strict"
const { commonGlobals, commonRules } = require("./_commons")
const globals = require("globals")
const { commonRules } = require("./_commons")
module.exports = {
// eslintrc config: https://eslint.org/docs/latest/use/configure/configuration-files
module.exports.eslintrc = {
env: {
node: true,
},
globals: {
...commonGlobals,
...globals.es2021,
__dirname: "readonly",

@@ -16,6 +21,5 @@ __filename: "readonly",

ecmaFeatures: { globalReturn: true },
ecmaVersion: 2019,
ecmaVersion: 2021,
sourceType: "script",
},
plugins: ["n"],
rules: {

@@ -26,1 +30,13 @@ ...commonRules,

}
// https://eslint.org/docs/latest/use/configure/configuration-files-new
module.exports.flat = {
languageOptions: {
sourceType: "commonjs",
globals: {
...globals.node,
...module.exports.eslintrc.globals,
},
},
rules: module.exports.eslintrc.rules,
}

@@ -7,13 +7,14 @@ "use strict"

module.exports = () => {
const packageJson = getPackageJson()
const isModule = (packageJson && packageJson.type) === "module"
const packageJson = getPackageJson()
const isModule = (packageJson && packageJson.type) === "module"
const recommendedConfig = isModule ? moduleConfig : scriptConfig
return {
...(isModule ? moduleConfig : scriptConfig),
overrides: [
{ files: ["*.cjs", ".*.cjs"], ...scriptConfig },
{ files: ["*.mjs", ".*.mjs"], ...moduleConfig },
],
}
module.exports.eslintrc = {
...recommendedConfig.eslintrc,
overrides: [
{ files: ["*.cjs", ".*.cjs"], ...scriptConfig.eslintrc },
{ files: ["*.mjs", ".*.mjs"], ...moduleConfig.eslintrc },
],
}
module.exports.flat = recommendedConfig.flat

@@ -7,3 +7,2 @@ var __create = Object.create;

var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {

@@ -13,18 +12,19 @@ for (var name in all)

};
var __reExport = (target, module2, copyDefault, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return target;
return to;
};
var __toESM = (module2, isNodeMode) => {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
var __toCommonJS = /* @__PURE__ */ ((cache) => {
return (module2, temp) => {
return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
};
})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

@@ -35,89 +35,174 @@ // node_modules/import-meta-resolve/lib/resolve.js

defaultResolve: () => defaultResolve,
getPackageType: () => getPackageType,
moduleResolve: () => moduleResolve
});
var import_url2 = require("url");
var import_fs2 = require("fs");
var import_path3 = __toESM(require("path"), 1);
var import_builtins = __toESM(require("builtins"), 1);
module.exports = __toCommonJS(resolve_exports);
var import_node_assert2 = __toESM(require("node:assert"), 1);
var import_node_fs2 = require("node:fs");
var import_node_process2 = __toESM(require("node:process"), 1);
var import_node_url3 = require("node:url");
var import_node_path3 = __toESM(require("node:path"), 1);
var import_node_module = require("node:module");
// node_modules/import-meta-resolve/lib/package-json-reader.js
var import_fs = __toESM(require("fs"), 1);
var import_path = __toESM(require("path"), 1);
var reader = { read };
var package_json_reader_default = reader;
function read(jsonPath) {
return find(import_path.default.dirname(jsonPath));
}
function find(dir) {
try {
const string = import_fs.default.readFileSync(import_path.default.toNamespacedPath(import_path.default.join(dir, "package.json")), "utf8");
return { string };
} catch (error) {
if (error.code === "ENOENT") {
const parent = import_path.default.dirname(dir);
if (dir !== parent)
return find(parent);
return { string: void 0 };
}
throw error;
}
}
// node_modules/import-meta-resolve/lib/get-format.js
var import_path2 = __toESM(require("path"), 1);
var import_url = require("url");
var import_node_path2 = __toESM(require("node:path"), 1);
var import_node_url2 = require("node:url");
// node_modules/import-meta-resolve/lib/package-config.js
var import_node_url = require("node:url");
// node_modules/import-meta-resolve/lib/errors.js
var import_assert = __toESM(require("assert"), 1);
var import_util = require("util");
var isWindows = process.platform === "win32";
var import_node_v8 = __toESM(require("node:v8"), 1);
var import_node_process = __toESM(require("node:process"), 1);
var import_node_assert = __toESM(require("node:assert"), 1);
var import_node_util = require("node:util");
var isWindows = import_node_process.default.platform === "win32";
var own = {}.hasOwnProperty;
var codes = {};
function formatList(array, type = "and") {
return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
}
var messages = /* @__PURE__ */ new Map();
var nodeInternalPrefix = "__node_internal_";
var userStackTraceLimit;
codes.ERR_INVALID_MODULE_SPECIFIER = createError("ERR_INVALID_MODULE_SPECIFIER", (request, reason, base = void 0) => {
return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
}, TypeError);
codes.ERR_INVALID_PACKAGE_CONFIG = createError("ERR_INVALID_PACKAGE_CONFIG", (path4, base, message) => {
return `Invalid package config ${path4}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
}, Error);
codes.ERR_INVALID_PACKAGE_TARGET = createError("ERR_INVALID_PACKAGE_TARGET", (pkgPath, key, target, isImport = false, base = void 0) => {
const relError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
if (key === ".") {
(0, import_assert.default)(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`;
}
return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`;
}, Error);
codes.ERR_MODULE_NOT_FOUND = createError("ERR_MODULE_NOT_FOUND", (path4, base, type = "package") => {
return `Cannot find ${type} '${path4}' imported from ${base}`;
}, Error);
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError("ERR_PACKAGE_IMPORT_NOT_DEFINED", (specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
}, TypeError);
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError("ERR_PACKAGE_PATH_NOT_EXPORTED", (pkgPath, subpath, base = void 0) => {
if (subpath === ".")
return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`;
return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`;
}, Error);
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
codes.ERR_UNKNOWN_FILE_EXTENSION = createError("ERR_UNKNOWN_FILE_EXTENSION", 'Unknown file extension "%s" for %s', TypeError);
codes.ERR_INVALID_ARG_VALUE = createError("ERR_INVALID_ARG_VALUE", (name, value, reason = "is invalid") => {
let inspected = (0, import_util.inspect)(value);
if (inspected.length > 128) {
inspected = `${inspected.slice(0, 128)}...`;
}
const type = name.includes(".") ? "property" : "argument";
return `The ${type} '${name}' ${reason}. Received ${inspected}`;
}, TypeError);
codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError("ERR_UNSUPPORTED_ESM_URL_SCHEME", (url) => {
let message = "Only file and data URLs are supported by the default ESM loader";
if (isWindows && url.protocol.length === 2) {
message += ". On Windows, absolute paths must be valid file:// URLs";
}
message += `. Received protocol '${url.protocol}'`;
return message;
}, Error);
codes.ERR_INVALID_MODULE_SPECIFIER = createError(
"ERR_INVALID_MODULE_SPECIFIER",
/**
* @param {string} request
* @param {string} reason
* @param {string} [base]
*/
(request, reason, base = void 0) => {
return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
},
TypeError
);
codes.ERR_INVALID_PACKAGE_CONFIG = createError(
"ERR_INVALID_PACKAGE_CONFIG",
/**
* @param {string} path
* @param {string} [base]
* @param {string} [message]
*/
(path4, base, message) => {
return `Invalid package config ${path4}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
},
Error
);
codes.ERR_INVALID_PACKAGE_TARGET = createError(
"ERR_INVALID_PACKAGE_TARGET",
/**
* @param {string} pkgPath
* @param {string} key
* @param {unknown} target
* @param {boolean} [isImport=false]
* @param {string} [base]
*/
(pkgPath, key, target, isImport = false, base = void 0) => {
const relError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
if (key === ".") {
(0, import_node_assert.default)(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`;
}
return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
target
)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ""}${relError ? '; targets must start with "./"' : ""}`;
},
Error
);
codes.ERR_MODULE_NOT_FOUND = createError(
"ERR_MODULE_NOT_FOUND",
/**
* @param {string} path
* @param {string} base
* @param {string} [type]
*/
(path4, base, type = "package") => {
return `Cannot find ${type} '${path4}' imported from ${base}`;
},
Error
);
codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
"ERR_NETWORK_IMPORT_DISALLOWED",
"import of '%s' by %s is not supported: %s",
Error
);
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
/**
* @param {string} specifier
* @param {string} packagePath
* @param {string} base
*/
(specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
},
TypeError
);
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
"ERR_PACKAGE_PATH_NOT_EXPORTED",
/**
* @param {string} pkgPath
* @param {string} subpath
* @param {string} [base]
*/
(pkgPath, subpath, base = void 0) => {
if (subpath === ".")
return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`;
return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ""}`;
},
Error
);
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
"ERR_UNSUPPORTED_DIR_IMPORT",
"Directory import '%s' is not supported resolving ES modules imported from %s",
Error
);
codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
"ERR_UNKNOWN_FILE_EXTENSION",
/**
* @param {string} ext
* @param {string} path
*/
(ext, path4) => {
return `Unknown file extension "${ext}" for ${path4}`;
},
TypeError
);
codes.ERR_INVALID_ARG_VALUE = createError(
"ERR_INVALID_ARG_VALUE",
/**
* @param {string} name
* @param {unknown} value
* @param {string} [reason='is invalid']
*/
(name, value, reason = "is invalid") => {
let inspected = (0, import_node_util.inspect)(value);
if (inspected.length > 128) {
inspected = `${inspected.slice(0, 128)}...`;
}
const type = name.includes(".") ? "property" : "argument";
return `The ${type} '${name}' ${reason}. Received ${inspected}`;
},
TypeError
// Note: extra classes have been shaken out.
// , RangeError
);
codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError(
"ERR_UNSUPPORTED_ESM_URL_SCHEME",
/**
* @param {URL} url
* @param {Array<string>} supported
*/
(url, supported) => {
let message = `Only URLs with a scheme in: ${formatList(
supported
)} are supported by the default ESM loader`;
if (isWindows && url.protocol.length === 2) {
message += ". On Windows, absolute paths must be valid file:// URLs";
}
message += `. Received protocol '${url.protocol}'`;
return message;
},
Error
);
function createError(sym, value, def) {

@@ -137,17 +222,22 @@ messages.set(sym, value);

const message = getMessage(key, args, error);
Object.defineProperty(error, "message", {
value: message,
enumerable: false,
writable: true,
configurable: true
});
Object.defineProperty(error, "toString", {
value() {
return `${this.name} [${key}]: ${this.message}`;
Object.defineProperties(error, {
// Note: no need to implement `kIsNodeError` symbol, would be hard,
// probably.
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
enumerable: false,
writable: true,
configurable: true
toString: {
/** @this {Error} */
value() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
writable: true,
configurable: true
}
});
addCodeToName(error, Base.name, key);
captureLargerStackTrace(error);
error.code = key;

@@ -157,18 +247,9 @@ return error;

}
var addCodeToName = hideStackFrames(function(error, name, code) {
error = captureLargerStackTrace(error);
error.name = `${name} [${code}]`;
error.stack;
if (name === "SystemError") {
Object.defineProperty(error, "name", {
value: name,
enumerable: false,
writable: true,
configurable: true
});
} else {
delete error.name;
function isErrorStackTraceLimitWritable() {
try {
if (import_node_v8.default.startupSnapshot.isBuildingSnapshot()) {
return false;
}
} catch {
}
});
function isErrorStackTraceLimitWritable() {
const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");

@@ -178,3 +259,3 @@ if (desc === void 0) {

}
return own.call(desc, "writable") ? desc.writable : desc.set !== void 0;
return own.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
}

@@ -186,120 +267,72 @@ function hideStackFrames(fn) {

}
var captureLargerStackTrace = hideStackFrames(function(error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
var captureLargerStackTrace = hideStackFrames(
/**
* @param {Error} error
* @returns {Error}
*/
// @ts-expect-error: fine
function(error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
}
Error.captureStackTrace(error);
if (stackTraceLimitIsWritable)
Error.stackTraceLimit = userStackTraceLimit;
return error;
}
Error.captureStackTrace(error);
if (stackTraceLimitIsWritable)
Error.stackTraceLimit = userStackTraceLimit;
return error;
});
);
function getMessage(key, args, self) {
const message = messages.get(key);
(0, import_node_assert.default)(typeof message !== "undefined", "expected `message` to be found");
if (typeof message === "function") {
(0, import_assert.default)(message.length <= args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${message.length}).`);
(0, import_node_assert.default)(
message.length <= args.length,
// Default options do not count.
`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${message.length}).`
);
return Reflect.apply(message, self, args);
}
const expectedLength = (message.match(/%[dfijoOs]/g) || []).length;
(0, import_assert.default)(expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`);
const regex = /%[dfijoOs]/g;
let expectedLength = 0;
while (regex.exec(message) !== null)
expectedLength++;
(0, import_node_assert.default)(
expectedLength === args.length,
`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`
);
if (args.length === 0)
return message;
args.unshift(message);
return Reflect.apply(import_util.format, null, args);
return Reflect.apply(import_node_util.format, null, args);
}
// node_modules/import-meta-resolve/lib/get-format.js
var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
var extensionFormatMap = {
__proto__: null,
".cjs": "commonjs",
".js": "module",
".mjs": "module"
};
function defaultGetFormat(url) {
if (url.startsWith("node:")) {
return { format: "builtin" };
}
const parsed = new import_url.URL(url);
if (parsed.protocol === "data:") {
const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [null, null];
const format2 = mime === "text/javascript" ? "module" : null;
return { format: format2 };
}
if (parsed.protocol === "file:") {
const ext = import_path2.default.extname(parsed.pathname);
let format2;
if (ext === ".js") {
format2 = getPackageType(parsed.href) === "module" ? "module" : "commonjs";
} else {
format2 = extensionFormatMap[ext];
// node_modules/import-meta-resolve/lib/package-json-reader.js
var import_node_fs = __toESM(require("node:fs"), 1);
var import_node_path = __toESM(require("node:path"), 1);
var reader = { read };
var package_json_reader_default = reader;
function read(jsonPath) {
try {
const string = import_node_fs.default.readFileSync(
import_node_path.default.toNamespacedPath(import_node_path.default.join(import_node_path.default.dirname(jsonPath), "package.json")),
"utf8"
);
return { string };
} catch (error) {
const exception = (
/** @type {ErrnoException} */
error
);
if (exception.code === "ENOENT") {
return { string: void 0 };
}
if (!format2) {
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, (0, import_url.fileURLToPath)(url));
}
return { format: format2 || null };
throw exception;
}
return { format: null };
}
// node_modules/import-meta-resolve/lib/resolve.js
var listOfBuiltins = (0, import_builtins.default)();
var {
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_PACKAGE_CONFIG,
ERR_INVALID_PACKAGE_TARGET,
ERR_MODULE_NOT_FOUND,
ERR_PACKAGE_IMPORT_NOT_DEFINED,
ERR_PACKAGE_PATH_NOT_EXPORTED,
ERR_UNSUPPORTED_DIR_IMPORT,
ERR_UNSUPPORTED_ESM_URL_SCHEME,
ERR_INVALID_ARG_VALUE
} = codes;
var own2 = {}.hasOwnProperty;
var DEFAULT_CONDITIONS = Object.freeze(["node", "import"]);
var DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);
var invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
var patternRegEx = /\*/g;
var encodedSepRegEx = /%2f|%2c/i;
var emittedPackageWarnings = /* @__PURE__ */ new Set();
// node_modules/import-meta-resolve/lib/package-config.js
var { ERR_INVALID_PACKAGE_CONFIG } = codes;
var packageJsonCache = /* @__PURE__ */ new Map();
function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {
const pjsonPath = (0, import_url2.fileURLToPath)(pjsonUrl);
if (emittedPackageWarnings.has(pjsonPath + "|" + match))
return;
emittedPackageWarnings.add(pjsonPath + "|" + match);
process.emitWarning(`Use of deprecated folder mapping "${match}" in the ${isExports ? '"exports"' : '"imports"'} field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_url2.fileURLToPath)(base)}` : ""}.
Update this package.json to use a subpath pattern like "${match}*".`, "DeprecationWarning", "DEP0148");
}
function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
const { format: format2 } = defaultGetFormat(url.href);
if (format2 !== "module")
return;
const path4 = (0, import_url2.fileURLToPath)(url.href);
const pkgPath = (0, import_url2.fileURLToPath)(new import_url2.URL(".", packageJsonUrl));
const basePath = (0, import_url2.fileURLToPath)(base);
if (main)
process.emitWarning(`Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, excluding the full filename and extension to the resolved file at "${path4.slice(pkgPath.length)}", imported from ${basePath}.
Automatic extension resolution of the "main" field isdeprecated for ES modules.`, "DeprecationWarning", "DEP0151");
else
process.emitWarning(`No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path4.slice(pkgPath.length)}", imported from ${basePath}.
Default "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
}
function getConditionsSet(conditions) {
if (conditions !== void 0 && conditions !== DEFAULT_CONDITIONS) {
if (!Array.isArray(conditions)) {
throw new ERR_INVALID_ARG_VALUE("conditions", conditions, "expected an array");
}
return new Set(conditions);
}
return DEFAULT_CONDITIONS_SET;
}
function tryStatSync(path4) {
try {
return (0, import_fs2.statSync)(path4);
} catch {
return new import_fs2.Stats();
}
}
function getPackageConfig(path4, specifier, base) {

@@ -328,3 +361,11 @@ const existing = packageJsonCache.get(path4);

} catch (error) {
throw new ERR_INVALID_PACKAGE_CONFIG(path4, (base ? `"${specifier}" from ` : "") + (0, import_url2.fileURLToPath)(base || specifier), error.message);
const exception = (
/** @type {ErrnoException} */
error
);
throw new ERR_INVALID_PACKAGE_CONFIG(
path4,
(base ? `"${specifier}" from ` : "") + (0, import_node_url.fileURLToPath)(base || specifier),
exception.message
);
}

@@ -338,3 +379,5 @@ const { exports, imports, main, name, type } = packageJson;

type: type === "module" || type === "commonjs" ? type : "none",
// @ts-expect-error Assume `Record<string, unknown>`.
exports,
// @ts-expect-error Assume `Record<string, unknown>`.
imports: imports && typeof imports === "object" ? imports : void 0

@@ -346,3 +389,3 @@ };

function getPackageScopeConfig(resolved) {
let packageJsonUrl = new import_url2.URL("./package.json", resolved);
let packageJsonUrl = new import_node_url.URL("package.json", resolved);
while (true) {

@@ -352,11 +395,14 @@ const packageJsonPath2 = packageJsonUrl.pathname;

break;
const packageConfig2 = getPackageConfig((0, import_url2.fileURLToPath)(packageJsonUrl), resolved);
const packageConfig2 = getPackageConfig(
(0, import_node_url.fileURLToPath)(packageJsonUrl),
resolved
);
if (packageConfig2.exists)
return packageConfig2;
const lastPackageJsonUrl = packageJsonUrl;
packageJsonUrl = new import_url2.URL("../package.json", packageJsonUrl);
packageJsonUrl = new import_node_url.URL("../package.json", packageJsonUrl);
if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname)
break;
}
const packageJsonPath = (0, import_url2.fileURLToPath)(packageJsonUrl);
const packageJsonPath = (0, import_node_url.fileURLToPath)(packageJsonUrl);
const packageConfig = {

@@ -374,4 +420,159 @@ pjsonPath: packageJsonPath,

}
// node_modules/import-meta-resolve/lib/resolve-get-package-type.js
function getPackageType(url) {
const packageConfig = getPackageScopeConfig(url);
return packageConfig.type;
}
// node_modules/import-meta-resolve/lib/get-format.js
var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
var hasOwnProperty = {}.hasOwnProperty;
var extensionFormatMap = {
// @ts-expect-error: hush.
__proto__: null,
".cjs": "commonjs",
".js": "module",
".json": "json",
".mjs": "module"
};
function mimeToFormat(mime) {
if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
return "module";
if (mime === "application/json")
return "json";
return null;
}
var protocolHandlers = {
// @ts-expect-error: hush.
__proto__: null,
"data:": getDataProtocolModuleFormat,
"file:": getFileProtocolModuleFormat,
"http:": getHttpProtocolModuleFormat,
"https:": getHttpProtocolModuleFormat,
"node:"() {
return "builtin";
}
};
function getDataProtocolModuleFormat(parsed) {
const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
parsed.pathname
) || [null, null, null];
return mimeToFormat(mime);
}
function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
const filepath = (0, import_node_url2.fileURLToPath)(url);
const ext = import_node_path2.default.extname(filepath);
if (ext === ".js") {
return getPackageType(url) === "module" ? "module" : "commonjs";
}
const format2 = extensionFormatMap[ext];
if (format2)
return format2;
if (ignoreErrors) {
return void 0;
}
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, filepath);
}
function getHttpProtocolModuleFormat() {
}
function defaultGetFormatWithoutErrors(url, context) {
if (!hasOwnProperty.call(protocolHandlers, url.protocol)) {
return null;
}
return protocolHandlers[url.protocol](url, context, true) || null;
}
// node_modules/import-meta-resolve/lib/utils.js
var { ERR_INVALID_ARG_VALUE } = codes;
var DEFAULT_CONDITIONS = Object.freeze(["node", "import"]);
var DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);
function getDefaultConditions() {
return DEFAULT_CONDITIONS;
}
function getDefaultConditionsSet() {
return DEFAULT_CONDITIONS_SET;
}
function getConditionsSet(conditions) {
if (conditions !== void 0 && conditions !== getDefaultConditions()) {
if (!Array.isArray(conditions)) {
throw new ERR_INVALID_ARG_VALUE(
"conditions",
conditions,
"expected an array"
);
}
return new Set(conditions);
}
return getDefaultConditionsSet();
}
// node_modules/import-meta-resolve/lib/resolve.js
var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
var experimentalNetworkImports = false;
var {
ERR_NETWORK_IMPORT_DISALLOWED,
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG2,
ERR_INVALID_PACKAGE_TARGET,
ERR_MODULE_NOT_FOUND,
ERR_PACKAGE_IMPORT_NOT_DEFINED,
ERR_PACKAGE_PATH_NOT_EXPORTED,
ERR_UNSUPPORTED_DIR_IMPORT,
ERR_UNSUPPORTED_ESM_URL_SCHEME
} = codes;
var own2 = {}.hasOwnProperty;
var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
var invalidPackageNameRegEx = /^\.|%|\\/;
var patternRegEx = /\*/g;
var encodedSepRegEx = /%2f|%5c/i;
var emittedPackageWarnings = /* @__PURE__ */ new Set();
var doubleSlashRegEx = /[/\\]{2}/;
function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
const pjsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl);
const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
import_node_process2.default.emitWarning(
`Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_node_url3.fileURLToPath)(base)}` : ""}.`,
"DeprecationWarning",
"DEP0166"
);
}
function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
const format2 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
if (format2 !== "module")
return;
const path4 = (0, import_node_url3.fileURLToPath)(url.href);
const pkgPath = (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl));
const basePath = (0, import_node_url3.fileURLToPath)(base);
if (main)
import_node_process2.default.emitWarning(
`Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, excluding the full filename and extension to the resolved file at "${path4.slice(
pkgPath.length
)}", imported from ${basePath}.
Automatic extension resolution of the "main" field isdeprecated for ES modules.`,
"DeprecationWarning",
"DEP0151"
);
else
import_node_process2.default.emitWarning(
`No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path4.slice(
pkgPath.length
)}", imported from ${basePath}.
Default "index" lookups for the main are deprecated for ES modules.`,
"DeprecationWarning",
"DEP0151"
);
}
function tryStatSync(path4) {
try {
return (0, import_node_fs2.statSync)(path4);
} catch {
return new import_node_fs2.Stats();
}
}
function fileExists(url) {
return tryStatSync((0, import_url2.fileURLToPath)(url)).isFile();
const stats = (0, import_node_fs2.statSync)(url, { throwIfNoEntry: false });
const isFile = stats ? stats.isFile() : void 0;
return isFile === null || isFile === void 0 ? false : isFile;
}

@@ -381,3 +582,3 @@ function legacyMainResolve(packageJsonUrl, packageConfig, base) {

if (packageConfig.main !== void 0) {
guess = new import_url2.URL(`./${packageConfig.main}`, packageJsonUrl);
guess = new import_node_url3.URL(packageConfig.main, packageJsonUrl);
if (fileExists(guess))

@@ -395,3 +596,3 @@ return guess;

while (++i2 < tries2.length) {
guess = new import_url2.URL(tries2[i2], packageJsonUrl);
guess = new import_node_url3.URL(tries2[i2], packageJsonUrl);
if (fileExists(guess))

@@ -402,3 +603,8 @@ break;

if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
emitLegacyIndexDeprecation(
guess,
packageJsonUrl,
base,
packageConfig.main
);
return guess;

@@ -410,3 +616,3 @@ }

while (++i < tries.length) {
guess = new import_url2.URL(tries[i], packageJsonUrl);
guess = new import_node_url3.URL(tries[i], packageJsonUrl);
if (fileExists(guess))

@@ -420,11 +626,20 @@ break;

}
throw new ERR_MODULE_NOT_FOUND((0, import_url2.fileURLToPath)(new import_url2.URL(".", packageJsonUrl)), (0, import_url2.fileURLToPath)(base));
throw new ERR_MODULE_NOT_FOUND(
(0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)),
(0, import_node_url3.fileURLToPath)(base)
);
}
function finalizeResolution(resolved, base) {
if (encodedSepRegEx.test(resolved.pathname))
throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, 'must not include encoded "/" or "\\" characters', (0, import_url2.fileURLToPath)(base));
const path4 = (0, import_url2.fileURLToPath)(resolved);
const stats = tryStatSync(path4.endsWith("/") ? path4.slice(-1) : path4);
function finalizeResolution(resolved, base, preserveSymlinks) {
if (encodedSepRegEx.exec(resolved.pathname) !== null)
throw new ERR_INVALID_MODULE_SPECIFIER(
resolved.pathname,
'must not include encoded "/" or "\\" characters',
(0, import_node_url3.fileURLToPath)(base)
);
const filePath = (0, import_node_url3.fileURLToPath)(resolved);
const stats = tryStatSync(
filePath.endsWith("/") ? filePath.slice(-1) : filePath
);
if (stats.isDirectory()) {
const error = new ERR_UNSUPPORTED_DIR_IMPORT(path4, (0, import_url2.fileURLToPath)(base));
const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, (0, import_node_url3.fileURLToPath)(base));
error.url = String(resolved);

@@ -434,23 +649,52 @@ throw error;

if (!stats.isFile()) {
throw new ERR_MODULE_NOT_FOUND(path4 || resolved.pathname, base && (0, import_url2.fileURLToPath)(base), "module");
throw new ERR_MODULE_NOT_FOUND(
filePath || resolved.pathname,
base && (0, import_node_url3.fileURLToPath)(base),
"module"
);
}
if (!preserveSymlinks) {
const real = (0, import_node_fs2.realpathSync)(filePath);
const { search, hash } = resolved;
resolved = (0, import_node_url3.pathToFileURL)(real + (filePath.endsWith(import_node_path3.default.sep) ? "/" : ""));
resolved.search = search;
resolved.hash = hash;
}
return resolved;
}
function throwImportNotDefined(specifier, packageJsonUrl, base) {
throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && (0, import_url2.fileURLToPath)(new import_url2.URL(".", packageJsonUrl)), (0, import_url2.fileURLToPath)(base));
function importNotDefined(specifier, packageJsonUrl, base) {
return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
specifier,
packageJsonUrl && (0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)),
(0, import_node_url3.fileURLToPath)(base)
);
}
function throwExportsNotFound(subpath, packageJsonUrl, base) {
throw new ERR_PACKAGE_PATH_NOT_EXPORTED((0, import_url2.fileURLToPath)(new import_url2.URL(".", packageJsonUrl)), subpath, base && (0, import_url2.fileURLToPath)(base));
function exportsNotFound(subpath, packageJsonUrl, base) {
return new ERR_PACKAGE_PATH_NOT_EXPORTED(
(0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)),
subpath,
base && (0, import_node_url3.fileURLToPath)(base)
);
}
function throwInvalidSubpath(subpath, packageJsonUrl, internal, base) {
const reason = `request is not a valid subpath for the "${internal ? "imports" : "exports"}" resolution of ${(0, import_url2.fileURLToPath)(packageJsonUrl)}`;
throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason, base && (0, import_url2.fileURLToPath)(base));
function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${(0, import_node_url3.fileURLToPath)(packageJsonUrl)}`;
throw new ERR_INVALID_MODULE_SPECIFIER(
request,
reason,
base && (0, import_node_url3.fileURLToPath)(base)
);
}
function throwInvalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
throw new ERR_INVALID_PACKAGE_TARGET((0, import_url2.fileURLToPath)(new import_url2.URL(".", packageJsonUrl)), subpath, target, internal, base && (0, import_url2.fileURLToPath)(base));
return new ERR_INVALID_PACKAGE_TARGET(
(0, import_node_url3.fileURLToPath)(new import_node_url3.URL(".", packageJsonUrl)),
subpath,
target,
internal,
base && (0, import_node_url3.fileURLToPath)(base)
);
}
function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, conditions) {
function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
if (!target.startsWith("./")) {

@@ -460,3 +704,3 @@ if (internal && !target.startsWith("../") && !target.startsWith("/")) {

try {
new import_url2.URL(target);
new import_node_url3.URL(target);
isURL = true;

@@ -466,22 +710,75 @@ } catch {

if (!isURL) {
const exportTarget = pattern ? target.replace(patternRegEx, subpath) : target + subpath;
const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
patternRegEx,
target,
() => subpath
) : target + subpath;
return packageResolve(exportTarget, packageJsonUrl, conditions);
}
}
throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
}
if (invalidSegmentRegEx.test(target.slice(2)))
throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
const resolved = new import_url2.URL(target, packageJsonUrl);
if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
if (!isPathMap) {
const request = pattern ? match.replace("*", () => subpath) : match + subpath;
const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
patternRegEx,
target,
() => subpath
) : target;
emitInvalidSegmentDeprecation(
resolvedTarget,
request,
match,
packageJsonUrl,
internal,
base,
true
);
}
} else {
throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
}
}
const resolved = new import_node_url3.URL(target, packageJsonUrl);
const resolvedPath = resolved.pathname;
const packagePath = new import_url2.URL(".", packageJsonUrl).pathname;
const packagePath = new import_node_url3.URL(".", packageJsonUrl).pathname;
if (!resolvedPath.startsWith(packagePath))
throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
if (subpath === "")
return resolved;
if (invalidSegmentRegEx.test(subpath))
throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base);
if (pattern)
return new import_url2.URL(resolved.href.replace(patternRegEx, subpath));
return new import_url2.URL(subpath, resolved);
if (invalidSegmentRegEx.exec(subpath) !== null) {
const request = pattern ? match.replace("*", () => subpath) : match + subpath;
if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
if (!isPathMap) {
const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
patternRegEx,
target,
() => subpath
) : target;
emitInvalidSegmentDeprecation(
resolvedTarget,
request,
match,
packageJsonUrl,
internal,
base,
false
);
}
} else {
throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
}
}
if (pattern) {
return new import_node_url3.URL(
RegExpPrototypeSymbolReplace.call(
patternRegEx,
resolved.href,
() => subpath
)
);
}
return new import_node_url3.URL(subpath, resolved);
}

@@ -494,5 +791,15 @@ function isArrayIndex(key) {

}
function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) {
function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
if (typeof target === "string") {
return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, conditions);
return resolvePackageTargetString(
target,
subpath,
packageSubpath,
packageJsonUrl,
base,
pattern,
internal,
isPathMap,
conditions
);
}

@@ -507,21 +814,35 @@ if (Array.isArray(target)) {

const targetItem = targetList[i];
let resolved;
let resolveResult;
try {
resolved = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, conditions);
resolveResult = resolvePackageTarget(
packageJsonUrl,
targetItem,
subpath,
packageSubpath,
base,
pattern,
internal,
isPathMap,
conditions
);
} catch (error) {
lastException = error;
if (error.code === "ERR_INVALID_PACKAGE_TARGET")
const exception = (
/** @type {ErrnoException} */
error
);
lastException = exception;
if (exception.code === "ERR_INVALID_PACKAGE_TARGET")
continue;
throw error;
}
if (resolved === void 0)
if (resolveResult === void 0)
continue;
if (resolved === null) {
if (resolveResult === null) {
lastException = null;
continue;
}
return resolved;
return resolveResult;
}
if (lastException === void 0 || lastException === null) {
return lastException;
return null;
}

@@ -536,3 +857,7 @@ throw lastException;

if (isArrayIndex(key)) {
throw new ERR_INVALID_PACKAGE_CONFIG((0, import_url2.fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain numeric property keys.');
throw new ERR_INVALID_PACKAGE_CONFIG2(
(0, import_node_url3.fileURLToPath)(packageJsonUrl),
base,
'"exports" cannot contain numeric property keys.'
);
}

@@ -544,10 +869,23 @@ }

if (key === "default" || conditions && conditions.has(key)) {
const conditionalTarget = target[key];
const resolved = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, conditions);
if (resolved === void 0)
const conditionalTarget = (
/** @type {unknown} */
target[key]
);
const resolveResult = resolvePackageTarget(
packageJsonUrl,
conditionalTarget,
subpath,
packageSubpath,
base,
pattern,
internal,
isPathMap,
conditions
);
if (resolveResult === void 0)
continue;
return resolved;
return resolveResult;
}
}
return void 0;
return null;
}

@@ -557,3 +895,9 @@ if (target === null) {

}
throwInvalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base);
throw invalidPackageTarget(
packageSubpath,
target,
packageJsonUrl,
internal,
base
);
}

@@ -575,3 +919,7 @@ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {

} else if (isConditionalSugar !== curIsConditionalSugar) {
throw new ERR_INVALID_PACKAGE_CONFIG((0, import_url2.fileURLToPath)(packageJsonUrl), base, `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`);
throw new ERR_INVALID_PACKAGE_CONFIG2(
(0, import_node_url3.fileURLToPath)(packageJsonUrl),
base,
`"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
);
}

@@ -581,14 +929,38 @@ }

}
function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
const pjsonPath = (0, import_node_url3.fileURLToPath)(pjsonUrl);
if (emittedPackageWarnings.has(pjsonPath + "|" + match))
return;
emittedPackageWarnings.add(pjsonPath + "|" + match);
import_node_process2.default.emitWarning(
`Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_node_url3.fileURLToPath)(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
"DeprecationWarning",
"DEP0155"
);
}
function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
let exports = packageConfig.exports;
if (isConditionalExportsMainSugar(exports, packageJsonUrl, base))
if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
exports = { ".": exports };
if (own2.call(exports, packageSubpath)) {
}
if (own2.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
const target = exports[packageSubpath];
const resolved = resolvePackageTarget(packageJsonUrl, target, "", packageSubpath, base, false, false, conditions);
if (resolved === null || resolved === void 0)
throwExportsNotFound(packageSubpath, packageJsonUrl, base);
return { resolved, exact: true };
const resolveResult = resolvePackageTarget(
packageJsonUrl,
target,
"",
packageSubpath,
base,
false,
false,
false,
conditions
);
if (resolveResult === null || resolveResult === void 0) {
throw exportsNotFound(packageSubpath, packageJsonUrl, base);
}
return resolveResult;
}
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(exports);

@@ -598,25 +970,67 @@ let i = -1;

const key = keys[i];
if (key[key.length - 1] === "*" && packageSubpath.startsWith(key.slice(0, -1)) && packageSubpath.length >= key.length && key.length > bestMatch.length) {
bestMatch = key;
} else if (key[key.length - 1] === "/" && packageSubpath.startsWith(key) && key.length > bestMatch.length) {
bestMatch = key;
const patternIndex = key.indexOf("*");
if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
if (packageSubpath.endsWith("/")) {
emitTrailingSlashPatternDeprecation(
packageSubpath,
packageJsonUrl,
base
);
}
const patternTrailer = key.slice(patternIndex + 1);
if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
bestMatch = key;
bestMatchSubpath = packageSubpath.slice(
patternIndex,
packageSubpath.length - patternTrailer.length
);
}
}
}
if (bestMatch) {
const target = exports[bestMatch];
const pattern = bestMatch[bestMatch.length - 1] === "*";
const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0));
const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, false, conditions);
if (resolved === null || resolved === void 0)
throwExportsNotFound(packageSubpath, packageJsonUrl, base);
if (!pattern)
emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base);
return { resolved, exact: pattern };
const target = (
/** @type {unknown} */
exports[bestMatch]
);
const resolveResult = resolvePackageTarget(
packageJsonUrl,
target,
bestMatchSubpath,
bestMatch,
base,
true,
false,
packageSubpath.endsWith("/"),
conditions
);
if (resolveResult === null || resolveResult === void 0) {
throw exportsNotFound(packageSubpath, packageJsonUrl, base);
}
return resolveResult;
}
throwExportsNotFound(packageSubpath, packageJsonUrl, base);
throw exportsNotFound(packageSubpath, packageJsonUrl, base);
}
function patternKeyCompare(a, b) {
const aPatternIndex = a.indexOf("*");
const bPatternIndex = b.indexOf("*");
const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
if (baseLengthA > baseLengthB)
return -1;
if (baseLengthB > baseLengthA)
return 1;
if (aPatternIndex === -1)
return 1;
if (bPatternIndex === -1)
return -1;
if (a.length > b.length)
return -1;
if (b.length > a.length)
return 1;
return 0;
}
function packageImportsResolve(name, base, conditions) {
if (name === "#" || name.startsWith("#/")) {
if (name === "#" || name.startsWith("#/") || name.endsWith("/")) {
const reason = "is not a valid internal imports specifier name";
throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, import_url2.fileURLToPath)(base));
throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, import_node_url3.fileURLToPath)(base));
}

@@ -626,11 +1040,23 @@ let packageJsonUrl;

if (packageConfig.exists) {
packageJsonUrl = (0, import_url2.pathToFileURL)(packageConfig.pjsonPath);
packageJsonUrl = (0, import_node_url3.pathToFileURL)(packageConfig.pjsonPath);
const imports = packageConfig.imports;
if (imports) {
if (own2.call(imports, name)) {
const resolved = resolvePackageTarget(packageJsonUrl, imports[name], "", name, base, false, true, conditions);
if (resolved !== null)
return { resolved, exact: true };
if (own2.call(imports, name) && !name.includes("*")) {
const resolveResult = resolvePackageTarget(
packageJsonUrl,
imports[name],
"",
name,
base,
false,
true,
false,
conditions
);
if (resolveResult !== null && resolveResult !== void 0) {
return resolveResult;
}
} else {
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(imports);

@@ -640,6 +1066,12 @@ let i = -1;

const key = keys[i];
if (key[key.length - 1] === "*" && name.startsWith(key.slice(0, -1)) && name.length >= key.length && key.length > bestMatch.length) {
bestMatch = key;
} else if (key[key.length - 1] === "/" && name.startsWith(key) && key.length > bestMatch.length) {
bestMatch = key;
const patternIndex = key.indexOf("*");
if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
const patternTrailer = key.slice(patternIndex + 1);
if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
bestMatch = key;
bestMatchSubpath = name.slice(
patternIndex,
name.length - patternTrailer.length
);
}
}

@@ -649,9 +1081,15 @@ }

const target = imports[bestMatch];
const pattern = bestMatch[bestMatch.length - 1] === "*";
const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0));
const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, true, conditions);
if (resolved !== null) {
if (!pattern)
emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base);
return { resolved, exact: pattern };
const resolveResult = resolvePackageTarget(
packageJsonUrl,
target,
bestMatchSubpath,
bestMatch,
base,
true,
true,
false,
conditions
);
if (resolveResult !== null && resolveResult !== void 0) {
return resolveResult;
}

@@ -662,8 +1100,4 @@ }

}
throwImportNotDefined(name, packageJsonUrl, base);
throw importNotDefined(name, packageJsonUrl, base);
}
function getPackageType(url) {
const packageConfig = getPackageScopeConfig(url);
return packageConfig.type;
}
function parsePackageName(specifier, base) {

@@ -682,11 +1116,11 @@ let separatorIndex = specifier.indexOf("/");

const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
let i = -1;
while (++i < packageName.length) {
if (packageName[i] === "%" || packageName[i] === "\\") {
validPackageName = false;
break;
}
if (invalidPackageNameRegEx.exec(packageName) !== null) {
validPackageName = false;
}
if (!validPackageName) {
throw new ERR_INVALID_MODULE_SPECIFIER(specifier, "is not a valid package name", (0, import_url2.fileURLToPath)(base));
throw new ERR_INVALID_MODULE_SPECIFIER(
specifier,
"is not a valid package name",
(0, import_node_url3.fileURLToPath)(base)
);
}

@@ -697,12 +1131,27 @@ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));

function packageResolve(specifier, base, conditions) {
const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base);
if (import_node_module.builtinModules.includes(specifier)) {
return new import_node_url3.URL("node:" + specifier);
}
const { packageName, packageSubpath, isScoped } = parsePackageName(
specifier,
base
);
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
const packageJsonUrl2 = (0, import_url2.pathToFileURL)(packageConfig.pjsonPath);
const packageJsonUrl2 = (0, import_node_url3.pathToFileURL)(packageConfig.pjsonPath);
if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
return packageExportsResolve(packageJsonUrl2, packageSubpath, packageConfig, base, conditions).resolved;
return packageExportsResolve(
packageJsonUrl2,
packageSubpath,
packageConfig,
base,
conditions
);
}
}
let packageJsonUrl = new import_url2.URL("./node_modules/" + packageName + "/package.json", base);
let packageJsonPath = (0, import_url2.fileURLToPath)(packageJsonUrl);
let packageJsonUrl = new import_node_url3.URL(
"./node_modules/" + packageName + "/package.json",
base
);
let packageJsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl);
let lastPath;

@@ -713,14 +1162,25 @@ do {

lastPath = packageJsonPath;
packageJsonUrl = new import_url2.URL((isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", packageJsonUrl);
packageJsonPath = (0, import_url2.fileURLToPath)(packageJsonUrl);
packageJsonUrl = new import_node_url3.URL(
(isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
packageJsonUrl
);
packageJsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl);
continue;
}
const packageConfig2 = getPackageConfig(packageJsonPath, specifier, base);
if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null)
return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig2, base, conditions).resolved;
if (packageSubpath === ".")
if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
return packageExportsResolve(
packageJsonUrl,
packageSubpath,
packageConfig2,
base,
conditions
);
}
if (packageSubpath === ".") {
return legacyMainResolve(packageJsonUrl, packageConfig2, base);
return new import_url2.URL(packageSubpath, packageJsonUrl);
}
return new import_node_url3.URL(packageSubpath, packageJsonUrl);
} while (packageJsonPath.length !== lastPath.length);
throw new ERR_MODULE_NOT_FOUND(packageName, (0, import_url2.fileURLToPath)(base));
throw new ERR_MODULE_NOT_FOUND(packageName, (0, import_node_url3.fileURLToPath)(base));
}

@@ -744,54 +1204,107 @@ function isRelativeSpecifier(specifier) {

}
function moduleResolve(specifier, base, conditions) {
function moduleResolve(specifier, base, conditions, preserveSymlinks) {
const isRemote = base.protocol === "http:" || base.protocol === "https:";
let resolved;
if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
resolved = new import_url2.URL(specifier, base);
} else if (specifier[0] === "#") {
;
({ resolved } = packageImportsResolve(specifier, base, conditions));
resolved = new import_node_url3.URL(specifier, base);
} else if (!isRemote && specifier[0] === "#") {
resolved = packageImportsResolve(specifier, base, conditions);
} else {
try {
resolved = new import_url2.URL(specifier);
resolved = new import_node_url3.URL(specifier);
} catch {
resolved = packageResolve(specifier, base, conditions);
if (!isRemote) {
resolved = packageResolve(specifier, base, conditions);
}
}
}
return finalizeResolution(resolved, base);
(0, import_node_assert2.default)(typeof resolved !== "undefined", "expected to be defined");
if (resolved.protocol !== "file:") {
return resolved;
}
return finalizeResolution(resolved, base, preserveSymlinks);
}
function checkIfDisallowedImport(specifier, parsed, parsedParentURL) {
if (parsed && parsedParentURL && (parsedParentURL.protocol === "http:" || parsedParentURL.protocol === "https:")) {
if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
if (parsed && parsed.protocol !== "https:" && parsed.protocol !== "http:") {
throw new ERR_NETWORK_IMPORT_DISALLOWED(
specifier,
parsedParentURL,
"remote imports cannot import from a local location."
);
}
return { url: parsed.href };
}
if (import_node_module.builtinModules.includes(specifier)) {
throw new ERR_NETWORK_IMPORT_DISALLOWED(
specifier,
parsedParentURL,
"remote imports cannot import from a local location."
);
}
throw new ERR_NETWORK_IMPORT_DISALLOWED(
specifier,
parsedParentURL,
"only relative and absolute specifiers are supported."
);
}
}
function throwIfUnsupportedURLProtocol(url) {
if (url.protocol !== "file:" && url.protocol !== "data:" && url.protocol !== "node:") {
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url);
}
}
function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports2) {
if (parsed && parsed.protocol !== "file:" && parsed.protocol !== "data:" && (!experimentalNetworkImports2 || parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(
parsed,
["file", "data"].concat(
experimentalNetworkImports2 ? ["https", "http"] : []
)
);
}
}
function defaultResolve(specifier, context = {}) {
const { parentURL } = context;
(0, import_node_assert2.default)(typeof parentURL !== "undefined", "expected `parentURL` to be defined");
let parsedParentURL;
if (parentURL) {
try {
parsedParentURL = new import_node_url3.URL(parentURL);
} catch {
}
}
let parsed;
try {
parsed = new import_url2.URL(specifier);
if (parsed.protocol === "data:") {
return { url: specifier };
parsed = shouldBeTreatedAsRelativeOrAbsolutePath(specifier) ? new import_node_url3.URL(specifier, parsedParentURL) : new import_node_url3.URL(specifier);
if (parsed.protocol === "data:" || experimentalNetworkImports && (parsed.protocol === "https:" || parsed.protocol === "http:")) {
return { url: parsed.href, format: null };
}
} catch {
}
const maybeReturn = checkIfDisallowedImport(
specifier,
parsed,
parsedParentURL
);
if (maybeReturn)
return maybeReturn;
if (parsed && parsed.protocol === "node:")
return { url: specifier };
if (parsed && parsed.protocol !== "file:" && parsed.protocol !== "data:")
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed);
if (listOfBuiltins.includes(specifier)) {
return { url: "node:" + specifier };
}
if (parentURL.startsWith("data:")) {
new import_url2.URL(specifier, parentURL);
}
throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports);
const conditions = getConditionsSet(context.conditions);
let url = moduleResolve(specifier, new import_url2.URL(parentURL), conditions);
const urlPath = (0, import_url2.fileURLToPath)(url);
const real = (0, import_fs2.realpathSync)(urlPath);
const old = url;
url = (0, import_url2.pathToFileURL)(real + (urlPath.endsWith(import_path3.default.sep) ? "/" : ""));
url.search = old.search;
url.hash = old.hash;
return { url: `${url}` };
const url = moduleResolve(specifier, new import_node_url3.URL(parentURL), conditions, false);
throwIfUnsupportedURLProtocol(url);
return {
// Do NOT cast `url` to a string: that will work even when there are real
// problems, silencing them
url: url.href,
format: defaultGetFormatWithoutErrors(url, { parentURL })
};
}
module.exports = __toCommonJS(resolve_exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
defaultResolve,
getPackageType,
moduleResolve
});

@@ -1,55 +0,76 @@

/* DON'T EDIT THIS FILE. This is generated by 'scripts/update-lib-index.js' */
"use strict"
module.exports = {
configs: {
"recommended-module": require("./configs/recommended-module"),
"recommended-script": require("./configs/recommended-script"),
get recommended() {
return require("./configs/recommended")()
},
},
rules: {
"callback-return": require("./rules/callback-return"),
"exports-style": require("./rules/exports-style"),
"file-extension-in-import": require("./rules/file-extension-in-import"),
"global-require": require("./rules/global-require"),
"handle-callback-err": require("./rules/handle-callback-err"),
"no-callback-literal": require("./rules/no-callback-literal"),
"no-deprecated-api": require("./rules/no-deprecated-api"),
"no-exports-assign": require("./rules/no-exports-assign"),
"no-extraneous-import": require("./rules/no-extraneous-import"),
"no-extraneous-require": require("./rules/no-extraneous-require"),
"no-missing-import": require("./rules/no-missing-import"),
"no-missing-require": require("./rules/no-missing-require"),
"no-mixed-requires": require("./rules/no-mixed-requires"),
"no-new-require": require("./rules/no-new-require"),
"no-path-concat": require("./rules/no-path-concat"),
"no-process-env": require("./rules/no-process-env"),
"no-process-exit": require("./rules/no-process-exit"),
"no-restricted-import": require("./rules/no-restricted-import"),
"no-restricted-require": require("./rules/no-restricted-require"),
"no-sync": require("./rules/no-sync"),
"no-unpublished-bin": require("./rules/no-unpublished-bin"),
"no-unpublished-import": require("./rules/no-unpublished-import"),
"no-unpublished-require": require("./rules/no-unpublished-require"),
"no-unsupported-features/es-builtins": require("./rules/no-unsupported-features/es-builtins"),
"no-unsupported-features/es-syntax": require("./rules/no-unsupported-features/es-syntax"),
"no-unsupported-features/node-builtins": require("./rules/no-unsupported-features/node-builtins"),
"prefer-global/buffer": require("./rules/prefer-global/buffer"),
"prefer-global/console": require("./rules/prefer-global/console"),
"prefer-global/process": require("./rules/prefer-global/process"),
"prefer-global/text-decoder": require("./rules/prefer-global/text-decoder"),
"prefer-global/text-encoder": require("./rules/prefer-global/text-encoder"),
"prefer-global/url-search-params": require("./rules/prefer-global/url-search-params"),
"prefer-global/url": require("./rules/prefer-global/url"),
"prefer-promises/dns": require("./rules/prefer-promises/dns"),
"prefer-promises/fs": require("./rules/prefer-promises/fs"),
"process-exit-as-throw": require("./rules/process-exit-as-throw"),
"shebang": require("./rules/shebang"),
const pkg = require("../package.json")
const esmConfig = require("./configs/recommended-module")
const cjsConfig = require("./configs/recommended-script")
const recommendedConfig = require("./configs/recommended")
// Deprecated rules.
"no-hide-core-modules": require("./rules/no-hide-core-modules"),
"no-unsupported-features": require("./rules/no-unsupported-features"),
const rules = {
"callback-return": require("./rules/callback-return"),
"exports-style": require("./rules/exports-style"),
"file-extension-in-import": require("./rules/file-extension-in-import"),
"global-require": require("./rules/global-require"),
"handle-callback-err": require("./rules/handle-callback-err"),
"no-callback-literal": require("./rules/no-callback-literal"),
"no-deprecated-api": require("./rules/no-deprecated-api"),
"no-exports-assign": require("./rules/no-exports-assign"),
"no-extraneous-import": require("./rules/no-extraneous-import"),
"no-extraneous-require": require("./rules/no-extraneous-require"),
"no-missing-import": require("./rules/no-missing-import"),
"no-missing-require": require("./rules/no-missing-require"),
"no-mixed-requires": require("./rules/no-mixed-requires"),
"no-new-require": require("./rules/no-new-require"),
"no-path-concat": require("./rules/no-path-concat"),
"no-process-env": require("./rules/no-process-env"),
"no-process-exit": require("./rules/no-process-exit"),
"no-restricted-import": require("./rules/no-restricted-import"),
"no-restricted-require": require("./rules/no-restricted-require"),
"no-sync": require("./rules/no-sync"),
"no-unpublished-bin": require("./rules/no-unpublished-bin"),
"no-unpublished-import": require("./rules/no-unpublished-import"),
"no-unpublished-require": require("./rules/no-unpublished-require"),
"no-unsupported-features/es-builtins": require("./rules/no-unsupported-features/es-builtins"),
"no-unsupported-features/es-syntax": require("./rules/no-unsupported-features/es-syntax"),
"no-unsupported-features/node-builtins": require("./rules/no-unsupported-features/node-builtins"),
"prefer-global/buffer": require("./rules/prefer-global/buffer"),
"prefer-global/console": require("./rules/prefer-global/console"),
"prefer-global/process": require("./rules/prefer-global/process"),
"prefer-global/text-decoder": require("./rules/prefer-global/text-decoder"),
"prefer-global/text-encoder": require("./rules/prefer-global/text-encoder"),
"prefer-global/url-search-params": require("./rules/prefer-global/url-search-params"),
"prefer-global/url": require("./rules/prefer-global/url"),
"prefer-promises/dns": require("./rules/prefer-promises/dns"),
"prefer-promises/fs": require("./rules/prefer-promises/fs"),
"process-exit-as-throw": require("./rules/process-exit-as-throw"),
shebang: require("./rules/shebang"),
// Deprecated rules.
"no-hide-core-modules": require("./rules/no-hide-core-modules"),
"no-unsupported-features": require("./rules/no-unsupported-features"),
}
const mod = {
meta: {
name: pkg.name,
version: pkg.version,
},
rules,
}
// set configs, e.g. mod.configs["recommended-module"]
// do not defined in the mod obj - to avoid circular dependency
mod.configs = {
"recommended-module": { plugins: ["n"], ...esmConfig.eslintrc },
"recommended-script": { plugins: ["n"], ...cjsConfig.eslintrc },
recommended: { plugins: ["n"], ...recommendedConfig.eslintrc },
"flat/recommended-module": { plugins: { n: mod }, ...esmConfig.flat },
"flat/recommended-script": { plugins: { n: mod }, ...cjsConfig.flat },
"flat/recommended": { plugins: { n: mod }, ...recommendedConfig.flat },
"flat/mixed-esm-and-cjs": [
{ plugins: { n: mod }, files: ["**/*.js"], ...recommendedConfig.flat },
{ plugins: { n: mod }, files: ["**/*.mjs"], ...esmConfig.flat },
{ plugins: { n: mod }, files: ["**/*.cjs"], ...cjsConfig.flat },
],
}
module.exports = mod

@@ -12,5 +12,4 @@ /**

description: "require `return` statements after callbacks",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/callback-return.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/callback-return.md",
},

@@ -31,3 +30,3 @@ schema: [

const callbacks = context.options[0] || ["callback", "cb", "next"]
const sourceCode = context.getSourceCode()
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9

@@ -34,0 +33,0 @@ /**

@@ -230,5 +230,4 @@ /**

description: "enforce either `module.exports` or `exports`",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/exports-style.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/exports-style.md",
},

@@ -263,3 +262,3 @@ type: "suggestion",

)
const sourceCode = context.getSourceCode()
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9

@@ -292,4 +291,3 @@ /**

*/
function enforceModuleExports() {
const globalScope = context.getScope()
function enforceModuleExports(globalScope) {
const exportsNodes = getExportsNodes(globalScope)

@@ -324,4 +322,3 @@ const assignList = batchAssignAllowed

*/
function enforceExports() {
const globalScope = context.getScope()
function enforceExports(globalScope) {
const exportsNodes = getExportsNodes(globalScope)

@@ -378,9 +375,11 @@ const moduleExportsNodes = getModuleExportsNodes(globalScope)

return {
"Program:exit"() {
"Program:exit"(node) {
const scope = sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
switch (mode) {
case "module.exports":
enforceModuleExports()
enforceModuleExports(scope)
break
case "exports":
enforceExports()
enforceExports(scope)
break

@@ -387,0 +386,0 @@

@@ -11,5 +11,2 @@ /**

const visitImport = require("../util/visit-import")
const packageNamePattern = /^(?:@[^/\\]+[/\\])?[^/\\]+$/u
const corePackageOverridePattern =
/^(?:assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|dns|domain|events|fs|http|http2|https|inspector|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|sys|timers|tls|trace_events|tty|url|util|v8|vm|worker_threads|zlib)[/\\]$/u

@@ -41,5 +38,4 @@ /**

"enforce the style of file extensions in `import` declarations",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/file-extension-in-import.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/file-extension-in-import.md",
},

@@ -66,3 +62,3 @@ fixable: "code",

create(context) {
if (context.getFilename().startsWith("<")) {
if ((context.filename ?? context.getFilename()).startsWith("<")) {
return {}

@@ -73,9 +69,9 @@ }

function verify({ filePath, name, node }) {
/**
* @param {import("../util/import-target.js")} target
* @returns {void}
*/
function verify({ filePath, name, node, moduleType }) {
// Ignore if it's not resolved to a file or it's a bare module.
if (
!filePath ||
packageNamePattern.test(name) ||
corePackageOverridePattern.test(name)
) {
if (moduleType !== "relative" && moduleType !== "absolute") {
return

@@ -82,0 +78,0 @@ }

@@ -56,5 +56,4 @@ /**

"require `require()` calls to be placed at top-level module scope",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/global-require.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/global-require.md",
},

@@ -69,5 +68,8 @@ fixable: null,

create(context) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
return {
CallExpression(node) {
const currentScope = context.getScope()
const currentScope =
sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9

@@ -78,4 +80,6 @@ if (

) {
const isGoodRequire = context
.getAncestors()
const isGoodRequire = (
sourceCode.getAncestors?.(node) ??
context.getAncestors()
) // TODO: remove context.getAncestors() when dropping support for ESLint < v9
.every(

@@ -82,0 +86,0 @@ parent =>

@@ -12,5 +12,4 @@ /**

description: "require error handling in callbacks",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/handle-callback-err.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/handle-callback-err.md",
},

@@ -29,2 +28,3 @@ fixable: null,

create(context) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const errorArgument = context.options[0] || "err"

@@ -75,3 +75,3 @@

function checkForError(node) {
const scope = context.getScope()
const scope = sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const parameters = getParameters(scope)

@@ -78,0 +78,0 @@ const firstParameter = parameters[0]

@@ -12,5 +12,4 @@ /**

"enforce Node.js-style error-first callback pattern is followed",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-callback-literal.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-callback-literal.md",
},

@@ -17,0 +16,0 @@ type: "problem",

@@ -7,8 +7,15 @@ /**

const { CALL, CONSTRUCT, READ, ReferenceTracker } = require("eslint-utils")
const {
CALL,
CONSTRUCT,
READ,
ReferenceTracker,
} = require("@eslint-community/eslint-utils")
const enumeratePropertyNames = require("../util/enumerate-property-names")
const getConfiguredNodeVersion = require("../util/get-configured-node-version")
const getSemverRange = require("../util/get-semver-range")
const extendTrackmapWithNodePrefix = require("../util/extend-trackmap-with-node-prefix")
const unprefixNodeColon = require("../util/unprefix-node-colon")
const modules = {
const rawModules = {
_linklist: {

@@ -566,2 +573,4 @@ [READ]: { since: "5.0.0", replacedBy: null },

}
const modules = extendTrackmapWithNodePrefix(rawModules)
const globals = {

@@ -660,3 +669,3 @@ Buffer: {

function toName(type, path) {
const baseName = path.join(".")
const baseName = unprefixNodeColon(path.join("."))
return type === ReferenceTracker.CALL

@@ -688,5 +697,4 @@ ? `${baseName}()`

description: "disallow deprecated APIs",
category: "Best Practices",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-deprecated-api.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-deprecated-api.md",
},

@@ -703,3 +711,5 @@ type: "problem",

items: {
enum: Array.from(enumeratePropertyNames(modules)),
enum: Array.from(
enumeratePropertyNames(rawModules)
),
},

@@ -754,5 +764,8 @@ additionalItems: false,

const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
return {
"Program:exit"() {
const tracker = new ReferenceTracker(context.getScope(), {
"Program:exit"(node) {
const scope = sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const tracker = new ReferenceTracker(scope, {
mode: "legacy",

@@ -759,0 +772,0 @@ })

@@ -7,3 +7,3 @@ /**

const { findVariable } = require("eslint-utils")
const { findVariable } = require("@eslint-community/eslint-utils")

@@ -42,5 +42,4 @@ function isExports(node, scope) {

description: "disallow the assignment to `exports`",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-exports-assign.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-exports-assign.md",
},

@@ -56,5 +55,8 @@ fixable: null,

create(context) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
return {
AssignmentExpression(node) {
const scope = context.getScope()
const scope = sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
if (

@@ -61,0 +63,0 @@ !isExports(node.left, scope) ||

@@ -18,5 +18,4 @@ /**

"disallow `import` declarations which import extraneous modules",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-extraneous-import.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-extraneous-import.md",
},

@@ -39,3 +38,3 @@ type: "problem",

create(context) {
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()
if (filePath === "<input>") {

@@ -42,0 +41,0 @@ return {}

@@ -19,5 +19,4 @@ /**

"disallow `require()` expressions which import extraneous modules",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-extraneous-require.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-extraneous-require.md",
},

@@ -41,3 +40,3 @@ type: "problem",

create(context) {
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()
if (filePath === "<input>") {

@@ -44,0 +43,0 @@ return {}

@@ -60,5 +60,4 @@ /**

"disallow third-party modules which are hiding core modules",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-hide-core-modules.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-hide-core-modules.md",
},

@@ -85,10 +84,12 @@ type: "problem",

messages: {
"unexpectedImport": "Unexpected import of third-party module '{{name}}'.",
}
unexpectedImport:
"Unexpected import of third-party module '{{name}}'.",
},
},
create(context) {
if (context.getFilename() === "<input>") {
const filename = context.filename ?? context.getFilename()
if (filename === "<input>") {
return {}
}
const filePath = path.resolve(context.getFilename())
const filePath = path.resolve(filename)
const dirPath = path.dirname(filePath)

@@ -95,0 +96,0 @@ const packageJson = getPackageJson(filePath)

@@ -10,2 +10,4 @@ /**

const getResolvePaths = require("../util/get-resolve-paths")
const getTSConfig = require("../util/get-tsconfig")
const getTypescriptExtensionMap = require("../util/get-typescript-extension-map")
const visitImport = require("../util/visit-import")

@@ -18,5 +20,4 @@

"disallow `import` declarations which import non-existence modules",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-missing-import.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-missing-import.md",
},

@@ -31,2 +32,4 @@ type: "problem",

resolvePaths: getResolvePaths.schema,
typescriptExtensionMap: getTypescriptExtensionMap.schema,
tsconfigPath: getTSConfig.schema,
},

@@ -39,3 +42,3 @@ additionalProperties: false,

create(context) {
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()
if (filePath === "<input>") {

@@ -42,0 +45,0 @@ return {}

@@ -10,3 +10,5 @@ /**

const getResolvePaths = require("../util/get-resolve-paths")
const getTSConfig = require("../util/get-tsconfig")
const getTryExtensions = require("../util/get-try-extensions")
const getTypescriptExtensionMap = require("../util/get-typescript-extension-map")
const visitRequire = require("../util/visit-require")

@@ -19,5 +21,4 @@

"disallow `require()` expressions which import non-existence modules",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-missing-require.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-missing-require.md",
},

@@ -33,2 +34,4 @@ type: "problem",

resolvePaths: getResolvePaths.schema,
typescriptExtensionMap: getTypescriptExtensionMap.schema,
tsconfigPath: getTSConfig.schema,
},

@@ -41,3 +44,3 @@ additionalProperties: false,

create(context) {
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()
if (filePath === "<input>") {

@@ -44,0 +47,0 @@ return {}

@@ -74,5 +74,4 @@ /**

"disallow `require` calls to be mixed with regular variable declarations",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-mixed-requires.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-mixed-requires.md",
},

@@ -79,0 +78,0 @@ fixable: null,

@@ -12,5 +12,4 @@ /**

description: "disallow `new` operators with calls to `require`",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-new-require.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-new-require.md",
},

@@ -17,0 +16,0 @@ fixable: null,

@@ -8,3 +8,7 @@ /**

const path = require("path")
const { READ, ReferenceTracker, getStringIfConstant } = require("eslint-utils")
const {
READ,
ReferenceTracker,
getStringIfConstant,
} = require("@eslint-community/eslint-utils")

@@ -166,5 +170,4 @@ /**

"disallow string concatenation with `__dirname` and `__filename`",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-path-concat.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-path-concat.md",
},

@@ -181,4 +184,6 @@ fixable: null,

return {
"Program:exit"() {
const globalScope = context.getScope()
"Program:exit"(node) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const globalScope =
sourceCode.getScope?.(node) ?? context.getScope()
const tracker = new ReferenceTracker(globalScope)

@@ -185,0 +190,0 @@ const sepNodes = new Set()

@@ -16,5 +16,4 @@ /**

description: "disallow the use of `process.env`",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-process-env.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-process-env.md",
},

@@ -21,0 +20,0 @@ fixable: null,

@@ -12,5 +12,4 @@ /**

description: "disallow the use of `process.exit()`",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-process-exit.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-process-exit.md",
},

@@ -17,0 +16,0 @@ fixable: null,

@@ -16,5 +16,4 @@ /**

"disallow specified modules when loaded by `import` declarations",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-restricted-import.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-restricted-import.md",
},

@@ -21,0 +20,0 @@ fixable: null,

@@ -16,5 +16,4 @@ /**

description: "disallow specified modules when loaded by `require`",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-restricted-require.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-restricted-require.md",
},

@@ -21,0 +20,0 @@ fixable: null,

@@ -7,2 +7,20 @@ /**

const allowedAtRootLevelSelector = [
// fs.readFileSync()
":function MemberExpression > Identifier[name=/Sync$/]",
// readFileSync.call(null, 'path')
":function MemberExpression > Identifier[name=/Sync$/]",
// readFileSync()
":function :not(MemberExpression) > Identifier[name=/Sync$/]",
]
const disallowedAtRootLevelSelector = [
// fs.readFileSync()
"MemberExpression > Identifier[name=/Sync$/]",
// readFileSync.call(null, 'path')
"MemberExpression > Identifier[name=/Sync$/]",
// readFileSync()
":not(MemberExpression) > Identifier[name=/Sync$/]",
]
module.exports = {

@@ -13,5 +31,4 @@ meta: {

description: "disallow synchronous methods",
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-sync.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-sync.md",
},

@@ -37,6 +54,5 @@ fixable: null,

create(context) {
const selector =
context.options[0] && context.options[0].allowAtRootLevel
? ":function MemberExpression[property.name=/.*Sync$/]"
: "MemberExpression[property.name=/.*Sync$/]"
const selector = context.options[0]?.allowAtRootLevel
? allowedAtRootLevelSelector
: disallowedAtRootLevelSelector

@@ -46,6 +62,6 @@ return {

context.report({
node,
node: node.parent,
messageId: "noSync",
data: {
propertyName: node.property.name,
propertyName: node.name,
},

@@ -52,0 +68,0 @@ })

@@ -36,5 +36,4 @@ /**

description: "disallow `bin` files that npm ignores",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unpublished-bin.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unpublished-bin.md",
},

@@ -53,4 +52,5 @@ type: "problem",

messages: {
invalidIgnored: "npm ignores '{{name}}'. Check 'files' field of 'package.json' or '.npmignore'."
}
invalidIgnored:
"npm ignores '{{name}}'. Check 'files' field of 'package.json' or '.npmignore'.",
},
},

@@ -61,3 +61,3 @@ create(context) {

// Check file path.
let rawFilePath = context.getFilename()
let rawFilePath = context.filename ?? context.getFilename()
if (rawFilePath === "<input>") {

@@ -64,0 +64,0 @@ return

@@ -18,5 +18,4 @@ /**

"disallow `import` declarations which import private modules",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unpublished-import.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unpublished-import.md",
},

@@ -40,3 +39,3 @@ type: "problem",

create(context) {
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()
const options = context.options[0] || {}

@@ -43,0 +42,0 @@ const ignoreTypeImport =

@@ -19,5 +19,4 @@ /**

"disallow `require()` expressions which import private modules",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unpublished-require.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unpublished-require.md",
},

@@ -41,3 +40,3 @@ type: "problem",

create(context) {
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()
if (filePath === "<input>") {

@@ -44,0 +43,0 @@ return {}

@@ -8,3 +8,6 @@ /**

const semver = require("semver")
const { getInnermostScope, getPropertyName } = require("eslint-utils")
const {
getInnermostScope,
getPropertyName,
} = require("@eslint-community/eslint-utils")
const getPackageJson = require("../util/get-package-json")

@@ -1049,6 +1052,5 @@

"disallow unsupported ECMAScript features on the specified version",
category: "Possible Errors",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unsupported-features.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unsupported-features.md",
},

@@ -1088,6 +1090,6 @@ type: "problem",

create(context) {
const sourceCode = context.getSourceCode()
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const supportInfo = parseOptions(
context.options[0],
getDefaultVersion(context.getFilename())
getDefaultVersion(context.filename ?? context.getFilename())
)

@@ -1102,3 +1104,4 @@

function* getReferences(names) {
const globalScope = context.getScope()
const globalScope =
sourceCode.getScope?.(sourceCode.ast) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9

@@ -1164,2 +1167,4 @@ for (const name of names) {

function report(node, key) {
const globalScope =
sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const version = supportInfo.version

@@ -1181,3 +1186,3 @@ const feature = supportInfo.features[key]

})
} else if (!normalizeScope(context.getScope(), node).isStrict) {
} else if (!normalizeScope(globalScope, node).isStrict) {
context.report({

@@ -1338,3 +1343,5 @@ node,

FunctionDeclaration(node) {
const scope = context.getScope().upper
const scope = (
sourceCode.getScope?.(node) ?? context.getScope()
).upper //TODO: remove context.getScope() when dropping support for ESLint < v9
if (!TOPLEVEL_SCOPE_TYPE.test(scope.type)) {

@@ -1341,0 +1348,0 @@ report(node, "blockScopedFunctions")

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const {

@@ -18,2 +18,5 @@ checkUnsupportedBuiltins,

globals: {
AggregateError: {
[READ]: { supported: "15.0.0" },
},
Array: {

@@ -26,2 +29,5 @@ from: { [READ]: { supported: "4.0.0" } },

},
FinalizationRegistry: {
[READ]: { supported: "14.6.0" },
},
Map: {

@@ -73,2 +79,3 @@ [READ]: { supported: "0.12.0" },

allSettled: { [READ]: { supported: "12.9.0" } },
any: { [READ]: { supported: "15.0.0" } },
},

@@ -130,2 +137,5 @@ Proxy: {

},
WeakRef: {
[READ]: { supported: "14.6.0" },
},
WeakSet: {

@@ -151,5 +161,4 @@ [READ]: { supported: "0.12.0" },

"disallow unsupported ECMAScript built-ins on the specified version",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unsupported-features/es-builtins.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unsupported-features/es-builtins.md",
},

@@ -156,0 +165,0 @@ type: "problem",

@@ -7,4 +7,4 @@ /**

const { rules: esRules } = require("eslint-plugin-es")
const { getInnermostScope } = require("eslint-utils")
const { rules: esRules } = require("eslint-plugin-es-x")
const { getInnermostScope } = require("@eslint-community/eslint-utils")
const { Range } = require("semver")

@@ -406,2 +406,24 @@ const rangeSubset = require("semver/ranges/subset")

},
//--------------------------------------------------------------------------
// ES2021
//--------------------------------------------------------------------------
logicalAssignmentOperators: {
ruleId: "no-logical-assignment-operators",
cases: [
{
supported: "15.0.0",
messageId: "no-logical-assignment-operators",
},
],
},
numericSeparators: {
ruleId: "no-numeric-separators",
cases: [
{
supported: "12.5.0",
messageId: "no-numeric-separators",
},
],
},
}

@@ -440,3 +462,3 @@ const keywords = Object.keys(features)

/**
* Define the visitor object as merging the rules of eslint-plugin-es.
* Define the visitor object as merging the rules of eslint-plugin-es-x.
* @param {RuleContext} context The rule context.

@@ -449,3 +471,5 @@ * @param {{version:Range,ignores:Set<string>}} options The options.

get isStrict() {
return normalizeScope(context.getScope(), this.node).isStrict
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const scope = sourceCode.getScope?.(this.node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
return normalizeScope(scope, this.node).isStrict
},

@@ -530,5 +554,4 @@ }

"disallow unsupported ECMAScript syntax on the specified version",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unsupported-features/es-syntax.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unsupported-features/es-syntax.md",
},

@@ -661,2 +684,10 @@ type: "problem",

"Nullish coalescing operators are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
//------------------------------------------------------------------
// ES2021
//------------------------------------------------------------------
"no-logical-assignment-operators":
"Logical assignment operators are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-numeric-separators":
"Numeric separators are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
},

@@ -663,0 +694,0 @@ },

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const {

@@ -15,2 +15,3 @@ checkUnsupportedBuiltins,

const getConfiguredNodeVersion = require("../../util/get-configured-node-version")
const extendTrackMapWithNodePrefix = require("../../util/extend-trackmap-with-node-prefix")

@@ -373,4 +374,5 @@ const trackMap = {

})
/*eslint-enable camelcase */
trackMap.modules = extendTrackMapWithNodePrefix(trackMap.modules)
module.exports = {

@@ -381,5 +383,4 @@ meta: {

"disallow unsupported Node.js built-in APIs on the specified version",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/no-unsupported-features/node-builtins.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/no-unsupported-features/node-builtins.md",
},

@@ -386,0 +387,0 @@ type: "problem",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -27,5 +27,4 @@

'enforce either `Buffer` or `require("buffer").Buffer`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/buffer.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/buffer.md",
},

@@ -32,0 +31,0 @@ type: "suggestion",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -24,5 +24,4 @@

description: 'enforce either `console` or `require("console")`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/console.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/console.md",
},

@@ -29,0 +28,0 @@ type: "suggestion",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -24,5 +24,4 @@

description: 'enforce either `process` or `require("process")`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/process.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/process.md",
},

@@ -29,0 +28,0 @@ type: "suggestion",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -27,5 +27,4 @@

'enforce either `TextDecoder` or `require("util").TextDecoder`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/text-decoder.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/text-decoder.md",
},

@@ -32,0 +31,0 @@ type: "suggestion",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -27,5 +27,4 @@

'enforce either `TextEncoder` or `require("util").TextEncoder`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/text-encoder.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/text-encoder.md",
},

@@ -32,0 +31,0 @@ type: "suggestion",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -27,5 +27,4 @@

'enforce either `URLSearchParams` or `require("url").URLSearchParams`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/url-search-params.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/url-search-params.md",
},

@@ -32,0 +31,0 @@ type: "suggestion",

@@ -7,3 +7,3 @@ /**

const { READ } = require("eslint-utils")
const { READ } = require("@eslint-community/eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")

@@ -26,5 +26,4 @@

description: 'enforce either `URL` or `require("url").URL`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-global/url.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-global/url.md",
},

@@ -31,0 +30,0 @@ type: "suggestion",

@@ -7,3 +7,7 @@ /**

const { CALL, CONSTRUCT, ReferenceTracker } = require("eslint-utils")
const {
CALL,
CONSTRUCT,
ReferenceTracker,
} = require("@eslint-community/eslint-utils")

@@ -32,2 +36,3 @@ const trackMap = {

}
trackMap["node:dns"] = trackMap.dns

@@ -38,5 +43,4 @@ module.exports = {

description: 'enforce `require("dns").promises`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-promises/dns.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-promises/dns.md",
},

@@ -54,4 +58,5 @@ fixable: null,

return {
"Program:exit"() {
const scope = context.getScope()
"Program:exit"(node) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const scope = sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const tracker = new ReferenceTracker(scope, { mode: "legacy" })

@@ -58,0 +63,0 @@ const references = [

@@ -7,3 +7,3 @@ /**

const { CALL, ReferenceTracker } = require("eslint-utils")
const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils")

@@ -38,2 +38,3 @@ const trackMap = {

}
trackMap["node:fs"] = trackMap.fs

@@ -44,5 +45,4 @@ module.exports = {

description: 'enforce `require("fs").promises`',
category: "Stylistic Issues",
recommended: false,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/prefer-promises/fs.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-promises/fs.md",
},

@@ -59,4 +59,5 @@ fixable: null,

return {
"Program:exit"() {
const scope = context.getScope()
"Program:exit"(node) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const scope = sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const tracker = new ReferenceTracker(scope, { mode: "legacy" })

@@ -63,0 +64,0 @@ const references = [

@@ -152,5 +152,4 @@ /* eslint-disable eslint-plugin/prefer-message-ids */

"require that `process.exit()` expressions use the same code path as `throw`",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/process-exit-as-throw.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/process-exit-as-throw.md",
},

@@ -157,0 +156,0 @@ type: "problem",

@@ -73,5 +73,4 @@ /**

description: "require correct usage of shebang",
category: "Possible Errors",
recommended: true,
url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/shebang.md",
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/shebang.md",
},

@@ -99,4 +98,4 @@ type: "problem",

create(context) {
const sourceCode = context.getSourceCode()
let filePath = context.getFilename()
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
let filePath = context.filename ?? context.getFilename()
if (filePath === "<input>") {

@@ -103,0 +102,0 @@ return {}

@@ -35,3 +35,3 @@ /**

const parsed = path.parse(target.filePath)
const reversedExt = mapTypescriptExtension(
const reversedExts = mapTypescriptExtension(
context,

@@ -42,7 +42,11 @@ target.filePath,

)
const reversedPath =
path.resolve(parsed.dir, parsed.name) + reversedExt
missingFile = target.moduleName == null && !exists(reversedPath)
const reversedPaths = reversedExts.map(
reversedExt =>
path.resolve(parsed.dir, parsed.name) + reversedExt
)
missingFile = reversedPaths.every(
reversedPath =>
target.moduleName == null && !exists(reversedPath)
)
}
if (missingModule || missingFile) {

@@ -49,0 +53,0 @@ context.report({

@@ -7,3 +7,4 @@ /**

const { ReferenceTracker } = require("eslint-utils")
const { ReferenceTracker } = require("@eslint-community/eslint-utils")
const extendTrackmapWithNodePrefix = require("./extend-trackmap-with-node-prefix")

@@ -34,15 +35,10 @@ /**

const { context, trackMap } = this
const tracker = new ReferenceTracker(context.getScope(), {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const scope =
sourceCode.getScope?.(sourceCode.ast) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const tracker = new ReferenceTracker(scope, {
mode: "legacy",
})
const modules = {
...trackMap.modules,
...Object.fromEntries(
Object.entries(trackMap.modules).map(([name, value]) => [
`node:${name}`,
value,
])
),
}
const modules = extendTrackmapWithNodePrefix(trackMap.modules)

@@ -63,3 +59,6 @@ for (const { node } of [

const { context, trackMap } = this
const tracker = new ReferenceTracker(context.getScope())
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const scope =
sourceCode.getScope?.(sourceCode.ast) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const tracker = new ReferenceTracker(scope)

@@ -66,0 +65,0 @@ for (const { node } of tracker.iterateGlobalReferences(

@@ -7,6 +7,7 @@ /**

const { Range, lt, major } = require("semver") //eslint-disable-line no-unused-vars
const { ReferenceTracker } = require("eslint-utils")
const { Range, lt, major } = require("semver") // eslint-disable-line no-unused-vars
const { ReferenceTracker } = require("@eslint-community/eslint-utils")
const getConfiguredNodeVersion = require("./get-configured-node-version")
const getSemverRange = require("./get-semver-range")
const unprefixNodeColon = require("./unprefix-node-colon")

@@ -88,3 +89,5 @@ /**

const options = parseOptions(context)
const tracker = new ReferenceTracker(context.getScope(), { mode: "legacy" })
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const scope = sourceCode.getScope?.(sourceCode.ast) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
const tracker = new ReferenceTracker(scope, { mode: "legacy" })
const references = [

@@ -97,3 +100,3 @@ ...tracker.iterateCjsReferences(trackMap.modules || {}),

for (const { node, path, info } of references) {
const name = path.join(".")
const name = unprefixNodeColon(path.join("."))
const supported = isSupported(info, options.version)

@@ -100,0 +103,0 @@

@@ -7,3 +7,4 @@ /**

const { CALL, CONSTRUCT, READ } = require("eslint-utils")
const { CALL, CONSTRUCT, READ } = require("@eslint-community/eslint-utils")
const unprefixNodeColon = require("./unprefix-node-colon")

@@ -22,13 +23,13 @@ /**

}
path.push(key)
const name = unprefixNodeColon(path.join("."))
if (value[CALL]) {
yield `${path.join(".")}()`
yield `${name}()`
}
if (value[CONSTRUCT]) {
yield `new ${path.join(".")}()`
yield `new ${name}()`
}
if (value[READ]) {
yield path.join(".")
yield name
}

@@ -35,0 +36,0 @@ yield* enumeratePropertyNames(value, path)

@@ -7,3 +7,3 @@ /**

const { Range } = require("semver") //eslint-disable-line no-unused-vars
const { Range } = require("semver") // eslint-disable-line no-unused-vars
const getPackageJson = require("./get-package-json")

@@ -40,3 +40,3 @@ const getSemverRange = require("./get-semver-range")

* 2. Look package.json up and parse `engines.node` then return it if it's valid.
* 3. Return `>=8.0.0`.
* 3. Return `>=16.0.0`.
*

@@ -52,3 +52,3 @@ * @param {string|undefined} version The version range text.

get(context.settings && (context.settings.n || context.settings.node))
const filePath = context.getFilename()
const filePath = context.filename ?? context.getFilename()

@@ -58,3 +58,3 @@ return (

getEnginesNode(filePath) ||
getSemverRange(">=8.0.0")
getSemverRange(">=16.0.0")
)

@@ -61,0 +61,0 @@ }

@@ -15,3 +15,2 @@ /**

const cache = new Cache()
const SLASH_AT_BEGIN_AND_END = /^!?\/+|^!|\/+$/gu
const PARENT_RELATIVE_PATH = /^\.\./u

@@ -94,3 +93,6 @@ const NEVER_IGNORED =

if (typeof file === "string" && file) {
const body = file.replace(SLASH_AT_BEGIN_AND_END, "")
const body = path.posix
.normalize(file.replace(/^!/u, ""))
.replace(/\/+$/u, "")
if (file.startsWith("!")) {

@@ -97,0 +99,0 @@ igN.add(`${body}`)

@@ -9,2 +9,3 @@ /**

const { pathToFileURL, fileURLToPath } = require("url")
const isBuiltin = require("is-builtin-module")
const resolve = require("resolve")

@@ -76,2 +77,10 @@ const {

function isNodeModule(name, options) {
try {
return require.resolve(name, options).startsWith(path.sep)
} catch {
return false
}
}
/**

@@ -121,2 +130,20 @@ * Gets the module name of a given path.

/**
* What type of module is this
* @type {'unknown'|'relative'|'absolute'|'node'|'npm'|'http'|void}
*/
this.moduleType = "unknown"
if (name.startsWith("./") || name.startsWith(".\\")) {
this.moduleType = "relative"
} else if (name.startsWith("/") || name.startsWith("\\")) {
this.moduleType = "absolute"
} else if (isBuiltin(name)) {
this.moduleType = "node"
} else if (isNodeModule(name, options)) {
this.moduleType = "npm"
} else if (name.startsWith("http://") || name.startsWith("https://")) {
this.moduleType = "http"
}
/**
* The full path of this import target.

@@ -123,0 +150,0 @@ * If the target is a module and it does not exist then this is `null`.

@@ -5,3 +5,3 @@ "use strict"

const typescriptExtensions = [".ts", ".cts", ".mts"]
const typescriptExtensions = [".ts", ".tsx", ".cts", ".mts"]

@@ -15,4 +15,9 @@ /**

module.exports = function isTypescript(context) {
const sourceFileExt = path.extname(context.getPhysicalFilename())
const sourceFileExt = path.extname(
context.physicalFilename ??
context.getPhysicalFilename?.() ??
context.filename ??
context.getFilename?.()
)
return typescriptExtensions.includes(sourceFileExt)
}
"use strict"
const path = require("path")
const isTypescript = require("../util/is-typescript")
const isTypescript = require("./is-typescript")
const getTypescriptExtensionMap = require("./get-typescript-extension-map")
const mapping = {
"": ".js", // default empty extension will map to js
".ts": ".js",
".cts": ".cjs",
".mts": ".mjs",
}
const reverseMapping = {
".js": ".ts",
".cjs": ".cts",
".mjs": ".mts",
}
/**

@@ -26,3 +14,3 @@ * Maps the typescript file extension that should be added in an import statement,

*
* @param {RuleContext} context
* @param {import('eslint').Rule.RuleContext} context
* @param {string} filePath The filePath of the import

@@ -39,10 +27,12 @@ * @param {string} fallbackExtension The non-typescript fallback

) {
const { forward, backward } = getTypescriptExtensionMap(context)
const ext = path.extname(filePath)
if (reverse) {
if (isTypescript(context) && ext in reverseMapping) {
return reverseMapping[ext]
if (isTypescript(context) && ext in backward) {
return backward[ext]
}
return [fallbackExtension]
} else {
if (isTypescript(context) && ext in mapping) {
return mapping[ext]
if (isTypescript(context) && ext in forward) {
return forward[ext]
}

@@ -49,0 +39,0 @@ }

@@ -33,3 +33,5 @@ /**

const targets = []
const basedir = path.dirname(path.resolve(context.getFilename()))
const basedir = path.dirname(
path.resolve(context.filename ?? context.getFilename())
)
const paths = getResolvePaths(context, optionIndex)

@@ -36,0 +38,0 @@ const extensions = getTryExtensions(context, optionIndex)

@@ -8,3 +8,7 @@ /**

const path = require("path")
const { CALL, ReferenceTracker, getStringIfConstant } = require("eslint-utils")
const {
CALL,
ReferenceTracker,
getStringIfConstant,
} = require("@eslint-community/eslint-utils")
const isCoreModule = require("is-core-module")

@@ -33,3 +37,5 @@ const getResolvePaths = require("./get-resolve-paths")

const targets = []
const basedir = path.dirname(path.resolve(context.getFilename()))
const basedir = path.dirname(
path.resolve(context.filename ?? context.getFilename())
)
const paths = getResolvePaths(context)

@@ -40,4 +46,7 @@ const extensions = getTryExtensions(context)

return {
"Program:exit"() {
const tracker = new ReferenceTracker(context.getScope())
"Program:exit"(node) {
const sourceCode = context.sourceCode ?? context.getSourceCode() // TODO: just use context.sourceCode when dropping eslint < v9
const tracker = new ReferenceTracker(
sourceCode.getScope?.(node) ?? context.getScope() //TODO: remove context.getScope() when dropping support for ESLint < v9
)
const references = tracker.iterateGlobalReferences({

@@ -44,0 +53,0 @@ require: {

{
"name": "eslint-plugin-n",
"version": "15.7.0",
"version": "16.6.1",
"description": "Additional ESLint's rules for Node.js",
"engines": {
"node": ">=12.22.0"
"node": ">=16.0.0"
},
"main": "lib/index.js",
"files": [
"lib"
"lib/",
"configs/"
],

@@ -16,35 +17,38 @@ "peerDependencies": {

"dependencies": {
"@eslint-community/eslint-utils": "^4.4.0",
"builtins": "^5.0.1",
"eslint-plugin-es": "^4.1.0",
"eslint-utils": "^3.0.0",
"ignore": "^5.1.1",
"is-core-module": "^2.11.0",
"eslint-plugin-es-x": "^7.5.0",
"get-tsconfig": "^4.7.0",
"globals": "^13.24.0",
"ignore": "^5.2.4",
"is-builtin-module": "^3.2.1",
"is-core-module": "^2.12.1",
"minimatch": "^3.1.2",
"resolve": "^1.22.1",
"semver": "^7.3.8"
"resolve": "^1.22.2",
"semver": "^7.5.3"
},
"devDependencies": {
"@typescript-eslint/parser": "^5.51.0",
"codecov": "^3.3.0",
"esbuild": "^0.14.39",
"eslint": "^8.27.0",
"eslint-config-prettier": "^8.5.0",
"eslint-doc-generator": "^1.4.2",
"eslint-plugin-eslint-plugin": "^5.0.6",
"@eslint/js": "^8.43.0",
"@types/eslint": "^8.44.6",
"@typescript-eslint/parser": "^5.60.0",
"esbuild": "^0.18.7",
"eslint": "^8.53.0",
"eslint-config-prettier": "^8.8.0",
"eslint-doc-generator": "^1.6.1",
"eslint-plugin-eslint-plugin": "^5.1.0",
"eslint-plugin-n": "file:.",
"fast-glob": "^3.2.12",
"globals": "^13.17.0",
"husky": "^8.0.2",
"import-meta-resolve": "^1.1.1",
"lint-staged": "^12.4.1",
"markdownlint-cli": "^0.32.2",
"mocha": "^10.1.0",
"npm-run-all": "^4.1.5",
"husky": "^8.0.3",
"import-meta-resolve": "^3.0.0",
"lint-staged": "^13.2.2",
"markdownlint-cli": "^0.35.0",
"mocha": "^10.2.0",
"npm-run-all2": "^6.1.1",
"nyc": "^15.1.0",
"opener": "^1.5.1",
"prettier": "^2.7.1",
"punycode": "^2.1.1",
"release-it": "^15.5.0",
"rimraf": "^3.0.2",
"typescript": "^4.9.5"
"opener": "^1.5.2",
"prettier": "^2.8.8",
"punycode": "^2.3.0",
"release-it": "^15.11.0",
"rimraf": "^5.0.1",
"typescript": "^5.1.3"
},

@@ -54,3 +58,2 @@ "scripts": {

"clean": "rimraf .nyc_output coverage",
"codecov": "nyc report --reporter text-lcov | codecov --pipe --disable=gcov -t $CODECOV_TOKEN",
"coverage": "opener ./coverage/lcov-report/index.html",

@@ -61,3 +64,3 @@ "format": "prettier --loglevel warn --write \"**/*.{js,css,md}\"",

"lint:eslint-docs": "npm run update:eslint-docs -- --check",
"lint:js": "eslint lib scripts tests/lib .eslintrc.js",
"lint:js": "eslint .",
"new": "node scripts/new-rule",

@@ -71,3 +74,3 @@ "postversion": "git push && git push --tags",

"test:ci": "nyc npm run -s test:_mocha",
"update:eslint-docs": "eslint-doc-generator --config-emoji recommended-module,☑️ --config-emoji recommended-script,✔️ --rule-list-split meta.docs.category --ignore-config recommended-module --ignore-config recommended-script --url-configs \"https://github.com/eslint-community/eslint-plugin-n#-configs\"",
"update:eslint-docs": "eslint-doc-generator",
"version": "npm run -s build && eslint lib/rules --fix && git add .",

@@ -74,0 +77,0 @@ "watch": "npm run test:_mocha -- --watch --growl"

@@ -5,6 +5,12 @@ # eslint-plugin-n

[![npm version](https://img.shields.io/npm/v/eslint-plugin-n.svg)](https://www.npmjs.com/package/eslint-plugin-n) [![Downloads/month](https://img.shields.io/npm/dm/eslint-plugin-n.svg)](http://www.npmtrends.com/eslint-plugin-n) [![Build Status](https://github.com/weiran-zsd/eslint-plugin-node/workflows/CI/badge.svg)](https://github.com/weiran-zsd/eslint-plugin-node/actions) [![Coverage Status](https://codecov.io/gh/weiran-zsd/eslint-plugin-node/branch/master/graph/badge.svg)](https://codecov.io/gh/weiran-zsd/eslint-plugin-node) [![Dependency Status](https://david-dm.org/weiran-zsd/eslint-plugin-node.svg)](https://david-dm.org/weiran-zsd/eslint-plugin-node)
[![npm version](https://img.shields.io/npm/v/eslint-plugin-n.svg)](https://www.npmjs.com/package/eslint-plugin-n)
[![Downloads](https://img.shields.io/npm/dm/eslint-plugin-n.svg)](https://www.npmjs.com/package/eslint-plugin-n)
[![Build Status](https://github.com/eslint-community/eslint-plugin-n/workflows/CI/badge.svg)](https://github.com/eslint-community/eslint-plugin-n/actions)
Additional ESLint's rules for Node.js
Additional ESLint rules for Node.js
## 🎨 Playground
[online-playground](https://eslint-online-playground.netlify.app/#eNp1jzEOwjAMRa9SeWFpYS8rOwtiIQxRalWBxIniFIFQ747bCASV2BK/Lz//J3AyG7xrHx2uLwwtWB9DytXKW2ZLfVP+q60iqGGN7CzlZCQbSNJPRVWlAO8ZqWMFbXWS3xxqE5rgvcyxU1BLKrqht9TS5oec67Kj0PcO+gI6MaZ9zDYUPEtnrfH6iIkFTHMFTmfkLLZ3gsOQDB4eEUvAh25w8p74qGiUTlGbq+6n9t+NOrztME4nkrG40M79/hgLbEqbZnHXRzu+APYwfks=)
## 💿 Install & Usage

@@ -16,3 +22,3 @@

- Requires Node.js `>=12.22.0`
- Requires Node.js `>=16.0.0`
- Requires ESLint `>=7.0.0`

@@ -22,3 +28,3 @@

**.eslintrc.json** (An example)
### **[.eslintrc.json](https://eslint.org/docs/latest/use/configure/configuration-files)** (An example)

@@ -29,15 +35,6 @@ ```jsonc

"parserOptions": {
// Only ESLint 6.2.0 and later support ES2020.
"ecmaVersion": 2020
"ecmaVersion": 2021
},
"rules": {
"n/exports-style": ["error", "module.exports"],
"n/file-extension-in-import": ["error", "always"],
"n/prefer-global/buffer": ["error", "always"],
"n/prefer-global/console": ["error", "always"],
"n/prefer-global/process": ["error", "always"],
"n/prefer-global/url-search-params": ["error", "always"],
"n/prefer-global/url": ["error", "always"],
"n/prefer-promises/dns": "error",
"n/prefer-promises/fs": "error"
"n/exports-style": ["error", "module.exports"]
}

@@ -47,2 +44,17 @@ }

### [`eslint.config.js`](https://eslint.org/docs/latest/use/configure/configuration-files-new) (requires eslint>=v8.23.0)
```js
const nodePlugin = require("eslint-plugin-n")
module.exports = [
nodePlugin.configs["flat/recommended-script"],
{
rules: {
"n/exports-style": ["error", "module.exports"]
}
}
]
```
**package.json** (An example)

@@ -61,2 +73,27 @@

### Configured Node.js version range
The rules get the supported Node.js version range from the following, falling back to the next if unspecified:
1. Rule configuration `version`
2. ESLint [shared setting](http://eslint.org/docs/user-guide/configuring.html#adding-shared-settings) `node.version`
3. `package.json` [`engines`] field
4. `>=16.0.0`
If you omit the [engines] field, this rule chooses `>=16.0.0` as the configured Node.js version since `16` is the maintained lts (see also [Node.js Release Working Group](https://github.com/nodejs/Release#readme)).
For Node.js packages, using the [`engines`] field is recommended because it's the official way to indicate support:
```json
{
"name": "your-module",
"version": "1.0.0",
"engines": {
"node": ">=16.0.0"
}
}
```
For [Shareable Configs](https://eslint.org/docs/latest/developer-guide/shareable-configs) or packages with a different development environment (e.g. pre-compiled, web package, etc.), you can configure ESLint with `settings.node.version` to specify support.
## 📖 Rules

@@ -67,77 +104,82 @@

💼 [Configurations](https://github.com/eslint-community/eslint-plugin-n#-configs) enabled in.\
✅ Set in the `recommended` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
☑️ Set in the `flat/recommended` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
🟢 Set in the `flat/recommended-module` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
✅ Set in the `flat/recommended-script` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
☑️ Set in the `recommended` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
🟢 Set in the `recommended-module` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
✅ Set in the `recommended-script` [configuration](https://github.com/eslint-community/eslint-plugin-n#-configs).\
🔧 Automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/user-guide/command-line-interface#--fix).\
❌ Deprecated.
### Best Practices
| Name                                  | Description | 💼 | 🔧 | ❌ |
| :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- | :-------------- | :- | :- |
| [callback-return](docs/rules/callback-return.md) | require `return` statements after callbacks | | | |
| [exports-style](docs/rules/exports-style.md) | enforce either `module.exports` or `exports` | | 🔧 | |
| [file-extension-in-import](docs/rules/file-extension-in-import.md) | enforce the style of file extensions in `import` declarations | | 🔧 | |
| [global-require](docs/rules/global-require.md) | require `require()` calls to be placed at top-level module scope | | | |
| [handle-callback-err](docs/rules/handle-callback-err.md) | require error handling in callbacks | | | |
| [no-callback-literal](docs/rules/no-callback-literal.md) | enforce Node.js-style error-first callback pattern is followed | | | |
| [no-deprecated-api](docs/rules/no-deprecated-api.md) | disallow deprecated APIs | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-exports-assign](docs/rules/no-exports-assign.md) | disallow the assignment to `exports` | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-extraneous-import](docs/rules/no-extraneous-import.md) | disallow `import` declarations which import extraneous modules | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-extraneous-require](docs/rules/no-extraneous-require.md) | disallow `require()` expressions which import extraneous modules | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-hide-core-modules](docs/rules/no-hide-core-modules.md) | disallow third-party modules which are hiding core modules | | | ❌ |
| [no-missing-import](docs/rules/no-missing-import.md) | disallow `import` declarations which import non-existence modules | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-missing-require](docs/rules/no-missing-require.md) | disallow `require()` expressions which import non-existence modules | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-mixed-requires](docs/rules/no-mixed-requires.md) | disallow `require` calls to be mixed with regular variable declarations | | | |
| [no-new-require](docs/rules/no-new-require.md) | disallow `new` operators with calls to `require` | | | |
| [no-path-concat](docs/rules/no-path-concat.md) | disallow string concatenation with `__dirname` and `__filename` | | | |
| [no-process-env](docs/rules/no-process-env.md) | disallow the use of `process.env` | | | |
| [no-process-exit](docs/rules/no-process-exit.md) | disallow the use of `process.exit()` | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-restricted-import](docs/rules/no-restricted-import.md) | disallow specified modules when loaded by `import` declarations | | | |
| [no-restricted-require](docs/rules/no-restricted-require.md) | disallow specified modules when loaded by `require` | | | |
| [no-sync](docs/rules/no-sync.md) | disallow synchronous methods | | | |
| [no-unpublished-bin](docs/rules/no-unpublished-bin.md) | disallow `bin` files that npm ignores | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-unpublished-import](docs/rules/no-unpublished-import.md) | disallow `import` declarations which import private modules | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-unpublished-require](docs/rules/no-unpublished-require.md) | disallow `require()` expressions which import private modules | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-unsupported-features](docs/rules/no-unsupported-features.md) | disallow unsupported ECMAScript features on the specified version | | | ❌ |
| [no-unsupported-features/es-builtins](docs/rules/no-unsupported-features/es-builtins.md) | disallow unsupported ECMAScript built-ins on the specified version | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-unsupported-features/es-syntax](docs/rules/no-unsupported-features/es-syntax.md) | disallow unsupported ECMAScript syntax on the specified version | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [no-unsupported-features/node-builtins](docs/rules/no-unsupported-features/node-builtins.md) | disallow unsupported Node.js built-in APIs on the specified version | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [prefer-global/buffer](docs/rules/prefer-global/buffer.md) | enforce either `Buffer` or `require("buffer").Buffer` | | | |
| [prefer-global/console](docs/rules/prefer-global/console.md) | enforce either `console` or `require("console")` | | | |
| [prefer-global/process](docs/rules/prefer-global/process.md) | enforce either `process` or `require("process")` | | | |
| [prefer-global/text-decoder](docs/rules/prefer-global/text-decoder.md) | enforce either `TextDecoder` or `require("util").TextDecoder` | | | |
| [prefer-global/text-encoder](docs/rules/prefer-global/text-encoder.md) | enforce either `TextEncoder` or `require("util").TextEncoder` | | | |
| [prefer-global/url](docs/rules/prefer-global/url.md) | enforce either `URL` or `require("url").URL` | | | |
| [prefer-global/url-search-params](docs/rules/prefer-global/url-search-params.md) | enforce either `URLSearchParams` or `require("url").URLSearchParams` | | | |
| [prefer-promises/dns](docs/rules/prefer-promises/dns.md) | enforce `require("dns").promises` | | | |
| [prefer-promises/fs](docs/rules/prefer-promises/fs.md) | enforce `require("fs").promises` | | | |
| [process-exit-as-throw](docs/rules/process-exit-as-throw.md) | require that `process.exit()` expressions use the same code path as `throw` | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | | |
| [shebang](docs/rules/shebang.md) | require correct usage of shebang | ☑️ 🟢 ✅ ☑️ 🟢 ✅ | 🔧 | |
| Name | Description | 💼 | 🔧 | ❌ |
| :--------------------------------------------------- | :----------------------- | :- | :- | :- |
| [no-deprecated-api](docs/rules/no-deprecated-api.md) | disallow deprecated APIs | ✅ | | |
<!-- end auto-generated rules list -->
### Possible Errors
## 🔧 Configs
| Name                                  | Description | 💼 | 🔧 | ❌ |
| :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- | :- | :- | :- |
| [handle-callback-err](docs/rules/handle-callback-err.md) | require error handling in callbacks | | | |
| [no-callback-literal](docs/rules/no-callback-literal.md) | enforce Node.js-style error-first callback pattern is followed | | | |
| [no-exports-assign](docs/rules/no-exports-assign.md) | disallow the assignment to `exports` | ✅ | | |
| [no-extraneous-import](docs/rules/no-extraneous-import.md) | disallow `import` declarations which import extraneous modules | ✅ | | |
| [no-extraneous-require](docs/rules/no-extraneous-require.md) | disallow `require()` expressions which import extraneous modules | ✅ | | |
| [no-hide-core-modules](docs/rules/no-hide-core-modules.md) | disallow third-party modules which are hiding core modules | | | ❌ |
| [no-missing-import](docs/rules/no-missing-import.md) | disallow `import` declarations which import non-existence modules | ✅ | | |
| [no-missing-require](docs/rules/no-missing-require.md) | disallow `require()` expressions which import non-existence modules | ✅ | | |
| [no-new-require](docs/rules/no-new-require.md) | disallow `new` operators with calls to `require` | | | |
| [no-path-concat](docs/rules/no-path-concat.md) | disallow string concatenation with `__dirname` and `__filename` | | | |
| [no-process-exit](docs/rules/no-process-exit.md) | disallow the use of `process.exit()` | ✅ | | |
| [no-unpublished-bin](docs/rules/no-unpublished-bin.md) | disallow `bin` files that npm ignores | ✅ | | |
| [no-unpublished-import](docs/rules/no-unpublished-import.md) | disallow `import` declarations which import private modules | ✅ | | |
| [no-unpublished-require](docs/rules/no-unpublished-require.md) | disallow `require()` expressions which import private modules | ✅ | | |
| [no-unsupported-features](docs/rules/no-unsupported-features.md) | disallow unsupported ECMAScript features on the specified version | | | ❌ |
| [no-unsupported-features/es-builtins](docs/rules/no-unsupported-features/es-builtins.md) | disallow unsupported ECMAScript built-ins on the specified version | ✅ | | |
| [no-unsupported-features/es-syntax](docs/rules/no-unsupported-features/es-syntax.md) | disallow unsupported ECMAScript syntax on the specified version | ✅ | | |
| [no-unsupported-features/node-builtins](docs/rules/no-unsupported-features/node-builtins.md) | disallow unsupported Node.js built-in APIs on the specified version | ✅ | | |
| [process-exit-as-throw](docs/rules/process-exit-as-throw.md) | require that `process.exit()` expressions use the same code path as `throw` | ✅ | | |
| [shebang](docs/rules/shebang.md) | require correct usage of shebang | ✅ | 🔧 | |
<!-- begin auto-generated configs list -->
### Stylistic Issues
| | Name |
| :- | :------------------------ |
| 🟠 | `flat/mixed-esm-and-cjs` |
| ☑️ | `flat/recommended` |
| 🟢 | `flat/recommended-module` |
| ✅ | `flat/recommended-script` |
| ☑️ | `recommended` |
| 🟢 | `recommended-module` |
| ✅ | `recommended-script` |
| Name                            | Description | 💼 | 🔧 | ❌ |
| :------------------------------------------------------------------------------- | :---------------------------------------------------------------------- | :- | :- | :- |
| [callback-return](docs/rules/callback-return.md) | require `return` statements after callbacks | | | |
| [exports-style](docs/rules/exports-style.md) | enforce either `module.exports` or `exports` | | 🔧 | |
| [file-extension-in-import](docs/rules/file-extension-in-import.md) | enforce the style of file extensions in `import` declarations | | 🔧 | |
| [global-require](docs/rules/global-require.md) | require `require()` calls to be placed at top-level module scope | | | |
| [no-mixed-requires](docs/rules/no-mixed-requires.md) | disallow `require` calls to be mixed with regular variable declarations | | | |
| [no-process-env](docs/rules/no-process-env.md) | disallow the use of `process.env` | | | |
| [no-restricted-import](docs/rules/no-restricted-import.md) | disallow specified modules when loaded by `import` declarations | | | |
| [no-restricted-require](docs/rules/no-restricted-require.md) | disallow specified modules when loaded by `require` | | | |
| [no-sync](docs/rules/no-sync.md) | disallow synchronous methods | | | |
| [prefer-global/buffer](docs/rules/prefer-global/buffer.md) | enforce either `Buffer` or `require("buffer").Buffer` | | | |
| [prefer-global/console](docs/rules/prefer-global/console.md) | enforce either `console` or `require("console")` | | | |
| [prefer-global/process](docs/rules/prefer-global/process.md) | enforce either `process` or `require("process")` | | | |
| [prefer-global/text-decoder](docs/rules/prefer-global/text-decoder.md) | enforce either `TextDecoder` or `require("util").TextDecoder` | | | |
| [prefer-global/text-encoder](docs/rules/prefer-global/text-encoder.md) | enforce either `TextEncoder` or `require("util").TextEncoder` | | | |
| [prefer-global/url](docs/rules/prefer-global/url.md) | enforce either `URL` or `require("url").URL` | | | |
| [prefer-global/url-search-params](docs/rules/prefer-global/url-search-params.md) | enforce either `URLSearchParams` or `require("url").URLSearchParams` | | | |
| [prefer-promises/dns](docs/rules/prefer-promises/dns.md) | enforce `require("dns").promises` | | | |
| [prefer-promises/fs](docs/rules/prefer-promises/fs.md) | enforce `require("fs").promises` | | | |
<!-- end auto-generated configs list -->
<!-- end auto-generated rules list -->
About each config:
## 🔧 Configs
- `recommended`: Considers both CommonJS and ES Modules. If [`"type":"module"` field](https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff#b023) existed in package.json then it considers files as ES Modules. Otherwise it considers files as CommonJS. In addition, it considers `*.mjs` files as ES Modules and `*.cjs` files as CommonJS.
- `recommended-module`: Considers all files as ES Modules.
- `recommended-script`: Considers all files as CommonJS.
This plugin provides three configs:
| Name | Description |
| :-- | :-- |
| `plugin:n/recommended` | Considers both CommonJS and ES Modules. If [`"type":"module"` field](https://medium.com/@nodejs/announcing-a-new-experimental-modules-1be8d2d6c2ff#b023) existed in package.json then it considers files as ES Modules. Otherwise it considers files as CommonJS. In addition, it considers `*.mjs` files as ES Modules and `*.cjs` files as CommonJS. |
| `plugin:n/recommended-module` | Considers all files as ES Modules. |
| `plugin:n/recommended-script` | Considers all files as CommonJS. |
These preset configs:
- enable [no-process-exit](http://eslint.org/docs/rules/no-process-exit) rule because [the official document](https://nodejs.org/api/process.html#process_process_exit_code) does not recommend a use of `process.exit()`.
- enable plugin rules which are given ✅ in the above table.
- add `{ecmaVersion: 2019}` and etc into `parserOptions`.
- enable plugin rules indicated by emojis in the [rules table](#-rules).
- add `{ecmaVersion: 2021}` and etc into `parserOptions`.
- add proper globals into `globals`.

@@ -151,2 +193,18 @@ - add this plugin into `plugins`.

- Q: How to use the flat eslint config with mixed commonjs and es modules?
- A: You can use the new exported flat config `flat/mixed-esm-and-cjs`, an example:
```js
const nodePlugin = require("eslint-plugin-n");
module.exports = [
...nodePlugin.configs["flat/mixed-esm-and-cjs"],
{
rules: {
"n/exports-style": ["error", "module.exports"],
},
},
]
```
## 🚥 Semantic Versioning Policy

@@ -178,3 +236,3 @@

- [GitHub Releases](https://github.com/weiran-zsd/eslint-plugin-node/releases)
- [GitHub Releases](https://github.com/eslint-community/eslint-plugin-n/releases)

@@ -181,0 +239,0 @@ ## ❤️ Contributing

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc