Skip to content
This repository has been archived by the owner on Feb 25, 2024. It is now read-only.

Fixed an issue with machines created by withConfig/withContext not being captured #301

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions src/parseMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@ import realmsShim from 'realms-shim';

const realm = realmsShim.makeRootRealm();

const wrapCallbackToPreventThis =
(callback: (...args: any[]) => void) =>
(...args: any[]) => {
function wrapToPreventThis<F extends (...args: any[]) => any>(callback: F): F {
const wrapped: any = (...args: any[]) => {
return callback(...args);
};
return wrapped;
}

const windowShim = {
setInterval: (callback: (...args: any[]) => void, ...args: any[]) => {
return setInterval(wrapCallbackToPreventThis(callback), ...args);
return setInterval(wrapToPreventThis(callback), ...args);
},
setTimeout: (callback: (...args: any[]) => void, ...args: any[]) => {
return setTimeout(wrapCallbackToPreventThis(callback), ...args);
return setTimeout(wrapToPreventThis(callback), ...args);
},
clearTimeout: (...args: any[]) => {
return clearTimeout(...args);
Expand All @@ -30,11 +31,18 @@ const windowShim = {
export function parseMachines(sourceJs: string): Array<StateNode> {
const machines: Array<StateNode> = [];

const createMachineCapturer =
(machineFactory: any) =>
(...args: any[]) => {
const machine = machineFactory(...args);
const createMachineCapturer = (machineFactory: any) =>
function (...args: any[]) {
const machine = machineFactory.apply(
// @ts-ignore
this as any,
args,
);
machines.push(machine);

machine.withConfig = createMachineCapturer(machine.withConfig);
machine.withContext = createMachineCapturer(machine.withContext);

return machine;
};

Expand All @@ -47,8 +55,10 @@ export function parseMachines(sourceJs: string): Array<StateNode> {
case 'xstate':
return {
...XState,
createMachine: createMachineCapturer(XState.createMachine),
Machine: createMachineCapturer(XState.Machine),
createMachine: createMachineCapturer(
wrapToPreventThis(XState.createMachine),
),
Machine: createMachineCapturer(wrapToPreventThis(XState.Machine)),
};
case 'xstate/lib/actions':
return XStateActions;
Expand Down