gdp-wired 0.25.0 → 0.27.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.
- package/README.md +14 -9
- package/dist/core/accel.d.ts +20 -1
- package/dist/core/accel.js +797 -220
- package/dist/core/bmc.d.ts +12 -1
- package/dist/core/bmc.js +275 -106
- package/dist/core/cycles.d.ts +2 -3
- package/dist/core/cycles.js +35 -131
- package/dist/core/cyclic.d.ts +4 -1
- package/dist/core/cyclic.js +103 -74
- package/dist/core/data.d.ts +1 -1
- package/dist/core/data.js +89 -118
- package/dist/core/discover.js +65 -27
- package/dist/core/dsl.d.ts +3 -2
- package/dist/core/dsl.js +29 -25
- package/dist/core/exists.js +7 -14
- package/dist/core/extract-check.d.ts +55 -4
- package/dist/core/extract-check.js +248 -122
- package/dist/core/extract-print.d.ts +1 -0
- package/dist/core/extract-print.js +26 -3
- package/dist/core/extract-read.d.ts +98 -4
- package/dist/core/extract-read.js +306 -43
- package/dist/core/extract-shapes.d.ts +14 -0
- package/dist/core/extract-shapes.js +609 -79
- package/dist/core/extract-xstate.d.ts +5 -1
- package/dist/core/extract-xstate.js +618 -184
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +81 -30
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +126 -64
- package/dist/core/machine.d.ts +6 -0
- package/dist/core/machine.js +35 -4
- package/dist/core/nonterm.d.ts +5 -1
- package/dist/core/nonterm.js +133 -45
- package/dist/core/q.d.ts +1 -0
- package/dist/core/q.js +2 -2
- package/dist/core/relation.d.ts +1 -0
- package/dist/core/relation.js +20 -36
- package/dist/core/solver.d.ts +33 -0
- package/dist/core/solver.js +84 -30
- package/dist/core/transfer.js +22 -13
- package/dist/core/translate.d.ts +1 -1
- package/dist/core/translate.js +88 -65
- package/dist/core/xstate.d.ts +6 -1
- package/dist/core/xstate.js +336 -55
- package/dist/kernel/cdcl.js +212 -79
- package/dist/kernel/prove.d.ts +36 -5
- package/dist/kernel/prove.js +212 -104
- package/dist/kernel/reader.d.ts +75 -5
- package/dist/kernel/reader.js +533 -76
- package/dist/kernel/simplex.d.ts +27 -2
- package/dist/kernel/simplex.js +160 -14
- package/package.json +3 -2
package/dist/core/xstate.js
CHANGED
|
@@ -14,29 +14,42 @@
|
|
|
14
14
|
// c.check(); c.prove([c.law('retries stay within 2', ({retries}) => retries.atMost(2))])
|
|
15
15
|
// conforms(c, machine, createActor) // {checked, failure?}
|
|
16
16
|
//
|
|
17
|
+
// An invoked actor and a timer are the world's: each answer of an actor (its done and its error) and each timer firing is
|
|
18
|
+
// an event from outside, named as XState names it (`xstate.done.actor.<id>`, `xstate.after.<delay>.<state id>`; v4's
|
|
19
|
+
// `done.invoke.<id>`, `xstate.after(<delay>)#<state id>`), taken only in the state that invoked or set it. Each comes
|
|
20
|
+
// once a visit, so every transition it takes must leave the state (or enter it again) and the last be unguarded; and one
|
|
21
|
+
// timer at a time (two fire in the order of their delays, which events from outside would not keep). Eventless (`always`)
|
|
22
|
+
// transitions and entry and exit actions that write the context are read into each transition as XState's macrostep:
|
|
23
|
+
// per state the machine is in, the exit actions (innermost first), the transition's, the entry actions (outermost
|
|
24
|
+
// first), then the eventless transitions of the state it lands in (innermost first, each guard on the context as it is
|
|
25
|
+
// then), again until none is enabled; the initial states' entry actions are the context's start.
|
|
17
26
|
// What a chart can't run the same way is refused when the chart is built, with the reason: a parallel state below the
|
|
18
|
-
// root,
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
27
|
+
// root, wildcard events, several targets at once, inline guards and actions, two regions writing the context on one
|
|
28
|
+
// event (XState runs their actions one after another; a chart's regions write in one step), a shallow history over
|
|
29
|
+
// nested states, eventless transitions or context-writing entry and exit actions in a parallel machine or beside a
|
|
30
|
+
// history node, eventless transitions that may run without end or that the machine takes at once from its start. So is
|
|
31
|
+
// every key it doesn't read, rather than dropped: a node or transition key outside the lists below (KEYS), an initial
|
|
32
|
+
// transition with actions, an event XState raises itself named in `on` (done, error, init).
|
|
23
33
|
// An XState v4 machine reads the same, its `cond` the guard v5 calls `guard` (a name, or {type, ...params}); v4's
|
|
24
34
|
// `in`, `strict`, `activities` and eventless `''` are refused with the rest. Each XState ignores the other's guard key,
|
|
25
35
|
// so a v5 machine with `cond` or a v4 one with `guard` is refused (a plain config is read by the key it uses).
|
|
26
|
-
import { Choice, bool, int } from "./dsl.js";
|
|
36
|
+
import { Choice, Cond, Maybe, Str, Term, all, bool, int, lit, no, yes } from "./dsl.js";
|
|
27
37
|
import { chart } from "./chart.js";
|
|
38
|
+
import { seeded } from "./machine.js";
|
|
28
39
|
// The keys read, and those that change nothing a run shows (descriptions, metadata, types, a final state's output, v4's
|
|
29
40
|
// action-order flags, which order no write to the context: those a transition makes run in order either way; v5's
|
|
30
41
|
// `reenter` and v4's `internal`, which change only which entry and exit actions run, and those write no context here).
|
|
31
42
|
// Any other is refused, by name, rather than dropped; some with the reason.
|
|
32
43
|
const KEYS = {
|
|
33
|
-
node: new Set(['id', 'type', 'history', 'initial', 'target', 'states', 'on', 'entry', 'exit', 'description', 'meta', 'tags', 'output', 'data']),
|
|
44
|
+
node: new Set(['id', 'type', 'history', 'initial', 'target', 'states', 'on', 'entry', 'exit', 'invoke', 'after', 'always', 'description', 'meta', 'tags', 'output', 'data']),
|
|
34
45
|
root: new Set(['context', 'version', 'types', 'schemas', 'schema', 'tsTypes', 'predictableActionArguments', 'preserveActionOrder']),
|
|
35
46
|
transition: new Set(['target', 'guard', 'cond', 'actions', 'reenter', 'internal', 'description', 'meta']),
|
|
47
|
+
// An invoked actor: what it is and the input it starts with are its own (outside the chart), its answers events.
|
|
48
|
+
invoke: new Set(['id', 'src', 'input', 'systemId', 'onDone', 'onError']),
|
|
36
49
|
};
|
|
37
50
|
const WHY = {
|
|
38
|
-
|
|
39
|
-
|
|
51
|
+
onDone: "a state's `onDone` (XState raises it when a final child is reached) has no chart counterpart",
|
|
52
|
+
onSnapshot: "an invoked actor's `onSnapshot` has no chart counterpart", activities: "v4's `activities` have no chart counterpart", strict: "v4's `strict` (an event no state takes throws) has no chart counterpart",
|
|
40
53
|
delimiter: 'a state path delimiter other than "."', onEntry: "v4's `onEntry`: write it as `entry`", onExit: "v4's `onExit`: write it as `exit`",
|
|
41
54
|
in: "v4's `in` guard: write it as a named guard reading env.in(...)",
|
|
42
55
|
};
|
|
@@ -137,10 +150,6 @@ export function fromXState(machine, opts = {}) {
|
|
|
137
150
|
const f = opts.actions[n];
|
|
138
151
|
return f ? [(env) => f(env, params)] : [];
|
|
139
152
|
});
|
|
140
|
-
for (const i of infos)
|
|
141
|
-
for (const k of ['entry', 'exit'])
|
|
142
|
-
if (actionsOf(pathOf(i), list(i.node[k])).length)
|
|
143
|
-
refuse(pathOf(i), `${k} actions that write the context (a chart writes the context on transitions only)`);
|
|
144
153
|
// Several actions run one after another, each reading the context the one before wrote.
|
|
145
154
|
const composed = (fs) => (fs.length ? (env) => {
|
|
146
155
|
let cur = env;
|
|
@@ -160,7 +169,7 @@ export function fromXState(machine, opts = {}) {
|
|
|
160
169
|
return { states: Object.fromEntries(kids.map(k => [k.segs.at(-1), nodeOf(k)])), ...(i.node.initial ? { initial: i.node.initial } : {}), ...(i.history ? { history: true } : {}) };
|
|
161
170
|
};
|
|
162
171
|
const top = infos.filter(x => x.parent === infos[0]);
|
|
163
|
-
let c = chart(name).params((opts.params ?? {})).inputs((opts.inputs ?? {})).context(contextOf(root, opts.context, refuse));
|
|
172
|
+
let c = chart(name).params((opts.params ?? {})).inputs((opts.inputs ?? {})).context(contextOf(root, opts.context, refuse, opts.ignore));
|
|
164
173
|
if (parallel) {
|
|
165
174
|
for (const r of top)
|
|
166
175
|
if (!infos.some(x => x.parent === r && x.node.type !== 'history'))
|
|
@@ -171,10 +180,53 @@ export function fromXState(machine, opts = {}) {
|
|
|
171
180
|
c = c.states(nodeOf(infos[0]).states ?? { [STATELESS]: {} }, root.initial ? { initial: root.initial } : {});
|
|
172
181
|
if (opts.events)
|
|
173
182
|
c = c.events(...opts.events);
|
|
174
|
-
//
|
|
175
|
-
//
|
|
176
|
-
const
|
|
183
|
+
// Entry and exit actions, each node's composed: those that write the context make each transition XState's macrostep
|
|
184
|
+
// (below), as do eventless transitions.
|
|
185
|
+
const entryOf = new Map(), exitOf = new Map();
|
|
177
186
|
for (const i of infos)
|
|
187
|
+
for (const k of ['entry', 'exit'])
|
|
188
|
+
(k === 'entry' ? entryOf : exitOf).set(i, composed(actionsOf(pathOf(i), list(i.node[k]))));
|
|
189
|
+
const raws = [], alwaysOf = new Map();
|
|
190
|
+
// A state's id as XState makes it (the machine's own id, '(machine)' where it has none, then the path).
|
|
191
|
+
const nodeId = (i) => i.node.id ?? (i.segs.length ? `${root.id ?? '(machine)'}.${pathOf(i)}` : root.id ?? '(machine)');
|
|
192
|
+
const read = (where, t) => {
|
|
193
|
+
if (t === null || (typeof t !== 'string' && typeof t !== 'object'))
|
|
194
|
+
refuse(where, `a transition given as ${typeof t === 'function' ? 'a function' : JSON.stringify(t)}`);
|
|
195
|
+
const o = (typeof t === 'string' ? { target: t } : t), targets = list(o.target);
|
|
196
|
+
keyCheck(o, KEYS.transition, what => refuse(where, what));
|
|
197
|
+
if (o.guard !== undefined && o.cond !== undefined)
|
|
198
|
+
refuse(where, 'both `guard` and v4\'s `cond`');
|
|
199
|
+
// (each XState reads its own and takes a transition with the other's unguarded: refused, not taken so)
|
|
200
|
+
if (o.cond !== undefined && version === 5)
|
|
201
|
+
refuse(where, 'v4\'s `cond` in an XState v5 machine, which doesn\'t read it (it takes this transition unguarded): name the guard in `guard`');
|
|
202
|
+
if (o.guard !== undefined && version === 4)
|
|
203
|
+
refuse(where, 'v5\'s `guard` in an XState v4 machine, which doesn\'t read it (it takes this transition unguarded): name the guard in `cond`');
|
|
204
|
+
if (targets.length > 1)
|
|
205
|
+
refuse(where, 'several targets at once');
|
|
206
|
+
return o;
|
|
207
|
+
};
|
|
208
|
+
const under = (a, b) => a === b || (!!a.parent && under(a.parent, b));
|
|
209
|
+
// A transition that leaves the state (or enters it again: XState stops the actors it invoked and its timer, and
|
|
210
|
+
// starts them anew), as v5 reads `reenter` and v4 an external transition.
|
|
211
|
+
const leaves = (i, o) => {
|
|
212
|
+
if (o.target === undefined)
|
|
213
|
+
return false;
|
|
214
|
+
const to = resolve(i, list(o.target)[0]).to;
|
|
215
|
+
if (!under(to, i))
|
|
216
|
+
return true;
|
|
217
|
+
return version === 5 ? o.reenter === true : o.internal !== true && !String(list(o.target)[0]).startsWith('.');
|
|
218
|
+
};
|
|
219
|
+
// An actor's answer and a timer come once a visit: each transition they take leaves the state (so a second answer of
|
|
220
|
+
// the same visit, which can't come, is never read), and the last takes the event whatever the guards say.
|
|
221
|
+
const once = (i, ts, where, what) => {
|
|
222
|
+
if (ts.some(o => !leaves(i, o)))
|
|
223
|
+
refuse(where, `${what} that doesn't leave the state (the answer comes once a visit; a chart would take it again)`);
|
|
224
|
+
const last = ts.at(-1);
|
|
225
|
+
if (last.guard !== undefined || last.cond !== undefined)
|
|
226
|
+
refuse(where, `${what} whose last transition is guarded (the answer, refused by every guard, comes once a visit; a chart would take it again)`);
|
|
227
|
+
};
|
|
228
|
+
const timed = infos.filter(i => i.node.after !== undefined);
|
|
229
|
+
for (const i of infos) {
|
|
178
230
|
for (const [event, spec] of Object.entries(i.node.on ?? {})) {
|
|
179
231
|
const where = `${pathOf(i) || 'the root'} on ${event || '""'}`;
|
|
180
232
|
if (event.includes('*'))
|
|
@@ -183,48 +235,264 @@ export function fromXState(machine, opts = {}) {
|
|
|
183
235
|
refuse(where, event ? 'an event XState raises itself (a done, error or init event)' : "v4's eventless transition (`''`)");
|
|
184
236
|
if (spec === undefined)
|
|
185
237
|
refuse(where, 'a forbidden event (an undefined transition)');
|
|
186
|
-
for (const t of list(spec))
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
238
|
+
for (const t of list(spec))
|
|
239
|
+
raws.push({ event, src: i, o: read(where, t), where });
|
|
240
|
+
}
|
|
241
|
+
list(i.node.invoke).forEach((inv, k) => {
|
|
242
|
+
const where = `${pathOf(i) || 'the root'}'s invoke${list(i.node.invoke).length > 1 ? ` ${k}` : ''}`;
|
|
243
|
+
if (!inv || typeof inv !== 'object' || Array.isArray(inv))
|
|
244
|
+
return refuse(where, 'an invoke given as other than {src, ...}');
|
|
245
|
+
keyCheck(inv, KEYS.invoke, what => refuse(where, what));
|
|
246
|
+
if (!version)
|
|
247
|
+
return refuse(where, 'an invoke in a plain config: give the machine itself (the events its actors answer by are named by its XState)');
|
|
248
|
+
const names = answers(version, nodeId(i), inv, k);
|
|
249
|
+
for (const [key, event] of [['onDone', names.done], ['onError', names.error]]) {
|
|
250
|
+
const spec = inv[key];
|
|
251
|
+
if (spec === undefined)
|
|
252
|
+
continue;
|
|
253
|
+
const ts = list(spec).map(t => read(`${where} ${key}`, t));
|
|
254
|
+
once(i, ts, `${where} ${key}`, `an actor's ${key}`);
|
|
255
|
+
for (const o of ts)
|
|
256
|
+
raws.push({ event, src: i, o, where: `${where} ${key}` });
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
if (i.node.after !== undefined) {
|
|
260
|
+
const where = `${pathOf(i) || 'the root'}'s after`, after = i.node.after;
|
|
261
|
+
if (!after || typeof after !== 'object' || Array.isArray(after))
|
|
262
|
+
refuse(where, '`after` given as other than {delay: transitions}');
|
|
263
|
+
if (!version)
|
|
264
|
+
refuse(where, '`after` in a plain config: give the machine itself (the event its timer sends is named by its XState)');
|
|
265
|
+
const delays = Object.keys(after);
|
|
266
|
+
// One timer at a time: two (in one state, or in a state and one within it) fire in the order of their delays, which
|
|
267
|
+
// a chart taking each as an event from outside would not keep.
|
|
268
|
+
if (delays.length > 1)
|
|
269
|
+
refuse(where, `two timers in one state (${delays.join(', ')}): they fire in the order of their delays, which the chart would not keep`);
|
|
270
|
+
const other = timed.find(j => j !== i && (under(j, i) || under(i, j)));
|
|
271
|
+
if (other)
|
|
272
|
+
refuse(where, `a timer in ${pathOf(i) || 'the root'} and another in ${pathOf(other) || 'the root'}, running at once: they fire in the order of their delays, which the chart would not keep`);
|
|
273
|
+
for (const delay of delays) {
|
|
274
|
+
const event = timer(version, nodeId(i), delay);
|
|
275
|
+
const ts = list(after[delay]).map(t => read(where, t));
|
|
276
|
+
once(i, ts, where, 'a timer');
|
|
277
|
+
for (const o of ts)
|
|
278
|
+
raws.push({ event, src: i, o, where });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (i.node.always !== undefined)
|
|
282
|
+
alwaysOf.set(i, list(i.node.always).map(t => ({ o: read(`${pathOf(i) || 'the root'}'s always`, t), where: `${pathOf(i) || 'the root'}'s always` })));
|
|
283
|
+
}
|
|
284
|
+
const guardOfO = (where, o) => (o.cond !== undefined ? guardOf(where, o.cond, true) : guardOf(where, o.guard));
|
|
285
|
+
// Where a transition applies: its state; for the root, every top state but a final one (XState stops there), or in a
|
|
286
|
+
// parallel machine the region its target is in (the first region, for one with no target).
|
|
287
|
+
const fromOf = (i, to) => (i.segs.length ? pathOf(i) : parallel ? (to ? to.segs[0] : top[0].segs[0]) : top.length ? top.filter(x => x.node.type !== 'final' && x.node.type !== 'history').map(pathOf) : STATELESS);
|
|
288
|
+
const macro = [...alwaysOf.values()].some(x => x.length) || infos.some(i => entryOf.get(i) || exitOf.get(i));
|
|
289
|
+
const writers = new Map();
|
|
290
|
+
if (!macro)
|
|
291
|
+
for (const { event, src: i, o, where } of raws) {
|
|
292
|
+
const to = o.target === undefined ? undefined : resolve(i, list(o.target)[0]);
|
|
293
|
+
const set = composed(actionsOf(where, list(o.actions))), when = guardOfO(where, o);
|
|
294
|
+
const from = fromOf(i, to?.to);
|
|
295
|
+
if (set) {
|
|
296
|
+
const region = parallel ? String(list(from)[0]).split('.')[0] : 'state';
|
|
297
|
+
writers.set(event, (writers.get(event) ?? new Set()).add(region));
|
|
298
|
+
}
|
|
299
|
+
c = c.on(event, { from, ...(to ? { to: pathOf(to.to), fresh: !to.viaHistory } : {}), ...(when ? { when } : {}), ...(set ? { set: set } : {}) });
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
// XState's macrostep, per state the machine is in: the transition's exit actions (innermost first), its own, the entry
|
|
303
|
+
// actions of the states it enters (outermost first), then the eventless transitions of the state it lands in (the
|
|
304
|
+
// innermost state's first, each guard read on the context as it is then), again until none is enabled.
|
|
305
|
+
if (parallel)
|
|
306
|
+
refuse('', 'a parallel machine with eventless transitions or entry or exit actions that write the context');
|
|
307
|
+
if (!top.length)
|
|
308
|
+
refuse('', 'a machine with no states, with eventless transitions or entry or exit actions that write the context');
|
|
309
|
+
for (const i of infos)
|
|
310
|
+
if (i.history)
|
|
311
|
+
refuse(pathOf(i), 'a history node in a machine with eventless transitions or entry or exit actions that write the context');
|
|
312
|
+
const leafOf = (i) => { const kids = infos.filter(x => x.parent === i && x.node.type !== 'history'); if (!kids.length)
|
|
313
|
+
return i; return leafOf(kids.find(k => k.segs.at(-1) === i.node.initial) ?? kids[0]); };
|
|
314
|
+
const leavesUnder = (i) => { const kids = infos.filter(x => x.parent === i && x.node.type !== 'history'); return kids.length ? kids.flatMap(leavesUnder) : [i]; };
|
|
315
|
+
const chain = (i) => (i.parent ? [i, ...chain(i.parent)] : [i]);
|
|
316
|
+
// The context after writes, read as a guard or an action reads it, in a state known statically.
|
|
317
|
+
// A value written, as the context's own kind holds it (a literal as the choice or the string it is; a maybe's parts).
|
|
318
|
+
const value = (was, v) => (typeof v === 'string' && was instanceof Choice ? was.of(v) : typeof v === 'string' && was instanceof Str ? was.literal(v)
|
|
319
|
+
: was instanceof Maybe && v instanceof Maybe ? new Maybe(v.present, value(was.inner, v.inner)) : was instanceof Maybe && v === null ? new Maybe(lit(0), was.inner)
|
|
320
|
+
: typeof v === 'number' ? lit(v) : typeof v === 'boolean' ? (v ? yes : no) : v);
|
|
321
|
+
// (With no state given, the state is the one the step starts in: the chart's own `in`.)
|
|
322
|
+
const at = (env, writes, leaf) => Object.assign(Object.create(null), env, Object.fromEntries(Object.entries(writes).map(([k, v]) => [k, value(env[k], v)])), leaf ? {
|
|
323
|
+
in: (p) => { const t = infos.find(x => pathOf(x) === p) ?? refuse('', `no state ${p}`); return under(leaf, t) ? yes : no; },
|
|
324
|
+
last: () => refuse('', 'a history read in a machine with eventless transitions or entry or exit actions that write the context'),
|
|
325
|
+
} : {});
|
|
326
|
+
const run = (fs, env, writes, leaf) => { let w = writes; for (const f of fs)
|
|
327
|
+
w = { ...w, ...f(at(env, w, leaf)) }; return w; };
|
|
328
|
+
// One microstep: transition o of state src, taken from leaf.
|
|
329
|
+
const micro = (v, src, o, where) => {
|
|
330
|
+
const fs = actionsOf(where, list(o.actions));
|
|
331
|
+
if (o.target === undefined)
|
|
332
|
+
return { ...v, apply: env => run(fs, env, v.apply(env), v.leaf) };
|
|
333
|
+
const { to: T, viaHistory } = resolve(src, list(o.target)[0]);
|
|
334
|
+
if (viaHistory)
|
|
335
|
+
refuse(where, 'a history target in a machine with eventless transitions or entry or exit actions that write the context');
|
|
336
|
+
// The transition's domain, as XState computes it: the source, for a target within it that isn't re-entered; else
|
|
337
|
+
// the nearest state above the target that holds the source.
|
|
338
|
+
const internal = version === 5 ? o.reenter !== true : o.internal === true || String(list(o.target)[0]).startsWith('.');
|
|
339
|
+
const D = internal && under(T, src) ? src : chain(T).slice(1).find(a => a !== src && under(src, a)) ?? infos[0];
|
|
340
|
+
const exited = chain(v.leaf).filter(n => n !== D && under(n, D));
|
|
341
|
+
const entered = chain(T).filter(n => n !== D && under(n, D)).reverse();
|
|
342
|
+
for (let n = T;;) {
|
|
343
|
+
const kids = infos.filter(x => x.parent === n && x.node.type !== 'history');
|
|
344
|
+
if (!kids.length)
|
|
345
|
+
break;
|
|
346
|
+
n = kids.find(k => k.segs.at(-1) === n.node.initial) ?? kids[0];
|
|
347
|
+
entered.push(n);
|
|
348
|
+
}
|
|
349
|
+
const all = [...exited.map(n => exitOf.get(n)), ...fs, ...entered.map(n => entryOf.get(n))].filter((f) => !!f);
|
|
350
|
+
const leaf = entered.at(-1) ?? leafOf(T);
|
|
351
|
+
return { conds: v.conds, leaf, apply: env => run(all, env, v.apply(env), v.leaf), exits: v.exits || exited.some(n => exitOf.get(n)) };
|
|
352
|
+
};
|
|
353
|
+
// The eventless transitions from where a microstep lands, until none is enabled (at most a few in a row).
|
|
354
|
+
const settle = (v, depth) => {
|
|
355
|
+
const cands = chain(v.leaf).flatMap(n => (alwaysOf.get(n) ?? []).map(a => ({ n, ...a })));
|
|
356
|
+
if (!cands.length)
|
|
357
|
+
return [v];
|
|
358
|
+
if (depth >= 6)
|
|
359
|
+
refuse(pathOf(v.leaf), 'eventless transitions that may run more than 6 times in a row');
|
|
360
|
+
const out = [], prior = [];
|
|
361
|
+
const after = (env) => at(env, v.apply(env), v.leaf);
|
|
362
|
+
for (const { n, o, where } of cands) {
|
|
363
|
+
const g = guardOfO(where, o), before = [...prior];
|
|
364
|
+
const taken = { ...v, conds: [...v.conds, ...before.map(p => (env) => p(after(env)).not()), ...(g ? [(env) => g(after(env))] : [])] };
|
|
365
|
+
out.push(...settle(micro(taken, n, o, where), depth + 1));
|
|
366
|
+
if (!g)
|
|
367
|
+
return out;
|
|
368
|
+
prior.push(g);
|
|
369
|
+
}
|
|
370
|
+
out.push({ ...v, conds: [...v.conds, ...prior.map(p => (env) => p(after(env)).not())] });
|
|
371
|
+
if (out.length > 64)
|
|
372
|
+
refuse(pathOf(v.leaf), 'eventless transitions with more than 64 ways through');
|
|
373
|
+
return out;
|
|
374
|
+
};
|
|
375
|
+
// The start: XState enters the initial states, runs their entry actions and then takes any eventless transition
|
|
376
|
+
// enabled. Both are read on the initial context, which must decide them: an entry action's writes become the
|
|
377
|
+
// context's start (each a value the initial context fixes), and no eventless transition may be enabled there.
|
|
378
|
+
const start = leafOf(infos[0]), path0 = chain(start).reverse();
|
|
379
|
+
const initGuards = path0.flatMap(n => (alwaysOf.get(n) ?? []).map(a => guardOfO(a.where, a.o)));
|
|
380
|
+
const entries0 = path0.map(n => entryOf.get(n)).filter((f) => !!f);
|
|
381
|
+
if (initGuards.length || entries0.length) {
|
|
382
|
+
if (initGuards.some(g => !g))
|
|
383
|
+
refuse(pathOf(start), 'an eventless transition the machine takes at once from its initial state');
|
|
384
|
+
const ctx0 = contextOf(root, opts.context, refuse, opts.ignore), env0 = Object.create(null), kinds = {};
|
|
385
|
+
for (const [k, v] of Object.entries(ctx0)) {
|
|
386
|
+
const { kind, init } = typeof v === 'number' ? { kind: undefined, init: v } : v;
|
|
387
|
+
if (typeof init === 'function')
|
|
388
|
+
refuse(pathOf(start), 'entry actions or an eventless transition at the start, over a context the params make');
|
|
389
|
+
kinds[k] = kind;
|
|
390
|
+
env0[k] = kind ? kind.build(k, part => lit(kind.encode(k, init)[part] ?? 0)) : lit(init);
|
|
391
|
+
}
|
|
392
|
+
const fixed = (o) => new Proxy(at(o, {}, start), { get: (x, k) => (typeof k === 'string' && !(k in x) ? refuse(pathOf(start), `entry actions or an eventless transition at the start that read ${k} (not the context)`) : x[k]) });
|
|
393
|
+
let writes = {};
|
|
394
|
+
for (const f of entries0)
|
|
395
|
+
writes = { ...writes, ...f(fixed({ ...env0, ...Object.fromEntries(Object.entries(writes).map(([k, w]) => [k, value(env0[k], w)])) })) };
|
|
396
|
+
const known = {};
|
|
397
|
+
for (const [k, w] of Object.entries(writes)) {
|
|
398
|
+
const x = value(env0[k], w);
|
|
399
|
+
const raw = x instanceof Choice ? (x.index.val === undefined ? undefined : x.values[x.index.val]) : x instanceof Term ? x.val : x instanceof Cond ? x.ok : undefined;
|
|
400
|
+
if (raw === undefined)
|
|
401
|
+
refuse(pathOf(start), `an initial state's entry action writes ${k} a value the initial context doesn't fix`);
|
|
402
|
+
known[k] = kinds[k] ? { kind: kinds[k], init: raw } : raw;
|
|
403
|
+
}
|
|
404
|
+
if (Object.keys(known).length)
|
|
405
|
+
c = c.context(known);
|
|
406
|
+
const env = fixed({ ...env0, ...Object.fromEntries(Object.entries(writes).map(([k, w]) => [k, value(env0[k], w)])) });
|
|
407
|
+
for (const g of initGuards) {
|
|
408
|
+
const ok = g(env).ok;
|
|
409
|
+
if (ok === undefined)
|
|
410
|
+
refuse(pathOf(start), 'an eventless transition from the initial state whose guard the initial context doesn\'t decide');
|
|
411
|
+
if (ok)
|
|
412
|
+
refuse(pathOf(start), 'an eventless transition the machine takes at once from its initial state');
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
for (const { event, src: i, o, where } of raws) {
|
|
416
|
+
const to = o.target === undefined ? undefined : resolve(i, list(o.target)[0]);
|
|
417
|
+
const when = guardOfO(where, o), from = fromOf(i, to?.to);
|
|
418
|
+
// Per state the machine may be in: where the transition exits states whose exit actions write the context, or
|
|
419
|
+
// lands where an eventless transition may be enabled, its macrostep by cases there; everywhere else one
|
|
420
|
+
// transition (its writes and the state it lands in the same from each), after those (which take every case
|
|
421
|
+
// where they are).
|
|
422
|
+
const sources = i.segs.length ? leavesUnder(i) : top.filter(x => x.node.type !== 'final' && x.node.type !== 'history').flatMap(leavesUnder);
|
|
423
|
+
let plain;
|
|
424
|
+
for (const leaf of sources) {
|
|
425
|
+
const v0 = micro({ conds: [], apply: () => ({}), leaf }, i, o, where);
|
|
426
|
+
if (!v0.exits && !chain(v0.leaf).some(n => alwaysOf.get(n)?.length)) {
|
|
427
|
+
plain ??= v0;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
for (const v of settle(v0, 0)) {
|
|
431
|
+
const conds = [...(when ? [when] : []), ...v.conds];
|
|
432
|
+
c = c.on(event, { from, ...(o.target === undefined && v.leaf === leaf ? {} : { to: pathOf(v.leaf), fresh: true }),
|
|
433
|
+
when: env => all(env.in(pathOf(leaf)), ...conds.map(f => f(env))), set: ((env) => v.apply(env)) });
|
|
208
434
|
}
|
|
209
|
-
|
|
435
|
+
}
|
|
436
|
+
if (plain) {
|
|
437
|
+
// (a transition with no target writes as its actions do from wherever it is taken: in the state it starts in)
|
|
438
|
+
const p = plain, fs = actionsOf(where, list(o.actions)), apply = o.target === undefined ? (env) => run(fs, env, {}) : p.apply;
|
|
439
|
+
c = c.on(event, { from, ...(o.target === undefined ? {} : { to: pathOf(p.leaf), fresh: true }), ...(when ? { when } : {}), set: ((env) => apply(env)) });
|
|
210
440
|
}
|
|
211
441
|
}
|
|
442
|
+
}
|
|
212
443
|
for (const [event, regions] of writers)
|
|
213
444
|
if (regions.size > 1)
|
|
214
445
|
refuse(`on ${event}`, `regions ${[...regions].join(' and ')} both write the context (XState runs their actions one after another)`);
|
|
215
446
|
return c;
|
|
216
447
|
}
|
|
448
|
+
// The events XState sends a machine itself, by its version: an invoked actor's answers (done, error), named by the
|
|
449
|
+
// invocation's id (its own, or its index and the state's id), and a timer's.
|
|
450
|
+
const answers = (version, nodeId, inv, k) => {
|
|
451
|
+
const id = inv.id ?? (version === 5 ? `${k}.${nodeId}` : `${nodeId}:invocation[${k}]`);
|
|
452
|
+
return version === 5 ? { done: `xstate.done.actor.${id}`, error: `xstate.error.actor.${id}` } : { done: `done.invoke.${id}`, error: `error.platform.${id}` };
|
|
453
|
+
};
|
|
454
|
+
const timer = (version, nodeId, delay) => (version === 5 ? `xstate.after.${delay}.${nodeId}` : `xstate.after(${delay})#${nodeId}`);
|
|
455
|
+
// Every event a machine reacts to: those its states name in `on`, its actors' answers and its timers (each of these with
|
|
456
|
+
// the state it comes in: the world sends an answer only while its actor runs, a timer only while it is set).
|
|
457
|
+
export function eventsOf(machine) { return eventsWhere(machine).map(([e]) => e); }
|
|
458
|
+
function eventsWhere(machine) {
|
|
459
|
+
const root = configOf(machine), version = versionOf(machine), name = root.id ?? '(machine)', out = [];
|
|
460
|
+
let segsNow = [];
|
|
461
|
+
const add = (e, only) => { if (!out.some(([x]) => x === e))
|
|
462
|
+
out.push([e, only ? segsNow : undefined]); };
|
|
463
|
+
const walk = (n, segs) => {
|
|
464
|
+
const id = n.id ?? (segs.length ? `${name}.${segs.join('.')}` : name);
|
|
465
|
+
segsNow = segs;
|
|
466
|
+
for (const e of Object.keys(n.on ?? {}))
|
|
467
|
+
add(e);
|
|
468
|
+
if (version) {
|
|
469
|
+
list(n.invoke).forEach((inv, k) => { const a = answers(version, id, inv, k); if (inv.onDone !== undefined)
|
|
470
|
+
add(a.done, true); if (inv.onError !== undefined)
|
|
471
|
+
add(a.error, true); });
|
|
472
|
+
for (const d of Object.keys((n.after ?? {})))
|
|
473
|
+
add(timer(version, id, d), true);
|
|
474
|
+
}
|
|
475
|
+
for (const [k, kid] of Object.entries(n.states ?? {}))
|
|
476
|
+
walk(kid, [...segs, k]);
|
|
477
|
+
};
|
|
478
|
+
walk(root, []);
|
|
479
|
+
return out;
|
|
480
|
+
}
|
|
217
481
|
// A machine with no states (its root's transitions only): one state of the chart's, XState's value {} there.
|
|
218
482
|
const STATELESS = '(machine)';
|
|
219
|
-
function contextOf(root, given, refuse) {
|
|
483
|
+
function contextOf(root, given, refuse, ignore = []) {
|
|
220
484
|
const out = {};
|
|
485
|
+
if (given)
|
|
486
|
+
for (const k of ignore)
|
|
487
|
+
if (k in given)
|
|
488
|
+
refuse('', `the context's ${k} both given and left out`);
|
|
221
489
|
if (root.context !== undefined && typeof root.context !== 'object') {
|
|
222
490
|
if (!given)
|
|
223
491
|
refuse('', 'a context computed by a function: give its kinds in context');
|
|
224
492
|
return { ...given };
|
|
225
493
|
}
|
|
226
494
|
for (const [k, v] of Object.entries((root.context ?? {}))) {
|
|
227
|
-
if (given && k in given)
|
|
495
|
+
if ((given && k in given) || ignore.includes(k))
|
|
228
496
|
continue;
|
|
229
497
|
if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
230
498
|
out[k] = v >= 0 ? v : int.from(v);
|
|
@@ -237,40 +505,53 @@ function contextOf(root, given, refuse) {
|
|
|
237
505
|
}
|
|
238
506
|
const canonical = (v) => (v && typeof v === 'object' ? `{${Object.keys(v).sort().map(k => `${k}:${canonical(v[k])}`).join(',')}}` : JSON.stringify(v));
|
|
239
507
|
export function conforms(c, machine, createActor, opts = {}) {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
walk(root);
|
|
508
|
+
// Every event it reacts to: its states' `on`, its actors' answers and its timers (sent as XState's own events, so a
|
|
509
|
+
// run takes them in any order the world could).
|
|
510
|
+
const root = configOf(machine), where = eventsWhere(machine), events = where.map(([e]) => e);
|
|
511
|
+
const value = (segs) => segs.reduceRight((acc, seg) => (acc === undefined ? seg : { [seg]: acc }), undefined);
|
|
245
512
|
const r = c.rule, g = r.compiled(), ps = r.encodeParams((opts.params ?? {}));
|
|
246
|
-
|
|
247
|
-
let x = opts.seed ?? 1;
|
|
248
|
-
const rand = (k) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); };
|
|
513
|
+
const rand = seeded(opts.seed ?? 1);
|
|
249
514
|
const valueOf = (d) => {
|
|
250
515
|
const nest = (path) => path.split('.').reduceRight((acc, seg) => (acc === undefined ? seg : { [seg]: acc }), undefined);
|
|
251
516
|
if (root.type === 'parallel')
|
|
252
517
|
return Object.fromEntries(Object.keys(root.states ?? {}).filter(k => root.states[k].type !== 'history').map(k => [k, nest(String(d[k]))]));
|
|
253
518
|
return d.state === STATELESS ? {} : nest(String(d.state));
|
|
254
519
|
};
|
|
255
|
-
const contextKeys = Object.keys((root.context && typeof root.context === 'object' ? root.context : {}));
|
|
520
|
+
const contextKeys = opts.context ?? Object.keys((root.context && typeof root.context === 'object' ? root.context : {}));
|
|
256
521
|
let checked = 0;
|
|
257
522
|
for (let run = 0; run < (opts.runs ?? 100); run++) {
|
|
258
523
|
const actor = createActor(machine).start();
|
|
259
524
|
let st = g.init(ps);
|
|
260
525
|
const sent = [];
|
|
261
526
|
for (let d = 0; d < (opts.depth ?? 12); d++) {
|
|
262
|
-
|
|
527
|
+
// An answer or a timer only where its state is (XState stops an actor whose answer is unhandled).
|
|
528
|
+
const now = actor.getSnapshot();
|
|
529
|
+
const live = where.every(([, segs]) => !segs?.length) ? events : where.filter(([, segs]) => !segs?.length || now.matches?.(value(segs))).map(([e]) => e);
|
|
530
|
+
if (!live.length)
|
|
531
|
+
break;
|
|
532
|
+
const type = live[rand(live.length)], payload = opts.payload?.(type, rand) ?? {};
|
|
263
533
|
sent.push(Object.keys(payload).length ? `${type}${JSON.stringify(payload)}` : type);
|
|
264
|
-
|
|
534
|
+
opts.beforeSend?.(type, payload);
|
|
535
|
+
actor.send((opts.event ? opts.event(type, payload) : { type, ...payload }));
|
|
265
536
|
st = g.step(ps, st, r.encodeInput({ event: type, ...payload }));
|
|
266
537
|
const snap = actor.getSnapshot(), d2 = r.decode(st), want = valueOf(d2);
|
|
267
|
-
if (canonical(snap.value) !== canonical(want))
|
|
538
|
+
if (canonical(snap.value) !== canonical(want)) {
|
|
539
|
+
actor.stop?.();
|
|
268
540
|
return { checked, failure: `after ${sent.join(', ')}: XState is in ${JSON.stringify(snap.value)}, the chart in ${JSON.stringify(want)}` };
|
|
541
|
+
}
|
|
269
542
|
for (const k of contextKeys)
|
|
270
|
-
if (JSON.stringify(snap.context?.[k]) !== JSON.stringify(d2[k]))
|
|
543
|
+
if (JSON.stringify(snap.context?.[k]) !== JSON.stringify(d2[k])) {
|
|
544
|
+
actor.stop?.();
|
|
271
545
|
return { checked, failure: `after ${sent.join(', ')}: XState's ${k} is ${JSON.stringify(snap.context?.[k])}, the chart's ${JSON.stringify(d2[k])}` };
|
|
546
|
+
}
|
|
272
547
|
checked++;
|
|
548
|
+
// XState v4, done (a final state at the top): its service takes no more events (and warns of each), nor does the
|
|
549
|
+
// chart; the run ends there. (v5's actor ignores them quietly, as the chart does: its runs go on.)
|
|
550
|
+
if (snap.done === true)
|
|
551
|
+
break;
|
|
273
552
|
}
|
|
553
|
+
// Its timers and actors stopped with it.
|
|
554
|
+
actor.stop?.();
|
|
274
555
|
}
|
|
275
556
|
return { checked };
|
|
276
557
|
}
|