import { z } from 'zod/v4'; import type { NodeDefinition } from '../node/types'; import type { TestFileSelection } from './test-project'; export interface NodeSpecDocument { markdown: string; warnings: readonly string[]; } const GENERATED_COMMENT = ''; export const sortNodesForSpec = ( nodes: readonly NodeDefinition[], ): NodeDefinition[] => { const priority = (name: string) => name === 'aiAct' ? 0 : name === 'aiAssert' ? 1 : 2; return [...nodes].sort( (left, right) => priority(left.name) - priority(right.name) || (left.name < right.name ? -1 : left.name > right.name ? 1 : 0), ); }; const escapeTableCell = (value: string): string => value .trim() .replace(/\\/g, '\\\\') .replace(/\|/g, '\\|') .replace(/\r\n|\r|\n/g, '
'); const renderNodeOverview = ( nodes: readonly NodeDefinition[], ): string => { const heading = '## Available Nodes'; if (nodes.length === 0) { return `${heading}\n\nNo nodes are registered by the current Test Project.`; } const rows = nodes.map( (node) => `| ${escapeTableCell(node.name)} | ${escapeTableCell(node.description || 'Description not declared.')} |`, ); 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')}`; }; interface NodeSpecLocation { configPath?: string; projects: readonly { name: string; files: TestFileSelection }[]; } const renderWorkflowLocations = (location?: NodeSpecLocation): string => { const sections = [ '## Where to use these Nodes', '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.', '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.', ]; if (location) { sections.push( `**Config file:** ${location.configPath ? `\`${location.configPath}\`` : 'No config file loaded.'}`, ); for (const project of location.projects) { const patterns = project.files.include .map((pattern) => `\`${pattern}\``) .join(', '); const projectLabel = location.projects.length > 1 || project.name !== 'default' ? ` (Execution Project: ${project.name})` : ''; const excludes = project.files.exclude?.length ? `; excludes: ${project.files.exclude.map((pattern) => `\`${pattern}\``).join(', ')}` : ''; sections.push(`**Case files:** ${patterns}${projectLabel}${excludes}`); } } sections.push( 'Files matching `files.exclude` are not selected. Midscene Test always ignores `.git/`, `.midscene/`, `midscene_run/`, and `node_modules/` directories, including nested ones.', '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.', ); return sections.join('\n\n'); }; const WORKFLOW_STEP_CONTRACT = `## Workflow Step Contract Each step uses a node name as its key. The \`$\` object contains engine metadata and is not part of the node input. \`\`\`yaml cases: - name: Example case steps: - node.name: prompt: Describe the task. $: timeout: 30000 continue-on-error: false \`\`\` A 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. Each 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.`; const sortJsonValue = (value: unknown): unknown => { if (Array.isArray(value)) return value.map(sortJsonValue); if (typeof value !== 'object' || value === null) return value; return Object.fromEntries( Object.entries(value) .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) .map(([key, child]) => [key, sortJsonValue(child)]), ); }; const assertSelfContainedRefs = (value: unknown, node: string): void => { if (Array.isArray(value)) { for (const child of value) assertSelfContainedRefs(child, node); return; } if (typeof value !== 'object' || value === null) return; for (const [key, child] of Object.entries(value)) { if (key === '$ref' && typeof child === 'string' && !child.startsWith('#')) { throw new Error( `Cannot describe node "${node}": inputSchema generated an external $ref.`, ); } assertSelfContainedRefs(child, node); } }; const toJsonSchema = (node: NodeDefinition): unknown => { try { const schema = z.toJSONSchema(node.inputSchema!, { target: 'draft-2020-12', io: 'input', unrepresentable: 'throw', cycles: 'ref', reused: 'ref', }); assertSelfContainedRefs(schema, node.name); return sortJsonValue(schema); } catch (error) { if ( error instanceof Error && error.message.startsWith(`Cannot describe node "${node.name}":`) ) { throw error; } throw new Error( `Cannot describe node "${node.name}": inputSchema contains a Zod type that cannot be represented as JSON Schema.`, { cause: error }, ); } }; const renderNode = ( node: NodeDefinition, warnings: string[], ): string => { const sections = [`### \`${node.name}\``]; if (node.title) sections.push(`**Title:** ${node.title.trim()}`); if (node.description) { sections.push(node.description.trim()); } else { warnings.push(`node "${node.name}" has no description`); sections.push( `> Description not declared. Do not infer this node's behavior.`, ); } if (node.stringInputKey === false || node.stringInputKey === undefined) { sections.push('**String shorthand:** Not supported by this Node.'); } else { sections.push( `**String shorthand:** Maps to \`{ ${node.stringInputKey}: value }\`.`, ); } sections.push('#### Input Schema'); if (node.inputSchema) { sections.push( `\`\`\`json\n${JSON.stringify(toJsonSchema(node), null, 2)}\n\`\`\``, ); } else { warnings.push(`node "${node.name}" has no inputSchema`); sections.push( '> Input schema not declared. Do not invent input fields for this node.', ); } return sections.join('\n\n'); }; export const renderNodeSpec = ( nodes: readonly NodeDefinition[], location?: NodeSpecLocation, ): NodeSpecDocument => { const warnings: string[] = []; const sortedNodes = sortNodesForSpec(nodes); const sections = [ GENERATED_COMMENT, '# Midscene Test Node Spec', '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.', [ 'Learn about the framework and YAML test authoring:', '', '- [Midscene Test overview](https://www.midscenejs.com/midscene-test/overview): framework concepts and the role of Nodes.', '- [Create and use test projects](https://www.midscenejs.com/midscene-test/use): write YAML cases, run tests, and inspect results.', '- [Configure test projects](https://www.midscenejs.com/midscene-test/configuration): register Nodes, select case files, and manage runtime resources.', ].join('\n'), renderNodeOverview(sortedNodes), renderWorkflowLocations(location), WORKFLOW_STEP_CONTRACT, ]; if (sortedNodes.length > 0) { sections.push('## Node Details'); for (const node of sortedNodes) sections.push(renderNode(node, warnings)); } return { markdown: `${sections.join('\n\n')}\n`, warnings, }; };