deno.land / x / xstate@xstate@4.33.6 / src / json.ts

نووسراو ببینە
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
import { StateNode, ActionObject, Guard, InvokeDefinition } from './';import { mapValues, isFunction } from './utils';
interface JSONFunction { $function: string;}
// tslint:disable-next-line:ban-typesexport function stringifyFunction(fn: Function): JSONFunction { return { $function: fn.toString() };}
function getStateNodeId(stateNode: StateNode): string { return `#${stateNode.id}`;}
interface TransitionConfig { target: string[]; source: string; actions: Array<ActionObject<any, any>>; cond: Guard<any, any> | undefined; eventType: string;}
interface StateNodeConfig { type: StateNode['type']; id: string; key: string; initial?: string; entry: Array<ActionObject<any, any>>; exit: Array<ActionObject<any, any>>; on: { [key: string]: TransitionConfig[]; }; invoke: Array<InvokeDefinition<any, any>>; states: Record<string, StateNodeConfig>;}
// derive config from machineexport function machineToJSON(stateNode: StateNode): StateNodeConfig { const config = { type: stateNode.type, initial: stateNode.initial === undefined ? undefined : String(stateNode.initial), id: stateNode.id, key: stateNode.key, entry: stateNode.onEntry, exit: stateNode.onExit, on: mapValues(stateNode.on, (transition) => { return transition.map((t) => { return { target: t.target ? t.target.map(getStateNodeId) : [], source: getStateNodeId(t.source), actions: t.actions, cond: t.cond, eventType: t.eventType }; }); }), invoke: stateNode.invoke, states: {} };
Object.values(stateNode.states).forEach((sn) => { config.states[sn.key] = machineToJSON(sn); });
return config;}
export function stringify(machine: StateNode): string { return JSON.stringify(machineToJSON(machine), (_, value) => { if (isFunction(value)) { return { $function: value.toString() }; } return value; });}
export function parse(machineString: string): StateNodeConfig { const config = JSON.parse(machineString, (_, value) => { if (typeof value === 'object' && '$function' in value) { return new Function(value.value); }
return value; });
return config;}
export function jsonify<T extends Record<string, any>>(value: T): T { Object.defineProperty(value, 'toJSON', { value: () => mapValues(value, (subValue) => { if (isFunction(subValue)) { return stringifyFunction(subValue); } else if (typeof subValue === 'object' && !Array.isArray(subValue)) { // mostly for assignments return mapValues(subValue, (subSubValue) => { if (isFunction(subSubValue)) { return stringifyFunction(subSubValue); } return subSubValue; }); }
return subValue; }) });
return value;}
xstate

Version Info

Tagged at
2 years ago