All files introspectMachine.ts

98.99% Statements 98/99
80.91% Branches 89/110
100% Functions 29/29
100% Lines 93/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 2262x   2x 2x               2x 12x 35x     12x 35x     23x         12x     2x                   35x   35x   35x 35x       11x         86x     23x 23x               2x   2x 12x 12x 12x           12x 12x   12x 35x     12x 35x           12x 35x 23x         35x 4x 1x 1x       35x 3x 2x 1x       35x 13x   11x     13x 1x 1x 1x   1x       13x       3x   3x 1x 2x 1x   2x       13x 13x 3x 2x 2x   2x   3x                 12x 35x 35x 35x   35x 3x 3x 3x       35x 2x 2x 1x       1x         12x 1x 1x   1x 1x           12x 5x 5x   4x 4x           12x 2x 2x   2x 2x           12x   12x                  
import 'colors';
import * as XState from 'xstate';
import { toStateValue, toStatePaths, pathToStateValue } from 'xstate/lib/utils';
import { getTransitionsFromNode } from './traversalUtils';
 
export interface SubState {
  targets: string;
  sources: string;
  states: Record<string, SubState>;
}
 
export const getMatchesStates = (machine: XState.StateNode) => {
  const allStateNodes = machine.stateIds.map((id) =>
    machine.getStateNodeById(id),
  );
 
  const states = allStateNodes.reduce((arr: string[], node) => {
    return [
      ...arr,
      ...toStatePaths(pathToStateValue(node.path)).map((path) =>
        path.join('.'),
      ),
    ];
  }, [] as string[]);
 
  return states;
};
 
const makeSubStateFromNode = (
  node: XState.StateNode,
  rootNode: XState.StateNode,
  nodeMaps: {
    [id: string]: {
      sources: Set<string>;
      children: Set<string>;
    };
  },
): SubState => {
  const nodeFromMap = nodeMaps[node.id];
 
  const stateNode = rootNode.getStateNodeById(node.id);
 
  const targets = getTransitionsFromNode(stateNode);
  return {
    sources:
      Array.from(nodeFromMap.sources)
        .filter(Boolean)
        .map((event) => `'${event}'`)
        .join(' | ') || 'never',
    targets:
      Array.from(targets)
        .filter(Boolean)
        .map((event) => `'${event}'`)
        .join(' | ') || 'never',
    states: Array.from(nodeFromMap.children).reduce((obj, child) => {
      const childNode = rootNode.getStateNodeById(child);
      return {
        ...obj,
        [childNode.key]: makeSubStateFromNode(childNode, rootNode, nodeMaps),
      };
    }, {}),
  };
};
 
const xstateRegex = /^xstate\./;
 
export const introspectMachine = (machine: XState.StateNode) => {
  const actionMaps: { [name: string]: Set<string> } = {};
  const condMaps: { [name: string]: Set<string> } = {};
  const servicesMaps: { [name: string]: Set<string> } = {};
  const nodeMaps: {
    [id: string]: {
      sources: Set<string>;
      children: Set<string>;
    };
  } = {};
  let activities: string[] = [];
 
  const allStateNodes = machine.stateIds.map((id) =>
    machine.getStateNodeById(id),
  );
 
  allStateNodes?.forEach((node) => {
    nodeMaps[node.id] = {
      sources: new Set(),
      children: new Set(),
    };
  });
 
  allStateNodes?.forEach((node) => {
    Object.values(node.states)?.forEach((childNode) => {
      nodeMaps[node.id].children.add(childNode.id);
    });
 
    // TODO - make activities pick up the events
    // that led to them
    node.activities?.forEach((activity) => {
      if (/\./.test(activity.type)) return;
      Eif (activity.type && activity.type !== 'xstate.invoke') {
        activities.push(activity.type);
      }
    });
 
    node.invoke?.forEach((service) => {
      if (typeof service.src !== 'string' || /\./.test(service.src)) return;
      if (!servicesMaps[service.src]) {
        servicesMaps[service.src] = new Set();
      }
    });
 
    node.transitions?.forEach((transition) => {
      ((transition.target as unknown) as XState.StateNode[])?.forEach(
        (targetNode) => {
          nodeMaps[targetNode.id].sources.add(transition.eventType);
        },
      );
      if (transition.cond && transition.cond.name) {
        Eif (transition.cond.name !== 'cond') {
          Eif (!condMaps[transition.cond.name]) {
            condMaps[transition.cond.name] = new Set();
          }
          condMaps[transition.cond.name].add(transition.eventType);
        }
      }
 
      if (
        ((transition.target as unknown) as XState.StateNode[])?.[0].invoke
          ?.length > 0
      ) {
        ((transition.target as unknown) as XState.StateNode[])?.[0].invoke?.forEach(
          (service) => {
            if (typeof service.src !== 'string' || /\./.test(service.src))
              return;
            if (!servicesMaps[service.src]) {
              servicesMaps[service.src] = new Set();
            }
            servicesMaps[service.src].add(transition.eventType);
          },
        );
      }
      Eif (transition.actions) {
        transition.actions?.forEach((action) => {
          if (!xstateRegex.test(action.type)) {
            Eif (!actionMaps[action.type]) {
              actionMaps[action.type] = new Set();
            }
            actionMaps[action.type].add(transition.eventType);
          }
          return {
            name: action.type,
            event: transition.eventType,
          };
        });
      }
    });
  });
 
  allStateNodes?.forEach((node) => {
    const allActions: XState.ActionObject<any, any>[] = [];
    allActions.push(...node.onExit);
    allActions.push(...node.onEntry);
 
    allActions?.forEach((action) => {
      Iif (xstateRegex.test(action.type) || action.exec) return;
      Eif (!actionMaps[action.type]) {
        actionMaps[action.type] = new Set();
      }
    });
 
    node.onEntry?.forEach((action) => {
      const sources = nodeMaps[node.id].sources;
      sources?.forEach((source) => {
        Iif (!actionMaps[action.type]) {
          /* istanbul ignore next */
          actionMaps[action.type] = new Set();
        }
        actionMaps[action.type].add(source);
      });
    });
  });
 
  const condLines = Object.entries(condMaps)
    .filter(([name]) => {
      return !/\./.test(name);
    })
    .map(([name, eventSet]) => {
      return {
        name,
        events: Array.from(eventSet).filter(Boolean),
      };
    });
 
  const actionLines = Object.entries(actionMaps)
    .filter(([name]) => {
      return !/\./.test(name);
    })
    .map(([name, eventSet]) => {
      return {
        name,
        events: Array.from(eventSet).filter(Boolean),
      };
    });
 
  const serviceLines = Object.entries(servicesMaps)
    .filter(([name]) => {
      return !/\./.test(name);
    })
    .map(([name, serviceSet]) => {
      return {
        name,
        events: Array.from(serviceSet).filter(Boolean),
      };
    });
 
  const subState: SubState = makeSubStateFromNode(machine, machine, nodeMaps);
 
  return {
    stateMatches: getMatchesStates(machine),
    subState,
    condLines,
    actionLines,
    services: serviceLines,
    activities: Array.from(activities),
  };
};