callman-core 1.17.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.
@@ -1,7 +1,7 @@
1
1
  import { buildConditionOutputPayload, evaluateConditionConfig, evaluateConditionRule, resolveConditionRuntimeValue, validateConditionConfig, } from "./condition.js";
2
2
  import { applyExtract } from "./extraction.js";
3
3
  import { evaluateAssertionConfig, validateAssertionConfig, } from "./assertion.js";
4
- import { createSubScenarioStepId, buildRuntimeStepDescriptors, DEFAULT_END_LOOP_DELAY_MS, DEFAULT_END_LOOP_ITERATIONS, flattenScenarioNodesForContext, MAX_END_LOOP_ITERATIONS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_POLL_MAX_ATTEMPTS, MAX_POLL_ATTEMPTS, } from "./graphTraversal.js";
4
+ import { createSubScenarioStepId, buildRuntimeStepDescriptors, DEFAULT_END_LOOP_DELAY_MS, DEFAULT_END_LOOP_ITERATIONS, flattenScenarioNodesForContext, MAX_END_LOOP_ITERATIONS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_POLL_MAX_ATTEMPTS, MAX_POLL_ATTEMPTS, DEFAULT_FOREACH_MAX_ITERATIONS, MAX_FOREACH_ITERATIONS, } from "./graphTraversal.js";
5
5
  import { executeWithScenarioNodePolicy } from "./executionPolicyRunner.js";
6
6
  import { getLegacyScenarioNodeExecutionPolicy, getScenarioNodeExecutionPolicy, supportsScenarioNodeExecutionPolicy, } from "./nodePolicy.js";
7
7
  import { buildScenarioExecutionGraph, buildScenarioTemplateValues, collectExclusiveBranchNodeIds, evaluateScenarioExpression, resolveScenarioJsonTemplateString, resolveScenarioTemplateString, } from "./templateResolver.js";
@@ -33,9 +33,18 @@ const buildTitle = (node) => {
33
33
  return `${node.type[0]?.toUpperCase() ?? ""}${node.type.slice(1)}`;
34
34
  };
35
35
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
36
- // `loop`/`loops` are the loop-iteration template roots (see the loop-frame
36
+ // `loop`/`loops` are the loop-iteration template roots and `item`/`each`/
37
+ // `eaches` the foreach-iteration ones (see the loop-frame and foreach
37
38
  // machinery in runScenario) — node labels must not shadow them.
38
- const RESERVED_WORKFLOW_ROOT_LABELS = new Set(["workflow", "__meta", "loop", "loops"]);
39
+ const RESERVED_WORKFLOW_ROOT_LABELS = new Set([
40
+ "workflow",
41
+ "__meta",
42
+ "loop",
43
+ "loops",
44
+ "item",
45
+ "each",
46
+ "eaches",
47
+ ]);
39
48
  const cloneNodeExecutionMeta = (meta) => ({
40
49
  ...meta,
41
50
  ...(meta.error ? { error: { ...meta.error } } : {}),
@@ -413,6 +422,18 @@ const updateRecordFromEvent = (records, event) => {
413
422
  });
414
423
  return;
415
424
  }
