callman-core 1.16.0 → 1.18.0

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 (74) hide show
  1. package/dist/contract/contractValidator.d.ts.map +1 -1
  2. package/dist/contract/contractValidator.js +19 -2
  3. package/dist/contract/contractValidator.js.map +1 -1
  4. package/dist/contract/xpathResolver.d.ts +7 -0
  5. package/dist/contract/xpathResolver.d.ts.map +1 -0
  6. package/dist/contract/xpathResolver.js +69 -0
  7. package/dist/contract/xpathResolver.js.map +1 -0
  8. package/dist/index.d.ts +4 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +5 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/scenario-runner/adapters/helpers/request-helpers.d.ts.map +1 -1
  13. package/dist/scenario-runner/adapters/helpers/request-helpers.js +8 -0
  14. package/dist/scenario-runner/adapters/helpers/request-helpers.js.map +1 -1
  15. package/dist/scenario-runner/adapters/request-executor.d.ts.map +1 -1
  16. package/dist/scenario-runner/adapters/request-executor.js +35 -0
  17. package/dist/scenario-runner/adapters/request-executor.js.map +1 -1
  18. package/dist/scenario-runner/adapters/types.d.ts +5 -0
  19. package/dist/scenario-runner/adapters/types.d.ts.map +1 -1
  20. package/dist/scenario-runner/condition.d.ts.map +1 -1
  21. package/dist/scenario-runner/condition.js +67 -3
  22. package/dist/scenario-runner/condition.js.map +1 -1
  23. package/dist/scenario-runner/graphTraversal.d.ts +5 -0
  24. package/dist/scenario-runner/graphTraversal.d.ts.map +1 -1
  25. package/dist/scenario-runner/graphTraversal.js +11 -2
  26. package/dist/scenario-runner/graphTraversal.js.map +1 -1
  27. package/dist/scenario-runner/nodePolicy.d.ts +2 -2
  28. package/dist/scenario-runner/nodePolicy.d.ts.map +1 -1
  29. package/dist/scenario-runner/nodePolicy.js +6 -0
  30. package/dist/scenario-runner/nodePolicy.js.map +1 -1
  31. package/dist/scenario-runner/runScenario.d.ts.map +1 -1
  32. package/dist/scenario-runner/runScenario.js +492 -4
  33. package/dist/scenario-runner/runScenario.js.map +1 -1
  34. package/dist/scenario-runner/types.d.ts +89 -4
  35. package/dist/scenario-runner/types.d.ts.map +1 -1
  36. package/dist/script/types.d.ts +4 -0
  37. package/dist/script/types.d.ts.map +1 -1
  38. package/dist/soap/envelope.d.ts +4 -0
  39. package/dist/soap/envelope.d.ts.map +1 -0
  40. package/dist/soap/envelope.js +25 -0
  41. package/dist/soap/envelope.js.map +1 -0
  42. package/dist/soap/transport.d.ts +22 -0
  43. package/dist/soap/transport.d.ts.map +1 -0
  44. package/dist/soap/transport.js +58 -0
  45. package/dist/soap/transport.js.map +1 -0
  46. package/dist/soap/wsSecurity.d.ts +19 -0
  47. package/dist/soap/wsSecurity.d.ts.map +1 -0
  48. package/dist/soap/wsSecurity.js +66 -0
  49. package/dist/soap/wsSecurity.js.map +1 -0
  50. package/dist-cjs/contract/contractValidator.js +19 -2
  51. package/dist-cjs/contract/contractValidator.js.map +1 -1
  52. package/dist-cjs/contract/xpathResolver.js +76 -0
  53. package/dist-cjs/contract/xpathResolver.js.map +1 -0
  54. package/dist-cjs/index.js +13 -1
  55. package/dist-cjs/index.js.map +1 -1
  56. package/dist-cjs/scenario-runner/adapters/helpers/request-helpers.js +8 -0
  57. package/dist-cjs/scenario-runner/adapters/helpers/request-helpers.js.map +1 -1
  58. package/dist-cjs/scenario-runner/adapters/request-executor.js +35 -0
  59. package/dist-cjs/scenario-runner/adapters/request-executor.js.map +1 -1
  60. package/dist-cjs/scenario-runner/condition.js +67 -3
  61. package/dist-cjs/scenario-runner/condition.js.map +1 -1
  62. package/dist-cjs/scenario-runner/graphTraversal.js +12 -3
  63. package/dist-cjs/scenario-runner/graphTraversal.js.map +1 -1
  64. package/dist-cjs/scenario-runner/nodePolicy.js +6 -0
  65. package/dist-cjs/scenario-runner/nodePolicy.js.map +1 -1
  66. package/dist-cjs/scenario-runner/runScenario.js +491 -3
  67. package/dist-cjs/scenario-runner/runScenario.js.map +1 -1
  68. package/dist-cjs/soap/envelope.js +29 -0
  69. package/dist-cjs/soap/envelope.js.map +1 -0
  70. package/dist-cjs/soap/transport.js +62 -0
  71. package/dist-cjs/soap/transport.js.map +1 -0
  72. package/dist-cjs/soap/wsSecurity.js +74 -0
  73. package/dist-cjs/soap/wsSecurity.js.map +1 -0
  74. package/package.json +4 -2
