← Files Flows by plugin.spaceARCHIVED FILE

lib/test-scenarios.mjs

17.7 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

// Shared by the viewer, local MCP server and cloud projection. Keep this module browser-safe.
import { filterQualitySuggestions, generateQualitySuggestions } from './quality-suggestions.mjs';
import { flowUserRoles } from './user-roles.mjs';
const text = (value, limit = 1000) => typeof value === 'string' ? value.trim().slice(0, limit) : '';
const unique = values => [...new Set(values)];
const compareId = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
const validId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,100}$/.test(value);
function systemNode(node) {
  const actor = text(node?.actor, 100).toLowerCase();
  // Human roles override technical nouns (e.g. "Application owner"). Only explicit
  // machine labels/suffixes are inferred; an arbitrary mention of "service" is not enough.
  if (/^(ai|automated|autonomous|software|system) agent$/.test(actor)) return true;
  if (/\b(owner|agent|admin|administrator|user|customer|operator|employee|staff|buyer|seller|merchant|manager|developer|engineer|representative)\b/.test(actor)) return false;
  return /(^|\s)(system|application|backend|back-end|server|service|api|automation)$/.test(actor)
    || /^(worker|background|background worker|job worker|queue worker)$/.test(actor)
    || /(^|\s)(payment|email|identity|authentication|auth|sms|storage|cloud|notification) provider$/.test(actor);
}

function stableId(value) {
  let a = 2166136261, b = 5381;
  for (let index = 0; index < value.length; index += 1) {
    const code = value.charCodeAt(index);
    a = Math.imul(a ^ code, 16777619);
    b = Math.imul(b, 33) ^ code;
  }
  return `scenario-${(a >>> 0).toString(16).padStart(8, '0')}${(b >>> 0).toString(16).padStart(8, '0')}`;
}

function reachableFrom(startIds, outgoing, excluded = new Set()) {
  const reached = new Set(), pending = [...startIds];
  while (pending.length) {
    const id = pending.pop();
    if (reached.has(id) || excluded.has(id)) continue;
    reached.add(id);
    for (const edge of outgoing.get(id) ?? []) pending.push(edge.target);
  }
  return reached;
}

