import { existsSync, realpathSync, statSync, writeFileSync } from 'node:fs'; import { relative, resolve, sep } from 'node:path'; import { WorkflowExecutionFailure } from '@midscene/core/internal/test-runner'; import { runWithConsoleLogHandler } from '@midscene/shared/logger'; import { version } from '../../package.json'; import { formatCliError, formatConciseError } from './error-format'; import type { CliFailureContext } from './failure-format'; import { githubFailureAnnotation } from './github-reporter'; import { renderNodeSpec, sortNodesForSpec } from './node-spec'; import { prepareTestRun } from './prepare-test-run'; import { runPreparedTestProject } from './run-prepared-project'; import { captureTerminalOutput } from './terminal-output'; import { TerminalReporter, type TerminalReporterMode, } from './terminal-reporter'; import { loadTestProject } from './test-project'; import { DEFAULT_TEST_FILE_SELECTION, discoverTestConfig, } from './test-project-runner'; import type { TestProjectRunResult } from './types'; export interface TestCliIO { log(message: string): void; error(message: string): void; write?(message: string): void; isTTY?: boolean; columns?: number; rows?: number; onResize?(listener: () => void): () => void; } interface ParsedTestArgs { command?: 'nodes'; cwd: string; projectRoot?: string; testPath?: string; configPath?: string; resultDir?: string; projectNames?: string[]; reporter?: TerminalReporterMode; } export const parseTestCliArgs = ( args: string[], cwd = process.cwd(), ): ParsedTestArgs => { const command = args[0] === 'nodes' ? args[0] : undefined; const commandOffset = command ? 1 : 0; let inputPath: string | undefined; let configPath: string | undefined; let resultDir: string | undefined; const projectNames: string[] = []; let reporter: TerminalReporterMode | undefined; for (let index = commandOffset; index < args.length; index += 1) { const token = args[index]; const equal = token.startsWith('-') ? token.indexOf('=') : -1; const arg = equal < 0 ? token : token.slice(0, equal); const inlineValue = equal < 0 ? undefined : token.slice(equal + 1); if (!arg.startsWith('-')) { if (inputPath) throw new Error('Only one test file or directory is allowed.'); inputPath = resolve(cwd, arg); continue; } if ( arg === '--config' || arg === '--result-dir' || arg === '--project' || arg === '--reporter' ) { const value = inlineValue ?? args[index + 1]; if (!value || value.startsWith('--')) throw new Error(`${arg} requires a value.`); if (arg === '--config') configPath = value; else if (arg === '--result-dir') resultDir = resolve(cwd, value); else if (arg === '--project') projectNames.push(value); else { if (value !== 'default' && value !== 'verbose') throw new Error( `Unknown reporter: ${value}. Expected default or verbose.`, ); reporter = value; } if (inlineValue === undefined) index += 1; } else { throw new Error(`Unknown option: ${token}`); } } if (command === 'nodes' && resultDir) { throw new Error('--result-dir is not supported by nodes.'); } if (command === 'nodes' && reporter) throw new Error('--reporter is not supported by nodes.'); if (command === 'nodes' && projectNames.length > 1) { throw new Error('nodes accepts only one --project name.'); } return { ...(command ? { command } : {}), cwd, ...(command ? { projectRoot: inputPath } : { testPath: inputPath }), configPath, resultDir, ...(projectNames.length > 0 ? { projectNames } : {}), ...(reporter ? { reporter } : {}), }; }; const defaultCliIO: TestCliIO = { log: console.log, error: console.error, write: process.stdout.write.bind(process.stdout), isTTY: Boolean(process.stdout.isTTY && !process.env.CI), get columns() { return process.stdout.columns; }, get rows() { return process.stdout.rows; }, onResize(listener) { process.stdout.on('resize', listener); return () => process.stdout.off('resize', listener); }, }; const testCliHelp = `Midscene Test: run native cases/steps Test projects. Usage: midscene-test [file.yaml | directory] [options] midscene-test --config [options] midscene-test nodes [directory] [--config midscene.config.ts] midscene-test create --help midscene-test model verify Check model connectivity and Midscene compatibility Options: --config Native TypeScript or JavaScript Test config --project Select a native execution Project (repeatable) --result-dir Store Test result files in this directory --reporter Concise Case results or full step diagnostics --help, -h Show this help --version Show the package version With a config, run paths filter project files. Without one, they select standalone inputs. Run paths never change config discovery or the artifact root. For test runs, config discovery checks cwd only; --config is relative to cwd. The selected config directory becomes the test root. File include/exclude and tag rules still apply to explicit paths. Legacy tasks/flow YAML and its CLI options belong to the midscene command. `; const assertDirectory = (path: string, label: string): void => { if (!existsSync(path) || !statSync(path).isDirectory()) { throw new Error(`${label} does not exist or is not a directory: ${path}`); } }; const runNodesCommand = async ( options: ParsedTestArgs, io: TestCliIO, ): Promise => { const cwd = resolve(options.cwd); assertDirectory(cwd, 'Test working directory'); const projectRoot = options.projectRoot ? resolve(cwd, options.projectRoot) : undefined; if (projectRoot) assertDirectory(projectRoot, 'Test project directory'); const configSearchRoot = projectRoot ?? cwd; const configPath = options.configPath ? resolve(configSearchRoot, options.configPath) : discoverTestConfig(configSearchRoot); if (options.configPath && /\.ya?ml$/i.test(configPath!)) { throw new Error( `midscene-test nodes --config only accepts a native TypeScript or JavaScript project config: ${configPath}.`, ); } if (options.configPath && (!configPath || !existsSync(configPath))) { throw new Error(`Midscene config does not exist: ${configPath}`); } const project = await loadTestProject(configPath); const projectName = options.projectNames?.[0]; const selectedProjects = projectName ? project.projects.filter((candidate) => candidate.name === projectName) : project.projects; if (selectedProjects.length === 0) { throw new Error(`Unknown Midscene project: ${projectName}`); } // Check every Project before writing, including when only one is selected. const filenames = new Map(); const owners = new Map(); for (const executionProject of project.projects) { const safeName = executionProject.name .normalize('NFC') // biome-ignore lint/suspicious/noControlCharactersInRegex: filenames cannot contain control characters. .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '-') .replace(/[. ]+$/g, '-'); const filename = project.hasExplicitProjects ? `midscene-node-spec.${safeName}.md` : 'midscene-node-spec.md'; const key = filename.toLowerCase(); const owner = owners.get(key); if (owner !== undefined) { throw new Error( `Projects "${owner}" and "${executionProject.name}" generate the same Node Spec filename: ${filename}`, ); } owners.set(key, executionProject.name); filenames.set(executionProject.name, filename); } const specs = selectedProjects.map((executionProject) => { const nodes = sortNodesForSpec(executionProject.nodes.definitions()); const document = renderNodeSpec(nodes, { configPath: configPath ? relative(configSearchRoot, configPath).split(sep).join('/') : undefined, projects: [ { name: executionProject.name, files: executionProject.files ?? DEFAULT_TEST_FILE_SELECTION, }, ], }); return { executionProject, nodes, document }; }); for (const { executionProject, nodes, document } of specs) { for (const warning of document.warnings) { io.error(`midscene-test nodes: ${warning}`); } const specPath = resolve( configSearchRoot, filenames.get(executionProject.name)!, ); writeFileSync(specPath, document.markdown); if (project.hasExplicitProjects || projectName) { io.log(`Execution Project: ${executionProject.name}`); } io.log(`Registered Nodes (${nodes.length}):`); if (nodes.length === 0) { io.log('No nodes are registered by the current Test Project.'); } for (const node of nodes) { io.log( `- ${node.name}: ${node.description?.trim() || 'Description not declared.'}`, ); } io.log(`\nNode Spec generated: ${specPath}`); } }; const reportTestProjectResult = ( result: TestProjectRunResult, io: TestCliIO, reporter: TerminalReporter, projectRoot: string, infrastructureErrors: readonly unknown[] = result.errors ?? [], ): number => { reporter.finish(result); const reportedErrors = new Set(); const reportError = ( source: string, error: unknown, sourcePath?: string, context?: CliFailureContext, ): void => { if (error instanceof Error && reportedErrors.has(error)) return; reporter.failure(source, error, { projectRoot, ...context }); const annotation = githubFailureAnnotation( source, formatConciseError(error), sourcePath ? resolve(projectRoot, sourcePath) : undefined, ); if (annotation) io.log(annotation); // Infrastructure failures carry raw errors that can also be causes of // the contextual errors already printed from the execution result. const pending = [error]; while (pending.length > 0) { const current = pending.pop(); if (!(current instanceof Error) || reportedErrors.has(current)) continue; reportedErrors.add(current); pending.push(current.cause); if (current instanceof AggregateError) pending.push(...current.errors); } }; for (const failure of result.collectionErrors) { reportError( `${failure.projectName}/${failure.sourcePath}`, failure.error, failure.sourcePath, { projectName: failure.projectName, sourcePath: failure.sourcePath, phase: 'collection', }, ); } const finalDocuments = new Map( result.documents.map((document) => [document.documentId, document]), ); const documentContext = ( projectName: string, documentId: string, sourcePath: string, ) => { const project = result.projects.find( (project) => project.name === projectName, ); const document = finalDocuments.get(documentId); const plan = document?.plan ?? project?.plans?.find((plan) => plan.documentId === documentId); const fileIndex = document?.attemptIndex ?? 0; return { plan, projectName, sourcePath, ...(plan?.retry.scope === 'document' ? { fileAttempt: { index: fileIndex, total: Math.max(fileIndex + 1, plan.retry.count + 1), }, } : {}), caseAttempts: plan?.retry.scope === 'document' ? 1 : (plan?.retry.count ?? project?.retry ?? 0) + 1, }; }; const finalCases = new Map( result.cases.map((outcome) => [outcome.caseId, outcome]), ); for (const outcome of finalCases.values()) { if (outcome.status !== 'failed' || !outcome.run) continue; const run = outcome.run; const source = `${run.projectName}/${run.sourcePath} / ${run.name}`; const { caseAttempts, plan, ...scope } = documentContext( run.projectName, outcome.documentId, run.sourcePath, ); const context: CliFailureContext = { ...scope, caseName: run.name, attempt: { index: run.attemptIndex, total: Math.max(caseAttempts, run.attemptIndex + 1), }, }; const casePlan = plan?.cases.find((item) => item.caseId === outcome.caseId); for (const [phase, steps] of [ ['beforeEach', run.beforeEach], ['steps', run.steps], ['afterEach', run.afterEach], ] as const) { for (const step of steps) { if (step.error) { reportError( `${source} / ${step.phase}[${step.stepIndex + 1}] ${step.node}${run.attemptIndex ? ` (failed after ${run.attemptIndex + 1} attempts)` : ''}`, step.error, run.sourcePath, { ...context, step, stepCount: casePlan?.[phase].length }, ); } } } for (const [phase, errors] of [ ['execution', run.executionErrors], ['teardown', run.teardownErrors], ] as const) { for (const error of errors ?? []) reportError(source, error, run.sourcePath, { ...context, phase }); } } for (const document of finalDocuments.values()) { if (document.status !== 'failed') continue; const source = `${document.projectName}/${document.sourcePath}`; const { caseAttempts: _, plan, ...context } = documentContext( document.projectName, document.documentId, document.sourcePath, ); for (const [phase, steps] of [ ['beforeAll', document.beforeAll], ['afterAll', document.afterAll], ] as const) { for (const step of steps) { if (step.error) { reportError( `${source} / ${step.phase}[${step.stepIndex + 1}] ${step.node}`, step.error, document.sourcePath, { ...context, step, stepCount: plan?.[phase].length }, ); } } } for (const [phase, errors] of [ ['execution', document.executionErrors], ['teardown', document.teardownErrors], ] as const) { for (const error of errors ?? []) reportError(source, error, document.sourcePath, { ...context, phase }); } for (const failure of document.hostErrors ?? []) { reportError( `${source} / host ${failure.phase}`, failure.error, document.sourcePath, { ...context, phase: `host ${failure.phase}` }, ); } } for (const project of result.projects) { if (project.lifecycle?.setupError) { reportError( `${project.name} / setup`, project.lifecycle.setupError, undefined, { projectName: project.name, phase: 'setup' }, ); } for (const error of project.lifecycle?.teardownErrors ?? []) { reportError(`${project.name} / teardown`, error, undefined, { projectName: project.name, phase: 'teardown', }); } } for (const error of infrastructureErrors) { reportError('infrastructure', error); } reporter.summary(result); if (reporter.mode === 'verbose') io.log(`Results: ${result.resultDir}`); io.log(`Summary: ${result.summaryPath}`); if (result.markdownPath && reporter.mode === 'verbose') io.log(`Markdown: ${result.markdownPath}`); if (result.reportPath) io.log(`Report: ${result.reportPath}`); return result.exitCode; }; export async function runTestCli( args: string[], io: TestCliIO = defaultCliIO, // The executable entry owns external publishing of completed run results. onResult?: (result: TestProjectRunResult) => void, ): Promise { try { if (args[0] === 'model') { const { runModelCommand } = await import('./model-command'); return runModelCommand(args, undefined, { stdout: io.log, stderr: io.error, }); } if (args[0] === 'create') { const { runCreateCommand } = await import('./create-command'); await runCreateCommand(args.slice(1), io); return 0; } if (args.includes('--help') || args.includes('-h')) { io.log(testCliHelp); return 0; } if (args.includes('--version')) { io.log(version); return 0; } const options = parseTestCliArgs(args); if (options.command === 'nodes') { await runNodesCommand(options, io); return 0; } const reporter = new TerminalReporter(io, options.reporter); const restoreOutput = io === defaultCliIO && io.isTTY && options.reporter !== 'verbose' ? captureTerminalOutput((message, write) => reporter.output(message, write), ) : undefined; try { return await runWithConsoleLogHandler( (entry) => reporter.console(entry), async () => { const plan = await prepareTestRun({ ...options, onProgress: (message) => reporter.progress(message), onEvent: (event) => reporter.event(event), }); const projectRoot = realpathSync(plan.projectRoot); let result: TestProjectRunResult; try { result = await runPreparedTestProject(plan); } catch (error) { if (!(error instanceof WorkflowExecutionFailure)) throw error; reportTestProjectResult( error.result, io, reporter, projectRoot, error.errors, ); onResult?.(error.result); return 1; } const exitCode = reportTestProjectResult( result, io, reporter, projectRoot, ); onResult?.(result); return exitCode; }, ); } finally { try { reporter.dispose(); } finally { restoreOutput?.(); } } } catch (error) { io.error(formatCliError(error)); return 1; } }