@midscene/test 1.15.6 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"test-cli.mjs","sources":["webpack/runtime/define_property_getters","webpack/runtime/ensure_chunk","webpack/runtime/get javascript chunk filename","webpack/runtime/has_own_property","webpack/runtime/module_chunk_loading","../../src/cli/error-format.ts","../../src/cli/node-spec.ts","../../src/engine/registry.ts","../../src/cli/test-project.ts","../../src/parser/identifiers.ts","../../src/parser/normalize.ts","../../src/parser/source.ts","../../src/parser/variables.ts","../../src/parser/collect.ts","../../src/cli/result-store.ts","../../src/cli/project-preparation.ts","../../src/cli/prepare-test-run.ts","../../src/report/result-markdown.ts","../../src/cli/document-invocation.ts","../../src/cli/operation-journal.ts","../../src/cli/run-prepared-project.ts","../../src/cli/test-project-runner.ts","../../src/cli/test-command.ts","../../src/test-cli.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(\n\t\tObject.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t\t__webpack_require__.f[key](chunkId, promises);\n\t\t\treturn promises;\n\t\t}, [])\n\t);\n};","// This function allow to reference chunks\n__webpack_require__.u = (chunkId) => {\n // return url for filenames not based on template\n \n // return url for filenames based on template\n return \"1~\" + chunkId + \".mjs\"\n}","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// no BaseURI\n // object to store loaded and loading chunks\n // undefined = chunk not loaded, null = chunk preloaded/prefetched\n // [resolve, Promise] = chunk loading, 0 = chunk loaded\n var installedChunks = {\"443\": 0,};\n var installChunk = (data) => {\n var __rspack_esm_ids = data.__rspack_esm_ids;\n var __webpack_modules__ = data.__webpack_modules__;\n var __rspack_esm_runtime = data.__rspack_esm_runtime;\n // add \"modules\" to the modules object,\n // then flag all \"ids\" as loaded and fire callback\n var moduleId, chunkId, i = 0;\n for (moduleId in __webpack_modules__) {\n if (__webpack_require__.o(__webpack_modules__, moduleId)) {\n __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];\n }\n }\n if (__rspack_esm_runtime) __rspack_esm_runtime(__webpack_require__);\n for (; i < __rspack_esm_ids.length; i++) {\n chunkId = __rspack_esm_ids[i];\n if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n installedChunks[chunkId][0]();\n }\n installedChunks[__rspack_esm_ids[i]] = 0;\n }\n \n};\n __webpack_require__.f.j = function (chunkId, promises) {\n // import() chunk loading for javascript\nvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\nif (installedChunkData !== 0) { // 0 means \"already installed\".'\n // a Promise means \"currently loading\".\n if (installedChunkData) {\n promises.push(installedChunkData[1]);\n } else {\n if (true) {\n // setup Promise in chunk cache\n var promise = import(\"./\" + __webpack_require__.u(chunkId)).then(installChunk, (e) => {\n if (installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;\n throw e;\n });\n var promise = Promise.race([promise, new Promise((resolve) => {\n installedChunkData = installedChunks[chunkId] = [resolve];\n })]);\n promises.push(installedChunkData[1] = promise);\n }\n \n }\n}\n }\n // no external install chunk\n// no on chunks loaded\n// no HMR\n// no HMR manifest\n","import { inspect } from 'node:util';\n\n/** Keep native Error stacks, causes, and aggregate errors in CLI diagnostics. */\nexport const formatCliError = (error: unknown): string =>\n typeof error === 'string'\n ? error\n : inspect(error, { colors: false, depth: null, customInspect: false });\n","import { z } from 'zod/v4';\nimport type { NodeDefinition } from '../node/types';\nimport type { TestFileSelection } from './test-project';\n\nexport interface NodeSpecDocument {\n markdown: string;\n warnings: readonly string[];\n}\n\nconst GENERATED_COMMENT =\n '<!-- Generated by `midscene-test nodes`. Do not edit directly. -->';\n\nexport const sortNodesForSpec = (\n nodes: readonly NodeDefinition<any, any, any>[],\n): NodeDefinition<any, any, any>[] => {\n const priority = (name: string) =>\n name === 'aiAct' ? 0 : name === 'aiAssert' ? 1 : 2;\n return [...nodes].sort(\n (left, right) =>\n priority(left.name) - priority(right.name) ||\n (left.name < right.name ? -1 : left.name > right.name ? 1 : 0),\n );\n};\n\nconst escapeTableCell = (value: string): string =>\n value\n .trim()\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\|/g, '\\\\|')\n .replace(/\\r\\n|\\r|\\n/g, '<br>');\n\nconst renderNodeOverview = (\n nodes: readonly NodeDefinition<any, any, any>[],\n): string => {\n const heading = '## Available Nodes';\n if (nodes.length === 0) {\n return `${heading}\\n\\nNo nodes are registered by the current Test Project.`;\n }\n const rows = nodes.map(\n (node) =>\n `| ${escapeTableCell(node.name)} | ${escapeTableCell(node.description || 'Description not declared.')} |`,\n );\n return `${heading}\\n\\nThis table lists all available Nodes. See [Node Details](#node-details) below for each Node's usage and input schema.\\n\\n${['| Node | Description |', '| --- | --- |', ...rows].join('\\n')}`;\n};\n\ninterface NodeSpecLocation {\n configPath?: string;\n projects: readonly { name: string; files: TestFileSelection }[];\n}\n\nconst renderWorkflowLocations = (location?: NodeSpecLocation): string => {\n const sections = [\n '## Where to use these Nodes',\n 'Use these Nodes in Workflow Documents (`.yaml` or `.yml` files) selected by an Execution Project. Case file patterns and the config file path below are relative to this spec file. Case file patterns use glob syntax. A custom `--config` path does not change where case files are selected.',\n 'Projects created by `midscene-test create` select `cases/**/*.{yaml,yml}` by default, so you can write test cases in `cases/example.yaml` or subdirectories of `cases/`. If an Execution Project has no `files` configuration, Midscene Test searches `**/*.{yaml,yml}` recursively instead. Check `projects[].files` in your configuration before choosing a file location.',\n ];\n if (location) {\n sections.push(\n `**Config file:** ${location.configPath ? `\\`${location.configPath}\\`` : 'No config file loaded.'}`,\n );\n for (const project of location.projects) {\n const patterns = project.files.include\n .map((pattern) => `\\`${pattern}\\``)\n .join(', ');\n const projectLabel =\n location.projects.length > 1 || project.name !== 'default'\n ? ` (Execution Project: ${project.name})`\n : '';\n const excludes = project.files.exclude?.length\n ? `; excludes: ${project.files.exclude.map((pattern) => `\\`${pattern}\\``).join(', ')}`\n : '';\n sections.push(`**Case files:** ${patterns}${projectLabel}${excludes}`);\n }\n }\n sections.push(\n 'Files matching `files.exclude` are not selected. Midscene Test always ignores `.git/`, `.midscene/`, `midscene_run/`, and `node_modules/` directories, including nested ones.',\n 'Call a Node in `cases[].steps`, or in the Workflow Document lifecycle steps `beforeAll`, `beforeEach`, `afterEach`, and `afterAll`. Root Nodes are shared defaults; `projects[].nodes` adds local Nodes and overrides same-named root Nodes only within that Execution Project. Each Execution Project supplies its own runtime environment.',\n );\n return sections.join('\\n\\n');\n};\n\nconst WORKFLOW_STEP_CONTRACT = `## Workflow Step Contract\n\nEach step uses a node name as its key. The \\`$\\` object contains engine metadata and is not part of the node input.\n\n\\`\\`\\`yaml\ncases:\n - name: Example case\n steps:\n - node.name:\n prompt: Describe the task.\n $:\n timeout: 30000\n continue-on-error: false\n\\`\\`\\`\n\nA Node may map a string step value to one declared input field. Each Node section states whether it supports this shorthand and names the target field.\n\nEach Node's returned \\`data\\` is saved on that Step's result. Results are not named or automatically passed to later Steps. A failed Case does not stop later Cases by default; \\`test.bail\\` controls early stopping across the run.`;\n\nconst sortJsonValue = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortJsonValue);\n if (typeof value !== 'object' || value === null) return value;\n\n return Object.fromEntries(\n Object.entries(value)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([key, child]) => [key, sortJsonValue(child)]),\n );\n};\n\nconst assertSelfContainedRefs = (value: unknown, node: string): void => {\n if (Array.isArray(value)) {\n for (const child of value) assertSelfContainedRefs(child, node);\n return;\n }\n if (typeof value !== 'object' || value === null) return;\n\n for (const [key, child] of Object.entries(value)) {\n if (key === '$ref' && typeof child === 'string' && !child.startsWith('#')) {\n throw new Error(\n `Cannot describe node \"${node}\": inputSchema generated an external $ref.`,\n );\n }\n assertSelfContainedRefs(child, node);\n }\n};\n\nconst toJsonSchema = (node: NodeDefinition<any, any, any>): unknown => {\n try {\n const schema = z.toJSONSchema(node.inputSchema!, {\n target: 'draft-2020-12',\n io: 'input',\n unrepresentable: 'throw',\n cycles: 'ref',\n reused: 'ref',\n });\n assertSelfContainedRefs(schema, node.name);\n return sortJsonValue(schema);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.startsWith(`Cannot describe node \"${node.name}\":`)\n ) {\n throw error;\n }\n throw new Error(\n `Cannot describe node \"${node.name}\": inputSchema contains a Zod type that cannot be represented as JSON Schema.`,\n { cause: error },\n );\n }\n};\n\nconst renderNode = (\n node: NodeDefinition<any, any, any>,\n warnings: string[],\n): string => {\n const sections = [`### \\`${node.name}\\``];\n\n if (node.title) sections.push(`**Title:** ${node.title.trim()}`);\n if (node.description) {\n sections.push(node.description.trim());\n } else {\n warnings.push(`node \"${node.name}\" has no description`);\n sections.push(\n `> Description not declared. Do not infer this node's behavior.`,\n );\n }\n\n if (node.stringInputKey === false || node.stringInputKey === undefined) {\n sections.push('**String shorthand:** Not supported by this Node.');\n } else {\n sections.push(\n `**String shorthand:** Maps to \\`{ ${node.stringInputKey}: value }\\`.`,\n );\n }\n\n sections.push('#### Input Schema');\n if (node.inputSchema) {\n sections.push(\n `\\`\\`\\`json\\n${JSON.stringify(toJsonSchema(node), null, 2)}\\n\\`\\`\\``,\n );\n } else {\n warnings.push(`node \"${node.name}\" has no inputSchema`);\n sections.push(\n '> Input schema not declared. Do not invent input fields for this node.',\n );\n }\n\n return sections.join('\\n\\n');\n};\n\nexport const renderNodeSpec = (\n nodes: readonly NodeDefinition<any, any, any>[],\n location?: NodeSpecLocation,\n): NodeSpecDocument => {\n const warnings: string[] = [];\n const sortedNodes = sortNodesForSpec(nodes);\n const sections = [\n GENERATED_COMMENT,\n '# Midscene Test Node Spec',\n 'This document describes the Nodes available in YAML test files (`.yaml` or `.yml`) for the Midscene Test framework (`@midscene/test`). It lists the Nodes registered by the current Test Project, their inputs, and how to call them in test steps and lifecycle hooks.',\n [\n 'Learn about the framework and YAML test authoring:',\n '',\n '- [Midscene Test overview](https://midscenejs.com/midscene-test/overview): framework concepts and the role of Nodes.',\n '- [Create and use test projects](https://midscenejs.com/midscene-test/use): write YAML cases, run tests, and inspect results.',\n '- [Configure test projects](https://midscenejs.com/midscene-test/configuration): register Nodes, select case files, and manage runtime resources.',\n ].join('\\n'),\n renderNodeOverview(sortedNodes),\n renderWorkflowLocations(location),\n WORKFLOW_STEP_CONTRACT,\n ];\n\n if (sortedNodes.length > 0) {\n sections.push('## Node Details');\n for (const node of sortedNodes) sections.push(renderNode(node, warnings));\n }\n\n return {\n markdown: `${sections.join('\\n\\n')}\\n`,\n warnings,\n };\n};\n","import { NodeRegistry as CoreNodeRegistry } from '@midscene/core/internal/test-runner';\nimport type { NodeDefinition } from '../node/types';\n\nexport type NodeRegistry = Omit<\n CoreNodeRegistry,\n 'get' | 'require' | 'register' | 'definitions'\n> & {\n get(name: string): NodeDefinition<any, any> | undefined;\n require(name: string): NodeDefinition<any, any>;\n register<TInput, TData>(node: NodeDefinition<TInput, TData>): NodeRegistry;\n definitions(): readonly NodeDefinition<any, any, any>[];\n};\nexport const NodeRegistry: {\n new (nodes?: readonly NodeDefinition<any, any>[]): NodeRegistry;\n} = CoreNodeRegistry;\n","import { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { require as tsxRequire } from 'tsx/cjs/api';\nimport { NodeRegistry } from '../engine/registry';\nimport type { NodeDefinition } from '../node/types';\n\nimport type {\n JsonValue,\n ProjectSetupDefinition,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nexport type {\n JsonPrimitive,\n JsonValue,\n ProjectSetupContext,\n ProjectSetupDefinition,\n ProjectTeardown,\n ProjectTeardownContext,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nimport type { ExecutionProjectDefinition as CoreExecutionProjectDefinition } from '@midscene/core/internal/test-runner';\n\nexport type ExecutionProjectDefinition<TContext = unknown> = Omit<\n CoreExecutionProjectDefinition<TContext>,\n 'nodes'\n> & {\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n};\n\nexport interface TestOptions {\n maxConcurrency?: number;\n bail?: number;\n testTimeout?: number;\n}\n\nexport interface ResolvedTestOptions {\n maxConcurrency: number;\n bail: number;\n testTimeout: number;\n}\n\nexport interface TestOutputDefinition {\n reportDir?: string;\n}\n\nexport interface ResolvedTestOutputDefinition {\n reportDir: string;\n}\n\nconst projectIdFromIndex = (index: number): string => `project-${index}`;\n\nexport interface TestProjectDefinition<TContext = undefined> {\n setup?: ProjectSetupDefinition<TContext>;\n projects?: readonly ExecutionProjectDefinition<TContext>[];\n test?: TestOptions;\n output?: TestOutputDefinition;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n}\n\nexport interface LoadedExecutionProject<TProjectContext = unknown>\n extends ResolvedExecutionProject<TProjectContext> {\n /** Effective Nodes: globals plus project-local overrides. */\n readonly nodes: NodeRegistry;\n}\n\nexport interface LoadedTestProject<TContext = undefined> {\n projects: readonly LoadedExecutionProject<TContext>[];\n hasExplicitProjects: boolean;\n test: ResolvedTestOptions;\n output: ResolvedTestOutputDefinition;\n nodes: NodeRegistry;\n resolveNode(name: string): NodeDefinition<any, any, TContext> | undefined;\n}\n\nexport const defineTestProject = <TContext = undefined>(\n definition: TestProjectDefinition<TContext>,\n): TestProjectDefinition<TContext> => definition;\n\nexport const defineProjectSetup = <TProjectContext>(\n definition: ProjectSetupDefinition<TProjectContext>,\n): ProjectSetupDefinition<TProjectContext> => definition;\n\nconst getDefaultExport = (loaded: unknown, absolutePath: string): unknown => {\n if (typeof loaded === 'object' && loaded !== null && 'default' in loaded) {\n const defaultExport = (loaded as { default: unknown }).default;\n if (\n typeof defaultExport === 'object' &&\n defaultExport !== null &&\n '__esModule' in defaultExport\n ) {\n if ('default' in defaultExport) {\n return (defaultExport as { default: unknown }).default;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n }\n return defaultExport;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n label: string,\n): void => {\n const allowed = new Set(allowedKeys);\n const unknown = Object.keys(value).find((key) => !allowed.has(key));\n if (unknown) {\n throw new TypeError(\n `Midscene config ${label}.${unknown} is not supported.`,\n );\n }\n};\n\nconst isAbsolutePattern = (pattern: string): boolean =>\n isAbsolute(pattern) ||\n /^[A-Za-z]:[\\\\/]/.test(pattern) ||\n pattern.startsWith('\\\\\\\\');\n\nconst validatePatterns = (\n value: unknown,\n field: 'include' | 'exclude',\n label = 'files',\n allowEmptyInclude = false,\n): readonly string[] => {\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n if (field === 'include' && value.length === 0 && !allowEmptyInclude) {\n throw new TypeError(\n `Midscene config ${label}.include must be a non-empty array.`,\n );\n }\n\n return value.map((pattern, index) => {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n if (isAbsolutePattern(pattern)) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be relative to the project root.`,\n );\n }\n if (pattern.split(/[\\\\/]/).includes('..')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must not contain a \"..\" path segment.`,\n );\n }\n if (pattern.includes('\\\\')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`,\n );\n }\n if (pattern.startsWith('!')) {\n if (field === 'include') {\n throw new TypeError(\n `Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`,\n );\n }\n throw new TypeError(\n `Midscene config ${label}.exclude[${index}] must not be a negated pattern.`,\n );\n }\n return pattern;\n });\n};\n\nexport const validateTestFileSelection = (\n value: unknown,\n label = 'files',\n): TestFileSelection | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['include', 'exclude'], label);\n const include = validatePatterns(value.include, 'include', label);\n const exclude =\n value.exclude === undefined\n ? undefined\n : validatePatterns(value.exclude, 'exclude', label);\n return Object.freeze({\n include: Object.freeze(include),\n ...(exclude ? { exclude: Object.freeze(exclude) } : {}),\n });\n};\n\nconst validateTagList = (\n value: unknown,\n field: 'include' | 'exclude',\n label: string,\n): readonly string[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n return value.map((tag, index) => {\n if (typeof tag !== 'string' || tag.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n return tag;\n });\n};\n\nconst validateTagSelection = (\n value: unknown,\n label: string,\n): Readonly<Required<TestTagSelection>> => {\n if (value === undefined) return Object.freeze({ include: [], exclude: [] });\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n return Object.freeze({\n include: Object.freeze(validateTagList(value.include, 'include', label)),\n exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label)),\n });\n};\n\nfunction assertJsonValue(\n value: unknown,\n path: string,\n seen: Set<unknown>,\n): asserts value is JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean'\n ) {\n return;\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return;\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (typeof value !== 'object' || value === undefined) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (seen.has(value)) {\n throw new TypeError(`Midscene config ${path} must not contain cycles.`);\n }\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertJsonValue(item, `${path}[${index}]`, seen),\n );\n } else {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${path}.${key}`, seen);\n }\n }\n seen.delete(value);\n}\n\nconst deepFreezeJson = <T extends JsonValue>(value: T): T => {\n if (typeof value === 'object' && value !== null) {\n for (const child of Object.values(value)) deepFreezeJson(child);\n Object.freeze(value);\n }\n return value;\n};\n\nconst validateVariables = (\n value: unknown,\n label: string,\n): Readonly<Record<string, JsonValue>> => {\n if (value === undefined) return Object.freeze({});\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n assertJsonValue(value, label, new Set());\n return deepFreezeJson(value as Record<string, JsonValue>);\n};\n\nconst validateSetup = <TSetup>(\n value: unknown,\n label: string,\n): TSetup | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['name', 'setup'], label);\n if (typeof value.name !== 'string' || value.name.trim().length === 0) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (typeof value.setup !== 'function') {\n throw new TypeError(`Midscene config ${label}.setup must be a function.`);\n }\n return value as unknown as TSetup;\n};\n\nconst validatePositiveInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) <= 0) {\n throw new TypeError(`Midscene config ${label} must be a positive integer.`);\n }\n return value as number;\n};\n\nconst validateNonNegativeInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) < 0) {\n throw new TypeError(\n `Midscene config ${label} must be a non-negative integer.`,\n );\n }\n return value as number;\n};\n\nconst validateExecutionProjects = <TProjectContext>(\n value: unknown,\n defaultSetup: unknown,\n globalNodes: NodeRegistry,\n): {\n projects: readonly LoadedExecutionProject<TProjectContext>[];\n hasExplicitProjects: boolean;\n} => {\n if (value === undefined) {\n const setup = validateSetup<ProjectSetupDefinition<TProjectContext>>(\n defaultSetup,\n 'setup',\n );\n return {\n hasExplicitProjects: false,\n projects: Object.freeze([\n Object.freeze({\n projectId: projectIdFromIndex(0),\n name: 'default',\n ...(setup ? { setup } : {}),\n tags: Object.freeze({ include: [], exclude: [] }),\n retry: 0,\n variables: Object.freeze({}),\n nodes: new NodeRegistry(globalNodes.definitions()),\n }),\n ]),\n };\n }\n if (defaultSetup !== undefined) {\n throw new TypeError(\n 'Midscene config setup cannot be used together with projects. Move setup to projects[].setup.',\n );\n }\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(\n 'Midscene config projects must be a non-empty array when declared.',\n );\n }\n const names = new Set<string>();\n const projects = value.map((candidate, index) => {\n const label = `projects[${index}]`;\n if (!isRecord(candidate)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(\n candidate,\n ['name', 'setup', 'nodes', 'files', 'tags', 'retry', 'variables'],\n label,\n );\n if (\n typeof candidate.name !== 'string' ||\n candidate.name.trim().length === 0\n ) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (names.has(candidate.name)) {\n throw new TypeError(\n `Midscene config project name \"${candidate.name}\" must be unique.`,\n );\n }\n names.add(candidate.name);\n const files = validateTestFileSelection(candidate.files, `${label}.files`);\n if (candidate.nodes !== undefined && !Array.isArray(candidate.nodes)) {\n throw new TypeError(`Midscene config ${label}.nodes must be an array.`);\n }\n const localNodes = new NodeRegistry(\n candidate.nodes as NodeDefinition[] | undefined,\n );\n const nodes = new NodeRegistry([\n ...globalNodes.definitions().filter((node) => !localNodes.has(node.name)),\n ...localNodes.definitions(),\n ]);\n return Object.freeze({\n projectId: projectIdFromIndex(index),\n name: candidate.name,\n nodes,\n ...(files ? { files } : {}),\n tags: validateTagSelection(candidate.tags, `${label}.tags`),\n retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),\n variables: validateVariables(candidate.variables, `${label}.variables`),\n ...(candidate.setup === undefined\n ? {}\n : {\n setup: validateSetup<ProjectSetupDefinition<TProjectContext>>(\n candidate.setup,\n `${label}.setup`,\n )!,\n }),\n });\n });\n return { projects: Object.freeze(projects), hasExplicitProjects: true };\n};\n\nconst validateTestOptions = (value: unknown): ResolvedTestOptions => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config test must be an object.');\n }\n const candidate = value ?? {};\n return Object.freeze({\n maxConcurrency: validatePositiveInteger(\n (candidate as Record<string, unknown>).maxConcurrency,\n 1,\n 'test.maxConcurrency',\n ),\n bail: validateNonNegativeInteger(\n (candidate as Record<string, unknown>).bail,\n 0,\n 'test.bail',\n ),\n testTimeout: validatePositiveInteger(\n (candidate as Record<string, unknown>).testTimeout,\n 120_000,\n 'test.testTimeout',\n ),\n });\n};\n\nconst validateOutputPath = (\n value: unknown,\n fallback: string,\n label: string,\n): string => {\n if (value === undefined) return fallback;\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`Midscene config ${label} must be non-empty.`);\n }\n return value;\n};\n\nconst validateOutput = (value: unknown): ResolvedTestOutputDefinition => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config output must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n rejectUnknownKeys(candidate, ['reportDir'], 'output');\n return Object.freeze({\n reportDir: validateOutputPath(\n candidate.reportDir,\n './midscene_run/report',\n 'output.reportDir',\n ),\n });\n};\n\nconst validateTestProjectDefinition = <TContext>(\n definition: unknown,\n): LoadedTestProject<TContext> => {\n if (!isRecord(definition)) {\n throw new TypeError('Midscene config must default export an object.');\n }\n if (definition.nodes !== undefined && !Array.isArray(definition.nodes)) {\n throw new TypeError('Midscene config nodes must be an array.');\n }\n if ('setupWorkflow' in definition) {\n throw new TypeError(\n 'Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.',\n );\n }\n if ('setupDocument' in definition) {\n throw new TypeError(\n 'Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.',\n );\n }\n if ('root' in definition) {\n throw new TypeError(\n 'Midscene config root is not supported. Pass the Test Project directory to midscene-test instead.',\n );\n }\n if ('files' in definition) {\n throw new TypeError(\n 'Midscene config files is not supported at the root. Move it to projects[].files.',\n );\n }\n if ('testRunner' in definition) {\n throw new TypeError(\n 'Midscene config testRunner is not supported. Rename it to test.',\n );\n }\n rejectUnknownKeys(\n definition,\n ['setup', 'projects', 'test', 'output', 'nodes'],\n 'root',\n );\n const nodes = new NodeRegistry(\n definition.nodes as NodeDefinition[] | undefined,\n );\n const resolvedProjects = validateExecutionProjects<TContext>(\n definition.projects,\n definition.setup,\n nodes,\n );\n return {\n ...resolvedProjects,\n test: validateTestOptions(definition.test),\n output: validateOutput(definition.output),\n nodes,\n resolveNode: (name) =>\n nodes.get(name) as NodeDefinition<any, any, TContext> | undefined,\n };\n};\n\nconst assertSupportedConfig = (absolutePath: string): '.ts' | '.mjs' => {\n if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {\n const extension = absolutePath.match(/(\\.[^./\\\\]+)$/)?.[1] ?? '(none)';\n throw new TypeError(\n `Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`,\n );\n }\n return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';\n};\n\nconst canRetryWithCjsLoader = (error: unknown): error is Error => {\n if (!(error instanceof Error)) return false;\n const errorCode = (error as Error & { code?: string }).code;\n return (\n (error instanceof SyntaxError &&\n /^Unexpected (?:identifier|reserved word|token)/.test(error.message)) ||\n errorCode === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' ||\n (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION' &&\n /^Unknown file extension\\b/.test(error.message))\n );\n};\n\nexport async function loadTestProject<TContext = undefined>(\n configPath?: string,\n): Promise<LoadedTestProject<TContext>> {\n if (!configPath) {\n return validateTestProjectDefinition<TContext>({\n nodes: [],\n });\n }\n\n const absolutePath = resolve(configPath);\n const extension = assertSupportedConfig(absolutePath);\n let loaded: unknown;\n try {\n if (extension === '.mjs') {\n loaded = await import(pathToFileURL(absolutePath).href);\n } else {\n // Select tsx's ESM entry even when this loader is built as CommonJS.\n // Its CommonJS entry can resolve the async loader relative to the wrong directory.\n const { tsImport } = await import('tsx/esm/api');\n loaded = await tsImport(pathToFileURL(absolutePath).href, {\n parentURL: pathToFileURL(`${dirname(absolutePath)}${sep}`).href,\n tsconfig: false,\n });\n }\n } catch (error) {\n try {\n if (extension === '.mjs' || !canRetryWithCjsLoader(error)) throw error;\n loaded = tsxRequire(absolutePath, pathToFileURL(absolutePath));\n } catch (fallbackError) {\n const message =\n fallbackError instanceof Error ? `: ${fallbackError.message}` : '';\n throw new Error(\n `Failed to load Midscene config \"${absolutePath}\"${message}`,\n { cause: fallbackError },\n );\n }\n }\n\n return validateTestProjectDefinition<TContext>(\n getDefaultExport(loaded, absolutePath),\n );\n}\n","import { createHash } from 'node:crypto';\n\n/** Internal invocation identity keeps repeated legacy files distinct. */\nexport const createCaseInvocationId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n caseIndex,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n\nexport const createDocumentInvocationId = (\n projectId: string,\n sourcePath: string,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n","import {\n type ResolveNodeForNormalization,\n normalizeStep as coreNormalizeStep,\n normalizeSteps as coreNormalizeSteps,\n} from '@midscene/core/internal/test-runner';\nimport type { NormalizedStep } from './types';\nexport type { ResolveNodeForNormalization } from '@midscene/core/internal/test-runner';\n\nexport const normalizeStep: (\n value: unknown,\n index?: number,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep = coreNormalizeStep;\nexport const normalizeSteps: (\n values: unknown,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep[] = coreNormalizeSteps;\n","import type { TestRunReportValue } from '@midscene/core';\nimport {\n isReportSecretKey,\n sanitizeReportText,\n} from '@midscene/core/internal/test-runner';\nimport { JSON_SCHEMA, load } from 'js-yaml';\n\ninterface SourceNode {\n start: number;\n end: number;\n value: unknown;\n children: SourceNode[];\n}\n\n/** Keep author formatting while redacting values by parsed YAML keys, including aliases. */\nexport function parseWorkflowSource(source: string): {\n parsed: unknown;\n sourceYaml: TestRunReportValue;\n} {\n const stack: SourceNode[] = [];\n const nodes: SourceNode[] = [];\n const sensitiveNodes = new Set<SourceNode>();\n const sensitiveValues = new Set<unknown>();\n const redactedPaths = new Set<string>();\n // js-yaml removes the BOM before reporting source positions.\n const sourceOffset = source.charCodeAt(0) === 0xfeff ? 1 : 0;\n const parsed = load(source, {\n schema: JSON_SCHEMA,\n listener(event, state) {\n if (event === 'open') {\n stack.push({\n start: state.position + sourceOffset,\n end: 0,\n value: null,\n children: [],\n });\n return;\n }\n const node = stack.pop()!;\n node.end = state.position + sourceOffset;\n node.value = state.result;\n stack.at(-1)?.children.push(node);\n nodes.push(node);\n if (state.kind !== 'mapping') return;\n for (let index = 0; index < node.children.length; index += 2) {\n const key = node.children[index].value;\n const value = node.children[index + 1];\n if (typeof key !== 'string' || !isReportSecretKey(key) || !value)\n continue;\n sensitiveNodes.add(value);\n if (value.value !== null) sensitiveValues.add(value.value);\n redactedPaths.add(`$..[${JSON.stringify(key)}]`);\n }\n },\n });\n // Redact the definition as well when a secret value refers to a YAML anchor.\n const ranges = nodes\n .filter(\n (node) => sensitiveNodes.has(node) || sensitiveValues.has(node.value),\n )\n .sort((left, right) => left.start - right.start || right.end - left.end);\n let offset = 0;\n let redacted = '';\n for (const range of ranges) {\n if (range.start < offset) continue;\n const text = source.slice(range.start, range.end);\n const leading = text.match(/^\\s*/)?.[0] ?? '';\n const trailing = text.slice(leading.length).match(/\\s*$/)?.[0] ?? '';\n redacted += `${source.slice(offset, range.start)}${leading}\"[REDACTED]\"${trailing}`;\n offset = range.end;\n }\n redacted += source.slice(offset);\n const value = sanitizeReportText(redacted, 64 * 1024);\n return {\n parsed,\n sourceYaml: {\n value,\n ...(redactedPaths.size ? { redactedPaths: [...redactedPaths] } : {}),\n ...(value !== redacted ? { truncatedPaths: ['$'] } : {}),\n },\n };\n}\n","import type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\n\nexport interface VariableResolutionLocation {\n projectName: string;\n sourcePath: string;\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll';\n stepIndex: number;\n caseIndex?: number;\n}\n\nexport interface ResolveWorkflowVariablesOptions {\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n location: VariableResolutionLocation;\n}\n\nconst interpolationExpression =\n /\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}|\\$\\{([^{}]+)\\}/g;\nconst exactEnvExpression = /^\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}$/;\nconst exactProjectExpression = /^\\$\\{([^{}]+)\\}$/;\n\nconst missingVariable = (\n kind: 'environment' | 'project',\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): never => {\n throw new WorkflowParseError(\n `Undefined ${kind} variable \"${name}\" in ${options.location.sourcePath}.`,\n { ...options.location, variable: name, variableKind: kind },\n );\n};\n\nconst projectVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n if (!Object.hasOwn(options.variables ?? {}, name)) {\n return missingVariable('project', name, options);\n }\n return options.variables![name];\n};\n\nconst environmentVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n const value = options.env?.[name];\n if (value === undefined) return missingVariable('environment', name, options);\n return value;\n};\n\nconst interpolationValue = (\n name: string,\n value: JsonValue,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n if (typeof value === 'object' && value !== null) {\n throw new WorkflowParseError(\n `Project variable \"${name}\" must be a primitive when embedded in a string.`,\n {\n ...options.location,\n variable: name,\n variableKind: 'project',\n },\n );\n }\n return String(value);\n};\n\nconst resolveString = (\n value: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n const exactEnv = exactEnvExpression.exec(value);\n if (exactEnv) return environmentVariable(exactEnv[1], options);\n const exactProject = exactProjectExpression.exec(value);\n if (exactProject) return projectVariable(exactProject[1], options);\n\n return value.replace(\n interpolationExpression,\n (_match, environmentName: string | undefined, projectName: string) =>\n environmentName\n ? environmentVariable(environmentName, options)\n : interpolationValue(\n projectName,\n projectVariable(projectName, options),\n options,\n ),\n );\n};\n\nexport const resolveWorkflowVariables = (\n value: unknown,\n options: ResolveWorkflowVariablesOptions,\n): unknown => {\n if (typeof value === 'string') return resolveString(value, options);\n if (Array.isArray(value)) {\n return value.map((child) => resolveWorkflowVariables(child, options));\n }\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n resolveWorkflowVariables(child, options),\n ]),\n );\n }\n return value;\n};\n","import { readFileSync } from 'node:fs';\nimport { sep } from 'node:path';\nimport { classifyWorkflowDocumentFormat } from '@midscene/core/internal/test-runner';\nimport type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\nimport type { NodeDefinition } from '../node/types';\nimport {\n createCaseInvocationId,\n createDocumentInvocationId,\n} from './identifiers';\nimport { normalizeSteps } from './normalize';\nimport { parseWorkflowSource } from './source';\nimport type {\n CollectedCase,\n CollectedWorkflowDocument,\n WorkflowDocumentSource,\n} from './types';\nimport { resolveWorkflowVariables } from './variables';\n\nexport interface CollectWorkflowDocumentOptions {\n resolveNode(name: string): NodeDefinition<any, any> | undefined;\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n}\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nexport class NativeWorkflowFormatError extends WorkflowParseError {\n readonly actualFormat: 'legacy' | 'legacy-batch' | 'mixed';\n\n constructor(\n actualFormat: 'legacy' | 'legacy-batch' | 'mixed',\n sourcePath: string,\n ) {\n super(\n actualFormat === 'legacy'\n ? `Legacy tasks/flow YAML is not supported by midscene-test: ${sourcePath}. Run it with \\`midscene ${sourcePath}\\`, or migrate the file to cases/steps.`\n : actualFormat === 'legacy-batch'\n ? `Legacy YAML batch configuration is not a midscene-test workflow document: ${sourcePath}. Run it with \\`midscene --config ${sourcePath}\\`, or migrate it to a native project config.`\n : `A workflow file cannot mix legacy tasks/flow with native cases/steps or lifecycle hooks: ${sourcePath}. Keep the formats in separate files and run each file with its matching command.`,\n { sourcePath, actualFormat, expectedFormat: 'native' },\n );\n this.actualFormat = actualFormat;\n }\n}\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowed: readonly string[],\n label: string,\n) => {\n const allowedSet = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !allowedSet.has(key));\n if (unknown.length) {\n throw new WorkflowParseError(\n `${label} has unsupported field \"${unknown[0]}\".`,\n { field: unknown[0] },\n );\n }\n};\n\nexport const createCaseId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n): string => createCaseInvocationId(projectId, sourcePath, caseIndex);\n\nexport const createWorkflowDocumentId = (\n projectId: string,\n sourcePath: string,\n): string => createDocumentInvocationId(projectId, sourcePath);\n\nexport function collectWorkflowDocument(\n source: WorkflowDocumentSource,\n options: CollectWorkflowDocumentOptions,\n): CollectedWorkflowDocument {\n let snapshot: ReturnType<typeof parseWorkflowSource>;\n try {\n snapshot = parseWorkflowSource(readFileSync(source.absolutePath, 'utf8'));\n } catch (error) {\n throw new WorkflowParseError(\n `Failed to parse workflow document \"${source.sourcePath}\".`,\n { sourcePath: source.sourcePath },\n error,\n );\n }\n const { parsed, sourceYaml } = snapshot;\n\n if (!isMapping(parsed)) {\n throw new WorkflowParseError('Workflow document must be a mapping.');\n }\n const format = classifyWorkflowDocumentFormat(parsed);\n if (format === 'legacy' || format === 'legacy-batch' || format === 'mixed') {\n throw new NativeWorkflowFormatError(format, source.sourcePath);\n }\n rejectUnknownKeys(\n parsed,\n ['beforeAll', 'beforeEach', 'cases', 'afterEach', 'afterAll'],\n 'Workflow document',\n );\n if (!Array.isArray(parsed.cases) || parsed.cases.length === 0) {\n throw new WorkflowParseError(\n 'Workflow document must contain a non-empty cases array.',\n );\n }\n\n const sourcePath = source.sourcePath.split(sep).join('/');\n const resolveStepVariables = (\n step: ReturnType<typeof normalizeSteps>[number],\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll',\n stepIndex: number,\n caseIndex?: number,\n ) => ({\n ...step,\n templateInput: step.input,\n input: resolveWorkflowVariables(step.input, {\n variables: options.variables,\n env: options.env ?? process.env,\n location: {\n projectName: source.projectName ?? source.projectId,\n sourcePath,\n phase,\n stepIndex,\n ...(caseIndex === undefined ? {} : { caseIndex }),\n },\n }) as typeof step.input,\n });\n const normalizeLifecycle = (\n phase: 'beforeAll' | 'beforeEach' | 'afterEach' | 'afterAll',\n ) => {\n const value = parsed[phase];\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new WorkflowParseError(\n `Workflow document ${phase} must be an array.`,\n { phase },\n );\n }\n return normalizeSteps(value, options.resolveNode).map(\n (normalized, stepIndex) => {\n const resolved = options.resolveNode(normalized.node);\n if (!resolved) {\n throw new WorkflowParseError(\n `Workflow document ${phase} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { phase, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, phase, stepIndex);\n },\n );\n };\n const lifecycle = {\n beforeAll: normalizeLifecycle('beforeAll'),\n beforeEach: normalizeLifecycle('beforeEach'),\n afterEach: normalizeLifecycle('afterEach'),\n afterAll: normalizeLifecycle('afterAll'),\n };\n const ids = new Set<string>();\n const cases: CollectedCase[] = parsed.cases.map((definition, caseIndex) => {\n if (!isMapping(definition)) {\n throw new WorkflowParseError(`Case ${caseIndex + 1} must be a mapping.`, {\n caseIndex,\n });\n }\n rejectUnknownKeys(\n definition,\n ['name', 'tags', 'steps'],\n `Case ${caseIndex + 1}`,\n );\n if (\n typeof definition.name !== 'string' ||\n definition.name.trim().length === 0\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} name must be a non-empty string.`,\n { caseIndex },\n );\n }\n if (!Array.isArray(definition.steps) || definition.steps.length === 0) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} steps must be a non-empty array.`,\n { caseIndex },\n );\n }\n const tags = definition.tags ?? [];\n if (\n !Array.isArray(tags) ||\n tags.some((tag) => typeof tag !== 'string' || tag.trim().length === 0)\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} tags must be an array of non-empty strings.`,\n { caseIndex },\n );\n }\n\n const steps = normalizeSteps(definition.steps, options.resolveNode).map(\n (normalized, stepIndex) => {\n if (!options.resolveNode(normalized.node)) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { caseIndex, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, 'steps', stepIndex, caseIndex);\n },\n );\n const caseId = createCaseId(source.projectId, sourcePath, caseIndex);\n if (ids.has(caseId)) {\n throw new WorkflowParseError(`Case id collision: ${caseId}.`, {\n caseId,\n });\n }\n ids.add(caseId);\n\n return {\n caseId,\n projectId: source.projectId,\n sourcePath,\n caseIndex,\n definition: {\n name: definition.name,\n tags: tags as string[],\n steps,\n },\n };\n });\n\n return {\n documentId: createWorkflowDocumentId(source.projectId, sourcePath),\n projectId: source.projectId,\n sourcePath,\n sourceYaml,\n lifecycle,\n cases,\n } satisfies CollectedWorkflowDocument;\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport {\n WorkflowPublicationError,\n sanitizeReportError,\n} from '@midscene/core/internal/test-runner';\nimport type { CaseRunResult, WorkflowDocumentRunResult } from '../engine/types';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type { TestProjectCollectionError, TestProjectRunResult } from './types';\n\nconst writeJson = async (path: string, value: unknown) => {\n try {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, JSON.stringify(value, null, 2));\n } catch (error) {\n throw new WorkflowPublicationError('write-result', path, error);\n }\n};\n\nexport const writeTestRunPlan = (\n runDir: string,\n projects: readonly PreparedExecutionProject[],\n) =>\n writeJson(join(runDir, 'plan.json'), {\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n projects: projects.map((item) => ({\n projectId: item.project.projectId,\n name: item.project.name,\n documents: item.plans ?? [],\n })),\n });\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nexport const caseAttemptResultPath = (\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n): string =>\n toPosix(\n join(\n projectId,\n 'documents',\n documentId,\n 'cases',\n result.caseId,\n `${result.runId}.json`,\n ),\n );\n\nexport const workflowDocumentResultPath = (\n result: WorkflowDocumentRunResult,\n): string =>\n toPosix(\n join(\n result.projectId,\n 'documents',\n result.documentId,\n result.attemptIndex === undefined\n ? 'document.json'\n : `${result.documentRunId}.json`,\n ),\n );\n\nexport const collectionErrorPath = (\n projectId: string,\n sourcePath: string,\n): string => {\n const id = createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath]))\n .digest('hex');\n return toPosix(join(projectId, 'collection-errors', `${id}.json`));\n};\n\nexport const writeWorkflowDocumentResult = (\n runDir: string,\n result: WorkflowDocumentRunResult,\n) => {\n const { documentRunId: _documentRunId, ...persistedResult } = result;\n return writeJson(\n join(runDir, workflowDocumentResultPath(result)),\n persistedResult,\n );\n};\n\nexport const writeCaseAttemptResult = (\n runDir: string,\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n) => {\n const { runId: attemptId, ...persistedResult } = result;\n return writeJson(\n join(runDir, caseAttemptResultPath(projectId, documentId, result)),\n {\n ...persistedResult,\n attemptId,\n },\n );\n};\n\nexport const writeCollectionError = (\n runDir: string,\n collectionError: TestProjectCollectionError,\n) => {\n return writeJson(\n join(\n runDir,\n collectionErrorPath(\n collectionError.projectId,\n collectionError.sourcePath,\n ),\n ),\n { kind: 'collection-error', ...collectionError },\n );\n};\n\nconst relativeToSummary = (summaryPath: string, target: string): string => {\n const value = relative(dirname(summaryPath), target);\n return toPosix(value || '.');\n};\n\nconst errorJson = sanitizeReportError;\n\nexport interface TestProjectResultFileOptions {\n projectRoot: string;\n configPath?: string;\n result: TestProjectRunResult;\n}\n\nexport const writeTestProjectRunResult = (\n options: TestProjectResultFileOptions,\n) => {\n const { result } = options;\n const fact = (path: string) => toPosix(path);\n\n return writeJson(result.summaryPath, {\n schemaVersion: result.schemaVersion,\n runId: result.runId,\n startedAt: result.startedAt,\n endedAt: result.endedAt,\n durationMs: result.durationMs,\n status: result.status,\n exitCode: result.exitCode,\n ...(result.errors?.length ? { errors: result.errors.map(errorJson) } : {}),\n projectRoot: options.projectRoot,\n ...(options.configPath ? { configPath: options.configPath } : {}),\n factsRoot: '.',\n plan: 'plan.json',\n ...(result.operationLog\n ? {\n operationLog: {\n ...result.operationLog,\n path: relativeToSummary(\n result.summaryPath,\n result.operationLog.path,\n ),\n },\n }\n : {}),\n reportDir: relativeToSummary(result.summaryPath, result.reportDir),\n ...(result.reportPath\n ? { report: relativeToSummary(result.summaryPath, result.reportPath) }\n : {}),\n ...(result.markdownPath\n ? { markdown: relativeToSummary(result.summaryPath, result.markdownPath) }\n : {}),\n summary: result.summary,\n projects: result.projects.map((project) => ({\n projectId: project.projectId,\n name: project.name,\n status: project.status,\n retry: project.retry,\n fileSelection: project.fileSelection,\n tagSelection: project.tagSelection,\n sourceCount: project.sourceCount,\n selectedCaseCount: project.selectedCaseCount,\n filteredCaseCount: project.filteredCaseCount,\n ...(project.lifecycle\n ? {\n lifecycle: {\n status: project.lifecycle.status,\n startedAt: project.lifecycle.startedAt,\n endedAt: project.lifecycle.endedAt,\n durationMs: project.lifecycle.durationMs,\n ...(project.lifecycle.cleanup\n ? { cleanup: project.lifecycle.cleanup }\n : {}),\n ...(project.lifecycle.pendingOperations\n ? { pendingOperations: project.lifecycle.pendingOperations }\n : {}),\n ...(project.lifecycle.setupError\n ? { setupError: errorJson(project.lifecycle.setupError) }\n : {}),\n ...(project.lifecycle.teardownErrors\n ? {\n teardownErrors:\n project.lifecycle.teardownErrors.map(errorJson),\n }\n : {}),\n },\n }\n : {}),\n cases: project.cases.map((outcome) => ({\n ...(outcome.documentRunId\n ? { documentRunId: outcome.documentRunId }\n : {}),\n documentId: outcome.documentId,\n caseId: outcome.caseId,\n sourcePath: outcome.sourcePath,\n caseIndex: outcome.caseIndex,\n name: outcome.name,\n status: outcome.status,\n ...(outcome.notRunReason ? { notRunReason: outcome.notRunReason } : {}),\n ...(outcome.attempts\n ? {\n attempts: outcome.attempts.map((attempt) => ({\n attemptId: attempt.runId,\n attemptIndex: attempt.attemptIndex,\n status: attempt.status,\n ...(attempt.cleanup ? { cleanup: attempt.cleanup } : {}),\n ...(attempt.pendingOperations\n ? { pendingOperations: attempt.pendingOperations }\n : {}),\n ...(attempt.executionStatus\n ? { executionStatus: attempt.executionStatus }\n : {}),\n ...(attempt.retryDecision\n ? { retryDecision: attempt.retryDecision }\n : {}),\n resultFile: fact(\n caseAttemptResultPath(\n project.projectId,\n outcome.documentId,\n attempt,\n ),\n ),\n ...(attempt.reportPaths?.length\n ? {\n reports: attempt.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n }\n : {}),\n })),\n documents: project.documents.map((document) => ({\n documentId: document.documentId,\n ...(document.attemptIndex === undefined\n ? {}\n : {\n attemptIndex: document.attemptIndex,\n documentRunId: document.documentRunId,\n }),\n sourcePath: document.sourcePath,\n status: document.status,\n ...(document.cleanup ? { cleanup: document.cleanup } : {}),\n ...(document.pendingOperations\n ? { pendingOperations: document.pendingOperations }\n : {}),\n ...(document.executionStatus\n ? { executionStatus: document.executionStatus }\n : {}),\n ...(document.retryDecision\n ? { retryDecision: document.retryDecision }\n : {}),\n resultFile: fact(workflowDocumentResultPath(document)),\n ...(document.reportPaths?.length\n ? {\n reports: document.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n collectionErrors: project.collectionErrors.map((error) => ({\n sourcePath: error.sourcePath,\n errorFile: fact(collectionErrorPath(error.projectId, error.sourcePath)),\n })),\n })),\n });\n};\n","import { readdirSync } from 'node:fs';\nimport { join, relative, resolve, sep } from 'node:path';\nimport type { CollectedWorkflowDocument } from '@midscene/core/internal/test-runner';\nimport { buildTestRunReportPlan } from '@midscene/core/internal/test-runner';\nimport { globSync } from 'tinyglobby';\nimport { WorkflowError, WorkflowParseError } from '../errors';\nimport { collectWorkflowDocument } from '../parser/collect';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n ProjectPreparationOptions,\n} from './execution-plan';\nimport { writeCollectionError } from './result-store';\nimport type { LoadedExecutionProject, TestFileSelection } from './test-project';\nimport { validateTestFileSelection } from './test-project';\nimport type { TestProjectCollectionError } from './types';\n\nexport const CONFIG_NAMES = [\n 'midscene.config.ts',\n 'midscene.config.mjs',\n] as const;\nconst CONFIG_PREFIX = 'midscene.config.';\nconst ALWAYS_IGNORED_PATTERNS = [\n '.git/**',\n '.midscene/**',\n 'midscene_run/**',\n 'node_modules/**',\n '**/.git/**',\n '**/.midscene/**',\n '**/midscene_run/**',\n '**/node_modules/**',\n];\n\nexport const DEFAULT_TEST_FILE_SELECTION: TestFileSelection = {\n include: ['**/*.{yaml,yml}'],\n};\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nconst discoverResolvedTestFiles = (\n projectRoot: string,\n selection: TestFileSelection,\n): string[] => {\n const root = resolve(projectRoot);\n const match = (patterns: readonly string[]) =>\n globSync(patterns, {\n absolute: true,\n caseSensitiveMatch: false,\n cwd: root,\n dot: true,\n expandDirectories: false,\n followSymbolicLinks: false,\n ignore: [...ALWAYS_IGNORED_PATTERNS, ...(selection.exclude ?? [])],\n onlyFiles: true,\n }).filter((file) => /\\.ya?ml$/i.test(file));\n const files = match(selection.include);\n\n return [...new Set(files.map((file) => resolve(file)))].sort((a, b) => {\n const relativeA = toPosix(relative(root, a));\n const relativeB = toPosix(relative(root, b));\n return relativeA < relativeB ? -1 : relativeA > relativeB ? 1 : 0;\n });\n};\n\nexport const discoverTestFiles = (\n projectRoot: string,\n selection: TestFileSelection = DEFAULT_TEST_FILE_SELECTION,\n): string[] => {\n const normalized = validateTestFileSelection(selection);\n if (!normalized) throw new TypeError('Test file selection is required.');\n return discoverResolvedTestFiles(projectRoot, normalized);\n};\n\nexport const discoverTestConfig = (projectRoot: string): string | undefined => {\n const root = resolve(projectRoot);\n const candidates = readdirSync(root)\n .filter((name) => name.startsWith(CONFIG_PREFIX))\n .sort();\n const supported = candidates.filter((name) =>\n CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n const unsupported = candidates.filter(\n (name) => !CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n if (unsupported.length > 0) {\n throw new Error(\n [\n `Unsupported or conflicting Midscene configs found in ${root}:`,\n ...candidates.map((name) => `- ${name}`),\n `Only ${CONFIG_NAMES.join(' and ')} are supported.`,\n ].join('\\n'),\n );\n }\n if (supported.length > 1) {\n throw new Error(\n [\n `Multiple Midscene configs found in ${root}:`,\n ...supported.map((name) => `- ${name}`),\n 'Pass --config <path> to select one explicitly.',\n ].join('\\n'),\n );\n }\n return supported[0] ? join(root, supported[0]) : undefined;\n};\n\nconst asCollectionError = (\n projectId: string,\n projectName: string,\n sourcePath: string,\n error: unknown,\n): TestProjectCollectionError => ({\n projectId,\n projectName,\n sourcePath,\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowParseError(\n `Failed to collect workflow document \"${sourcePath}\": ${\n error instanceof Error ? error.message : String(error)\n }`,\n { projectName, sourcePath },\n error,\n ),\n});\n\nexport const matchesTags = (\n tags: readonly string[],\n selection: LoadedExecutionProject['tags'],\n): boolean => {\n if (selection.exclude.some((tag) => tags.includes(tag))) return false;\n return (\n selection.include.length === 0 ||\n selection.include.some((tag) => tags.includes(tag))\n );\n};\n\nconst filterDocumentCases = (\n document: CollectedWorkflowDocument,\n project: LoadedExecutionProject,\n): { document?: CollectedWorkflowDocument; filtered: number } => {\n const cases = document.cases.filter((item) =>\n matchesTags(item.definition.tags ?? [], project.tags),\n );\n const filtered = document.cases.length - cases.length;\n return cases.length === 0\n ? { filtered }\n : { document: { ...document, cases }, filtered };\n};\n\nexport const selectProjects = <TProjectContext>(\n projects: readonly LoadedExecutionProject<TProjectContext>[],\n names: readonly string[] | undefined,\n): readonly LoadedExecutionProject<TProjectContext>[] => {\n if (!names || names.length === 0) return projects;\n const requested = new Set(names);\n if (requested.size !== names.length) {\n throw new Error('Each --project name may only be specified once.');\n }\n const known = new Set(projects.map((project) => project.name));\n const unknown = names.find((name) => !known.has(name));\n if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);\n return projects.filter((project) => requested.has(project.name));\n};\n\n/** Prepare and validate every document before any Project resource is acquired. */\nexport async function prepareProject(\n project: LoadedExecutionProject,\n projectRoot: string,\n runDir: string,\n defaultTimeoutMs: number,\n options: ProjectPreparationOptions = {},\n): Promise<PreparedExecutionProject> {\n const platform = options.platform?.trim();\n const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;\n const prerequisiteFile = options.prerequisiteFile\n ? resolve(options.prerequisiteFile)\n : undefined;\n const mainFiles =\n options.files ?? discoverResolvedTestFiles(projectRoot, fileSelection);\n const files = [\n ...(prerequisiteFile ? [prerequisiteFile] : []),\n ...mainFiles.filter((file) => file !== prerequisiteFile),\n ];\n const occurrences = new Map<string, number>();\n const sources = files.map((absolutePath) => {\n const invocationIndex = occurrences.get(absolutePath) ?? 0;\n occurrences.set(absolutePath, invocationIndex + 1);\n return {\n projectId: project.projectId,\n projectName: project.name,\n sourcePath: toPosix(relative(projectRoot, absolutePath)),\n absolutePath,\n invocationIndex,\n };\n });\n const collectionErrors: TestProjectCollectionError[] = [];\n const invocations: PreparedDocumentInvocation[] = [];\n const plans: import('@midscene/core').TestRunReportDocumentPlan[] = [];\n let filteredCaseCount = 0;\n\n if (sources.length === 0) {\n const error = asCollectionError(\n project.projectId,\n project.name,\n '<project>',\n new WorkflowParseError(\n `No workflow YAML files found for project \"${project.name}\" in ${projectRoot}.`,\n { projectName: project.name, projectRoot },\n ),\n );\n collectionErrors.push(error);\n await writeCollectionError(runDir, error);\n }\n\n for (const source of sources) {\n try {\n const collected = await options.collectDocument?.(source, project);\n if (collected) {\n filteredCaseCount += collected.filteredCaseCount;\n if (collected.invocation) {\n const plan = buildTestRunReportPlan(collected.invocation.document, {\n defaultTimeoutMs: collected.invocation.defaultTimeoutMs,\n retry: collected.invocation.retry,\n });\n invocations.push({ ...collected.invocation, plan });\n plans.push(plan);\n }\n continue;\n }\n const document = collectWorkflowDocument(source, {\n resolveNode: project.nodes.get.bind(project.nodes),\n variables: project.variables,\n env: process.env,\n });\n const filtered =\n source.absolutePath === prerequisiteFile\n ? { document, filtered: 0 }\n : filterDocumentCases(document, project);\n const plan = buildTestRunReportPlan(document, {\n selectedCaseIds:\n filtered.document?.cases.map((item) => item.caseId) ?? [],\n defaultTimeoutMs,\n retry: { scope: 'case', count: project.retry },\n });\n plans.push(plan);\n filteredCaseCount += filtered.filtered;\n if (filtered.document)\n invocations.push({\n plan,\n document: filtered.document,\n retry: { scope: 'case', count: project.retry },\n defaultTimeoutMs,\n reportEnabled: true,\n bindings: { resolveNode: project.nodes.require.bind(project.nodes) },\n });\n } catch (error) {\n const collectionError = asCollectionError(\n project.projectId,\n project.name,\n source.sourcePath,\n error,\n );\n collectionErrors.push(collectionError);\n await writeCollectionError(runDir, collectionError);\n }\n }\n\n const documents = invocations.map((invocation) => invocation.document);\n const prerequisiteSource = sources.find(\n (source) => source.absolutePath === prerequisiteFile,\n );\n const prerequisiteDocument = documents.find(\n (document) => document.sourcePath === prerequisiteSource?.sourcePath,\n );\n return {\n project,\n ...(platform ? { platform } : {}),\n documentConcurrency: options.documentConcurrency ?? 1,\n ...(prerequisiteDocument\n ? { prerequisiteDocumentId: prerequisiteDocument.documentId }\n : {}),\n fileSelection,\n sources,\n documents,\n invocations,\n plans,\n collectionErrors,\n selectedCaseCount: documents.reduce(\n (total, document) => total + document.cases.length,\n 0,\n ),\n filteredCaseCount,\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, statSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { NativeWorkflowFormatError } from '../parser/collect';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n TestProjectRunOptions,\n TestRunInput,\n} from './execution-plan';\nimport {\n discoverTestConfig,\n prepareProject,\n selectProjects,\n} from './project-preparation';\nimport { loadTestProject } from './test-project';\n\nconst padDatePart = (value: number): string => String(value).padStart(2, '0');\n\nexport const createTestRunId = (\n date = new Date(),\n uuid = randomUUID(),\n): string => {\n const timestamp = [\n date.getFullYear(),\n padDatePart(date.getMonth() + 1),\n padDatePart(date.getDate()),\n padDatePart(date.getHours()),\n padDatePart(date.getMinutes()),\n padDatePart(date.getSeconds()),\n ].join('');\n return `${timestamp}-${uuid.slice(0, 8)}`;\n};\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nconst resolveRunInput = (options: TestProjectRunOptions): TestRunInput => {\n const cwd = resolve(options.cwd ?? process.cwd());\n assertDirectory(cwd, 'Test working directory');\n const inputPath = options.projectRoot\n ? resolve(cwd, options.projectRoot)\n : undefined;\n const singleFile =\n inputPath && existsSync(inputPath) && statSync(inputPath).isFile()\n ? inputPath\n : undefined;\n if (singleFile && !/\\.ya?ml$/i.test(singleFile))\n throw new Error(\n `Test input must be a YAML file or project directory: ${singleFile}`,\n );\n const cliProjectRoot = singleFile ? dirname(singleFile) : inputPath;\n if (cliProjectRoot) assertDirectory(cliProjectRoot, 'Test project directory');\n const projectRoot = cliProjectRoot ?? cwd;\n return {\n cwd,\n projectRoot,\n configSearchRoot: projectRoot,\n ...(singleFile ? { singleFile } : {}),\n };\n};\n\n/** Composition boundary only: execution receives no raw input syntax or host options. */\nexport async function prepareTestRun(\n options: TestProjectRunOptions,\n): Promise<PreparedTestRunPlan> {\n const startedAt = new Date();\n const runId = createTestRunId(startedAt);\n const input = resolveRunInput(options);\n const configPath = options.configPath\n ? resolve(input.configSearchRoot, options.configPath)\n : discoverTestConfig(input.configSearchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \\`midscene --config ${options.configPath}\\`.`,\n );\n }\n if (options.configPath && !existsSync(configPath!))\n throw new Error(`Midscene config does not exist: ${configPath}`);\n const definition = await loadTestProject<unknown>(configPath);\n const resultDir = options.resultDir\n ? resolve(input.cwd, options.resultDir)\n : join(input.projectRoot, '.midscene', 'test-results');\n const runDir = join(resultDir, runId);\n const summaryPath = join(runDir, 'summary.json');\n const reportDir = resolve(input.projectRoot, definition.output.reportDir);\n mkdirSync(resultDir, { recursive: true });\n mkdirSync(runDir);\n const projects: PreparedExecutionProject[] = [];\n for (const project of selectProjects(\n definition.projects,\n options.projectNames,\n ))\n projects.push(\n await prepareProject(\n project,\n input.projectRoot,\n runDir,\n definition.test.testTimeout,\n input.singleFile ? { files: [input.singleFile] } : undefined,\n ),\n );\n const hasFormatMismatch = projects.some((project) =>\n project.collectionErrors.some(\n ({ error }) => error instanceof NativeWorkflowFormatError,\n ),\n );\n return {\n startedAt,\n runId,\n projectRoot: input.projectRoot,\n ...(configPath ? { configPath } : {}),\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects,\n // A wrong-format file invalidates the complete command invocation. Other\n // native collection failures retain the existing per-Project isolation.\n preflightScope: hasFormatMismatch ? 'run' : 'project',\n reportEnabled: true,\n publications: [],\n onProgress: options.onProgress ?? (() => {}),\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport type {\n TestRunReportDump,\n TestRunReportSourceIndex,\n TestRunReportStep,\n} from '@midscene/core';\nimport type { TestProjectRunResult } from '../cli/types';\nimport { buildTestRunReportDump } from './test-run-report';\n\nconst text = (value: string): string =>\n value\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll('|', '&#124;')\n .replaceAll('[', '&#91;')\n .replaceAll(']', '&#93;')\n .replaceAll('*', '&#42;')\n .replaceAll('_', '&#95;')\n .replaceAll('`', '&#96;')\n .replaceAll('\\\\', '&#92;')\n .replace(/[\\r\\n]+/g, ' ');\n\nconst duration = (ms: number): string => {\n const seconds = Math.round(ms / 1000);\n return seconds < 60\n ? `${seconds}s`\n : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;\n};\nconst href = (from: string, target: string): string =>\n relative(dirname(from), target).split(sep).map(encodeURIComponent).join('/');\n\nexport interface TestResultMarkdownOptions {\n /** Relative or hosted URL of the HTML report. */\n reportHref?: string;\n}\n\n/** Render the same sanitized execution facts used by the HTML report. */\nexport function renderTestResultMarkdown(\n dump: TestRunReportDump,\n options: TestResultMarkdownOptions = {},\n): string {\n const { summary } = dump;\n const outcome =\n dump.status === 'success'\n ? `✅ **${summary.passed}/${summary.total} passed**`\n : `❌ **${summary.failed} failed** · ${summary.passed} passed · ${summary.notRun} not run`;\n const lines = [\n '## Midscene Test',\n '',\n `${outcome} · ${duration(dump.durationMs)}`,\n '',\n ];\n if (summary.filtered) lines.push(`**Filtered:** ${summary.filtered}`, '');\n const infrastructure = [\n summary.collectionErrors\n ? `${summary.collectionErrors} collection errors`\n : '',\n summary.documentFailures\n ? `${summary.documentFailures} document failures`\n : '',\n summary.projectFailures\n ? `${summary.projectFailures} project failures`\n : '',\n ].filter(Boolean);\n if (infrastructure.length)\n lines.push(`**Infrastructure:** ${infrastructure.join(' · ')}`, '');\n const groups: { name: string; rows: string[] }[] = [];\n const errors: string[] = [];\n const recordSteps = (label: string, steps: readonly TestRunReportStep[]) => {\n for (const step of steps) {\n if (step.status === 'failed')\n errors.push(\n `${label} / ${step.node}: ${step.error?.message ?? 'Step failed'}`,\n );\n }\n };\n for (const project of dump.projects) {\n if (project.lifecycle?.setupError)\n errors.push(`${project.name}: ${project.lifecycle.setupError.message}`);\n for (const error of project.lifecycle?.teardownErrors ?? [])\n errors.push(`${project.name}: ${error.message}`);\n for (const error of project.collectionErrors)\n errors.push(\n `${project.name} / ${error.sourcePath}: ${error.error.message}`,\n );\n for (const document of project.documents) {\n const name = document.sourcePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:yaml|yml)$/, '');\n const group = {\n name: dump.projects.length > 1 ? `${project.name} / ${name}` : name,\n rows: [] as string[],\n };\n groups.push(group);\n recordSteps(`${project.name} / ${document.sourcePath}`, [\n ...document.beforeAll,\n ...document.afterAll,\n ]);\n for (const error of document.teardownErrors ?? [])\n errors.push(`${document.sourcePath}: ${error.message}`);\n for (const failure of document.hostErrors ?? [])\n errors.push(\n `${document.sourcePath} / ${failure.phase}: ${failure.error.message}`,\n );\n for (const testCase of document.cases) {\n group.rows.push(\n ` - ${testCase.status === 'success' ? '✅' : testCase.status === 'not-run' ? '⏭️' : '❌'} ${text(testCase.name)}`,\n );\n }\n }\n }\n for (const diagnostic of dump.diagnostics ?? []) {\n if (diagnostic.level === 'error') errors.push(diagnostic.message);\n }\n if (errors.length)\n lines.push(\n '### Execution errors',\n '',\n ...errors.map((error) => `- ${text(error)}`),\n '',\n );\n for (const group of groups) {\n if (group.rows.length) lines.push(`- ${text(group.name)}`, ...group.rows);\n }\n if (!groups.some((group) => group.rows.length))\n lines.push('No cases were reported.');\n if (options.reportHref)\n lines.push(\n '',\n `[Open the Midscene Test report ↗](<${options.reportHref}>)`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n\nconst emptyIndex = (): TestRunReportSourceIndex => ({\n sources: [],\n metrics: {\n modelCallCount: 0,\n modelTimeMs: 0,\n promptTokens: 0,\n cachedInputTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n },\n});\n\n/** Write a per-run Markdown artifact even when HTML publication fails or is disabled. */\nexport async function writeTestResultMarkdown(\n result: TestProjectRunResult,\n index: TestRunReportSourceIndex = emptyIndex(),\n): Promise<string> {\n const output = join(dirname(result.summaryPath), 'result.md');\n const dump = buildTestRunReportDump(result, index);\n await writeFile(\n output,\n renderTestResultMarkdown(dump, {\n ...(result.reportPath\n ? { reportHref: href(output, result.reportPath) }\n : {}),\n }),\n );\n return output;\n}\n","import {\n WorkflowExecutionFailure,\n decideRetry,\n isResourceRecoveryError,\n runDocumentAttempts,\n runWorkflowDocument,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CaseRunOutcome,\n StepExecutionInfo,\n StepRunResult,\n WorkflowDocumentExecutionResult,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport { isFatalDeviceError } from '../errors';\nimport type { PreparedDocumentInvocation } from './execution-plan';\nimport {\n writeCaseAttemptResult,\n writeWorkflowDocumentResult,\n} from './result-store';\nimport type { LoadedExecutionProject } from './test-project';\nimport type { TestProjectCaseRunResult } from './types';\n\ninterface DocumentInvocationSinks {\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n}\n\ninterface ExecuteDocumentInvocationOptions {\n invocation: PreparedDocumentInvocation;\n project: LoadedExecutionProject<unknown>;\n projectContext: unknown;\n runDir: string;\n signal: AbortSignal;\n rootSignal: AbortSignal;\n shouldBail(): boolean;\n isProjectFatal(): boolean;\n markProjectFatal(): void;\n addFailedCases(count: number): void;\n onProgress(message: string): void;\n onDocumentResult?(result: WorkflowDocumentRunResult): Promise<void>;\n sinks: DocumentInvocationSinks;\n}\n\nconst stepPosition = (info: StepExecutionInfo) =>\n info.scope === 'case' ? info.case : info.document;\n\nconst formatStep = (info: StepExecutionInfo): string => {\n const position = stepPosition(info);\n const phase = position.phase === 'steps' ? 'step' : position.phase;\n return `${phase} ${position.stepIndex + 1}/${info.stepCount}: ${info.node}`;\n};\n\nconst formatStepResult = (\n info: StepExecutionInfo,\n result: StepRunResult,\n): string => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n if (result.status === 'not-run')\n return `${indent}– ${formatStep(info)} (not run: ${result.notRunReason})`;\n const symbol = result.status === 'success' ? '✓' : '✗';\n const error = result.error ? ` — ${result.error.message}` : '';\n const continuation = result.continuedAfterError ? '; continuing' : '';\n return `${indent}${symbol} ${formatStep(info)} (${result.durationMs} ms)${error}${continuation}`;\n};\n\nconst caseHasFatalError = (outcome: CaseRunOutcome): boolean =>\n (outcome.attempts ?? []).some(\n (attempt) =>\n [...attempt.beforeEach, ...attempt.steps, ...attempt.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (attempt.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!attempt.executionErrors?.some(isResourceRecoveryError),\n );\n\nconst documentHasFatalError = (result: WorkflowDocumentRunResult): boolean =>\n [...result.beforeAll, ...result.afterAll].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (result.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!result.executionErrors?.some(isResourceRecoveryError);\n\n/** Execute prepared document policies through the shared retry boundary. */\nexport async function executeDocumentInvocation(\n options: ExecuteDocumentInvocationOptions,\n): Promise<void> {\n const { invocation, project, sinks } = options;\n const { document } = invocation;\n const documentRetry = invocation.retry.scope === 'document';\n const attempts: WorkflowDocumentExecutionResult[] = [];\n\n await runDocumentAttempts(\n {\n retry: documentRetry ? invocation.retry.count : 0,\n signal: options.signal,\n shouldStop: () => options.shouldBail() || options.isProjectFatal(),\n },\n async (documentAttemptIndex) => {\n if (documentRetry)\n options.onProgress(\n ` file attempt ${documentAttemptIndex + 1}/${invocation.retry.count + 1}: ${document.sourcePath}`,\n );\n const execution = await runWorkflowDocument(document, {\n plan: invocation.plan,\n documentAttemptIndex: documentRetry ? documentAttemptIndex : undefined,\n ...invocation.bindings,\n project,\n projectContext: options.projectContext,\n retry: documentRetry ? 0 : invocation.retry.count,\n signal: options.signal,\n defaultTimeoutMs: invocation.defaultTimeoutMs,\n shouldStop: () =>\n options.rootSignal.aborted ||\n options.shouldBail() ||\n options.isProjectFatal(),\n stopReason: () =>\n options.rootSignal.aborted\n ? 'interrupted'\n : options.isProjectFatal()\n ? 'fatal-error'\n : 'bail',\n isFatalError: (run) =>\n [...run.beforeEach, ...run.steps, ...run.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) || (run.teardownErrors ?? []).some(isFatalDeviceError),\n onCaseStart: (collectedCase) => {\n options.onProgress(\n ` [case ${collectedCase.caseIndex + 1}/${document.cases.length}] ${collectedCase.definition.name}`,\n );\n },\n onStepStart: (info) => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n options.onProgress(`${indent}→ ${formatStep(info)}`);\n },\n onStepResult: async (info, result) => {\n await invocation.bindings.onStepResult?.(info, result);\n options.onProgress(formatStepResult(info, result));\n },\n onCaseResult: async (attempt) => {\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n options.onProgress(\n ` ${attempt.status === 'success' ? '✓' : '✗'} attempt ${attempt.attemptIndex + 1}/${documentRetry ? 1 : invocation.retry.count + 1}: ${attempt.name} (${attempt.durationMs} ms)`,\n );\n },\n onCaseOutcome: (outcome) => {\n if (caseHasFatalError(outcome)) options.markProjectFatal();\n if (!documentRetry && outcome.status === 'failed')\n options.addFailedCases(1);\n },\n onDocumentResult: options.onDocumentResult,\n }).catch(async (error: unknown) => {\n if (error instanceof WorkflowExecutionFailure) {\n const partial = error.result as WorkflowDocumentExecutionResult;\n const resourceOnly =\n error.errors.length > 0 &&\n error.errors.every(\n (failure) =>\n isResourceRecoveryError(failure) ||\n partial.document.hostErrors?.some(\n (host) =>\n host.phase === 'cleanup' &&\n (host.error === failure ||\n (host.error instanceof Error &&\n host.error.cause === failure)),\n ),\n );\n // Recovery and disposal failures stop this Project, not independent\n // Projects. Publication and other infrastructure failures still throw.\n if (resourceOnly) {\n if (error.errors.some(isResourceRecoveryError))\n options.markProjectFatal();\n return partial;\n }\n if (documentRetry)\n partial.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n attempts.push(partial);\n sinks.documents.push(partial.document);\n sinks.cases.push(\n ...partial.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: partial.document.documentRunId,\n })),\n );\n try {\n for (const outcome of partial.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, partial.document);\n } catch (publicationError) {\n throw new WorkflowExecutionFailure(partial, [\n ...error.errors,\n publicationError,\n ]);\n }\n }\n throw error;\n });\n\n if (documentHasFatalError(execution.document)) options.markProjectFatal();\n const owners = [\n execution.document,\n ...execution.cases.flatMap((outcome) => outcome.attempts ?? []),\n ];\n const cleanupPending = owners.some(\n (owner) => owner.cleanup?.status === 'pending',\n );\n const operationPending = owners.some(\n (owner) => !!owner.pendingOperations?.length,\n );\n const cleanupFailed = owners.some(\n (owner) =>\n owner.cleanup?.status === 'failed' ||\n !!owner.teardownErrors?.length ||\n ('hostErrors' in owner &&\n owner.hostErrors?.some(({ phase }) => phase === 'cleanup')),\n );\n // Files share the Project context; stop reusing it without cancelling\n // independent Projects. Publication and execution errors still throw.\n if (cleanupPending || cleanupFailed || operationPending)\n options.markProjectFatal();\n const failed =\n execution.document.status === 'failed' ||\n execution.cases.some((item) => item.status !== 'success');\n const decision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: failed ? 'failed' : 'success',\n cleanupPending,\n cleanupFailed,\n operationPending,\n fatalError: options.isProjectFatal(),\n interrupted: options.signal.aborted || options.rootSignal.aborted,\n shouldStop: options.shouldBail(),\n });\n if (documentRetry) execution.document.retryDecision = decision;\n attempts.push(execution);\n sinks.cases.push(\n ...execution.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: execution.document.documentRunId,\n })),\n );\n sinks.documents.push(execution.document);\n // Per-attempt callbacks publish incremental facts; seal the final retry\n // decision after callback-driven interruption/bail has been observed.\n try {\n for (const outcome of execution.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, execution.document);\n } catch (error) {\n execution.document.status = 'failed';\n execution.document.hostErrors = [\n ...(execution.document.hostErrors ?? []),\n { phase: 'publication', error },\n ];\n if (documentRetry)\n execution.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n throw new WorkflowExecutionFailure(execution, [error]);\n }\n return decision.decision === 'retry' ? 'failed' : undefined;\n },\n );\n\n const final = attempts.at(-1);\n if (!final) return;\n const failedCases = final.cases.filter(\n (item) => item.status === 'failed',\n ).length;\n if (documentRetry && failedCases) options.addFailedCases(failedCases);\n else if (final.document.status === 'failed' && failedCases === 0)\n options.addFailedCases(Math.max(1, failedCases));\n}\n","import { appendFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { TestRunReportOperationEvent } from '@midscene/core';\n\n/** Registered operations keep this sink after the report has been sealed.\n * Each small, bounded event is written before returning to the operation. No\n * open file descriptor or mutable report object is retained by the journal.\n */\nexport function createOperationJournal(runDir: string) {\n const path = join(runDir, 'operations.jsonl');\n writeFileSync(path, '', { flag: 'wx' });\n return {\n path,\n append(event: Readonly<TestRunReportOperationEvent>) {\n appendFileSync(path, `${JSON.stringify(event)}\\n`);\n },\n };\n}\n","import { setMaxListeners } from 'node:events';\nimport { dirname, join } from 'node:path';\nimport type { TestRunReportSourceIndex } from '@midscene/core';\nimport {\n WorkflowExecutionFailure,\n WorkflowPublicationError,\n asExecutionError,\n observeResourceOperations,\n runConcurrentJobs,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CollectedCase,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n TestRunReportAssembler,\n calculateTestRunHealth,\n} from '@midscene/core/report';\nimport { getDebug } from '@midscene/shared/logger';\nimport { createProjectRuntime } from '../engine/project-runtime';\nimport { writeTestResultMarkdown } from '../report/result-markdown';\nimport {\n buildTestRunReportDump,\n collectTestRunReportSources,\n} from '../report/test-run-report';\nimport { executeDocumentInvocation } from './document-invocation';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n PreparedTestRunPlan,\n} from './execution-plan';\nimport { createOperationJournal } from './operation-journal';\nimport { writeTestProjectRunResult, writeTestRunPlan } from './result-store';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n TestProjectRunResult,\n TestProjectRunSummary,\n} from './types';\n\nconst asNotRun = (\n documentId: string,\n collectedCase: CollectedCase,\n projectName: string,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult => ({\n documentId,\n caseId: collectedCase.caseId,\n projectName,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n});\n\nconst summarize = (\n projects: readonly TestExecutionProjectRunResult[],\n): TestProjectRunSummary => {\n const healthCases = projects.flatMap((project) => {\n const documentAttemptByRunId = new Map(\n project.documents.map((document) => [\n document.documentRunId,\n document.attemptIndex ?? 0,\n ]),\n );\n return latestById(project.cases, (item) => item.caseId).map((item) => {\n return {\n status: item.status,\n ...(item.run ? { run: item.run } : {}),\n ...(item.attempts ? { attempts: item.attempts } : {}),\n retryCount: item.documentRunId\n ? (documentAttemptByRunId.get(item.documentRunId) ?? 0)\n : 0,\n };\n });\n });\n const documents = projects.flatMap((project) =>\n latestById(project.documents, (item) => item.documentId),\n );\n const health = calculateTestRunHealth(healthCases);\n return {\n total: health.total,\n passed: health.passed,\n failed: health.failed,\n notRun: health.notRun,\n passedAfterRetry: health.passedAfterRetry,\n finalPassRate: health.finalPassRate,\n firstPassRate: health.firstPassRate,\n filtered: projects.reduce(\n (total, project) => total + project.filteredCaseCount,\n 0,\n ),\n collectionErrors: projects.reduce(\n (total, project) => total + project.collectionErrors.length,\n 0,\n ),\n documentFailures: documents.filter(\n (document) => document.status === 'failed',\n ).length,\n projectFailures: projects.filter((project) => project.status === 'failed')\n .length,\n };\n};\n\nconst latestById = <T>(items: readonly T[], id: (item: T) => string): T[] => [\n ...new Map(items.map((item) => [id(item), item])).values(),\n];\n\nconst notRunSuite = (\n prepared: PreparedExecutionProject,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult[] =>\n prepared.documents.flatMap((document) =>\n document.cases.map((item) =>\n asNotRun(document.documentId, item, prepared.project.name, reason),\n ),\n );\n\n/** The executor sees prepared policies and bindings, never source-language rules. */\nexport async function runPreparedTestProject(\n plan: PreparedTestRunPlan,\n): Promise<TestProjectRunResult> {\n const {\n startedAt,\n runId,\n projectRoot,\n configPath,\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects: preparedProjects,\n } = plan;\n const progress = plan.onProgress;\n const totalDocuments = preparedProjects.reduce(\n (total, prepared) => total + prepared.documents.length,\n 0,\n );\n const totalCases = preparedProjects.reduce(\n (total, prepared) => total + prepared.selectedCaseCount,\n 0,\n );\n const totalErrors = preparedProjects.reduce(\n (total, prepared) => total + prepared.collectionErrors.length,\n 0,\n );\n progress(\n `midscene-test: preflighted ${preparedProjects.length} projects, ${totalDocuments} documents, ${totalCases} cases, ${totalErrors} collection errors`,\n );\n\n const effectiveConcurrency = Math.min(\n definition.test.maxConcurrency,\n preparedProjects.length,\n );\n await writeTestRunPlan(runDir, preparedProjects);\n const journal = createOperationJournal(runDir);\n const rootController = new AbortController();\n setMaxListeners(\n Math.max(10, effectiveConcurrency + 1),\n rootController.signal,\n );\n const handleSignal = (signal: NodeJS.Signals) => {\n rootController.abort(new Error(`Workflow interrupted by ${signal}.`));\n };\n const sigint = () => handleSignal('SIGINT');\n const sigterm = () => handleSignal('SIGTERM');\n process.on('SIGINT', sigint);\n process.on('SIGTERM', sigterm);\n\n let failedCaseCount = 0;\n const bailReached = () =>\n definition.test.bail > 0 && failedCaseCount >= definition.test.bail;\n let hasInfrastructureError = false;\n const infrastructureErrors: unknown[] = [];\n const recordInfrastructureError = (error: unknown) => {\n const errors =\n error instanceof WorkflowExecutionFailure ? error.errors : [error];\n for (const item of errors)\n if (!infrastructureErrors.includes(item)) infrastructureErrors.push(item);\n hasInfrastructureError = true;\n rootController.abort(error);\n };\n const runInfrastructureCallback = <T>(callback: () => T): T => {\n try {\n return callback();\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n };\n const stopObservingOperations = observeResourceOperations(\n rootController.signal,\n (event) => {\n try {\n journal.append(event);\n } catch (error) {\n recordInfrastructureError(\n new WorkflowPublicationError('write-result', journal.path, error),\n );\n getDebug('test-runner:operations', { console: true })(\n `Could not persist operation event: ${String(error)}`,\n );\n }\n },\n );\n type PreparedProject = (typeof preparedProjects)[number];\n const announceProject = (prepared: PreparedProject, projectIndex: number) => {\n const { project } = prepared;\n runInfrastructureCallback(() =>\n progress(\n `[project ${projectIndex + 1}/${preparedProjects.length}] ${project.name}`,\n ),\n );\n };\n const buildProjectResult = (\n prepared: PreparedProject,\n cases: readonly TestProjectCaseRunResult[],\n documents: readonly WorkflowDocumentRunResult[],\n lifecycle?: TestExecutionProjectRunResult['lifecycle'],\n ): TestExecutionProjectRunResult => {\n const { project } = prepared;\n const projectFailed =\n prepared.collectionErrors.length > 0 ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n lifecycle?.status === 'failed';\n return {\n projectId: project.projectId,\n name: project.name,\n ...(prepared.platform ? { platform: prepared.platform } : {}),\n status: projectFailed ? 'failed' : 'success',\n retry: project.retry,\n fileSelection: prepared.fileSelection,\n tagSelection: project.tags,\n sourceCount: prepared.sources.length,\n selectedCaseCount: prepared.selectedCaseCount,\n filteredCaseCount: prepared.filteredCaseCount,\n ...(lifecycle ? { lifecycle } : {}),\n cases,\n plans: prepared.plans,\n documents,\n collectionErrors: prepared.collectionErrors,\n };\n };\n const buildSkippedProjectResult = (\n prepared: PreparedProject,\n projectIndex: number,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n ): TestExecutionProjectRunResult => {\n announceProject(prepared, projectIndex);\n return buildProjectResult(prepared, notRunSuite(prepared, reason), []);\n };\n const runPreparedProject = async (\n prepared: PreparedProject,\n projectIndex: number,\n ): Promise<TestExecutionProjectRunResult> => {\n const { project } = prepared;\n announceProject(prepared, projectIndex);\n const projectProgress = (message: string) =>\n runInfrastructureCallback(() =>\n progress(\n effectiveConcurrency > 1 ? `[${project.name}]${message}` : message,\n ),\n );\n const cases: TestProjectCaseRunResult[] = [];\n const documents: WorkflowDocumentRunResult[] = [];\n let lifecycle: TestExecutionProjectRunResult['lifecycle'];\n let projectFatal = false;\n\n if (\n prepared.collectionErrors.length > 0 ||\n (plan.preflightScope === 'run' && totalErrors > 0)\n ) {\n cases.push(...notRunSuite(prepared, 'project-preflight-failed'));\n } else if (rootController.signal.aborted) {\n cases.push(...notRunSuite(prepared, 'interrupted'));\n } else if (bailReached()) {\n cases.push(...notRunSuite(prepared, 'bail'));\n } else {\n const runtime = createProjectRuntime({\n project,\n setup: project.setup,\n signal: rootController.signal,\n });\n let hasProjectExecutionError = false;\n try {\n await runtime.start();\n if (!runtime.canRun) {\n cases.push(\n ...notRunSuite(\n prepared,\n rootController.signal.aborted\n ? 'interrupted'\n : 'project-setup-failed',\n ),\n );\n } else {\n const runDocument = async (\n invocation: PreparedDocumentInvocation,\n documentIndex: number,\n ) => {\n const { document } = invocation;\n if (\n rootController.signal.aborted ||\n bailReached() ||\n projectFatal\n ) {\n const reason = rootController.signal.aborted\n ? 'interrupted'\n : projectFatal\n ? 'fatal-error'\n : 'bail';\n cases.push(\n ...document.cases.map((item) =>\n asNotRun(document.documentId, item, project.name, reason),\n ),\n );\n return;\n }\n projectProgress(\n ` [document ${documentIndex + 1}/${prepared.documents.length}] ${document.sourcePath}`,\n );\n await executeDocumentInvocation({\n invocation,\n project,\n projectContext: runtime.context,\n runDir,\n signal: runtime.signal,\n rootSignal: rootController.signal,\n shouldBail: bailReached,\n isProjectFatal: () => projectFatal,\n markProjectFatal: () => {\n projectFatal = true;\n },\n addFailedCases: (count) => {\n failedCaseCount += count;\n },\n onProgress: projectProgress,\n sinks: {\n cases,\n documents,\n },\n });\n };\n let prerequisiteFailed = false;\n const prerequisite = prepared.invocations.find(\n (invocation) =>\n invocation.document.documentId ===\n prepared.prerequisiteDocumentId,\n );\n const prerequisiteCount = prerequisite ? 1 : 0;\n if (prerequisite) {\n await runDocument(prerequisite, 0);\n prerequisiteFailed =\n documents.at(-1)?.status === 'failed' ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n );\n }\n if (!prerequisiteFailed) {\n await runConcurrentJobs(\n prepared.invocations.filter(\n (invocation) => invocation !== prerequisite,\n ),\n {\n concurrency: prepared.documentConcurrency,\n shouldStop: () =>\n rootController.signal.aborted ||\n bailReached() ||\n projectFatal,\n },\n async (invocation, index) => {\n try {\n await runDocument(invocation, index + prerequisiteCount);\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n },\n );\n }\n const completed = new Set(cases.map((item) => item.caseId));\n const reason = prerequisiteFailed\n ? 'project-setup-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : projectFatal\n ? 'fatal-error'\n : 'bail';\n cases.push(\n ...notRunSuite(prepared, reason).filter(\n (item) => !completed.has(item.caseId),\n ),\n );\n }\n } catch (error) {\n hasProjectExecutionError = true;\n recordInfrastructureError(error);\n } finally {\n const hasFailure =\n hasProjectExecutionError ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n projectFatal ||\n rootController.signal.aborted;\n lifecycle = await runtime.finish(hasFailure ? 'failed' : 'success');\n }\n if (hasProjectExecutionError) {\n const completed = new Set(cases.map((item) => item.caseId));\n cases.push(\n ...notRunSuite(prepared, 'interrupted').filter(\n (item) => !completed.has(item.caseId),\n ),\n );\n }\n }\n\n const order = new Map(\n prepared.documents.map((document, index) => [document.documentId, index]),\n );\n const documentOrder = (id: string) =>\n order.get(id) ?? Number.MAX_SAFE_INTEGER;\n cases.sort(\n (a, b) =>\n documentOrder(a.documentId) - documentOrder(b.documentId) ||\n a.caseIndex - b.caseIndex,\n );\n documents.sort(\n (a, b) =>\n documentOrder(a.documentId) - documentOrder(b.documentId) ||\n (a.attemptIndex ?? 0) - (b.attemptIndex ?? 0),\n );\n return buildProjectResult(prepared, cases, documents, lifecycle);\n };\n\n const projectResults: Array<TestExecutionProjectRunResult | undefined> =\n new Array(preparedProjects.length);\n\n try {\n await runConcurrentJobs(\n preparedProjects,\n {\n concurrency: effectiveConcurrency,\n shouldStop: () =>\n hasInfrastructureError ||\n rootController.signal.aborted ||\n bailReached(),\n },\n async (prepared, index) => {\n try {\n projectResults[index] = await runPreparedProject(prepared, index);\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n },\n );\n } catch (error) {\n recordInfrastructureError(error);\n } finally {\n stopObservingOperations();\n process.off('SIGINT', sigint);\n process.off('SIGTERM', sigterm);\n }\n\n const completedProjectResults = preparedProjects.map(\n (prepared, projectIndex) => {\n const result = projectResults[projectIndex];\n if (result) return result;\n const reason = prepared.collectionErrors.length\n ? 'project-preflight-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : bailReached()\n ? 'bail'\n : undefined;\n if (!reason) {\n throw new Error(\n `Project scheduler did not produce a result for \"${prepared.project.name}\".`,\n );\n }\n return buildSkippedProjectResult(prepared, projectIndex, reason);\n },\n );\n\n const summary = summarize(completedProjectResults);\n const failed =\n hasInfrastructureError ||\n rootController.signal.aborted ||\n summary.failed > 0 ||\n summary.notRun > 0 ||\n summary.collectionErrors > 0 ||\n summary.documentFailures > 0 ||\n summary.projectFailures > 0;\n const endedAt = new Date();\n const result: TestProjectRunResult = {\n schemaVersion: 3,\n operationLog: { path: journal.path, snapshotAt: endedAt.toISOString() },\n runId,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n status: failed ? 'failed' : 'success',\n exitCode: failed ? 1 : 0,\n resultDir,\n summaryPath,\n reportDir,\n summary,\n projects: completedProjectResults,\n cases: completedProjectResults.flatMap((project) => project.cases),\n documents: completedProjectResults.flatMap((project) => project.documents),\n collectionErrors: completedProjectResults.flatMap(\n (project) => project.collectionErrors,\n ),\n ...(hasInfrastructureError\n ? { errors: infrastructureErrors.map(asExecutionError) }\n : {}),\n };\n let completedResult = result;\n let reportIndex: TestRunReportSourceIndex | undefined;\n const publish = async (\n operation: 'write-result' | 'write-report',\n path: string,\n callback: () => unknown | Promise<unknown>,\n ): Promise<boolean> => {\n try {\n await callback();\n return true;\n } catch (error) {\n recordInfrastructureError(\n error instanceof WorkflowPublicationError ||\n error instanceof WorkflowExecutionFailure\n ? error\n : new WorkflowPublicationError(operation, path, error),\n );\n completedResult = {\n ...completedResult,\n status: 'failed',\n exitCode: 1,\n errors: infrastructureErrors.map(asExecutionError),\n };\n return false;\n }\n };\n const writeSummary = () =>\n publish('write-result', summaryPath, () =>\n writeTestProjectRunResult({\n projectRoot,\n ...(configPath ? { configPath } : {}),\n result: completedResult,\n }),\n );\n const writeReport = () =>\n publish('write-report', reportDir, async () => {\n if (!plan.reportEnabled) return;\n const reportPath = await new TestRunReportAssembler().assembleAsync({\n outputDir: reportDir,\n reportFileName: `midscene-e2e-${runId}`,\n overwrite: false,\n sources: collectTestRunReportSources(completedResult),\n buildRunnerDump: (index) => {\n reportIndex = index;\n const dump = buildTestRunReportDump(completedResult, index);\n const warn = getDebug('test-runner:report-assembler', {\n console: true,\n });\n for (const diagnostic of dump.diagnostics ?? [])\n warn(diagnostic.message);\n return dump;\n },\n });\n completedResult = { ...completedResult, reportPath };\n });\n // Publish each artifact once. The summary includes the report path or its\n // failure. If the summary itself fails, the thrown result remains authoritative;\n // do not rebuild an already-published execution report to backfill that error.\n await writeReport();\n for (const publication of plan.publications)\n await publish(publication.operation, publication.path, async () => {\n await publication.publish(completedResult);\n });\n await publish(\n 'write-result',\n join(dirname(summaryPath), 'result.md'),\n async () => {\n const markdownPath = await writeTestResultMarkdown(\n completedResult,\n reportIndex,\n );\n completedResult = { ...completedResult, markdownPath };\n },\n );\n await writeSummary();\n if (hasInfrastructureError)\n throw new WorkflowExecutionFailure(completedResult, infrastructureErrors);\n return completedResult;\n}\n","import type { TestProjectRunOptions } from './execution-plan';\nimport { prepareTestRun } from './prepare-test-run';\nimport { runPreparedTestProject } from './run-prepared-project';\nimport type { TestProjectRunResult } from './types';\n\nexport type { TestProjectRunOptions } from './execution-plan';\nexport { createTestRunId } from './prepare-test-run';\nexport {\n DEFAULT_TEST_FILE_SELECTION,\n discoverTestConfig,\n discoverTestFiles,\n} from './project-preparation';\n\n/** Native Test entry for cases/steps workflow documents. */\nexport async function runTestProject(\n options: TestProjectRunOptions = {},\n): Promise<TestProjectRunResult> {\n return runPreparedTestProject(await prepareTestRun(options));\n}\n","import { existsSync, statSync, writeFileSync } from 'node:fs';\nimport { relative, resolve, sep } from 'node:path';\nimport { WorkflowExecutionFailure } from '@midscene/core/internal/test-runner';\nimport { version } from '../../package.json';\nimport { formatCliError } from './error-format';\nimport { renderNodeSpec, sortNodesForSpec } from './node-spec';\nimport { loadTestProject } from './test-project';\nimport {\n DEFAULT_TEST_FILE_SELECTION,\n discoverTestConfig,\n runTestProject,\n} from './test-project-runner';\nimport type { TestProjectRunResult } from './types';\n\nexport interface TestCliIO {\n log(message: string): void;\n error(message: string): void;\n write?(message: string): void;\n}\n\ninterface ParsedTestArgs {\n command?: 'nodes';\n cwd: string;\n projectRoot?: string;\n configPath?: string;\n resultDir?: string;\n projectNames?: string[];\n}\n\nexport const parseTestCliArgs = (\n args: string[],\n cwd = process.cwd(),\n): ParsedTestArgs => {\n const command = args[0] === 'nodes' ? args[0] : undefined;\n const commandOffset = command ? 1 : 0;\n let projectRoot: string | undefined;\n let configPath: string | undefined;\n let resultDir: string | undefined;\n const projectNames: string[] = [];\n\n for (let index = commandOffset; index < args.length; index += 1) {\n const token = args[index];\n const equal = token.startsWith('-') ? token.indexOf('=') : -1;\n const arg = equal < 0 ? token : token.slice(0, equal);\n const inlineValue = equal < 0 ? undefined : token.slice(equal + 1);\n if (!arg.startsWith('-')) {\n if (projectRoot)\n throw new Error('Only one test project directory is allowed.');\n projectRoot = resolve(cwd, arg);\n continue;\n }\n if (arg === '--config' || arg === '--result-dir' || arg === '--project') {\n const value = inlineValue ?? args[index + 1];\n if (!value || value.startsWith('--'))\n throw new Error(`${arg} requires a value.`);\n if (arg === '--config') configPath = value;\n else if (arg === '--result-dir') resultDir = resolve(cwd, value);\n else projectNames.push(value);\n if (inlineValue === undefined) index += 1;\n } else {\n throw new Error(`Unknown option: ${token}`);\n }\n }\n\n if (command === 'nodes' && resultDir) {\n throw new Error('--result-dir is not supported by nodes.');\n }\n if (command === 'nodes' && projectNames.length > 1) {\n throw new Error('nodes accepts only one --project name.');\n }\n return {\n ...(command ? { command } : {}),\n cwd,\n projectRoot,\n configPath,\n resultDir,\n ...(projectNames.length > 0 ? { projectNames } : {}),\n };\n};\n\nconst defaultCliIO: TestCliIO = {\n log: console.log,\n error: console.error,\n write: (message) => process.stdout.write(message),\n};\n\nconst testCliHelp = `Midscene Test: run native cases/steps Test projects.\n\nUsage:\n midscene-test [file.yaml | directory] [options]\n midscene-test --config <midscene.config.ts> [options]\n midscene-test nodes [directory] [--config midscene.config.ts]\n midscene-test create --help\n midscene-test model verify Check model connectivity and Midscene compatibility\n\nOptions:\n --config <path> Native TypeScript or JavaScript Test config\n --project <name> Select a native execution Project (repeatable)\n --result-dir <path> Store Test result files in this directory\n --help, -h Show this help\n --version Show the package version\n\nLegacy tasks/flow YAML and its CLI options belong to the midscene command.\n`;\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nconst runNodesCommand = async (\n options: ParsedTestArgs,\n io: TestCliIO,\n): Promise<void> => {\n const cwd = resolve(options.cwd);\n assertDirectory(cwd, 'Test working directory');\n const projectRoot = options.projectRoot\n ? resolve(cwd, options.projectRoot)\n : undefined;\n if (projectRoot) assertDirectory(projectRoot, 'Test project directory');\n\n const configSearchRoot = projectRoot ?? cwd;\n const configPath = options.configPath\n ? resolve(configSearchRoot, options.configPath)\n : discoverTestConfig(configSearchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test nodes --config only accepts a native TypeScript or JavaScript project config: ${configPath}.`,\n );\n }\n if (options.configPath && (!configPath || !existsSync(configPath))) {\n throw new Error(`Midscene config does not exist: ${configPath}`);\n }\n\n const project = await loadTestProject(configPath);\n const projectName = options.projectNames?.[0];\n const selectedProjects = projectName\n ? project.projects.filter((candidate) => candidate.name === projectName)\n : project.projects;\n if (selectedProjects.length === 0) {\n throw new Error(`Unknown Midscene project: ${projectName}`);\n }\n // Check every Project before writing, including when only one is selected.\n const filenames = new Map<string, string>();\n const owners = new Map<string, string>();\n for (const executionProject of project.projects) {\n const safeName = executionProject.name\n .normalize('NFC')\n // biome-ignore lint/suspicious/noControlCharactersInRegex: filenames cannot contain control characters.\n .replace(/[<>:\"/\\\\|?*\\u0000-\\u001f]/g, '-')\n .replace(/[. ]+$/g, '-');\n const filename = project.hasExplicitProjects\n ? `midscene-node-spec.${safeName}.md`\n : 'midscene-node-spec.md';\n const key = filename.toLowerCase();\n const owner = owners.get(key);\n if (owner !== undefined) {\n throw new Error(\n `Projects \"${owner}\" and \"${executionProject.name}\" generate the same Node Spec filename: ${filename}`,\n );\n }\n owners.set(key, executionProject.name);\n filenames.set(executionProject.name, filename);\n }\n const specs = selectedProjects.map((executionProject) => {\n const nodes = sortNodesForSpec(executionProject.nodes.definitions());\n const document = renderNodeSpec(nodes, {\n configPath: configPath\n ? relative(configSearchRoot, configPath).split(sep).join('/')\n : undefined,\n projects: [\n {\n name: executionProject.name,\n files: executionProject.files ?? DEFAULT_TEST_FILE_SELECTION,\n },\n ],\n });\n return { executionProject, nodes, document };\n });\n for (const { executionProject, nodes, document } of specs) {\n for (const warning of document.warnings) {\n io.error(`midscene-test nodes: ${warning}`);\n }\n const specPath = resolve(\n configSearchRoot,\n filenames.get(executionProject.name)!,\n );\n writeFileSync(specPath, document.markdown);\n if (project.hasExplicitProjects || projectName) {\n io.log(`Execution Project: ${executionProject.name}`);\n }\n io.log(`Registered Nodes (${nodes.length}):`);\n if (nodes.length === 0) {\n io.log('No nodes are registered by the current Test Project.');\n }\n for (const node of nodes) {\n io.log(\n `- ${node.name}: ${node.description?.trim() || 'Description not declared.'}`,\n );\n }\n io.log(`\\nNode Spec generated: ${specPath}`);\n }\n};\n\nconst reportTestProjectResult = (\n result: TestProjectRunResult,\n io: TestCliIO,\n infrastructureErrors: readonly unknown[] = result.errors ?? [],\n): number => {\n const reportedErrors = new Set<Error>();\n const reportError = (source: string, error: unknown): void => {\n if (error instanceof Error && reportedErrors.has(error)) return;\n io.error(`midscene-test: ${source}: ${formatCliError(error)}`);\n // Infrastructure failures carry raw errors that can also be causes of\n // the contextual errors already printed from the execution result.\n const pending = [error];\n while (pending.length > 0) {\n const current = pending.pop();\n if (!(current instanceof Error) || reportedErrors.has(current)) continue;\n reportedErrors.add(current);\n pending.push(current.cause);\n if (current instanceof AggregateError) pending.push(...current.errors);\n }\n };\n for (const failure of result.collectionErrors) {\n reportError(`${failure.projectName}/${failure.sourcePath}`, failure.error);\n }\n const finalCases = new Map(\n result.cases.map((outcome) => [outcome.caseId, outcome]),\n );\n for (const outcome of finalCases.values()) {\n if (outcome.status !== 'failed' || !outcome.run) continue;\n const run = outcome.run;\n const source = `${run.projectName}/${run.sourcePath} / ${run.name}`;\n for (const step of [...run.beforeEach, ...run.steps, ...run.afterEach]) {\n if (step.error) {\n reportError(\n `${source} / ${step.phase}[${step.stepIndex + 1}] ${step.node}`,\n step.error,\n );\n }\n }\n for (const error of [\n ...(run.executionErrors ?? []),\n ...(run.teardownErrors ?? []),\n ]) {\n reportError(source, error);\n }\n }\n const finalDocuments = new Map(\n result.documents.map((document) => [document.documentId, document]),\n );\n for (const document of finalDocuments.values()) {\n if (document.status !== 'failed') continue;\n const source = `${document.projectName}/${document.sourcePath}`;\n for (const step of [...document.beforeAll, ...document.afterAll]) {\n if (step.error) {\n reportError(\n `${source} / ${step.phase}[${step.stepIndex + 1}] ${step.node}`,\n step.error,\n );\n }\n }\n for (const error of [\n ...(document.executionErrors ?? []),\n ...(document.teardownErrors ?? []),\n ]) {\n reportError(source, error);\n }\n for (const failure of document.hostErrors ?? []) {\n reportError(`${source} / host ${failure.phase}`, failure.error);\n }\n }\n for (const project of result.projects) {\n if (project.lifecycle?.setupError) {\n reportError(`${project.name} / setup`, project.lifecycle.setupError);\n }\n for (const error of project.lifecycle?.teardownErrors ?? []) {\n reportError(`${project.name} / teardown`, error);\n }\n }\n for (const error of infrastructureErrors) {\n reportError('infrastructure', error);\n }\n io.log(\n `midscene-test: ${result.summary.passed}/${result.summary.total} cases passed, ${result.summary.failed} failed, ${result.summary.notRun} not run`,\n );\n io.log(`Results: ${result.resultDir}`);\n io.log(`Summary: ${result.summaryPath}`);\n if (result.markdownPath) io.log(`Markdown: ${result.markdownPath}`);\n if (result.reportPath) io.log(`Report: ${result.reportPath}`);\n return result.exitCode;\n};\n\nexport async function runTestCli(\n args: string[],\n io: TestCliIO = defaultCliIO,\n): Promise<number> {\n try {\n if (args[0] === 'model') {\n const { runModelCommand } = await import('./model-command');\n return runModelCommand(args, undefined, {\n stdout: io.log,\n stderr: io.error,\n });\n }\n if (args[0] === 'create') {\n const { runCreateCommand } = await import('./create-command');\n await runCreateCommand(args.slice(1), io);\n return 0;\n }\n if (args.includes('--help') || args.includes('-h')) {\n io.log(testCliHelp);\n return 0;\n }\n if (args.includes('--version')) {\n io.log(version);\n return 0;\n }\n const options = parseTestCliArgs(args);\n if (options.command === 'nodes') {\n await runNodesCommand(options, io);\n return 0;\n }\n let result: TestProjectRunResult;\n try {\n result = await runTestProject({\n ...options,\n onProgress: (message) => io.log(message),\n });\n } catch (error) {\n if (!(error instanceof WorkflowExecutionFailure)) throw error;\n reportTestProjectResult(error.result, io, error.errors);\n return 1;\n }\n return reportTestProjectResult(result, io);\n } catch (error) {\n io.error(formatCliError(error));\n return 1;\n }\n}\n","import { runTestCli } from './cli/test-command';\n\nvoid runTestCli(process.argv.slice(2)).then((exitCode) => {\n process.exitCode = exitCode;\n});\n"],"names":["__webpack_require__","exports","definition","key","Object","chunkId","Promise","promises","obj","prop","installedChunks","installChunk","data","__rspack_esm_ids","__webpack_modules__","__rspack_esm_runtime","moduleId","i","installedChunkData","promise","e","resolve","formatCliError","error","inspect","GENERATED_COMMENT","sortNodesForSpec","nodes","priority","name","left","right","escapeTableCell","value","renderNodeOverview","heading","rows","node","renderWorkflowLocations","location","sections","project","patterns","pattern","projectLabel","excludes","WORKFLOW_STEP_CONTRACT","sortJsonValue","Array","child","assertSelfContainedRefs","Error","toJsonSchema","schema","z","renderNode","warnings","undefined","JSON","renderNodeSpec","sortedNodes","NodeRegistry","CoreNodeRegistry","projectIdFromIndex","index","getDefaultExport","loaded","absolutePath","defaultExport","TypeError","isRecord","rejectUnknownKeys","allowedKeys","label","allowed","Set","unknown","isAbsolutePattern","isAbsolute","validatePatterns","field","allowEmptyInclude","validateTestFileSelection","include","exclude","validateTagList","tag","validateTagSelection","assertJsonValue","path","seen","Number","item","deepFreezeJson","validateVariables","validateSetup","validatePositiveInteger","fallback","validateNonNegativeInteger","validateExecutionProjects","defaultSetup","globalNodes","setup","names","projects","candidate","files","localNodes","validateTestOptions","validateOutputPath","validateOutput","validateTestProjectDefinition","resolvedProjects","assertSupportedConfig","extension","canRetryWithCjsLoader","errorCode","SyntaxError","loadTestProject","configPath","pathToFileURL","tsImport","dirname","sep","tsxRequire","fallbackError","message","createCaseInvocationId","projectId","sourcePath","caseIndex","invocationIndex","createHash","createDocumentInvocationId","normalizeSteps","coreNormalizeSteps","parseWorkflowSource","source","stack","sensitiveNodes","sensitiveValues","redactedPaths","sourceOffset","parsed","load","JSON_SCHEMA","event","state","isReportSecretKey","ranges","offset","redacted","range","text","leading","trailing","sanitizeReportText","interpolationExpression","exactEnvExpression","exactProjectExpression","missingVariable","kind","options","WorkflowParseError","projectVariable","environmentVariable","interpolationValue","String","resolveString","exactEnv","exactProject","_match","environmentName","projectName","resolveWorkflowVariables","isMapping","NativeWorkflowFormatError","actualFormat","allowedSet","createCaseId","createWorkflowDocumentId","collectWorkflowDocument","snapshot","readFileSync","sourceYaml","format","classifyWorkflowDocumentFormat","resolveStepVariables","step","phase","stepIndex","process","normalizeLifecycle","normalized","resolved","lifecycle","ids","cases","tags","steps","caseId","writeJson","mkdir","writeFile","WorkflowPublicationError","writeTestRunPlan","runDir","join","Date","toPosix","caseAttemptResultPath","documentId","result","workflowDocumentResultPath","collectionErrorPath","id","writeWorkflowDocumentResult","_documentRunId","persistedResult","writeCaseAttemptResult","attemptId","writeCollectionError","collectionError","relativeToSummary","summaryPath","target","relative","errorJson","sanitizeReportError","writeTestProjectRunResult","fact","outcome","attempt","document","CONFIG_NAMES","CONFIG_PREFIX","ALWAYS_IGNORED_PATTERNS","DEFAULT_TEST_FILE_SELECTION","discoverResolvedTestFiles","projectRoot","selection","root","match","globSync","file","a","b","relativeA","relativeB","discoverTestConfig","candidates","readdirSync","supported","unsupported","asCollectionError","WorkflowError","matchesTags","filterDocumentCases","filtered","selectProjects","requested","known","prepareProject","defaultTimeoutMs","platform","fileSelection","prerequisiteFile","mainFiles","occurrences","Map","sources","collectionErrors","invocations","plans","filteredCaseCount","collected","plan","buildTestRunReportPlan","documents","invocation","prerequisiteSource","prerequisiteDocument","total","padDatePart","createTestRunId","date","uuid","randomUUID","timestamp","assertDirectory","existsSync","statSync","resolveRunInput","cwd","inputPath","singleFile","cliProjectRoot","prepareTestRun","startedAt","runId","input","resultDir","reportDir","mkdirSync","hasFormatMismatch","duration","ms","seconds","Math","href","from","encodeURIComponent","renderTestResultMarkdown","dump","summary","lines","infrastructure","Boolean","groups","errors","recordSteps","group","failure","testCase","diagnostic","emptyIndex","writeTestResultMarkdown","output","buildTestRunReportDump","stepPosition","info","formatStep","position","formatStepResult","indent","symbol","continuation","caseHasFatalError","isFatalDeviceError","isResourceRecoveryError","documentHasFatalError","executeDocumentInvocation","sinks","documentRetry","attempts","runDocumentAttempts","documentAttemptIndex","execution","runWorkflowDocument","run","collectedCase","WorkflowExecutionFailure","partial","resourceOnly","host","decideRetry","publicationError","owners","cleanupPending","owner","operationPending","cleanupFailed","failed","decision","final","failedCases","createOperationJournal","writeFileSync","appendFileSync","asNotRun","reason","summarize","healthCases","documentAttemptByRunId","latestById","health","calculateTestRunHealth","items","notRunSuite","prepared","runPreparedTestProject","preparedProjects","progress","totalDocuments","totalCases","totalErrors","effectiveConcurrency","journal","rootController","AbortController","setMaxListeners","handleSignal","signal","sigint","sigterm","failedCaseCount","bailReached","hasInfrastructureError","infrastructureErrors","recordInfrastructureError","runInfrastructureCallback","callback","stopObservingOperations","observeResourceOperations","getDebug","announceProject","projectIndex","buildProjectResult","projectFailed","buildSkippedProjectResult","runPreparedProject","projectProgress","projectFatal","runtime","createProjectRuntime","hasProjectExecutionError","runDocument","documentIndex","count","prerequisiteFailed","prerequisite","prerequisiteCount","runConcurrentJobs","completed","hasFailure","order","documentOrder","projectResults","completedProjectResults","endedAt","asExecutionError","completedResult","reportIndex","publish","operation","writeSummary","writeReport","reportPath","TestRunReportAssembler","collectTestRunReportSources","warn","publication","markdownPath","runTestProject","parseTestCliArgs","args","command","commandOffset","projectNames","token","equal","arg","inlineValue","defaultCliIO","console","testCliHelp","runNodesCommand","io","configSearchRoot","selectedProjects","filenames","executionProject","safeName","filename","specs","warning","specPath","reportTestProjectResult","reportedErrors","reportError","pending","current","AggregateError","finalCases","finalDocuments","runTestCli","runModelCommand","runCreateCommand","version","exitCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAAA,oBAAoB,CAAC,GAAG,CAACC,SAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGF,oBAAoB,CAAC,CAACE,YAAYC,QAAQ,CAACH,oBAAoB,CAAC,CAACC,SAASE,MACzEC,OAAO,cAAc,CAACH,SAASE,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAH,oBAAoB,CAAC,GAAG,CAAC;IAGzBA,oBAAoB,CAAC,GAAG,CAACK,UACjBC,QAAQ,GAAG,CACjBF,OAAO,IAAI,CAACJ,oBAAoB,CAAC,EAAE,MAAM,CAAC,CAACO,UAAUJ;YACpDH,oBAAoB,CAAC,CAACG,IAAI,CAACE,SAASE;YACpC,OAAOA;QACR,GAAG,EAAE;;;ICPPP,oBAAoB,CAAC,GAAG,CAACK,UAIhB,OAAOA,UAAU;;;ICL1BL,oBAAoB,CAAC,GAAG,CAACQ,KAAKC,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KAAK,QAAQ,CAAC,aAAaA,KAAK,QAAQ,CAAC,OAAO;YAClDY,GAAG,GAAG,CAACF;YACP,OAAO;QACT;QACA,IAAIV,KAAK,QAAQ,CAAC,cAAc;YAC9BY,GAAG,GAAG,CAACqB,UAAAA,EAAOA;YACd,OAAO;QACT;QACA,MAAM5T,UAAU0R,iBAAiBC;QACjC,IAAI3R,AAAoB,YAApBA,QAAQ,OAAO,EAAc;YAC/B,MAAMsS,gBAAgBtS,SAASuS;YAC/B,OAAO;QACT;QACA,IAAIrP;QACJ,IAAI;YACFA,SAAS,MAAMuO,eAAe;gBAC5B,GAAGzR,OAAO;gBACV,YAAY,CAACpC,UAAY2U,GAAG,GAAG,CAAC3U;YAClC;QACF,EAAE,OAAOvG,OAAO;YACd,IAAI,CAAEA,CAAAA,iBAAiBwU,wBAAuB,GAAI,MAAMxU;YACxD4b,wBAAwB5b,MAAM,MAAM,EAAEkb,IAAIlb,MAAM,MAAM;YACtD,OAAO;QACT;QACA,OAAO4b,wBAAwB/P,QAAQqP;IACzC,EAAE,OAAOlb,OAAO;QACdkb,GAAG,KAAK,CAACnb,eAAeC;QACxB,OAAO;IACT;AACF;ACnVKoc,WAAW5R,QAAQ,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,CAACgS;IAC3ChS,QAAQ,QAAQ,GAAGgS;AACrB"}
1
+ {"version":3,"file":"test-cli.mjs","sources":["webpack/runtime/define_property_getters","webpack/runtime/ensure_chunk","webpack/runtime/get javascript chunk filename","webpack/runtime/has_own_property","webpack/runtime/module_chunk_loading","../../src/cli/error-format.ts","../../src/cli/node-spec.ts","../../src/engine/registry.ts","../../src/cli/test-project.ts","../../src/parser/identifiers.ts","../../src/parser/normalize.ts","../../src/parser/source.ts","../../src/parser/variables.ts","../../src/parser/collect.ts","../../src/cli/result-store.ts","../../src/cli/project-preparation.ts","../../src/cli/prepare-test-run.ts","../../src/report/result-markdown.ts","../../src/cli/document-invocation.ts","../../src/cli/file-scheduler.ts","../../src/cli/operation-journal.ts","../../src/cli/run-prepared-project.ts","../../src/cli/test-project-runner.ts","../../src/cli/test-command.ts","../../src/test-cli.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(\n\t\tObject.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t\t__webpack_require__.f[key](chunkId, promises);\n\t\t\treturn promises;\n\t\t}, [])\n\t);\n};","// This function allow to reference chunks\n__webpack_require__.u = (chunkId) => {\n // return url for filenames not based on template\n \n // return url for filenames based on template\n return \"1~\" + chunkId + \".mjs\"\n}","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// no BaseURI\n // object to store loaded and loading chunks\n // undefined = chunk not loaded, null = chunk preloaded/prefetched\n // [resolve, Promise] = chunk loading, 0 = chunk loaded\n var installedChunks = {\"443\": 0,};\n var installChunk = (data) => {\n var __rspack_esm_ids = data.__rspack_esm_ids;\n var __webpack_modules__ = data.__webpack_modules__;\n var __rspack_esm_runtime = data.__rspack_esm_runtime;\n // add \"modules\" to the modules object,\n // then flag all \"ids\" as loaded and fire callback\n var moduleId, chunkId, i = 0;\n for (moduleId in __webpack_modules__) {\n if (__webpack_require__.o(__webpack_modules__, moduleId)) {\n __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];\n }\n }\n if (__rspack_esm_runtime) __rspack_esm_runtime(__webpack_require__);\n for (; i < __rspack_esm_ids.length; i++) {\n chunkId = __rspack_esm_ids[i];\n if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n installedChunks[chunkId][0]();\n }\n installedChunks[__rspack_esm_ids[i]] = 0;\n }\n \n};\n __webpack_require__.f.j = function (chunkId, promises) {\n // import() chunk loading for javascript\nvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\nif (installedChunkData !== 0) { // 0 means \"already installed\".'\n // a Promise means \"currently loading\".\n if (installedChunkData) {\n promises.push(installedChunkData[1]);\n } else {\n if (true) {\n // setup Promise in chunk cache\n var promise = import(\"./\" + __webpack_require__.u(chunkId)).then(installChunk, (e) => {\n if (installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;\n throw e;\n });\n var promise = Promise.race([promise, new Promise((resolve) => {\n installedChunkData = installedChunks[chunkId] = [resolve];\n })]);\n promises.push(installedChunkData[1] = promise);\n }\n \n }\n}\n }\n // no external install chunk\n// no on chunks loaded\n// no HMR\n// no HMR manifest\n","import { inspect } from 'node:util';\n\n/** Keep native Error stacks, causes, and aggregate errors in CLI diagnostics. */\nexport const formatCliError = (error: unknown): string =>\n typeof error === 'string'\n ? error\n : inspect(error, { colors: false, depth: null, customInspect: false });\n","import { z } from 'zod/v4';\nimport type { NodeDefinition } from '../node/types';\nimport type { TestFileSelection } from './test-project';\n\nexport interface NodeSpecDocument {\n markdown: string;\n warnings: readonly string[];\n}\n\nconst GENERATED_COMMENT =\n '<!-- Generated by `midscene-test nodes`. Do not edit directly. -->';\n\nexport const sortNodesForSpec = (\n nodes: readonly NodeDefinition<any, any, any>[],\n): NodeDefinition<any, any, any>[] => {\n const priority = (name: string) =>\n name === 'aiAct' ? 0 : name === 'aiAssert' ? 1 : 2;\n return [...nodes].sort(\n (left, right) =>\n priority(left.name) - priority(right.name) ||\n (left.name < right.name ? -1 : left.name > right.name ? 1 : 0),\n );\n};\n\nconst escapeTableCell = (value: string): string =>\n value\n .trim()\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\|/g, '\\\\|')\n .replace(/\\r\\n|\\r|\\n/g, '<br>');\n\nconst renderNodeOverview = (\n nodes: readonly NodeDefinition<any, any, any>[],\n): string => {\n const heading = '## Available Nodes';\n if (nodes.length === 0) {\n return `${heading}\\n\\nNo nodes are registered by the current Test Project.`;\n }\n const rows = nodes.map(\n (node) =>\n `| ${escapeTableCell(node.name)} | ${escapeTableCell(node.description || 'Description not declared.')} |`,\n );\n return `${heading}\\n\\nThis table lists all available Nodes. See [Node Details](#node-details) below for each Node's usage and input schema.\\n\\n${['| Node | Description |', '| --- | --- |', ...rows].join('\\n')}`;\n};\n\ninterface NodeSpecLocation {\n configPath?: string;\n projects: readonly { name: string; files: TestFileSelection }[];\n}\n\nconst renderWorkflowLocations = (location?: NodeSpecLocation): string => {\n const sections = [\n '## Where to use these Nodes',\n 'Use these Nodes in Workflow Documents (`.yaml` or `.yml` files) selected by an Execution Project. Case file patterns and the config file path below are relative to this spec file. Case file patterns use glob syntax. A custom `--config` path does not change where case files are selected.',\n 'Projects created by `midscene-test create` select `cases/**/*.{yaml,yml}` by default, so you can write test cases in `cases/example.yaml` or subdirectories of `cases/`. If an Execution Project has no `files` configuration, Midscene Test searches `**/*.{yaml,yml}` recursively instead. Check `projects[].files` in your configuration before choosing a file location.',\n ];\n if (location) {\n sections.push(\n `**Config file:** ${location.configPath ? `\\`${location.configPath}\\`` : 'No config file loaded.'}`,\n );\n for (const project of location.projects) {\n const patterns = project.files.include\n .map((pattern) => `\\`${pattern}\\``)\n .join(', ');\n const projectLabel =\n location.projects.length > 1 || project.name !== 'default'\n ? ` (Execution Project: ${project.name})`\n : '';\n const excludes = project.files.exclude?.length\n ? `; excludes: ${project.files.exclude.map((pattern) => `\\`${pattern}\\``).join(', ')}`\n : '';\n sections.push(`**Case files:** ${patterns}${projectLabel}${excludes}`);\n }\n }\n sections.push(\n 'Files matching `files.exclude` are not selected. Midscene Test always ignores `.git/`, `.midscene/`, `midscene_run/`, and `node_modules/` directories, including nested ones.',\n 'Call a Node in `cases[].steps`, or in the Workflow Document lifecycle steps `beforeAll`, `beforeEach`, `afterEach`, and `afterAll`. Root Nodes are shared defaults; `projects[].nodes` adds local Nodes and overrides same-named root Nodes only within that Execution Project. Each Execution Project supplies its own runtime environment.',\n );\n return sections.join('\\n\\n');\n};\n\nconst WORKFLOW_STEP_CONTRACT = `## Workflow Step Contract\n\nEach step uses a node name as its key. The \\`$\\` object contains engine metadata and is not part of the node input.\n\n\\`\\`\\`yaml\ncases:\n - name: Example case\n steps:\n - node.name:\n prompt: Describe the task.\n $:\n timeout: 30000\n continue-on-error: false\n\\`\\`\\`\n\nA Node may map a string step value to one declared input field. Each Node section states whether it supports this shorthand and names the target field.\n\nEach Node's returned \\`data\\` is saved on that Step's result. Results are not named or automatically passed to later Steps. A failed Case does not stop later Cases by default; \\`test.bail\\` controls early stopping across the run.`;\n\nconst sortJsonValue = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortJsonValue);\n if (typeof value !== 'object' || value === null) return value;\n\n return Object.fromEntries(\n Object.entries(value)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([key, child]) => [key, sortJsonValue(child)]),\n );\n};\n\nconst assertSelfContainedRefs = (value: unknown, node: string): void => {\n if (Array.isArray(value)) {\n for (const child of value) assertSelfContainedRefs(child, node);\n return;\n }\n if (typeof value !== 'object' || value === null) return;\n\n for (const [key, child] of Object.entries(value)) {\n if (key === '$ref' && typeof child === 'string' && !child.startsWith('#')) {\n throw new Error(\n `Cannot describe node \"${node}\": inputSchema generated an external $ref.`,\n );\n }\n assertSelfContainedRefs(child, node);\n }\n};\n\nconst toJsonSchema = (node: NodeDefinition<any, any, any>): unknown => {\n try {\n const schema = z.toJSONSchema(node.inputSchema!, {\n target: 'draft-2020-12',\n io: 'input',\n unrepresentable: 'throw',\n cycles: 'ref',\n reused: 'ref',\n });\n assertSelfContainedRefs(schema, node.name);\n return sortJsonValue(schema);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.startsWith(`Cannot describe node \"${node.name}\":`)\n ) {\n throw error;\n }\n throw new Error(\n `Cannot describe node \"${node.name}\": inputSchema contains a Zod type that cannot be represented as JSON Schema.`,\n { cause: error },\n );\n }\n};\n\nconst renderNode = (\n node: NodeDefinition<any, any, any>,\n warnings: string[],\n): string => {\n const sections = [`### \\`${node.name}\\``];\n\n if (node.title) sections.push(`**Title:** ${node.title.trim()}`);\n if (node.description) {\n sections.push(node.description.trim());\n } else {\n warnings.push(`node \"${node.name}\" has no description`);\n sections.push(\n `> Description not declared. Do not infer this node's behavior.`,\n );\n }\n\n if (node.stringInputKey === false || node.stringInputKey === undefined) {\n sections.push('**String shorthand:** Not supported by this Node.');\n } else {\n sections.push(\n `**String shorthand:** Maps to \\`{ ${node.stringInputKey}: value }\\`.`,\n );\n }\n\n sections.push('#### Input Schema');\n if (node.inputSchema) {\n sections.push(\n `\\`\\`\\`json\\n${JSON.stringify(toJsonSchema(node), null, 2)}\\n\\`\\`\\``,\n );\n } else {\n warnings.push(`node \"${node.name}\" has no inputSchema`);\n sections.push(\n '> Input schema not declared. Do not invent input fields for this node.',\n );\n }\n\n return sections.join('\\n\\n');\n};\n\nexport const renderNodeSpec = (\n nodes: readonly NodeDefinition<any, any, any>[],\n location?: NodeSpecLocation,\n): NodeSpecDocument => {\n const warnings: string[] = [];\n const sortedNodes = sortNodesForSpec(nodes);\n const sections = [\n GENERATED_COMMENT,\n '# Midscene Test Node Spec',\n 'This document describes the Nodes available in YAML test files (`.yaml` or `.yml`) for the Midscene Test framework (`@midscene/test`). It lists the Nodes registered by the current Test Project, their inputs, and how to call them in test steps and lifecycle hooks.',\n [\n 'Learn about the framework and YAML test authoring:',\n '',\n '- [Midscene Test overview](https://midscenejs.com/midscene-test/overview): framework concepts and the role of Nodes.',\n '- [Create and use test projects](https://midscenejs.com/midscene-test/use): write YAML cases, run tests, and inspect results.',\n '- [Configure test projects](https://midscenejs.com/midscene-test/configuration): register Nodes, select case files, and manage runtime resources.',\n ].join('\\n'),\n renderNodeOverview(sortedNodes),\n renderWorkflowLocations(location),\n WORKFLOW_STEP_CONTRACT,\n ];\n\n if (sortedNodes.length > 0) {\n sections.push('## Node Details');\n for (const node of sortedNodes) sections.push(renderNode(node, warnings));\n }\n\n return {\n markdown: `${sections.join('\\n\\n')}\\n`,\n warnings,\n };\n};\n","import { NodeRegistry as CoreNodeRegistry } from '@midscene/core/internal/test-runner';\nimport type { NodeDefinition } from '../node/types';\n\nexport type NodeRegistry = Omit<\n CoreNodeRegistry,\n 'get' | 'require' | 'register' | 'definitions'\n> & {\n get(name: string): NodeDefinition<any, any> | undefined;\n require(name: string): NodeDefinition<any, any>;\n register<TInput, TData>(node: NodeDefinition<TInput, TData>): NodeRegistry;\n definitions(): readonly NodeDefinition<any, any, any>[];\n};\nexport const NodeRegistry: {\n new (nodes?: readonly NodeDefinition<any, any>[]): NodeRegistry;\n} = CoreNodeRegistry;\n","import { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { require as tsxRequire } from 'tsx/cjs/api';\nimport { NodeRegistry } from '../engine/registry';\nimport type { NodeDefinition } from '../node/types';\n\nimport type {\n FileSetupDefinition,\n JsonValue,\n ProjectSetupDefinition,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nexport type {\n FileSetupContext,\n FileSetupDefinition,\n JsonPrimitive,\n JsonValue,\n ProjectSetupContext,\n ProjectSetupDefinition,\n ProjectTeardown,\n ProjectTeardownContext,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nimport type { ExecutionProjectDefinition as CoreExecutionProjectDefinition } from '@midscene/core/internal/test-runner';\n\nexport type ExecutionProjectDefinition<\n TContext = unknown,\n TProjectContext = TContext,\n> = Omit<\n CoreExecutionProjectDefinition<TProjectContext>,\n 'nodes' | 'fileSetup'\n> & {\n fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n};\n\nexport interface TestOptions {\n /** Global active files, including preparation and cleanup. Default 1; null is unlimited. */\n maxConcurrentFiles?: number | null;\n /** Projects from setup through completed cleanup. Default 1; null is unlimited. */\n maxConcurrentProjects?: number | null;\n /** Milliseconds for each Project setup/fileSetup, including device waits. */\n setupTimeout?: number;\n /** Milliseconds per cleanup scope; shared deadline during abnormal shutdown. */\n teardownTimeout?: number;\n bail?: number;\n testTimeout?: number;\n}\n\nexport interface ResolvedTestOptions {\n maxConcurrentFiles: number | null;\n maxConcurrentProjects: number | null;\n setupTimeout: number;\n teardownTimeout: number;\n bail: number;\n testTimeout: number;\n}\n\nexport interface TestOutputDefinition {\n reportDir?: string;\n}\n\nexport interface ResolvedTestOutputDefinition {\n reportDir: string;\n}\n\nconst projectIdFromIndex = (index: number): string => `project-${index}`;\n\nexport interface TestProjectDefinition<\n TContext = undefined,\n TProjectContext = TContext,\n> {\n setup?: ProjectSetupDefinition<TProjectContext>;\n fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n projects?: readonly ExecutionProjectDefinition<TContext, TProjectContext>[];\n test?: TestOptions;\n output?: TestOutputDefinition;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n}\n\nexport interface LoadedExecutionProject<\n TContext = unknown,\n TProjectContext = TContext,\n> extends ResolvedExecutionProject<TProjectContext> {\n readonly fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n /** Effective Nodes: globals plus project-local overrides. */\n readonly nodes: NodeRegistry;\n}\n\nexport interface LoadedTestProject<\n TContext = undefined,\n TProjectContext = TContext,\n> {\n projects: readonly LoadedExecutionProject<TContext, TProjectContext>[];\n hasExplicitProjects: boolean;\n test: ResolvedTestOptions;\n output: ResolvedTestOutputDefinition;\n nodes: NodeRegistry;\n resolveNode(name: string): NodeDefinition<any, any, TContext> | undefined;\n}\n\nexport const defineTestProject = <\n TContext = undefined,\n TProjectContext = TContext,\n>(\n definition: TestProjectDefinition<TContext, TProjectContext>,\n): TestProjectDefinition<TContext, TProjectContext> => definition;\n\nexport const defineProjectSetup = <TProjectContext>(\n definition: ProjectSetupDefinition<TProjectContext>,\n): ProjectSetupDefinition<TProjectContext> => definition;\n\nexport const defineFileSetup = <TContext, TProjectContext = unknown>(\n definition: FileSetupDefinition<TContext, TProjectContext>,\n): FileSetupDefinition<TContext, TProjectContext> => definition;\n\nconst getDefaultExport = (loaded: unknown, absolutePath: string): unknown => {\n if (typeof loaded === 'object' && loaded !== null && 'default' in loaded) {\n const defaultExport = (loaded as { default: unknown }).default;\n if (\n typeof defaultExport === 'object' &&\n defaultExport !== null &&\n '__esModule' in defaultExport\n ) {\n if ('default' in defaultExport) {\n return (defaultExport as { default: unknown }).default;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n }\n return defaultExport;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n label: string,\n): void => {\n const allowed = new Set(allowedKeys);\n const unknown = Object.keys(value).find((key) => !allowed.has(key));\n if (unknown) {\n throw new TypeError(\n `Midscene config ${label}.${unknown} is not supported.`,\n );\n }\n};\n\nconst isAbsolutePattern = (pattern: string): boolean =>\n isAbsolute(pattern) ||\n /^[A-Za-z]:[\\\\/]/.test(pattern) ||\n pattern.startsWith('\\\\\\\\');\n\nconst validatePatterns = (\n value: unknown,\n field: 'include' | 'exclude',\n label = 'files',\n allowEmptyInclude = false,\n): readonly string[] => {\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n if (field === 'include' && value.length === 0 && !allowEmptyInclude) {\n throw new TypeError(\n `Midscene config ${label}.include must be a non-empty array.`,\n );\n }\n\n return value.map((pattern, index) => {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n if (isAbsolutePattern(pattern)) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be relative to the project root.`,\n );\n }\n if (pattern.split(/[\\\\/]/).includes('..')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must not contain a \"..\" path segment.`,\n );\n }\n if (pattern.includes('\\\\')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`,\n );\n }\n if (pattern.startsWith('!')) {\n if (field === 'include') {\n throw new TypeError(\n `Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`,\n );\n }\n throw new TypeError(\n `Midscene config ${label}.exclude[${index}] must not be a negated pattern.`,\n );\n }\n return pattern;\n });\n};\n\nexport const validateTestFileSelection = (\n value: unknown,\n label = 'files',\n): TestFileSelection | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['include', 'exclude'], label);\n const include = validatePatterns(value.include, 'include', label);\n const exclude =\n value.exclude === undefined\n ? undefined\n : validatePatterns(value.exclude, 'exclude', label);\n return Object.freeze({\n include: Object.freeze(include),\n ...(exclude ? { exclude: Object.freeze(exclude) } : {}),\n });\n};\n\nconst validateTagList = (\n value: unknown,\n field: 'include' | 'exclude',\n label: string,\n): readonly string[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n return value.map((tag, index) => {\n if (typeof tag !== 'string' || tag.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n return tag;\n });\n};\n\nconst validateTagSelection = (\n value: unknown,\n label: string,\n): Readonly<Required<TestTagSelection>> => {\n if (value === undefined) return Object.freeze({ include: [], exclude: [] });\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n return Object.freeze({\n include: Object.freeze(validateTagList(value.include, 'include', label)),\n exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label)),\n });\n};\n\nfunction assertJsonValue(\n value: unknown,\n path: string,\n seen: Set<unknown>,\n): asserts value is JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean'\n ) {\n return;\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return;\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (typeof value !== 'object' || value === undefined) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (seen.has(value)) {\n throw new TypeError(`Midscene config ${path} must not contain cycles.`);\n }\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertJsonValue(item, `${path}[${index}]`, seen),\n );\n } else {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${path}.${key}`, seen);\n }\n }\n seen.delete(value);\n}\n\nconst deepFreezeJson = <T extends JsonValue>(value: T): T => {\n if (typeof value === 'object' && value !== null) {\n for (const child of Object.values(value)) deepFreezeJson(child);\n Object.freeze(value);\n }\n return value;\n};\n\nconst validateVariables = (\n value: unknown,\n label: string,\n): Readonly<Record<string, JsonValue>> => {\n if (value === undefined) return Object.freeze({});\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n assertJsonValue(value, label, new Set());\n return deepFreezeJson(value as Record<string, JsonValue>);\n};\n\nconst validateSetup = <TSetup>(\n value: unknown,\n label: string,\n): TSetup | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['name', 'setup'], label);\n if (typeof value.name !== 'string' || value.name.trim().length === 0) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (typeof value.setup !== 'function') {\n throw new TypeError(`Midscene config ${label}.setup must be a function.`);\n }\n return value as unknown as TSetup;\n};\n\nconst validatePositiveInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) <= 0) {\n throw new TypeError(`Midscene config ${label} must be a positive integer.`);\n }\n return value as number;\n};\n\nconst validateNonNegativeInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) < 0) {\n throw new TypeError(\n `Midscene config ${label} must be a non-negative integer.`,\n );\n }\n return value as number;\n};\n\nconst validateConcurrency = (value: unknown, label: string): number | null => {\n if (value === null) return null;\n return validatePositiveInteger(value, 1, label);\n};\n\nconst validateFileConcurrency = (\n maxConcurrentFiles: number,\n fileSetup: unknown,\n label: string,\n): void => {\n if (maxConcurrentFiles > 1 && !fileSetup) {\n throw new TypeError(\n `Midscene config ${label}.fileSetup is required when the effective maxConcurrentFiles is greater than 1.`,\n );\n }\n};\n\nconst validateExecutionProjects = <TContext, TProjectContext>(\n value: unknown,\n defaultSetup: unknown,\n defaultFileSetup: unknown,\n globalNodes: NodeRegistry,\n test: ResolvedTestOptions,\n): {\n projects: readonly LoadedExecutionProject<TContext, TProjectContext>[];\n hasExplicitProjects: boolean;\n} => {\n if (value === undefined) {\n const setup = validateSetup<ProjectSetupDefinition<TProjectContext>>(\n defaultSetup,\n 'setup',\n );\n const fileSetup = validateSetup<\n FileSetupDefinition<TContext, TProjectContext>\n >(defaultFileSetup, 'fileSetup');\n const maxConcurrentFiles =\n test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY;\n validateFileConcurrency(maxConcurrentFiles, fileSetup, 'default');\n return {\n hasExplicitProjects: false,\n projects: Object.freeze([\n Object.freeze({\n projectId: projectIdFromIndex(0),\n name: 'default',\n ...(setup ? { setup } : {}),\n ...(fileSetup ? { fileSetup } : {}),\n maxConcurrentFiles,\n tags: Object.freeze({ include: [], exclude: [] }),\n retry: 0,\n variables: Object.freeze({}),\n nodes: new NodeRegistry(globalNodes.definitions()),\n }),\n ]),\n };\n }\n if (defaultSetup !== undefined) {\n throw new TypeError(\n 'Midscene config setup cannot be used together with projects. Move setup to projects[].setup.',\n );\n }\n if (defaultFileSetup !== undefined) {\n throw new TypeError(\n 'Midscene config fileSetup cannot be used together with projects. Move fileSetup to projects[].fileSetup.',\n );\n }\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(\n 'Midscene config projects must be a non-empty array when declared.',\n );\n }\n const names = new Set<string>();\n const projects = value.map((candidate, index) => {\n const label = `projects[${index}]`;\n if (!isRecord(candidate)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(\n candidate,\n [\n 'name',\n 'setup',\n 'fileSetup',\n 'maxConcurrentFiles',\n 'nodes',\n 'files',\n 'tags',\n 'retry',\n 'variables',\n ],\n label,\n );\n if (\n typeof candidate.name !== 'string' ||\n candidate.name.trim().length === 0\n ) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (names.has(candidate.name)) {\n throw new TypeError(\n `Midscene config project name \"${candidate.name}\" must be unique.`,\n );\n }\n names.add(candidate.name);\n const files = validateTestFileSelection(candidate.files, `${label}.files`);\n if (candidate.nodes !== undefined && !Array.isArray(candidate.nodes)) {\n throw new TypeError(`Midscene config ${label}.nodes must be an array.`);\n }\n const localNodes = new NodeRegistry(\n candidate.nodes as NodeDefinition[] | undefined,\n );\n const nodes = new NodeRegistry([\n ...globalNodes.definitions().filter((node) => !localNodes.has(node.name)),\n ...localNodes.definitions(),\n ]);\n const fileSetup = validateSetup<\n FileSetupDefinition<TContext, TProjectContext>\n >(candidate.fileSetup, `${label}.fileSetup`);\n const globalFileLimit = test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY;\n const maxConcurrentFiles = Math.min(\n globalFileLimit,\n validatePositiveInteger(\n candidate.maxConcurrentFiles,\n globalFileLimit,\n `${label}.maxConcurrentFiles`,\n ),\n );\n validateFileConcurrency(maxConcurrentFiles, fileSetup, label);\n return Object.freeze({\n projectId: projectIdFromIndex(index),\n name: candidate.name,\n nodes,\n ...(fileSetup ? { fileSetup } : {}),\n maxConcurrentFiles,\n ...(files ? { files } : {}),\n tags: validateTagSelection(candidate.tags, `${label}.tags`),\n retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),\n variables: validateVariables(candidate.variables, `${label}.variables`),\n ...(candidate.setup === undefined\n ? {}\n : {\n setup: validateSetup<ProjectSetupDefinition<TProjectContext>>(\n candidate.setup,\n `${label}.setup`,\n )!,\n }),\n });\n });\n return { projects: Object.freeze(projects), hasExplicitProjects: true };\n};\n\nconst validateTestOptions = (\n value: unknown,\n hasExplicitProjects: boolean,\n): ResolvedTestOptions => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config test must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n if (candidate.maxConcurrency !== undefined) {\n const limit =\n typeof candidate.maxConcurrency === 'number' &&\n Number.isInteger(candidate.maxConcurrency) &&\n candidate.maxConcurrency > 0\n ? candidate.maxConcurrency\n : 1;\n throw new TypeError(\n [\n 'Midscene config test.maxConcurrency is no longer supported.',\n 'It controlled project concurrency, not file concurrency. Remove it and use:',\n ` test: { maxConcurrentProjects: ${limit}, maxConcurrentFiles: ${hasExplicitProjects ? limit : 1} }`,\n hasExplicitProjects\n ? ' Set projects[].maxConcurrentFiles to 1 to keep files sequential within each project.'\n : ' The implicit default project keeps running files sequentially.',\n hasExplicitProjects\n ? 'For parallel files, configure fileSetup and raise both test.maxConcurrentFiles and projects[].maxConcurrentFiles.'\n : 'For parallel files, configure fileSetup and raise test.maxConcurrentFiles.',\n 'Migration guide: https://midscenejs.com/midscene-test/configuration.html#existing-configurations',\n ].join('\\n'),\n );\n }\n return Object.freeze({\n maxConcurrentFiles: validateConcurrency(\n candidate.maxConcurrentFiles,\n 'test.maxConcurrentFiles',\n ),\n maxConcurrentProjects: validateConcurrency(\n candidate.maxConcurrentProjects,\n 'test.maxConcurrentProjects',\n ),\n setupTimeout: validatePositiveInteger(\n candidate.setupTimeout,\n 120_000,\n 'test.setupTimeout',\n ),\n teardownTimeout: validatePositiveInteger(\n candidate.teardownTimeout,\n 30_000,\n 'test.teardownTimeout',\n ),\n bail: validateNonNegativeInteger(\n (candidate as Record<string, unknown>).bail,\n 0,\n 'test.bail',\n ),\n testTimeout: validatePositiveInteger(\n (candidate as Record<string, unknown>).testTimeout,\n 120_000,\n 'test.testTimeout',\n ),\n });\n};\n\nconst validateOutputPath = (\n value: unknown,\n fallback: string,\n label: string,\n): string => {\n if (value === undefined) return fallback;\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`Midscene config ${label} must be non-empty.`);\n }\n return value;\n};\n\nconst validateOutput = (value: unknown): ResolvedTestOutputDefinition => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config output must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n rejectUnknownKeys(candidate, ['reportDir'], 'output');\n return Object.freeze({\n reportDir: validateOutputPath(\n candidate.reportDir,\n './midscene_run/report',\n 'output.reportDir',\n ),\n });\n};\n\nconst validateTestProjectDefinition = <TContext, TProjectContext = TContext>(\n definition: unknown,\n): LoadedTestProject<TContext, TProjectContext> => {\n if (!isRecord(definition)) {\n throw new TypeError('Midscene config must default export an object.');\n }\n if (definition.nodes !== undefined && !Array.isArray(definition.nodes)) {\n throw new TypeError('Midscene config nodes must be an array.');\n }\n if ('setupWorkflow' in definition) {\n throw new TypeError(\n 'Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.',\n );\n }\n if ('setupDocument' in definition) {\n throw new TypeError(\n 'Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.',\n );\n }\n if ('root' in definition) {\n throw new TypeError(\n 'Midscene config root is not supported. Pass the Test Project directory to midscene-test instead.',\n );\n }\n if ('files' in definition) {\n throw new TypeError(\n 'Midscene config files is not supported at the root. Move it to projects[].files.',\n );\n }\n if ('testRunner' in definition) {\n throw new TypeError(\n 'Midscene config testRunner is not supported. Rename it to test.',\n );\n }\n rejectUnknownKeys(\n definition,\n ['setup', 'fileSetup', 'projects', 'test', 'output', 'nodes'],\n 'root',\n );\n const nodes = new NodeRegistry(\n definition.nodes as NodeDefinition[] | undefined,\n );\n const test = validateTestOptions(\n definition.test,\n definition.projects !== undefined,\n );\n const resolvedProjects = validateExecutionProjects<TContext, TProjectContext>(\n definition.projects,\n definition.setup,\n definition.fileSetup,\n nodes,\n test,\n );\n return {\n ...resolvedProjects,\n test,\n output: validateOutput(definition.output),\n nodes,\n resolveNode: (name) =>\n nodes.get(name) as NodeDefinition<any, any, TContext> | undefined,\n };\n};\n\nconst assertSupportedConfig = (absolutePath: string): '.ts' | '.mjs' => {\n if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {\n const extension = absolutePath.match(/(\\.[^./\\\\]+)$/)?.[1] ?? '(none)';\n throw new TypeError(\n `Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`,\n );\n }\n return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';\n};\n\nconst canRetryWithCjsLoader = (error: unknown): error is Error => {\n if (!(error instanceof Error)) return false;\n const errorCode = (error as Error & { code?: string }).code;\n return (\n (error instanceof SyntaxError &&\n /^Unexpected (?:identifier|reserved word|token)/.test(error.message)) ||\n errorCode === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' ||\n (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION' &&\n /^Unknown file extension\\b/.test(error.message))\n );\n};\n\nexport async function loadTestProject<\n TContext = undefined,\n TProjectContext = TContext,\n>(configPath?: string): Promise<LoadedTestProject<TContext, TProjectContext>> {\n if (!configPath) {\n return validateTestProjectDefinition<TContext, TProjectContext>({\n nodes: [],\n });\n }\n\n const absolutePath = resolve(configPath);\n const extension = assertSupportedConfig(absolutePath);\n let loaded: unknown;\n try {\n if (extension === '.mjs') {\n loaded = await import(pathToFileURL(absolutePath).href);\n } else {\n // Select tsx's ESM entry even when this loader is built as CommonJS.\n // Its CommonJS entry can resolve the async loader relative to the wrong directory.\n const { tsImport } = await import('tsx/esm/api');\n loaded = await tsImport(pathToFileURL(absolutePath).href, {\n parentURL: pathToFileURL(`${dirname(absolutePath)}${sep}`).href,\n tsconfig: false,\n });\n }\n } catch (error) {\n try {\n if (extension === '.mjs' || !canRetryWithCjsLoader(error)) throw error;\n loaded = tsxRequire(absolutePath, pathToFileURL(absolutePath));\n } catch (fallbackError) {\n const message =\n fallbackError instanceof Error ? `: ${fallbackError.message}` : '';\n throw new Error(\n `Failed to load Midscene config \"${absolutePath}\"${message}`,\n { cause: fallbackError },\n );\n }\n }\n\n return validateTestProjectDefinition<TContext, TProjectContext>(\n getDefaultExport(loaded, absolutePath),\n );\n}\n","import { createHash } from 'node:crypto';\n\n/** Internal invocation identity keeps repeated legacy files distinct. */\nexport const createCaseInvocationId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n caseIndex,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n\nexport const createDocumentInvocationId = (\n projectId: string,\n sourcePath: string,\n invocationIndex = 0,\n): string =>\n createHash('sha256')\n .update(\n JSON.stringify([\n projectId,\n sourcePath,\n ...(invocationIndex ? [invocationIndex] : []),\n ]),\n )\n .digest('hex');\n","import {\n type ResolveNodeForNormalization,\n normalizeStep as coreNormalizeStep,\n normalizeSteps as coreNormalizeSteps,\n} from '@midscene/core/internal/test-runner';\nimport type { NormalizedStep } from './types';\nexport type { ResolveNodeForNormalization } from '@midscene/core/internal/test-runner';\n\nexport const normalizeStep: (\n value: unknown,\n index?: number,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep = coreNormalizeStep;\nexport const normalizeSteps: (\n values: unknown,\n resolveNode?: ResolveNodeForNormalization,\n) => NormalizedStep[] = coreNormalizeSteps;\n","import type { TestRunReportValue } from '@midscene/core';\nimport {\n isReportSecretKey,\n sanitizeReportText,\n} from '@midscene/core/internal/test-runner';\nimport { JSON_SCHEMA, load } from 'js-yaml';\n\ninterface SourceNode {\n start: number;\n end: number;\n value: unknown;\n children: SourceNode[];\n}\n\n/** Keep author formatting while redacting values by parsed YAML keys, including aliases. */\nexport function parseWorkflowSource(source: string): {\n parsed: unknown;\n sourceYaml: TestRunReportValue;\n} {\n const stack: SourceNode[] = [];\n const nodes: SourceNode[] = [];\n const sensitiveNodes = new Set<SourceNode>();\n const sensitiveValues = new Set<unknown>();\n const redactedPaths = new Set<string>();\n // js-yaml removes the BOM before reporting source positions.\n const sourceOffset = source.charCodeAt(0) === 0xfeff ? 1 : 0;\n const parsed = load(source, {\n schema: JSON_SCHEMA,\n listener(event, state) {\n if (event === 'open') {\n stack.push({\n start: state.position + sourceOffset,\n end: 0,\n value: null,\n children: [],\n });\n return;\n }\n const node = stack.pop()!;\n node.end = state.position + sourceOffset;\n node.value = state.result;\n stack.at(-1)?.children.push(node);\n nodes.push(node);\n if (state.kind !== 'mapping') return;\n for (let index = 0; index < node.children.length; index += 2) {\n const key = node.children[index].value;\n const value = node.children[index + 1];\n if (typeof key !== 'string' || !isReportSecretKey(key) || !value)\n continue;\n sensitiveNodes.add(value);\n if (value.value !== null) sensitiveValues.add(value.value);\n redactedPaths.add(`$..[${JSON.stringify(key)}]`);\n }\n },\n });\n // Redact the definition as well when a secret value refers to a YAML anchor.\n const ranges = nodes\n .filter(\n (node) => sensitiveNodes.has(node) || sensitiveValues.has(node.value),\n )\n .sort((left, right) => left.start - right.start || right.end - left.end);\n let offset = 0;\n let redacted = '';\n for (const range of ranges) {\n if (range.start < offset) continue;\n const text = source.slice(range.start, range.end);\n const leading = text.match(/^\\s*/)?.[0] ?? '';\n const trailing = text.slice(leading.length).match(/\\s*$/)?.[0] ?? '';\n redacted += `${source.slice(offset, range.start)}${leading}\"[REDACTED]\"${trailing}`;\n offset = range.end;\n }\n redacted += source.slice(offset);\n const value = sanitizeReportText(redacted, 64 * 1024);\n return {\n parsed,\n sourceYaml: {\n value,\n ...(redactedPaths.size ? { redactedPaths: [...redactedPaths] } : {}),\n ...(value !== redacted ? { truncatedPaths: ['$'] } : {}),\n },\n };\n}\n","import type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\n\nexport interface VariableResolutionLocation {\n projectName: string;\n sourcePath: string;\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll';\n stepIndex: number;\n caseIndex?: number;\n}\n\nexport interface ResolveWorkflowVariablesOptions {\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n location: VariableResolutionLocation;\n}\n\nconst interpolationExpression =\n /\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}|\\$\\{([^{}]+)\\}/g;\nconst exactEnvExpression = /^\\$\\{\\{([A-Za-z_][A-Za-z0-9_]*)\\}\\}$/;\nconst exactProjectExpression = /^\\$\\{([^{}]+)\\}$/;\n\nconst missingVariable = (\n kind: 'environment' | 'project',\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): never => {\n throw new WorkflowParseError(\n `Undefined ${kind} variable \"${name}\" in ${options.location.sourcePath}.`,\n { ...options.location, variable: name, variableKind: kind },\n );\n};\n\nconst projectVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n if (!Object.hasOwn(options.variables ?? {}, name)) {\n return missingVariable('project', name, options);\n }\n return options.variables![name];\n};\n\nconst environmentVariable = (\n name: string,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n const value = options.env?.[name];\n if (value === undefined) return missingVariable('environment', name, options);\n return value;\n};\n\nconst interpolationValue = (\n name: string,\n value: JsonValue,\n options: ResolveWorkflowVariablesOptions,\n): string => {\n if (typeof value === 'object' && value !== null) {\n throw new WorkflowParseError(\n `Project variable \"${name}\" must be a primitive when embedded in a string.`,\n {\n ...options.location,\n variable: name,\n variableKind: 'project',\n },\n );\n }\n return String(value);\n};\n\nconst resolveString = (\n value: string,\n options: ResolveWorkflowVariablesOptions,\n): JsonValue => {\n const exactEnv = exactEnvExpression.exec(value);\n if (exactEnv) return environmentVariable(exactEnv[1], options);\n const exactProject = exactProjectExpression.exec(value);\n if (exactProject) return projectVariable(exactProject[1], options);\n\n return value.replace(\n interpolationExpression,\n (_match, environmentName: string | undefined, projectName: string) =>\n environmentName\n ? environmentVariable(environmentName, options)\n : interpolationValue(\n projectName,\n projectVariable(projectName, options),\n options,\n ),\n );\n};\n\nexport const resolveWorkflowVariables = (\n value: unknown,\n options: ResolveWorkflowVariablesOptions,\n): unknown => {\n if (typeof value === 'string') return resolveString(value, options);\n if (Array.isArray(value)) {\n return value.map((child) => resolveWorkflowVariables(child, options));\n }\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n resolveWorkflowVariables(child, options),\n ]),\n );\n }\n return value;\n};\n","import { readFileSync } from 'node:fs';\nimport { sep } from 'node:path';\nimport { classifyWorkflowDocumentFormat } from '@midscene/core/internal/test-runner';\nimport type { JsonValue } from '../cli/test-project';\nimport { WorkflowParseError } from '../errors';\nimport type { NodeDefinition } from '../node/types';\nimport {\n createCaseInvocationId,\n createDocumentInvocationId,\n} from './identifiers';\nimport { normalizeSteps } from './normalize';\nimport { parseWorkflowSource } from './source';\nimport type {\n CollectedCase,\n CollectedWorkflowDocument,\n WorkflowDocumentSource,\n} from './types';\nimport { resolveWorkflowVariables } from './variables';\n\nexport interface CollectWorkflowDocumentOptions {\n resolveNode(name: string): NodeDefinition<any, any> | undefined;\n variables?: Readonly<Record<string, JsonValue>>;\n env?: Readonly<NodeJS.ProcessEnv>;\n}\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nexport class NativeWorkflowFormatError extends WorkflowParseError {\n readonly actualFormat: 'legacy' | 'legacy-batch' | 'mixed';\n\n constructor(\n actualFormat: 'legacy' | 'legacy-batch' | 'mixed',\n sourcePath: string,\n ) {\n super(\n actualFormat === 'legacy'\n ? `Legacy tasks/flow YAML is not supported by midscene-test: ${sourcePath}. Run it with \\`midscene ${sourcePath}\\`, or migrate the file to cases/steps.`\n : actualFormat === 'legacy-batch'\n ? `Legacy YAML batch configuration is not a midscene-test workflow document: ${sourcePath}. Run it with \\`midscene --config ${sourcePath}\\`, or migrate it to a native project config.`\n : `A workflow file cannot mix legacy tasks/flow with native cases/steps or lifecycle hooks: ${sourcePath}. Keep the formats in separate files and run each file with its matching command.`,\n { sourcePath, actualFormat, expectedFormat: 'native' },\n );\n this.actualFormat = actualFormat;\n }\n}\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowed: readonly string[],\n label: string,\n) => {\n const allowedSet = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !allowedSet.has(key));\n if (unknown.length) {\n throw new WorkflowParseError(\n `${label} has unsupported field \"${unknown[0]}\".`,\n { field: unknown[0] },\n );\n }\n};\n\nexport const createCaseId = (\n projectId: string,\n sourcePath: string,\n caseIndex: number,\n): string => createCaseInvocationId(projectId, sourcePath, caseIndex);\n\nexport const createWorkflowDocumentId = (\n projectId: string,\n sourcePath: string,\n): string => createDocumentInvocationId(projectId, sourcePath);\n\nexport function collectWorkflowDocument(\n source: WorkflowDocumentSource,\n options: CollectWorkflowDocumentOptions,\n): CollectedWorkflowDocument {\n let snapshot: ReturnType<typeof parseWorkflowSource>;\n try {\n snapshot = parseWorkflowSource(readFileSync(source.absolutePath, 'utf8'));\n } catch (error) {\n throw new WorkflowParseError(\n `Failed to parse workflow document \"${source.sourcePath}\".`,\n { sourcePath: source.sourcePath },\n error,\n );\n }\n const { parsed, sourceYaml } = snapshot;\n\n if (!isMapping(parsed)) {\n throw new WorkflowParseError('Workflow document must be a mapping.');\n }\n const format = classifyWorkflowDocumentFormat(parsed);\n if (format === 'legacy' || format === 'legacy-batch' || format === 'mixed') {\n throw new NativeWorkflowFormatError(format, source.sourcePath);\n }\n rejectUnknownKeys(\n parsed,\n ['beforeAll', 'beforeEach', 'cases', 'afterEach', 'afterAll'],\n 'Workflow document',\n );\n if (!Array.isArray(parsed.cases) || parsed.cases.length === 0) {\n throw new WorkflowParseError(\n 'Workflow document must contain a non-empty cases array.',\n );\n }\n\n const sourcePath = source.sourcePath.split(sep).join('/');\n const resolveStepVariables = (\n step: ReturnType<typeof normalizeSteps>[number],\n phase: 'beforeAll' | 'beforeEach' | 'steps' | 'afterEach' | 'afterAll',\n stepIndex: number,\n caseIndex?: number,\n ) => ({\n ...step,\n templateInput: step.input,\n input: resolveWorkflowVariables(step.input, {\n variables: options.variables,\n env: options.env ?? process.env,\n location: {\n projectName: source.projectName ?? source.projectId,\n sourcePath,\n phase,\n stepIndex,\n ...(caseIndex === undefined ? {} : { caseIndex }),\n },\n }) as typeof step.input,\n });\n const normalizeLifecycle = (\n phase: 'beforeAll' | 'beforeEach' | 'afterEach' | 'afterAll',\n ) => {\n const value = parsed[phase];\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new WorkflowParseError(\n `Workflow document ${phase} must be an array.`,\n { phase },\n );\n }\n return normalizeSteps(value, options.resolveNode).map(\n (normalized, stepIndex) => {\n const resolved = options.resolveNode(normalized.node);\n if (!resolved) {\n throw new WorkflowParseError(\n `Workflow document ${phase} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { phase, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, phase, stepIndex);\n },\n );\n };\n const lifecycle = {\n beforeAll: normalizeLifecycle('beforeAll'),\n beforeEach: normalizeLifecycle('beforeEach'),\n afterEach: normalizeLifecycle('afterEach'),\n afterAll: normalizeLifecycle('afterAll'),\n };\n const ids = new Set<string>();\n const cases: CollectedCase[] = parsed.cases.map((definition, caseIndex) => {\n if (!isMapping(definition)) {\n throw new WorkflowParseError(`Case ${caseIndex + 1} must be a mapping.`, {\n caseIndex,\n });\n }\n rejectUnknownKeys(\n definition,\n ['name', 'tags', 'steps'],\n `Case ${caseIndex + 1}`,\n );\n if (\n typeof definition.name !== 'string' ||\n definition.name.trim().length === 0\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} name must be a non-empty string.`,\n { caseIndex },\n );\n }\n if (!Array.isArray(definition.steps) || definition.steps.length === 0) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} steps must be a non-empty array.`,\n { caseIndex },\n );\n }\n const tags = definition.tags ?? [];\n if (\n !Array.isArray(tags) ||\n tags.some((tag) => typeof tag !== 'string' || tag.trim().length === 0)\n ) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} tags must be an array of non-empty strings.`,\n { caseIndex },\n );\n }\n\n const steps = normalizeSteps(definition.steps, options.resolveNode).map(\n (normalized, stepIndex) => {\n if (!options.resolveNode(normalized.node)) {\n throw new WorkflowParseError(\n `Case ${caseIndex + 1} step ${stepIndex + 1} references unknown node \"${normalized.node}\".`,\n { caseIndex, stepIndex, node: normalized.node },\n );\n }\n return resolveStepVariables(normalized, 'steps', stepIndex, caseIndex);\n },\n );\n const caseId = createCaseId(source.projectId, sourcePath, caseIndex);\n if (ids.has(caseId)) {\n throw new WorkflowParseError(`Case id collision: ${caseId}.`, {\n caseId,\n });\n }\n ids.add(caseId);\n\n return {\n caseId,\n projectId: source.projectId,\n sourcePath,\n caseIndex,\n definition: {\n name: definition.name,\n tags: tags as string[],\n steps,\n },\n };\n });\n\n return {\n documentId: createWorkflowDocumentId(source.projectId, sourcePath),\n projectId: source.projectId,\n sourcePath,\n sourceYaml,\n lifecycle,\n cases,\n } satisfies CollectedWorkflowDocument;\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport {\n WorkflowPublicationError,\n sanitizeReportError,\n} from '@midscene/core/internal/test-runner';\nimport type { CaseRunResult, WorkflowDocumentRunResult } from '../engine/types';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type { TestProjectCollectionError, TestProjectRunResult } from './types';\n\nconst writeJson = async (path: string, value: unknown) => {\n try {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, JSON.stringify(value, null, 2));\n } catch (error) {\n throw new WorkflowPublicationError('write-result', path, error);\n }\n};\n\nexport const writeTestRunPlan = (\n runDir: string,\n projects: readonly PreparedExecutionProject[],\n) =>\n writeJson(join(runDir, 'plan.json'), {\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n projects: projects.map((item) => ({\n projectId: item.project.projectId,\n name: item.project.name,\n documents: item.plans ?? [],\n })),\n });\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nexport const caseAttemptResultPath = (\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n): string =>\n toPosix(\n join(\n projectId,\n 'documents',\n documentId,\n 'cases',\n result.caseId,\n `${result.runId}.json`,\n ),\n );\n\nexport const workflowDocumentResultPath = (\n result: WorkflowDocumentRunResult,\n): string =>\n toPosix(\n join(\n result.projectId,\n 'documents',\n result.documentId,\n result.attemptIndex === undefined\n ? 'document.json'\n : `${result.documentRunId}.json`,\n ),\n );\n\nexport const collectionErrorPath = (\n projectId: string,\n sourcePath: string,\n): string => {\n const id = createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath]))\n .digest('hex');\n return toPosix(join(projectId, 'collection-errors', `${id}.json`));\n};\n\nexport const writeWorkflowDocumentResult = (\n runDir: string,\n result: WorkflowDocumentRunResult,\n) => {\n const { documentRunId: _documentRunId, ...persistedResult } = result;\n return writeJson(\n join(runDir, workflowDocumentResultPath(result)),\n persistedResult,\n );\n};\n\nexport const writeCaseAttemptResult = (\n runDir: string,\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n) => {\n const { runId: attemptId, ...persistedResult } = result;\n return writeJson(\n join(runDir, caseAttemptResultPath(projectId, documentId, result)),\n {\n ...persistedResult,\n attemptId,\n },\n );\n};\n\nexport const writeCollectionError = (\n runDir: string,\n collectionError: TestProjectCollectionError,\n) => {\n return writeJson(\n join(\n runDir,\n collectionErrorPath(\n collectionError.projectId,\n collectionError.sourcePath,\n ),\n ),\n { kind: 'collection-error', ...collectionError },\n );\n};\n\nconst relativeToSummary = (summaryPath: string, target: string): string => {\n const value = relative(dirname(summaryPath), target);\n return toPosix(value || '.');\n};\n\nconst errorJson = sanitizeReportError;\n\nexport interface TestProjectResultFileOptions {\n projectRoot: string;\n configPath?: string;\n result: TestProjectRunResult;\n}\n\nexport const writeTestProjectRunResult = (\n options: TestProjectResultFileOptions,\n) => {\n const { result } = options;\n const fact = (path: string) => toPosix(path);\n\n return writeJson(result.summaryPath, {\n schemaVersion: result.schemaVersion,\n runId: result.runId,\n startedAt: result.startedAt,\n endedAt: result.endedAt,\n durationMs: result.durationMs,\n status: result.status,\n exitCode: result.exitCode,\n ...(result.errors?.length ? { errors: result.errors.map(errorJson) } : {}),\n projectRoot: options.projectRoot,\n ...(options.configPath ? { configPath: options.configPath } : {}),\n factsRoot: '.',\n plan: 'plan.json',\n ...(result.operationLog\n ? {\n operationLog: {\n ...result.operationLog,\n path: relativeToSummary(\n result.summaryPath,\n result.operationLog.path,\n ),\n },\n }\n : {}),\n reportDir: relativeToSummary(result.summaryPath, result.reportDir),\n ...(result.reportPath\n ? { report: relativeToSummary(result.summaryPath, result.reportPath) }\n : {}),\n ...(result.markdownPath\n ? { markdown: relativeToSummary(result.summaryPath, result.markdownPath) }\n : {}),\n summary: result.summary,\n projects: result.projects.map((project) => ({\n projectId: project.projectId,\n name: project.name,\n status: project.status,\n retry: project.retry,\n fileSelection: project.fileSelection,\n tagSelection: project.tagSelection,\n sourceCount: project.sourceCount,\n selectedCaseCount: project.selectedCaseCount,\n filteredCaseCount: project.filteredCaseCount,\n ...(project.lifecycle\n ? {\n lifecycle: {\n status: project.lifecycle.status,\n startedAt: project.lifecycle.startedAt,\n endedAt: project.lifecycle.endedAt,\n durationMs: project.lifecycle.durationMs,\n ...(project.lifecycle.cleanup\n ? { cleanup: project.lifecycle.cleanup }\n : {}),\n ...(project.lifecycle.pendingOperations\n ? { pendingOperations: project.lifecycle.pendingOperations }\n : {}),\n ...(project.lifecycle.setupError\n ? { setupError: errorJson(project.lifecycle.setupError) }\n : {}),\n ...(project.lifecycle.teardownErrors\n ? {\n teardownErrors:\n project.lifecycle.teardownErrors.map(errorJson),\n }\n : {}),\n },\n }\n : {}),\n cases: project.cases.map((outcome) => ({\n ...(outcome.documentRunId\n ? { documentRunId: outcome.documentRunId }\n : {}),\n documentId: outcome.documentId,\n caseId: outcome.caseId,\n sourcePath: outcome.sourcePath,\n caseIndex: outcome.caseIndex,\n name: outcome.name,\n status: outcome.status,\n ...(outcome.notRunReason ? { notRunReason: outcome.notRunReason } : {}),\n ...(outcome.attempts\n ? {\n attempts: outcome.attempts.map((attempt) => ({\n attemptId: attempt.runId,\n attemptIndex: attempt.attemptIndex,\n status: attempt.status,\n ...(attempt.cleanup ? { cleanup: attempt.cleanup } : {}),\n ...(attempt.pendingOperations\n ? { pendingOperations: attempt.pendingOperations }\n : {}),\n ...(attempt.executionStatus\n ? { executionStatus: attempt.executionStatus }\n : {}),\n ...(attempt.retryDecision\n ? { retryDecision: attempt.retryDecision }\n : {}),\n resultFile: fact(\n caseAttemptResultPath(\n project.projectId,\n outcome.documentId,\n attempt,\n ),\n ),\n ...(attempt.reportPaths?.length\n ? {\n reports: attempt.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n }\n : {}),\n })),\n documents: project.documents.map((document) => ({\n documentId: document.documentId,\n ...(document.attemptIndex === undefined\n ? {}\n : {\n attemptIndex: document.attemptIndex,\n documentRunId: document.documentRunId,\n }),\n sourcePath: document.sourcePath,\n status: document.status,\n ...(document.cleanup ? { cleanup: document.cleanup } : {}),\n ...(document.pendingOperations\n ? { pendingOperations: document.pendingOperations }\n : {}),\n ...(document.executionStatus\n ? { executionStatus: document.executionStatus }\n : {}),\n ...(document.retryDecision\n ? { retryDecision: document.retryDecision }\n : {}),\n resultFile: fact(workflowDocumentResultPath(document)),\n ...(document.reportPaths?.length\n ? {\n reports: document.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n collectionErrors: project.collectionErrors.map((error) => ({\n sourcePath: error.sourcePath,\n errorFile: fact(collectionErrorPath(error.projectId, error.sourcePath)),\n })),\n })),\n });\n};\n","import { readdirSync } from 'node:fs';\nimport { join, relative, resolve, sep } from 'node:path';\nimport type { CollectedWorkflowDocument } from '@midscene/core/internal/test-runner';\nimport { buildTestRunReportPlan } from '@midscene/core/internal/test-runner';\nimport { globSync } from 'tinyglobby';\nimport { WorkflowError, WorkflowParseError } from '../errors';\nimport { collectWorkflowDocument } from '../parser/collect';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n ProjectPreparationOptions,\n} from './execution-plan';\nimport { writeCollectionError } from './result-store';\nimport type { LoadedExecutionProject, TestFileSelection } from './test-project';\nimport { validateTestFileSelection } from './test-project';\nimport type { TestProjectCollectionError } from './types';\n\nexport const CONFIG_NAMES = [\n 'midscene.config.ts',\n 'midscene.config.mjs',\n] as const;\nconst CONFIG_PREFIX = 'midscene.config.';\nconst ALWAYS_IGNORED_PATTERNS = [\n '.git/**',\n '.midscene/**',\n 'midscene_run/**',\n 'node_modules/**',\n '**/.git/**',\n '**/.midscene/**',\n '**/midscene_run/**',\n '**/node_modules/**',\n];\n\nexport const DEFAULT_TEST_FILE_SELECTION: TestFileSelection = {\n include: ['**/*.{yaml,yml}'],\n};\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nconst discoverResolvedTestFiles = (\n projectRoot: string,\n selection: TestFileSelection,\n): string[] => {\n const root = resolve(projectRoot);\n const match = (patterns: readonly string[]) =>\n globSync(patterns, {\n absolute: true,\n caseSensitiveMatch: false,\n cwd: root,\n dot: true,\n expandDirectories: false,\n followSymbolicLinks: false,\n ignore: [...ALWAYS_IGNORED_PATTERNS, ...(selection.exclude ?? [])],\n onlyFiles: true,\n }).filter((file) => /\\.ya?ml$/i.test(file));\n const files = match(selection.include);\n\n return [...new Set(files.map((file) => resolve(file)))].sort((a, b) => {\n const relativeA = toPosix(relative(root, a));\n const relativeB = toPosix(relative(root, b));\n return relativeA < relativeB ? -1 : relativeA > relativeB ? 1 : 0;\n });\n};\n\nexport const discoverTestFiles = (\n projectRoot: string,\n selection: TestFileSelection = DEFAULT_TEST_FILE_SELECTION,\n): string[] => {\n const normalized = validateTestFileSelection(selection);\n if (!normalized) throw new TypeError('Test file selection is required.');\n return discoverResolvedTestFiles(projectRoot, normalized);\n};\n\nexport const discoverTestConfig = (projectRoot: string): string | undefined => {\n const root = resolve(projectRoot);\n const candidates = readdirSync(root)\n .filter((name) => name.startsWith(CONFIG_PREFIX))\n .sort();\n const supported = candidates.filter((name) =>\n CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n const unsupported = candidates.filter(\n (name) => !CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n if (unsupported.length > 0) {\n throw new Error(\n [\n `Unsupported or conflicting Midscene configs found in ${root}:`,\n ...candidates.map((name) => `- ${name}`),\n `Only ${CONFIG_NAMES.join(' and ')} are supported.`,\n ].join('\\n'),\n );\n }\n if (supported.length > 1) {\n throw new Error(\n [\n `Multiple Midscene configs found in ${root}:`,\n ...supported.map((name) => `- ${name}`),\n 'Pass --config <path> to select one explicitly.',\n ].join('\\n'),\n );\n }\n return supported[0] ? join(root, supported[0]) : undefined;\n};\n\nconst asCollectionError = (\n projectId: string,\n projectName: string,\n sourcePath: string,\n error: unknown,\n): TestProjectCollectionError => ({\n projectId,\n projectName,\n sourcePath,\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowParseError(\n `Failed to collect workflow document \"${sourcePath}\": ${\n error instanceof Error ? error.message : String(error)\n }`,\n { projectName, sourcePath },\n error,\n ),\n});\n\nexport const matchesTags = (\n tags: readonly string[],\n selection: LoadedExecutionProject['tags'],\n): boolean => {\n if (selection.exclude.some((tag) => tags.includes(tag))) return false;\n return (\n selection.include.length === 0 ||\n selection.include.some((tag) => tags.includes(tag))\n );\n};\n\nconst filterDocumentCases = (\n document: CollectedWorkflowDocument,\n project: LoadedExecutionProject,\n): { document?: CollectedWorkflowDocument; filtered: number } => {\n const cases = document.cases.filter((item) =>\n matchesTags(item.definition.tags ?? [], project.tags),\n );\n const filtered = document.cases.length - cases.length;\n return cases.length === 0\n ? { filtered }\n : { document: { ...document, cases }, filtered };\n};\n\nexport const selectProjects = <TProjectContext>(\n projects: readonly LoadedExecutionProject<TProjectContext>[],\n names: readonly string[] | undefined,\n): readonly LoadedExecutionProject<TProjectContext>[] => {\n if (!names || names.length === 0) return projects;\n const requested = new Set(names);\n if (requested.size !== names.length) {\n throw new Error('Each --project name may only be specified once.');\n }\n const known = new Set(projects.map((project) => project.name));\n const unknown = names.find((name) => !known.has(name));\n if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);\n return projects.filter((project) => requested.has(project.name));\n};\n\n/** Prepare and validate every document before any Project resource is acquired. */\nexport async function prepareProject(\n project: LoadedExecutionProject,\n projectRoot: string,\n runDir: string,\n defaultTimeoutMs: number,\n options: ProjectPreparationOptions = {},\n): Promise<PreparedExecutionProject> {\n const platform = options.platform?.trim();\n const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;\n const prerequisiteFile = options.prerequisiteFile\n ? resolve(options.prerequisiteFile)\n : undefined;\n const mainFiles =\n options.files ?? discoverResolvedTestFiles(projectRoot, fileSelection);\n const files = [\n ...(prerequisiteFile ? [prerequisiteFile] : []),\n ...mainFiles.filter((file) => file !== prerequisiteFile),\n ];\n const occurrences = new Map<string, number>();\n const sources = files.map((absolutePath) => {\n const invocationIndex = occurrences.get(absolutePath) ?? 0;\n occurrences.set(absolutePath, invocationIndex + 1);\n return {\n projectId: project.projectId,\n projectName: project.name,\n sourcePath: toPosix(relative(projectRoot, absolutePath)),\n absolutePath,\n invocationIndex,\n };\n });\n const collectionErrors: TestProjectCollectionError[] = [];\n const invocations: PreparedDocumentInvocation[] = [];\n const plans: import('@midscene/core').TestRunReportDocumentPlan[] = [];\n let filteredCaseCount = 0;\n\n if (sources.length === 0) {\n const error = asCollectionError(\n project.projectId,\n project.name,\n '<project>',\n new WorkflowParseError(\n `No workflow YAML files found for project \"${project.name}\" in ${projectRoot}.`,\n { projectName: project.name, projectRoot },\n ),\n );\n collectionErrors.push(error);\n await writeCollectionError(runDir, error);\n }\n\n for (const source of sources) {\n try {\n const collected = await options.collectDocument?.(source, project);\n if (collected) {\n filteredCaseCount += collected.filteredCaseCount;\n if (collected.invocation) {\n const plan = buildTestRunReportPlan(collected.invocation.document, {\n defaultTimeoutMs: collected.invocation.defaultTimeoutMs,\n retry: collected.invocation.retry,\n });\n invocations.push({ ...collected.invocation, plan });\n plans.push(plan);\n }\n continue;\n }\n const document = collectWorkflowDocument(source, {\n resolveNode: project.nodes.get.bind(project.nodes),\n variables: project.variables,\n env: process.env,\n });\n const filtered =\n source.absolutePath === prerequisiteFile\n ? { document, filtered: 0 }\n : filterDocumentCases(document, project);\n const plan = buildTestRunReportPlan(document, {\n selectedCaseIds:\n filtered.document?.cases.map((item) => item.caseId) ?? [],\n defaultTimeoutMs,\n retry: { scope: 'case', count: project.retry },\n });\n plans.push(plan);\n filteredCaseCount += filtered.filtered;\n if (filtered.document)\n invocations.push({\n plan,\n document: filtered.document,\n retry: { scope: 'case', count: project.retry },\n defaultTimeoutMs,\n reportEnabled: true,\n bindings: {\n resolveNode: project.nodes.require.bind(project.nodes),\n ...(project.fileSetup\n ? {\n documentSetup: {\n name: project.fileSetup.name,\n setup({ projectContext, document, signal, onTeardown }) {\n return project.fileSetup!.setup({\n project,\n projectContext,\n file: document,\n env: Object.freeze({ ...process.env }),\n signal,\n onTeardown,\n });\n },\n },\n }\n : {}),\n },\n });\n } catch (error) {\n const collectionError = asCollectionError(\n project.projectId,\n project.name,\n source.sourcePath,\n error,\n );\n collectionErrors.push(collectionError);\n await writeCollectionError(runDir, collectionError);\n }\n }\n\n const documents = invocations.map((invocation) => invocation.document);\n const prerequisiteSource = sources.find(\n (source) => source.absolutePath === prerequisiteFile,\n );\n const prerequisiteDocument = documents.find(\n (document) => document.sourcePath === prerequisiteSource?.sourcePath,\n );\n return {\n project,\n ...(platform ? { platform } : {}),\n documentConcurrency: options.documentConcurrency ?? 1,\n ...(prerequisiteDocument\n ? { prerequisiteDocumentId: prerequisiteDocument.documentId }\n : {}),\n fileSelection,\n sources,\n documents,\n invocations,\n plans,\n collectionErrors,\n selectedCaseCount: documents.reduce(\n (total, document) => total + document.cases.length,\n 0,\n ),\n filteredCaseCount,\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, statSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { NativeWorkflowFormatError } from '../parser/collect';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n TestProjectRunOptions,\n TestRunInput,\n} from './execution-plan';\nimport {\n discoverTestConfig,\n prepareProject,\n selectProjects,\n} from './project-preparation';\nimport { loadTestProject } from './test-project';\n\nconst padDatePart = (value: number): string => String(value).padStart(2, '0');\n\nexport const createTestRunId = (\n date = new Date(),\n uuid = randomUUID(),\n): string => {\n const timestamp = [\n date.getFullYear(),\n padDatePart(date.getMonth() + 1),\n padDatePart(date.getDate()),\n padDatePart(date.getHours()),\n padDatePart(date.getMinutes()),\n padDatePart(date.getSeconds()),\n ].join('');\n return `${timestamp}-${uuid.slice(0, 8)}`;\n};\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nconst resolveRunInput = (options: TestProjectRunOptions): TestRunInput => {\n const cwd = resolve(options.cwd ?? process.cwd());\n assertDirectory(cwd, 'Test working directory');\n const inputPath = options.projectRoot\n ? resolve(cwd, options.projectRoot)\n : undefined;\n const singleFile =\n inputPath && existsSync(inputPath) && statSync(inputPath).isFile()\n ? inputPath\n : undefined;\n if (singleFile && !/\\.ya?ml$/i.test(singleFile))\n throw new Error(\n `Test input must be a YAML file or project directory: ${singleFile}`,\n );\n const cliProjectRoot = singleFile ? dirname(singleFile) : inputPath;\n if (cliProjectRoot) assertDirectory(cliProjectRoot, 'Test project directory');\n const projectRoot = cliProjectRoot ?? cwd;\n return {\n cwd,\n projectRoot,\n configSearchRoot: projectRoot,\n ...(singleFile ? { singleFile } : {}),\n };\n};\n\n/** Composition boundary only: execution receives no raw input syntax or host options. */\nexport async function prepareTestRun(\n options: TestProjectRunOptions,\n): Promise<PreparedTestRunPlan> {\n const startedAt = new Date();\n const runId = createTestRunId(startedAt);\n const input = resolveRunInput(options);\n const configPath = options.configPath\n ? resolve(input.configSearchRoot, options.configPath)\n : discoverTestConfig(input.configSearchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \\`midscene --config ${options.configPath}\\`.`,\n );\n }\n if (options.configPath && !existsSync(configPath!))\n throw new Error(`Midscene config does not exist: ${configPath}`);\n const definition = await loadTestProject<unknown>(configPath);\n const resultDir = options.resultDir\n ? resolve(input.cwd, options.resultDir)\n : join(input.projectRoot, '.midscene', 'test-results');\n const runDir = join(resultDir, runId);\n const summaryPath = join(runDir, 'summary.json');\n const reportDir = resolve(input.projectRoot, definition.output.reportDir);\n mkdirSync(resultDir, { recursive: true });\n mkdirSync(runDir);\n const projects: PreparedExecutionProject[] = [];\n for (const project of selectProjects(\n definition.projects,\n options.projectNames,\n ))\n projects.push(\n await prepareProject(\n project,\n input.projectRoot,\n runDir,\n definition.test.testTimeout,\n input.singleFile ? { files: [input.singleFile] } : undefined,\n ),\n );\n const hasFormatMismatch = projects.some((project) =>\n project.collectionErrors.some(\n ({ error }) => error instanceof NativeWorkflowFormatError,\n ),\n );\n return {\n startedAt,\n runId,\n projectRoot: input.projectRoot,\n ...(configPath ? { configPath } : {}),\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects,\n // A wrong-format file invalidates the complete command invocation. Other\n // native collection failures retain the existing per-Project isolation.\n preflightScope: hasFormatMismatch ? 'run' : 'project',\n reportEnabled: true,\n publications: [],\n onProgress: options.onProgress ?? (() => {}),\n };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport type {\n TestRunReportDump,\n TestRunReportSourceIndex,\n TestRunReportStep,\n} from '@midscene/core';\nimport type { TestProjectRunResult } from '../cli/types';\nimport { buildTestRunReportDump } from './test-run-report';\n\nconst text = (value: string): string =>\n value\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll('|', '&#124;')\n .replaceAll('[', '&#91;')\n .replaceAll(']', '&#93;')\n .replaceAll('*', '&#42;')\n .replaceAll('_', '&#95;')\n .replaceAll('`', '&#96;')\n .replaceAll('\\\\', '&#92;')\n .replace(/[\\r\\n]+/g, ' ');\n\nconst duration = (ms: number): string => {\n const seconds = Math.round(ms / 1000);\n return seconds < 60\n ? `${seconds}s`\n : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;\n};\nconst href = (from: string, target: string): string =>\n relative(dirname(from), target).split(sep).map(encodeURIComponent).join('/');\n\nexport interface TestResultMarkdownOptions {\n /** Relative or hosted URL of the HTML report. */\n reportHref?: string;\n}\n\n/** Render the same sanitized execution facts used by the HTML report. */\nexport function renderTestResultMarkdown(\n dump: TestRunReportDump,\n options: TestResultMarkdownOptions = {},\n): string {\n const { summary } = dump;\n const outcome =\n dump.status === 'success'\n ? `✅ **${summary.passed}/${summary.total} passed**`\n : `❌ **${summary.failed} failed** · ${summary.passed} passed · ${summary.notRun} not run`;\n const lines = [\n '## Midscene Test',\n '',\n `${outcome} · ${duration(dump.durationMs)}`,\n '',\n ];\n if (summary.filtered) lines.push(`**Filtered:** ${summary.filtered}`, '');\n const infrastructure = [\n summary.collectionErrors\n ? `${summary.collectionErrors} collection errors`\n : '',\n summary.documentFailures\n ? `${summary.documentFailures} document failures`\n : '',\n summary.projectFailures\n ? `${summary.projectFailures} project failures`\n : '',\n ].filter(Boolean);\n if (infrastructure.length)\n lines.push(`**Infrastructure:** ${infrastructure.join(' · ')}`, '');\n const groups: { name: string; rows: string[] }[] = [];\n const errors: string[] = [];\n const recordSteps = (label: string, steps: readonly TestRunReportStep[]) => {\n for (const step of steps) {\n if (step.status === 'failed')\n errors.push(\n `${label} / ${step.node}: ${step.error?.message ?? 'Step failed'}`,\n );\n }\n };\n for (const project of dump.projects) {\n if (project.lifecycle?.setupError)\n errors.push(`${project.name}: ${project.lifecycle.setupError.message}`);\n for (const error of project.lifecycle?.teardownErrors ?? [])\n errors.push(`${project.name}: ${error.message}`);\n for (const error of project.collectionErrors)\n errors.push(\n `${project.name} / ${error.sourcePath}: ${error.error.message}`,\n );\n for (const document of project.documents) {\n const name = document.sourcePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:yaml|yml)$/, '');\n const group = {\n name: dump.projects.length > 1 ? `${project.name} / ${name}` : name,\n rows: [] as string[],\n };\n groups.push(group);\n recordSteps(`${project.name} / ${document.sourcePath}`, [\n ...document.beforeAll,\n ...document.afterAll,\n ]);\n for (const error of document.teardownErrors ?? [])\n errors.push(`${document.sourcePath}: ${error.message}`);\n for (const failure of document.hostErrors ?? [])\n errors.push(\n `${document.sourcePath} / ${failure.phase}: ${failure.error.message}`,\n );\n for (const testCase of document.cases) {\n group.rows.push(\n ` - ${testCase.status === 'success' ? '✅' : testCase.status === 'not-run' ? '⏭️' : '❌'} ${text(testCase.name)}`,\n );\n }\n }\n }\n for (const diagnostic of dump.diagnostics ?? []) {\n if (diagnostic.level === 'error') errors.push(diagnostic.message);\n }\n if (errors.length)\n lines.push(\n '### Execution errors',\n '',\n ...errors.map((error) => `- ${text(error)}`),\n '',\n );\n for (const group of groups) {\n if (group.rows.length) lines.push(`- ${text(group.name)}`, ...group.rows);\n }\n if (!groups.some((group) => group.rows.length))\n lines.push('No cases were reported.');\n if (options.reportHref)\n lines.push(\n '',\n `[Open the Midscene Test report ↗](<${options.reportHref}>)`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n\nconst emptyIndex = (): TestRunReportSourceIndex => ({\n sources: [],\n metrics: {\n modelCallCount: 0,\n modelTimeMs: 0,\n promptTokens: 0,\n cachedInputTokens: 0,\n completionTokens: 0,\n totalTokens: 0,\n },\n});\n\n/** Write a per-run Markdown artifact even when HTML publication fails or is disabled. */\nexport async function writeTestResultMarkdown(\n result: TestProjectRunResult,\n index: TestRunReportSourceIndex = emptyIndex(),\n): Promise<string> {\n const output = join(dirname(result.summaryPath), 'result.md');\n const dump = buildTestRunReportDump(result, index);\n await writeFile(\n output,\n renderTestResultMarkdown(dump, {\n ...(result.reportPath\n ? { reportHref: href(output, result.reportPath) }\n : {}),\n }),\n );\n return output;\n}\n","import {\n WorkflowExecutionFailure,\n decideRetry,\n isResourceRecoveryError,\n runDocumentAttempts,\n runWorkflowDocument,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CaseRunOutcome,\n StepExecutionInfo,\n StepRunResult,\n WorkflowDocumentExecutionResult,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport { isFatalDeviceError } from '../errors';\nimport type { PreparedDocumentInvocation } from './execution-plan';\nimport {\n writeCaseAttemptResult,\n writeWorkflowDocumentResult,\n} from './result-store';\nimport type { LoadedExecutionProject } from './test-project';\nimport type { TestProjectCaseRunResult } from './types';\n\ninterface DocumentInvocationSinks {\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n}\n\ninterface ExecuteDocumentInvocationOptions {\n isolatedContext?: boolean;\n setupTimeoutMs?: number;\n teardownTimeoutMs?: () => number;\n onUnresolvedResources?(): void;\n /** Classify failures by resource ownership, independently of notifications. */\n isProjectResourceFailure?(error: unknown): boolean;\n invocation: PreparedDocumentInvocation;\n project: LoadedExecutionProject<unknown>;\n projectContext: unknown;\n runDir: string;\n signal: AbortSignal;\n rootSignal: AbortSignal;\n shouldBail(): boolean;\n isProjectFatal(): boolean;\n markProjectFatal(): void;\n addFailedCases(count: number): void;\n onProgress(message: string): void;\n onDocumentResult?(result: WorkflowDocumentRunResult): Promise<void>;\n sinks: DocumentInvocationSinks;\n}\n\nconst stepPosition = (info: StepExecutionInfo) =>\n info.scope === 'case' ? info.case : info.document;\n\nconst formatStep = (info: StepExecutionInfo): string => {\n const position = stepPosition(info);\n const phase = position.phase === 'steps' ? 'step' : position.phase;\n return `${phase} ${position.stepIndex + 1}/${info.stepCount}: ${info.node}`;\n};\n\nconst formatStepResult = (\n info: StepExecutionInfo,\n result: StepRunResult,\n): string => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n if (result.status === 'not-run')\n return `${indent}– ${formatStep(info)} (not run: ${result.notRunReason})`;\n const symbol = result.status === 'success' ? '✓' : '✗';\n const error = result.error ? ` — ${result.error.message}` : '';\n const continuation = result.continuedAfterError ? '; continuing' : '';\n return `${indent}${symbol} ${formatStep(info)} (${result.durationMs} ms)${error}${continuation}`;\n};\n\nconst caseHasFatalError = (outcome: CaseRunOutcome): boolean =>\n (outcome.attempts ?? []).some(\n (attempt) =>\n [...attempt.beforeEach, ...attempt.steps, ...attempt.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (attempt.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!attempt.executionErrors?.some(isResourceRecoveryError),\n );\n\nconst documentHasFatalError = (result: WorkflowDocumentRunResult): boolean =>\n [...result.beforeAll, ...result.afterAll].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (result.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!result.executionErrors?.some(isResourceRecoveryError);\n\n// Only an explicit ownership signal can establish a Project-wide failure.\nexport const isSharedResourceFailure = (error: unknown): boolean => {\n const seen = new Set<object>();\n const pending: unknown[] = [error];\n while (pending.length && seen.size < 50) {\n const item = pending.pop();\n if (typeof item !== 'object' || item === null || seen.has(item)) continue;\n seen.add(item);\n const failure = item as {\n code?: string;\n cause?: unknown;\n errors?: unknown[];\n };\n if (failure.code === 'PROJECT_RESOURCE_ERROR') return true;\n if (failure.cause) pending.push(failure.cause);\n if (Array.isArray(failure.errors))\n pending.push(...failure.errors.slice(0, 50));\n }\n return false;\n};\n\n/** Execute prepared document policies through the shared retry boundary. */\nexport async function executeDocumentInvocation(\n options: ExecuteDocumentInvocationOptions,\n): Promise<void> {\n const { invocation, project, sinks } = options;\n const isProjectResourceFailure =\n options.isProjectResourceFailure ?? (() => false);\n const { document } = invocation;\n const documentRetry = invocation.retry.scope === 'document';\n const attempts: WorkflowDocumentExecutionResult[] = [];\n const fileSetup = invocation.bindings.documentSetup;\n const documentSetup =\n options.isProjectResourceFailure && fileSetup\n ? {\n ...fileSetup,\n async setup(ctx: Parameters<typeof fileSetup.setup>[0]) {\n try {\n return await fileSetup.setup(ctx);\n } catch (error) {\n if (isProjectResourceFailure(error)) options.markProjectFatal();\n throw error;\n }\n },\n }\n : fileSetup;\n\n await runDocumentAttempts(\n {\n retry: documentRetry ? invocation.retry.count : 0,\n signal: options.signal,\n shouldStop: () => options.shouldBail() || options.isProjectFatal(),\n },\n async (documentAttemptIndex) => {\n if (documentRetry)\n options.onProgress(\n ` file attempt ${documentAttemptIndex + 1}/${invocation.retry.count + 1}: ${document.sourcePath}`,\n );\n const execution = await runWorkflowDocument(document, {\n plan: invocation.plan,\n documentAttemptIndex: documentRetry ? documentAttemptIndex : undefined,\n ...invocation.bindings,\n documentSetup,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n project,\n projectContext: options.projectContext,\n retry: documentRetry ? 0 : invocation.retry.count,\n signal: options.signal,\n defaultTimeoutMs: invocation.defaultTimeoutMs,\n shouldStop: () =>\n options.rootSignal.aborted ||\n options.shouldBail() ||\n options.isProjectFatal(),\n stopReason: () =>\n options.rootSignal.aborted\n ? 'interrupted'\n : options.isProjectFatal()\n ? 'fatal-error'\n : 'bail',\n isFatalError: (run) =>\n [...run.beforeEach, ...run.steps, ...run.afterEach].some(\n (step) =>\n step.error &&\n (isFatalDeviceError(step.error) ||\n isProjectResourceFailure(step.error)),\n ) ||\n (run.teardownErrors ?? []).some(\n (error) =>\n isFatalDeviceError(error) || isProjectResourceFailure(error),\n ),\n onCaseStart: (collectedCase) => {\n options.onProgress(\n ` [case ${collectedCase.caseIndex + 1}/${document.cases.length}] ${collectedCase.definition.name}`,\n );\n },\n onStepStart: (info) => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n options.onProgress(`${indent}→ ${formatStep(info)}`);\n },\n onStepResult: async (info, result) => {\n if (isProjectResourceFailure(result.error))\n options.markProjectFatal();\n await invocation.bindings.onStepResult?.(info, result);\n options.onProgress(formatStepResult(info, result));\n },\n onCaseResult: async (attempt) => {\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n options.onProgress(\n ` ${attempt.status === 'success' ? '✓' : '✗'} attempt ${attempt.attemptIndex + 1}/${documentRetry ? 1 : invocation.retry.count + 1}: ${attempt.name} (${attempt.durationMs} ms)`,\n );\n },\n onCaseOutcome: (outcome) => {\n if (\n outcome.attempts?.some(\n (attempt) =>\n [\n ...attempt.beforeEach,\n ...attempt.steps,\n ...attempt.afterEach,\n ].some((step) => isProjectResourceFailure(step.error)) ||\n attempt.teardownErrors?.some(isProjectResourceFailure),\n )\n )\n options.markProjectFatal();\n if (!options.isolatedContext && caseHasFatalError(outcome))\n options.markProjectFatal();\n if (!documentRetry && outcome.status === 'failed')\n options.addFailedCases(1);\n },\n onDocumentResult: options.onDocumentResult,\n }).catch(async (error: unknown) => {\n if (error instanceof WorkflowExecutionFailure) {\n const partial = error.result as WorkflowDocumentExecutionResult;\n const resourceOnly =\n error.errors.length > 0 &&\n error.errors.every(\n (failure) =>\n isResourceRecoveryError(failure) ||\n partial.document.hostErrors?.some(\n (host) =>\n host.phase === 'cleanup' &&\n (host.error === failure ||\n (host.error instanceof Error &&\n host.error.cause === failure)),\n ),\n );\n // Legacy recovery failures stop context reuse. Isolated file failures\n // are checked for unresolved resources below; publication still throws.\n if (resourceOnly) {\n if (\n !options.isolatedContext &&\n error.errors.some(isResourceRecoveryError)\n )\n options.markProjectFatal();\n return partial;\n }\n if (documentRetry)\n partial.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n attempts.push(partial);\n sinks.documents.push(partial.document);\n sinks.cases.push(\n ...partial.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: partial.document.documentRunId,\n })),\n );\n try {\n for (const outcome of partial.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, partial.document);\n } catch (publicationError) {\n throw new WorkflowExecutionFailure(partial, [\n ...error.errors,\n publicationError,\n ]);\n }\n }\n throw error;\n });\n\n if (!options.isolatedContext && documentHasFatalError(execution.document))\n options.markProjectFatal();\n if (\n [\n ...execution.document.beforeAll,\n ...execution.document.afterAll,\n ...(execution.document.hostErrors ?? []).map(({ error }) => ({\n error,\n })),\n ...(execution.document.teardownErrors ?? []).map((error) => ({\n error,\n })),\n ].some(({ error }) => isProjectResourceFailure(error))\n )\n options.markProjectFatal();\n const owners = [\n execution.document,\n ...execution.cases.flatMap((outcome) => outcome.attempts ?? []),\n ];\n const cleanupPending = owners.some(\n (owner) => owner.cleanup?.status === 'pending',\n );\n const operationPending = owners.some(\n (owner) => !!owner.pendingOperations?.length,\n );\n const cleanupFailed = owners.some(\n (owner) =>\n owner.cleanup?.status === 'failed' ||\n !!owner.teardownErrors?.length ||\n ('hostErrors' in owner &&\n owner.hostErrors?.some(({ phase }) => phase === 'cleanup')),\n );\n // Legacy files reuse their Project context. Isolated files may continue\n // after settled local cleanup failure; unresolved ownership stops dispatch.\n if (cleanupPending || operationPending) {\n options.markProjectFatal();\n options.onUnresolvedResources?.();\n } else if (cleanupFailed && !options.isolatedContext)\n options.markProjectFatal();\n const failed =\n execution.document.status === 'failed' ||\n execution.cases.some((item) => item.status !== 'success');\n const decision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: failed ? 'failed' : 'success',\n cleanupPending,\n cleanupFailed,\n operationPending,\n fatalError: options.isProjectFatal(),\n interrupted: options.signal.aborted || options.rootSignal.aborted,\n shouldStop: options.shouldBail(),\n });\n if (documentRetry) execution.document.retryDecision = decision;\n attempts.push(execution);\n sinks.cases.push(\n ...execution.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: execution.document.documentRunId,\n })),\n );\n sinks.documents.push(execution.document);\n // Per-attempt callbacks publish incremental facts; seal the final retry\n // decision after callback-driven interruption/bail has been observed.\n try {\n for (const outcome of execution.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, execution.document);\n } catch (error) {\n execution.document.status = 'failed';\n execution.document.hostErrors = [\n ...(execution.document.hostErrors ?? []),\n { phase: 'publication', error },\n ];\n if (documentRetry)\n execution.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n throw new WorkflowExecutionFailure(execution, [error]);\n }\n return decision.decision === 'retry' ? 'failed' : undefined;\n },\n );\n\n const final = attempts.at(-1);\n if (!final) return;\n const failedCases = final.cases.filter(\n (item) => item.status === 'failed',\n ).length;\n if (documentRetry && failedCases) options.addFailedCases(failedCases);\n else if (final.document.status === 'failed' && failedCases === 0)\n options.addFailedCases(Math.max(1, failedCases));\n}\n","import type {\n ProjectRuntime,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n WorkflowError,\n getPendingScopeOperations,\n getResourceCleanupCompletion,\n trackResourceOperation,\n waitForScopeOperations,\n} from '@midscene/core/internal/test-runner';\nimport { createProjectRuntime } from '../engine/project-runtime';\nimport {\n executeDocumentInvocation,\n isSharedResourceFailure,\n} from './document-invocation';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n} from './types';\n\ninterface FileProjectState {\n prepared: PreparedExecutionProject;\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n runtime?: ProjectRuntime;\n lifecycle?: TestExecutionProjectRunResult['lifecycle'];\n cursor: number;\n active: number;\n initializing: boolean;\n finished: boolean;\n fatal: boolean;\n setupFailed: boolean;\n}\n\ninterface FileSchedulerOptions {\n projects: readonly PreparedExecutionProject[];\n maxConcurrentFiles: number;\n maxConcurrentProjects: number;\n setupTimeoutMs: number;\n teardownTimeoutMs(): number;\n signal: AbortSignal;\n runDir: string;\n preflightFailed: boolean;\n shouldBail(): boolean;\n addFailedCases(count: number): void;\n announceProject(project: PreparedExecutionProject, index: number): void;\n onProgress(project: PreparedExecutionProject, message: string): void;\n onInfrastructureError(error: unknown): void;\n}\n\n/** Round-robin files within global file and live Project limits. */\nexport async function runPreparedFiles(\n options: FileSchedulerOptions,\n): Promise<FileProjectState[]> {\n const states: FileProjectState[] = options.projects.map((prepared) => ({\n prepared,\n cases: [],\n documents: [],\n cursor: 0,\n active: 0,\n initializing: false,\n finished: false,\n fatal: false,\n setupFailed: false,\n }));\n let nextProject = 0;\n let resourcesUnresolved = false;\n let occupied = 0;\n let occupiedProjects = 0;\n const cleanupQueue: Array<() => void> = [];\n const release = () => {\n occupied--;\n while (occupied < options.maxConcurrentFiles && cleanupQueue.length) {\n occupied++;\n cleanupQueue.shift()!();\n }\n wake?.();\n };\n let wake: (() => void) | undefined;\n const running = new Set<Promise<void>>();\n const stopped = (state: FileProjectState) =>\n options.signal.aborted || options.shouldBail() || state.fatal;\n const invalid = (state: FileProjectState) =>\n options.preflightFailed || state.prepared.collectionErrors.length > 0;\n const unresolved = () => {\n if (resourcesUnresolved) return;\n resourcesUnresolved = true;\n options.onInfrastructureError(\n new WorkflowError(\n 'Resources are still running or cleanup is pending. No new test files will start.',\n { code: 'UNRESOLVED_FILE_RESOURCES' },\n ),\n );\n };\n const finishProject = async (state: FileProjectState) => {\n if (!state.runtime || state.finished) return;\n state.finished = true;\n const failed =\n state.fatal ||\n options.signal.aborted ||\n state.cases.some((item) => item.status !== 'success') ||\n state.documents.some((item) => item.status !== 'success');\n state.lifecycle = await state.runtime.finish(failed ? 'failed' : 'success');\n const releaseProject = () => {\n occupiedProjects--;\n wake?.();\n };\n if (\n state.lifecycle.cleanup?.status === 'pending' ||\n state.lifecycle.pendingOperations?.length\n ) {\n unresolved();\n // A result snapshot can precede actual resource release.\n void Promise.all([\n waitForScopeOperations(state.runtime.signal),\n getResourceCleanupCompletion(state.runtime.signal),\n ]).then(releaseProject, (error) => {\n options.onInfrastructureError(error);\n releaseProject();\n });\n } else releaseProject();\n };\n\n const admit = () => {\n for (let offset = 0; offset < states.length; offset++) {\n const index = (nextProject + offset) % states.length;\n const state = states[index];\n if (invalid(state) || state.finished || state.initializing) continue;\n if (!state.runtime && occupiedProjects >= options.maxConcurrentProjects)\n continue;\n const cleanupOnly =\n !!state.runtime &&\n state.active === 0 &&\n (stopped(state) || state.cursor === state.prepared.invocations.length);\n if (\n !cleanupOnly &&\n (stopped(state) ||\n state.cursor >= state.prepared.invocations.length ||\n state.active >=\n (state.prepared.project.maxConcurrentFiles ??\n options.maxConcurrentFiles))\n )\n continue;\n nextProject = (index + 1) % states.length;\n occupied++;\n state.active++;\n if (!state.runtime && !cleanupOnly) {\n // Claim both budgets before setup so idle Projects are not pre-created.\n occupiedProjects++;\n state.initializing = true;\n }\n const invocationIndex = cleanupOnly ? -1 : state.cursor++;\n return { state, index, invocationIndex };\n }\n };\n\n const run = async ({\n state,\n index,\n invocationIndex,\n }: NonNullable<ReturnType<typeof admit>>) => {\n const { prepared } = state;\n const { project } = prepared;\n let fileResourcesPending = false;\n try {\n if (invocationIndex < 0) {\n await finishProject(state);\n return;\n }\n if (!state.runtime) {\n state.runtime = createProjectRuntime({\n project,\n setup: project.setup,\n signal: options.signal,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n });\n setMaxListeners(\n Math.max(\n 10,\n Math.min(\n prepared.invocations.length,\n project.maxConcurrentFiles ?? options.maxConcurrentFiles,\n ) + 1,\n ),\n state.runtime.signal,\n );\n options.announceProject(prepared, index);\n await state.runtime.start();\n state.initializing = false;\n if (!state.runtime.canRun) {\n state.fatal = true;\n state.setupFailed = true;\n }\n wake?.();\n }\n if (stopped(state)) return;\n const invocation = prepared.invocations[invocationIndex];\n options.onProgress(\n prepared,\n ` [document ${invocationIndex + 1}/${prepared.invocations.length}] ${invocation.document.sourcePath}`,\n );\n await executeDocumentInvocation({\n invocation,\n project,\n projectContext: state.runtime.context,\n runDir: options.runDir,\n signal: state.runtime.signal,\n rootSignal: options.signal,\n shouldBail: options.shouldBail,\n isProjectFatal: () => state.fatal,\n markProjectFatal: () => {\n if (state.fatal) return;\n state.fatal = true;\n state.runtime?.abort(\n new WorkflowError(\n `Project \"${project.name}\" shared execution environment is unavailable.`,\n { code: 'PROJECT_RESOURCE_ERROR' },\n ),\n );\n },\n addFailedCases: options.addFailedCases,\n onProgress: (message) => options.onProgress(prepared, message),\n sinks: state,\n isolatedContext: project.fileSetup !== undefined,\n isProjectResourceFailure: isSharedResourceFailure,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n onUnresolvedResources: () => {\n fileResourcesPending = true;\n unresolved();\n },\n });\n } catch (error) {\n state.fatal = true;\n fileResourcesPending =\n !!state.runtime &&\n getPendingScopeOperations(state.runtime.signal).length > 0;\n options.onInfrastructureError(error);\n } finally {\n state.initializing = false;\n try {\n // The last file retains its global/local admission through shared cleanup.\n if (\n state.active === 1 &&\n (stopped(state) || state.cursor === prepared.invocations.length)\n )\n await finishProject(state);\n } catch (error) {\n options.onInfrastructureError(error);\n }\n state.active--;\n if (\n state.runtime &&\n (fileResourcesPending || state.lifecycle?.cleanup?.status === 'pending')\n ) {\n // A returned pending snapshot does not release the actual admission.\n // At shutdown this may conservatively wait for siblings in the Project.\n void waitForScopeOperations(state.runtime.signal).then(\n release,\n (error) => {\n options.onInfrastructureError(error);\n release();\n },\n );\n } else release();\n wake?.();\n }\n };\n\n while (true) {\n const changed = new Promise<void>((resolve) => {\n wake = resolve;\n });\n while (occupied < options.maxConcurrentFiles) {\n const job = admit();\n if (!job) break;\n const task = run(job);\n running.add(task);\n const settled = () => {\n running.delete(task);\n wake?.();\n };\n void task.then(settled, (error) => {\n options.onInfrastructureError(error);\n settled();\n });\n }\n if (!running.size) break;\n await changed;\n }\n wake = undefined;\n\n // Pending acquisitions/disposers retain their admissions after the result\n // deadline. Idle initialized Projects queue actual cleanup behind those\n // admissions; their snapshots still return within the shared shutdown limit.\n await Promise.all(\n states.map(async (state) => {\n if (!state.runtime || state.finished) return;\n const admission = new Promise<void>((resolve) => {\n cleanupQueue.push(resolve);\n });\n trackResourceOperation({}, admission, state.runtime.signal);\n while (occupied < options.maxConcurrentFiles && cleanupQueue.length) {\n occupied++;\n cleanupQueue.shift()!();\n }\n try {\n await finishProject(state);\n } catch (error) {\n options.onInfrastructureError(error);\n } finally {\n void Promise.all([\n admission,\n getResourceCleanupCompletion(state.runtime.signal),\n ]).then(release, (error) => {\n options.onInfrastructureError(error);\n release();\n });\n }\n }),\n );\n\n for (const state of states) {\n const { prepared } = state;\n if (!state.runtime)\n options.announceProject(prepared, states.indexOf(state));\n const completed = new Set(state.cases.map((item) => item.caseId));\n const reason = invalid(state)\n ? 'project-preflight-failed'\n : state.setupFailed\n ? 'project-setup-failed'\n : options.signal.aborted\n ? 'interrupted'\n : state.fatal\n ? 'fatal-error'\n : 'bail';\n for (const document of prepared.documents) {\n for (const item of document.cases) {\n if (completed.has(item.caseId)) continue;\n state.cases.push({\n documentId: document.documentId,\n caseId: item.caseId,\n projectName: prepared.project.name,\n name: item.definition.name,\n sourcePath: item.sourcePath,\n caseIndex: item.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n });\n }\n }\n const order = new Map(\n prepared.documents.map((document, i) => [document.documentId, i]),\n );\n const position = (id: string) => order.get(id) ?? Number.MAX_SAFE_INTEGER;\n state.cases.sort(\n (a, b) =>\n position(a.documentId) - position(b.documentId) ||\n a.caseIndex - b.caseIndex,\n );\n state.documents.sort(\n (a, b) => position(a.documentId) - position(b.documentId),\n );\n }\n return states;\n}\nimport { setMaxListeners } from 'node:events';\n","import { appendFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { TestRunReportOperationEvent } from '@midscene/core';\n\n/** Registered operations keep this sink after the report has been sealed.\n * Each small, bounded event is written before returning to the operation. No\n * open file descriptor or mutable report object is retained by the journal.\n */\nexport function createOperationJournal(runDir: string) {\n const path = join(runDir, 'operations.jsonl');\n writeFileSync(path, '', { flag: 'wx' });\n return {\n path,\n append(event: Readonly<TestRunReportOperationEvent>) {\n appendFileSync(path, `${JSON.stringify(event)}\\n`);\n },\n };\n}\n","import { setMaxListeners } from 'node:events';\nimport { dirname, join } from 'node:path';\nimport type { TestRunReportSourceIndex } from '@midscene/core';\nimport {\n WorkflowExecutionFailure,\n WorkflowPublicationError,\n asExecutionError,\n observeResourceOperations,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CollectedCase,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n TestRunReportAssembler,\n calculateTestRunHealth,\n} from '@midscene/core/report';\nimport { getDebug } from '@midscene/shared/logger';\nimport { writeTestResultMarkdown } from '../report/result-markdown';\nimport {\n buildTestRunReportDump,\n collectTestRunReportSources,\n} from '../report/test-run-report';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n} from './execution-plan';\nimport { runPreparedFiles } from './file-scheduler';\nimport { createOperationJournal } from './operation-journal';\nimport { writeTestProjectRunResult, writeTestRunPlan } from './result-store';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n TestProjectRunResult,\n TestProjectRunSummary,\n} from './types';\n\nconst asNotRun = (\n documentId: string,\n collectedCase: CollectedCase,\n projectName: string,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult => ({\n documentId,\n caseId: collectedCase.caseId,\n projectName,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n});\n\nconst summarize = (\n projects: readonly TestExecutionProjectRunResult[],\n): TestProjectRunSummary => {\n const healthCases = projects.flatMap((project) => {\n const documentAttemptByRunId = new Map(\n project.documents.map((document) => [\n document.documentRunId,\n document.attemptIndex ?? 0,\n ]),\n );\n return latestById(project.cases, (item) => item.caseId).map((item) => {\n return {\n status: item.status,\n ...(item.run ? { run: item.run } : {}),\n ...(item.attempts ? { attempts: item.attempts } : {}),\n retryCount: item.documentRunId\n ? (documentAttemptByRunId.get(item.documentRunId) ?? 0)\n : 0,\n };\n });\n });\n const documents = projects.flatMap((project) =>\n latestById(project.documents, (item) => item.documentId),\n );\n const health = calculateTestRunHealth(healthCases);\n return {\n total: health.total,\n passed: health.passed,\n failed: health.failed,\n notRun: health.notRun,\n passedAfterRetry: health.passedAfterRetry,\n finalPassRate: health.finalPassRate,\n firstPassRate: health.firstPassRate,\n filtered: projects.reduce(\n (total, project) => total + project.filteredCaseCount,\n 0,\n ),\n collectionErrors: projects.reduce(\n (total, project) => total + project.collectionErrors.length,\n 0,\n ),\n documentFailures: documents.filter(\n (document) => document.status === 'failed',\n ).length,\n projectFailures: projects.filter((project) => project.status === 'failed')\n .length,\n };\n};\n\nconst latestById = <T>(items: readonly T[], id: (item: T) => string): T[] => [\n ...new Map(items.map((item) => [id(item), item])).values(),\n];\n\nconst notRunSuite = (\n prepared: PreparedExecutionProject,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult[] =>\n prepared.documents.flatMap((document) =>\n document.cases.map((item) =>\n asNotRun(document.documentId, item, prepared.project.name, reason),\n ),\n );\n\n/** The executor sees prepared policies and bindings, never source-language rules. */\nexport async function runPreparedTestProject(\n plan: PreparedTestRunPlan,\n): Promise<TestProjectRunResult> {\n const {\n startedAt,\n runId,\n projectRoot,\n configPath,\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects: preparedProjects,\n } = plan;\n const progress = plan.onProgress;\n const totalDocuments = preparedProjects.reduce(\n (total, prepared) => total + prepared.documents.length,\n 0,\n );\n const totalCases = preparedProjects.reduce(\n (total, prepared) => total + prepared.selectedCaseCount,\n 0,\n );\n const totalErrors = preparedProjects.reduce(\n (total, prepared) => total + prepared.collectionErrors.length,\n 0,\n );\n progress(\n `midscene-test: preflighted ${preparedProjects.length} projects, ${totalDocuments} documents, ${totalCases} cases, ${totalErrors} collection errors`,\n );\n\n const effectiveConcurrency = Math.min(\n definition.test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY,\n Math.max(1, totalDocuments),\n );\n await writeTestRunPlan(runDir, preparedProjects);\n const journal = createOperationJournal(runDir);\n const rootController = new AbortController();\n setMaxListeners(\n Math.max(10, effectiveConcurrency + 1),\n rootController.signal,\n );\n const handleSignal = (signal: NodeJS.Signals) => {\n rootController.abort(new Error(`Workflow interrupted by ${signal}.`));\n };\n const sigint = () => handleSignal('SIGINT');\n const sigterm = () => handleSignal('SIGTERM');\n process.on('SIGINT', sigint);\n process.on('SIGTERM', sigterm);\n\n let failedCaseCount = 0;\n const bailReached = () =>\n definition.test.bail > 0 && failedCaseCount >= definition.test.bail;\n let shutdownDeadline: number | undefined;\n const beginShutdown = () => {\n shutdownDeadline ??= Date.now() + definition.test.teardownTimeout;\n };\n rootController.signal.addEventListener('abort', beginShutdown, {\n once: true,\n });\n const addFailedCases = (count: number) => {\n failedCaseCount += count;\n if (bailReached()) beginShutdown();\n };\n const teardownTimeoutMs = () =>\n Math.max(\n 0,\n Math.min(\n definition.test.teardownTimeout,\n shutdownDeadline === undefined\n ? Number.POSITIVE_INFINITY\n : shutdownDeadline - Date.now(),\n ),\n );\n let hasInfrastructureError = false;\n const infrastructureErrors: unknown[] = [];\n const recordInfrastructureError = (error: unknown) => {\n const errors =\n error instanceof WorkflowExecutionFailure ? error.errors : [error];\n for (const item of errors)\n if (!infrastructureErrors.includes(item)) infrastructureErrors.push(item);\n hasInfrastructureError = true;\n rootController.abort(error);\n };\n const runInfrastructureCallback = <T>(callback: () => T): T => {\n try {\n return callback();\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n };\n const stopObservingOperations = observeResourceOperations(\n rootController.signal,\n (event) => {\n try {\n journal.append(event);\n } catch (error) {\n recordInfrastructureError(\n new WorkflowPublicationError('write-result', journal.path, error),\n );\n getDebug('test-runner:operations', { console: true })(\n `Could not persist operation event: ${String(error)}`,\n );\n }\n },\n );\n type PreparedProject = (typeof preparedProjects)[number];\n const announceProject = (prepared: PreparedProject, projectIndex: number) => {\n const { project } = prepared;\n runInfrastructureCallback(() =>\n progress(\n `[project ${projectIndex + 1}/${preparedProjects.length}] ${project.name}`,\n ),\n );\n };\n const buildProjectResult = (\n prepared: PreparedProject,\n cases: readonly TestProjectCaseRunResult[],\n documents: readonly WorkflowDocumentRunResult[],\n lifecycle?: TestExecutionProjectRunResult['lifecycle'],\n ): TestExecutionProjectRunResult => {\n const { project } = prepared;\n const projectFailed =\n prepared.collectionErrors.length > 0 ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n lifecycle?.status === 'failed';\n return {\n projectId: project.projectId,\n name: project.name,\n ...(prepared.platform ? { platform: prepared.platform } : {}),\n status: projectFailed ? 'failed' : 'success',\n retry: project.retry,\n fileSelection: prepared.fileSelection,\n tagSelection: project.tags,\n sourceCount: prepared.sources.length,\n selectedCaseCount: prepared.selectedCaseCount,\n filteredCaseCount: prepared.filteredCaseCount,\n ...(lifecycle ? { lifecycle } : {}),\n cases,\n plans: prepared.plans,\n documents,\n collectionErrors: prepared.collectionErrors,\n };\n };\n const buildSkippedProjectResult = (\n prepared: PreparedProject,\n projectIndex: number,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n ): TestExecutionProjectRunResult => {\n announceProject(prepared, projectIndex);\n return buildProjectResult(prepared, notRunSuite(prepared, reason), []);\n };\n const projectResults: Array<TestExecutionProjectRunResult | undefined> =\n new Array(preparedProjects.length);\n\n try {\n const states = await runPreparedFiles({\n projects: preparedProjects,\n maxConcurrentFiles: effectiveConcurrency,\n maxConcurrentProjects:\n definition.test.maxConcurrentProjects ?? Number.POSITIVE_INFINITY,\n setupTimeoutMs: definition.test.setupTimeout,\n teardownTimeoutMs,\n signal: rootController.signal,\n runDir,\n preflightFailed: plan.preflightScope === 'run' && totalErrors > 0,\n shouldBail: bailReached,\n addFailedCases,\n announceProject,\n onProgress: (prepared, message) =>\n runInfrastructureCallback(() =>\n progress(\n effectiveConcurrency > 1\n ? `[${prepared.project.name}]${message}`\n : message,\n ),\n ),\n onInfrastructureError: recordInfrastructureError,\n });\n states.forEach((state, index) => {\n projectResults[index] = buildProjectResult(\n state.prepared,\n state.cases,\n state.documents,\n state.lifecycle,\n );\n });\n } catch (error) {\n recordInfrastructureError(error);\n } finally {\n stopObservingOperations();\n process.off('SIGINT', sigint);\n process.off('SIGTERM', sigterm);\n }\n\n const completedProjectResults = preparedProjects.map(\n (prepared, projectIndex) => {\n const result = projectResults[projectIndex];\n if (result) return result;\n const reason = prepared.collectionErrors.length\n ? 'project-preflight-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : bailReached()\n ? 'bail'\n : undefined;\n if (!reason) {\n throw new Error(\n `Project scheduler did not produce a result for \"${prepared.project.name}\".`,\n );\n }\n return buildSkippedProjectResult(prepared, projectIndex, reason);\n },\n );\n\n const summary = summarize(completedProjectResults);\n const failed =\n hasInfrastructureError ||\n rootController.signal.aborted ||\n summary.failed > 0 ||\n summary.notRun > 0 ||\n summary.collectionErrors > 0 ||\n summary.documentFailures > 0 ||\n summary.projectFailures > 0;\n const endedAt = new Date();\n const result: TestProjectRunResult = {\n schemaVersion: 3,\n operationLog: { path: journal.path, snapshotAt: endedAt.toISOString() },\n runId,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n status: failed ? 'failed' : 'success',\n exitCode: failed ? 1 : 0,\n resultDir,\n summaryPath,\n reportDir,\n summary,\n projects: completedProjectResults,\n cases: completedProjectResults.flatMap((project) => project.cases),\n documents: completedProjectResults.flatMap((project) => project.documents),\n collectionErrors: completedProjectResults.flatMap(\n (project) => project.collectionErrors,\n ),\n ...(hasInfrastructureError\n ? { errors: infrastructureErrors.map(asExecutionError) }\n : {}),\n };\n let completedResult = result;\n let reportIndex: TestRunReportSourceIndex | undefined;\n const publish = async (\n operation: 'write-result' | 'write-report',\n path: string,\n callback: () => unknown | Promise<unknown>,\n ): Promise<boolean> => {\n try {\n await callback();\n return true;\n } catch (error) {\n recordInfrastructureError(\n error instanceof WorkflowPublicationError ||\n error instanceof WorkflowExecutionFailure\n ? error\n : new WorkflowPublicationError(operation, path, error),\n );\n completedResult = {\n ...completedResult,\n status: 'failed',\n exitCode: 1,\n errors: infrastructureErrors.map(asExecutionError),\n };\n return false;\n }\n };\n const writeSummary = () =>\n publish('write-result', summaryPath, () =>\n writeTestProjectRunResult({\n projectRoot,\n ...(configPath ? { configPath } : {}),\n result: completedResult,\n }),\n );\n const writeReport = () =>\n publish('write-report', reportDir, async () => {\n if (!plan.reportEnabled) return;\n const reportPath = await new TestRunReportAssembler().assembleAsync({\n outputDir: reportDir,\n reportFileName: `midscene-e2e-${runId}`,\n overwrite: false,\n sources: collectTestRunReportSources(completedResult),\n buildRunnerDump: (index) => {\n reportIndex = index;\n const dump = buildTestRunReportDump(completedResult, index);\n const warn = getDebug('test-runner:report-assembler', {\n console: true,\n });\n for (const diagnostic of dump.diagnostics ?? [])\n warn(diagnostic.message);\n return dump;\n },\n });\n completedResult = { ...completedResult, reportPath };\n });\n // Publish each artifact once. The summary includes the report path or its\n // failure. If the summary itself fails, the thrown result remains authoritative;\n // do not rebuild an already-published execution report to backfill that error.\n await writeReport();\n for (const publication of plan.publications)\n await publish(publication.operation, publication.path, async () => {\n await publication.publish(completedResult);\n });\n await publish(\n 'write-result',\n join(dirname(summaryPath), 'result.md'),\n async () => {\n const markdownPath = await writeTestResultMarkdown(\n completedResult,\n reportIndex,\n );\n completedResult = { ...completedResult, markdownPath };\n },\n );\n await writeSummary();\n if (hasInfrastructureError)\n throw new WorkflowExecutionFailure(completedResult, infrastructureErrors);\n return completedResult;\n}\n","import type { TestProjectRunOptions } from './execution-plan';\nimport { prepareTestRun } from './prepare-test-run';\nimport { runPreparedTestProject } from './run-prepared-project';\nimport type { TestProjectRunResult } from './types';\n\nexport type { TestProjectRunOptions } from './execution-plan';\nexport { createTestRunId } from './prepare-test-run';\nexport {\n DEFAULT_TEST_FILE_SELECTION,\n discoverTestConfig,\n discoverTestFiles,\n} from './project-preparation';\n\n/** Native Test entry for cases/steps workflow documents. */\nexport async function runTestProject(\n options: TestProjectRunOptions = {},\n): Promise<TestProjectRunResult> {\n return runPreparedTestProject(await prepareTestRun(options));\n}\n","import { existsSync, statSync, writeFileSync } from 'node:fs';\nimport { relative, resolve, sep } from 'node:path';\nimport { WorkflowExecutionFailure } from '@midscene/core/internal/test-runner';\nimport { version } from '../../package.json';\nimport { formatCliError } from './error-format';\nimport { renderNodeSpec, sortNodesForSpec } from './node-spec';\nimport { loadTestProject } from './test-project';\nimport {\n DEFAULT_TEST_FILE_SELECTION,\n discoverTestConfig,\n runTestProject,\n} from './test-project-runner';\nimport type { TestProjectRunResult } from './types';\n\nexport interface TestCliIO {\n log(message: string): void;\n error(message: string): void;\n write?(message: string): void;\n}\n\ninterface ParsedTestArgs {\n command?: 'nodes';\n cwd: string;\n projectRoot?: string;\n configPath?: string;\n resultDir?: string;\n projectNames?: string[];\n}\n\nexport const parseTestCliArgs = (\n args: string[],\n cwd = process.cwd(),\n): ParsedTestArgs => {\n const command = args[0] === 'nodes' ? args[0] : undefined;\n const commandOffset = command ? 1 : 0;\n let projectRoot: string | undefined;\n let configPath: string | undefined;\n let resultDir: string | undefined;\n const projectNames: string[] = [];\n\n for (let index = commandOffset; index < args.length; index += 1) {\n const token = args[index];\n const equal = token.startsWith('-') ? token.indexOf('=') : -1;\n const arg = equal < 0 ? token : token.slice(0, equal);\n const inlineValue = equal < 0 ? undefined : token.slice(equal + 1);\n if (!arg.startsWith('-')) {\n if (projectRoot)\n throw new Error('Only one test project directory is allowed.');\n projectRoot = resolve(cwd, arg);\n continue;\n }\n if (arg === '--config' || arg === '--result-dir' || arg === '--project') {\n const value = inlineValue ?? args[index + 1];\n if (!value || value.startsWith('--'))\n throw new Error(`${arg} requires a value.`);\n if (arg === '--config') configPath = value;\n else if (arg === '--result-dir') resultDir = resolve(cwd, value);\n else projectNames.push(value);\n if (inlineValue === undefined) index += 1;\n } else {\n throw new Error(`Unknown option: ${token}`);\n }\n }\n\n if (command === 'nodes' && resultDir) {\n throw new Error('--result-dir is not supported by nodes.');\n }\n if (command === 'nodes' && projectNames.length > 1) {\n throw new Error('nodes accepts only one --project name.');\n }\n return {\n ...(command ? { command } : {}),\n cwd,\n projectRoot,\n configPath,\n resultDir,\n ...(projectNames.length > 0 ? { projectNames } : {}),\n };\n};\n\nconst defaultCliIO: TestCliIO = {\n log: console.log,\n error: console.error,\n write: (message) => process.stdout.write(message),\n};\n\nconst testCliHelp = `Midscene Test: run native cases/steps Test projects.\n\nUsage:\n midscene-test [file.yaml | directory] [options]\n midscene-test --config <midscene.config.ts> [options]\n midscene-test nodes [directory] [--config midscene.config.ts]\n midscene-test create --help\n midscene-test model verify Check model connectivity and Midscene compatibility\n\nOptions:\n --config <path> Native TypeScript or JavaScript Test config\n --project <name> Select a native execution Project (repeatable)\n --result-dir <path> Store Test result files in this directory\n --help, -h Show this help\n --version Show the package version\n\nLegacy tasks/flow YAML and its CLI options belong to the midscene command.\n`;\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nconst runNodesCommand = async (\n options: ParsedTestArgs,\n io: TestCliIO,\n): Promise<void> => {\n const cwd = resolve(options.cwd);\n assertDirectory(cwd, 'Test working directory');\n const projectRoot = options.projectRoot\n ? resolve(cwd, options.projectRoot)\n : undefined;\n if (projectRoot) assertDirectory(projectRoot, 'Test project directory');\n\n const configSearchRoot = projectRoot ?? cwd;\n const configPath = options.configPath\n ? resolve(configSearchRoot, options.configPath)\n : discoverTestConfig(configSearchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test nodes --config only accepts a native TypeScript or JavaScript project config: ${configPath}.`,\n );\n }\n if (options.configPath && (!configPath || !existsSync(configPath))) {\n throw new Error(`Midscene config does not exist: ${configPath}`);\n }\n\n const project = await loadTestProject(configPath);\n const projectName = options.projectNames?.[0];\n const selectedProjects = projectName\n ? project.projects.filter((candidate) => candidate.name === projectName)\n : project.projects;\n if (selectedProjects.length === 0) {\n throw new Error(`Unknown Midscene project: ${projectName}`);\n }\n // Check every Project before writing, including when only one is selected.\n const filenames = new Map<string, string>();\n const owners = new Map<string, string>();\n for (const executionProject of project.projects) {\n const safeName = executionProject.name\n .normalize('NFC')\n // biome-ignore lint/suspicious/noControlCharactersInRegex: filenames cannot contain control characters.\n .replace(/[<>:\"/\\\\|?*\\u0000-\\u001f]/g, '-')\n .replace(/[. ]+$/g, '-');\n const filename = project.hasExplicitProjects\n ? `midscene-node-spec.${safeName}.md`\n : 'midscene-node-spec.md';\n const key = filename.toLowerCase();\n const owner = owners.get(key);\n if (owner !== undefined) {\n throw new Error(\n `Projects \"${owner}\" and \"${executionProject.name}\" generate the same Node Spec filename: ${filename}`,\n );\n }\n owners.set(key, executionProject.name);\n filenames.set(executionProject.name, filename);\n }\n const specs = selectedProjects.map((executionProject) => {\n const nodes = sortNodesForSpec(executionProject.nodes.definitions());\n const document = renderNodeSpec(nodes, {\n configPath: configPath\n ? relative(configSearchRoot, configPath).split(sep).join('/')\n : undefined,\n projects: [\n {\n name: executionProject.name,\n files: executionProject.files ?? DEFAULT_TEST_FILE_SELECTION,\n },\n ],\n });\n return { executionProject, nodes, document };\n });\n for (const { executionProject, nodes, document } of specs) {\n for (const warning of document.warnings) {\n io.error(`midscene-test nodes: ${warning}`);\n }\n const specPath = resolve(\n configSearchRoot,\n filenames.get(executionProject.name)!,\n );\n writeFileSync(specPath, document.markdown);\n if (project.hasExplicitProjects || projectName) {\n io.log(`Execution Project: ${executionProject.name}`);\n }\n io.log(`Registered Nodes (${nodes.length}):`);\n if (nodes.length === 0) {\n io.log('No nodes are registered by the current Test Project.');\n }\n for (const node of nodes) {\n io.log(\n `- ${node.name}: ${node.description?.trim() || 'Description not declared.'}`,\n );\n }\n io.log(`\\nNode Spec generated: ${specPath}`);\n }\n};\n\nconst reportTestProjectResult = (\n result: TestProjectRunResult,\n io: TestCliIO,\n infrastructureErrors: readonly unknown[] = result.errors ?? [],\n): number => {\n const reportedErrors = new Set<Error>();\n const reportError = (source: string, error: unknown): void => {\n if (error instanceof Error && reportedErrors.has(error)) return;\n io.error(`midscene-test: ${source}: ${formatCliError(error)}`);\n // Infrastructure failures carry raw errors that can also be causes of\n // the contextual errors already printed from the execution result.\n const pending = [error];\n while (pending.length > 0) {\n const current = pending.pop();\n if (!(current instanceof Error) || reportedErrors.has(current)) continue;\n reportedErrors.add(current);\n pending.push(current.cause);\n if (current instanceof AggregateError) pending.push(...current.errors);\n }\n };\n for (const failure of result.collectionErrors) {\n reportError(`${failure.projectName}/${failure.sourcePath}`, failure.error);\n }\n const finalCases = new Map(\n result.cases.map((outcome) => [outcome.caseId, outcome]),\n );\n for (const outcome of finalCases.values()) {\n if (outcome.status !== 'failed' || !outcome.run) continue;\n const run = outcome.run;\n const source = `${run.projectName}/${run.sourcePath} / ${run.name}`;\n for (const step of [...run.beforeEach, ...run.steps, ...run.afterEach]) {\n if (step.error) {\n reportError(\n `${source} / ${step.phase}[${step.stepIndex + 1}] ${step.node}`,\n step.error,\n );\n }\n }\n for (const error of [\n ...(run.executionErrors ?? []),\n ...(run.teardownErrors ?? []),\n ]) {\n reportError(source, error);\n }\n }\n const finalDocuments = new Map(\n result.documents.map((document) => [document.documentId, document]),\n );\n for (const document of finalDocuments.values()) {\n if (document.status !== 'failed') continue;\n const source = `${document.projectName}/${document.sourcePath}`;\n for (const step of [...document.beforeAll, ...document.afterAll]) {\n if (step.error) {\n reportError(\n `${source} / ${step.phase}[${step.stepIndex + 1}] ${step.node}`,\n step.error,\n );\n }\n }\n for (const error of [\n ...(document.executionErrors ?? []),\n ...(document.teardownErrors ?? []),\n ]) {\n reportError(source, error);\n }\n for (const failure of document.hostErrors ?? []) {\n reportError(`${source} / host ${failure.phase}`, failure.error);\n }\n }\n for (const project of result.projects) {\n if (project.lifecycle?.setupError) {\n reportError(`${project.name} / setup`, project.lifecycle.setupError);\n }\n for (const error of project.lifecycle?.teardownErrors ?? []) {\n reportError(`${project.name} / teardown`, error);\n }\n }\n for (const error of infrastructureErrors) {\n reportError('infrastructure', error);\n }\n io.log(\n `midscene-test: ${result.summary.passed}/${result.summary.total} cases passed, ${result.summary.failed} failed, ${result.summary.notRun} not run`,\n );\n io.log(`Results: ${result.resultDir}`);\n io.log(`Summary: ${result.summaryPath}`);\n if (result.markdownPath) io.log(`Markdown: ${result.markdownPath}`);\n if (result.reportPath) io.log(`Report: ${result.reportPath}`);\n return result.exitCode;\n};\n\nexport async function runTestCli(\n args: string[],\n io: TestCliIO = defaultCliIO,\n): Promise<number> {\n try {\n if (args[0] === 'model') {\n const { runModelCommand } = await import('./model-command');\n return runModelCommand(args, undefined, {\n stdout: io.log,\n stderr: io.error,\n });\n }\n if (args[0] === 'create') {\n const { runCreateCommand } = await import('./create-command');\n await runCreateCommand(args.slice(1), io);\n return 0;\n }\n if (args.includes('--help') || args.includes('-h')) {\n io.log(testCliHelp);\n return 0;\n }\n if (args.includes('--version')) {\n io.log(version);\n return 0;\n }\n const options = parseTestCliArgs(args);\n if (options.command === 'nodes') {\n await runNodesCommand(options, io);\n return 0;\n }\n let result: TestProjectRunResult;\n try {\n result = await runTestProject({\n ...options,\n onProgress: (message) => io.log(message),\n });\n } catch (error) {\n if (!(error instanceof WorkflowExecutionFailure)) throw error;\n reportTestProjectResult(error.result, io, error.errors);\n return 1;\n }\n return reportTestProjectResult(result, io);\n } catch (error) {\n io.error(formatCliError(error));\n return 1;\n }\n}\n","import { runTestCli } from './cli/test-command';\n\nvoid runTestCli(process.argv.slice(2)).then((exitCode) => {\n process.exitCode = exitCode;\n});\n"],"names":["__webpack_require__","exports","definition","key","Object","chunkId","Promise","promises","obj","prop","installedChunks","installChunk","data","__rspack_esm_ids","__webpack_modules__","__rspack_esm_runtime","moduleId","i","installedChunkData","promise","e","resolve","formatCliError","error","inspect","GENERATED_COMMENT","sortNodesForSpec","nodes","priority","name","left","right","escapeTableCell","value","renderNodeOverview","heading","rows","node","renderWorkflowLocations","location","sections","project","patterns","pattern","projectLabel","excludes","WORKFLOW_STEP_CONTRACT","sortJsonValue","Array","child","assertSelfContainedRefs","Error","toJsonSchema","schema","z","renderNode","warnings","undefined","JSON","renderNodeSpec","sortedNodes","NodeRegistry","CoreNodeRegistry","projectIdFromIndex","index","getDefaultExport","loaded","absolutePath","defaultExport","TypeError","isRecord","rejectUnknownKeys","allowedKeys","label","allowed","Set","unknown","isAbsolutePattern","isAbsolute","validatePatterns","field","allowEmptyInclude","validateTestFileSelection","include","exclude","validateTagList","tag","validateTagSelection","assertJsonValue","path","seen","Number","item","deepFreezeJson","validateVariables","validateSetup","validatePositiveInteger","fallback","validateNonNegativeInteger","validateConcurrency","validateFileConcurrency","maxConcurrentFiles","fileSetup","validateExecutionProjects","defaultSetup","defaultFileSetup","globalNodes","test","setup","names","projects","candidate","files","localNodes","globalFileLimit","Math","validateTestOptions","hasExplicitProjects","limit","validateOutputPath","validateOutput","validateTestProjectDefinition","resolvedProjects","assertSupportedConfig","extension","canRetryWithCjsLoader","errorCode","SyntaxError","loadTestProject","configPath","pathToFileURL","tsImport","dirname","sep","tsxRequire","fallbackError","message","createCaseInvocationId","projectId","sourcePath","caseIndex","invocationIndex","createHash","createDocumentInvocationId","normalizeSteps","coreNormalizeSteps","parseWorkflowSource","source","stack","sensitiveNodes","sensitiveValues","redactedPaths","sourceOffset","parsed","load","JSON_SCHEMA","event","state","isReportSecretKey","ranges","offset","redacted","range","text","leading","trailing","sanitizeReportText","interpolationExpression","exactEnvExpression","exactProjectExpression","missingVariable","kind","options","WorkflowParseError","projectVariable","environmentVariable","interpolationValue","String","resolveString","exactEnv","exactProject","_match","environmentName","projectName","resolveWorkflowVariables","isMapping","NativeWorkflowFormatError","actualFormat","allowedSet","createCaseId","createWorkflowDocumentId","collectWorkflowDocument","snapshot","readFileSync","sourceYaml","format","classifyWorkflowDocumentFormat","resolveStepVariables","step","phase","stepIndex","process","normalizeLifecycle","normalized","resolved","lifecycle","ids","cases","tags","steps","caseId","writeJson","mkdir","writeFile","WorkflowPublicationError","writeTestRunPlan","runDir","join","Date","toPosix","caseAttemptResultPath","documentId","result","workflowDocumentResultPath","collectionErrorPath","id","writeWorkflowDocumentResult","_documentRunId","persistedResult","writeCaseAttemptResult","attemptId","writeCollectionError","collectionError","relativeToSummary","summaryPath","target","relative","errorJson","sanitizeReportError","writeTestProjectRunResult","fact","outcome","attempt","document","CONFIG_NAMES","CONFIG_PREFIX","ALWAYS_IGNORED_PATTERNS","DEFAULT_TEST_FILE_SELECTION","discoverResolvedTestFiles","projectRoot","selection","root","match","globSync","file","a","b","relativeA","relativeB","discoverTestConfig","candidates","readdirSync","supported","unsupported","asCollectionError","WorkflowError","matchesTags","filterDocumentCases","filtered","selectProjects","requested","known","prepareProject","defaultTimeoutMs","platform","fileSelection","prerequisiteFile","mainFiles","occurrences","Map","sources","collectionErrors","invocations","plans","filteredCaseCount","collected","plan","buildTestRunReportPlan","projectContext","signal","onTeardown","documents","invocation","prerequisiteSource","prerequisiteDocument","total","padDatePart","createTestRunId","date","uuid","randomUUID","timestamp","assertDirectory","existsSync","statSync","resolveRunInput","cwd","inputPath","singleFile","cliProjectRoot","prepareTestRun","startedAt","runId","input","resultDir","reportDir","mkdirSync","hasFormatMismatch","duration","ms","seconds","href","from","encodeURIComponent","renderTestResultMarkdown","dump","summary","lines","infrastructure","Boolean","groups","errors","recordSteps","group","failure","testCase","diagnostic","emptyIndex","writeTestResultMarkdown","output","buildTestRunReportDump","stepPosition","info","formatStep","position","formatStepResult","indent","symbol","continuation","caseHasFatalError","isFatalDeviceError","isResourceRecoveryError","documentHasFatalError","isSharedResourceFailure","pending","executeDocumentInvocation","sinks","isProjectResourceFailure","documentRetry","attempts","documentSetup","ctx","runDocumentAttempts","documentAttemptIndex","execution","runWorkflowDocument","run","collectedCase","WorkflowExecutionFailure","partial","resourceOnly","host","decideRetry","publicationError","owners","cleanupPending","owner","operationPending","cleanupFailed","failed","decision","final","failedCases","runPreparedFiles","states","prepared","nextProject","resourcesUnresolved","occupied","occupiedProjects","cleanupQueue","release","wake","running","stopped","invalid","unresolved","finishProject","releaseProject","waitForScopeOperations","getResourceCleanupCompletion","admit","cleanupOnly","fileResourcesPending","createProjectRuntime","setMaxListeners","getPendingScopeOperations","changed","job","task","settled","admission","trackResourceOperation","completed","reason","order","createOperationJournal","writeFileSync","appendFileSync","asNotRun","summarize","healthCases","documentAttemptByRunId","latestById","health","calculateTestRunHealth","items","notRunSuite","runPreparedTestProject","preparedProjects","progress","totalDocuments","totalCases","totalErrors","effectiveConcurrency","journal","rootController","AbortController","handleSignal","sigint","sigterm","failedCaseCount","bailReached","shutdownDeadline","beginShutdown","addFailedCases","count","teardownTimeoutMs","hasInfrastructureError","infrastructureErrors","recordInfrastructureError","runInfrastructureCallback","callback","stopObservingOperations","observeResourceOperations","getDebug","announceProject","projectIndex","buildProjectResult","projectFailed","buildSkippedProjectResult","projectResults","completedProjectResults","endedAt","asExecutionError","completedResult","reportIndex","publish","operation","writeSummary","writeReport","reportPath","TestRunReportAssembler","collectTestRunReportSources","warn","publication","markdownPath","runTestProject","parseTestCliArgs","args","command","commandOffset","projectNames","token","equal","arg","inlineValue","defaultCliIO","console","testCliHelp","runNodesCommand","io","configSearchRoot","selectedProjects","filenames","executionProject","safeName","filename","specs","warning","specPath","reportTestProjectResult","reportedErrors","reportError","current","AggregateError","finalCases","finalDocuments","runTestCli","runModelCommand","runCreateCommand","version","exitCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAAA,oBAAoB,CAAC,GAAG,CAACC,SAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGF,oBAAoB,CAAC,CAACE,YAAYC,QAAQ,CAACH,oBAAoB,CAAC,CAACC,SAASE,MACzEC,OAAO,cAAc,CAACH,SAASE,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAH,oBAAoB,CAAC,GAAG,CAAC;IAGzBA,oBAAoB,CAAC,GAAG,CAACK,UACjBC,QAAQ,GAAG,CACjBF,OAAO,IAAI,CAACJ,oBAAoB,CAAC,EAAE,MAAM,CAAC,CAACO,UAAUJ;YACpDH,oBAAoB,CAAC,CAACG,IAAI,CAACE,SAASE;YACpC,OAAOA;QACR,GAAG,EAAE;;;ICPPP,oBAAoB,CAAC,GAAG,CAACK,UAIhB,OAAOA,UAAU;;;ICL1BL,oBAAoB,CAAC,GAAG,CAACQ,KAAKC,OAAUL,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACI,KAAKC;;;ICI5E,IAAIC,kBAAkB;QAAC,KAAO;IAAE;IAChC,IAAIC,eAAe,CAACC;QACtB,IAAIC,mBAAmBD,KAAK,gBAA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