function buildCase(document, route, nodeById, outgoing, assignedRoleIds) {
  const steps = [], preconditions = [], warnings = [];
  const routeNodes = route.nodeIds.map(id => nodeById.get(id));
  const routeEdges = route.edges;
  const roleHints = [...routeNodes, ...routeEdges].filter(item => item.test?.userRoleIds !== undefined).map(item => Array.isArray(item.test.userRoleIds) ? item.test.userRoleIds : []);
  // Route restrictions narrow explicit flow membership. Labels, actors and
  // permission names cannot establish the identity of a test participant.
  const userRoleIds = assignedRoleIds.filter(id => roleHints.every(hint => hint.includes(id)));
  if (roleHints.length && !userRoleIds.length) warnings.push('The role assignments on this route have no assigned flow role in common. Review the mappings or model a role handoff explicitly before testing.');
  const add = (kind, prompt, source, references) => {
    if (text(prompt)) steps.push({ kind, prompt: source === 'mapped' ? prompt.slice(0, 1000) : text(prompt), ...references, source });
  };
  const transition = (edge, target, includeTargetAction = true) => {
    const sourceNode = nodeById.get(edge.source);
    const condition = text(edge.condition);
    if (condition) preconditions.push(condition);
    else if (sourceNode?.type === 'decision') preconditions.push(text(`Branch from "${sourceNode.title}": ${edge.label}`));
    if (systemNode(sourceNode)) return;
    const systemTarget = systemNode(target);
    // The target action and its incoming transition normally describe the same interaction.
    if (includeTargetAction && !systemTarget && text(target?.test?.action)) return;
    // A mapped UI action (e.g. Click Pay) can trigger a backend node without
    // turning that backend operation or its generic transition label into a UI action.
    if (text(edge.test?.action)) add('action', edge.test.action, 'mapped', { edgeId: edge.id });
    else if (systemTarget) return;
    else if (includeTargetAction && target?.type === 'action') return;
    else if (!condition && !['decision', 'action'].includes(sourceNode?.type) && text(edge.label)) add('action', edge.label, 'derived', { edgeId: edge.id });
  };
  const nodeSteps = (node, incoming) => {
    if (!systemNode(node)) {
      if (text(node.test?.action)) add('action', node.test.action, 'mapped', { nodeId: node.id });
      else if (node.type === 'action' && !(text(incoming?.test?.action) && !systemNode(nodeById.get(incoming.source)))) add('action', node.title, 'derived', { nodeId: node.id });
    }
    if (text(node.test?.assertion)) add('assertion', node.test.assertion, 'mapped', { nodeId: node.id });
    else if (!systemNode(node) && node.type === 'screen' && text(node.title)) add('assertion', `The "${node.title}" screen is visible.`, 'derived', { nodeId: node.id });
    else if (!systemNode(node) && node.type === 'state' && text(node.title)) add('assertion', `The interface shows: ${node.title}.`, 'derived', { nodeId: node.id });
  };
  for (let index = 0; index < routeNodes.length; index += 1) {
    const incoming = routeEdges[index - 1];
    if (incoming) transition(incoming, routeNodes[index]);
    nodeSteps(routeNodes[index], incoming);
  }
  if (route.termination === 'cycle') {
    const returning = routeEdges.at(-1), target = nodeById.get(returning.target);
    transition(returning, target, false);
    // Confirm the bounded return without executing the target action again.
    if (text(target.test?.assertion)) add('assertion', target.test.assertion, 'mapped', { nodeId: target.id, edgeId: returning.id });
    else if (!systemNode(target) && ['screen', 'state'].includes(target.type)) add('assertion', `The interface returns to: ${target.title}.`, 'derived', { nodeId: target.id, edgeId: returning.id });
    warnings.push('Cycle coverage stops at the first return to an earlier node; repeated iterations and later exits require separate cases.');
  }
  const backgroundStarts = routeNodes.flatMap(node => (outgoing.get(node.id) ?? []).filter(edge => edge.parallel === true).map(edge => edge.target));
  // Background lanes may contain alternative outcomes and different timing. Keep them
  // review-only rather than asserting all descendants against the same interface.
  if (backgroundStarts.length) warnings.push('Parallel background work is review-only and its transitions remain uncovered. Implement its conditions, timing and assertions with custom test Nodes.');
  if (routeNodes.some(systemNode)) warnings.push('System actions are not executed as UI actions. Prepare or verify these effects with custom test Nodes.');
  if (steps.some(step => step.source === 'derived')) warnings.push('Some prompts were derived from labels. Review actions and observable assertions before running this draft.');
  if (routeNodes.some(node => node.source?.kind !== 'observed')) warnings.push('This path contains proposed, inferred, or unspecified evidence; confirm it against the application.');
  if (preconditions.length) warnings.push('Branch conditions are prerequisites, not executable setup. Prepare data and state that satisfy them before running.');
  if (!steps.some(step => step.kind === 'assertion')) warnings.push('No observable assertion is mapped for this path. It is omitted from executable Midscene YAML until an assertion is supplied.');
  const branches = routeEdges.filter(edge => (outgoing.get(edge.source) ?? []).filter(candidate => candidate.parallel !== true).length > 1).map(edge => text(edge.label, 100));
  const suffix = branches.length ? branches.join(' / ') : text(routeNodes.at(-1)?.title, 100);
  return {
    id: stableId(JSON.stringify([document?.id ?? '', route.nodeIds, routeEdges.map(edge => edge.id), route.termination])),
    name: text(`${text(document?.name, 200) || 'Flow'}${suffix ? ` — ${suffix}` : ''}`, 200),
    status: 'draft',
    userRoleIds,
    nodeIds: [...route.nodeIds],
    edgeIds: routeEdges.map(edge => edge.id),
    preconditions: unique(preconditions),
    warnings,
    steps,
    termination: route.termination,
  };
}

// Enumerate each mapped combination of decisions, including a cycle's returning
// edge. An explicit stack avoids a call-stack limit on long paths. A node can
// appear only once in the active path, so cycles finish without an arbitrary
// iteration, depth or scenario count limit. Backtracking keeps alternatives.
function* mappedRoutes(start, outgoing) {
  const foreground = new Map([...outgoing].map(([id, edges]) => [id, edges.filter(edge => edge.parallel !== true)]));
  const nodeIds = [start], edges = [], visited = new Set(nodeIds);
  const stack = [{ id: start, next: 0 }];
  while (stack.length) {
    const frame = stack.at(-1), options = foreground.get(frame.id) ?? [];
    if (!options.length) yield { nodeIds: [...nodeIds], edges: [...edges], termination: 'terminal' };
    if (frame.next >= options.length) {
      stack.pop();
      visited.delete(nodeIds.pop());
      if (edges.length) edges.pop();
      continue;
    }
    const edge = options[frame.next++];
    if (visited.has(edge.target)) {
      yield { nodeIds: [...nodeIds], edges: [...edges, edge], termination: 'cycle' };
      continue;
    }
    edges.push(edge);
    nodeIds.push(edge.target);
    visited.add(edge.target);
    stack.push({ id: edge.target, next: 0 });
  }
}

