@midscene/test 1.17.8-beta-20261106101231.0 → 1.17.8

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.
Files changed (51) hide show
  1. package/dist/es/154.mjs +2 -0
  2. package/dist/es/164.mjs +1469 -0
  3. package/dist/es/164.mjs.map +1 -0
  4. package/dist/es/183.mjs +295 -0
  5. package/dist/es/183.mjs.map +1 -0
  6. package/dist/es/1~112.mjs +372 -0
  7. package/dist/es/1~112.mjs.map +1 -0
  8. package/dist/es/209.mjs +1 -0
  9. package/dist/es/299.mjs +1886 -0
  10. package/dist/es/299.mjs.map +1 -0
  11. package/dist/es/398.mjs +5 -0
  12. package/dist/es/398.mjs.map +1 -0
  13. package/dist/es/431.mjs +375 -0
  14. package/dist/es/431.mjs.map +1 -0
  15. package/dist/es/470.mjs +1 -0
  16. package/dist/es/487.mjs +1 -0
  17. package/dist/es/629.mjs +1 -0
  18. package/dist/es/793.mjs +1 -0
  19. package/dist/es/822.mjs +1 -0
  20. package/dist/es/946.mjs +1 -0
  21. package/dist/es/cli/index.mjs +3 -2196
  22. package/dist/es/cli/index.mjs.map +1 -1
  23. package/dist/es/cli/model-command.mjs +1 -296
  24. package/dist/es/index.mjs +10 -409
  25. package/dist/es/index.mjs.map +1 -1
  26. package/dist/es/midscene/index.mjs +9 -9
  27. package/dist/es/midscene/index.mjs.map +1 -1
  28. package/dist/es/runtime/index.mjs +4 -5
  29. package/dist/es/runtime/index.mjs.map +1 -1
  30. package/dist/es/test-cli.mjs +1 -3786
  31. package/dist/lib/0~703.js.map +1 -1
  32. package/dist/lib/cli/index.js +45 -58
  33. package/dist/lib/cli/index.js.map +1 -1
  34. package/dist/lib/cli/model-command.js +1 -1
  35. package/dist/lib/cli/model-command.js.map +1 -1
  36. package/dist/lib/index.js +8 -37
  37. package/dist/lib/index.js.map +1 -1
  38. package/dist/lib/midscene/index.js +1 -1
  39. package/dist/lib/midscene/index.js.map +1 -1
  40. package/dist/lib/runtime/index.js +1 -1
  41. package/dist/lib/runtime/index.js.map +1 -1
  42. package/dist/lib/test-cli.js +884 -877
  43. package/dist/lib/test-cli.js.map +1 -1
  44. package/dist/types/cli/index.d.ts +4 -0
  45. package/package.json +20 -21
  46. package/dist/es/1~4.mjs +0 -383
  47. package/dist/es/1~4.mjs.map +0 -1
  48. package/dist/es/1~731.mjs +0 -306
  49. package/dist/es/1~731.mjs.map +0 -1
  50. package/dist/es/cli/model-command.mjs.map +0 -1
  51. package/dist/es/test-cli.mjs.map +0 -1
@@ -28,7 +28,9 @@ var __webpack_modules__ = {
28
28
  module.exports = require("yargs/yargs");
29
29
  },
30
30
  "./package.json" (module) {
31
- module.exports = JSON.parse('{"rE":"1.17.8-beta-20261106101231.0"}');
31
+ module.exports = {
32
+ rE: "1.17.8"
33
+ };
32
34
  }
33
35
  };
34
36
  var __webpack_module_cache__ = {};
@@ -137,6 +139,15 @@ var __webpack_exports__ = {};
137
139
  const text = oneLine(value);
138
140
  return text.length <= length ? text : `${text.slice(0, length - 1)}…`;
139
141
  };
142
+ function unwrapFrameLocation(location) {
143
+ if (!location.endsWith(')')) return location;
144
+ const absoluteStart = location.search(/ \((?:file:\/\/|[A-Za-z]:[\\/]|\/|\\\\)/);
145
+ if (-1 !== absoluteStart) return location.slice(absoluteStart + 2, -1);
146
+ let depth = 0;
147
+ for(let index = location.length - 1; index >= 0; index--)if (')' === location[index]) depth++;
148
+ else if ('(' === location[index] && 0 === --depth) return ' ' === location[index - 1] ? location.slice(index + 1, -1) : location;
149
+ return location;
150
+ }
140
151
  function firstBusinessFrame(error, projectRoot) {
141
152
  const seen = new Set();
142
153
  const frames = [];
@@ -149,8 +160,7 @@ var __webpack_exports__ = {};
149
160
  if ('string' != typeof detail.stack) return;
150
161
  for (const line of detail.stack.split('\n')){
151
162
  if (!line.trim().startsWith('at ')) continue;
152
- let location = line.trim().slice(3).replace(/^async /, '');
153
- if (location.endsWith(')')) location = location.slice(location.lastIndexOf('(') + 1, -1);
163
+ const location = unwrapFrameLocation(line.trim().slice(3).replace(/^async /, ''));
154
164
  const match = location.match(/^(.*):(\d+):(\d+)$/);
155
165
  if (!match) continue;
156
166
  let file = match[1];
@@ -178,17 +188,15 @@ var __webpack_exports__ = {};
178
188
  function formatFailureInput(input) {
179
189
  if (void 0 === input) return [];
180
190
  const value = (0, test_runner_namespaceObject.sanitizeReportValue)(input).value;
181
- const render = (value)=>shorten((0, test_runner_namespaceObject.sanitizeReportError)({
182
- message: 'string' == typeof value ? value : (0, external_node_util_namespaceObject.inspect)(value, {
183
- colors: false,
184
- depth: 2,
185
- maxArrayLength: 4,
186
- maxStringLength: 180,
187
- breakLength: 1 / 0,
188
- customInspect: false,
189
- getters: false
190
- })
191
- }).message, 160);
191
+ const render = (value)=>shorten('string' == typeof value ? value : (0, external_node_util_namespaceObject.inspect)(value, {
192
+ colors: false,
193
+ depth: 2,
194
+ maxArrayLength: 4,
195
+ maxStringLength: 180,
196
+ breakLength: 1 / 0,
197
+ customInspect: false,
198
+ getters: false
199
+ }), 160);
192
200
  if (value && 'object' == typeof value && !Array.isArray(value)) {
193
201
  const entries = Object.entries(value);
194
202
  const rows = entries.slice(0, 4).map(([key, value])=>`${shorten(key, 48)}: ${render(value)}`);
@@ -225,10 +233,7 @@ var __webpack_exports__ = {};
225
233
  ]
226
234
  ])if (attempt && (attempt.total > 1 || attempt.index > 0)) field(label, `${attempt.index + 1}/${attempt.total}`);
227
235
  if (body.length) body.push('');
228
- const safeMessage = (0, test_runner_namespaceObject.sanitizeReportError)({
229
- message: formatConciseError(error)
230
- }).message;
231
- const lines = (0, external_node_util_namespaceObject.stripVTControlCharacters)(safeMessage).split(/\r?\n/);
236
+ const lines = (0, external_node_util_namespaceObject.stripVTControlCharacters)(formatConciseError(error)).split(/\r?\n/);
232
237
  body.push(` Error: ${shorten(lines[0], 320)}`, ...lines.slice(1, 6).map((line)=>` ${shorten(line, 320)}`));
233
238
  if (lines.length > 6) body.push(' … (use --reporter verbose for details)');
234
239
  const input = step ? formatFailureInput(step.input) : [];
@@ -1077,6 +1082,13 @@ var __webpack_exports__ = {};
1077
1082
  '\r': ' ',
1078
1083
  '\n': ' '
1079
1084
  })[char]);
1085
+ const code = (text)=>{
1086
+ const value = text.replace(/[\r\n]+/g, ' ');
1087
+ const longest = Math.max(0, ...(value.match(/`+/g) ?? []).map((run)=>run.length));
1088
+ const fence = '`'.repeat(longest + 1);
1089
+ const pad = value.startsWith('`') || value.endsWith('`') ? ' ' : '';
1090
+ return `${fence}${pad}${value}${pad}${fence}`;
1091
+ };
1080
1092
  function githubFailureAnnotation(source, message, file) {
1081
1093
  if ('true' !== process.env.GITHUB_ACTIONS) return;
1082
1094
  const workspace = process.env.GITHUB_WORKSPACE ?? process.cwd();
@@ -1102,7 +1114,7 @@ var __webpack_exports__ = {};
1102
1114
  '',
1103
1115
  'Passed after retry is included in Passed.',
1104
1116
  '',
1105
- ...failedCases.map((item)=>`- Failed: **${markdown(item.name)}** — ${markdown(item.projectName)}/\`${markdown(item.sourcePath)}\``),
1117
+ ...failedCases.map((item)=>`- Failed: **${markdown(item.name)}** — ${markdown(item.projectName)}/${code(item.sourcePath)}`),
1106
1118
  ...result.summary.collectionErrors ? [
1107
1119
  `- Collection errors: ${result.summary.collectionErrors}`
1108
1120
  ] : [],
@@ -1114,9 +1126,9 @@ var __webpack_exports__ = {};
1114
1126
  ] : [],
1115
1127
  '',
1116
1128
  ...result.reportPath ? [
1117
- `Report artifact entry: \`${markdown(result.reportPath)}\``
1129
+ `Report artifact entry: ${code(result.reportPath)}`
1118
1130
  ] : [],
1119
- `Structured results: \`${markdown(result.summaryPath)}\``,
1131
+ `Structured results: ${code(result.summaryPath)}`,
1120
1132
  ''
1121
1133
  ].join('\n');
1122
1134
  (0, external_node_fs_.appendFileSync)(output, `${summary}\n`);
@@ -1255,716 +1267,340 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
1255
1267
  warnings
1256
1268
  };
1257
1269
  };
