import { readFile, stat } from "node:fs/promises"; import { extname, resolve } from "node:path"; import * as process from "node:process"; import { validateEnvironmentName, validateFlakinessScoringOptions, validateMetricsConfig, } from "@allurereport/core-api"; import { type NameContext, createNameContext, resolveName } from "@allurereport/core-api/expression"; import type { Config, PluginConstructor, PluginConstructorContext, PluginDescriptor } from "@allurereport/plugin-api"; import { parse } from "yaml"; import type { FullConfig, PluginInstance } from "./api.js"; import { resolveAllureService } from "./config/allureService.js"; import { resolveCategories } from "./config/categories.js"; import { resolveEnvironments } from "./config/environments.js"; import { findUnsupportedCoreExpressions, findUnsupportedExpressions, supportsPluginExpression, } from "./config/expressionWarnings.js"; import { resolveHideLabels } from "./config/hideLabels.js"; import { resolvePluginOptions } from "./config/pluginOptions.js"; import { resolveQualityGate } from "./config/qualityGate.js"; import { FileSystemReportFiles } from "./plugin.js"; import { DEFAULT_KNOWN_ISSUES_PATH, resolveExactIssuesFilePath, validateResolutionsConfig } from "./resolutions.js"; import { createDynamicEnvironmentResolver, environmentIdentityById, environmentIdentityByName, validateAllowedEnvironmentIds, normalizeEnvironmentDescriptorMap, validateAllowedEnvironmentId, } from "./utils/environment.js"; import { importWrapper } from "./utils/module.js"; import { assertNodeSupportsTsConfig } from "./utils/nodeVersion.js"; import { normalizeImportPath } from "./utils/path.js"; import { normalizeResultsDir } from "./utils/resultsDir.js"; import { assertValidPluginIdForWindows, isWindows } from "./utils/windows.js"; export interface ConfigOverride { cwd?: string; name?: Config["name"]; output?: Config["output"]; open?: Config["open"]; port?: Config["port"]; host?: Config["host"]; hideLabels?: Config["hideLabels"]; historyPath?: Config["historyPath"]; historyBaseUrl?: Config["historyBaseUrl"]; historyLimit?: Config["historyLimit"]; resolutions?: Pick, "knownIssuesPath">; plugins?: Config["plugins"]; } const CONFIG_FILENAMES = [ "allurerc.js", "allurerc.mjs", "allurerc.cjs", "allurerc.ts", "allurerc.mts", "allurerc.cts", "allurerc.json", "allurerc.yaml", "allurerc.yml", ] as const; const DEFAULT_CONFIG: Config = {} as const; export const isAgentDescriptor = (value: string | undefined) => { return value === "agent" || value === "@allurereport/plugin-agent"; }; export const hasConfiguredAgent = (plugins: Record) => { return Object.entries(plugins).some( ([key, descriptor]) => isAgentDescriptor(key) || isAgentDescriptor(descriptor.import), ); }; /** * Ensures a plugin id is safe as a single path segment */ export const assertValidPluginId = (id: string): void => { if (id.length === 0) { throw new Error("Invalid plugin id: must not be empty"); } if (id === "." || id === "..") { throw new Error(`Invalid plugin id ${JSON.stringify(id)}: must not be "." or ".."`); } if (id.includes("..")) { throw new Error(`Invalid plugin id ${JSON.stringify(id)}: must not contain ".."`); } if (/[/\\]/.test(id)) { throw new Error(`Invalid plugin id ${JSON.stringify(id)}: must not contain path separators`); } if (isWindows()) { assertValidPluginIdForWindows(id); } }; export const getPluginId = (key: string): string => { const trimmed = key.trim(); if (trimmed.length === 0) { throw new Error(`Invalid plugin key ${JSON.stringify(key)}: must not be empty or whitespace-only`); } const id = trimmed.replace(/^@.*\//, "").replace(/[/\\]/g, "-"); assertValidPluginId(id); return id; }; /** * Tries to find the well-known config file in the given cwd or uses the provided config path * @param cwd * @param configPath */ export const findConfig = async (cwd: string, configPath?: string) => { if (configPath) { const resolved = resolve(cwd, configPath); try { const stats = await stat(resolved); if (stats.isFile()) { return resolved; } } catch {} throw new Error(`invalid config path ${resolved}: not a regular file`); } for (const configFilename of CONFIG_FILENAMES) { const resolved = resolve(cwd, configFilename); try { const stats = await stat(resolved); if (stats.isFile()) { return resolved; } } catch { // ignore } } }; /** * Validates the provided config * At this moment supports unknown fields check only * @example * ```js * validateConfig({ name: "Allure" }) // { valid: true } * validateConfig({ name: "Allure", unknownField: "value" }) // { valid: false, fields: ["unknownField"] } * ``` * @param config */ export const validateConfig = (config: Config) => { const supportedFields = [ "name", "output", "open", "port", "host", "hideLabels", "historyPath", "historyBaseUrl", "historyLimit", "flakyDetection", "resolutions", "plugins", "defaultLabels", "variables", "environment", "allowedEnvironments", "environments", "dynamicEnvironments", "appendHistory", "qualityGate", "metrics", "performance", "allureService", "categories", "globalAttachments", "resultsDir", "dump", ] as const; const unsupportedFields = Object.keys(config).filter( (key) => !supportedFields.includes(key as (typeof supportedFields)[number]), ); return { valid: unsupportedFields.length === 0, fields: unsupportedFields, }; }; /** * Loads the yaml config from the given path * If the file does not exist, returns the default config * @param configPath */ export const loadYamlConfig = async (configPath: string): Promise => { try { const rawConfig = await readFile(configPath, "utf-8"); const parsedConfig = parse(rawConfig) as Config; return parsedConfig || DEFAULT_CONFIG; } catch (err) { if ((err as any)?.code === "ENOENT") { return DEFAULT_CONFIG; } throw err; } }; /** * Loads the json config from the given path * If the file does not exist, returns the default config * @param configPath */ export const loadJsonConfig = async (configPath: string): Promise => { try { const rawConfig = await readFile(configPath, "utf-8"); const parsedConfig = JSON.parse(rawConfig) as Config; return parsedConfig || DEFAULT_CONFIG; } catch (err) { if ((err as any)?.code === "ENOENT") { return DEFAULT_CONFIG; } throw err; } }; /** * Loads the javascript config from the given path * @param configPath */ export const loadJsConfig = async (configPath: string): Promise => { return (await import(normalizeImportPath(configPath))).default; }; /** * Loads the TypeScript config from the given path via Node native type stripping * @param configPath */ export const loadTsConfig = async (configPath: string): Promise => { assertNodeSupportsTsConfig(); return loadJsConfig(configPath); }; const resolveConfigEnvironments = (config: Config, context: NameContext) => { const errors: string[] = []; const { ids: allowedEnvironments, idsSet: allowedEnvironmentIds, errors: allowedEnvironmentErrors, } = validateAllowedEnvironmentIds(config.allowedEnvironments, "config.allowedEnvironments"); const { normalized: environments, errors: environmentErrors } = normalizeEnvironmentDescriptorMap( resolveEnvironments(config.environments, context) ?? {}, "config.environments", ); let environment: string | undefined; errors.push(...allowedEnvironmentErrors, ...environmentErrors); if (config.environment !== undefined) { const environmentResult = validateEnvironmentName(config.environment); if (!environmentResult.valid) { errors.push(`environment ${environmentResult.reason}`); } else { const normalizedEnvironment = environmentResult.normalized; environment = environmentIdentityById(environments, normalizedEnvironment)?.id ?? environmentIdentityByName(environments, normalizedEnvironment)?.id ?? normalizedEnvironment; const allowedEnvironmentError = validateAllowedEnvironmentId(environment, allowedEnvironmentIds, "config"); if (allowedEnvironmentError) { throw new Error(`The provided Allure config contains invalid environments: ${allowedEnvironmentError}`); } } } for (const environmentId of Object.keys(environments)) { const allowedEnvironmentError = validateAllowedEnvironmentId( environmentId, allowedEnvironmentIds, "config.environments", ); if (allowedEnvironmentError) { throw new Error(`The provided Allure config contains invalid environments: ${allowedEnvironmentError}`); } } if (errors.length > 0) { throw new Error(`The provided Allure config contains invalid environments: ${errors.join("; ")}`); } return { environments, environment, allowedEnvironments, }; }; const validateFlakyDetectionConfig = (config: Config["flakyDetection"]) => { if (config === undefined) { return; } const { historyDepth, includePassedTests, stabilizationPeriod } = config; if (historyDepth !== undefined && (!Number.isInteger(historyDepth) || historyDepth < -1)) { throw new Error("flakyDetection.historyDepth must be an integer greater than or equal to -1"); } if (stabilizationPeriod !== undefined && (!Number.isInteger(stabilizationPeriod) || stabilizationPeriod < 1)) { throw new Error("flakyDetection.stabilizationPeriod must be a positive integer"); } if (includePassedTests !== undefined && typeof includePassedTests !== "boolean") { throw new TypeError("flakyDetection.includePassedTests must be a boolean"); } validateFlakinessScoringOptions(config, "flakyDetection"); }; const printedExpressionWarnings = new Set(); const warnUnsupportedExpression = (path: string, source = ""): void => { const message = `Dynamic expressions are not supported at ${path}${source}; the value will not be evaluated.`; if (!printedExpressionWarnings.has(message)) { printedExpressionWarnings.add(message); console.warn(message); } }; export const resolveConfig = async (config: Config, override: ConfigOverride = {}): Promise => { const validationResult = validateConfig(config); if (!validationResult.valid) { throw new Error(`The provided Allure config contains unsupported fields: ${validationResult.fields.join(", ")}`); } for (const path of findUnsupportedCoreExpressions(config, override)) { const source = path === "config.name" && override.name != null ? " (report-name override)" : ""; warnUnsupportedExpression(path, source); } validateResolutionsConfig(config.resolutions); validateFlakyDetectionConfig(config.flakyDetection); const metrics = config.metrics ?? config.performance; validateMetricsConfig(metrics); const nameContext = createNameContext(); const { environments, environment, allowedEnvironments } = resolveConfigEnvironments(config, nameContext); // Keep override precedence in sync with CORE_CONFIG_NULLISH_OVERRIDE_KEYS and // findUnsupportedCoreExpressions in config/expressionWarnings.ts. const name = override.name ?? resolveName(config.name ?? "Allure Report", "name", nameContext)!; const open = override.open ?? config.open ?? false; const port = override.port ?? config.port ?? undefined; const host = override.host ?? config.host ?? undefined; const hideLabels = resolveHideLabels(override.hideLabels ?? config.hideLabels); const historyPath = override.historyPath ?? config.historyPath; const historyBaseUrl = override.historyBaseUrl ?? config.historyBaseUrl; const historyLimit = override.historyLimit ?? config.historyLimit; const dump = config.dump; const appendHistory = config.appendHistory ?? true; const configuredKnownIssuesPath = override.resolutions?.knownIssuesPath ?? config.resolutions?.knownIssuesPath; const knownIssuesPathInput = configuredKnownIssuesPath ?? (config.resolutions ? DEFAULT_KNOWN_ISSUES_PATH : undefined); const knownIssuesPath = await resolveExactIssuesFilePath(knownIssuesPathInput, "known issues"); const resolutions = config.resolutions || override.resolutions?.knownIssuesPath !== undefined ? { ...(config.resolutions ?? { rules: [] }), knownIssuesPath } : undefined; const output = resolve(override.output ?? config.output ?? "./allure-report"); const cwd = resolve(override.cwd ?? process.cwd()); const variables = config.variables ?? {}; const resultsDir = normalizeResultsDir(config.resultsDir); let pluginInstances: PluginInstance[] = []; const hasPluginsOverride = override.plugins !== undefined; if (!hasPluginsOverride || Object.keys(override.plugins ?? {}).length > 0) { const configuredPlugins = hasPluginsOverride ? override.plugins : config.plugins; const basePlugins = !hasPluginsOverride && Object.keys(configuredPlugins ?? {}).length === 0 ? { awesome: { options: {}, }, } : configuredPlugins!; const pluginsWithAgent = hasConfiguredAgent(basePlugins) ? basePlugins : { ...basePlugins, agent: { options: {}, }, }; pluginInstances = await resolvePlugins(pluginsWithAgent, nameContext); } return { name, cwd, output, open, port, host, hideLabels, resolutions, environment, allowedEnvironments, variables, environments, dynamicEnvironments: createDynamicEnvironmentResolver(config.dynamicEnvironments), appendHistory, historyLimit, flakyDetection: config.flakyDetection, historyPath: historyPath ? resolve(historyPath) : undefined, historyBaseUrl, dump, reportFiles: new FileSystemReportFiles(output), plugins: pluginInstances, defaultLabels: config.defaultLabels ?? {}, qualityGate: resolveQualityGate(config.qualityGate), metrics, performance: config.performance, allureService: resolveAllureService(config.allureService, nameContext.env), categories: resolveCategories(config.categories, nameContext), globalAttachments: config.globalAttachments, ...(resultsDir.length ? { resultsDir } : {}), }; }; /** * Tries to read Allure Runtime configuration file in given cwd * If config path is not provided, tries to find well-known config file * Supports javascript, typescript, json and yaml config files * If nothing is found returns an empty config * @param cwd * @param configPath * @param override */ export const readConfig = async ( cwd: string = process.cwd(), configPath?: string, override?: ConfigOverride, ): Promise => { const cfg = (await findConfig(cwd, configPath)) ?? ""; let config: Config; switch (extname(cfg)) { case ".json": config = await loadJsonConfig(cfg); break; case ".yaml": case ".yml": config = await loadYamlConfig(cfg); break; case ".js": case ".cjs": case ".mjs": config = await loadJsConfig(cfg); break; case ".ts": case ".cts": case ".mts": config = await loadTsConfig(cfg); break; default: config = DEFAULT_CONFIG; } const fullConfig = await resolveConfig(config, { ...override, cwd }); return fullConfig; }; export const readRawConfig = async (cwd: string = process.cwd(), configPath?: string): Promise => { const cfg = (await findConfig(cwd, configPath)) ?? ""; switch (extname(cfg)) { case ".json": return loadJsonConfig(cfg); case ".yaml": case ".yml": return loadYamlConfig(cfg); case ".js": case ".cjs": case ".mjs": return loadJsConfig(cfg); case ".ts": case ".cts": case ".mts": return loadTsConfig(cfg); default: return DEFAULT_CONFIG; } }; /** * Returns the plugin instance that matches the given predicate * If there are more than one instance that matches the predicate, returns the first one * @param config * @param predicate */ export const getPluginInstance = (config: FullConfig, predicate: (plugin: PluginInstance) => boolean) => { return config?.plugins?.find(predicate); }; /** * Checks if the error is a module not found error * * @see https://nodejs.org/api/errors.html#err-module-not-found */ const isModuleNotFoundError = (err: unknown): err is Error & { code: "ERR_MODULE_NOT_FOUND" | "MODULE_NOT_FOUND" } => { return ( err instanceof Error && "code" in err && (err.code === "ERR_MODULE_NOT_FOUND" || err.code === "MODULE_NOT_FOUND") ); }; export const resolvePlugin = async (path: string): Promise => { // try to append @allurereport/plugin- scope if (!path.startsWith("@allurereport/plugin-")) { try { const module = await importWrapper(`@allurereport/plugin-${path}`); return module.default; } catch (err) { // Only suppress "module not found" errors // because we will try to resolve plugin without "@allurereport/plugin-" prefix if (!isModuleNotFoundError(err)) { // This means that there is a problem with the plugin code itself, so throw away! throw err; } } } try { const module = await importWrapper(path); return module.default; } catch { throw new Error(`Cannot resolve plugin: ${path}`); } }; const resolvePlugins = async (plugins: Record, context: NameContext) => { const pluginInstances: PluginInstance[] = []; for (const id in plugins) { const pluginConfig = plugins[id]; const pluginId = getPluginId(id); const { options: rawOptions, ...descriptor } = pluginConfig; for (const path of findUnsupportedExpressions(descriptor, () => false, ["plugins", id])) { warnUnsupportedExpression(path); } const Plugin = await resolvePlugin(pluginConfig.import ?? id); for (const path of findUnsupportedExpressions( rawOptions, (segments) => supportsPluginExpression(Plugin.configExpressions, segments.slice(3)), ["plugins", id, "options"], )) { warnUnsupportedExpression(path); } const options = resolvePluginOptions( pluginConfig.options, Plugin.configExpressions, `plugins[${JSON.stringify(id)}].options`, context, ); const enabled = pluginConfig.enabled ?? true; const constructorContext: PluginConstructorContext = {}; if ("enabled" in pluginConfig) { constructorContext.enabled = pluginConfig.enabled; } pluginInstances.push({ id: pluginId, enabled, options: options ?? {}, plugin: new Plugin(options, constructorContext), }); } return pluginInstances; };