/** Derive all finite mapped routes as deterministic drafts, never from a cached suite. */
export function generateTestScenarios(document) {
  const userRoles = flowUserRoles(document).sort(compareId);
  const assignedRoleIds = userRoles.map(role => role.id);
  const inputNodes = Array.isArray(document?.nodes) ? document.nodes : [];
  const inputEdges = Array.isArray(document?.edges) ? document.edges : [];
  const nodeIds = new Set(), edgeIds = new Set();
  const nodes = inputNodes.filter(node => {
    if (!validId(node?.id) || nodeIds.has(node.id)) return false;
    nodeIds.add(node.id);
    return true;
  }).sort(compareId);
  const nodeById = new Map(nodes.map(node => [node.id, node]));
  const edges = inputEdges.filter(edge => {
    if (!validId(edge?.id) || edgeIds.has(edge.id) || !nodeById.has(edge.source) || !nodeById.has(edge.target)) return false;
    edgeIds.add(edge.id);
    return true;
  }).sort(compareId);
  const outgoing = new Map(nodes.map(node => [node.id, []]));
  for (const edge of edges) outgoing.get(edge.source).push(edge);
  const truncated = nodes.length !== inputNodes.length || edges.length !== inputEdges.length;
  const hasStart = nodeById.has(document?.startNode);
  const cases = [], included = new Set();
  if (hasStart) for (const route of mappedRoutes(document.startNode, outgoing)) {
    cases.push(buildCase(document, route, nodeById, outgoing, assignedRoleIds));
    for (const edge of route.edges) included.add(edge.id);
  }
  const reached = hasStart ? reachableFrom([document.startNode], outgoing) : new Set();
  const suite = {
    version: 1,
    source: 'flow-map',
    userRoles,
    cases,
    warnings: ['Generated scenarios are unexecuted drafts. Coverage describes included mapped routes, not verified behavior.'],
    coverage: {
      coveredEdgeIds: edges.filter(edge => included.has(edge.id)).map(edge => edge.id),
      uncoveredEdgeIds: edges.filter(edge => !included.has(edge.id)).map(edge => edge.id),
      unreachableNodeIds: nodes.filter(node => !reached.has(node.id)).map(node => node.id),
      truncated,
    },
  };
  suite.warnings.push(userRoles.length ? 'Role links identify the explicitly assigned flow participants, not verified permissions. Prepare the appropriate account and data for each relevant role; authentication and role switching are not generated.' : 'No user roles are assigned to this flow. Its scenarios remain unclassified until roles are explicitly assigned.');
  if (!hasStart) suite.warnings.push('No valid start node is available; map a starting point before generating cases.');
  if (suite.cases.some(scenario => scenario.termination === 'cycle')) suite.warnings.push('Cycles are bounded at their first return; iteration coverage is incomplete.');
  if (suite.coverage.unreachableNodeIds.length) suite.warnings.push('Some nodes are unreachable from the mapped starting point and are not included in cases.');
  if (truncated) suite.warnings.push('Some invalid or duplicate graph entries were excluded. Fix the mapped source to include them.');
  if (suite.coverage.uncoveredEdgeIds.length) suite.warnings.push('Some transitions are not included in generated cases; inspect uncoveredEdgeIds for missing routes and background work.');
  suite.quality = generateQualitySuggestions(document, cases);
  return suite;
}

export function withTestScenarios(document) {
  return { ...document, testScenarios: generateTestScenarios(document) };
}

/** Filter drafts without implying that excluded routes have been covered. */
export function filterTestScenarios(suite, userRoleId) {
  if (userRoleId === undefined) return suite;
  const role = (suite.userRoles ?? []).find(candidate => candidate.id === userRoleId);
  if (userRoleId !== null && !role) throw new Error('Choose a user role assigned to this flow.');
  const cases = suite.cases.filter(scenario => userRoleId === null ? !(scenario.userRoleIds?.length) : scenario.userRoleIds?.includes(userRoleId));
  const covered = new Set(cases.flatMap(scenario => scenario.edgeIds));
  const edges = unique([...suite.coverage.coveredEdgeIds, ...suite.coverage.uncoveredEdgeIds]).sort();
  const warning = `Filtered to ${role ? `user role ${role.name} (${role.id})` : 'unclassified scenarios'}; coverage describes only the included scenarios. Transitions absent from these scenarios remain uncovered.`;
  const quality = suite.quality ? filterQualitySuggestions(suite.quality, userRoleId, suite.cases) : undefined;
  return { ...suite, cases, warnings: [...suite.warnings, warning], coverage: { ...suite.coverage, coveredEdgeIds: edges.filter(id => covered.has(id)), uncoveredEdgeIds: edges.filter(id => !covered.has(id)) }, ...(quality ? { quality } : {}) };
}