@@ -36,9 +36,18 @@ const buildTitle = (node) => {
36
36
  return `${node.type[0]?.toUpperCase() ?? ""}${node.type.slice(1)}`;
37
37
  };
38
38
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39
- // `loop`/`loops` are the loop-iteration template roots (see the loop-frame
39
+ // `loop`/`loops` are the loop-iteration template roots and `item`/`each`/
40
+ // `eaches` the foreach-iteration ones (see the loop-frame and foreach
40
41
  // machinery in runScenario) — node labels must not shadow them.
41
- const RESERVED_WORKFLOW_ROOT_LABELS = new Set(["workflow", "__meta", "loop", "loops"]);
42
+ const RESERVED_WORKFLOW_ROOT_LABELS = new Set([
43
+ "workflow",
44
+ "__meta",
45
+ "loop",
46
+ "loops",
47
+ "item",
48
+ "each",
49
+ "eaches",
50
+ ]);
42
51
  const cloneNodeExecutionMeta = (meta) => ({
43
52
  ...meta,
44
53
  ...(meta.error ? { error: { ...meta.error } } : {}),
@@ -403,6 +412,31 @@ const updateRecordFromEvent = (records, event) => {
403
412
  });
404
413
  return;
405
414
  }
415
+ if (event.type === "step:poll") {
416
+ // Tick progress only — the terminal success/fail event owns the rest.
417
+ records.set(event.stepId, {
418
+ ...current,
419
+ stepType: event.stepType,
420
+ title: event.title,
421
+ attempts: event.attempt,
422
+ currentAttempt: event.attempt,
423
+ maxAttempts: event.maxAttempts,
424
+ startedAt: current.startedAt ?? event.at,
425
+ });
426
+ return;
427
+ }
428
+ if (event.type === "step:iteration") {
429
+ // Iteration progress marker only — the terminal success/fail event owns
430
+ // the record. Without this early return the generic fallback below would
431
+ // stamp status:"failed" on the foreach step.
432
+ records.set(event.stepId, {
433
+ ...current,
434
+ stepType: event.stepType,
435
+ title: event.title,
436
+ startedAt: current.startedAt ?? event.at,
437
+ });
438
+ return;
439
+ }
406
440
  if (event.type === "step:condition") {
407
441
  records.set(event.stepId, {
408
442
  ...current,
@@ -495,6 +529,12 @@ const callHandler = async (handlers, event) => {
495
529
  case "step:retry":
496
530
  await handlers?.onNodeRetry?.(event);
497
531
  return;
532
+ case "step:poll":
533
+ await handlers?.onPollTick?.(event);
534
+ return;
535
+ case "step:iteration":
536
+ await handlers?.onForeachIteration?.(event);
537
+ return;
498
538
  case "step:success":
499
539
  await handlers?.onNodeSuccess?.(event);
500
540
  return;
@@ -805,9 +845,18 @@ const runScenario = async ({ scenario, environment = {}, globals = {}, runtimeAd
805
845
  localStatuses.set(stepId, "running");
806
846
  const title = buildTitle(node);
807
847
  const nodeLabel = node.data.label.trim();
808
- const executionPolicy = (0, nodePolicy_js_1.supportsScenarioNodeExecutionPolicy)(node)
848
+ let executionPolicy = (0, nodePolicy_js_1.supportsScenarioNodeExecutionPolicy)(node)
809
849
  ? withNotificationFailurePolicyOverride(node, (0, nodePolicy_js_1.getScenarioNodeExecutionPolicy)(node))
810
850
  : (0, nodePolicy_js_1.getLegacyScenarioNodeExecutionPolicy)();
851
+ if (node.type === "poll" || node.type === "foreach") {
852
+ // The poll/item loop REPLACES per-node retry (nested retry loops would
853
+ // be unexplainable). onFailure — incl. error edges — still governs the
854
+ // final outcome.
855
+ executionPolicy = {
856
+ ...executionPolicy,
857
+ retry: { enabled: false, maxAttempts: 0, delayMs: 0 },
858
+ };
859
+ }
811
860
  const executionStartedAtMs = Date.now();
812
861
  let inputData = createInputSnapshot(runtimeContext);
813
862
  let statusCode = null;
@@ -1025,6 +1074,223 @@ const runScenario = async ({ scenario, environment = {}, globals = {}, runtimeAd
1025
1074
  throw new ScenarioNodeFailureError(redisResult.failureMessage);
1026
1075
  }
1027
1076
  }
1077
+ if (node.type === "poll") {
1078
+ const pollConfig = node.data.config;
1079
+ const blockingPollIssue = (0, condition_js_1.validateConditionConfig)(pollConfig.successCondition).find((issue) => issue.severity === "error");
1080
+ if (blockingPollIssue) {
1081
+ throw new ScenarioNodeFailureError(`Poll success condition is invalid: ${blockingPollIssue.message}`);
1082
+ }
1083
+ const pollStartedAtMs = Date.now();
1084
+ const pollMaxAttempts = Math.min(graphTraversal_js_1.MAX_POLL_ATTEMPTS, Math.max(1, Math.round(pollConfig.maxAttempts ?? graphTraversal_js_1.DEFAULT_POLL_MAX_ATTEMPTS)));
1085
+ const pollBaseIntervalMs = Math.max(0, Math.round(pollConfig.intervalMs ?? graphTraversal_js_1.DEFAULT_POLL_INTERVAL_MS));
1086
+ const pollTimeoutMs = typeof pollConfig.timeoutMs === "number" && pollConfig.timeoutMs > 0
1087
+ ? Math.round(pollConfig.timeoutMs)
1088
+ : null;
1089
+ // Thinned emission keeps stored events bounded (~100 tick events).
1090
+ const pollEmitStride = Math.max(1, Math.ceil(pollMaxAttempts / 100));
1091
+ // One tick = the embedded action through the SAME host adapters real
1092
+ // nodes use (desktop IPC / backend drivers both covered), publishing
1093
+ // results into the runtime context exactly like the real node would,
1094
+ // so the success condition AND downstream nodes read the last
1095
+ // attempt's data. Returns the action's error message, or null.
1096
+ const runPollTick = async () => {
1097
+ const tickValues = (0, templateResolver_js_1.buildScenarioTemplateValues)({
1098
+ environment: runtimeContext.environment,
1099
+ globals: runtimeContext.globals,
1100
+ workflowContext: runtimeContext.workflowContext,
1101
+ nodeMetaByLabel: runtimeContext.nodeMetaByLabel,
1102
+ responseRoot: runtimeContext.responseRoot,
1103
+ dbResult: runtimeContext.dbResult,
1104
+ kafkaEvent: runtimeContext.kafkaEvent,
1105
+ redisResult: runtimeContext.redisResult,
1106
+ });
1107
+ if (pollConfig.actionType === "request") {
1108
+ if (!pollConfig.request) {
1109
+ throw new ScenarioNodeFailureError("Poll node has no request configuration.");
1110
+ }
1111
+ const tickResult = await runtimeAdapters.requestExecutor({
1112
+ runId,
1113
+ stepId,
1114
+ node: {
1115
+ id: node.id,
1116
+ type: "request",
1117
+ position: node.position,
1118
+ data: { label: node.data.label, config: pollConfig.request },
1119
+ },
1120
+ context: createContextSnapshot(runtimeContext),
1121
+ kafkaCapturePlans: [],
1122
+ captureFromTimestampMs: startedAtMs,
1123
+ signal,
1124
+ });
1125
+ if (tickResult.cancelled) {
1126
+ throw new ScenarioStopError();
1127
+ }
1128
+ runtimeContext.environment = { ...tickResult.environment };
1129
+ runtimeContext.globals = { ...tickResult.globals };
1130
+ runtimeContext.lastResponse = tickResult.response;
1131
+ runtimeContext.responseRoot = tickResult.responseRoot;
1132
+ response = tickResult.response;
1133
+ statusCode = tickResult.response.status;
1134
+ testResults = tickResult.testResults;
1135
+ contractResults = tickResult.contractResults;
1136
+ contractSummary = tickResult.contractSummary;
1137
+ contractValidationError = tickResult.contractValidationError;
1138
+ dbAssertionResults = tickResult.dbAssertionResults;
1139
+ redisAssertionResults = tickResult.redisAssertionResults;
1140
+ return tickResult.failureMessage ?? null;
1141
+ }
1142
+ if (pollConfig.actionType === "db") {
1143
+ if (!pollConfig.db) {
1144
+ throw new ScenarioNodeFailureError("Poll node has no database configuration.");
1145
+ }
1146
+ const resolvedQuery = (0, templateResolver_js_1.resolveScenarioTemplateString)(pollConfig.db.query, tickValues);
1147
+ const resolvedParams = (pollConfig.db.params ?? []).map((param) => (0, templateResolver_js_1.resolveScenarioTemplateString)(param, tickValues));
1148
+ const tickResult = await runtimeAdapters.dbExecutor({
1149
+ runId,
1150
+ stepId,
1151
+ node: {
1152
+ id: node.id,
1153
+ type: "db",
1154
+ position: node.position,
1155
+ data: { label: node.data.label, config: pollConfig.db },
1156
+ },
1157
+ resolvedQuery,
1158
+ resolvedParams,
1159
+ context: createContextSnapshot(runtimeContext),
1160
+ signal,
1161
+ });
1162
+ runtimeContext.dbResult = tickResult.dbResult;
1163
+ return tickResult.failureMessage ?? null;
1164
+ }
1165
+ if (pollConfig.actionType === "redis") {
1166
+ if (!pollConfig.redis) {
1167
+ throw new ScenarioNodeFailureError("Poll node has no Redis configuration.");
1168
+ }
1169
+ const resolvedCommands = pollConfig.redis.commands
1170
+ .map((command) => (0, templateResolver_js_1.resolveScenarioTemplateString)(command, tickValues))
1171
+ .filter((command) => command.trim().length > 0);
1172
+ const tickResult = await runtimeAdapters.redisExecutor({
1173
+ runId,
1174
+ stepId,
1175
+ node: {
1176
+ id: node.id,
1177
+ type: "redis",
1178
+ position: node.position,
1179
+ data: { label: node.data.label, config: pollConfig.redis },
1180
+ },
1181
+ resolvedCommands,
1182
+ context: createContextSnapshot(runtimeContext),
1183
+ signal,
1184
+ });
1185
+ runtimeContext.redisResult = tickResult.redisResult;
1186
+ return tickResult.failureMessage ?? null;
1187
+ }
1188
+ if (!pollConfig.script) {
1189
+ throw new ScenarioNodeFailureError("Poll node has no script configuration.");
1190
+ }
1191
+ const tickResult = await runtimeAdapters.scriptExecutor({
1192
+ runId,
1193
+ stepId,
1194
+ node: {
1195
+ id: node.id,
1196
+ type: "script",
1197
+ position: node.position,
1198
+ data: { label: node.data.label, config: pollConfig.script },
1199
+ },
1200
+ context: createContextSnapshot(runtimeContext),
1201
+ signal,
1202
+ });
1203
+ scriptSource = tickResult.scriptSource;
1204
+ scriptTimeoutMs = tickResult.timeoutMs;
1205
+ scriptLogs = tickResult.logs;
1206
+ testResults = tickResult.testResults;
1207
+ applyVariableMutationsToContext(runtimeContext, tickResult.variableMutations);
1208
+ return tickResult.failureMessage ?? null;
1209
+ };
1210
+ let pollAttempt = 0;
1211
+ let pollPassed = false;
1212
+ let lastTickError = null;
1213
+ for (;;) {
1214
+ throwIfStopped(signal);
1215
+ pollAttempt += 1;
1216
+ lastTickError = await runPollTick();
1217
+ if (lastTickError === null) {
1218
+ const evaluation = (0, condition_js_1.evaluateConditionConfig)(pollConfig.successCondition, {
1219
+ environment: runtimeContext.environment,
1220
+ globals: runtimeContext.globals,
1221
+ workflowContext: runtimeContext.workflowContext,
1222
+ nodeMetaByLabel: runtimeContext.nodeMetaByLabel,
1223
+ responseRoot: runtimeContext.responseRoot,
1224
+ dbResult: runtimeContext.dbResult,
1225
+ kafkaEvent: runtimeContext.kafkaEvent,
1226
+ redisResult: runtimeContext.redisResult,
1227
+ });
1228
+ const conditionPayload = (0, condition_js_1.buildConditionOutputPayload)(pollConfig.successCondition, evaluation);
1229
+ conditionResult = evaluation.result;
1230
+ conditionExpression = conditionPayload.expression;
1231
+ conditionPreview = conditionPayload.preview;
1232
+ conditionMode = conditionPayload.mode;
1233
+ conditionDebug = conditionPayload.debug;
1234
+ pollPassed = evaluation.result;
1235
+ }
1236
+ else {
1237
+ conditionResult = false;
1238
+ }
1239
+ const pollElapsedNow = Date.now() - pollStartedAtMs;
1240
+ const budgetExhausted = pollAttempt >= pollMaxAttempts ||
1241
+ (pollTimeoutMs !== null && pollElapsedNow >= pollTimeoutMs);
1242
+ const pollBackoff = pollConfig.backoffMultiplier && pollConfig.backoffMultiplier > 1
1243
+ ? Math.min(10, pollConfig.backoffMultiplier)
1244
+ : 1;
1245
+ const nextDelayMs = pollPassed || budgetExhausted
1246
+ ? null
1247
+ : Math.min(pollConfig.maxDelayMs && pollConfig.maxDelayMs > 0
1248
+ ? Math.round(pollConfig.maxDelayMs)
1249
+ : Number.MAX_SAFE_INTEGER, Math.round(pollBaseIntervalMs * Math.pow(pollBackoff, pollAttempt - 1)));
1250
+ if (pollPassed ||
1251
+ budgetExhausted ||
1252
+ pollAttempt === 1 ||
1253
+ pollAttempt % pollEmitStride === 0) {
1254
+ await emit({
1255
+ type: "step:poll",
1256
+ runId,
1257
+ scenarioId: scenario.id,
1258
+ stepId,
1259
+ stepType: node.type,
1260
+ title,
1261
+ at: new Date().toISOString(),
1262
+ attempt: pollAttempt,
1263
+ maxAttempts: pollMaxAttempts,
1264
+ elapsedMs: pollElapsedNow,
1265
+ timeoutMs: pollTimeoutMs,
1266
+ conditionResult: pollPassed,
1267
+ tickError: lastTickError,
1268
+ nextPollDelayMs: nextDelayMs,
1269
+ });
1270
+ }
1271
+ if (pollPassed || budgetExhausted) {
1272
+ break;
1273
+ }
1274
+ await waitForDuration(nextDelayMs ?? pollBaseIntervalMs);
1275
+ }
1276
+ const pollElapsedMs = Date.now() - pollStartedAtMs;
1277
+ outputData = {
1278
+ attempts: pollAttempt,
1279
+ maxAttempts: pollMaxAttempts,
1280
+ elapsedMs: pollElapsedMs,
1281
+ timedOut: !pollPassed,
1282
+ conditionResult: pollPassed,
1283
+ ...(lastTickError ? { lastTickError } : {}),
1284
+ };
1285
+ if (!pollPassed) {
1286
+ if ((pollConfig.onTimeout ?? "fail") === "continue") {
1287
+ shouldMarkPartialSuccess = true;
1288
+ }
1289
+ else {
1290
+ throw new ScenarioNodeFailureError(`Poll did not succeed within ${pollAttempt} attempt(s) (${pollElapsedMs}ms).${lastTickError ? ` Last error: ${lastTickError}` : ""}`);
1291
+ }
1292
+ }
1293
+ }
1028
1294
  if (node.type === "notification") {
1029
1295
  const resolvedMessage = (0, index_js_1.renderNotificationTemplate)(node.data.config.messageTemplate, templateValues).trim();
1030
1296
  const resolvedChannelOverride = node.data.config.channelOverride?.trim()
@@ -1294,6 +1560,228 @@ const runScenario = async ({ scenario, environment = {}, globals = {}, runtimeAd
1294
1560
  shouldMarkPartialSuccess = degradedStepIds.size > degradedCountBefore;
1295
1561
  outputData = groupedOutput;
1296
1562
  }
1563
+ if (node.type === "foreach") {
1564
+ const foreachConfig = node.data.config;
1565
+ // ── Resolve the items array ──────────────────────────────────────
1566
+ let items;
1567
+ if (foreachConfig.sourceMode === "inline") {
1568
+ const rawInline = (foreachConfig.itemsInline ?? "").trim();
1569
+ if (!rawInline) {
1570
+ throw new ScenarioNodeFailureError("Foreach inline items are empty.");
1571
+ }
1572
+ const resolvedInline = (0, templateResolver_js_1.resolveScenarioJsonTemplateString)(rawInline, templateValues);
1573
+ let parsedInline;
1574
+ try {
1575
+ parsedInline = JSON.parse(resolvedInline);
1576
+ }
1577
+ catch {
1578
+ throw new ScenarioNodeFailureError("Foreach inline items are not valid JSON after template resolution.");
1579
+ }
1580
+ if (!Array.isArray(parsedInline)) {
1581
+ throw new ScenarioNodeFailureError("Foreach inline items must be a JSON array.");
1582
+ }
1583
+ items = parsedInline;
1584
+ }
1585
+ else {
1586
+ const itemsPath = (foreachConfig.itemsPath ?? "").trim();
1587
+ if (!itemsPath) {
1588
+ throw new ScenarioNodeFailureError("Foreach items path is required.");
1589
+ }
1590
+ const resolved = (0, condition_js_1.resolveConditionRuntimeValue)({
1591
+ environment: runtimeContext.environment,
1592
+ globals: runtimeContext.globals,
1593
+ workflowContext: runtimeContext.workflowContext,
1594
+ nodeMetaByLabel: runtimeContext.nodeMetaByLabel,
1595
+ responseRoot: runtimeContext.responseRoot,
1596
+ dbResult: runtimeContext.dbResult,
1597
+ kafkaEvent: runtimeContext.kafkaEvent,
1598
+ redisResult: runtimeContext.redisResult,
1599
+ }, itemsPath);
1600
+ if (!resolved.exists || typeof resolved.value === "undefined") {
1601
+ throw new ScenarioNodeFailureError(`Foreach items path "${itemsPath}" resolved to nothing.`);
1602
+ }
1603
+ if (!Array.isArray(resolved.value)) {
1604
+ throw new ScenarioNodeFailureError(`Foreach items path "${itemsPath}" must resolve to an array (got ${typeof resolved.value}).`);
1605
+ }
1606
+ items = resolved.value;
1607
+ }
1608
+ const itemAlias = (foreachConfig.itemAlias ?? "").trim();
1609
+ if (itemAlias && RESERVED_WORKFLOW_ROOT_LABELS.has(itemAlias)) {
1610
+ throw new ScenarioNodeFailureError(`Foreach item alias "${itemAlias}" is a reserved name.`);
1611
+ }
1612
+ const maxIterations = Math.min(graphTraversal_js_1.MAX_FOREACH_ITERATIONS, Math.max(1, Math.round(foreachConfig.maxIterations ?? graphTraversal_js_1.DEFAULT_FOREACH_MAX_ITERATIONS)));
1613
+ const processLimit = Math.min(items.length, maxIterations);
1614
+ const iterationDelayMs = Math.max(0, Math.round(foreachConfig.delayMs ?? 0));
1615
+ const onItemFailure = foreachConfig.onItemFailure ?? "stop";
1616
+ const collectResults = foreachConfig.collectResults !== false;
1617
+ // Thinned emission keeps stored events bounded (~100 iteration markers).
1618
+ const iterationEmitStride = Math.max(1, Math.ceil(processLimit / 100));
1619
+ const internalGraph = (0, templateResolver_js_1.buildScenarioExecutionGraph)(foreachConfig.nodes, foreachConfig.edges);
1620
+ const internalScope = {
1621
+ graph: internalGraph,
1622
+ stepIdForNode: (childNodeId) => (0, graphTraversal_js_1.createSubScenarioStepId)(stepId, childNodeId),
1623
+ stepIdForEdge: (edgeId) => (0, graphTraversal_js_1.createSubScenarioStepId)(stepId, edgeId),
1624
+ };
1625
+ // ALL descendant step ids (nested containers included) — reset
1626
+ // targets between iterations.
1627
+ const internalStepIds = (0, graphTraversal_js_1.buildRuntimeStepDescriptors)(foreachConfig.nodes, stepId).map((descriptor) => descriptor.stepId);
1628
+ const childLabels = (0, graphTraversal_js_1.flattenScenarioNodesForContext)(foreachConfig.nodes)
1629
+ .map((childNode) => childNode.data.label.trim())
1630
+ .filter((childLabel) => childLabel.length > 0);
1631
+ const workflowRoots = runtimeContext.workflowContext;
1632
+ // Save the enclosing iteration roots so a NESTED foreach restores
1633
+ // its parent's {{item}}/{{each}} when it finishes mid-iteration.
1634
+ const hadItemRoot = Object.prototype.hasOwnProperty.call(workflowRoots, "item");
1635
+ const previousItemRoot = workflowRoots.item;
1636
+ const hadEachRoot = Object.prototype.hasOwnProperty.call(workflowRoots, "each");
1637
+ const previousEachRoot = workflowRoots.each;
1638
+ const hadAliasRoot = itemAlias
1639
+ ? Object.prototype.hasOwnProperty.call(workflowRoots, itemAlias)
1640
+ : false;
1641
+ const previousAliasRoot = itemAlias ? workflowRoots[itemAlias] : undefined;
1642
+ const nodeLabelKey = nodeLabel;
1643
+ const previousEaches = workflowRoots.eaches;
1644
+ const degradedCountBefore = degradedStepIds.size;
1645
+ const results = [];
1646
+ let failedItems = 0;
1647
+ try {
1648
+ for (let index = 0; index < processLimit; index += 1) {
1649
+ throwIfStopped(signal);
1650
+ if (index > 0) {
1651
+ // Fresh pass: every internal step back to idle (including the
1652
+ // "skipped" stamped on unreached nodes last pass), degraded
1653
+ // marks cleared, records reset via the bulk step:reset event.
1654
+ for (const internalStepId of internalStepIds) {
1655
+ localStatuses.set(internalStepId, "idle");
1656
+ degradedStepIds.delete(internalStepId);
1657
+ }
1658
+ await emit({
1659
+ type: "step:reset",
1660
+ runId,
1661
+ scenarioId: scenario.id,
1662
+ stepIds: internalStepIds,
1663
+ at: new Date().toISOString(),
1664
+ reason: `Item ${index + 1}/${processLimit}: reset foreach body`,
1665
+ });
1666
+ if (iterationDelayMs > 0) {
1667
+ await waitForDuration(iterationDelayMs);
1668
+ }
1669
+ }
1670
+ // Fresh-pass isolation: a failed/short-circuited item must not
1671
+ // inherit the previous iteration's child outputs in its results
1672
+ // snapshot. The final iteration's children stay published after
1673
+ // the loop (last-iteration-wins for downstream reads).
1674
+ for (const childLabel of childLabels) {
1675
+ delete workflowRoots[childLabel];
1676
+ }
1677
+ const item = items[index];
1678
+ const frame = {
1679
+ index,
1680
+ iteration: index + 1,
1681
+ total: processLimit,
1682
+ remaining: processLimit - (index + 1),
1683
+ };
1684
+ workflowRoots.item = item;
1685
+ if (itemAlias) {
1686
+ workflowRoots[itemAlias] = item;
1687
+ }
1688
+ workflowRoots.each = frame;
1689
+ if (nodeLabelKey) {
1690
+ const eachesRoot = workflowRoots.eaches && typeof workflowRoots.eaches === "object"
1691
+ ? workflowRoots.eaches
1692
+ : {};
1693
+ workflowRoots.eaches = { ...eachesRoot, [nodeLabelKey]: frame };
1694
+ }
1695
+ if (index === 0 ||
1696
+ index === processLimit - 1 ||
1697
+ (index + 1) % iterationEmitStride === 0) {
1698
+ const itemPreview = (() => {
1699
+ try {
1700
+ const serialized = JSON.stringify(item);
1701
+ if (typeof serialized !== "string")
1702
+ return String(item);
1703
+ return serialized.length > 2048 ? `${serialized.slice(0, 2048)}…` : serialized;
1704
+ }
1705
+ catch {
1706
+ return null;
1707
+ }
1708
+ })();
1709
+ await emit({
1710
+ type: "step:iteration",
1711
+ runId,
1712
+ scenarioId: scenario.id,
1713
+ stepId,
1714
+ stepType: node.type,
1715
+ title,
1716
+ at: new Date().toISOString(),
1717
+ index,
1718
+ iteration: index + 1,
1719
+ total: processLimit,
1720
+ itemPreview,
1721
+ });
1722
+ }
1723
+ try {
1724
+ for (const startNodeId of internalGraph.startNodeIds) {
1725
+ throwIfStopped(signal);
1726
+ await executeNode(startNodeId, null, {}, internalScope);
1727
+ }
1728
+ await markScopeRemainingNodesSkipped(internalScope, `Internal node was not reached inside ${title} (item ${index + 1}).`);
1729
+ }
1730
+ catch (error) {
1731
+ if (error instanceof ScenarioStopError) {
1732
+ throw error;
1733
+ }
1734
+ failedItems += 1;
1735
+ if (onItemFailure === "stop") {
1736
+ const message = error instanceof Error ? error.message : String(error);
1737
+ throw new ScenarioNodeFailureError(`Foreach item ${index + 1}/${processLimit} failed: ${message}`);
1738
+ }
1739
+ // continue: unreached internal nodes stay consistent for the
1740
+ // report, the run degrades to partial success below.
1741
+ await markScopeRemainingNodesSkipped(internalScope, `Internal node was not reached inside ${title} (item ${index + 1} failed).`);
1742
+ }
1743
+ if (collectResults) {
1744
+ const iterationOutput = {};
1745
+ for (const childLabel of childLabels) {
1746
+ if (Object.prototype.hasOwnProperty.call(workflowRoots, childLabel)) {
1747
+ iterationOutput[childLabel] = workflowRoots[childLabel];
1748
+ }
1749
+ }
1750
+ results.push(iterationOutput);
1751
+ }
1752
+ }
1753
+ }
1754
+ finally {
1755
+ // Restore the enclosing iteration roots (or clear ours).
1756
+ if (hadItemRoot)
1757
+ workflowRoots.item = previousItemRoot;
1758
+ else
1759
+ delete workflowRoots.item;
1760
+ if (hadEachRoot)
1761
+ workflowRoots.each = previousEachRoot;
1762
+ else
1763
+ delete workflowRoots.each;
1764
+ if (itemAlias) {
1765
+ if (hadAliasRoot)
1766
+ workflowRoots[itemAlias] = previousAliasRoot;
1767
+ else
1768
+ delete workflowRoots[itemAlias];
1769
+ }
1770
+ if (typeof previousEaches === "undefined")
1771
+ delete workflowRoots.eaches;
1772
+ else
1773
+ workflowRoots.eaches = previousEaches;
1774
+ }
1775
+ shouldMarkPartialSuccess =
1776
+ degradedStepIds.size > degradedCountBefore || failedItems > 0;
1777
+ outputData = {
1778
+ ...(collectResults ? { results } : {}),
1779
+ itemCount: items.length,
1780
+ processedCount: processLimit,
1781
+ truncated: items.length > processLimit,
1782
+ failedItems,
1783
+ };
1784
+ }
1297
1785
  if (node.type === "end") {
1298
1786
  if (node.data.config.loop && node.data.config.loopTargetNodeId) {
1299
1787
  const loopTargetNode = scope.graph.nodeMap.get(node.data.config.loopTargetNodeId);