@margoengine/fsm 0.0.0-stage → 1.0.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.
@@ -0,0 +1,78 @@
1
+ import { StateMachine } from './index.js';
2
+ /** A transition as data. As {@link Transition}, with `guard` naming a function of {@link MachineBindings}. */
3
+ export interface TransitionDocument {
4
+ /** Source state. */
5
+ from: string;
6
+ /** Target state. */
7
+ to: string;
8
+ /** Event name. Give this or `after`. */
9
+ event?: string;
10
+ /** Delay in seconds, above 0. Give this or `event`. */
11
+ after?: number;
12
+ /** Cross-fade time in seconds. Default 0. */
13
+ duration?: number;
14
+ /** Name in `bindings.guards`. Default none. */
15
+ guard?: string;
16
+ }
17
+ /** A state as data. Hooks are names in `bindings.hooks`, as functions do not fit in JSON. */
18
+ export interface StateDocument {
19
+ /** Name of the parent state. */
20
+ parent?: string;
21
+ /** Descendant to go on to. */
22
+ initial?: string;
23
+ /** What the state remembers. */
24
+ history?: 'shallow' | 'deep';
25
+ /** Hook name, called on entry. */
26
+ enter?: string;
27
+ /** Hook name, called on exit. */
28
+ exit?: string;
29
+ /** Hook name, called with the context and delta on update. */
30
+ update?: string;
31
+ /** Parallel regions by name, run while this state is active. A state with regions takes no hooks. */
32
+ regions?: Record<string, RegionDocument>;
33
+ /** With `regions`: each region resumes where it stopped. Default false. */
34
+ regionHistory?: boolean;
35
+ }
36
+ /** A region as data: states, a starting state and transitions. */
37
+ export interface RegionDocument {
38
+ /** States by name. */
39
+ states: Record<string, StateDocument>;
40
+ /** The starting state. */
41
+ initial: string;
42
+ /** Transitions. Default none. */
43
+ transitions?: TransitionDocument[];
44
+ }
45
+ /** A whole machine as plain data, so it saves and loads as JSON. */
46
+ export interface MachineDocument extends RegionDocument {
47
+ /** Format version; 1. */
48
+ version: 1;
49
+ }
50
+ /** The functions a document names. */
51
+ export interface MachineBindings<C> {
52
+ /** Hooks by name; `enter` and `exit` hooks get the context, `update` hooks the context and delta. */
53
+ hooks?: Readonly<Record<string, (context: C, delta: number) => void>>;
54
+ /** Guards by name. */
55
+ guards?: Readonly<Record<string, (context: C) => boolean>>;
56
+ }
57
+ /** One thing wrong with a document. */
58
+ export interface MachineIssue {
59
+ /** Where, such as `states.run.parent` or `transitions[2].to`. */
60
+ path: string;
61
+ /** What is wrong and how to fix it. */
62
+ message: string;
63
+ }
64
+ /**
65
+ * Every problem in a document, or an empty list. With `bindings`, each hook and guard must also name a function there.
66
+ * Takes any value, so it can check what `JSON.parse` returned.
67
+ */
68
+ export declare function validateMachine<C>(value: unknown, bindings?: MachineBindings<C>): MachineIssue[];
69
+ /**
70
+ * Build a machine from a document. Its `enter` hooks run, as for `new StateMachine`.
71
+ * @throws TypeError listing every issue of {@link validateMachine}.
72
+ */
73
+ export declare function loadMachine<C>(document: MachineDocument, context: C, bindings?: MachineBindings<C>): StateMachine<C>;
74
+ /**
75
+ * The document of a machine, for `JSON.stringify`: its definition, not where it is now; for that see `fsm/trace`.
76
+ * @throws TypeError for a hook or guard that is not in `bindings`.
77
+ */
78
+ export declare function saveMachine<C>(machine: StateMachine<C>, bindings?: MachineBindings<C>): MachineDocument;
@@ -0,0 +1,149 @@
1
+ import { StateMachine as e } from "./index.js";
2
+ import { ParallelRegions as t } from "./parallel.js";
3
+ //#region src/document.ts
4
+ var n = /* @__PURE__ */ new Set([
5
+ "parent",
6
+ "initial",
7
+ "history",
8
+ "enter",
9
+ "exit",
10
+ "update",
11
+ "regions",
12
+ "regionHistory"
13
+ ]), r = /* @__PURE__ */ new Set([
14
+ "from",
15
+ "to",
16
+ "event",
17
+ "after",
18
+ "duration",
19
+ "guard"
20
+ ]), i = [
21
+ "enter",
22
+ "exit",
23
+ "update"
24
+ ], a = (e) => typeof e == "object" && !!e && !Array.isArray(e), o = (e) => typeof e == "string" && e.length > 0;
25
+ function s(e, t, n, i, s) {
26
+ if (!a(e)) return i(t, "A transition is an object");
27
+ for (let n of Object.keys(e)) r.has(n) || i(`${t}.${n}`, "Unknown key; remove it");
28
+ for (let r of ["from", "to"]) (!o(e[r]) || !Object.hasOwn(n, e[r])) && i(`${t}.${r}`, "Unknown state; name one of the states");
29
+ let { event: c, after: l, duration: u, guard: d } = e;
30
+ c === void 0 == (l === void 0) && i(t, "Give event or after, not both or neither"), c !== void 0 && !o(c) && i(`${t}.event`, "An event is a non-empty string"), l !== void 0 && !(typeof l == "number" && Number.isFinite(l) && l > 0) && i(`${t}.after`, "A delay is a number of seconds above 0"), u !== void 0 && !(typeof u == "number" && Number.isFinite(u) && u >= 0) && i(`${t}.duration`, "A cross-fade is a number of seconds, 0 or more"), d !== void 0 && (o(d) ? s && !Object.hasOwn(s.guards ?? {}, d) && i(`${t}.guard`, `No guard named ${d} in bindings`) : i(`${t}.guard`, "A guard is the name of a function in bindings"));
31
+ }
32
+ function c(e, t, r, s, c, u) {
33
+ if (!a(e)) return c(r, "A state is an object");
34
+ for (let t of Object.keys(e)) n.has(t) || c(`${r}.${t}`, "Unknown key; remove it");
35
+ let { parent: d, initial: f, history: p, regions: m, regionHistory: h } = e;
36
+ d !== void 0 && (!o(d) || !Object.hasOwn(s, d)) && c(`${r}.parent`, "Unknown parent; name one of the states");
37
+ let g = (e) => {
38
+ let t = [];
39
+ for (let n = e; o(n) && Object.hasOwn(s, n);) {
40
+ if (t.includes(n)) return n === e ? null : t;
41
+ t.push(n);
42
+ let r = s[n];
43
+ n = a(r) ? r.parent : void 0;
44
+ }
45
+ return t;
46
+ };
47
+ g(t) || c(`${r}.parent`, "Hierarchy cycle; a state cannot be its own ancestor"), f !== void 0 && (!g(f)?.includes(t) || f === t) && c(`${r}.initial`, "Name one of the descendants of this state"), p !== void 0 && p !== "shallow" && p !== "deep" && c(`${r}.history`, "Use 'shallow' or 'deep'");
48
+ for (let t of i) {
49
+ let n = e[t];
50
+ n !== void 0 && (o(n) ? u && !Object.hasOwn(u.hooks ?? {}, n) && c(`${r}.${t}`, `No hook named ${n} in bindings`) : c(`${r}.${t}`, "A hook is the name of a function in bindings"), m !== void 0 && c(`${r}.${t}`, "A state with regions takes no hooks; put them on its parent"));
51
+ }
52
+ if (h !== void 0 && (typeof h != "boolean" && c(`${r}.regionHistory`, "Use true or false"), m === void 0 && c(`${r}.regionHistory`, "Only a state with regions has this")), m !== void 0) {
53
+ if (!a(m) || !Object.keys(m).length) c(`${r}.regions`, "Name at least one region");
54
+ else for (let e of Object.keys(m)) l(m[e], `${r}.regions.${e}`, c, u, !1);
55
+ }
56
+ }
57
+ function l(e, t, n, r, i) {
58
+ let l = (e) => t ? `${t}.${e}` : e;
59
+ if (!a(e)) return n(t || "document", "A machine is an object");
60
+ for (let t of Object.keys(e)) t !== "states" && t !== "initial" && t !== "transitions" && !(i && t === "version") && n(l(t), "Unknown key; remove it");
61
+ let { states: u, initial: d, transitions: f } = e;
62
+ if (!a(u) || !Object.keys(u).length) return n(l("states"), "Name at least one state");
63
+ for (let e of Object.keys(u)) c(u[e], e, l(`states.${e}`), u, n, r);
64
+ if ((!o(d) || !Object.hasOwn(u, d)) && n(l("initial"), "Unknown state; name one of the states"), f !== void 0) {
65
+ if (!Array.isArray(f)) return n(l("transitions"), "Transitions are a list");
66
+ f.forEach((e, t) => s(e, l(`transitions[${t}]`), u, n, r));
67
+ }
68
+ }
69
+ function u(e, t) {
70
+ let n = [], r = (e, t) => void n.push({
71
+ path: e,
72
+ message: t
73
+ });
74
+ return a(e) && e.version !== 1 && r("version", "Unknown version; this reader takes version 1"), l(e, "", r, t, !0), n;
75
+ }
76
+ function d(e, n, r, i) {
77
+ let a = Object.create(null);
78
+ for (let o of Object.keys(e.states)) {
79
+ let { parent: s, initial: c, history: l, enter: u, exit: f, update: p, regions: m, regionHistory: h } = e.states[o], g = {};
80
+ if (m) {
81
+ let e = Object.create(null), a = Object.create(null);
82
+ for (let t of Object.keys(m)) e[t] = {}, a[t] = d(m[t], n, r, e[t]);
83
+ let o = new t(a, n, {
84
+ history: h,
85
+ forward: (e) => void i.machine?.send(e)
86
+ });
87
+ for (let t of Object.keys(m)) e[t].machine = o.machines[t];
88
+ Object.assign(g, o.asState());
89
+ }
90
+ s !== void 0 && (g.parent = s), c !== void 0 && (g.initial = c), l !== void 0 && (g.history = l), u !== void 0 && (g.enter = r.hooks[u]), f !== void 0 && (g.exit = r.hooks[f]), p !== void 0 && (g.update = r.hooks[p]), a[o] = g;
91
+ }
92
+ let o = (e.transitions ?? []).map(({ guard: e, ...t }) => {
93
+ let n = t;
94
+ return e !== void 0 && (n.guard = r.guards[e]), n;
95
+ });
96
+ return {
97
+ states: a,
98
+ initial: e.initial,
99
+ transitions: o
100
+ };
101
+ }
102
+ function f(t, n, r = {}) {
103
+ let i = u(t, r);
104
+ if (i.length) throw TypeError(`Invalid machine; ${i.map(({ path: e, message: t }) => `${e}: ${t}`).join("; ")}`);
105
+ let a = {}, { states: o, initial: s, transitions: c } = d(t, n, r, a);
106
+ return a.machine = new e(o, s, n, c);
107
+ }
108
+ function p(e, t, n) {
109
+ for (let n of Object.keys(e ?? {})) if (e[n] === t) return n;
110
+ throw TypeError(`No name for ${n} in bindings; add the function to bindings`);
111
+ }
112
+ function m(e, t, n, r) {
113
+ let a = Object.create(null);
114
+ for (let t of Object.keys(e)) {
115
+ let n = e[t], o = {};
116
+ if (n.parent !== void 0 && (o.parent = n.parent), n.initial !== void 0 && (o.initial = n.initial), n.history !== void 0 && (o.history = n.history), n.regions) {
117
+ let { definition: e, options: t } = n.regions;
118
+ o.regions = Object.create(null);
119
+ for (let t of Object.keys(e)) {
120
+ let n = e[t];
121
+ o.regions[t] = m(n.states, n.initial, n.transitions ?? [], r);
122
+ }
123
+ t.history && (o.regionHistory = !0);
124
+ } else {
125
+ if (n.plan) throw TypeError(`Unsupported plan hook on state ${t}; a document holds only named hooks and regions`);
126
+ for (let e of i) {
127
+ let i = n[e];
128
+ i && (o[e] = p(r.hooks, i, `${e} of ${t}`));
129
+ }
130
+ }
131
+ a[t] = o;
132
+ }
133
+ let o = {
134
+ states: a,
135
+ initial: t
136
+ };
137
+ return n.length && (o.transitions = n.map(({ guard: e, ...t }, n) => {
138
+ let i = { ...t };
139
+ return e && (i.guard = p(r.guards, e, `the guard of transition ${n}`)), i;
140
+ })), o;
141
+ }
142
+ function h(e, t = {}) {
143
+ return {
144
+ version: 1,
145
+ ...m(e.states, e.initial, e.transitions, t)
146
+ };
147
+ }
148
+ //#endregion
149
+ export { f as loadMachine, h as saveMachine, u as validateMachine };
@@ -0,0 +1,41 @@
1
+ import { StateMachine, type State, type Transition } from './index.js';
2
+ import { MachineTrace, type TraceOptions, type TraceRecord } from './trace.js';
3
+ /** Payload-aware hooks. Initial entry, direct goto and timed updates receive undefined data. */
4
+ export interface EventState<C, D = unknown> extends Omit<State<C>, 'enter' | 'exit' | 'plan'> {
5
+ /** Entry hook, receiving the exact payload supplied to send. */
6
+ enter?: (context: C, data: D | undefined) => void;
7
+ /** Exit hook, receiving the same payload as the guard. */
8
+ exit?: (context: C, data: D | undefined) => void;
9
+ /** Offer an event and its payload to a nested machine before the containing state's transitions. */
10
+ plan?: (event: string, data: D | undefined) => (() => void) | null;
11
+ }
12
+ /** A transition whose guard can inspect event data. */
13
+ export interface EventTransition<C, D = unknown> extends Omit<Transition<C>, 'guard'> {
14
+ /** Return true to accept this event and payload. */
15
+ guard?: (context: C, data: D | undefined) => boolean;
16
+ }
17
+ /** Optional payload delivery over the existing hierarchy, history and delay runtime. */
18
+ export declare class EventMachine<C, D = unknown> extends StateMachine<C> {
19
+ private readonly delivery;
20
+ /** Build and enter the machine. Data is passed by reference, never cloned or merged into context. */
21
+ constructor(states: Readonly<Record<string, EventState<C, D>>>, initial: string, context: C, transitions?: readonly EventTransition<C, D>[]);
22
+ /** Payload of the delivery currently running; undefined outside delivery. */
23
+ get data(): D | undefined;
24
+ /** Choose with this payload and retain it in the returned action, even if other events intervene. */
25
+ plan(event: string, data?: D): (() => void) | null;
26
+ /** Deliver one event with optional data; returns whether a transition accepted it. */
27
+ send(event: string, data?: D): boolean;
28
+ private deliver;
29
+ }
30
+ /** Transition trace with the original event payload by reference. */
31
+ export interface EventTraceRecord<D = unknown> extends TraceRecord {
32
+ /** Payload supplied to send; undefined for a direct or timed transition. */
33
+ data: D | undefined;
34
+ }
35
+ /** Bounded trace retaining payloads alongside the ordinary machine trace fields. */
36
+ export declare class EventTrace<C, D = unknown> extends MachineTrace<C> {
37
+ /** Attach a trace. As MachineTrace, dispose it before attaching another listener. */
38
+ constructor(machine: EventMachine<C, D>, options?: TraceOptions);
39
+ /** Records oldest first, including the exact payload of each accepted transition. */
40
+ get records(): EventTraceRecord<D>[];
41
+ }
package/dist/events.js ADDED
@@ -0,0 +1,50 @@
1
+ import { StateMachine as e } from "./index.js";
2
+ import { MachineTrace as t } from "./trace.js";
3
+ //#region src/events.ts
4
+ var n = class extends e {
5
+ constructor(e, t, n, r = []) {
6
+ let i = { data: void 0 }, a = Object.fromEntries(Object.entries(e).map(([e, t]) => [e, {
7
+ ...t,
8
+ enter: t.enter && ((e) => t.enter(e, i.data)),
9
+ exit: t.exit && ((e) => t.exit(e, i.data)),
10
+ plan: t.plan && ((e) => t.plan(e, i.data))
11
+ }]));
12
+ super(a, t, n, r.map((e) => ({
13
+ ...e,
14
+ guard: e.guard && ((t) => e.guard(t, i.data))
15
+ }))), this.delivery = i;
16
+ }
17
+ get data() {
18
+ return this.delivery.data;
19
+ }
20
+ plan(e, t) {
21
+ let n = this.deliver(t, () => super.plan(e));
22
+ return n && (() => this.deliver(t, n));
23
+ }
24
+ send(e, t) {
25
+ let n = this.plan(e, t);
26
+ return n?.(), n !== null;
27
+ }
28
+ deliver(e, t) {
29
+ let n = this.delivery.data;
30
+ this.delivery.data = e;
31
+ try {
32
+ return t();
33
+ } finally {
34
+ this.delivery.data = n;
35
+ }
36
+ }
37
+ }, r = class extends t {
38
+ constructor(e, t = {}) {
39
+ super(e, t);
40
+ let n = e.listener;
41
+ e.listener = (t, r, i) => {
42
+ n(t, r, i), Object.assign(super.records.at(-1), { data: e.data });
43
+ };
44
+ }
45
+ get records() {
46
+ return super.records;
47
+ }
48
+ };
49
+ //#endregion
50
+ export { n as EventMachine, r as EventTrace };
@@ -0,0 +1,39 @@
1
+ import { EventMachine, type EventState, type EventTransition } from './events.js';
2
+ /** A hierarchical state that may complete its containing state. */
3
+ export interface FinalState<C, D = unknown> extends EventState<C, D> {
4
+ /** True for a terminal leaf. A top-level final stops the machine. Default false. */
5
+ final?: boolean;
6
+ }
7
+ /** An ordinary transition or a guarded eventless transition. */
8
+ export interface FinalTransition<C, D = unknown> extends EventTransition<C, D> {
9
+ /** Run without an external event when enabled. Give exactly one of always:true, event or after. */
10
+ always?: boolean;
11
+ }
12
+ /** Run-to-completion state machine with final states, completion events and eventless transitions. */
13
+ export declare class FinalMachine<C, D = unknown> extends EventMachine<C, D> {
14
+ private readonly definition;
15
+ private readonly finalStates;
16
+ private readonly queue;
17
+ private lastFinal;
18
+ private settling;
19
+ private steps;
20
+ /** True after a top-level final state is entered. It accepts no more events or updates. */
21
+ done: boolean;
22
+ /** Authored transitions in definition order, with public event, after and always triggers for inspection. */
23
+ get transitionDefinitions(): readonly FinalTransition<C, D>[];
24
+ /** Build and settle initial eventless transitions and completion events before returning. */
25
+ constructor(states: Readonly<Record<string, FinalState<C, D>>>, initial: string, context: C, transitions?: readonly FinalTransition<C, D>[]);
26
+ /** Choose an external event and settle its complete macrostep when the returned action runs. */
27
+ plan(event: string, data?: D): (() => void) | null;
28
+ /** Deliver an event, then reconsider eventless guards even when no event transition accepts it. */
29
+ send(event: string, data?: D): boolean;
30
+ /** Directly enter a state and settle its eventless and completion transitions. */
31
+ goto(next: string, duration?: number): void;
32
+ /** Advance delays, settling each microstep before time can advance in the next state. */
33
+ update(delta: number): void;
34
+ /** Extension point called once after a public operation reaches a stable configuration. */
35
+ protected onStable(_data?: D): void;
36
+ private activePath;
37
+ private microstep;
38
+ private stabilize;
39
+ }
package/dist/final.js ADDED
@@ -0,0 +1,116 @@
1
+ import { EventMachine as e } from "./events.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ //#region src/final.ts
4
+ var n = "\0fsm.", r = `${n}always`, i = class extends e {
5
+ get transitionDefinitions() {
6
+ return this.definition;
7
+ }
8
+ constructor(e, t, i, a = []) {
9
+ for (let [t, n] of Object.entries(e)) {
10
+ if (n.final !== void 0 && typeof n.final != "boolean") throw TypeError("Invalid final flag; use true or false");
11
+ if (n.final && (n.initial !== void 0 || n.regions || Object.values(e).some((e) => e.parent === t) || a.some((e) => e.from === t))) throw TypeError("Invalid final state; use a leaf with no outgoing transitions or regions");
12
+ }
13
+ for (let e of a) if (Number(e.always === !0) + Number(e.event !== void 0) + Number(e.after !== void 0) !== 1 || e.always !== void 0 && e.always !== !0 || e.event?.startsWith(n) || e.after !== void 0 && (!Number.isFinite(e.after) || e.after <= 0)) throw TypeError("Invalid transition trigger; give event, positive after or always:true");
14
+ super(e, t, i, a.map((e, t) => ({
15
+ ...e,
16
+ after: void 0,
17
+ event: e.always ? r : e.after === void 0 ? e.event : `${n}${t}`
18
+ }))), this.queue = [], this.lastFinal = null, this.settling = !1, this.steps = 0, this.done = !1, this.definition = a, this.finalStates = e, this.stabilize(void 0);
19
+ }
20
+ plan(e, t) {
21
+ if (e.startsWith(n)) throw TypeError("Reserved event name; use a name without a NUL prefix");
22
+ if (this.done) return null;
23
+ let r = super.plan(e, t);
24
+ return r && (() => {
25
+ r(), this.stabilize(t), this.onStable(t);
26
+ });
27
+ }
28
+ send(e, t) {
29
+ let n = this.plan(e, t);
30
+ return n?.(), !n && !this.done && (this.stabilize(t), this.onStable(t)), n !== null;
31
+ }
32
+ goto(e, t = 0) {
33
+ super.goto(e, t), this.done = !1, this.stabilize(void 0), this.onStable();
34
+ }
35
+ update(e) {
36
+ if (!Number.isFinite(e) || e < 0) throw RangeError("Invalid state delta; pass finite non-negative seconds");
37
+ if (this.done) return;
38
+ this.stabilize(void 0);
39
+ let r = e, i = 0;
40
+ for (;;) {
41
+ let e = !1;
42
+ for (let r of this.activePath().reverse()) {
43
+ for (let a = 0; a < this.definition.length; a++) {
44
+ let o = this.definition[a];
45
+ if (!(o.from !== r || o.after === void 0 || this.clock < this.waitStart(a) + o.after) && this.microstep(`${n}${a}`, void 0)) {
46
+ if (++i > 1e5) throw new t("state", "Too many delayed transitions; use longer delays or a shorter delta");
47
+ this.entered.has(r) && this.waits.set(a, this.clock), this.stabilize(void 0), this.onStable(), e = !0;
48
+ break;
49
+ }
50
+ }
51
+ if (e) break;
52
+ }
53
+ if (this.done) break;
54
+ if (e) continue;
55
+ if (r === 0) break;
56
+ let a = r;
57
+ for (let e = 0; e < this.definition.length; e++) {
58
+ let t = this.definition[e], n = this.waitStart(e);
59
+ if (n === void 0 || t.after === void 0) continue;
60
+ let r = n + t.after - this.clock;
61
+ r > 0 && (a = Math.min(a, r));
62
+ }
63
+ super.update(a), r -= a, this.stabilize(void 0);
64
+ }
65
+ this.onStable();
66
+ }
67
+ onStable(e) {}
68
+ activePath() {
69
+ let e = [];
70
+ for (let t = this.state; t !== void 0; t = this.states[t].parent) e.unshift(t);
71
+ return e;
72
+ }
73
+ microstep(e, t) {
74
+ let n = super.plan(e, t);
75
+ if (!n) return !1;
76
+ let r = this.transitions.map((e) => ({
77
+ event: e.event,
78
+ after: e.after
79
+ }));
80
+ this.transitions.forEach((e, t) => {
81
+ e.event = this.definition[t].event, e.after = this.definition[t].after;
82
+ });
83
+ try {
84
+ n();
85
+ } finally {
86
+ this.transitions.forEach((e, t) => Object.assign(e, r[t]));
87
+ }
88
+ return !0;
89
+ }
90
+ stabilize(e) {
91
+ if (!this.settling) {
92
+ this.settling = !0, this.steps = 0;
93
+ try {
94
+ for (;;) {
95
+ let n = this.finalStates[this.state];
96
+ if (n.final && this.lastFinal !== this.state) {
97
+ if (this.lastFinal = this.state, n.parent === void 0) {
98
+ this.done = !0, this.queue.length = 0;
99
+ return;
100
+ }
101
+ this.queue.push(`done.state.${n.parent}`);
102
+ } else n.final || (this.lastFinal = null);
103
+ if (++this.steps > 1e4) throw new t("state", "Eventless transitions do not settle; break the cycle with a guard or event");
104
+ if (this.microstep(r, e)) continue;
105
+ let i = this.queue.shift();
106
+ if (i === void 0) return;
107
+ this.microstep(i, e);
108
+ }
109
+ } finally {
110
+ this.settling = !1, this.queue.length = 0;
111
+ }
112
+ }
113
+ }
114
+ };
115
+ //#endregion
116
+ export { i as FinalMachine };
@@ -0,0 +1,124 @@
1
+ import type { ParallelRegions } from './parallel.js';
2
+ /** One state of a {@link StateMachine}; `C` is the shared context passed to every hook. */
3
+ export interface State<C> {
4
+ /** Name of the parent state; ancestors stay entered while moving between their children. */
5
+ parent?: string;
6
+ /** Descendant to go on to when this state is the target of a transition. Default none: the machine stops here. */
7
+ initial?: string;
8
+ /**
9
+ * Remember where the machine was when it left this state, and return there when it comes back: `'shallow'` to the
10
+ * child that was active, which then starts as usual; `'deep'` to the exact innermost state. Before the first visit,
11
+ * `initial` applies. Default none.
12
+ */
13
+ history?: 'shallow' | 'deep';
14
+ /** Called on entry, outermost ancestor first. */
15
+ enter?: (context: C) => void;
16
+ /** Called on exit, innermost state first. */
17
+ exit?: (context: C) => void;
18
+ /** Called by `StateMachine.update` for each state on the active path, outermost first, with `delta` in seconds. */
19
+ update?: (context: C, delta: number) => void;
20
+ /**
21
+ * Offer an event to a machine nested in this state, such as parallel regions. Runs on the active path before this
22
+ * state's own transitions, so what is nested wins. Return the action that carries the event out, or null to pass.
23
+ */
24
+ plan?: (event: string) => (() => void) | null;
25
+ /** The regions this state runs, set by `ParallelRegions.asState`, for saving and tracing. */
26
+ regions?: ParallelRegions<C>;
27
+ }
28
+ /** Edge between two states, taken on an event or after a delay; `C` is the shared context the guard gets. */
29
+ export interface Transition<C = unknown> {
30
+ /** Source state; also matches while a descendant of it is active. */
31
+ from: string;
32
+ /** Target state. */
33
+ to: string;
34
+ /** Event name passed to `StateMachine.send`; must be non-empty. Give this or `after`, not both. */
35
+ event?: string;
36
+ /**
37
+ * Seconds in `from` after which `StateMachine.update` takes this transition by itself; finite and above 0. Give this
38
+ * or `event`, not both. The time counts from entering `from`, so moving between its children does not restart it,
39
+ * and leaving it cancels it. A guard that declines is asked again on every update until it passes.
40
+ */
41
+ after?: number;
42
+ /** Cross-fade time in seconds; finite and >= 0. Default 0 (no cross-fade). */
43
+ duration?: number;
44
+ /** Return false to decline the transition. */
45
+ guard?: (context: C) => boolean;
46
+ }
47
+ /** Hierarchical state transitions retain common ancestors and expose cross-fade progress. */
48
+ export declare class StateMachine<C> {
49
+ readonly states: Readonly<Record<string, State<C>>>;
50
+ readonly initial: string;
51
+ readonly context: C;
52
+ readonly transitions: readonly Transition<C>[];
53
+ /** Name of the current (innermost) state. */
54
+ state: string;
55
+ /** State being cross-faded from, or null when no cross-fade is running. */
56
+ previous: string | null;
57
+ /** Seconds since the last state change. */
58
+ elapsed: number;
59
+ /** Seconds this machine has run, from every `update`. */
60
+ clock: number;
61
+ /** Value of `clock` when each active state was entered, by state name, for delayed transitions. */
62
+ readonly entered: Map<string, number>;
63
+ /**
64
+ * When a delayed transition that left its `from` active started waiting again, by its index in `transitions`. Its
65
+ * wait counts from this or from entering `from`, whichever is later, so re-arming one leaves the others alone.
66
+ */
67
+ readonly waits: Map<number, number>;
68
+ /** What each state with `history` remembers, by state name. Delete a key, or clear it, to forget. */
69
+ readonly memory: Map<string, string>;
70
+ /** Length of the running cross-fade in seconds. */
71
+ duration: number;
72
+ /** True while the hooks of a state change run. */
73
+ changing: boolean;
74
+ /** Called on every state change, before any hook, with the transition that caused it, or null for `goto`. */
75
+ listener: ((from: string, to: string, transition: Transition<C> | null) => void) | null;
76
+ private readonly paths;
77
+ private readonly timed;
78
+ /**
79
+ * Build the machine and enter `initial` (and its ancestors).
80
+ * @throws TypeError for an unknown parent, a hierarchy cycle, an unknown initial state, a state's `initial` that is
81
+ * not its descendant, an unknown `history`, or an invalid transition.
82
+ */
83
+ constructor(states: Readonly<Record<string, State<C>>>, initial: string, context: C, transitions?: readonly Transition<C>[]);
84
+ /** Cross-fade progress in [0, 1]; 1 when no cross-fade is running. */
85
+ get blend(): number;
86
+ /** True while `name` is the current state or one of its ancestors. */
87
+ matches(name: string): boolean;
88
+ /**
89
+ * Choose what `event` would do without doing it: guards run, nothing changes. Searches from the current state outward
90
+ * to its ancestors, offering each state's `plan` hook first. Returns the action to run, or null when nothing matched.
91
+ */
92
+ plan(event: string): (() => void) | null;
93
+ /**
94
+ * Fire the first matching transition whose guard passes, searching as {@link StateMachine.plan} does.
95
+ * Returns false when none matched. Throws as {@link StateMachine.goto} does.
96
+ */
97
+ send(event: string): boolean;
98
+ /**
99
+ * Change to `next` directly, exiting and entering only the states below the common ancestor. A `next` being entered
100
+ * goes on to what it remembers, else to its `initial`; one already active goes on to its `initial`. No-op when that
101
+ * is where the machine already is.
102
+ * @param duration Cross-fade time in seconds, finite and >= 0. Default 0.
103
+ * @throws RangeError for an unknown state or invalid `duration`.
104
+ * @throws MargoError `'state'` when called from an enter/exit hook.
105
+ */
106
+ goto(next: string, duration?: number): void;
107
+ private change;
108
+ private resolve;
109
+ /**
110
+ * Advance the machine by `delta` seconds: the cross-fade timer, the active path's update hooks, and delayed
111
+ * transitions. A delay that ends inside `delta` splits it: hooks get the time up to that moment, the transition runs,
112
+ * and the rest goes to the new state, so one long update ends where many short ones do. Stops the hooks of a path if
113
+ * a hook changes state.
114
+ * @throws RangeError when `delta` is negative or not finite.
115
+ * @throws MargoError `'state'` when delayed transitions fire over 100,000 times in one update.
116
+ */
117
+ update(delta: number): void;
118
+ private advance;
119
+ private nextDue;
120
+ private fire;
121
+ /** When the wait of the delayed transition at `index` began, or undefined while its `from` is not active. */
122
+ protected waitStart(index: number): number | undefined;
123
+ private dueTransition;
124
+ }