function startUrlValue(value) {
  if (value === undefined) return '${{FLOWS_TEST_URL}}';
  if (typeof value !== 'string' || !value.trim() || value.length > 2000 || value.includes('${')) throw new Error('Provide an HTTP(S) test URL without interpolation markers.');
  let parsed;
  try { parsed = new URL(value); } catch { throw new Error('Provide a valid HTTP(S) test URL.'); }
  if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) throw new Error('Provide an HTTP(S) test URL without embedded credentials.');
  return parsed.href;
}

// YAML quoting cannot disable Midscene interpolation: neutralize markers in all mapped text.
const literalText = value => String(value).replace(/\$\{/g, '${');
const yamlString = value => JSON.stringify(String(value)).replace(/\u0085/g, '\\u0085').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
const comment = value => String(value).split(/[\r\n\u0085\u2028\u2029]/).map(line => `# ${line}`).join('\n');

/** Native @midscene/test cases/steps, for use inside a configured Web test project. */
export function exportMidsceneYaml(document, options = {}) {
  const url = startUrlValue(options.startUrl);
  const suite = filterTestScenarios(generateTestScenarios(document), options.userRoleId);
  if (options.userRoleId !== undefined && !suite.cases.length) throw new Error('No scenarios match the selected user role. Choose another role or include all scenarios before exporting Midscene YAML.');
  const runnable = [], omittedCases = [];
  for (const scenario of suite.cases) (scenario.steps.some(step => step.kind === 'assertion') ? runnable : omittedCases).push(scenario);
  if (!runnable.length) throw new Error('No scenarios have an observable assertion. Add a screen/state or an explicit node.test.assertion before exporting Midscene YAML.');
  const lines = [
    '# Midscene Test (@midscene/test) — generated, unexecuted drafts',
    '# Review prerequisites, test data, derived prompts and assertions before running.',
    '# Configure a Web project with registered Midscene Nodes; run: pnpm exec midscene-test ./cases/flow.yaml',
    '# Documentation: https://midscenejs.com/midscene-test/use',
    '# Mapped interpolation markers use a full-width dollar sign to prevent environment substitution.',
    `# Exported cases: ${runnable.length}; omitted without assertions: ${omittedCases.length}. JSON coverage includes omitted drafts.`,
    ...suite.warnings.map(comment),
  ];
  if (options.startUrl === undefined) lines.push('# Set FLOWS_TEST_URL to the test environment URL before running.');
  for (const scenario of omittedCases) lines.push(comment(`Omitted: ${scenario.id} — ${scenario.name}; no observable assertion.`));
  lines.push('cases:');
  for (const scenario of runnable) {
    lines.push(`  ${comment(`Draft ${scenario.id}`).replace(/\n/g, '\n  ')}`);
    const roles = suite.userRoles.filter(role => scenario.userRoleIds.includes(role.id));
    lines.push(`  ${comment(`User roles: ${roles.length ? roles.map(role => `${role.name} (${role.id})`).join(', ') : 'Unclassified'}`).replace(/\n/g, '\n  ')}`);
    for (const value of scenario.preconditions) lines.push(`  ${comment(`Precondition: ${value}`).replace(/\n/g, '\n  ')}`);
    for (const value of scenario.warnings) lines.push(`  ${comment(`Review: ${value}`).replace(/\n/g, '\n  ')}`);
    lines.push(`  - name: ${yamlString(literalText(scenario.name))}`, '    steps:', `      - gotoUrl: ${yamlString(url)}`);
    for (const step of scenario.steps) {
      lines.push(`      ${comment(`${step.source}; ${step.nodeId ? `node ${step.nodeId}` : ''}${step.edgeId ? ` edge ${step.edgeId}` : ''}`)}`);
      lines.push(`      - ${step.kind === 'action' ? 'aiAct' : 'aiAssert'}: ${yamlString(literalText(step.prompt))}`);
    }
  }
  return `${lines.join('\n')}\n`;
}

export function exportTestScenariosJson(document, options = {}) {
  return `${JSON.stringify(filterTestScenarios(generateTestScenarios(document), options.userRoleId))}\n`;
}

SHA-256: c65490dfd92907be24b8c1783ea6a0635794076b604d1fa93edf65623bd35135