UNPKG

rc-config-loader

Version:

load config file from .{product}rc.{json,yml,js,ts}

341 lines • 13.5 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.rcFile = rcFile; exports.loadConfigFile = loadConfigFile; // MIT © 2017 azu // MIT © Zoltan Kochan // Original https://github.com/zkochan/rcfile const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); const json5_1 = __importDefault(require("json5")); const debug = require("debug")("rc-config-loader"); const defaultLoaderByExt = { ".cjs": loadJSConfigFile, ".js": loadJSConfigFile, ".mjs": loadJSConfigFile, ".json": loadJSONConfigFile, ".yaml": loadYAMLConfigFile, ".yml": loadYAMLConfigFile, ".ts": loadJSConfigFile, ".cts": loadJSConfigFile, ".mts": loadJSConfigFile }; /** * Every supported extension. `loadConfigFile` allows them by default. */ const supportedExtensions = [".json", ".yaml", ".yml", ".js", ".cjs", ".mjs", ".ts", ".cts", ".mts"]; /** * The default extensions to search by `rcFile`, and their priority. * `.cjs`, `.mjs`, `.cts`, and `.mts` are searched only when they are given in `extensions`, * to keep the number of existence checks small. * A file without extension like `.<product>rc` is tried as JSON, YAML, then JavaScript. */ const defaultSearchExtensions = [".json", ".yaml", ".yml", ".js", ".ts"]; const defaultOptions = { packageJSON: false, cwd: process.cwd() }; const isSupportedExtension = (extension) => { return Object.prototype.hasOwnProperty.call(defaultLoaderByExt, extension); }; /** * Return the extensions that are allowed to load, in order of priority. * If `extensions` is not specified, return the default extensions. */ const resolveAllowedExtensions = (extensions, defaultExtensions) => { if (extensions === undefined) { return defaultExtensions; } if (!Array.isArray(extensions) || extensions.length === 0) { throw new Error("extensions should be a non-empty array."); } extensions.forEach((extension) => { if (!isSupportedExtension(extension)) { throw new Error(`${extension} is not supported.`); } }); return extensions; }; /** * Return the loaders for a file without known extension, in order of `extensions`. * - `.json` → JSON, `.yaml` or `.yml` → YAML, `.js` → JavaScript * - Other extensions like `.ts` do not add a loader, because a file without extension can not be TypeScript. * - The same loader is not added twice, so a JavaScript file is not run twice. */ const selectLoadersForNoExtension = (extensions) => { const loaders = []; extensions.forEach((extension) => { const loader = extension === ".json" ? loadJSONConfigFile : extension === ".yaml" || extension === ".yml" ? loadYAMLConfigFile : extension === ".js" ? loadJSConfigFile : undefined; if (loader && !loaders.includes(loader)) { loaders.push(loader); } }); return loaders; }; /** * Find and load rcfile, return { config, filePath } * If not found any rcfile, throw an Error. * @param {string} pkgName * @param {rcConfigLoaderOption} [opts] * @returns {{ config: Object, filePath:string } | undefined} */ function rcFile(pkgName, opts = {}) { if (Object.prototype.hasOwnProperty.call(opts, "defaultExtension")) { throw new Error("defaultExtension option is removed. Use extensions option instead."); } // path/to/config or basename of config file. const configFileName = opts.configFileName || `.${pkgName}rc`; const allowedExtensions = resolveAllowedExtensions(opts.extensions, defaultSearchExtensions); const cwd = opts.cwd || defaultOptions.cwd; const packageJSON = opts.packageJSON || defaultOptions.packageJSON; const packageJSONFieldName = typeof packageJSON === "object" ? packageJSON.fieldName : pkgName; const parts = splitPath(cwd); // A file without extension: if only one format is allowed, its error is thrown. // If multiple formats are allowed, errors are suppressed and the file is skipped when all fail. const noExtensionLoaders = selectLoadersForNoExtension(allowedExtensions); const loadersByOrder = noExtensionLoaders.length === 1 ? noExtensionLoaders[0] : noExtensionLoaders; // Search the extensions in the order of `extensions`, then the name without extension. const loaderByExt = {}; allowedExtensions.forEach((extension) => { loaderByExt[extension] = defaultLoaderByExt[extension]; }); if (noExtensionLoaders.length > 0) { loaderByExt[""] = loadersByOrder; } return findConfig({ parts, loaderByExt, loadersByOrder, configFileName, packageJSON, packageJSONFieldName }); } /** * Load exactly one config file, return { config, filePath } * - `filePath` is resolved from `opts.cwd`(default: `process.cwd()`) * - It does not search parent directories, does not append any extension, and does not read `package.json` * - The loader is selected by the extension of `filePath` * - `.json` → JSON, `.yaml`/`.yml` → YAML, `.js`/`.cjs`/`.mjs` → JavaScript, `.ts`/`.cts`/`.mts` → TypeScript * - Other names like `.secretlintrc` are tried as JSON, YAML, then JavaScript (in order of `extensions`) * - If the file does not exist, throw an Error that has `code: "ENOENT"` * - If the file can not be parsed, throw an Error * @param {string} filePath * @param {loadConfigFileOption} [opts] * @returns {{ config: Object, filePath:string }} */ function loadConfigFile(filePath, opts = {}) { const cwd = opts.cwd || defaultOptions.cwd; const allowedExtensions = resolveAllowedExtensions(opts.extensions, supportedExtensions); const configLocation = path_1.default.resolve(cwd, filePath); if (!fs_1.default.existsSync(configLocation)) { const error = new Error(`Config file not found: ${configLocation}`); error.code = "ENOENT"; error.path = configLocation; throw error; } const ext = path_1.default.extname(configLocation); if (isSupportedExtension(ext)) { if (!allowedExtensions.includes(ext)) { throw createNotAllowedError(configLocation); } const loader = defaultLoaderByExt[ext]; return { config: loader(configLocation, false), filePath: configLocation }; } // Unknown or no extension like `.secretlintrc`: try the formats in order of `extensions`. // By default, JSON, YAML, then JavaScript. // Errors are suppressed except for the last loader, so the error of the last loader is thrown when all fail. const fallbackLoaders = selectLoadersForNoExtension(allowedExtensions); if (fallbackLoaders.length === 0) { throw createNotAllowedError(configLocation); } for (let i = 0; i < fallbackLoaders.length; i++) { const isLast = i === fallbackLoaders.length - 1; const result = fallbackLoaders[i](configLocation, !isLast); if (isLast || result !== undefined) { return { config: result, filePath: configLocation }; } } // unreachable: the last loader returns or throws throw createNotAllowedError(configLocation); } function createNotAllowedError(configLocation) { const error = new Error(`Config file is not allowed by extensions option: ${configLocation}`); error.code = "ERR_RC_CONFIG_EXTENSION_NOT_ALLOWED"; error.path = configLocation; return error; } /** * * @returns {{ * config: string, * filePath: string * }} */ function findConfig({ parts, loaderByExt, loadersByOrder, configFileName, packageJSON, packageJSONFieldName }) { const extensions = Object.keys(loaderByExt); while (extensions.length) { const ext = extensions.shift(); // may be ext is "". if it .<product>rc const configLocation = join(parts, configFileName + ext); if (!fs_1.default.existsSync(configLocation)) { continue; } // if ext === ""(empty string):, use ordered loaders const loaders = ext ? loaderByExt[ext] : loadersByOrder; if (!Array.isArray(loaders)) { const loader = loaders; const result = loader(configLocation, false); if (!result) { continue; } return { config: result, filePath: configLocation }; } for (let i = 0; i < loaders.length; i++) { const loader = loaders[i]; const result = loader(configLocation, true); if (!result) { continue; } return { config: result, filePath: configLocation }; } } if (packageJSON) { const pkgJSONLoc = join(parts, "package.json"); if (fs_1.default.existsSync(pkgJSONLoc)) { const pkgJSON = json5_1.default.parse(readFile(pkgJSONLoc)); if (pkgJSON[packageJSONFieldName]) { return { config: pkgJSON[packageJSONFieldName], filePath: pkgJSONLoc }; } } } if (parts.pop()) { return findConfig({ parts, loaderByExt, loadersByOrder, configFileName, packageJSON, packageJSONFieldName }); } return; } function splitPath(x) { return path_1.default.resolve(x || "").split(path_1.default.sep); } function join(parts, filename) { return path_1.default.resolve(parts.join(path_1.default.sep) + path_1.default.sep, filename); } /** * Load JavaScript or TypeScript config file by Node.js's `require()`. * - CommonJS and ES Modules are supported. ES Modules are loaded by `require(esm)`. * - TypeScript is supported by Node.js's built-in type stripping. */ function loadJSConfigFile(filePath, suppress) { debug(`Loading JavaScript config file: ${filePath}`); try { const resolvedPath = require.resolve(filePath); // Remove the cache of CommonJS module to load the latest content. // Note: Node.js does not provide a way to remove the cache of ES Modules. delete require.cache[resolvedPath]; try { return interopDefault(require(resolvedPath)); } finally { // `require()` adds the loaded module to `module.children`. // Remove it so that loading a config file many times does not keep old modules in memory. removeChildModule(resolvedPath); } } catch (error) { debug(`Error reading JavaScript file: ${filePath}`); if (!suppress) { error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`; throw error; } } } function removeChildModule(resolvedPath) { const children = module.children; for (let i = children.length - 1; i >= 0; i--) { if (children[i].id === resolvedPath || children[i].filename === resolvedPath) { children.splice(i, 1); } } } /** * `require(esm)` returns the module namespace object like `{ __esModule: true, default: config }`. * Return the default export as config. */ function interopDefault(exported) { if (exported && exported.__esModule && "default" in exported) { return exported.default; } return exported; } function loadJSONConfigFile(filePath, suppress) { debug(`Loading JSON config file: ${filePath}`); try { return json5_1.default.parse(readFile(filePath)); } catch (error) { debug(`Error reading JSON file: ${filePath}`); if (!suppress) { error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`; throw error; } } } function readFile(filePath) { return fs_1.default.readFileSync(filePath, "utf8"); } function loadYAMLConfigFile(filePath, suppress) { debug(`Loading YAML config file: ${filePath}`); // lazy load YAML to improve performance when not used const { load, loadAll, CORE_SCHEMA, mergeTag, timestampTag } = require("js-yaml"); // js-yaml v5 uses YAML 1.2 CORE_SCHEMA by default. // Add `<<` merge keys and timestamps back to keep the same behavior as js-yaml v4's DEFAULT_SCHEMA const schema = CORE_SCHEMA.withTags(mergeTag, timestampTag); try { const content = readFile(filePath); // js-yaml v5's load() throws on empty input(empty, whitespace-only or comment-only file), // but loadAll() returns an empty array for it. Treat it as an empty config. // Use loadAll() to parse the content only once. const documents = loadAll(content, { schema }); if (documents.length === 0) { return {}; } if (documents.length > 1) { // throw the same error as load() for multiple documents return load(content, { schema }); } // empty document like "---" is null, so always use object return documents[0] || {}; } catch (error) { debug(`Error reading YAML file: ${filePath}`); if (!suppress) { error.message = `Cannot read config file: ${filePath}\nError: ${error.message}`; throw error; } } } //# sourceMappingURL=rc-config-loader.js.map