425
+ if (event.type === "step:iteration") {
426
+ // Iteration progress marker only — the terminal success/fail event owns
427
+ // the record. Without this early return the generic fallback below would
428
+ // stamp status:"failed" on the foreach step.
429
+ records.set(event.stepId, {
430
+ ...current,
431
+ stepType: event.stepType,
432
+ title: event.title,
433
+ startedAt: current.startedAt ?? event.at,
434
+ });
435
+ return;
436
+ }
416
437
  if (event.type === "step:condition") {
417
438
  records.set(event.stepId, {
418
439
  ...current,
@@ -508,6 +529,9 @@ const callHandler = async (handlers, event) => {
508
529
  case "step:poll":
509
530
  await handlers?.onPollTick?.(event);
510
531
  return;
532
+ case "step:iteration":
533
+ await handlers?.onForeachIteration?.(event);
534
+ return;
511
535
  case "step:success":
512
536
  await handlers?.onNodeSuccess?.(event);
513
537
  return;
@@ -821,10 +845,10 @@ export const runScenario = async ({ scenario, environment = {}, globals = {}, ru
821
845
  let executionPolicy = supportsScenarioNodeExecutionPolicy(node)
822
846
  ? withNotificationFailurePolicyOverride(node, getScenarioNodeExecutionPolicy(node))
823
847
  : getLegacyScenarioNodeExecutionPolicy();
824
- if (node.type === "poll") {
825
- // The poll loop REPLACES per-node retry (nested retry loops would be
826
- // unexplainable). onFailure — incl. error edges — still governs the
827
- // timeout outcome.
848
+ if (node.type === "poll" || node.type === "foreach") {
849
+ // The poll/item loop REPLACES per-node retry (nested retry loops would
850
+ // be unexplainable). onFailure — incl. error edges — still governs the
851
+ // final outcome.
828
852
  executionPolicy = {
829
853
  ...executionPolicy,
830
854
  retry: { enabled: false, maxAttempts: 0, delayMs: 0 },
@@ -1533,6 +1557,228 @@ export const runScenario = async ({ scenario, environment = {}, globals = {}, ru
1533
1557
  shouldMarkPartialSuccess = degradedStepIds.size > degradedCountBefore;
1534
1558
  outputData = groupedOutput;
1535
1559
  }
1560
+ if (node.type === "foreach") {
1561
+ const foreachConfig = node.data.config;
1562
+ // ── Resolve the items array ──────────────────────────────────────
1563
+ let items;
1564
+ if (foreachConfig.sourceMode === "inline") {
1565
+ const rawInline = (foreachConfig.itemsInline ?? "").trim();
1566
+ if (!rawInline) {
1567
+ throw new ScenarioNodeFailureError("Foreach inline items are empty.");
1568
+ }
1569
+ const resolvedInline = resolveScenarioJsonTemplateString(rawInline, templateValues);
1570
+ let parsedInline;
1571
+ try {
1572
+ parsedInline = JSON.parse(resolvedInline);
1573
+ }
1574
+ catch {
1575
+ throw new ScenarioNodeFailureError("Foreach inline items are not valid JSON after template resolution.");
1576
+ }
1577
+ if (!Array.isArray(parsedInline)) {
1578
+ throw new ScenarioNodeFailureError("Foreach inline items must be a JSON array.");
1579
+ }
1580
+ items = parsedInline;
1581
+ }
1582
+ else {
1583
+ const itemsPath = (foreachConfig.itemsPath ?? "").trim();
1584
+ if (!itemsPath) {
1585
+ throw new ScenarioNodeFailureError("Foreach items path is required.");
1586
+ }
1587
+ const resolved = resolveConditionRuntimeValue({
1588
+ environment: runtimeContext.environment,
1589
+ globals: runtimeContext.globals,
1590
+ workflowContext: runtimeContext.workflowContext,
1591
+ nodeMetaByLabel: runtimeContext.nodeMetaByLabel,
1592
+ responseRoot: runtimeContext.responseRoot,
1593
+ dbResult: runtimeContext.dbResult,
1594
+ kafkaEvent: runtimeContext.kafkaEvent,
1595
+ redisResult: runtimeContext.redisResult,
1596
+ }, itemsPath);
1597
+ if (!resolved.exists || typeof resolved.value === "undefined") {
1598
+ throw new ScenarioNodeFailureError(`Foreach items path "${itemsPath}" resolved to nothing.`);
1599
+ }
1600
+ if (!Array.isArray(resolved.value)) {
1601
+ throw new ScenarioNodeFailureError(`Foreach items path "${itemsPath}" must resolve to an array (got ${typeof resolved.value}).`);
1602
+ }
1603
+ items = resolved.value;
1604
+ }
1605
+ const itemAlias = (foreachConfig.itemAlias ?? "").trim();
1606
+ if (itemAlias && RESERVED_WORKFLOW_ROOT_LABELS.has(itemAlias)) {
1607
+ throw new ScenarioNodeFailureError(`Foreach item alias "${itemAlias}" is a reserved name.`);
1608
+ }
1609
+ const maxIterations = Math.min(MAX_FOREACH_ITERATIONS, Math.max(1, Math.round(foreachConfig.maxIterations ?? DEFAULT_FOREACH_MAX_ITERATIONS)));
1610
+ const processLimit = Math.min(items.length, maxIterations);
1611
+ const iterationDelayMs = Math.max(0, Math.round(foreachConfig.delayMs ?? 0));
1612
+ const onItemFailure = foreachConfig.onItemFailure ?? "stop";
1613
+ const collectResults = foreachConfig.collectResults !== false;
1614
+ // Thinned emission keeps stored events bounded (~100 iteration markers).
1615
+ const iterationEmitStride = Math.max(1, Math.ceil(processLimit / 100));
1616
+ const internalGraph = buildScenarioExecutionGraph(foreachConfig.nodes, foreachConfig.edges);
1617
+ const internalScope = {
1618
+ graph: internalGraph,
1619
+ stepIdForNode: (childNodeId) => createSubScenarioStepId(stepId, childNodeId),
1620
+ stepIdForEdge: (edgeId) => createSubScenarioStepId(stepId, edgeId),
1621
+ };
1622
+ // ALL descendant step ids (nested containers included) — reset
1623
+ // targets between iterations.
1624
+ const internalStepIds = buildRuntimeStepDescriptors(foreachConfig.nodes, stepId).map((descriptor) => descriptor.stepId);
1625
+ const childLabels = flattenScenarioNodesForContext(foreachConfig.nodes)
1626
+ .map((childNode) => childNode.data.label.trim())
1627
+ .filter((childLabel) => childLabel.length > 0);
1628
+ const workflowRoots = runtimeContext.workflowContext;
1629
+ // Save the enclosing iteration roots so a NESTED foreach restores
1630
+ // its parent's {{item}}/{{each}} when it finishes mid-iteration.
1631
+ const hadItemRoot = Object.prototype.hasOwnProperty.call(workflowRoots, "item");
1632
+ const previousItemRoot = workflowRoots.item;
1633
+ const hadEachRoot = Object.prototype.hasOwnProperty.call(workflowRoots, "each");
1634
+ const previousEachRoot = workflowRoots.each;
1635
+ const hadAliasRoot = itemAlias
1636
+ ? Object.prototype.hasOwnProperty.call(workflowRoots, itemAlias)
1637
+ : false;
1638
+ const previousAliasRoot = itemAlias ? workflowRoots[itemAlias] : undefined;
1639
+ const nodeLabelKey = nodeLabel;
1640
+ const previousEaches = workflowRoots.eaches;
1641
+ const degradedCountBefore = degradedStepIds.size;
1642
+ const results = [];
1643
+ let failedItems = 0;
1644
+ try {
1645
+ for (let index = 0; index < processLimit; index += 1) {
1646
+ throwIfStopped(signal);
1647
+ if (index > 0) {
1648
+ // Fresh pass: every internal step back to idle (including the
1649
+ // "skipped" stamped on unreached nodes last pass), degraded
1650
+ // marks cleared, records reset via the bulk step:reset event.
1651
+ for (const internalStepId of internalStepIds) {
1652
+ localStatuses.set(internalStepId, "idle");
1653
+ degradedStepIds.delete(internalStepId);
1654
+ }
1655
+ await emit({
1656
+ type: "step:reset",
1657
+ runId,
1658
+ scenarioId: scenario.id,
1659
+ stepIds: internalStepIds,
1660
+ at: new Date().toISOString(),
1661
+ reason: `Item ${index + 1}/${processLimit}: reset foreach body`,
1662
+ });
1663
+ if (iterationDelayMs > 0) {
1664
+ await waitForDuration(iterationDelayMs);
1665
+ }
1666
+ }
1667
+ // Fresh-pass isolation: a failed/short-circuited item must not
1668
+ // inherit the previous iteration's child outputs in its results
1669
+ // snapshot. The final iteration's children stay published after
1670
+ // the loop (last-iteration-wins for downstream reads).
1671
+ for (const childLabel of childLabels) {
1672
+ delete workflowRoots[childLabel];
1673
+ }
1674
+ const item = items[index];
1675
+ const frame = {
1676
+ index,
1677
+ iteration: index + 1,
1678
+ total: processLimit,
1679
+ remaining: processLimit - (index + 1),
1680
+ };
1681
+ workflowRoots.item = item;
1682
+ if (itemAlias) {
1683
+ workflowRoots[itemAlias] = item;
1684
+ }
1685
+ workflowRoots.each = frame;
1686
+ if (nodeLabelKey) {
1687
+ const eachesRoot = workflowRoots.eaches && typeof workflowRoots.eaches === "object"
1688
+ ? workflowRoots.eaches
1689
+ : {};
1690
+ workflowRoots.eaches = { ...eachesRoot, [nodeLabelKey]: frame };
1691
+ }
1692
+ if (index === 0 ||
1693
+ index === processLimit - 1 ||
1694
+ (index + 1) % iterationEmitStride === 0) {
1695
+ const itemPreview = (() => {
1696
+ try {
1697
+ const serialized = JSON.stringify(item);
1698
+ if (typeof serialized !== "string")
1699
+ return String(item);
1700
+ return serialized.length > 2048 ? `${serialized.slice(0, 2048)}…` : serialized;
1701
+ }
1702
+ catch {
1703
+ return null;
1704
+ }
1705
+ })();
1706
+ await emit({
1707
+ type: "step:iteration",
1708
+ runId,
1709
+ scenarioId: scenario.id,
1710
+ stepId,
1711
+ stepType: node.type,
1712
+ title,
1713
+ at: new Date().toISOString(),
1714
+ index,
1715
+ iteration: index + 1,
1716
+ total: processLimit,
1717
+ itemPreview,
1718
+ });
1719
+ }
1720
+ try {
1721
+ for (const startNodeId of internalGraph.startNodeIds) {
1722
+ throwIfStopped(signal);
1723
+ await executeNode(startNodeId, null, {}, internalScope);
1724
+ }
1725
+ await markScopeRemainingNodesSkipped(internalScope, `Internal node was not reached inside ${title} (item ${index + 1}).`);
1726
+ }
1727
+ catch (error) {
1728
+ if (error instanceof ScenarioStopError) {
1729
+ throw error;
1730
+ }
1731
+ failedItems += 1;
1732
+ if (onItemFailure === "stop") {
1733
+ const message = error instanceof Error ? error.message : String(error);
1734
+ throw new ScenarioNodeFailureError(`Foreach item ${index + 1}/${processLimit} failed: ${message}`);
1735
+ }
1736
+ // continue: unreached internal nodes stay consistent for the
1737
+ // report, the run degrades to partial success below.
1738
+ await markScopeRemainingNodesSkipped(internalScope, `Internal node was not reached inside ${title} (item ${index + 1} failed).`);
1739
+ }
1740
+ if (collectResults) {
1741
+ const iterationOutput = {};
1742
+ for (const childLabel of childLabels) {
1743
+ if (Object.prototype.hasOwnProperty.call(workflowRoots, childLabel)) {
1744
+ iterationOutput[childLabel] = workflowRoots[childLabel];
1745
+ }
1746
+ }
1747
+ results.push(iterationOutput);
1748
+ }
1749
+ }
1750
+ }
1751
+ finally {
1752
+ // Restore the enclosing iteration roots (or clear ours).
1753
+ if (hadItemRoot)
1754
+ workflowRoots.item = previousItemRoot;
1755
+ else
1756
+ delete workflowRoots.item;
1757
+ if (hadEachRoot)
1758
+ workflowRoots.each = previousEachRoot;
1759
+ else
1760
+ delete workflowRoots.each;
1761
+ if (itemAlias) {
1762
+ if (hadAliasRoot)
1763
+ workflowRoots[itemAlias] = previousAliasRoot;
1764
+ else
1765
+ delete workflowRoots[itemAlias];
1766
+ }
1767
+ if (typeof previousEaches === "undefined")
1768
+ delete workflowRoots.eaches;
1769
+ else
1770
+ workflowRoots.eaches = previousEaches;
1771
+ }
1772
+ shouldMarkPartialSuccess =
1773
+ degradedStepIds.size > degradedCountBefore || failedItems > 0;
1774
+ outputData = {
1775
+ ...(collectResults ? { results } : {}),
1776
+ itemCount: items.length,
1777
+ processedCount: processLimit,
1778
+ truncated: items.length > processLimit,
1779
+ failedItems,
1780
+ };
1781
+ }
1536
1782
  if (node.type === "end") {
1537
1783
  if (node.data.config.loop && node.data.config.loopTargetNodeId) {
1538
1784
  const loopTargetNode = scope.graph.nodeMap.get(node.data.config.loopTargetNodeId);