Save current BZZZ config-ui state before CHORUS branding update

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-08-19 00:19:00 +10:00
parent 6a6a49b7b1
commit c177363a19
16410 changed files with 1789161 additions and 230 deletions

View File

@@ -0,0 +1,15 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "lcov", "text", "html", "json"],
"instrument": false,
"exclude": [
"coverage",
"test",
"tests",
"resolvers/*/test",
"scripts",
"memo-parser",
"lib"
]
}

View File

@@ -0,0 +1,253 @@
# Change Log
All notable changes to this module will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/).
This change log adheres to standards from [Keep a CHANGELOG](https://keepachangelog.com).
## Unreleased
## v2.12.1 - 2025-06-19
### Fixed
- `unambiguous`: detect modules exported from minified code ([#3124], thanks [@michaelfaith])
### Changed
- [refactor] `parse`: avoid using a regex here (thanks [@ljharb])
## v2.12.0 - 2024-09-26
### Added
- `hash`: add support for hashing functions ([#3072], thanks [@michaelfaith])
## v2.11.1 - 2024-09-23
### Fixed
- `parse`: remove unneeded extra backticks ([#3057], thanks [@G-Rath])
- `parse`: espree parser isn't working with flat config ([#3061], thanks [@michaelfaith])
- `parse`: add `ecmaVersion` and `sourceType` to `parserOptions` ([#3061], thanks [@michaelfaith])
## v2.11.0 - 2024-09-05
### New
- `declaredScope`: take a `node` for modern eslint versions (thanks [@michaelfaith])
## v2.10.0 - 2024-09-05
### New
- add context compatibility helpers ([#3049], thanks [@michaelfaith])
## v2.9.0 - 2024-09-02
### New
- add support for Flat Config ([#3018], thanks [@michaelfaith])
## v2.8.2 - 2024-08-25
### Fixed
- `parse`: also delete `parserOptions.projectService` ([#3039], thanks [@Mysak0CZ])
### Changed
- [types] use shared config (thanks [@ljharb])
- [meta] add `exports`, `main`
- [meta] add `repository.directory` field
- [refactor] avoid hoisting
## v2.8.1 - 2024-02-26
### Fixed
- `parse`: also delete `parserOptions.EXPERIMENTAL_useProjectService` ([#2963], thanks [@JoshuaKGoldberg])
### Changed
- add types (thanks [@ljharb])
## v2.8.0 - 2023-04-14
### New
- `parse`: support flat config ([#2714], thanks [@DMartens])
### Fixed
- Improve performance of `fullResolve` for large projects ([#2755], thanks [@leipert])
## v2.7.4 - 2022-08-11
### Fixed
- [Fix] Ignore hashbang and BOM while parsing ([#2431], thanks [@silverwind])
### Changed
- [patch] mark eslint as an optional peer dep ([#2523], thanks [@wmertens])
## v2.7.3 - 2022-01-26
### Fixed
- `parse`: restore compatibility by making the return value `ast` again ([#2350], thanks [@ljharb])
## v2.7.2 - 2022-01-01
### Fixed
- [patch] Fix `@babel/eslint-parser` 8 compatibility ([#2343], thanks [@nicolo-ribaudo])
### Changed
- [Refactor] inline `pkgDir` implementation; remove `pkg-dir`
## v2.7.1 - 2021-10-13
### Fixed
- fixed SyntaxError in node <= 6: Unexpected token ) in parse.js ([#2261], thanks [@VitusFW])
## v2.7.0 - 2021-10-11
### Added
- `fileExistsWithCaseSync`: add `strict` argument ([#1262], thanks [@sergei-startsev])
- add `visit`, to support dynamic imports ([#1660], [#2212], thanks [@maxkomarychev], [@aladdin-add], [@Hypnosphi])
- create internal replacement for `pkg-up` and `read-pkg-up` ([#2047], [@mgwalker])
## v2.6.2 - 2021-08-08
### Fixed
- Use `context.getPhysicalFilename()` when available (ESLint 7.28+) ([#2160], thanks [@pmcelhaney])
## v2.6.1 - 2021-05-13
### Fixed
- `no-unresolved`: check `import()` ([#2026], thanks [@aladdin-add])
- Add fix for Windows Subsystem for Linux ([#1786], thanks [@manuth])
### Changed
- [deps] update `debug`
- [Refactor] use `Array.isArray` instead of `instanceof Array`
## v2.6.0 - 2020-03-28
### Added
- Print more helpful info if parsing fails ([#1671], thanks [@kaiyoma])
## v2.5.2 - 2020-01-12
### Fixed
- Makes the loader resolution more tolerant ([#1606], thanks [@arcanis])
- Use `createRequire` instead of `createRequireFromPath` if available ([#1602], thanks [@iamnapo])
## v2.5.1 - 2020-01-11
### Fixed
- Uses createRequireFromPath to resolve loaders ([#1591], thanks [@arcanis])
- report the error stack on a resolution error ([#599], thanks [@sompylasar])
## v2.5.0 - 2019-12-07
### Added
- support `parseForESLint` from custom parser ([#1435], thanks [@JounQin])
### Changed
- Avoid superfluous calls and code ([#1551], thanks [@brettz9])
## v2.4.1 - 2019-07-19
### Fixed
- Improve parse perf when using `@typescript-eslint/parser` ([#1409], thanks [@bradzacher])
- Improve support for TypeScript declare structures ([#1356], thanks [@christophercurrie])
## v2.4.0 - 2019-04-13
### Added
- no-useless-path-segments: Add noUselessIndex option ([#1290], thanks [@timkraut])
### Fixed
- Fix overwriting of dynamic import() CallExpression ([`no-cycle`], [`no-relative-parent-import`], [`no-unresolved`], [`no-useless-path-segments`]) ([#1218], [#1166], [#1035], thanks [@vikr01])
## v2.3.0 - 2019-01-22
### Fixed
- use `process.hrtime()` for cache dates ([#1160], thanks [@hulkish])
## v2.2.0 - 2018-03-29
### Changed
- `parse`: attach node locations by default.
- `moduleVisitor`: visitor now gets the full `import` statement node as a second
argument, so rules may report against the full statement / `require` call instead
of only the string literal node.
## v2.1.1 - 2017-06-22
Re-releasing v2.1.0 after vetting (again) and unable to reproduce issue.
## v2.1.0 - 2017-06-02 [YANKED]
Yanked due to critical issue with cache key resulting from #839.
### Added
- `parse` now additionally passes `filePath` to `parser` in `parserOptions` like `eslint` core does
## v2.0.0 - 2016-11-07
### Changed
- `unambiguous` no longer exposes fast test regex
### Fixed
- `unambiguous.test()` regex is now properly in multiline mode
[#3124]: https://github.com/import-js/eslint-plugin-import/pull/3124
[#3072]: https://github.com/import-js/eslint-plugin-import/pull/3072
[#3061]: https://github.com/import-js/eslint-plugin-import/pull/3061
[#3057]: https://github.com/import-js/eslint-plugin-import/pull/3057
[#3049]: https://github.com/import-js/eslint-plugin-import/pull/3049
[#3039]: https://github.com/import-js/eslint-plugin-import/pull/3039
[#3018]: https://github.com/import-js/eslint-plugin-import/pull/3018
[#2963]: https://github.com/import-js/eslint-plugin-import/pull/2963
[#2755]: https://github.com/import-js/eslint-plugin-import/pull/2755
[#2714]: https://github.com/import-js/eslint-plugin-import/pull/2714
[#2523]: https://github.com/import-js/eslint-plugin-import/pull/2523
[#2431]: https://github.com/import-js/eslint-plugin-import/pull/2431
[#2350]: https://github.com/import-js/eslint-plugin-import/issues/2350
[#2343]: https://github.com/import-js/eslint-plugin-import/pull/2343
[#2261]: https://github.com/import-js/eslint-plugin-import/pull/2261
[#2212]: https://github.com/import-js/eslint-plugin-import/pull/2212
[#2160]: https://github.com/import-js/eslint-plugin-import/pull/2160
[#2047]: https://github.com/import-js/eslint-plugin-import/pull/2047
[#2026]: https://github.com/import-js/eslint-plugin-import/pull/2026
[#1786]: https://github.com/import-js/eslint-plugin-import/pull/1786
[#1671]: https://github.com/import-js/eslint-plugin-import/pull/1671
[#1660]: https://github.com/import-js/eslint-plugin-import/pull/1660
[#1606]: https://github.com/import-js/eslint-plugin-import/pull/1606
[#1602]: https://github.com/import-js/eslint-plugin-import/pull/1602
[#1591]: https://github.com/import-js/eslint-plugin-import/pull/1591
[#1551]: https://github.com/import-js/eslint-plugin-import/pull/1551
[#1435]: https://github.com/import-js/eslint-plugin-import/pull/1435
[#1409]: https://github.com/import-js/eslint-plugin-import/pull/1409
[#1356]: https://github.com/import-js/eslint-plugin-import/pull/1356
[#1290]: https://github.com/import-js/eslint-plugin-import/pull/1290
[#1262]: https://github.com/import-js/eslint-plugin-import/pull/1262
[#1218]: https://github.com/import-js/eslint-plugin-import/pull/1218
[#1166]: https://github.com/import-js/eslint-plugin-import/issues/1166
[#1160]: https://github.com/import-js/eslint-plugin-import/pull/1160
[#1035]: https://github.com/import-js/eslint-plugin-import/issues/1035
[#599]: https://github.com/import-js/eslint-plugin-import/pull/599
[@aladdin-add]: https://github.com/aladdin-add
[@arcanis]: https://github.com/arcanis
[@bradzacher]: https://github.com/bradzacher
[@brettz9]: https://github.com/brettz9
[@christophercurrie]: https://github.com/christophercurrie
[@DMartens]: https://github.com/DMartens
[@G-Rath]: https://github.com/G-Rath
[@hulkish]: https://github.com/hulkish
[@Hypnosphi]: https://github.com/Hypnosphi
[@iamnapo]: https://github.com/iamnapo
[@JoshuaKGoldberg]: https://github.com/JoshuaKGoldberg
[@JounQin]: https://github.com/JounQin
[@kaiyoma]: https://github.com/kaiyoma
[@leipert]: https://github.com/leipert
[@ljharb]: https://github.com/ljharb
[@manuth]: https://github.com/manuth
[@maxkomarychev]: https://github.com/maxkomarychev
[@mgwalker]: https://github.com/mgwalker
[@michaelfaith]: https://github.com/michaelfaith
[@Mysak0CZ]: https://github.com/Mysak0CZ
[@nicolo-ribaudo]: https://github.com/nicolo-ribaudo
[@pmcelhaney]: https://github.com/pmcelhaney
[@sergei-startsev]: https://github.com/sergei-startsev
[@silverwind]: https://github.com/silverwind
[@sompylasar]: https://github.com/sompylasar
[@timkraut]: https://github.com/timkraut
[@vikr01]: https://github.com/vikr01
[@VitusFW]: https://github.com/VitusFW
[@wmertens]: https://github.com/wmertens

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Ben Mosher
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,22 @@
import type { ESLintSettings } from "./types";
export type CacheKey = unknown;
export type CacheObject = {
result: unknown;
lastSeen: ReturnType<typeof process.hrtime>;
};
declare class ModuleCache {
map: Map<CacheKey, CacheObject>;
constructor(map?: Map<CacheKey, CacheObject>);
get<T>(cacheKey: CacheKey, settings: ESLintSettings): T | undefined;
set<T>(cacheKey: CacheKey, result: T): T;
static getSettings(settings: ESLintSettings): { lifetime: number } & Omit<ESLintSettings['import/cache'], 'lifetime'>;
}
export default ModuleCache;
export type { ModuleCache }

View File

@@ -0,0 +1,52 @@
'use strict';
exports.__esModule = true;
const log = require('debug')('eslint-module-utils:ModuleCache');
/** @type {import('./ModuleCache').ModuleCache} */
class ModuleCache {
/** @param {typeof import('./ModuleCache').ModuleCache.prototype.map} map */
constructor(map) {
this.map = map || /** @type {{typeof import('./ModuleCache').ModuleCache.prototype.map} */ new Map();
}
/** @type {typeof import('./ModuleCache').ModuleCache.prototype.set} */
set(cacheKey, result) {
this.map.set(cacheKey, { result, lastSeen: process.hrtime() });
log('setting entry for', cacheKey);
return result;
}
/** @type {typeof import('./ModuleCache').ModuleCache.prototype.get} */
get(cacheKey, settings) {
if (this.map.has(cacheKey)) {
const f = this.map.get(cacheKey);
// check freshness
// @ts-expect-error TS can't narrow properly from `has` and `get`
if (process.hrtime(f.lastSeen)[0] < settings.lifetime) { return f.result; }
} else {
log('cache miss for', cacheKey);
}
// cache miss
return undefined;
}
/** @type {typeof import('./ModuleCache').ModuleCache.getSettings} */
static getSettings(settings) {
/** @type {ReturnType<typeof ModuleCache.getSettings>} */
const cacheSettings = Object.assign({
lifetime: 30, // seconds
}, settings['import/cache']);
// parse infinity
// @ts-expect-error the lack of type overlap is because we're abusing `cacheSettings` as a temporary object
if (cacheSettings.lifetime === '∞' || cacheSettings.lifetime === 'Infinity') {
cacheSettings.lifetime = Infinity;
}
return cacheSettings;
}
}
exports.default = ModuleCache;

View File

@@ -0,0 +1,38 @@
import { Scope, SourceCode, Rule } from 'eslint';
import * as ESTree from 'estree';
type LegacyContext = {
getFilename: () => string,
getPhysicalFilename: () => string,
getSourceCode: () => SourceCode,
getScope: never,
getAncestors: never,
getDeclaredVariables: never,
};
type NewContext = {
filename: string,
sourceCode: SourceCode,
getPhysicalFilename?: () => string,
getScope: () => Scope.Scope,
getAncestors: () => ESTree.Node[],
getDeclaredVariables: (node: ESTree.Node) => Scope.Variable[],
};
export type Context = LegacyContext | NewContext | Rule.RuleContext;
declare function getAncestors(context: Context, node: ESTree.Node): ESTree.Node[];
declare function getDeclaredVariables(context: Context, node: ESTree.Node): Scope.Variable[];
declare function getFilename(context: Context): string;
declare function getPhysicalFilename(context: Context): string;
declare function getScope(context: Context, node: ESTree.Node): Scope.Scope;
declare function getSourceCode(context: Context): SourceCode;
export {
getAncestors,
getDeclaredVariables,
getFilename,
getPhysicalFilename,
getScope,
getSourceCode,
};

View File

@@ -0,0 +1,72 @@
'use strict';
exports.__esModule = true;
/** @type {import('./contextCompat').getAncestors} */
function getAncestors(context, node) {
const sourceCode = getSourceCode(context);
if (sourceCode && sourceCode.getAncestors) {
return sourceCode.getAncestors(node);
}
return context.getAncestors();
}
/** @type {import('./contextCompat').getDeclaredVariables} */
function getDeclaredVariables(context, node) {
const sourceCode = getSourceCode(context);
if (sourceCode && sourceCode.getDeclaredVariables) {
return sourceCode.getDeclaredVariables(node);
}
return context.getDeclaredVariables(node);
}
/** @type {import('./contextCompat').getFilename} */
function getFilename(context) {
if ('filename' in context) {
return context.filename;
}
return context.getFilename();
}
/** @type {import('./contextCompat').getPhysicalFilename} */
function getPhysicalFilename(context) {
if (context.getPhysicalFilename) {
return context.getPhysicalFilename();
}
return getFilename(context);
}
/** @type {import('./contextCompat').getScope} */
function getScope(context, node) {
const sourceCode = getSourceCode(context);
if (sourceCode && sourceCode.getScope) {
return sourceCode.getScope(node);
}
return context.getScope();
}
/** @type {import('./contextCompat').getSourceCode} */
function getSourceCode(context) {
if ('sourceCode' in context) {
return context.sourceCode;
}
return context.getSourceCode();
}
module.exports = {
getAncestors,
getDeclaredVariables,
getFilename,
getPhysicalFilename,
getScope,
getSourceCode,
};

View File

@@ -0,0 +1,10 @@
import { Rule, Scope } from 'eslint';
import * as ESTree from 'estree';
declare function declaredScope(
context: Rule.RuleContext,
name: string,
node?: ESTree.Node,
): Scope.Scope['type'] | undefined;
export default declaredScope;

View File

@@ -0,0 +1,13 @@
'use strict';
exports.__esModule = true;
const { getScope } = require('./contextCompat');
/** @type {import('./declaredScope').default} */
exports.default = function declaredScope(context, name, node) {
const references = (node ? getScope(context, node) : context.getScope()).references;
const reference = references.find((x) => x.identifier.name === name);
if (!reference || !reference.resolved) { return undefined; }
return reference.resolved.scope.type;
};

View File

@@ -0,0 +1,14 @@
import type { Hash } from 'crypto';
declare function hashArray(value: Array<unknown>, hash?: Hash): Hash;
declare function hashObject<T extends object>(value: T, hash?: Hash): Hash;
declare function hashify(
value: Array<unknown> | object | unknown,
hash?: Hash,
): Hash;
export default hashify;
export { hashArray, hashObject };

View File

@@ -0,0 +1,66 @@
/**
* utilities for hashing config objects.
* basically iteratively updates hash with a JSON-like format
*/
'use strict';
exports.__esModule = true;
const createHash = require('crypto').createHash;
const stringify = JSON.stringify;
/** @type {import('./hash').default} */
function hashify(value, hash) {
if (!hash) { hash = createHash('sha256'); }
if (Array.isArray(value)) {
hashArray(value, hash);
} else if (typeof value === 'function') {
hash.update(String(value));
} else if (value instanceof Object) {
hashObject(value, hash);
} else {
hash.update(stringify(value) || 'undefined');
}
return hash;
}
exports.default = hashify;
/** @type {import('./hash').hashArray} */
function hashArray(array, hash) {
if (!hash) { hash = createHash('sha256'); }
hash.update('[');
for (let i = 0; i < array.length; i++) {
hashify(array[i], hash);
hash.update(',');
}
hash.update(']');
return hash;
}
hashify.array = hashArray;
exports.hashArray = hashArray;
/** @type {import('./hash').hashObject} */
function hashObject(object, optionalHash) {
const hash = optionalHash || createHash('sha256');
hash.update('{');
Object.keys(object).sort().forEach((key) => {
hash.update(stringify(key));
hash.update(':');
// @ts-expect-error the key is guaranteed to exist on the object here
hashify(object[key], hash);
hash.update(',');
});
hash.update('}');
return hash;
}
hashify.object = hashObject;
exports.hashObject = hashObject;

View File

@@ -0,0 +1,12 @@
import { Rule } from 'eslint';
import type { ESLintSettings, Extension } from './types';
declare function ignore(path: string, context: Rule.RuleContext): boolean;
declare function getFileExtensions(settings: ESLintSettings): Set<Extension>;
declare function hasValidExtension(path: string, context: Rule.RuleContext): path is `${string}${Extension}`;
export default ignore;
export { getFileExtensions, hasValidExtension }

View File

@@ -0,0 +1,73 @@
'use strict';
exports.__esModule = true;
const extname = require('path').extname;
const log = require('debug')('eslint-plugin-import:utils:ignore');
// one-shot memoized
/** @type {Set<import('./types').Extension>} */ let cachedSet;
/** @type {import('./types').ESLintSettings} */ let lastSettings;
/** @type {import('./ignore').getFileExtensions} */
function makeValidExtensionSet(settings) {
// start with explicit JS-parsed extensions
/** @type {Set<import('./types').Extension>} */
const exts = new Set(settings['import/extensions'] || ['.js', '.mjs', '.cjs']);
// all alternate parser extensions are also valid
if ('import/parsers' in settings) {
for (const parser in settings['import/parsers']) {
const parserSettings = settings['import/parsers'][parser];
if (!Array.isArray(parserSettings)) {
throw new TypeError('"settings" for ' + parser + ' must be an array');
}
parserSettings.forEach((ext) => exts.add(ext));
}
}
return exts;
}
exports.getFileExtensions = makeValidExtensionSet;
/** @type {(context: import('eslint').Rule.RuleContext) => Set<import('./types').Extension>} */
function validExtensions(context) {
if (cachedSet && context.settings === lastSettings) {
return cachedSet;
}
lastSettings = context.settings;
cachedSet = makeValidExtensionSet(context.settings);
return cachedSet;
}
/** @type {import('./ignore').hasValidExtension} */
function hasValidExtension(path, context) {
// eslint-disable-next-line no-extra-parens
return validExtensions(context).has(/** @type {import('./types').Extension} */ (extname(path)));
}
exports.hasValidExtension = hasValidExtension;
/** @type {import('./ignore').default} */
exports.default = function ignore(path, context) {
// check extension whitelist first (cheap)
if (!hasValidExtension(path, context)) {
return true;
}
if (!('import/ignore' in context.settings)) {
return false;
}
const ignoreStrings = context.settings['import/ignore'];
for (let i = 0; i < ignoreStrings.length; i++) {
const regex = new RegExp(ignoreStrings[i]);
if (regex.test(path)) {
log(`ignoring ${path}, matched pattern /${ignoreStrings[i]}/`);
return true;
}
}
return false;
};

View File

@@ -0,0 +1,3 @@
declare function moduleRequire<T>(p: string): T;
export default moduleRequire;

View File

@@ -0,0 +1,36 @@
'use strict';
exports.__esModule = true;
const Module = require('module');
const path = require('path');
// borrowed from babel-eslint
/** @type {(filename: string) => Module} */
function createModule(filename) {
const mod = new Module(filename);
mod.filename = filename;
// @ts-expect-error _nodeModulesPaths are undocumented
mod.paths = Module._nodeModulePaths(path.dirname(filename));
return mod;
}
/** @type {import('./module-require').default} */
exports.default = function moduleRequire(p) {
try {
// attempt to get espree relative to eslint
const eslintPath = require.resolve('eslint');
const eslintModule = createModule(eslintPath);
// @ts-expect-error _resolveFilename is undocumented
return require(Module._resolveFilename(p, eslintModule));
} catch (err) { /* ignore */ }
try {
// try relative to entry point
// @ts-expect-error TODO: figure out what this is
return require.main.require(p);
} catch (err) { /* ignore */ }
// finally, try from here
return require(p);
};

View File

@@ -0,0 +1,26 @@
import type { Rule } from 'eslint';
import type { Node } from 'estree';
type Visitor = (source: Node, importer: unknown) => any;
type Options = {
amd?: boolean;
commonjs?: boolean;
esmodule?: boolean;
ignore?: string[];
};
declare function moduleVisitor(
visitor: Visitor,
options?: Options,
): object;
export default moduleVisitor;
export type Schema = NonNullable<Rule.RuleModule['schema']>;
declare function makeOptionsSchema(additionalProperties?: Partial<Schema>): Schema
declare const optionsSchema: Schema;
export { makeOptionsSchema, optionsSchema };

View File

@@ -0,0 +1,164 @@
'use strict';
exports.__esModule = true;
/** @typedef {import('estree').Node} Node */
/** @typedef {{ arguments: import('estree').CallExpression['arguments'], callee: Node }} Call */
/** @typedef {import('estree').ImportDeclaration | import('estree').ExportNamedDeclaration | import('estree').ExportAllDeclaration} Declaration */
/**
* Returns an object of node visitors that will call
* 'visitor' with every discovered module path.
*
* @type {(import('./moduleVisitor').default)}
*/
exports.default = function visitModules(visitor, options) {
const ignore = options && options.ignore;
const amd = !!(options && options.amd);
const commonjs = !!(options && options.commonjs);
// if esmodule is not explicitly disabled, it is assumed to be enabled
const esmodule = !!Object.assign({ esmodule: true }, options).esmodule;
const ignoreRegExps = ignore == null ? [] : ignore.map((p) => new RegExp(p));
/** @type {(source: undefined | null | import('estree').Literal, importer: Parameters<typeof visitor>[1]) => void} */
function checkSourceValue(source, importer) {
if (source == null) { return; } //?
// handle ignore
if (ignoreRegExps.some((re) => re.test(String(source.value)))) { return; }
// fire visitor
visitor(source, importer);
}
// for import-y declarations
/** @type {(node: Declaration) => void} */
function checkSource(node) {
checkSourceValue(node.source, node);
}
// for esmodule dynamic `import()` calls
/** @type {(node: import('estree').ImportExpression | import('estree').CallExpression) => void} */
function checkImportCall(node) {
/** @type {import('estree').Expression | import('estree').Literal | import('estree').CallExpression['arguments'][0]} */
let modulePath;
// refs https://github.com/estree/estree/blob/HEAD/es2020.md#importexpression
if (node.type === 'ImportExpression') {
modulePath = node.source;
} else if (node.type === 'CallExpression') {
// @ts-expect-error this structure is from an older version of eslint
if (node.callee.type !== 'Import') { return; }
if (node.arguments.length !== 1) { return; }
modulePath = node.arguments[0];
} else {
throw new TypeError('this should be unreachable');
}
if (modulePath.type !== 'Literal') { return; }
if (typeof modulePath.value !== 'string') { return; }
checkSourceValue(modulePath, node);
}
// for CommonJS `require` calls
// adapted from @mctep: https://git.io/v4rAu
/** @type {(call: Call) => void} */
function checkCommon(call) {
if (call.callee.type !== 'Identifier') { return; }
if (call.callee.name !== 'require') { return; }
if (call.arguments.length !== 1) { return; }
const modulePath = call.arguments[0];
if (modulePath.type !== 'Literal') { return; }
if (typeof modulePath.value !== 'string') { return; }
checkSourceValue(modulePath, call);
}
/** @type {(call: Call) => void} */
function checkAMD(call) {
if (call.callee.type !== 'Identifier') { return; }
if (call.callee.name !== 'require' && call.callee.name !== 'define') { return; }
if (call.arguments.length !== 2) { return; }
const modules = call.arguments[0];
if (modules.type !== 'ArrayExpression') { return; }
for (const element of modules.elements) {
if (!element) { continue; }
if (element.type !== 'Literal') { continue; }
if (typeof element.value !== 'string') { continue; }
if (
element.value === 'require'
|| element.value === 'exports'
) {
continue; // magic modules: https://github.com/requirejs/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#magic-modules
}
checkSourceValue(element, element);
}
}
const visitors = {};
if (esmodule) {
Object.assign(visitors, {
ImportDeclaration: checkSource,
ExportNamedDeclaration: checkSource,
ExportAllDeclaration: checkSource,
CallExpression: checkImportCall,
ImportExpression: checkImportCall,
});
}
if (commonjs || amd) {
const currentCallExpression = visitors.CallExpression;
visitors.CallExpression = /** @type {(call: Call) => void} */ function (call) {
if (currentCallExpression) { currentCallExpression(call); }
if (commonjs) { checkCommon(call); }
if (amd) { checkAMD(call); }
};
}
return visitors;
};
/**
* make an options schema for the module visitor, optionally adding extra fields.
* @type {import('./moduleVisitor').makeOptionsSchema}
*/
function makeOptionsSchema(additionalProperties) {
/** @type {import('./moduleVisitor').Schema} */
const base = {
type: 'object',
properties: {
commonjs: { type: 'boolean' },
amd: { type: 'boolean' },
esmodule: { type: 'boolean' },
ignore: {
type: 'array',
minItems: 1,
items: { type: 'string' },
uniqueItems: true,
},
},
additionalProperties: false,
};
if (additionalProperties) {
for (const key in additionalProperties) {
// @ts-expect-error TS always has trouble with arbitrary object assignment/mutation
base.properties[key] = additionalProperties[key];
}
}
return base;
}
exports.makeOptionsSchema = makeOptionsSchema;
/**
* json schema object for options parameter. can be used to build rule options schema object.
*/
exports.optionsSchema = makeOptionsSchema();

View File

@@ -0,0 +1,395 @@
3.1.0 / 2017-09-26
==================
* Add `DEBUG_HIDE_DATE` env var (#486)
* Remove ReDoS regexp in %o formatter (#504)
* Remove "component" from package.json
* Remove `component.json`
* Ignore package-lock.json
* Examples: fix colors printout
* Fix: browser detection
* Fix: spelling mistake (#496, @EdwardBetts)
3.0.1 / 2017-08-24
==================
* Fix: Disable colors in Edge and Internet Explorer (#489)
3.0.0 / 2017-08-08
==================
* Breaking: Remove DEBUG_FD (#406)
* Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418)
* Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408)
* Addition: document `enabled` flag (#465)
* Addition: add 256 colors mode (#481)
* Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440)
* Update: component: update "ms" to v2.0.0
* Update: separate the Node and Browser tests in Travis-CI
* Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots
* Update: separate Node.js and web browser examples for organization
* Update: update "browserify" to v14.4.0
* Fix: fix Readme typo (#473)
2.6.9 / 2017-09-22
==================
* remove ReDoS regexp in %o formatter (#504)
2.6.8 / 2017-05-18
==================
* Fix: Check for undefined on browser globals (#462, @marbemac)
2.6.7 / 2017-05-16
==================
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
* Fix: Inline extend function in node implementation (#452, @dougwilson)
* Docs: Fix typo (#455, @msasad)
2.6.5 / 2017-04-27
==================
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
* Misc: clean up browser reference checks (#447, @thebigredgeek)
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
2.6.4 / 2017-04-20
==================
* Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
* Misc: update "ms" to v0.7.3 (@tootallnate)
2.6.3 / 2017-03-13
==================
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
* Docs: Changelog fix (@thebigredgeek)
2.6.2 / 2017-03-10
==================
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
* Docs: Add Slackin invite badge (@tootallnate)
2.6.1 / 2017-02-10
==================
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
* Fix: Namespaces would not disable once enabled (#409, @musikov)
2.6.0 / 2016-12-28
==================
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
2.5.2 / 2016-12-25
==================
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
* Docs: fixed README typo (#391, @lurch)
* Docs: added notice about v3 api discussion (@thebigredgeek)
2.5.1 / 2016-12-20
==================
* Fix: babel-core compatibility
2.5.0 / 2016-12-20
==================
* Fix: wrong reference in bower file (@thebigredgeek)
* Fix: webworker compatibility (@thebigredgeek)
* Fix: output formatting issue (#388, @kribblo)
* Fix: babel-loader compatibility (#383, @escwald)
* Misc: removed built asset from repo and publications (@thebigredgeek)
* Misc: moved source files to /src (#378, @yamikuronue)
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
* Test: coveralls integration (#378, @yamikuronue)
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
2.4.5 / 2016-12-17
==================
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
* Fix: custom log function (#379, @hsiliev)
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
2.4.4 / 2016-12-14
==================
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
2.4.3 / 2016-12-14
==================
* Fix: navigation.userAgent error for react native (#364, @escwald)
2.4.2 / 2016-12-14
==================
* Fix: browser colors (#367, @tootallnate)
* Misc: travis ci integration (@thebigredgeek)
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
2.4.1 / 2016-12-13
==================
* Fix: typo that broke the package (#356)
2.4.0 / 2016-12-13
==================
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)
2.3.3 / 2016-11-09
==================
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
2.3.2 / 2016-11-09
==================
* Fix: be super-safe in index.js as well (@TooTallNate)
* Fix: should check whether process exists (Tom Newby)
2.3.1 / 2016-11-09
==================
* Fix: Added electron compatibility (#324, @paulcbetts)
* Improvement: Added performance optimizations (@tootallnate)
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
2.3.0 / 2016-11-07
==================
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
* Readme: fix USE_COLORS to DEBUG_COLORS
* Readme: Doc fixes for format string sugar (#269, @mlucool)
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
* Readme: better docs for browser support (#224, @matthewmueller)
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
* Misc: Updated contributors (@thebigredgeek)
2.2.0 / 2015-05-09
==================
* package: update "ms" to v0.7.1 (#202, @dougwilson)
* README: add logging to file example (#193, @DanielOchoa)
* README: fixed a typo (#191, @amir-s)
* browser: expose `storage` (#190, @stephenmathieson)
* Makefile: add a `distclean` target (#189, @stephenmathieson)
2.1.3 / 2015-03-13
==================
* Updated stdout/stderr example (#186)
* Updated example/stdout.js to match debug current behaviour
* Renamed example/stderr.js to stdout.js
* Update Readme.md (#184)
* replace high intensity foreground color for bold (#182, #183)
2.1.2 / 2015-03-01
==================
* dist: recompile
* update "ms" to v0.7.0
* package: update "browserify" to v9.0.3
* component: fix "ms.js" repo location
* changed bower package name
* updated documentation about using debug in a browser
* fix: security error on safari (#167, #168, @yields)
2.1.1 / 2014-12-29
==================
* browser: use `typeof` to check for `console` existence
* browser: check for `console.log` truthiness (fix IE 8/9)
* browser: add support for Chrome apps
* Readme: added Windows usage remarks
* Add `bower.json` to properly support bower install
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release

View File

@@ -0,0 +1,19 @@
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,437 @@
# debug
[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1 @@
module.exports = require('./src/node');

View File

@@ -0,0 +1,51 @@
{
"name": "debug",
"version": "3.2.7",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"description": "small debugging utility",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"node.js",
"dist/debug.js",
"LICENSE",
"README.md"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"contributors": [
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"dependencies": {
"ms": "^2.1.1"
},
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"browserify": "14.4.0",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.0.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"xo": "^0.23.0"
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"unpkg": "./dist/debug.js"
}

View File

@@ -0,0 +1,180 @@
"use strict";
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
/**
* Colors.
*/
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
} // Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
} // Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
var _console;
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.getItem('debug');
} catch (error) {} // Swallow
// XXX (@Qix-) should we be logging these?
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};

View File

@@ -0,0 +1,249 @@
"use strict";
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
// Disabled?
if (!debug.enabled) {
return;
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var self = debug; // Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
} // Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
}); // Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend; // Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
createDebug.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

View File

@@ -0,0 +1,12 @@
"use strict";
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

View File

@@ -0,0 +1,177 @@
"use strict";
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
var supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221];
}
} catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be.
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// Camel-case
var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) {
return k.toUpperCase();
}); // Coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
var name = this.namespace,
useColors = this.useColors;
if (useColors) {
var c = this.color;
var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c);
var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m");
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log() {
return process.stderr.write(util.format.apply(util, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
var keys = Object.keys(exports.inspectOpts);
for (var i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(function (str) { return str.trim(); })
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

View File

@@ -0,0 +1,83 @@
{
"name": "eslint-module-utils",
"version": "2.12.1",
"description": "Core utilities to support eslint-plugin-import and other module-related plugins.",
"engines": {
"node": ">=4"
},
"main": false,
"exports": {
"./contextCompat": "./contextCompat.js",
"./ModuleCache": "./ModuleCache.js",
"./ModuleCache.js": "./ModuleCache.js",
"./declaredScope": "./declaredScope.js",
"./declaredScope.js": "./declaredScope.js",
"./hash": "./hash.js",
"./hash.js": "./hash.js",
"./ignore": "./ignore.js",
"./ignore.js": "./ignore.js",
"./module-require": "./module-require.js",
"./module-require.js": "./module-require.js",
"./moduleVisitor": "./moduleVisitor.js",
"./moduleVisitor.js": "./moduleVisitor.js",
"./parse": "./parse.js",
"./parse.js": "./parse.js",
"./pkgDir": "./pkgDir.js",
"./pkgDir.js": "./pkgDir.js",
"./pkgUp": "./pkgUp.js",
"./pkgUp.js": "./pkgUp.js",
"./readPkgUp": "./readPkgUp.js",
"./readPkgUp.js": "./readPkgUp.js",
"./resolve": "./resolve.js",
"./resolve.js": "./resolve.js",
"./unambiguous": "./unambiguous.js",
"./unambiguous.js": "./unambiguous.js",
"./visit": "./visit.js",
"./visit.js": "./visit.js",
"./package.json": "./package.json"
},
"scripts": {
"prepublishOnly": "cp ../{LICENSE,.npmrc} ./",
"tsc": "tsc -p .",
"posttsc": "attw -P .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/import-js/eslint-plugin-import.git",
"directory": "utils"
},
"keywords": [
"eslint-plugin-import",
"eslint",
"modules",
"esmodules"
],
"author": "Ben Mosher <me@benmosher.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/import-js/eslint-plugin-import/issues"
},
"homepage": "https://github.com/import-js/eslint-plugin-import#readme",
"dependencies": {
"debug": "^3.2.7"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.18.2",
"@ljharb/tsconfig": "^0.3.2",
"@types/debug": "^4.1.12",
"@types/eslint": "^8.56.3",
"@types/node": "^20.19.1",
"typescript": "next"
},
"peerDependenciesMeta": {
"eslint": {
"optional": true
}
},
"publishConfig": {
"ignore": [
".attw.json"
]
}
}

View File

@@ -0,0 +1,11 @@
import { AST, Rule } from 'eslint';
declare function parse(
path: string,
content: string,
context: Rule.RuleContext
): AST.Program | null | undefined;
export default parse;

View File

@@ -0,0 +1,193 @@
'use strict';
exports.__esModule = true;
/** @typedef {`.${string}`} Extension */
/** @typedef {NonNullable<import('eslint').Rule.RuleContext['settings']> & { 'import/extensions'?: Extension[], 'import/parsers'?: { [k: string]: Extension[] }, 'import/cache'?: { lifetime: number | '∞' | 'Infinity' } }} ESLintSettings */
const moduleRequire = require('./module-require').default;
const extname = require('path').extname;
const fs = require('fs');
const log = require('debug')('eslint-plugin-import:parse');
/** @type {(parserPath: NonNullable<import('eslint').Rule.RuleContext['parserPath']>) => unknown} */
function getBabelEslintVisitorKeys(parserPath) {
if (parserPath.endsWith('index.js')) {
const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js');
if (fs.existsSync(hypotheticalLocation)) {
const keys = moduleRequire(hypotheticalLocation);
return keys.default || keys;
}
}
return null;
}
/** @type {(parserPath: import('eslint').Rule.RuleContext['parserPath'], parserInstance: { VisitorKeys: unknown }, parsedResult?: { visitorKeys?: unknown }) => unknown} */
function keysFromParser(parserPath, parserInstance, parsedResult) {
// Exposed by @typescript-eslint/parser and @babel/eslint-parser
if (parsedResult && parsedResult.visitorKeys) {
return parsedResult.visitorKeys;
}
// The old babel parser doesn't have a `parseForESLint` eslint function, so we don't end
// up with a `parsedResult` here. It also doesn't expose the visitor keys on the parser itself,
// so we have to try and infer the visitor-keys module from the parserPath.
// This is NOT supported in flat config!
if (typeof parserPath === 'string' && parserPath.indexOf('babel-eslint') > -1) {
return getBabelEslintVisitorKeys(parserPath);
}
// The espree parser doesn't have the `parseForESLint` function, so we don't end up with a
// `parsedResult` here, but it does expose the visitor keys on the parser instance that we can use.
if (parserInstance && parserInstance.VisitorKeys) {
return parserInstance.VisitorKeys;
}
return null;
}
// this exists to smooth over the unintentional breaking change in v2.7.
// TODO, semver-major: avoid mutating `ast` and return a plain object instead.
/** @type {<T extends import('eslint').AST.Program>(ast: T, visitorKeys: unknown) => T} */
function makeParseReturn(ast, visitorKeys) {
if (ast) {
// @ts-expect-error see TODO
ast.visitorKeys = visitorKeys;
// @ts-expect-error see TODO
ast.ast = ast;
}
return ast;
}
/** @type {(text: string) => string} */
function stripUnicodeBOM(text) {
return text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
}
/** @type {(text: string) => string} */
function transformHashbang(text) {
return text.replace(/^#!([^\r\n]+)/u, (_, captured) => `//${captured}`);
}
/** @type {(path: string, context: import('eslint').Rule.RuleContext & { settings?: ESLintSettings }) => import('eslint').Rule.RuleContext['parserPath']} */
function getParserPath(path, context) {
const parsers = context.settings['import/parsers'];
if (parsers != null) {
// eslint-disable-next-line no-extra-parens
const extension = /** @type {Extension} */ (extname(path));
for (const parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath);
return parserPath;
}
}
}
// default to use ESLint parser
return context.parserPath;
}
/** @type {(path: string, context: import('eslint').Rule.RuleContext) => string | null | import('eslint').Linter.ParserModule | import('eslint').Linter.FlatConfigParserModule} */
function getParser(path, context) {
const parserPath = getParserPath(path, context);
if (parserPath) {
return parserPath;
}
if (
!!context.languageOptions
&& !!context.languageOptions.parser
&& typeof context.languageOptions.parser !== 'string'
&& (
// @ts-expect-error TODO: figure out a better type
typeof context.languageOptions.parser.parse === 'function'
// @ts-expect-error TODO: figure out a better type
|| typeof context.languageOptions.parser.parseForESLint === 'function'
)
) {
return context.languageOptions.parser;
}
return null;
}
/** @type {import('./parse').default} */
exports.default = function parse(path, content, context) {
if (context == null) { throw new Error('need context to parse properly'); }
// ESLint in "flat" mode only sets context.languageOptions.parserOptions
const languageOptions = context.languageOptions;
let parserOptions = languageOptions && languageOptions.parserOptions || context.parserOptions;
const parserOrPath = getParser(path, context);
if (!parserOrPath) { throw new Error('parserPath or languageOptions.parser is required!'); }
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions);
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures);
// always include comments and tokens (for doc parsing)
parserOptions.comment = true;
parserOptions.attachComment = true; // keeping this for backward-compat with older parsers
parserOptions.tokens = true;
// attach node locations
parserOptions.loc = true;
parserOptions.range = true;
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path;
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.EXPERIMENTAL_useProjectService;
delete parserOptions.projectService;
delete parserOptions.project;
delete parserOptions.projects;
// If this is a flat config, we need to add ecmaVersion and sourceType (if present) from languageOptions
if (languageOptions && languageOptions.ecmaVersion) {
parserOptions.ecmaVersion = languageOptions.ecmaVersion;
}
if (languageOptions && languageOptions.sourceType) {
// @ts-expect-error languageOptions is from the flatConfig Linter type in 8.57 while parserOptions is not.
// Non-flat config parserOptions.sourceType doesn't have "commonjs" in the type. Once upgraded to v9 types,
// they'll be the same and this expect-error should be removed.
parserOptions.sourceType = languageOptions.sourceType;
}
// require the parser relative to the main module (i.e., ESLint)
const parser = typeof parserOrPath === 'string' ? moduleRequire(parserOrPath) : parserOrPath;
// replicate bom strip and hashbang transform of ESLint
// https://github.com/eslint/eslint/blob/b93af98b3c417225a027cabc964c38e779adb945/lib/linter/linter.js#L779
content = transformHashbang(stripUnicodeBOM(String(content)));
if (typeof parser.parseForESLint === 'function') {
let ast;
try {
const parserRaw = parser.parseForESLint(content, parserOptions);
ast = parserRaw.ast;
// @ts-expect-error TODO: FIXME
return makeParseReturn(ast, keysFromParser(parserOrPath, parser, parserRaw));
} catch (e) {
console.warn();
console.warn('Error while parsing ' + parserOptions.filePath);
// @ts-expect-error e is almost certainly an Error here
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message);
}
if (!ast || typeof ast !== 'object') {
console.warn(
// Can only be invalid for custom parser per imports/parser
'`parseForESLint` from parser `' + (typeof parserOrPath === 'string' ? parserOrPath : 'context.languageOptions.parser') + '` is invalid and will just be ignored'
);
} else {
// @ts-expect-error TODO: FIXME
return makeParseReturn(ast, keysFromParser(parserOrPath, parser, undefined));
}
}
const ast = parser.parse(content, parserOptions);
// @ts-expect-error TODO: FIXME
return makeParseReturn(ast, keysFromParser(parserOrPath, parser, undefined));
};

View File

@@ -0,0 +1,3 @@
declare function pkgDir(cwd: string): string | null;
export default pkgDir;

View File

@@ -0,0 +1,12 @@
'use strict';
const path = require('path');
const pkgUp = require('./pkgUp').default;
exports.__esModule = true;
/** @type {import('./pkgDir').default} */
exports.default = function (cwd) {
const fp = pkgUp({ cwd });
return fp ? path.dirname(fp) : null;
};

View File

@@ -0,0 +1,3 @@
declare function pkgUp(opts?: { cwd?: string }): string | null;
export default pkgUp;

View File

@@ -0,0 +1,61 @@
'use strict';
exports.__esModule = true;
const fs = require('fs');
const path = require('path');
/**
* Derived significantly from package find-up@2.0.0. See license below.
*
* @copyright Sindre Sorhus
* MIT License
*
* Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/** @type {(filename: string | string[], cwd?: string) => string | null} */
function findUp(filename, cwd) {
let dir = path.resolve(cwd || '');
const root = path.parse(dir).root;
/** @type {string[]} */ // @ts-expect-error TS sucks with concat
const filenames = [].concat(filename);
// eslint-disable-next-line no-constant-condition
while (true) {
const file = filenames.find((el) => fs.existsSync(path.resolve(dir, el)));
if (file) {
return path.join(dir, file);
}
if (dir === root) {
return null;
}
dir = path.dirname(dir);
}
}
/** @type {import('./pkgUp').default} */
exports.default = function pkgUp(opts) {
return findUp('package.json', opts && opts.cwd);
};

View File

@@ -0,0 +1,5 @@
import pkgUp from './pkgUp';
declare function readPkgUp(opts?: Parameters<typeof pkgUp>[0]): {} | { pkg: string, path: string };
export default readPkgUp;

View File

@@ -0,0 +1,55 @@
'use strict';
exports.__esModule = true;
const fs = require('fs');
const pkgUp = require('./pkgUp').default;
/** @type {(str: string) => string} */
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Derived significantly from read-pkg-up@2.0.0. See license below.
*
* @copyright Sindre Sorhus
* MIT License
*
* Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/** @type {import('./readPkgUp').default} */
exports.default = function readPkgUp(opts) {
const fp = pkgUp(opts);
if (!fp) {
return {};
}
try {
return {
pkg: JSON.parse(stripBOM(fs.readFileSync(fp, { encoding: 'utf-8' }))),
path: fp,
};
} catch (e) {
return {};
}
};

View File

@@ -0,0 +1,30 @@
import type { Rule } from 'eslint';
import type ModuleCache from './ModuleCache';
import type { ESLintSettings } from './types';
export type ResultNotFound = { found: false, path?: undefined };
export type ResultFound = { found: true, path: string | null };
export type ResolvedResult = ResultNotFound | ResultFound;
export type ResolverResolve = (modulePath: string, sourceFile:string, config: unknown) => ResolvedResult;
export type ResolverResolveImport = (modulePath: string, sourceFile:string, config: unknown) => string | undefined;
export type Resolver = { interfaceVersion?: 1 | 2, resolve: ResolverResolve, resolveImport: ResolverResolveImport };
declare function resolve(
p: string,
context: Rule.RuleContext,
): ResolvedResult['path'];
export default resolve;
declare function fileExistsWithCaseSync(
filepath: string | null,
cacheSettings: ESLintSettings,
strict: boolean
): boolean | ReturnType<typeof ModuleCache.prototype.get>;
declare function relative(modulePath: string, sourceFile: string, settings: ESLintSettings): ResolvedResult['path'];
export { fileExistsWithCaseSync, relative };

View File

@@ -0,0 +1,254 @@
'use strict';
exports.__esModule = true;
const fs = require('fs');
const Module = require('module');
const path = require('path');
const { getPhysicalFilename } = require('./contextCompat');
const hashObject = require('./hash').hashObject;
const ModuleCache = require('./ModuleCache').default;
const pkgDir = require('./pkgDir').default;
const CASE_SENSITIVE_FS = !fs.existsSync(path.join(__dirname.toUpperCase(), 'reSOLVE.js'));
exports.CASE_SENSITIVE_FS = CASE_SENSITIVE_FS;
const ERROR_NAME = 'EslintPluginImportResolveError';
const fileExistsCache = new ModuleCache();
// Polyfill Node's `Module.createRequireFromPath` if not present (added in Node v10.12.0)
// Use `Module.createRequire` if available (added in Node v12.2.0)
const createRequire = Module.createRequire
// @ts-expect-error this only exists in older node
|| Module.createRequireFromPath
|| /** @type {(filename: string) => unknown} */ function (filename) {
const mod = new Module(filename, void null);
mod.filename = filename;
// @ts-expect-error _nodeModulePaths is undocumented
mod.paths = Module._nodeModulePaths(path.dirname(filename));
// @ts-expect-error _compile is undocumented
mod._compile(`module.exports = require;`, filename);
return mod.exports;
};
/** @type {(resolver: object) => resolver is import('./resolve').Resolver} */
function isResolverValid(resolver) {
if ('interfaceVersion' in resolver && resolver.interfaceVersion === 2) {
return 'resolve' in resolver && !!resolver.resolve && typeof resolver.resolve === 'function';
}
return 'resolveImport' in resolver && !!resolver.resolveImport && typeof resolver.resolveImport === 'function';
}
/** @type {<T extends string>(target: T, sourceFile?: string | null | undefined) => undefined | ReturnType<typeof require>} */
function tryRequire(target, sourceFile) {
let resolved;
try {
// Check if the target exists
if (sourceFile != null) {
try {
resolved = createRequire(path.resolve(sourceFile)).resolve(target);
} catch (e) {
resolved = require.resolve(target);
}
} else {
resolved = require.resolve(target);
}
} catch (e) {
// If the target does not exist then just return undefined
return undefined;
}
// If the target exists then return the loaded module
return require(resolved);
}
/** @type {<T extends Map<string, unknown>>(resolvers: string[] | string | { [k: string]: string }, map: T) => T} */
function resolverReducer(resolvers, map) {
if (Array.isArray(resolvers)) {
resolvers.forEach((r) => resolverReducer(r, map));
return map;
}
if (typeof resolvers === 'string') {
map.set(resolvers, null);
return map;
}
if (typeof resolvers === 'object') {
for (const key in resolvers) {
map.set(key, resolvers[key]);
}
return map;
}
const err = new Error('invalid resolver config');
err.name = ERROR_NAME;
throw err;
}
/** @type {(sourceFile: string) => string} */
function getBaseDir(sourceFile) {
return pkgDir(sourceFile) || process.cwd();
}
/** @type {(name: string, sourceFile: string) => import('./resolve').Resolver} */
function requireResolver(name, sourceFile) {
// Try to resolve package with conventional name
const resolver = tryRequire(`eslint-import-resolver-${name}`, sourceFile)
|| tryRequire(name, sourceFile)
|| tryRequire(path.resolve(getBaseDir(sourceFile), name));
if (!resolver) {
const err = new Error(`unable to load resolver "${name}".`);
err.name = ERROR_NAME;
throw err;
}
if (!isResolverValid(resolver)) {
const err = new Error(`${name} with invalid interface loaded as resolver`);
err.name = ERROR_NAME;
throw err;
}
return resolver;
}
// https://stackoverflow.com/a/27382838
/** @type {import('./resolve').fileExistsWithCaseSync} */
exports.fileExistsWithCaseSync = function fileExistsWithCaseSync(filepath, cacheSettings, strict) {
// don't care if the FS is case-sensitive
if (CASE_SENSITIVE_FS) { return true; }
// null means it resolved to a builtin
if (filepath === null) { return true; }
if (filepath.toLowerCase() === process.cwd().toLowerCase() && !strict) { return true; }
const parsedPath = path.parse(filepath);
const dir = parsedPath.dir;
let result = fileExistsCache.get(filepath, cacheSettings);
if (result != null) { return result; }
// base case
if (dir === '' || parsedPath.root === filepath) {
result = true;
} else {
const filenames = fs.readdirSync(dir);
if (filenames.indexOf(parsedPath.base) === -1) {
result = false;
} else {
result = fileExistsWithCaseSync(dir, cacheSettings, strict);
}
}
fileExistsCache.set(filepath, result);
return result;
};
/** @type {import('./types').ESLintSettings | null} */
let prevSettings = null;
let memoizedHash = '';
/** @type {(modulePath: string, sourceFile: string, settings: import('./types').ESLintSettings) => import('./resolve').ResolvedResult} */
function fullResolve(modulePath, sourceFile, settings) {
// check if this is a bonus core module
const coreSet = new Set(settings['import/core-modules']);
if (coreSet.has(modulePath)) { return { found: true, path: null }; }
const sourceDir = path.dirname(sourceFile);
if (prevSettings !== settings) {
memoizedHash = hashObject(settings).digest('hex');
prevSettings = settings;
}
const cacheKey = sourceDir + memoizedHash + modulePath;
const cacheSettings = ModuleCache.getSettings(settings);
const cachedPath = fileExistsCache.get(cacheKey, cacheSettings);
if (cachedPath !== undefined) { return { found: true, path: cachedPath }; }
/** @type {(resolvedPath: string | null) => void} */
function cache(resolvedPath) {
fileExistsCache.set(cacheKey, resolvedPath);
}
/** @type {(resolver: import('./resolve').Resolver, config: unknown) => import('./resolve').ResolvedResult} */
function withResolver(resolver, config) {
if (resolver.interfaceVersion === 2) {
return resolver.resolve(modulePath, sourceFile, config);
}
try {
const resolved = resolver.resolveImport(modulePath, sourceFile, config);
if (resolved === undefined) { return { found: false }; }
return { found: true, path: resolved };
} catch (err) {
return { found: false };
}
}
const configResolvers = settings['import/resolver']
|| { node: settings['import/resolve'] }; // backward compatibility
const resolvers = resolverReducer(configResolvers, new Map());
for (const pair of resolvers) {
const name = pair[0];
const config = pair[1];
const resolver = requireResolver(name, sourceFile);
const resolved = withResolver(resolver, config);
if (!resolved.found) { continue; }
// else, counts
cache(resolved.path);
return resolved;
}
// failed
// cache(undefined)
return { found: false };
}
/** @type {import('./resolve').relative} */
function relative(modulePath, sourceFile, settings) {
return fullResolve(modulePath, sourceFile, settings).path;
}
exports.relative = relative;
/** @type {Set<import('eslint').Rule.RuleContext>} */
const erroredContexts = new Set();
/**
* Given
* @param p - module path
* @param context - ESLint context
* @return - the full module filesystem path; null if package is core; undefined if not found
* @type {import('./resolve').default}
*/
function resolve(p, context) {
try {
return relative(p, getPhysicalFilename(context), context.settings);
} catch (err) {
if (!erroredContexts.has(context)) {
// The `err.stack` string starts with `err.name` followed by colon and `err.message`.
// We're filtering out the default `err.name` because it adds little value to the message.
// @ts-expect-error this might be an Error
let errMessage = err.message;
// @ts-expect-error this might be an Error
if (err.name !== ERROR_NAME && err.stack) {
// @ts-expect-error this might be an Error
errMessage = err.stack.replace(/^Error: /, '');
}
context.report({
message: `Resolve error: ${errMessage}`,
loc: { line: 1, column: 0 },
});
erroredContexts.add(context);
}
}
}
resolve.relative = relative;
exports.default = resolve;

View File

@@ -0,0 +1,11 @@
{
"extends": "@ljharb/tsconfig",
"compilerOptions": {
"target": "ES2017",
"moduleResolution": "node",
"maxNodeModuleJsDepth": 0,
},
"exclude": [
"coverage",
],
}

View File

@@ -0,0 +1,9 @@
import type { Rule } from 'eslint';
export type Extension = `.${string}`;
export type ESLintSettings = NonNullable<Rule.RuleContext['settings']> & {
'import/extensions'?: Extension[];
'import/parsers'?: { [k: string]: Extension[] };
'import/cache'?: { lifetime: number | '∞' | 'Infinity' };
};

View File

@@ -0,0 +1,7 @@
import type { AST } from 'eslint';
declare function isModule(ast: AST.Program): boolean;
declare function test(content: string): boolean;
export { isModule, test }

View File

@@ -0,0 +1,29 @@
'use strict';
exports.__esModule = true;
const pattern = /(^|[;})])\s*(export|import)((\s+\w)|(\s*[{*=]))|import\(/m;
/**
* detect possible imports/exports without a full parse.
*
* A negative test means that a file is definitely _not_ a module.
* A positive test means it _could_ be.
*
* Not perfect, just a fast way to disqualify large non-ES6 modules and
* avoid a parse.
* @type {import('./unambiguous').test}
*/
exports.test = function isMaybeUnambiguousModule(content) {
return pattern.test(content);
};
// future-/Babel-proof at the expense of being a little loose
const unambiguousNodeType = /^(?:(?:Exp|Imp)ort.*Declaration|TSExportAssignment)$/;
/**
* Given an AST, return true if the AST unambiguously represents a module.
* @type {import('./unambiguous').isModule}
*/
exports.isModule = function isUnambiguousModule(ast) {
return ast.body && ast.body.some((node) => unambiguousNodeType.test(node.type));
};

View File

@@ -0,0 +1,9 @@
import type { Node } from 'estree';
declare function visit(
node: Node,
keys: { [k in Node['type']]?: (keyof Node)[] },
visitorSpec: { [k in Node['type'] | `${Node['type']}:Exit`]?: Function }
): void;
export default visit;

View File

@@ -0,0 +1,30 @@
'use strict';
exports.__esModule = true;
/** @type {import('./visit').default} */
exports.default = function visit(node, keys, visitorSpec) {
if (!node || !keys) {
return;
}
const type = node.type;
const visitor = visitorSpec[type];
if (typeof visitor === 'function') {
visitor(node);
}
const childFields = keys[type];
if (!childFields) {
return;
}
childFields.forEach((fieldName) => {
// @ts-expect-error TS sucks with concat
[].concat(node[fieldName]).forEach((item) => {
visit(item, keys, visitorSpec);
});
});
const exit = visitorSpec[`${type}:Exit`];
if (typeof exit === 'function') {
exit(node);
}
};