import { existsSync, realpathSync, statSync } from "node:fs"; import { readFile, rm } from "node:fs/promises"; import { createRequire } from "node:module"; import { fileURLToPath, pathToFileURL } from "node:url"; import { homedir } from "node:os"; import { resolve, extname, dirname, basename, join, normalize } from "pathe"; import { resolveModulePath } from "exsolve"; import * as rc9 from "rc9"; import { defu } from "defu"; import { setupDotenv } from "./dotenv.ts"; import type { UserInputConfig, ConfigLayerMeta, LoadConfigOptions, ResolvedConfig, ResolvableConfig, ConfigLayer, SourceOptions, InputConfig, ConfigSource, ConfigFunctionContext, StandardSchemaV1, } from "./types.ts"; const _normalize = (p?: string) => p?.replace(/\\/g, "/"); let importCounter = 0; const ASYNC_LOADERS = { ".json": () => JSON.parse, ".yaml": () => import("confbox/yaml").then((r) => r.parseYAML), ".yml": () => import("confbox/yaml").then((r) => r.parseYAML), // `allowTrailingComma` defaults to false since confbox v0.3 (jsonc-parser -> strip-json-comments) ".jsonc": () => import("confbox/jsonc").then( (r) => (source: string) => r.parseJSONC(source, { allowTrailingComma: true }), ), ".json5": () => import("confbox/json5").then((r) => r.parseJSON5), ".toml": () => import("confbox/toml").then((r) => r.parseTOML), } as const; export const SUPPORTED_EXTENSIONS = Object.freeze([ // with import ".js", ".ts", ".mjs", ".cjs", ".mts", ".cts", // with parsers ".json", ".jsonc", ".json5", ".yaml", ".yml", ".toml", ]) as unknown as string[]; export async function loadConfig< T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta, >(options: LoadConfigOptions): Promise> { // Normalize options options.cwd = resolve(process.cwd(), options.cwd || "."); options.name = options.name || "config"; options.envName = options.envName ?? process.env.NODE_ENV; options.configFile = options.configFile ?? (options.name === "config" ? "config" : `${options.name}.config`); options.rcFile = options.rcFile ?? `.${options.name}rc`; if (options.extend !== false) { options.extend = { extendKey: "extends", dedupe: true, ...options.extend, }; } // Custom merger const _merger = options.merger || defu; // Create context const r: ResolvedConfig = { config: {} as any, cwd: options.cwd, configFile: resolve(options.cwd, options.configFile), layers: [], _configFile: undefined, }; // prettier-ignore const rawConfigs: Record< ConfigSource, ResolvableConfig | null | undefined > = { overrides: options.overrides, main: undefined, rc: undefined, packageJson: undefined, defaultConfig: options.defaultConfig, }; // Load dotenv if (options.dotenv) { await setupDotenv({ cwd: options.cwd, ...(options.dotenv === true ? {} : options.dotenv), }); } // Load main config file const seen = options.extend && options.extend.dedupe !== false ? new Set() : undefined; // `seen` is empty here, so the main config can never be a duplicate const _mainConfig = (await resolveConfig(".", options, {}, seen)) as ResolvedConfig; if (_mainConfig.configFile) { rawConfigs.main = _mainConfig.config; r.configFile = _mainConfig.configFile; r._configFile = _mainConfig._configFile; } if (_mainConfig.meta) { r.meta = _mainConfig.meta; } // Load rc files if (options.rcFile) { const rcSources: T[] = []; // 1. cwd rcSources.push(rc9.read({ name: options.rcFile, dir: options.cwd })); if (options.globalRc) { // 2. workspace const { findWorkspaceDir } = await import("pkg-types"); const workspaceDir = await findWorkspaceDir(options.cwd).catch(() => {}); if (workspaceDir) { rcSources.push(rc9.read({ name: options.rcFile, dir: workspaceDir })); } // 3. user config dir ($XDG_CONFIG_HOME or ~/.config) rcSources.push(rc9.readUserConfig({ name: options.rcFile })); // 4. user home (legacy) rcSources.push(rc9.read({ name: options.rcFile, dir: homedir() })); } rawConfigs.rc = _merger({} as T, ...rcSources); } // Load config from package.json if (options.packageJson) { const keys = ( Array.isArray(options.packageJson) ? options.packageJson : [typeof options.packageJson === "string" ? options.packageJson : options.name] ).filter((t) => t && typeof t === "string"); const { readPackageJSON } = await import("pkg-types"); const pkgJsonFile = await readPackageJSON(options.cwd).catch(() => {}); const values = keys.map((key) => pkgJsonFile?.[key]); rawConfigs.packageJson = _merger({} as T, ...values); } // Resolve config sources const configs = {} as Record; // TODO: #253 change order from defaults to overrides in next major version for (const key in rawConfigs) { const value = rawConfigs[key as ConfigSource]; const config = await (typeof value === "function" ? value({ configs, rawConfigs }) : value); configs[key as ConfigSource] = key === "overrides" ? applyEnvConfig(config, options) : config; } if (Array.isArray(configs.main)) { // If the main config exports an array, use it directly without merging or extending r.config = configs.main; } else { // Combine sources r.config = _merger( configs.overrides, configs.main, configs.rc, configs.packageJson, configs.defaultConfig, ) as T; // Allow extending if (options.extend) { await extendConfig(r.config, options, seen); r.layers = r.config._layers; delete r.config._layers; r.config = _merger(r.config, ...r.layers!.map((e) => e.config)) as T; } } // Preserve unmerged sources as layers const baseLayers: ConfigLayer[] = [ configs.overrides && { config: configs.overrides, configFile: undefined, cwd: undefined, }, { config: configs.main, configFile: options.configFile, cwd: options.cwd }, configs.rc && { config: configs.rc, configFile: options.rcFile }, configs.packageJson && { config: configs.packageJson, configFile: "package.json", }, ].filter((l) => l && l.config) as ConfigLayer[]; r.layers = [...baseLayers, ...r.layers!]; // Apply defaults if (options.defaults) { r.config = _merger(r.config, options.defaults) as T; } // Remove environment-specific and built-in keys start with $ if (options.omit$Keys) { for (const key in r.config) { if (key.startsWith("$")) { delete r.config[key]; } } } // Fail if no config loaded if (options.configFileRequired && !r._configFile) { throw new Error(`Required config (${r.configFile}) cannot be resolved.`); } // Validate final config if (options.schema != null) { r.config = (await validateConfig(r.config, options.schema)) as T; } // Return resolved config return r; } async function extendConfig< T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta, >(config: InputConfig, options: LoadConfigOptions, seen?: Set) { (config as any)._layers = config._layers || []; if (!options.extend) { return; } let keys = options.extend.extendKey; if (typeof keys === "string") { keys = [keys]; } const extendSources = []; for (const key of keys as string[]) { extendSources.push( ...(Array.isArray(config[key]) ? config[key] : [config[key]]).filter(Boolean), ); delete config[key]; } for (let extendSource of extendSources) { const originalExtendSource = extendSource; let sourceOptions = {}; if (extendSource.source) { sourceOptions = extendSource.options || {}; extendSource = extendSource.source; } if (Array.isArray(extendSource)) { sourceOptions = extendSource[1] || {}; extendSource = extendSource[0]; } if (typeof extendSource !== "string") { // TODO: Use error in next major versions console.warn( `Cannot extend config from \`${JSON.stringify(originalExtendSource)}\` in ${options.cwd}`, ); continue; } const _config = await resolveConfig(extendSource, options, sourceOptions, seen); if (_config === DUPLICATE) { continue; } if (!_config.config) { // TODO: Use error in next major versions console.warn(`Cannot extend config from \`${extendSource}\` in ${options.cwd}`); continue; } await extendConfig(_config.config, { ...options, cwd: _config.cwd }, seen); config._layers.push(_config); if (_config.config._layers) { config._layers.push(..._config.config._layers); delete _config.config._layers; } } } // TODO: Either expose from giget directly or redirect all non file:// protocols to giget const GIGET_PREFIXES = ["gh:", "github:", "gitlab:", "bitbucket:", "https://", "http://"]; // https://github.com/dword-design/package-name-regex const NPM_PACKAGE_RE = /^(@[\da-z~-][\d._a-z~-]*\/)?[\da-z~-][\d._a-z~-]*($|\/.*)/; async function resolveConfig< T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta, >( source: string, options: LoadConfigOptions, sourceOptions: SourceOptions = {}, seen?: Set, ): Promise | typeof DUPLICATE> { // Custom user resolver if (options.resolve) { const res = await options.resolve(source, options); if (res) { const file = res._configFile || res.configFile; const cwd = res.cwd && resolve(options.cwd!, res.cwd); const configFile = file && resolve(cwd || options.cwd!, file); return _isDuplicateLayer(seen, configFile, cwd) ? DUPLICATE : res; } } // Custom merger const _merger = options.merger || defu; // Download giget URIs and resolve to local path const customProviderKeys = Object.keys(sourceOptions.giget?.providers || {}).map( (key) => `${key}:`, ); const gigetPrefixes = customProviderKeys.length > 0 ? [...new Set([...customProviderKeys, ...GIGET_PREFIXES])] : GIGET_PREFIXES; if (options.giget !== false && gigetPrefixes.some((prefix) => source.startsWith(prefix))) { if (seen?.has(`giget:${source}`)) { return DUPLICATE; } seen?.add(`giget:${source}`); const { downloadTemplate } = await import("giget").catch((error) => { throw new Error( `Extending config from \`${source}\` requires \`giget\` peer dependency to be installed.\n\nInstall it with: \`npx nypm i giget\``, { cause: error }, ); }); const { digest } = await import("ohash"); const cloneName = source.replace(/\W+/g, "_").split("_").splice(0, 3).join("_") + "_" + digest(source).slice(0, 10).replace(/[-_]/g, ""); let cloneDir: string; const localNodeModules = resolve(options.cwd!, "node_modules"); const parentDir = dirname(options.cwd!); if (basename(parentDir) === ".c12") { cloneDir = join(parentDir, cloneName); } else if (existsSync(localNodeModules)) { cloneDir = join(localNodeModules, ".c12", cloneName); } else { cloneDir = process.env.XDG_CACHE_HOME ? resolve(process.env.XDG_CACHE_HOME, "c12", cloneName) : resolve(homedir(), ".cache/c12", cloneName); } // Install the cloned layer in isolation as it lives in `.c12/` and is // not a workspace member (unjs/c12#128). `defu` is used over a spread so an // explicit `undefined` does not clobber the default, and the normalized // value is shared with the cleanup guard and `force` below so all three // stay in agreement (`null` is falsy here, unlike `typeof x === "object"`). // Note: nypm only honors `ignoreWorkspace` for pnpm. const install = sourceOptions.install ? defu(sourceOptions.install === true ? {} : sourceOptions.install, { ignoreWorkspace: true, }) : false; if (existsSync(cloneDir) && !install) { await rm(cloneDir, { recursive: true }); } const cloned = await downloadTemplate(source, { dir: cloneDir, install, force: Boolean(install), auth: sourceOptions.auth, ...options.giget, ...sourceOptions.giget, }); source = cloned.dir; } // Try resolving as npm package if (NPM_PACKAGE_RE.test(source)) { source = tryResolve(source, options) || source; } // Import from local fs const ext = extname(source); const resolvedPath = resolve(options.cwd!, source); const isDir = _isDirectory(resolvedPath) ?? (!ext || ext === basename(source)); /* #71 */ const cwd = resolve(options.cwd!, isDir ? source : dirname(source)); if (isDir) { source = options.configFile!; } const res: ResolvedConfig = { config: undefined as unknown as T, configFile: undefined, cwd, source, sourceOptions, }; res.configFile = tryResolve(resolve(cwd, source), options) || tryResolve(resolve(cwd, ".config", source.replace(/\.config$/, "")), options) || tryResolve(resolve(cwd, ".config", source), options) || source; if (!existsSync(res.configFile!)) { return res; } if (_isDuplicateLayer(seen, res.configFile!, res.cwd)) { return DUPLICATE; } res._configFile = res.configFile; const configFileExt = extname(res.configFile!) || ""; if (configFileExt in ASYNC_LOADERS) { const asyncLoader = await ASYNC_LOADERS[configFileExt as keyof typeof ASYNC_LOADERS](); const contents = await readFile(res.configFile!, "utf8"); res.config = asyncLoader(contents); } else { const _resolveModule = options.resolveModule || _resolveDefaultExport; if (options.import) { res.config = _resolveModule(await options.import(res.configFile!)) as T; } else { const _configURL = pathToFileURL(res.configFile!); // Bun caches modules by path and ignores the query string (#362) if ("Bun" in globalThis) { delete createRequire(import.meta.url).cache[fileURLToPath(_configURL)]; } _configURL.search = `_${++importCounter}`; res.config = (await import(_configURL.href).then(_resolveModule, async (error) => { const { createJiti } = await import("jiti").catch(() => { throw new Error( `Failed to load config file \`${res.configFile}\`: ${error?.message}. Hint install \`jiti\` for compatibility.`, { cause: error }, ); }); const jiti = createJiti(join(options.cwd || ".", options.configFile || "/"), { interopDefault: true, moduleCache: false, extensions: [...SUPPORTED_EXTENSIONS], ...options.jitiOptions, }); options.import = (id: string) => jiti.import(id); return _resolveModule(await options.import(res.configFile!)); })) as T; } } if (typeof res.config === "function") { res.config = await (res.config as (ctx?: ConfigFunctionContext) => Promise)( options.context, ); } // Config may be frozen or a module namespace, but gets mutated below (#205) if ( res.config && typeof res.config === "object" && !Array.isArray(res.config) && !Object.isExtensible(res.config) ) { res.config = { ...res.config }; } // Always windows paths res.configFile = _normalize(res.configFile); res.source = _normalize(res.source); // Nothing to apply on a config resolving to `null` or `undefined` if (res.config == null) { return res; } // Extend env specific config res.config = applyEnvConfig(res.config, options); // Meta res.meta = defu(res.sourceOptions!.meta, res.config!.$meta) as MT; delete res.config!.$meta; // Overrides if (res.sourceOptions!.overrides) { res.config = _merger(applyEnvConfig(res.sourceOptions!.overrides, options), res.config) as T; } return res; } // --- internal --- function applyEnvConfig( config: T, options: LoadConfigOptions, ): T { if (!config) { return config; } // Later names in the list have higher priority (deduped, last occurrence wins) const envNames = [ ...new Set( (Array.isArray(options.envName) ? options.envName : [options.envName]) .filter(Boolean) .reverse() as string[], ), ]; const envConfigs = envNames .flatMap((envName) => [config.$env?.[envName], config["$" + envName]]) .filter((c) => c && Object.keys(c).length > 0); if (envConfigs.length === 0) { return config; } const _envMerger = options.envMerger || options.merger || defu; return _envMerger({} as T, ...envConfigs, config) as T; } async function validateConfig(config: unknown, schema: StandardSchemaV1) { if (typeof schema?.["~standard"]?.validate !== "function") { throw new TypeError( "Invalid `schema` option: expected a Standard Schema (https://standardschema.dev).", ); } const result = await schema["~standard"].validate(config); if (result.issues) { const messages = result.issues.map((issue) => { const path = issue.path?.map((p) => String(typeof p === "object" ? p.key : p)).join("."); return ` - ${path ? `${path}: ` : ""}${issue.message}`; }); throw new Error( `Config validation failed (${schema["~standard"].vendor}):\n${messages.join("\n")}`, { cause: result.issues }, ); } return result.value; } const DUPLICATE = Symbol("duplicate"); function _layerKey(path: string): string { try { return _normalize(realpathSync(path))!; } catch { return _normalize(resolve(path))!; } } function _isDuplicateLayer(seen: Set | undefined, configFile?: string, cwd?: string) { const path = configFile || cwd; if (!seen || !path) { return false; } const key = _layerKey(path); if (seen.has(key)) { return true; } seen.add(key); if (configFile && cwd) { seen.add(_layerKey(cwd)); } return false; } function tryResolve(id: string, options: LoadConfigOptions) { const res = resolveModulePath(id, { try: true, from: pathToFileURL(join(options.cwd || ".", options.configFile || "/")), suffixes: ["", "/index"], extensions: SUPPORTED_EXTENSIONS, cache: false, }); return res ? normalize(res) : undefined; } /** * Picks the `default` export, falling back to the module itself only when there is none, * so `export default null` resolves to an empty config instead of the module namespace (#356). * jiti interop may return non-namespace values (e.g. `null` for CJS `module.exports = null`). */ function _resolveDefaultExport(mod: any) { const isObject = mod !== null && (typeof mod === "object" || typeof mod === "function"); return isObject && "default" in mod ? mod.default : mod; } /** Returns `true`/`false` if the path exists, `null` if it doesn't. */ function _isDirectory(path: string): boolean | null { try { return statSync(path).isDirectory(); } catch { return null; } }