1258
- function captureTerminalOutput(output, streams = [
1259
- process.stdout,
1260
- process.stderr
1261
- ]) {
1262
- const cleanups = [];
1263
- for (const stream of streams){
1264
- const original = stream.write;
1265
- const forward = original.bind(stream);
1266
- const intercepted = (chunk, encoding, callback)=>{
1267
- const done = 'function' == typeof encoding ? encoding : callback;
1268
- const message = 'string' == typeof chunk ? chunk : Buffer.from(chunk).toString();
1269
- let accepted = true;
1270
- output(message, (text)=>{
1271
- accepted = forward(text, done);
1270
+ const external_node_crypto_namespaceObject = require("node:crypto");
1271
+ const common_namespaceObject = require("@midscene/shared/common");
1272
+ const createCaseInvocationId = (projectId, sourcePath, caseIndex, invocationIndex = 0)=>(0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify([
1273
+ projectId,
1274
+ sourcePath,
1275
+ caseIndex,
1276
+ ...invocationIndex ? [
1277
+ invocationIndex
1278
+ ] : []
1279
+ ])).digest('hex');
1280
+ const createDocumentInvocationId = (projectId, sourcePath, invocationIndex = 0)=>(0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify([
1281
+ projectId,
1282
+ sourcePath,
1283
+ ...invocationIndex ? [
1284
+ invocationIndex
1285
+ ] : []
1286
+ ])).digest('hex');
1287
+ const normalizeSteps = test_runner_namespaceObject.normalizeSteps;
1288
+ const external_js_yaml_namespaceObject = require("js-yaml");
1289
+ function parseWorkflowSource(source) {
1290
+ const stack = [];
1291
+ let root;
1292
+ const sourceOffset = 0xfeff === source.charCodeAt(0) ? 1 : 0;
1293
+ const parsed = (0, external_js_yaml_namespaceObject.load)(source, {
1294
+ schema: external_js_yaml_namespaceObject.JSON_SCHEMA,
1295
+ listener (event, state) {
1296
+ if ('open' === event) return void stack.push({
1297
+ start: state.position + sourceOffset,
1298
+ end: 0,
1299
+ value: null,
1300
+ children: [],
1301
+ kind: null
1272
1302
  });
1273
- return accepted;
1274
- };
1275
- stream.write = intercepted;
1276
- cleanups.push(()=>{
1277
- if (stream.write === intercepted) stream.write = original;
1278
- });
1279
- }
1280
- return ()=>{
1281
- for (const cleanup of cleanups)cleanup();
1303
+ const node = stack.pop();
1304
+ node.end = state.position + sourceOffset;
1305
+ node.value = state.result;
1306
+ node.kind = state.kind;
1307
+ const parent = stack.at(-1);
1308
+ if (parent) parent.children.push(node);
1309
+ else root = node;
1310
+ }
1311
+ });
1312
+ const value = (0, test_runner_namespaceObject.sanitizeReportText)(source, 65536);
1313
+ return {
1314
+ parsed,
1315
+ locate (path) {
1316
+ let node = root;
1317
+ for (const part of path){
1318
+ if (!node) return;
1319
+ while(1 === node.children.length && node.children[0].value === node.value)node = node.children[0];
1320
+ if ('number' == typeof part && 'sequence' === node.kind) node = node.children[part];
1321
+ else {
1322
+ if ('string' != typeof part || 'mapping' !== node.kind) return;
1323
+ const children = node.children;
1324
+ node = void 0;
1325
+ for(let index = 0; index < children.length; index += 2)if (children[index].value === part) {
1326
+ node = children[index + 1];
1327
+ break;
1328
+ }
1329
+ }
1330
+ }
1331
+ if (!node) return;
1332
+ let start = node.start;
1333
+ while(start < node.end)if (/\s/.test(source[start])) start++;
1334
+ else if ('#' === source[start]) {
1335
+ const end = source.indexOf('\n', start);
1336
+ if (end < 0) return;
1337
+ start = end + 1;
1338
+ } else break;
1339
+ const prefix = source.slice(0, start).split(/\r\n|\r|\n/);
1340
+ return {
1341
+ line: prefix.length,
1342
+ column: prefix.at(-1).length + 1
1343
+ };
1344
+ },
1345
+ sourceYaml: {
1346
+ value,
1347
+ ...value !== source ? {
1348
+ truncatedPaths: [
1349
+ '$'
1350
+ ]
1351
+ } : {}
1352
+ }
1282
1353
  };
1283
1354
  }
1284
- const api_namespaceObject = require("tsx/cjs/api");
1285
- const NodeRegistry = test_runner_namespaceObject.NodeRegistry;
1286
- const projectIdFromIndex = (index)=>`project-${index}`;
1287
- const getDefaultExport = (loaded, absolutePath)=>{
1288
- if ('object' == typeof loaded && null !== loaded && 'default' in loaded) {
1289
- const defaultExport = loaded.default;
1290
- if ('object' == typeof defaultExport && null !== defaultExport && '__esModule' in defaultExport) {
1291
- if ('default' in defaultExport) return defaultExport.default;
1292
- throw new TypeError(`Midscene config "${absolutePath}" must have a default export.`);
1293
- }
1294
- return defaultExport;
1295
- }
1296
- throw new TypeError(`Midscene config "${absolutePath}" must have a default export.`);
1355
+ const interpolationExpression = /\$\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}|\$\{([^{}]+)\}/g;
1356
+ const exactEnvExpression = /^\$\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}$/;
1357
+ const exactProjectExpression = /^\$\{([^{}]+)\}$/;
1358
+ const missingVariable = (kind, name, options)=>{
1359
+ throw new test_runner_namespaceObject.WorkflowParseError(`Undefined ${kind} variable "${name}" in ${options.location.sourcePath}.`, {
1360
+ ...options.location,
1361
+ variable: name,
1362
+ variableKind: kind
1363
+ });
1297
1364
  };
1298
- const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
1299
- const rejectUnknownKeys = (value, allowedKeys, label)=>{
1300
- const allowed = new Set(allowedKeys);
1301
- const unknown = Object.keys(value).find((key)=>!allowed.has(key));
1302
- if (unknown) throw new TypeError(`Midscene config ${label}.${unknown} is not supported.`);
1365
+ const projectVariable = (name, options)=>{
1366
+ if (!Object.hasOwn(options.variables ?? {}, name)) return missingVariable('project', name, options);
1367
+ return options.variables[name];
1303
1368
  };
1304
- const isAbsolutePattern = (pattern)=>(0, external_node_path_.isAbsolute)(pattern) || /^[A-Za-z]:[\\/]/.test(pattern) || pattern.startsWith('\\\\');
1305
- const validatePatterns = (value, field, label = 'files', allowEmptyInclude = false)=>{
1306
- if (!Array.isArray(value)) throw new TypeError(`Midscene config ${label}.${field} must be an array.`);
1307
- if ('include' === field && 0 === value.length && !allowEmptyInclude) throw new TypeError(`Midscene config ${label}.include must be a non-empty array.`);
1308
- return value.map((pattern, index)=>{
1309
- if ('string' != typeof pattern || 0 === pattern.trim().length) throw new TypeError(`Midscene config ${label}.${field}[${index}] must be a non-empty string.`);
1310
- if (isAbsolutePattern(pattern)) throw new TypeError(`Midscene config ${label}.${field}[${index}] must be relative to the project root.`);
1311
- if (pattern.split(/[\\/]/).includes('..')) throw new TypeError(`Midscene config ${label}.${field}[${index}] must not contain a ".." path segment.`);
1312
- if (pattern.includes('\\')) throw new TypeError(`Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`);
1313
- if (pattern.startsWith('!')) {
1314
- if ('include' === field) throw new TypeError(`Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`);
1315
- throw new TypeError(`Midscene config ${label}.exclude[${index}] must not be a negated pattern.`);
1316
- }
1317
- return pattern;
1318
- });
1369
+ const environmentVariable = (name, options)=>{
1370
+ const value = options.env?.[name];
1371
+ if (void 0 === value) return missingVariable('environment', name, options);
1372
+ return value;
1319
1373
  };
1320
- const test_project_validateTestFileSelection = (value, label = 'files')=>{
1321
- if (void 0 === value) return;
1322
- if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
1323
- rejectUnknownKeys(value, [
1324
- 'include',
1325
- 'exclude'
1326
- ], label);
1327
- const include = validatePatterns(value.include, 'include', label);
1328
- const exclude = void 0 === value.exclude ? void 0 : validatePatterns(value.exclude, 'exclude', label);
1329
- return Object.freeze({
1330
- include: Object.freeze(include),
1331
- ...exclude ? {
1332
- exclude: Object.freeze(exclude)
1333
- } : {}
1374
+ const interpolationValue = (name, value, options)=>{
1375
+ if ('object' == typeof value && null !== value) throw new test_runner_namespaceObject.WorkflowParseError(`Project variable "${name}" must be a primitive when embedded in a string.`, {
1376
+ ...options.location,
1377
+ variable: name,
1378
+ variableKind: 'project'
1334
1379
  });
1380
+ return String(value);
1335
1381
  };
1336
- const validateTagList = (value, field, label)=>{
1337
- if (void 0 === value) return [];
1338
- if (!Array.isArray(value)) throw new TypeError(`Midscene config ${label}.${field} must be an array.`);
1339
- return value.map((tag, index)=>{
1340
- if ('string' != typeof tag || 0 === tag.trim().length) throw new TypeError(`Midscene config ${label}.${field}[${index}] must be a non-empty string.`);
1341
- return tag;
1342
- });
1382
+ const resolveString = (value, options)=>{
1383
+ const exactEnv = exactEnvExpression.exec(value);
1384
+ if (exactEnv) return environmentVariable(exactEnv[1], options);
1385
+ const exactProject = exactProjectExpression.exec(value);
1386
+ if (exactProject) return projectVariable(exactProject[1], options);
1387
+ return value.replace(interpolationExpression, (_match, environmentName, projectName)=>environmentName ? environmentVariable(environmentName, options) : interpolationValue(projectName, projectVariable(projectName, options), options));
1343
1388
  };
1344
- const validateTagSelection = (value, label)=>{
1345
- if (void 0 === value) return Object.freeze({
1346
- include: [],
1347
- exclude: []
1348
- });
1349
- if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
1350
- return Object.freeze({
1351
- include: Object.freeze(validateTagList(value.include, 'include', label)),
1352
- exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label))
1353
- });
1389
+ const resolveWorkflowVariables = (value, options)=>{
1390
+ if ('string' == typeof value) return resolveString(value, options);
1391
+ if (Array.isArray(value)) return value.map((child)=>resolveWorkflowVariables(child, options));
1392
+ if ('object' == typeof value && null !== value) return Object.fromEntries(Object.entries(value).map(([key, child])=>[
1393
+ key,
1394
+ resolveWorkflowVariables(child, options)
1395
+ ]));
1396
+ return value;
1354
1397
  };
1355
- function assertJsonValue(value, path, seen) {
1356
- if (null === value || 'string' == typeof value || 'boolean' == typeof value) return;
1357
- if ('number' == typeof value) {
1358
- if (Number.isFinite(value)) return;
1359
- throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);
1360
- }
1361
- if ('object' != typeof value || void 0 === value) throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);
1362
- if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && null !== Object.getPrototypeOf(value)) throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);
1363
- if (seen.has(value)) throw new TypeError(`Midscene config ${path} must not contain cycles.`);
1364
- seen.add(value);
1365
- if (Array.isArray(value)) value.forEach((item, index)=>assertJsonValue(item, `${path}[${index}]`, seen));
1366
- else for (const [key, child] of Object.entries(value))assertJsonValue(child, `${path}.${key}`, seen);
1367
- seen.delete(value);
1398
+ function collect_define_property(obj, key, value) {
1399
+ if (key in obj) Object.defineProperty(obj, key, {
1400
+ value: value,
1401
+ enumerable: true,
1402
+ configurable: true,
1403
+ writable: true
1404
+ });
1405
+ else obj[key] = value;
1406
+ return obj;
1368
1407
  }
1369
- const deepFreezeJson = (value)=>{
1370
- if ('object' == typeof value && null !== value) {
1371
- for (const child of Object.values(value))deepFreezeJson(child);
1372
- Object.freeze(value);
1408
+ const isMapping = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
1409
+ class NativeWorkflowFormatError extends test_runner_namespaceObject.WorkflowParseError {
1410
+ constructor(actualFormat, sourcePath){
1411
+ super('legacy' === actualFormat ? `Legacy tasks/flow YAML is not supported by midscene-test: ${sourcePath}. Run it with \`midscene ${sourcePath}\`, or migrate the file to cases/steps.` : 'legacy-batch' === actualFormat ? `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.` : `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.`, {
1412
+ sourcePath,
1413
+ actualFormat,
1414
+ expectedFormat: 'native'
1415
+ }), collect_define_property(this, "actualFormat", void 0);
1416
+ this.actualFormat = actualFormat;
1373
1417
  }
1374
- return value;
1375
- };
1376
- const validateVariables = (value, label)=>{
1377
- if (void 0 === value) return Object.freeze({});
1378
- if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
1379
- assertJsonValue(value, label, new Set());
1380
- return deepFreezeJson(value);
1418
+ }
1419
+ const rejectUnknownKeys = (value, allowed, label)=>{
1420
+ const allowedSet = new Set(allowed);
1421
+ const unknown = Object.keys(value).filter((key)=>!allowedSet.has(key));
1422
+ if (unknown.length) throw new test_runner_namespaceObject.WorkflowParseError(`${label} has unsupported field "${unknown[0]}".`, {
1423
+ field: unknown[0]
1424
+ });
1381
1425
  };
1382
- const validateSetup = (value, label)=>{
1383
- if (void 0 === value) return;
1384
- if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
1385
- rejectUnknownKeys(value, [
1386
- 'name',
1387
- 'setup'
1388
- ], label);
1389
- if ('string' != typeof value.name || 0 === value.name.trim().length) throw new TypeError(`Midscene config ${label}.name must be non-empty.`);
1390
- if ('function' != typeof value.setup) throw new TypeError(`Midscene config ${label}.setup must be a function.`);
1391
- return value;
1392
- };
1393
- const validatePositiveInteger = (value, fallback, label)=>{
1394
- if (void 0 === value) return fallback;
1395
- if (!Number.isInteger(value) || value <= 0) throw new TypeError(`Midscene config ${label} must be a positive integer.`);
1396
- return value;
1397
- };
1398
- const validateNonNegativeInteger = (value, fallback, label)=>{
1399
- if (void 0 === value) return fallback;
1400
- if (!Number.isInteger(value) || value < 0) throw new TypeError(`Midscene config ${label} must be a non-negative integer.`);
1401
- return value;
1402
- };
1403
- const validateConcurrency = (value, label)=>{
1404
- if (null === value) return null;
1405
- return validatePositiveInteger(value, 1, label);
1406
- };
1407
- const validateFileConcurrency = (maxConcurrentFiles, fileSetup, label)=>{
1408
- if (maxConcurrentFiles > 1 && !fileSetup) throw new TypeError(`Midscene config ${label}.fileSetup is required when the effective maxConcurrentFiles is greater than 1.`);
1409
- };
1410
- const validateExecutionProjects = (value, defaultSetup, defaultFileSetup, globalNodes, test)=>{
1411
- if (void 0 === value) {
1412
- const setup = validateSetup(defaultSetup, 'setup');
1413
- const fileSetup = validateSetup(defaultFileSetup, 'fileSetup');
1414
- const maxConcurrentFiles = test.maxConcurrentFiles ?? 1 / 0;
1415
- validateFileConcurrency(maxConcurrentFiles, fileSetup, 'default');
1416
- return {
1417
- hasExplicitProjects: false,
1418
- projects: Object.freeze([
1419
- Object.freeze({
1420
- projectId: projectIdFromIndex(0),
1421
- name: 'default',
1422
- ...setup ? {
1423
- setup
1424
- } : {},
1425
- ...fileSetup ? {
1426
- fileSetup
1427
- } : {},
1428
- maxConcurrentFiles,
1429
- tags: Object.freeze({
1430
- include: [],
1431
- exclude: []
1432
- }),
1433
- retry: 0,
1434
- variables: Object.freeze({}),
1435
- nodes: new NodeRegistry(globalNodes.definitions())
1436
- })
1437
- ])
1438
- };
1426
+ const createCaseId = (projectId, sourcePath, caseIndex)=>createCaseInvocationId(projectId, sourcePath, caseIndex);
1427
+ const createWorkflowDocumentId = (projectId, sourcePath)=>createDocumentInvocationId(projectId, sourcePath);
1428
+ function collectWorkflowDocument(source, options) {
1429
+ let snapshot;
1430
+ try {
1431
+ snapshot = parseWorkflowSource((0, external_node_fs_.readFileSync)(source.absolutePath, 'utf8'));
1432
+ } catch (error) {
1433
+ throw new test_runner_namespaceObject.WorkflowParseError(`Failed to parse workflow document "${source.sourcePath}".`, {
1434
+ sourcePath: source.sourcePath
1435
+ }, error);
1439
1436
  }
1440
- if (void 0 !== defaultSetup) throw new TypeError('Midscene config setup cannot be used together with projects. Move setup to projects[].setup.');
1441
- if (void 0 !== defaultFileSetup) throw new TypeError('Midscene config fileSetup cannot be used together with projects. Move fileSetup to projects[].fileSetup.');
1442
- if (!Array.isArray(value) || 0 === value.length) throw new TypeError('Midscene config projects must be a non-empty array when declared.');
1443
- const names = new Set();
1444
- const projects = value.map((candidate, index)=>{
1445
- const label = `projects[${index}]`;
1446
- if (!isRecord(candidate)) throw new TypeError(`Midscene config ${label} must be an object.`);
1447
- rejectUnknownKeys(candidate, [
1437
+ const { parsed, sourceYaml } = snapshot;
1438
+ if (!isMapping(parsed)) throw new test_runner_namespaceObject.WorkflowParseError('Workflow document must be a mapping.');
1439
+ const format = (0, test_runner_namespaceObject.classifyWorkflowDocumentFormat)(parsed);
1440
+ if ('legacy' === format || 'legacy-batch' === format || 'mixed' === format) throw new NativeWorkflowFormatError(format, source.sourcePath);
1441
+ rejectUnknownKeys(parsed, [
1442
+ 'beforeAll',
1443
+ 'beforeEach',
1444
+ 'cases',
1445
+ 'afterEach',
1446
+ 'afterAll'
1447
+ ], 'Workflow document');
1448
+ if (!Array.isArray(parsed.cases) || 0 === parsed.cases.length) throw new test_runner_namespaceObject.WorkflowParseError('Workflow document must contain a non-empty cases array.');
1449
+ const sourcePath = source.sourcePath.split(external_node_path_.sep).join('/');
1450
+ const resolveStepVariables = (step, phase, stepIndex, caseIndex)=>({
1451
+ ...step,
1452
+ meta: {
1453
+ ...step.meta,
1454
+ sourceLocation: snapshot.locate('steps' === phase ? [
1455
+ 'cases',
1456
+ caseIndex,
1457
+ 'steps',
1458
+ stepIndex
1459
+ ] : [
1460
+ phase,
1461
+ stepIndex
1462
+ ])
1463
+ },
1464
+ templateInput: step.input,
1465
+ input: resolveWorkflowVariables(step.input, {
1466
+ variables: options.variables,
1467
+ env: options.env ?? process.env,
1468
+ location: {
1469
+ projectName: source.projectName ?? source.projectId,
1470
+ sourcePath,
1471
+ phase,
1472
+ stepIndex,
1473
+ ...void 0 === caseIndex ? {} : {
1474
+ caseIndex
1475
+ }
1476
+ }
1477
+ })
1478
+ });
1479
+ const normalizeLifecycle = (phase)=>{
1480
+ const value = parsed[phase];
1481
+ if (void 0 === value) return [];
1482
+ if (!Array.isArray(value)) throw new test_runner_namespaceObject.WorkflowParseError(`Workflow document ${phase} must be an array.`, {
1483
+ phase
1484
+ });
1485
+ return normalizeSteps(value, options.resolveNode).map((normalized, stepIndex)=>{
1486
+ const resolved = options.resolveNode(normalized.node);
1487
+ if (!resolved) throw new test_runner_namespaceObject.WorkflowParseError(`Workflow document ${phase} step ${stepIndex + 1} references unknown node "${normalized.node}".`, {
1488
+ phase,
1489
+ stepIndex,
1490
+ node: normalized.node
1491
+ });
1492
+ return resolveStepVariables(normalized, phase, stepIndex);
1493
+ });
1494
+ };
1495
+ const lifecycle = {
1496
+ beforeAll: normalizeLifecycle('beforeAll'),
1497
+ beforeEach: normalizeLifecycle('beforeEach'),
1498
+ afterEach: normalizeLifecycle('afterEach'),
1499
+ afterAll: normalizeLifecycle('afterAll')
1500
+ };
1501
+ const ids = new Set();
1502
+ const cases = parsed.cases.map((definition, caseIndex)=>{
1503
+ if (!isMapping(definition)) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} must be a mapping.`, {
1504
+ caseIndex
1505
+ });
1506
+ rejectUnknownKeys(definition, [
1448
1507
  'name',
1449
- 'setup',
1450
- 'fileSetup',
1451
- 'maxConcurrentFiles',
1452
- 'nodes',
1453
- 'files',
1454
1508
  'tags',
1455
- 'retry',
1456
- 'variables'
1457
- ], label);
1458
- if ('string' != typeof candidate.name || 0 === candidate.name.trim().length) throw new TypeError(`Midscene config ${label}.name must be non-empty.`);
1459
- if (names.has(candidate.name)) throw new TypeError(`Midscene config project name "${candidate.name}" must be unique.`);
1460
- names.add(candidate.name);
1461
- const files = test_project_validateTestFileSelection(candidate.files, `${label}.files`);
1462
- if (void 0 !== candidate.nodes && !Array.isArray(candidate.nodes)) throw new TypeError(`Midscene config ${label}.nodes must be an array.`);
1463
- const localNodes = new NodeRegistry(candidate.nodes);
1464
- const nodes = new NodeRegistry([
1465
- ...globalNodes.definitions().filter((node)=>!localNodes.has(node.name)),
1466
- ...localNodes.definitions()
1467
- ]);
1468
- const fileSetup = validateSetup(candidate.fileSetup, `${label}.fileSetup`);
1469
- const globalFileLimit = test.maxConcurrentFiles ?? 1 / 0;
1470
- const maxConcurrentFiles = Math.min(globalFileLimit, validatePositiveInteger(candidate.maxConcurrentFiles, globalFileLimit, `${label}.maxConcurrentFiles`));
1471
- validateFileConcurrency(maxConcurrentFiles, fileSetup, label);
1472
- return Object.freeze({
1473
- projectId: projectIdFromIndex(index),
1474
- name: candidate.name,
1475
- nodes,
1476
- ...fileSetup ? {
1477
- fileSetup
1478
- } : {},
1479
- maxConcurrentFiles,
1480
- ...files ? {
1481
- files
1482
- } : {},
1483
- tags: validateTagSelection(candidate.tags, `${label}.tags`),
1484
- retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),
1485
- variables: validateVariables(candidate.variables, `${label}.variables`),
1486
- ...void 0 === candidate.setup ? {} : {
1487
- setup: validateSetup(candidate.setup, `${label}.setup`)
1488
- }
1509
+ 'steps'
1510
+ ], `Case ${caseIndex + 1}`);
1511
+ if ('string' != typeof definition.name || 0 === definition.name.trim().length) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} name must be a non-empty string.`, {
1512
+ caseIndex
1513
+ });
1514
+ if (!Array.isArray(definition.steps) || 0 === definition.steps.length) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} steps must be a non-empty array.`, {
1515
+ caseIndex
1516
+ });
1517
+ const tags = definition.tags ?? [];
1518
+ if (!Array.isArray(tags) || tags.some((tag)=>'string' != typeof tag || 0 === tag.trim().length)) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} tags must be an array of non-empty strings.`, {
1519
+ caseIndex
1520
+ });
1521
+ const steps = normalizeSteps(definition.steps, options.resolveNode).map((normalized, stepIndex)=>{
1522
+ if (!options.resolveNode(normalized.node)) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} step ${stepIndex + 1} references unknown node "${normalized.node}".`, {
1523
+ caseIndex,
1524
+ stepIndex,
1525
+ node: normalized.node
1526
+ });
1527
+ return resolveStepVariables(normalized, 'steps', stepIndex, caseIndex);
1528
+ });
1529
+ const caseId = createCaseId(source.projectId, sourcePath, caseIndex);
1530
+ if (ids.has(caseId)) throw new test_runner_namespaceObject.WorkflowParseError(`Case id collision: ${caseId}.`, {
1531
+ caseId
1489
1532
  });
1533
+ ids.add(caseId);
1534
+ return {
1535
+ caseId,
1536
+ projectId: source.projectId,
1537
+ sourcePath,
1538
+ caseIndex,
1539
+ definition: {
1540
+ name: definition.name,
1541
+ tags: tags,
1542
+ steps
1543
+ }
1544
+ };
1490
1545
  });
1491
1546
  return {
1492
- projects: Object.freeze(projects),
1493
- hasExplicitProjects: true
1547
+ documentId: createWorkflowDocumentId(source.projectId, sourcePath),
1548
+ projectId: source.projectId,
1549
+ sourcePath,
1550
+ sourceYaml,
1551
+ lifecycle,
1552
+ cases
1494
1553
  };
1495
- };
1496
- const validateTestOptions = (value, hasExplicitProjects)=>{
1497
- if (void 0 !== value && !isRecord(value)) throw new TypeError('Midscene config test must be an object.');
1498
- const candidate = value ?? {};
1499
- if (void 0 !== candidate.maxConcurrency) {
1500
- const limit = 'number' == typeof candidate.maxConcurrency && Number.isInteger(candidate.maxConcurrency) && candidate.maxConcurrency > 0 ? candidate.maxConcurrency : 1;
1501
- throw new TypeError([
1502
- 'Midscene config test.maxConcurrency is no longer supported.',
1503
- 'It controlled project concurrency, not file concurrency. Remove it and use:',
1504
- ` test: { maxConcurrentProjects: ${limit}, maxConcurrentFiles: ${hasExplicitProjects ? limit : 1} }`,
1505
- hasExplicitProjects ? ' Set projects[].maxConcurrentFiles to 1 to keep files sequential within each project.' : ' The implicit default project keeps running files sequentially.',
1506
- hasExplicitProjects ? 'For parallel files, configure fileSetup and raise both test.maxConcurrentFiles and projects[].maxConcurrentFiles.' : 'For parallel files, configure fileSetup and raise test.maxConcurrentFiles.',
1507
- 'Migration guide: https://midscenejs.com/midscene-test/configuration.html#existing-configurations'
1508
- ].join('\n'));
1554
+ }
1555
+ const external_tinyglobby_namespaceObject = require("tinyglobby");
1556
+ const promises_namespaceObject = require("node:fs/promises");
1557
+ const writeJson = async (path, value)=>{
1558
+ try {
1559
+ await (0, promises_namespaceObject.mkdir)((0, external_node_path_.dirname)(path), {
1560
+ recursive: true
1561
+ });
1562
+ await (0, promises_namespaceObject.writeFile)(path, JSON.stringify(value, null, 2));
1563
+ } catch (error) {
1564
+ throw new test_runner_namespaceObject.WorkflowPublicationError('write-result', path, error);
1509
1565
  }
1510
- return Object.freeze({
1511
- maxConcurrentFiles: validateConcurrency(candidate.maxConcurrentFiles, 'test.maxConcurrentFiles'),
1512
- maxConcurrentProjects: validateConcurrency(candidate.maxConcurrentProjects, 'test.maxConcurrentProjects'),
1513
- setupTimeout: validatePositiveInteger(candidate.setupTimeout, 120000, 'test.setupTimeout'),
1514
- teardownTimeout: validatePositiveInteger(candidate.teardownTimeout, 30000, 'test.teardownTimeout'),
1515
- bail: validateNonNegativeInteger(candidate.bail, 0, 'test.bail'),
1516
- testTimeout: validatePositiveInteger(candidate.testTimeout, 120000, 'test.testTimeout')
1517
- });
1518
1566
  };
1519
- const validateOutputPath = (value, label)=>{
1520
- if ('string' != typeof value || 0 === value.trim().length) throw new TypeError(`Midscene config ${label} must be non-empty.`);
1521
- return value;
1522
- };
1523
- const validateOutput = (value)=>{
1524
- if (void 0 !== value && !isRecord(value)) throw new TypeError('Midscene config output must be an object.');
1525
- const candidate = value ?? {};
1526
- rejectUnknownKeys(candidate, [
1527
- 'reportDir',
1528
- 'reportFormat'
1529
- ], 'output');
1530
- if (void 0 !== candidate.reportFormat && 'single-html' !== candidate.reportFormat && 'html-and-external-assets' !== candidate.reportFormat) throw new TypeError('Midscene config output.reportFormat must be single-html or html-and-external-assets.');
1531
- return Object.freeze({
1532
- reportFormat: candidate.reportFormat ?? 'single-html',
1533
- ...void 0 === candidate.reportDir ? {} : {
1534
- reportDir: validateOutputPath(candidate.reportDir, 'output.reportDir')
1535
- }
1536
- });
1537
- };
1538
- const validateTestProjectDefinition = (definition)=>{
1539
- if (!isRecord(definition)) throw new TypeError('Midscene config must default export an object.');
1540
- if (void 0 !== definition.nodes && !Array.isArray(definition.nodes)) throw new TypeError('Midscene config nodes must be an array.');
1541
- if ('setupWorkflow' in definition) throw new TypeError('Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.');
1542
- if ('setupDocument' in definition) throw new TypeError('Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.');
1543
- if ('root' in definition) throw new TypeError('Midscene config root is not supported. Pass the Test Project directory to midscene-test instead.');
1544
- if ('files' in definition) throw new TypeError('Midscene config files is not supported at the root. Move it to projects[].files.');
1545
- if ('testRunner' in definition) throw new TypeError('Midscene config testRunner is not supported. Rename it to test.');
1546
- rejectUnknownKeys(definition, [
1547
- 'setup',
1548
- 'fileSetup',
1549
- 'projects',
1550
- 'test',
1551
- 'output',
1552
- 'nodes'
1553
- ], 'root');
1554
- const nodes = new NodeRegistry(definition.nodes);
1555
- const test = validateTestOptions(definition.test, void 0 !== definition.projects);
1556
- const resolvedProjects = validateExecutionProjects(definition.projects, definition.setup, definition.fileSetup, nodes, test);
1557
- return {
1558
- ...resolvedProjects,
1559
- test,
1560
- output: validateOutput(definition.output),
1561
- nodes,
1562
- resolveNode: (name)=>nodes.get(name)
1563
- };
1564
- };
1565
- const assertSupportedConfig = (absolutePath)=>{
1566
- if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {
1567
- const extension = absolutePath.match(/(\.[^./\\]+)$/)?.[1] ?? '(none)';
1568
- throw new TypeError(`Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`);
1569
- }
1570
- return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';
1571
- };
1572
- const canRetryWithCjsLoader = (error)=>{
1573
- if (!(error instanceof Error)) return false;
1574
- const errorCode = error.code;
1575
- return error instanceof SyntaxError && /^Unexpected (?:identifier|reserved word|token)/.test(error.message) || 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' === errorCode || 'ERR_UNKNOWN_FILE_EXTENSION' === errorCode && /^Unknown file extension\b/.test(error.message);
1576
- };
1577
- async function loadTestProject(configPath) {
1578
- if (!configPath) return validateTestProjectDefinition({
1579
- nodes: []
1567
+ const writeTestRunPlan = (runDir, projects)=>writeJson((0, external_node_path_.join)(runDir, 'plan.json'), {
1568
+ schemaVersion: 1,
1569
+ createdAt: new Date().toISOString(),
1570
+ projects: projects.map((item)=>({
1571
+ projectId: item.project.projectId,
1572
+ name: item.project.name,
1573
+ documents: item.plans ?? []
1574
+ }))
1580
1575
  });
1581
- const absolutePath = (0, external_node_path_.resolve)(configPath);
1582
- const extension = assertSupportedConfig(absolutePath);
1583
- let loaded;
1584
- try {
1585
- if ('.mjs' === extension) loaded = await import((0, external_node_url_namespaceObject.pathToFileURL)(absolutePath).href);
1586
- else {
1587
- const { tsImport } = await import("tsx/esm/api");
1588
- loaded = await tsImport((0, external_node_url_namespaceObject.pathToFileURL)(absolutePath).href, {
1589
- parentURL: (0, external_node_url_namespaceObject.pathToFileURL)(`${(0, external_node_path_.dirname)(absolutePath)}${external_node_path_.sep}`).href,
1590
- tsconfig: false
1591
- });
1592
- }
1593
- } catch (error) {
1594
- try {
1595
- if ('.mjs' === extension || !canRetryWithCjsLoader(error)) throw error;
1596
- loaded = (0, api_namespaceObject.require)(absolutePath, (0, external_node_url_namespaceObject.pathToFileURL)(absolutePath));
1597
- } catch (fallbackError) {
1598
- const message = fallbackError instanceof Error ? `: ${fallbackError.message}` : '';
1599
- throw new Error(`Failed to load Midscene config "${absolutePath}"${message}`, {
1600
- cause: fallbackError
1601
- });
1602
- }
1603
- }
1604
- return validateTestProjectDefinition(getDefaultExport(loaded, absolutePath));
1605
- }
1606
- const external_tinyglobby_namespaceObject = require("tinyglobby");
1607
- const external_node_crypto_namespaceObject = require("node:crypto");
1608
- const createCaseInvocationId = (projectId, sourcePath, caseIndex, invocationIndex = 0)=>(0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify([
1609
- projectId,
1610
- sourcePath,
1611
- caseIndex,
1612
- ...invocationIndex ? [
1613
- invocationIndex
1614
- ] : []
1615
- ])).digest('hex');
1616
- const createDocumentInvocationId = (projectId, sourcePath, invocationIndex = 0)=>(0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify([
1576
+ const toPosix = (value)=>value.split(external_node_path_.sep).join('/');
1577
+ const caseAttemptResultPath = (projectId, documentId, result)=>toPosix((0, external_node_path_.join)(projectId, 'documents', documentId, 'cases', result.caseId, `${result.runId}.json`));
1578
+ const workflowDocumentResultPath = (result)=>toPosix((0, external_node_path_.join)(result.projectId, 'documents', result.documentId, void 0 === result.attemptIndex ? 'document.json' : `${result.documentRunId}.json`));
1579
+ const collectionErrorPath = (projectId, sourcePath)=>{
1580
+ const id = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify([
1617
1581
  projectId,
1618
- sourcePath,
1619
- ...invocationIndex ? [
1620
- invocationIndex
1621
- ] : []
1582
+ sourcePath
1622
1583
  ])).digest('hex');
1623
- const normalizeSteps = test_runner_namespaceObject.normalizeSteps;
1624
- const external_js_yaml_namespaceObject = require("js-yaml");
1625
- function parseWorkflowSource(source) {
1626
- const stack = [];
1627
- const nodes = [];
1628
- const sensitiveNodes = new Set();
1629
- const sensitiveValues = new Set();
1630
- const redactedPaths = new Set();
1631
- const sourceOffset = 0xfeff === source.charCodeAt(0) ? 1 : 0;
1632
- const parsed = (0, external_js_yaml_namespaceObject.load)(source, {
1633
- schema: external_js_yaml_namespaceObject.JSON_SCHEMA,
1634
- listener (event, state) {
1635
- if ('open' === event) return void stack.push({
1636
- start: state.position + sourceOffset,
1637
- end: 0,
1638
- value: null,
1639
- children: [],
1640
- kind: null
1641
- });
1642
- const node = stack.pop();
1643
- node.end = state.position + sourceOffset;
1644
- node.value = state.result;
1645
- node.kind = state.kind;
1646
- stack.at(-1)?.children.push(node);
1647
- nodes.push(node);
1648
- if ('mapping' !== state.kind) return;
1649
- for(let index = 0; index < node.children.length; index += 2){
1650
- const key = node.children[index].value;
1651
- const value = node.children[index + 1];
1652
- if ('string' == typeof key && (0, test_runner_namespaceObject.isReportSecretKey)(key) && value) {
1653
- sensitiveNodes.add(value);
1654
- if (null !== value.value) sensitiveValues.add(value.value);
1655
- redactedPaths.add(`$..[${JSON.stringify(key)}]`);
1656
- }
1657
- }
1658
- }
1659
- });
1660
- const ranges = nodes.filter((node)=>sensitiveNodes.has(node) || sensitiveValues.has(node.value)).sort((left, right)=>left.start - right.start || right.end - left.end);
1661
- let offset = 0;
1662
- let redacted = '';
1663
- for (const range of ranges){
1664
- if (range.start < offset) continue;
1665
- const text = source.slice(range.start, range.end);
1666
- const leading = text.match(/^\s*/)?.[0] ?? '';
1667
- const trailing = text.slice(leading.length).match(/\s*$/)?.[0] ?? '';
1668
- redacted += `${source.slice(offset, range.start)}${leading}"[REDACTED]"${trailing}`;
1669
- offset = range.end;
1670
- }
1671
- redacted += source.slice(offset);
1672
- const value = (0, test_runner_namespaceObject.sanitizeReportText)(redacted, 65536);
1673
- return {
1674
- parsed,
1675
- locate (path) {
1676
- let node = nodes.at(-1);
1677
- for (const part of path){
1678
- if (!node) return;
1679
- while(1 === node.children.length && node.children[0].value === node.value)node = node.children[0];
1680
- if ('number' == typeof part && 'sequence' === node.kind) node = node.children[part];
1681
- else {
1682
- if ('string' != typeof part || 'mapping' !== node.kind) return;
1683
- const children = node.children;
1684
- node = void 0;
1685
- for(let index = 0; index < children.length; index += 2)if (children[index].value === part) {
1686
- node = children[index + 1];
1687
- break;
1688
- }
1689
- }
1690
- }
1691
- if (!node) return;
1692
- let start = node.start;
1693
- while(start < node.end)if (/\s/.test(source[start])) start++;
1694
- else if ('#' === source[start]) {
1695
- const end = source.indexOf('\n', start);
1696
- if (end < 0) return;
1697
- start = end + 1;
1698
- } else break;
1699
- const prefix = source.slice(0, start).split(/\r\n|\r|\n/);
1700
- return {
1701
- line: prefix.length,
1702
- column: prefix.at(-1).length + 1
1703
- };
1704
- },
1705
- sourceYaml: {
1706
- value,
1707
- ...redactedPaths.size ? {
1708
- redactedPaths: [
1709
- ...redactedPaths
1710
- ]
1711
- } : {},
1712
- ...value !== redacted ? {
1713
- truncatedPaths: [
1714
- '$'
1715
- ]
1716
- } : {}
1717
- }
1718
- };
1719
- }
1720
- const interpolationExpression = /\$\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}|\$\{([^{}]+)\}/g;
1721
- const exactEnvExpression = /^\$\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}$/;
1722
- const exactProjectExpression = /^\$\{([^{}]+)\}$/;
1723
- const missingVariable = (kind, name, options)=>{
1724
- throw new test_runner_namespaceObject.WorkflowParseError(`Undefined ${kind} variable "${name}" in ${options.location.sourcePath}.`, {
1725
- ...options.location,
1726
- variable: name,
1727
- variableKind: kind
1728
- });
1729
- };
1730
- const projectVariable = (name, options)=>{
1731
- if (!Object.hasOwn(options.variables ?? {}, name)) return missingVariable('project', name, options);
1732
- return options.variables[name];
1584
+ return toPosix((0, external_node_path_.join)(projectId, 'collection-errors', `${id}.json`));
1733
1585
  };
1734
- const environmentVariable = (name, options)=>{
1735
- const value = options.env?.[name];
1736
- if (void 0 === value) return missingVariable('environment', name, options);
1737
- return value;
1586
+ const writeWorkflowDocumentResult = (runDir, result)=>{
1587
+ const { documentRunId: _documentRunId, ...persistedResult } = result;
1588
+ return writeJson((0, external_node_path_.join)(runDir, workflowDocumentResultPath(result)), persistedResult);
1738
1589
  };
1739
- const interpolationValue = (name, value, options)=>{
1740
- if ('object' == typeof value && null !== value) throw new test_runner_namespaceObject.WorkflowParseError(`Project variable "${name}" must be a primitive when embedded in a string.`, {
1741
- ...options.location,
1742
- variable: name,
1743
- variableKind: 'project'
1590
+ const writeCaseAttemptResult = (runDir, projectId, documentId, result)=>{
1591
+ const { runId: attemptId, ...persistedResult } = result;
1592
+ return writeJson((0, external_node_path_.join)(runDir, caseAttemptResultPath(projectId, documentId, result)), {
1593
+ ...persistedResult,
1594
+ attemptId
1744
1595
  });
1745
- return String(value);
1746
- };
1747
- const resolveString = (value, options)=>{
1748
- const exactEnv = exactEnvExpression.exec(value);
1749
- if (exactEnv) return environmentVariable(exactEnv[1], options);
1750
- const exactProject = exactProjectExpression.exec(value);
1751
- if (exactProject) return projectVariable(exactProject[1], options);
1752
- return value.replace(interpolationExpression, (_match, environmentName, projectName)=>environmentName ? environmentVariable(environmentName, options) : interpolationValue(projectName, projectVariable(projectName, options), options));
1753
1596
  };
1754
- const resolveWorkflowVariables = (value, options)=>{
1755
- if ('string' == typeof value) return resolveString(value, options);
1756
- if (Array.isArray(value)) return value.map((child)=>resolveWorkflowVariables(child, options));
1757
- if ('object' == typeof value && null !== value) return Object.fromEntries(Object.entries(value).map(([key, child])=>[
1758
- key,
1759
- resolveWorkflowVariables(child, options)
1760
- ]));
1761
- return value;
1762
- };
1763
- function collect_define_property(obj, key, value) {
1764
- if (key in obj) Object.defineProperty(obj, key, {
1765
- value: value,
1766
- enumerable: true,
1767
- configurable: true,
1768
- writable: true
1769
- });
1770
- else obj[key] = value;
1771
- return obj;
1772
- }
1773
- const isMapping = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
1774
- class NativeWorkflowFormatError extends test_runner_namespaceObject.WorkflowParseError {
1775
- constructor(actualFormat, sourcePath){
1776
- super('legacy' === actualFormat ? `Legacy tasks/flow YAML is not supported by midscene-test: ${sourcePath}. Run it with \`midscene ${sourcePath}\`, or migrate the file to cases/steps.` : 'legacy-batch' === actualFormat ? `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.` : `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.`, {
1777
- sourcePath,
1778
- actualFormat,
1779
- expectedFormat: 'native'
1780
- }), collect_define_property(this, "actualFormat", void 0);
1781
- this.actualFormat = actualFormat;
1782
- }
1783
- }
1784
- const collect_rejectUnknownKeys = (value, allowed, label)=>{
1785
- const allowedSet = new Set(allowed);
1786
- const unknown = Object.keys(value).filter((key)=>!allowedSet.has(key));
1787
- if (unknown.length) throw new test_runner_namespaceObject.WorkflowParseError(`${label} has unsupported field "${unknown[0]}".`, {
1788
- field: unknown[0]
1597
+ const writeCollectionError = (runDir, collectionError)=>writeJson((0, external_node_path_.join)(runDir, collectionErrorPath(collectionError.projectId, collectionError.sourcePath)), {
1598
+ kind: 'collection-error',
1599
+ ...collectionError
1789
1600
  });
1790
- };
1791
- const createCaseId = (projectId, sourcePath, caseIndex)=>createCaseInvocationId(projectId, sourcePath, caseIndex);
1792
- const createWorkflowDocumentId = (projectId, sourcePath)=>createDocumentInvocationId(projectId, sourcePath);
1793
- function collectWorkflowDocument(source, options) {
1794
- let snapshot;
1795
- try {
1796
- snapshot = parseWorkflowSource((0, external_node_fs_.readFileSync)(source.absolutePath, 'utf8'));
1797
- } catch (error) {
1798
- throw new test_runner_namespaceObject.WorkflowParseError(`Failed to parse workflow document "${source.sourcePath}".`, {
1799
- sourcePath: source.sourcePath
1800
- }, error);
1801
- }
1802
- const { parsed, sourceYaml } = snapshot;
1803
- if (!isMapping(parsed)) throw new test_runner_namespaceObject.WorkflowParseError('Workflow document must be a mapping.');
1804
- const format = (0, test_runner_namespaceObject.classifyWorkflowDocumentFormat)(parsed);
1805
- if ('legacy' === format || 'legacy-batch' === format || 'mixed' === format) throw new NativeWorkflowFormatError(format, source.sourcePath);
1806
- collect_rejectUnknownKeys(parsed, [
1807
- 'beforeAll',
1808
- 'beforeEach',
1809
- 'cases',
1810
- 'afterEach',
1811
- 'afterAll'
1812
- ], 'Workflow document');
1813
- if (!Array.isArray(parsed.cases) || 0 === parsed.cases.length) throw new test_runner_namespaceObject.WorkflowParseError('Workflow document must contain a non-empty cases array.');
1814
- const sourcePath = source.sourcePath.split(external_node_path_.sep).join('/');
1815
- const resolveStepVariables = (step, phase, stepIndex, caseIndex)=>({
1816
- ...step,
1817
- meta: {
1818
- ...step.meta,
1819
- sourceLocation: snapshot.locate('steps' === phase ? [
1820
- 'cases',
1821
- caseIndex,
1822
- 'steps',
1823
- stepIndex
1824
- ] : [
1825
- phase,
1826
- stepIndex
1827
- ])
1828
- },
1829
- templateInput: step.input,
1830
- input: resolveWorkflowVariables(step.input, {
1831
- variables: options.variables,
1832
- env: options.env ?? process.env,
1833
- location: {
1834
- projectName: source.projectName ?? source.projectId,
1835
- sourcePath,
1836
- phase,
1837
- stepIndex,
1838
- ...void 0 === caseIndex ? {} : {
1839
- caseIndex
1840
- }
1841
- }
1842
- })
1843
- });
1844
- const normalizeLifecycle = (phase)=>{
1845
- const value = parsed[phase];
1846
- if (void 0 === value) return [];
1847
- if (!Array.isArray(value)) throw new test_runner_namespaceObject.WorkflowParseError(`Workflow document ${phase} must be an array.`, {
1848
- phase
1849
- });
1850
- return normalizeSteps(value, options.resolveNode).map((normalized, stepIndex)=>{
1851
- const resolved = options.resolveNode(normalized.node);
1852
- if (!resolved) throw new test_runner_namespaceObject.WorkflowParseError(`Workflow document ${phase} step ${stepIndex + 1} references unknown node "${normalized.node}".`, {
1853
- phase,
1854
- stepIndex,
1855
- node: normalized.node
1856
- });
1857
- return resolveStepVariables(normalized, phase, stepIndex);
1858
- });
1859
- };
1860
- const lifecycle = {
1861
- beforeAll: normalizeLifecycle('beforeAll'),
1862
- beforeEach: normalizeLifecycle('beforeEach'),
1863
- afterEach: normalizeLifecycle('afterEach'),
1864
- afterAll: normalizeLifecycle('afterAll')
1865
- };
1866
- const ids = new Set();
1867
- const cases = parsed.cases.map((definition, caseIndex)=>{
1868
- if (!isMapping(definition)) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} must be a mapping.`, {
1869
- caseIndex
1870
- });
1871
- collect_rejectUnknownKeys(definition, [
1872
- 'name',
1873
- 'tags',
1874
- 'steps'
1875
- ], `Case ${caseIndex + 1}`);
1876
- if ('string' != typeof definition.name || 0 === definition.name.trim().length) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} name must be a non-empty string.`, {
1877
- caseIndex
1878
- });
1879
- if (!Array.isArray(definition.steps) || 0 === definition.steps.length) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} steps must be a non-empty array.`, {
1880
- caseIndex
1881
- });
1882
- const tags = definition.tags ?? [];
1883
- if (!Array.isArray(tags) || tags.some((tag)=>'string' != typeof tag || 0 === tag.trim().length)) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} tags must be an array of non-empty strings.`, {
1884
- caseIndex
1885
- });
1886
- const steps = normalizeSteps(definition.steps, options.resolveNode).map((normalized, stepIndex)=>{
1887
- if (!options.resolveNode(normalized.node)) throw new test_runner_namespaceObject.WorkflowParseError(`Case ${caseIndex + 1} step ${stepIndex + 1} references unknown node "${normalized.node}".`, {
1888
- caseIndex,
1889
- stepIndex,
1890
- node: normalized.node
1891
- });
1892
- return resolveStepVariables(normalized, 'steps', stepIndex, caseIndex);
1893
- });
1894
- const caseId = createCaseId(source.projectId, sourcePath, caseIndex);
1895
- if (ids.has(caseId)) throw new test_runner_namespaceObject.WorkflowParseError(`Case id collision: ${caseId}.`, {
1896
- caseId
1897
- });
1898
- ids.add(caseId);
1899
- return {
1900
- caseId,
1901
- projectId: source.projectId,
1902
- sourcePath,
1903
- caseIndex,
1904
- definition: {
1905
- name: definition.name,
1906
- tags: tags,
1907
- steps
1908
- }
1909
- };
1910
- });
1911
- return {
1912
- documentId: createWorkflowDocumentId(source.projectId, sourcePath),
1913
- projectId: source.projectId,
1914
- sourcePath,
1915
- sourceYaml,
1916
- lifecycle,
1917
- cases
1918
- };
1919
- }
1920
- const promises_namespaceObject = require("node:fs/promises");
1921
- const writeJson = async (path, value)=>{
1922
- try {
1923
- await (0, promises_namespaceObject.mkdir)((0, external_node_path_.dirname)(path), {
1924
- recursive: true
1925
- });
1926
- await (0, promises_namespaceObject.writeFile)(path, JSON.stringify(value, null, 2));
1927
- } catch (error) {
1928
- throw new test_runner_namespaceObject.WorkflowPublicationError('write-result', path, error);
1929
- }
1930
- };
1931
- const writeTestRunPlan = (runDir, projects)=>writeJson((0, external_node_path_.join)(runDir, 'plan.json'), {
1932
- schemaVersion: 1,
1933
- createdAt: new Date().toISOString(),
1934
- projects: projects.map((item)=>({
1935
- projectId: item.project.projectId,
1936
- name: item.project.name,
1937
- documents: item.plans ?? []
1938
- }))
1939
- });
1940
- const toPosix = (value)=>value.split(external_node_path_.sep).join('/');
1941
- const caseAttemptResultPath = (projectId, documentId, result)=>toPosix((0, external_node_path_.join)(projectId, 'documents', documentId, 'cases', result.caseId, `${result.runId}.json`));
1942
- const workflowDocumentResultPath = (result)=>toPosix((0, external_node_path_.join)(result.projectId, 'documents', result.documentId, void 0 === result.attemptIndex ? 'document.json' : `${result.documentRunId}.json`));
1943
- const collectionErrorPath = (projectId, sourcePath)=>{
1944
- const id = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify([
1945
- projectId,
1946
- sourcePath
1947
- ])).digest('hex');
1948
- return toPosix((0, external_node_path_.join)(projectId, 'collection-errors', `${id}.json`));
1949
- };
1950
- const writeWorkflowDocumentResult = (runDir, result)=>{
1951
- const { documentRunId: _documentRunId, ...persistedResult } = result;
1952
- return writeJson((0, external_node_path_.join)(runDir, workflowDocumentResultPath(result)), persistedResult);
1953
- };
1954
- const writeCaseAttemptResult = (runDir, projectId, documentId, result)=>{
1955
- const { runId: attemptId, ...persistedResult } = result;
1956
- return writeJson((0, external_node_path_.join)(runDir, caseAttemptResultPath(projectId, documentId, result)), {
1957
- ...persistedResult,
1958
- attemptId
1959
- });
1960
- };
1961
- const writeCollectionError = (runDir, collectionError)=>writeJson((0, external_node_path_.join)(runDir, collectionErrorPath(collectionError.projectId, collectionError.sourcePath)), {
1962
- kind: 'collection-error',
1963
- ...collectionError
1964
- });
1965
- const relativeToSummary = (summaryPath, target)=>{
1966
- const value = (0, external_node_path_.relative)((0, external_node_path_.dirname)(summaryPath), target);
1967
- return toPosix(value || '.');
1601
+ const relativeToSummary = (summaryPath, target)=>{
1602
+ const value = (0, external_node_path_.relative)((0, external_node_path_.dirname)(summaryPath), target);
1603
+ return toPosix(value || '.');
1968
1604
  };
1969
1605
  const errorJson = test_runner_namespaceObject.sanitizeReportError;
1970
1606
  const writeTestProjectRunResult = (options)=>{
@@ -2183,161 +1819,487 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
2183
1819
  sourcePath
2184
1820
  }, error)
2185
1821
  });
2186
- const matchesTags = (tags, selection)=>{
2187
- if (selection.exclude.some((tag)=>tags.includes(tag))) return false;
2188
- return 0 === selection.include.length || selection.include.some((tag)=>tags.includes(tag));
1822
+ const matchesTags = (tags, selection)=>{
1823
+ if (selection.exclude.some((tag)=>tags.includes(tag))) return false;
1824
+ return 0 === selection.include.length || selection.include.some((tag)=>tags.includes(tag));
1825
+ };
1826
+ const filterDocumentCases = (document, project)=>{
1827
+ const cases = document.cases.filter((item)=>matchesTags(item.definition.tags ?? [], project.tags));
1828
+ const filtered = document.cases.length - cases.length;
1829
+ return 0 === cases.length ? {
1830
+ filtered
1831
+ } : {
1832
+ document: {
1833
+ ...document,
1834
+ cases
1835
+ },
1836
+ filtered
1837
+ };
1838
+ };
1839
+ const selectProjects = (projects, names)=>{
1840
+ if (!names || 0 === names.length) return projects;
1841
+ const requested = new Set(names);
1842
+ if (requested.size !== names.length) throw new Error('Each --project name may only be specified once.');
1843
+ const known = new Set(projects.map((project)=>project.name));
1844
+ const unknown = names.find((name)=>!known.has(name));
1845
+ if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);
1846
+ return projects.filter((project)=>requested.has(project.name));
1847
+ };
1848
+ async function prepareProject(project, projectRoot, runDir, defaultTimeoutMs, options = {}) {
1849
+ const platform = options.platform?.trim();
1850
+ const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;
1851
+ const prerequisiteFile = options.prerequisiteFile ? (0, external_node_path_.resolve)(options.prerequisiteFile) : void 0;
1852
+ const discoveredFiles = options.files ?? discoverResolvedTestFiles(options.discoveryRoot ?? projectRoot, fileSelection, options.excludedDirectories);
1853
+ const selectedPath = options.testPath ? (0, external_node_fs_.realpathSync)(options.testPath) : void 0;
1854
+ const mainFiles = selectedPath ? discoveredFiles.filter((file)=>{
1855
+ const within = (0, external_node_path_.relative)(selectedPath, (0, external_node_fs_.realpathSync)(file));
1856
+ return '' === within || !(0, external_node_path_.isAbsolute)(within) && '..' !== within && !within.startsWith(`..${external_node_path_.sep}`);
1857
+ }) : discoveredFiles;
1858
+ const files = [
1859
+ ...prerequisiteFile ? [
1860
+ prerequisiteFile
1861
+ ] : [],
1862
+ ...mainFiles.filter((file)=>file !== prerequisiteFile)
1863
+ ];
1864
+ const occurrences = new Map();
1865
+ const sources = files.map((absolutePath)=>{
1866
+ const invocationIndex = occurrences.get(absolutePath) ?? 0;
1867
+ occurrences.set(absolutePath, invocationIndex + 1);
1868
+ return {
1869
+ projectId: project.projectId,
1870
+ projectName: project.name,
1871
+ sourcePath: project_preparation_toPosix((0, external_node_path_.relative)(projectRoot, absolutePath)),
1872
+ absolutePath,
1873
+ invocationIndex
1874
+ };
1875
+ });
1876
+ const collectionErrors = [];
1877
+ const invocations = [];
1878
+ const plans = [];
1879
+ let filteredCaseCount = 0;
1880
+ if (0 === sources.length && !options.testPath) {
1881
+ const error = asCollectionError(project.projectId, project.name, '<project>', new test_runner_namespaceObject.WorkflowParseError(`No workflow YAML files found for project "${project.name}" in ${projectRoot}.`, {
1882
+ projectName: project.name,
1883
+ projectRoot
1884
+ }));
1885
+ collectionErrors.push(error);
1886
+ await writeCollectionError(runDir, error);
1887
+ }
1888
+ for (const source of sources)try {
1889
+ const collected = await options.collectDocument?.(source, project);
1890
+ if (collected) {
1891
+ filteredCaseCount += collected.filteredCaseCount;
1892
+ if (collected.invocation) {
1893
+ const plan = (0, test_runner_namespaceObject.buildTestRunReportPlan)(collected.invocation.document, {
1894
+ defaultTimeoutMs: collected.invocation.defaultTimeoutMs,
1895
+ retry: collected.invocation.retry
1896
+ });
1897
+ invocations.push({
1898
+ ...collected.invocation,
1899
+ plan
1900
+ });
1901
+ plans.push(plan);
1902
+ }
1903
+ continue;
1904
+ }
1905
+ const document = collectWorkflowDocument(source, {
1906
+ resolveNode: project.nodes.get.bind(project.nodes),
1907
+ variables: project.variables,
1908
+ env: process.env
1909
+ });
1910
+ const filtered = source.absolutePath === prerequisiteFile ? {
1911
+ document,
1912
+ filtered: 0
1913
+ } : filterDocumentCases(document, project);
1914
+ const plan = (0, test_runner_namespaceObject.buildTestRunReportPlan)(document, {
1915
+ selectedCaseIds: filtered.document?.cases.map((item)=>item.caseId) ?? [],
1916
+ defaultTimeoutMs,
1917
+ retry: {
1918
+ scope: 'case',
1919
+ count: project.retry
1920
+ }
1921
+ });
1922
+ plans.push(plan);
1923
+ filteredCaseCount += filtered.filtered;
1924
+ if (filtered.document) invocations.push({
1925
+ plan,
1926
+ document: filtered.document,
1927
+ retry: {
1928
+ scope: 'case',
1929
+ count: project.retry
1930
+ },
1931
+ defaultTimeoutMs,
1932
+ reportEnabled: true,
1933
+ bindings: {
1934
+ resolveNode: project.nodes.require.bind(project.nodes),
1935
+ ...project.fileSetup ? {
1936
+ documentSetup: {
1937
+ name: project.fileSetup.name,
1938
+ setup ({ projectContext, document, signal, onTeardown }) {
1939
+ return project.fileSetup.setup({
1940
+ project,
1941
+ projectContext,
1942
+ file: document,
1943
+ env: Object.freeze({
1944
+ ...process.env
1945
+ }),
1946
+ signal,
1947
+ onTeardown
1948
+ });
1949
+ }
1950
+ }
1951
+ } : {}
1952
+ }
1953
+ });
1954
+ } catch (error) {
1955
+ const collectionError = asCollectionError(project.projectId, project.name, source.sourcePath, error);
1956
+ collectionErrors.push(collectionError);
1957
+ await writeCollectionError(runDir, collectionError);
1958
+ }
1959
+ const documents = invocations.map((invocation)=>invocation.document);
1960
+ const prerequisiteSource = sources.find((source)=>source.absolutePath === prerequisiteFile);
1961
+ const prerequisiteDocument = documents.find((document)=>document.sourcePath === prerequisiteSource?.sourcePath);
1962
+ return {
1963
+ project,
1964
+ ...platform ? {
1965
+ platform
1966
+ } : {},
1967
+ documentConcurrency: options.documentConcurrency ?? 1,
1968
+ ...prerequisiteDocument ? {
1969
+ prerequisiteDocumentId: prerequisiteDocument.documentId
1970
+ } : {},
1971
+ fileSelection,
1972
+ sources,
1973
+ documents,
1974
+ invocations,
1975
+ plans,
1976
+ collectionErrors,
1977
+ selectedCaseCount: documents.reduce((total, document)=>total + document.cases.length, 0),
1978
+ filteredCaseCount
1979
+ };
1980
+ }
1981
+ const api_namespaceObject = require("tsx/cjs/api");
1982
+ const NodeRegistry = test_runner_namespaceObject.NodeRegistry;
1983
+ const projectIdFromIndex = (index)=>`project-${index}`;
1984
+ const getDefaultExport = (loaded, absolutePath)=>{
1985
+ if ('object' == typeof loaded && null !== loaded && 'default' in loaded) {
1986
+ const defaultExport = loaded.default;
1987
+ if ('object' == typeof defaultExport && null !== defaultExport && '__esModule' in defaultExport) {
1988
+ if ('default' in defaultExport) return defaultExport.default;
1989
+ throw new TypeError(`Midscene config "${absolutePath}" must have a default export.`);
1990
+ }
1991
+ return defaultExport;
1992
+ }
1993
+ throw new TypeError(`Midscene config "${absolutePath}" must have a default export.`);
1994
+ };
1995
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
1996
+ const test_project_rejectUnknownKeys = (value, allowedKeys, label)=>{
1997
+ const allowed = new Set(allowedKeys);
1998
+ const unknown = Object.keys(value).find((key)=>!allowed.has(key));
1999
+ if (unknown) throw new TypeError(`Midscene config ${label}.${unknown} is not supported.`);
2000
+ };
2001
+ const isAbsolutePattern = (pattern)=>(0, external_node_path_.isAbsolute)(pattern) || /^[A-Za-z]:[\\/]/.test(pattern) || pattern.startsWith('\\\\');
2002
+ const validatePatterns = (value, field, label = 'files', allowEmptyInclude = false)=>{
2003
+ if (!Array.isArray(value)) throw new TypeError(`Midscene config ${label}.${field} must be an array.`);
2004
+ if ('include' === field && 0 === value.length && !allowEmptyInclude) throw new TypeError(`Midscene config ${label}.include must be a non-empty array.`);
2005
+ return value.map((pattern, index)=>{
2006
+ if ('string' != typeof pattern || 0 === pattern.trim().length) throw new TypeError(`Midscene config ${label}.${field}[${index}] must be a non-empty string.`);
2007
+ if (isAbsolutePattern(pattern)) throw new TypeError(`Midscene config ${label}.${field}[${index}] must be relative to the project root.`);
2008
+ if (pattern.split(/[\\/]/).includes('..')) throw new TypeError(`Midscene config ${label}.${field}[${index}] must not contain a ".." path segment.`);
2009
+ if (pattern.includes('\\')) throw new TypeError(`Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`);
2010
+ if (pattern.startsWith('!')) {
2011
+ if ('include' === field) throw new TypeError(`Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`);
2012
+ throw new TypeError(`Midscene config ${label}.exclude[${index}] must not be a negated pattern.`);
2013
+ }
2014
+ return pattern;
2015
+ });
2016
+ };
2017
+ const test_project_validateTestFileSelection = (value, label = 'files')=>{
2018
+ if (void 0 === value) return;
2019
+ if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
2020
+ test_project_rejectUnknownKeys(value, [
2021
+ 'include',
2022
+ 'exclude'
2023
+ ], label);
2024
+ const include = validatePatterns(value.include, 'include', label);
2025
+ const exclude = void 0 === value.exclude ? void 0 : validatePatterns(value.exclude, 'exclude', label);
2026
+ return Object.freeze({
2027
+ include: Object.freeze(include),
2028
+ ...exclude ? {
2029
+ exclude: Object.freeze(exclude)
2030
+ } : {}
2031
+ });
2032
+ };
2033
+ const validateTagList = (value, field, label)=>{
2034
+ if (void 0 === value) return [];
2035
+ if (!Array.isArray(value)) throw new TypeError(`Midscene config ${label}.${field} must be an array.`);
2036
+ return value.map((tag, index)=>{
2037
+ if ('string' != typeof tag || 0 === tag.trim().length) throw new TypeError(`Midscene config ${label}.${field}[${index}] must be a non-empty string.`);
2038
+ return tag;
2039
+ });
2040
+ };
2041
+ const validateTagSelection = (value, label)=>{
2042
+ if (void 0 === value) return Object.freeze({
2043
+ include: [],
2044
+ exclude: []
2045
+ });
2046
+ if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
2047
+ return Object.freeze({
2048
+ include: Object.freeze(validateTagList(value.include, 'include', label)),
2049
+ exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label))
2050
+ });
2051
+ };
2052
+ function assertJsonValue(value, path, seen) {
2053
+ if (null === value || 'string' == typeof value || 'boolean' == typeof value) return;
2054
+ if ('number' == typeof value) {
2055
+ if (Number.isFinite(value)) return;
2056
+ throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);
2057
+ }
2058
+ if ('object' != typeof value || void 0 === value) throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);
2059
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && null !== Object.getPrototypeOf(value)) throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);
2060
+ if (seen.has(value)) throw new TypeError(`Midscene config ${path} must not contain cycles.`);
2061
+ seen.add(value);
2062
+ if (Array.isArray(value)) value.forEach((item, index)=>assertJsonValue(item, `${path}[${index}]`, seen));
2063
+ else for (const [key, child] of Object.entries(value))assertJsonValue(child, `${path}.${key}`, seen);
2064
+ seen.delete(value);
2065
+ }
2066
+ const deepFreezeJson = (value)=>{
2067
+ if ('object' == typeof value && null !== value) {
2068
+ for (const child of Object.values(value))deepFreezeJson(child);
2069
+ Object.freeze(value);
2070
+ }
2071
+ return value;
2072
+ };
2073
+ const validateVariables = (value, label)=>{
2074
+ if (void 0 === value) return Object.freeze({});
2075
+ if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
2076
+ assertJsonValue(value, label, new Set());
2077
+ return deepFreezeJson(value);
2078
+ };
2079
+ const validateSetup = (value, label)=>{
2080
+ if (void 0 === value) return;
2081
+ if (!isRecord(value)) throw new TypeError(`Midscene config ${label} must be an object.`);
2082
+ test_project_rejectUnknownKeys(value, [
2083
+ 'name',
2084
+ 'setup'
2085
+ ], label);
2086
+ if ('string' != typeof value.name || 0 === value.name.trim().length) throw new TypeError(`Midscene config ${label}.name must be non-empty.`);
2087
+ if ('function' != typeof value.setup) throw new TypeError(`Midscene config ${label}.setup must be a function.`);
2088
+ return value;
2089
+ };
2090
+ const validatePositiveInteger = (value, fallback, label)=>{
2091
+ if (void 0 === value) return fallback;
2092
+ if (!Number.isInteger(value) || value <= 0) throw new TypeError(`Midscene config ${label} must be a positive integer.`);
2093
+ return value;
2094
+ };
2095
+ const validateNonNegativeInteger = (value, fallback, label)=>{
2096
+ if (void 0 === value) return fallback;
2097
+ if (!Number.isInteger(value) || value < 0) throw new TypeError(`Midscene config ${label} must be a non-negative integer.`);
2098
+ return value;
2099
+ };
2100
+ const validateConcurrency = (value, label)=>{
2101
+ if (null === value) return null;
2102
+ return validatePositiveInteger(value, 1, label);
2103
+ };
2104
+ const validateFileConcurrency = (maxConcurrentFiles, fileSetup, label)=>{
2105
+ if (maxConcurrentFiles > 1 && !fileSetup) throw new TypeError(`Midscene config ${label}.fileSetup is required when the effective maxConcurrentFiles is greater than 1.`);
2106
+ };
2107
+ const validateExecutionProjects = (value, defaultSetup, defaultFileSetup, globalNodes, test)=>{
2108
+ if (void 0 === value) {
2109
+ const setup = validateSetup(defaultSetup, 'setup');
2110
+ const fileSetup = validateSetup(defaultFileSetup, 'fileSetup');
2111
+ const maxConcurrentFiles = test.maxConcurrentFiles ?? 1 / 0;
2112
+ validateFileConcurrency(maxConcurrentFiles, fileSetup, 'default');
2113
+ return {
2114
+ hasExplicitProjects: false,
2115
+ projects: Object.freeze([
2116
+ Object.freeze({
2117
+ projectId: projectIdFromIndex(0),
2118
+ name: 'default',
2119
+ ...setup ? {
2120
+ setup
2121
+ } : {},
2122
+ ...fileSetup ? {
2123
+ fileSetup
2124
+ } : {},
2125
+ maxConcurrentFiles,
2126
+ tags: Object.freeze({
2127
+ include: [],
2128
+ exclude: []
2129
+ }),
2130
+ retry: 0,
2131
+ variables: Object.freeze({}),
2132
+ nodes: new NodeRegistry(globalNodes.definitions())
2133
+ })
2134
+ ])
2135
+ };
2136
+ }
2137
+ if (void 0 !== defaultSetup) throw new TypeError('Midscene config setup cannot be used together with projects. Move setup to projects[].setup.');
2138
+ if (void 0 !== defaultFileSetup) throw new TypeError('Midscene config fileSetup cannot be used together with projects. Move fileSetup to projects[].fileSetup.');
2139
+ if (!Array.isArray(value) || 0 === value.length) throw new TypeError('Midscene config projects must be a non-empty array when declared.');
2140
+ const names = new Set();
2141
+ const projects = value.map((candidate, index)=>{
2142
+ const label = `projects[${index}]`;
2143
+ if (!isRecord(candidate)) throw new TypeError(`Midscene config ${label} must be an object.`);
2144
+ test_project_rejectUnknownKeys(candidate, [
2145
+ 'name',
2146
+ 'setup',
2147
+ 'fileSetup',
2148
+ 'maxConcurrentFiles',
2149
+ 'nodes',
2150
+ 'files',
2151
+ 'tags',
2152
+ 'retry',
2153
+ 'variables'
2154
+ ], label);
2155
+ if ('string' != typeof candidate.name || 0 === candidate.name.trim().length) throw new TypeError(`Midscene config ${label}.name must be non-empty.`);
2156
+ if (names.has(candidate.name)) throw new TypeError(`Midscene config project name "${candidate.name}" must be unique.`);
2157
+ names.add(candidate.name);
2158
+ const files = test_project_validateTestFileSelection(candidate.files, `${label}.files`);
2159
+ if (void 0 !== candidate.nodes && !Array.isArray(candidate.nodes)) throw new TypeError(`Midscene config ${label}.nodes must be an array.`);
2160
+ const localNodes = new NodeRegistry(candidate.nodes);
2161
+ const nodes = new NodeRegistry([
2162
+ ...globalNodes.definitions().filter((node)=>!localNodes.has(node.name)),
2163
+ ...localNodes.definitions()
2164
+ ]);
2165
+ const fileSetup = validateSetup(candidate.fileSetup, `${label}.fileSetup`);
2166
+ const globalFileLimit = test.maxConcurrentFiles ?? 1 / 0;
2167
+ const maxConcurrentFiles = Math.min(globalFileLimit, validatePositiveInteger(candidate.maxConcurrentFiles, globalFileLimit, `${label}.maxConcurrentFiles`));
2168
+ validateFileConcurrency(maxConcurrentFiles, fileSetup, label);
2169
+ return Object.freeze({
2170
+ projectId: projectIdFromIndex(index),
2171
+ name: candidate.name,
2172
+ nodes,
2173
+ ...fileSetup ? {
2174
+ fileSetup
2175
+ } : {},
2176
+ maxConcurrentFiles,
2177
+ ...files ? {
2178
+ files
2179
+ } : {},
2180
+ tags: validateTagSelection(candidate.tags, `${label}.tags`),
2181
+ retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),
2182
+ variables: validateVariables(candidate.variables, `${label}.variables`),
2183
+ ...void 0 === candidate.setup ? {} : {
2184
+ setup: validateSetup(candidate.setup, `${label}.setup`)
2185
+ }
2186
+ });
2187
+ });
2188
+ return {
2189
+ projects: Object.freeze(projects),
2190
+ hasExplicitProjects: true
2191
+ };
2192
+ };
2193
+ const validateTestOptions = (value, hasExplicitProjects)=>{
2194
+ if (void 0 !== value && !isRecord(value)) throw new TypeError('Midscene config test must be an object.');
2195
+ const candidate = value ?? {};
2196
+ if (void 0 !== candidate.maxConcurrency) {
2197
+ const limit = 'number' == typeof candidate.maxConcurrency && Number.isInteger(candidate.maxConcurrency) && candidate.maxConcurrency > 0 ? candidate.maxConcurrency : 1;
2198
+ throw new TypeError([
2199
+ 'Midscene config test.maxConcurrency is no longer supported.',
2200
+ 'It controlled project concurrency, not file concurrency. Remove it and use:',
2201
+ ` test: { maxConcurrentProjects: ${limit}, maxConcurrentFiles: ${hasExplicitProjects ? limit : 1} }`,
2202
+ hasExplicitProjects ? ' Set projects[].maxConcurrentFiles to 1 to keep files sequential within each project.' : ' The implicit default project keeps running files sequentially.',
2203
+ hasExplicitProjects ? 'For parallel files, configure fileSetup and raise both test.maxConcurrentFiles and projects[].maxConcurrentFiles.' : 'For parallel files, configure fileSetup and raise test.maxConcurrentFiles.',
2204
+ 'Migration guide: https://midscenejs.com/midscene-test/configuration.html#existing-configurations'
2205
+ ].join('\n'));
2206
+ }
2207
+ return Object.freeze({
2208
+ maxConcurrentFiles: validateConcurrency(candidate.maxConcurrentFiles, 'test.maxConcurrentFiles'),
2209
+ maxConcurrentProjects: validateConcurrency(candidate.maxConcurrentProjects, 'test.maxConcurrentProjects'),
2210
+ setupTimeout: validatePositiveInteger(candidate.setupTimeout, 120000, 'test.setupTimeout'),
2211
+ teardownTimeout: validatePositiveInteger(candidate.teardownTimeout, 30000, 'test.teardownTimeout'),
2212
+ bail: validateNonNegativeInteger(candidate.bail, 0, 'test.bail'),
2213
+ testTimeout: validatePositiveInteger(candidate.testTimeout, 120000, 'test.testTimeout')
2214
+ });
2215
+ };
2216
+ const validateOutputPath = (value, label)=>{
2217
+ if ('string' != typeof value || 0 === value.trim().length) throw new TypeError(`Midscene config ${label} must be non-empty.`);
2218
+ return value;
2219
+ };
2220
+ const validateOutput = (value)=>{
2221
+ if (void 0 !== value && !isRecord(value)) throw new TypeError('Midscene config output must be an object.');
2222
+ const candidate = value ?? {};
2223
+ test_project_rejectUnknownKeys(candidate, [
2224
+ 'reportDir',
2225
+ 'reportFormat'
2226
+ ], 'output');
2227
+ if (void 0 !== candidate.reportFormat && 'single-html' !== candidate.reportFormat && 'html-and-external-assets' !== candidate.reportFormat) throw new TypeError('Midscene config output.reportFormat must be single-html or html-and-external-assets.');
2228
+ return Object.freeze({
2229
+ reportFormat: candidate.reportFormat ?? 'single-html',
2230
+ ...void 0 === candidate.reportDir ? {} : {
2231
+ reportDir: validateOutputPath(candidate.reportDir, 'output.reportDir')
2232
+ }
2233
+ });
2189
2234
  };
2190
- const filterDocumentCases = (document, project)=>{
2191
- const cases = document.cases.filter((item)=>matchesTags(item.definition.tags ?? [], project.tags));
2192
- const filtered = document.cases.length - cases.length;
2193
- return 0 === cases.length ? {
2194
- filtered
2195
- } : {
2196
- document: {
2197
- ...document,
2198
- cases
2199
- },
2200
- filtered
2235
+ const validateTestProjectDefinition = (definition)=>{
2236
+ if (!isRecord(definition)) throw new TypeError('Midscene config must default export an object.');
2237
+ if (void 0 !== definition.nodes && !Array.isArray(definition.nodes)) throw new TypeError('Midscene config nodes must be an array.');
2238
+ if ('setupWorkflow' in definition) throw new TypeError('Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.');
2239
+ if ('setupDocument' in definition) throw new TypeError('Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.');
2240
+ if ('root' in definition) throw new TypeError('Midscene config root is not supported. Run midscene-test from the project directory or select its config with --config instead.');
2241
+ if ('files' in definition) throw new TypeError('Midscene config files is not supported at the root. Move it to projects[].files.');
2242
+ if ('testRunner' in definition) throw new TypeError('Midscene config testRunner is not supported. Rename it to test.');
2243
+ test_project_rejectUnknownKeys(definition, [
2244
+ 'setup',
2245
+ 'fileSetup',
2246
+ 'projects',
2247
+ 'test',
2248
+ 'output',
2249
+ 'nodes'
2250
+ ], 'root');
2251
+ const nodes = new NodeRegistry(definition.nodes);
2252
+ const test = validateTestOptions(definition.test, void 0 !== definition.projects);
2253
+ const resolvedProjects = validateExecutionProjects(definition.projects, definition.setup, definition.fileSetup, nodes, test);
2254
+ return {
2255
+ ...resolvedProjects,
2256
+ test,
2257
+ output: validateOutput(definition.output),
2258
+ nodes,
2259
+ resolveNode: (name)=>nodes.get(name)
2201
2260
  };
2202
2261
  };
2203
- const selectProjects = (projects, names)=>{
2204
- if (!names || 0 === names.length) return projects;
2205
- const requested = new Set(names);
2206
- if (requested.size !== names.length) throw new Error('Each --project name may only be specified once.');
2207
- const known = new Set(projects.map((project)=>project.name));
2208
- const unknown = names.find((name)=>!known.has(name));
2209
- if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);
2210
- return projects.filter((project)=>requested.has(project.name));
2262
+ const assertSupportedConfig = (absolutePath)=>{
2263
+ if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {
2264
+ const extension = absolutePath.match(/(\.[^./\\]+)$/)?.[1] ?? '(none)';
2265
+ throw new TypeError(`Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`);
2266
+ }
2267
+ return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';
2211
2268
  };
2212
- async function prepareProject(project, projectRoot, runDir, defaultTimeoutMs, options = {}) {
2213
- const platform = options.platform?.trim();
2214
- const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;
2215
- const prerequisiteFile = options.prerequisiteFile ? (0, external_node_path_.resolve)(options.prerequisiteFile) : void 0;
2216
- const mainFiles = options.files ?? discoverResolvedTestFiles(projectRoot, fileSelection, options.excludedDirectories);
2217
- const files = [
2218
- ...prerequisiteFile ? [
2219
- prerequisiteFile
2220
- ] : [],
2221
- ...mainFiles.filter((file)=>file !== prerequisiteFile)
2222
- ];
2223
- const occurrences = new Map();
2224
- const sources = files.map((absolutePath)=>{
2225
- const invocationIndex = occurrences.get(absolutePath) ?? 0;
2226
- occurrences.set(absolutePath, invocationIndex + 1);
2227
- return {
2228
- projectId: project.projectId,
2229
- projectName: project.name,
2230
- sourcePath: project_preparation_toPosix((0, external_node_path_.relative)(projectRoot, absolutePath)),
2231
- absolutePath,
2232
- invocationIndex
2233
- };
2269
+ const canRetryWithCjsLoader = (error)=>{
2270
+ if (!(error instanceof Error)) return false;
2271
+ const errorCode = error.code;
2272
+ return error instanceof SyntaxError && /^Unexpected (?:identifier|reserved word|token)/.test(error.message) || 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' === errorCode || 'ERR_UNKNOWN_FILE_EXTENSION' === errorCode && /^Unknown file extension\b/.test(error.message);
2273
+ };
2274
+ async function loadTestProject(configPath) {
2275
+ if (!configPath) return validateTestProjectDefinition({
2276
+ nodes: []
2234
2277
  });
2235
- const collectionErrors = [];
2236
- const invocations = [];
2237
- const plans = [];
2238
- let filteredCaseCount = 0;
2239
- if (0 === sources.length) {
2240
- const error = asCollectionError(project.projectId, project.name, '<project>', new test_runner_namespaceObject.WorkflowParseError(`No workflow YAML files found for project "${project.name}" in ${projectRoot}.`, {
2241
- projectName: project.name,
2242
- projectRoot
2243
- }));
2244
- collectionErrors.push(error);
2245
- await writeCollectionError(runDir, error);
2246
- }
2247
- for (const source of sources)try {
2248
- const collected = await options.collectDocument?.(source, project);
2249
- if (collected) {
2250
- filteredCaseCount += collected.filteredCaseCount;
2251
- if (collected.invocation) {
2252
- const plan = (0, test_runner_namespaceObject.buildTestRunReportPlan)(collected.invocation.document, {
2253
- defaultTimeoutMs: collected.invocation.defaultTimeoutMs,
2254
- retry: collected.invocation.retry
2255
- });
2256
- invocations.push({
2257
- ...collected.invocation,
2258
- plan
2259
- });
2260
- plans.push(plan);
2261
- }
2262
- continue;
2278
+ const absolutePath = (0, external_node_path_.resolve)(configPath);
2279
+ const extension = assertSupportedConfig(absolutePath);
2280
+ let loaded;
2281
+ try {
2282
+ if ('.mjs' === extension) loaded = await import((0, external_node_url_namespaceObject.pathToFileURL)(absolutePath).href);
2283
+ else {
2284
+ const { tsImport } = await import("tsx/esm/api");
2285
+ loaded = await tsImport((0, external_node_url_namespaceObject.pathToFileURL)(absolutePath).href, {
2286
+ parentURL: (0, external_node_url_namespaceObject.pathToFileURL)(`${(0, external_node_path_.dirname)(absolutePath)}${external_node_path_.sep}`).href,
2287
+ tsconfig: false
2288
+ });
2263
2289
  }
2264
- const document = collectWorkflowDocument(source, {
2265
- resolveNode: project.nodes.get.bind(project.nodes),
2266
- variables: project.variables,
2267
- env: process.env
2268
- });
2269
- const filtered = source.absolutePath === prerequisiteFile ? {
2270
- document,
2271
- filtered: 0
2272
- } : filterDocumentCases(document, project);
2273
- const plan = (0, test_runner_namespaceObject.buildTestRunReportPlan)(document, {
2274
- selectedCaseIds: filtered.document?.cases.map((item)=>item.caseId) ?? [],
2275
- defaultTimeoutMs,
2276
- retry: {
2277
- scope: 'case',
2278
- count: project.retry
2279
- }
2280
- });
2281
- plans.push(plan);
2282
- filteredCaseCount += filtered.filtered;
2283
- if (filtered.document) invocations.push({
2284
- plan,
2285
- document: filtered.document,
2286
- retry: {
2287
- scope: 'case',
2288
- count: project.retry
2289
- },
2290
- defaultTimeoutMs,
2291
- reportEnabled: true,
2292
- bindings: {
2293
- resolveNode: project.nodes.require.bind(project.nodes),
2294
- ...project.fileSetup ? {
2295
- documentSetup: {
2296
- name: project.fileSetup.name,
2297
- setup ({ projectContext, document, signal, onTeardown }) {
2298
- return project.fileSetup.setup({
2299
- project,
2300
- projectContext,
2301
- file: document,
2302
- env: Object.freeze({
2303
- ...process.env
2304
- }),
2305
- signal,
2306
- onTeardown
2307
- });
2308
- }
2309
- }
2310
- } : {}
2311
- }
2312
- });
2313
2290
  } catch (error) {
2314
- const collectionError = asCollectionError(project.projectId, project.name, source.sourcePath, error);
2315
- collectionErrors.push(collectionError);
2316
- await writeCollectionError(runDir, collectionError);
2291
+ try {
2292
+ if ('.mjs' === extension || !canRetryWithCjsLoader(error)) throw error;
2293
+ loaded = (0, api_namespaceObject.require)(absolutePath, (0, external_node_url_namespaceObject.pathToFileURL)(absolutePath));
2294
+ } catch (fallbackError) {
2295
+ const message = fallbackError instanceof Error ? `: ${fallbackError.message}` : '';
2296
+ throw new Error(`Failed to load Midscene config "${absolutePath}"${message}`, {
2297
+ cause: fallbackError
2298
+ });
2299
+ }
2317
2300
  }
2318
- const documents = invocations.map((invocation)=>invocation.document);
2319
- const prerequisiteSource = sources.find((source)=>source.absolutePath === prerequisiteFile);
2320
- const prerequisiteDocument = documents.find((document)=>document.sourcePath === prerequisiteSource?.sourcePath);
2321
- return {
2322
- project,
2323
- ...platform ? {
2324
- platform
2325
- } : {},
2326
- documentConcurrency: options.documentConcurrency ?? 1,
2327
- ...prerequisiteDocument ? {
2328
- prerequisiteDocumentId: prerequisiteDocument.documentId
2329
- } : {},
2330
- fileSelection,
2331
- sources,
2332
- documents,
2333
- invocations,
2334
- plans,
2335
- collectionErrors,
2336
- selectedCaseCount: documents.reduce((total, document)=>total + document.cases.length, 0),
2337
- filteredCaseCount
2338
- };
2301
+ return validateTestProjectDefinition(getDefaultExport(loaded, absolutePath));
2339
2302
  }
2340
- const common_namespaceObject = require("@midscene/shared/common");
2341
2303
  const padDatePart = (value)=>String(value).padStart(2, '0');
2342
2304
  const createTestRunId = (date = new Date(), uuid = (0, external_node_crypto_namespaceObject.randomUUID)())=>{
2343
2305
  const timestamp = [
@@ -2356,18 +2318,25 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
2356
2318
  const resolveRunInput = (options)=>{
2357
2319
  const cwd = (0, external_node_path_.resolve)(options.cwd ?? process.cwd());
2358
2320
  assertDirectory(cwd, 'Test working directory');
2359
- const inputPath = options.projectRoot ? (0, external_node_path_.resolve)(cwd, options.projectRoot) : void 0;
2360
- const singleFile = inputPath && (0, external_node_fs_.existsSync)(inputPath) && (0, external_node_fs_.statSync)(inputPath).isFile() ? inputPath : void 0;
2361
- if (singleFile && !/\.ya?ml$/i.test(singleFile)) throw new Error(`Test input must be a YAML file or project directory: ${singleFile}`);
2362
- const cliProjectRoot = singleFile ? (0, external_node_path_.dirname)(singleFile) : inputPath;
2363
- if (cliProjectRoot) assertDirectory(cliProjectRoot, 'Test project directory');
2364
- const projectRoot = cliProjectRoot ?? cwd;
2321
+ const searchRoot = (0, external_node_path_.resolve)(cwd, options.projectRoot ?? '.');
2322
+ assertDirectory(searchRoot, 'Test project directory');
2323
+ const configPath = options.configPath ? (0, external_node_path_.resolve)(cwd, options.configPath) : discoverTestConfig(searchRoot);
2324
+ if (options.configPath && /\.ya?ml$/i.test(configPath)) throw new Error(`midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \`midscene --config ${options.configPath}\`.`);
2325
+ if (configPath && (!(0, external_node_fs_.existsSync)(configPath) || !(0, external_node_fs_.statSync)(configPath).isFile())) throw new Error(`Midscene config does not exist or is not a file: ${configPath}`);
2326
+ const testPath = options.testPath ? (0, external_node_path_.resolve)(cwd, options.testPath) : void 0;
2327
+ if (testPath) {
2328
+ if (!(0, external_node_fs_.existsSync)(testPath)) throw new Error(`Test path does not exist: ${testPath}`);
2329
+ const stat = (0, external_node_fs_.statSync)(testPath);
2330
+ if (!stat.isDirectory() && !(stat.isFile() && /\.ya?ml$/i.test(testPath))) throw new Error(`Test input must be a YAML file or directory: ${testPath}`);
2331
+ }
2365
2332
  return {
2366
2333
  cwd,
2367
- projectRoot,
2368
- configSearchRoot: projectRoot,
2369
- ...singleFile ? {
2370
- singleFile
2334
+ projectRoot: configPath ? (0, external_node_path_.dirname)(configPath) : searchRoot,
2335
+ ...configPath ? {
2336
+ configPath
2337
+ } : {},
2338
+ ...testPath ? {
2339
+ testPath
2371
2340
  } : {}
2372
2341
  };
2373
2342
  };
@@ -2375,9 +2344,15 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
2375
2344
  const startedAt = new Date();
2376
2345
  const runId = createTestRunId(startedAt);
2377
2346
  const input = resolveRunInput(options);
2378
- const configPath = options.configPath ? (0, external_node_path_.resolve)(input.configSearchRoot, options.configPath) : discoverTestConfig(input.configSearchRoot);
2379
- if (options.configPath && /\.ya?ml$/i.test(configPath)) throw new Error(`midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \`midscene --config ${options.configPath}\`.`);
2380
- if (options.configPath && !(0, external_node_fs_.existsSync)(configPath)) throw new Error(`Midscene config does not exist: ${configPath}`);
2347
+ const { configPath } = input;
2348
+ const standalonePath = configPath ? void 0 : input.testPath;
2349
+ const discovery = standalonePath && (0, external_node_fs_.statSync)(standalonePath).isFile() ? {
2350
+ files: [
2351
+ standalonePath
2352
+ ]
2353
+ } : {
2354
+ discoveryRoot: standalonePath
2355
+ };
2381
2356
  const definition = await loadTestProject(configPath);
2382
2357
  const artifactDir = (0, common_namespaceObject.resolveMidsceneRunDir)(input.projectRoot);
2383
2358
  return (0, common_namespaceObject.runWithMidsceneRunDir)(artifactDir, async ()=>{
@@ -2391,11 +2366,8 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
2391
2366
  (0, external_node_fs_.mkdirSync)(runDir);
2392
2367
  const projects = [];
2393
2368
  for (const project of selectProjects(definition.projects, options.projectNames))projects.push(await prepareProject(project, input.projectRoot, runDir, definition.test.testTimeout, {
2394
- ...input.singleFile ? {
2395
- files: [
2396
- input.singleFile
2397
- ]
2398
- } : {},
2369
+ testPath: input.testPath,
2370
+ ...discovery,
2399
2371
  excludedDirectories: [
2400
2372
  artifactDir,
2401
2373
  resultDir,
@@ -2409,6 +2381,7 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
2409
2381
  ].map((name)=>(0, external_node_path_.join)(artifactDir, name))
2410
2382
  ]
2411
2383
  }));
2384
+ if (input.testPath && projects.every((project)=>0 === project.selectedCaseCount && 0 === project.collectionErrors.length)) throw new Error(`No test cases match "${input.testPath}" in ${input.projectRoot}. Check --project, files.include/files.exclude, tags, and ignored output directories.`);
2412
2385
  const hasFormatMismatch = projects.some((project)=>project.collectionErrors.some(({ error })=>error instanceof NativeWorkflowFormatError));
2413
2386
  return {
2414
2387
  startedAt,
@@ -3424,13 +3397,36 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
3424
3397
  if (hasInfrastructureError) throw new test_runner_namespaceObject.WorkflowExecutionFailure(completedResult, infrastructureErrors);
3425
3398
  return completedResult;
3426
3399
  }
3427
- async function runTestProject(options = {}) {
3428
- return runPreparedTestProject(await prepareTestRun(options));
3400
+ function captureTerminalOutput(output, streams = [
3401
+ process.stdout,
3402
+ process.stderr
3403
+ ]) {
3404
+ const cleanups = [];
3405
+ for (const stream of streams){
3406
+ const original = stream.write;
3407
+ const forward = original.bind(stream);
3408
+ const intercepted = (chunk, encoding, callback)=>{
3409
+ const done = 'function' == typeof encoding ? encoding : callback;
3410
+ const message = 'string' == typeof chunk ? chunk : Buffer.from(chunk).toString();
3411
+ let accepted = true;
3412
+ output(message, (text)=>{
3413
+ accepted = forward(text, done);
3414
+ });
3415
+ return accepted;
3416
+ };
3417
+ stream.write = intercepted;
3418
+ cleanups.push(()=>{
3419
+ if (stream.write === intercepted) stream.write = original;
3420
+ });
3421
+ }
3422
+ return ()=>{
3423
+ for (const cleanup of cleanups)cleanup();
3424
+ };
3429
3425
  }
3430
3426
  const parseTestCliArgs = (args, cwd = process.cwd())=>{
3431
3427
  const command = 'nodes' === args[0] ? args[0] : void 0;
3432
3428
  const commandOffset = command ? 1 : 0;
3433
- let projectRoot;
3429
+ let inputPath;
3434
3430
  let configPath;
3435
3431
  let resultDir;
3436
3432
  const projectNames = [];
@@ -3441,8 +3437,8 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
3441
3437
  const arg = equal < 0 ? token : token.slice(0, equal);
3442
3438
  const inlineValue = equal < 0 ? void 0 : token.slice(equal + 1);
3443
3439
  if (!arg.startsWith('-')) {
3444
- if (projectRoot) throw new Error('Only one test project directory is allowed.');
3445
- projectRoot = (0, external_node_path_.resolve)(cwd, arg);
3440
+ if (inputPath) throw new Error('Only one test file or directory is allowed.');
3441
+ inputPath = (0, external_node_path_.resolve)(cwd, arg);
3446
3442
  continue;
3447
3443
  }
3448
3444
  if ('--config' === arg || '--result-dir' === arg || '--project' === arg || '--reporter' === arg) {
@@ -3466,7 +3462,11 @@ Each Node's returned \`data\` is saved on that Step's result. Results are not na
3466
3462
  command
3467
3463
  } : {},
3468
3464
  cwd,
3469
- projectRoot,
3465
+ ...command ? {
3466
+ projectRoot: inputPath
3467
+ } : {
3468
+ testPath: inputPath
3469
+ },
3470
3470
  configPath,
3471
3471
  resultDir,
3472
3472
  ...projectNames.length > 0 ? {
@@ -3510,6 +3510,12 @@ Options:
3510
3510
  --help, -h Show this help
3511
3511
  --version Show the package version
3512
3512
 
3513
+ With a config, run paths filter project files. Without one, they select standalone inputs.
3514
+ Run paths never change config discovery or the artifact root.
3515
+ For test runs, config discovery checks cwd only; --config is relative to cwd.
3516
+ The selected config directory becomes the test root.
3517
+ File include/exclude and tag rules still apply to explicit paths.
3518
+
3513
3519
  Legacy tasks/flow YAML and its CLI options belong to the midscene command.
3514
3520
  `;
3515
3521
  const test_command_assertDirectory = (path, label)=>{
@@ -3749,16 +3755,17 @@ Legacy tasks/flow YAML and its CLI options belong to the midscene command.
3749
3755
  }
3750
3756
  const reporter = new TerminalReporter(io, options.reporter);
3751
3757
  const restoreOutput = io === defaultCliIO && io.isTTY && 'verbose' !== options.reporter ? captureTerminalOutput((message, write)=>reporter.output(message, write)) : void 0;
3752
- const projectRoot = (0, external_node_fs_.realpathSync)(options.projectRoot && (0, external_node_fs_.existsSync)(options.projectRoot) && (0, external_node_fs_.statSync)(options.projectRoot).isFile() ? (0, external_node_path_.dirname)(options.projectRoot) : options.projectRoot ?? options.cwd);
3753
3758
  try {
3754
3759
  return await (0, logger_namespaceObject.runWithConsoleLogHandler)((entry)=>reporter.console(entry), async ()=>{
3760
+ const plan = await prepareTestRun({
3761
+ ...options,
3762
+ onProgress: (message)=>reporter.progress(message),
3763
+ onEvent: (event)=>reporter.event(event)
3764
+ });
3765
+ const projectRoot = (0, external_node_fs_.realpathSync)(plan.projectRoot);
3755
3766
  let result;
3756
3767
  try {
3757
- result = await runTestProject({
3758
- ...options,
3759
- onProgress: (message)=>reporter.progress(message),
3760
- onEvent: (event)=>reporter.event(event)
3761
- });
3768
+ result = await runPreparedTestProject(plan);
3762
3769
  } catch (error) {
3763
3770
  if (!(error instanceof test_runner_namespaceObject.WorkflowExecutionFailure)) throw error;
3764
3771
  reportTestProjectResult(error.result, io, reporter, projectRoot, error.errors);