@earnestjs/xstate 0.0.0-stage → 0.2.1

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,193 @@
1
+ import { type Declaration, type SearchFindingKind, type Status, type Verdict } from "@earnestjs/model";
2
+ import type { AnyMachineSnapshot, AnyStateMachine, ContextFrom, EventFromLogic, EventObject, InputFrom, SnapshotFrom } from "xstate";
3
+ /** A rule `checkMachine` judges in every snapshot it reaches: a sentence and its predicate. */
4
+ export interface MachineRule<TMachine extends AnyStateMachine> {
5
+ readonly says: string;
6
+ holds(snapshot: SnapshotFrom<TMachine>): boolean;
7
+ }
8
+ type EventOfType<TMachine extends AnyStateMachine, Type> = Extract<EventFromLogic<TMachine>, {
9
+ readonly type: Type;
10
+ }>;
11
+ /**
12
+ * A declaration written with `m` from `@earnestjs/model` for each payload field of one event
13
+ * type, every field but `type`. Only declarations of plain JavaScript values are taken: booleans,
14
+ * whole numbers, texts and other `m.enum` or `m.oneOf` values, `.optional()` and `m.record` of
15
+ * those. When several event shapes share a type, the schema declares the fields of one of them.
16
+ * A record payload arrives frozen, as `m.record` gives it, and the same object is sent from every
17
+ * snapshot, so the machine must copy it rather than change it in place.
18
+ */
19
+ export type MachinePayloadSchema<TEvent extends EventObject> = TEvent extends unknown ? {
20
+ readonly [Field in keyof Omit<TEvent, "type">]: Declaration<Omit<TEvent, "type">[Field], never>;
21
+ } : never;
22
+ /**
23
+ * The event types to try, each with a declaration for each of its payload fields, such as
24
+ * `{ PAY: { coins: m.int(1, 2) }, PUSH: {} }`. A type is tried with every combination of the
25
+ * values its fields declare, the first field varying fastest, as `explore` tries an action's
26
+ * inputs; the event sent is `{ type, ...payload }`. Types are tried in the record's key order,
27
+ * where JavaScript puts integer-like keys first. A type with more than 1,000,000 payloads is a
28
+ * `RangeError`.
29
+ */
30
+ export type MachineEventSchema<TMachine extends AnyStateMachine> = {
31
+ readonly [Type in EventFromLogic<TMachine>["type"]]?: MachinePayloadSchema<EventOfType<TMachine, Type>>;
32
+ };
33
+ /**
34
+ * The events to try in every snapshot: a list, or a function of the snapshot that gives one, as
35
+ * in the traversal options of `@xstate/graph`, or a `MachineEventSchema` that declares each
36
+ * event type's payload.
37
+ */
38
+ export type MachineEvents<TMachine extends AnyStateMachine> = readonly EventFromLogic<TMachine>[] | ((snapshot: SnapshotFrom<TMachine>) => readonly EventFromLogic<TMachine>[]) | MachineEventSchema<TMachine>;
39
+ type ContextKey<TContext> = TContext extends unknown ? keyof TContext : never;
40
+ type ContextField<TContext, Key> = TContext extends unknown ? Key extends keyof TContext ? TContext[Key] : never : never;
41
+ type MayLack<TContext, Key> = TContext extends unknown ? Key extends keyof TContext ? {} extends Pick<TContext, Key> ? true : undefined extends TContext[Key] ? true : false : true : never;
42
+ type Declarable<TValue> = TValue extends object ? {
43
+ [Key in keyof TValue]-?: Declarable<Exclude<TValue[Key], undefined>> | (MayLack<TValue, Key> extends false ? never : null);
44
+ } : TValue;
45
+ type DeclaredField<TContext, Key> = Declarable<Exclude<ContextField<TContext, Key>, undefined>> | (MayLack<TContext, Key> extends false ? never : null);
46
+ /**
47
+ * A declaration written with `m` from `@earnestjs/model` for some fields of the machine's
48
+ * context, such as `{ visitors: m.int(0, 3) }`. Only declarations of plain JavaScript values are
49
+ * taken, as in `MachinePayloadSchema`. Fields it does not name are not checked. Any field of any
50
+ * member of a union context can be named, its declaration checked against that field's type in
51
+ * the members that have it. Where a member lacks the field, or the field is optional or may be
52
+ * `undefined`, the declaration may be `.optional()`, which also takes a missing field. The same
53
+ * holds for the fields of a record, at every depth.
54
+ */
55
+ export type MachineContextSchema<TMachine extends AnyStateMachine> = {
56
+ readonly [Field in ContextKey<ContextFrom<TMachine>>]?: Declaration<DeclaredField<ContextFrom<TMachine>, Field>, never>;
57
+ };
58
+ /**
59
+ * What `checkMachine` is given. `events` must list every event to try: XState gives no public
60
+ * way to list a machine's own events. `rules` gives each rule its id, the key it is listed under;
61
+ * the results follow the record's key order, where JavaScript puts integer-like keys first.
62
+ * `input` is the machine's input, used to make the initial snapshot. `maxStates` stops the
63
+ * search before it holds more distinct states than this; the default is 5,000,000. `context`
64
+ * bounds the search: a snapshot whose context has a value outside what `context` declares for
65
+ * it is out of range. A missing field and `undefined` are out of range too, unless the
66
+ * declaration is `.optional()`, which takes them as it takes `null`, also inside a record. A
67
+ * record may hold no field its declaration lacks, unless the field holds `undefined`. A value a
68
+ * record declaration checks must be plain data at every level: an object that is not a plain
69
+ * object, such as a `Date`, is out of range. A snapshot out of range is counted, no rule is
70
+ * judged in it and nothing is searched from it, as `explore` does with a model's state out of
71
+ * range.
72
+ */
73
+ export interface CheckMachineOptions<TMachine extends AnyStateMachine> {
74
+ readonly events: MachineEvents<TMachine>;
75
+ readonly rules?: Readonly<Record<string, MachineRule<TMachine>>>;
76
+ readonly input?: InputFrom<TMachine>;
77
+ readonly maxStates?: number;
78
+ readonly context?: MachineContextSchema<TMachine>;
79
+ }
80
+ /** One event on a path and the snapshot after it. */
81
+ export interface MachineStep<TMachine extends AnyStateMachine> {
82
+ readonly event: EventFromLogic<TMachine>;
83
+ readonly snapshot: SnapshotFrom<TMachine>;
84
+ }
85
+ /**
86
+ * A shortest path from the initial snapshot: `start`, then one step per event. `events` are the
87
+ * events of the steps in order, ready to send to an actor of the machine, and `end` is the last
88
+ * snapshot, `start` when there are no steps.
89
+ */
90
+ export interface MachinePath<TMachine extends AnyStateMachine> {
91
+ readonly start: SnapshotFrom<TMachine>;
92
+ readonly steps: readonly MachineStep<TMachine>[];
93
+ readonly events: readonly EventFromLogic<TMachine>[];
94
+ readonly end: SnapshotFrom<TMachine>;
95
+ }
96
+ /** One rule's result. `path` is the shortest path to a snapshot that breaks it, or `null`. */
97
+ export interface MachineRuleResult<TMachine extends AnyStateMachine> {
98
+ readonly id: string;
99
+ readonly says: string;
100
+ readonly verdict: Verdict;
101
+ readonly path: MachinePath<TMachine> | null;
102
+ }
103
+ /** A problem that is not a broken rule, with the shortest path to the first snapshot showing it. */
104
+ export interface MachineFinding<TMachine extends AnyStateMachine> {
105
+ readonly kind: SearchFindingKind;
106
+ readonly message: string;
107
+ readonly path: MachinePath<TMachine>;
108
+ }
109
+ /**
110
+ * What `checkMachine` found, in the words of `explore` from `@earnestjs/model`. `states` counts
111
+ * distinct states, out-of-range ones included. `findings` holds at most one stuck state, then at
112
+ * most one state out of range. `reason` says why an unfinished check stopped, and is `null`
113
+ * otherwise. `reached` gives the shortest path to every counted state, in the order the search
114
+ * reached them; each path is built as it is asked for.
115
+ */
116
+ export interface MachineCheck<TMachine extends AnyStateMachine> {
117
+ readonly status: Status;
118
+ readonly states: number;
119
+ readonly rules: readonly MachineRuleResult<TMachine>[];
120
+ readonly findings: readonly MachineFinding<TMachine>[];
121
+ readonly reason: string | null;
122
+ reached(): Iterable<MachinePath<TMachine>>;
123
+ }
124
+ /** Whether `value` is a plain object: made by `{}`, `Object.create(null)` or JSON. */
125
+ export declare const isPlain: (value: object) => boolean;
126
+ /**
127
+ * A text that is equal for two values exactly when `checkMachine` takes them for the same part
128
+ * of a state. Throws a `TypeError` for a value that is not plain data.
129
+ */
130
+ export declare const keyOf: (value: unknown) => string;
131
+ /** What each history state of the snapshot remembers, by node id, sorted. */
132
+ export declare const historyOf: ({ historyValue, }: AnyMachineSnapshot) => Readonly<Record<string, string[]>>;
133
+ /** A declaration of plain values, as the options take it. */
134
+ export type Declared = Declaration<unknown, never>;
135
+ /** The declarations of a record of fields, in the record's order. */
136
+ export type Fields = readonly (readonly [string, Declared])[];
137
+ /** What `value` is, in words, for an error that refuses it: `the number 1`, `a function`. */
138
+ export declare const described: (value: unknown) => string;
139
+ /** The advice that ends a refusal of a record of fields. */
140
+ export declare const EACH_FIELD = "give a declaration written with m from @earnestjs/model for each field";
141
+ /**
142
+ * `value` when it is a plain record that is not a declaration; otherwise a `TypeError` in the
143
+ * words of `caller`, saying what `value` is and that `expected` was.
144
+ */
145
+ export declare const fieldRecord: (caller: string, option: string, value: unknown, expected: string) => object;
146
+ /**
147
+ * The declarations of `schema`, the option named `option`, without its `undefined` entries.
148
+ * Throws a `TypeError` in the words of `caller` for an entry that is not a declaration of plain
149
+ * values.
150
+ */
151
+ export declare const plainFields: (caller: string, option: string, schema: object) => Fields;
152
+ /**
153
+ * Each event type of an event schema with the declarations of its payload fields, in the
154
+ * schema's order. Throws a `TypeError` in the words of `caller` for an entry that is not a plain
155
+ * record of declarations, or that declares `type`.
156
+ */
157
+ export declare const payloadsOf: (caller: string, events: object) => readonly (readonly [string, Fields])[];
158
+ /**
159
+ * Whether `value` is one of the values `declared` has, as `checkMachine` judges a context field:
160
+ * an optional is in range when it is `null`, `undefined` or missing, at any depth; a record must
161
+ * be a plain object with no key the declaration lacks, a key holding `undefined` being no key.
162
+ * Pass `undefined` for a missing field.
163
+ */
164
+ export declare const inRange: (declared: Declared, value: unknown) => boolean;
165
+ /**
166
+ * Checks an XState v5 machine as Earnest checks a model: it visits every state reachable from
167
+ * the initial snapshot, breadth first, and gives what `explore` from `@earnestjs/model` gives.
168
+ * That is pass, fail or unfinished, the count of distinct states, each rule's verdict with the
169
+ * shortest path of events to a snapshot that breaks it, and the first stuck state. Two
170
+ * snapshots are one state when their state value, context, status and the states their history
171
+ * states remember are equal, whatever event led there. A machine with a history state counts a
172
+ * state again once a history state remembers something. The context must be plain data: plain objects with string keys, arrays,
173
+ * strings, numbers, booleans, `null`, `undefined`, and values with a `toJSON`, such as a `Date`
174
+ * or an actor ref, read through it. Anything else in it, such as a `Map`, a class instance or a
175
+ * function, is an error. A field set to `undefined` is the same as no field. A final
176
+ * state's output and child actors are not part of the state. An event is tried in a snapshot only when `snapshot.can(event)` is true: a guard that fails, or a
177
+ * transition with no target and no action, is no event at all. A snapshot whose status is
178
+ * `done`, a top-level final state, is an end. Any other snapshot where none of the events can
179
+ * happen is stuck. Events are sent through the machine's `transition`: no action of your own
180
+ * runs, except one made with `assign`, and no child actor starts, but the code that computes the next snapshot does, often
181
+ * more than once: guards, `assign`, `enqueueActions` callbacks, invoke `input` and the context
182
+ * of a child machine. Keep that code free of side effects and give it the same result for the
183
+ * same snapshot and event. Every state found is held in memory with its whole snapshot, so a
184
+ * large machine can run out of memory before the default `maxStates`. An
185
+ * error thrown by a guard, an `assign`, the context factory or a rule is thrown by
186
+ * `checkMachine`, also one XState catches into a snapshot whose status is `error`. A
187
+ * declaration in `context` or in an event schema whose values are not plain JavaScript, such as
188
+ * `m.set(...)`, is a `TypeError` before the search starts, naming the option and the field. So
189
+ * is an entry that is no declaration at all, such as a number or an uncalled `m.int`, and an
190
+ * event type whose payload is not a plain record of fields, a whole `m.record(...)` included.
191
+ */
192
+ export declare const checkMachine: <TMachine extends AnyStateMachine>(machine: TMachine, options: NoInfer<CheckMachineOptions<TMachine>>) => MachineCheck<TMachine>;
193
+ export {};
package/dist/check.js ADDED
@@ -0,0 +1,266 @@
1
+ import { combinationsOf, compareText, search, } from "@earnestjs/model";
2
+ import { stepping } from "./machine.js";
3
+ const STUCK = "none of the listed events can happen here, and the machine is not in a top-level final state";
4
+ /** Whether `value` is a plain object: made by `{}`, `Object.create(null)` or JSON. */
5
+ export const isPlain = (value) => {
6
+ const prototype = Object.getPrototypeOf(value);
7
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
8
+ };
9
+ const kindOf = (value) => typeof value === "object" && value !== null
10
+ ? value.constructor?.name || Object.prototype.toString.call(value).slice(8, -1)
11
+ : typeof value;
12
+ /**
13
+ * A text that is equal for two values exactly when `checkMachine` takes them for the same part
14
+ * of a state. Throws a `TypeError` for a value that is not plain data.
15
+ */
16
+ export const keyOf = (value) => {
17
+ if (typeof value === "number") {
18
+ return value === 0 ? "0" : String(value);
19
+ }
20
+ if (value === undefined || value === null || typeof value === "boolean") {
21
+ return String(value);
22
+ }
23
+ if (typeof value === "string") {
24
+ return JSON.stringify(value);
25
+ }
26
+ if (Array.isArray(value)) {
27
+ const items = [...value.keys()].map((index) => (index in value ? keyOf(value[index]) : "hole"));
28
+ return `[${items.join(",")}]`;
29
+ }
30
+ if (typeof value === "object") {
31
+ const shown = "toJSON" in value && typeof value.toJSON === "function" ? value.toJSON() : value;
32
+ if (shown !== value) {
33
+ return `${kindOf(value)}(${keyOf(shown)})`;
34
+ }
35
+ if (Object.getOwnPropertySymbols(value).length > 0) {
36
+ throw new TypeError("checkMachine tells states apart by their context, and cannot read a symbol key in it; keep the context to plain data");
37
+ }
38
+ if (isPlain(value)) {
39
+ const fields = Object.entries(value)
40
+ .filter(([, field]) => field !== undefined)
41
+ .sort(([a], [b]) => compareText(a, b));
42
+ return `{${fields.map(([name, field]) => `${JSON.stringify(name)}:${keyOf(field)}`).join(",")}}`;
43
+ }
44
+ }
45
+ throw new TypeError(`checkMachine tells states apart by their context, and cannot read this ${kindOf(value)} in it; keep the context to plain data`);
46
+ };
47
+ /** What each history state of the snapshot remembers, by node id, sorted. */
48
+ export const historyOf = ({ historyValue, }) => Object.fromEntries(Object.entries(historyValue).map(([historyNode, remembered]) => [
49
+ historyNode,
50
+ remembered.map((node) => node.id).sort(compareText),
51
+ ]));
52
+ const stateKey = (snapshot) => {
53
+ const { value, context, status, error } = snapshot;
54
+ if (status === "error") {
55
+ throw error;
56
+ }
57
+ return keyOf({ value, context, status, history: historyOf(snapshot) });
58
+ };
59
+ const article = (word) => /^[aeio]/i.test(word) || word.startsWith("u") ? `an ${word}` : `a ${word}`;
60
+ const isDeclaration = (value) => typeof value === "object" &&
61
+ value !== null &&
62
+ typeof Reflect.get(value, "kind") === "string" &&
63
+ typeof Reflect.get(value, "count") === "number" &&
64
+ typeof Reflect.get(value, "has") === "function" &&
65
+ typeof Reflect.get(value, "values") === "function";
66
+ /** What `value` is, in words, for an error that refuses it: `the number 1`, `a function`. */
67
+ export const described = (value) => {
68
+ if (value === null || value === undefined) {
69
+ return String(value);
70
+ }
71
+ if (isDeclaration(value)) {
72
+ return `${article(value.kind)} declaration`;
73
+ }
74
+ if (Array.isArray(value)) {
75
+ return "an array";
76
+ }
77
+ if (typeof value === "object") {
78
+ return isPlain(value) ? "a plain object" : article(kindOf(value));
79
+ }
80
+ if (typeof value === "string") {
81
+ return `the text ${JSON.stringify(value)}`;
82
+ }
83
+ return typeof value === "function" ? "a function" : `the ${typeof value} ${String(value)}`;
84
+ };
85
+ /** The advice that ends a refusal of a record of fields. */
86
+ export const EACH_FIELD = "give a declaration written with m from @earnestjs/model for each field";
87
+ /**
88
+ * `value` when it is a plain record that is not a declaration; otherwise a `TypeError` in the
89
+ * words of `caller`, saying what `value` is and that `expected` was.
90
+ */
91
+ export const fieldRecord = (caller, option, value, expected) => {
92
+ if (typeof value === "object" && value !== null && isPlain(value) && !isDeclaration(value)) {
93
+ return value;
94
+ }
95
+ throw new TypeError(`${caller} can't take ${option}: it is ${described(value)}, not ${expected}`);
96
+ };
97
+ /**
98
+ * The declarations of `schema`, the option named `option`, without its `undefined` entries.
99
+ * Throws a `TypeError` in the words of `caller` for an entry that is not a declaration of plain
100
+ * values.
101
+ */
102
+ export const plainFields = (caller, option, schema) => Object.entries(schema).flatMap(([name, declared]) => {
103
+ if (declared === undefined) {
104
+ return [];
105
+ }
106
+ if (!isDeclaration(declared)) {
107
+ throw new TypeError(`${caller} can't take ${option}.${name}: it is ${described(declared)}, not a declaration; write one with m from @earnestjs/model, such as m.int(0, 3), or m.record({ ... }) for an object`);
108
+ }
109
+ const held = declared.libraryKind;
110
+ const parts = [held, declared.fields, declared.inner];
111
+ if (parts.includes(undefined)) {
112
+ throw new TypeError(`${caller} can't take ${option}.${name}: it was made with an @earnestjs/model older than the one @earnestjs/xstate uses; install the version it depends on`);
113
+ }
114
+ if (held !== null) {
115
+ const holding = held === declared.kind ? "" : ` that holds ${article(held)}`;
116
+ throw new TypeError(`${caller} can't take ${option}.${name}, ${article(declared.kind)} declaration${holding}: its values are objects of @earnestjs/model, not plain data an XState context or event holds; declare booleans, numbers, texts, optionals and records of those`);
117
+ }
118
+ return [[name, declared]];
119
+ });
120
+ /**
121
+ * Each event type of an event schema with the declarations of its payload fields, in the
122
+ * schema's order. Throws a `TypeError` in the words of `caller` for an entry that is not a plain
123
+ * record of declarations, or that declares `type`.
124
+ */
125
+ export const payloadsOf = (caller, events) => Object.entries(events).flatMap(([type, payload]) => {
126
+ if (payload === undefined) {
127
+ return [];
128
+ }
129
+ const option = `events.${type}`;
130
+ const fields = fieldRecord(caller, option, payload, `a record of payload fields; ${EACH_FIELD}, such as { group: m.int(1, 2) }, or {} for none`);
131
+ if (Object.hasOwn(fields, "type")) {
132
+ throw new TypeError(`${caller} can't take ${option}.type: an event's type is its key in events`);
133
+ }
134
+ return [[type, plainFields(caller, option, fields)]];
135
+ });
136
+ const eventListOf = (events) => {
137
+ if (typeof events === "function") {
138
+ return events;
139
+ }
140
+ if (Array.isArray(events)) {
141
+ return () => events;
142
+ }
143
+ const schema = fieldRecord("checkMachine", "events", events, "a list of events, a function that gives one, or a record of event types, such as { ENTER: { group: m.int(1, 2) } }");
144
+ const listed = payloadsOf("checkMachine", schema).flatMap(([type, fields]) => {
145
+ try {
146
+ return combinationsOf(Object.fromEntries(fields)).map((row) => ({ type, ...row }));
147
+ }
148
+ catch (error) {
149
+ throw new RangeError(`checkMachine can't list the payloads of events.${type}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
150
+ }
151
+ });
152
+ return () => listed;
153
+ };
154
+ const eventsToTry = (events, snapshot) => {
155
+ if (snapshot.status !== "active") {
156
+ return [];
157
+ }
158
+ return events(snapshot).filter((event) => snapshot.can(event));
159
+ };
160
+ /**
161
+ * Whether `value` is one of the values `declared` has, as `checkMachine` judges a context field:
162
+ * an optional is in range when it is `null`, `undefined` or missing, at any depth; a record must
163
+ * be a plain object with no key the declaration lacks, a key holding `undefined` being no key.
164
+ * Pass `undefined` for a missing field.
165
+ */
166
+ export const inRange = (declared, value) => {
167
+ const inner = declared.inner;
168
+ if (inner !== null) {
169
+ return value === undefined || value === null || inRange(inner, value);
170
+ }
171
+ const fields = declared.fields;
172
+ if (fields === null) {
173
+ return declared.has(value);
174
+ }
175
+ if (typeof value !== "object" || value === null || Array.isArray(value) || !isPlain(value)) {
176
+ return false;
177
+ }
178
+ return (Object.entries(value).every(([name, field]) => field === undefined || Object.hasOwn(fields, name)) &&
179
+ Object.entries(fields).every(([name, field]) => inRange(field, Object.hasOwn(value, name) ? Reflect.get(value, name) : undefined)));
180
+ };
181
+ const outsideOf = (fields) => ({ snapshot }) => {
182
+ const context = snapshot.context;
183
+ const field = fields.find(([name, declared]) => !inRange(declared, typeof context === "object" && context !== null && Object.hasOwn(context, name)
184
+ ? Reflect.get(context, name)
185
+ : undefined));
186
+ return field === undefined
187
+ ? null
188
+ : `the context field \`${field[0]}\` leaves the values it declares`;
189
+ };
190
+ const toPath = ({ start, steps }) => ({
191
+ start: start.snapshot,
192
+ steps: steps.map(({ move, state }) => ({ event: move, snapshot: state.snapshot })),
193
+ events: steps.map(({ move }) => move),
194
+ end: (steps.at(-1)?.state ?? start).snapshot,
195
+ });
196
+ const toFinding = ({ kind, message, path, }) => ({
197
+ kind,
198
+ message: kind === "stuck" ? STUCK : message,
199
+ path: toPath(path),
200
+ });
201
+ const check = (machine, options) => {
202
+ const events = eventListOf(options.events);
203
+ const context = options.context === undefined
204
+ ? null
205
+ : plainFields("checkMachine", "context", fieldRecord("checkMachine", "context", options.context, `a record of context fields; ${EACH_FIELD}, such as { visitors: m.int(0, 3) }`));
206
+ const found = search({
207
+ ...stepping(machine, {
208
+ ...(options.input === undefined ? {} : { input: options.input }),
209
+ events: (snapshot) => eventsToTry(events, snapshot),
210
+ serializeState: stateKey,
211
+ }),
212
+ rules: Object.entries(options.rules ?? {}).map(([id, rule]) => ({
213
+ id,
214
+ says: rule.says,
215
+ holds: ({ snapshot }) => rule.holds(snapshot),
216
+ })),
217
+ isEnd: ({ snapshot }) => snapshot.status === "done",
218
+ ...(context === null ? {} : { outside: outsideOf(context) }),
219
+ ...(options.maxStates === undefined ? {} : { maxStates: options.maxStates }),
220
+ });
221
+ return {
222
+ status: found.status,
223
+ states: found.states,
224
+ rules: found.rules.map(({ id, says, verdict, path }) => ({
225
+ id,
226
+ says,
227
+ verdict,
228
+ path: path === null ? null : toPath(path),
229
+ })),
230
+ findings: found.findings.map(toFinding),
231
+ reason: found.reason,
232
+ *reached() {
233
+ for (const trail of found.reached()) {
234
+ yield toPath(trail);
235
+ }
236
+ },
237
+ };
238
+ };
239
+ /**
240
+ * Checks an XState v5 machine as Earnest checks a model: it visits every state reachable from
241
+ * the initial snapshot, breadth first, and gives what `explore` from `@earnestjs/model` gives.
242
+ * That is pass, fail or unfinished, the count of distinct states, each rule's verdict with the
243
+ * shortest path of events to a snapshot that breaks it, and the first stuck state. Two
244
+ * snapshots are one state when their state value, context, status and the states their history
245
+ * states remember are equal, whatever event led there. A machine with a history state counts a
246
+ * state again once a history state remembers something. The context must be plain data: plain objects with string keys, arrays,
247
+ * strings, numbers, booleans, `null`, `undefined`, and values with a `toJSON`, such as a `Date`
248
+ * or an actor ref, read through it. Anything else in it, such as a `Map`, a class instance or a
249
+ * function, is an error. A field set to `undefined` is the same as no field. A final
250
+ * state's output and child actors are not part of the state. An event is tried in a snapshot only when `snapshot.can(event)` is true: a guard that fails, or a
251
+ * transition with no target and no action, is no event at all. A snapshot whose status is
252
+ * `done`, a top-level final state, is an end. Any other snapshot where none of the events can
253
+ * happen is stuck. Events are sent through the machine's `transition`: no action of your own
254
+ * runs, except one made with `assign`, and no child actor starts, but the code that computes the next snapshot does, often
255
+ * more than once: guards, `assign`, `enqueueActions` callbacks, invoke `input` and the context
256
+ * of a child machine. Keep that code free of side effects and give it the same result for the
257
+ * same snapshot and event. Every state found is held in memory with its whole snapshot, so a
258
+ * large machine can run out of memory before the default `maxStates`. An
259
+ * error thrown by a guard, an `assign`, the context factory or a rule is thrown by
260
+ * `checkMachine`, also one XState catches into a snapshot whose status is `error`. A
261
+ * declaration in `context` or in an event schema whose values are not plain JavaScript, such as
262
+ * `m.set(...)`, is a `TypeError` before the search starts, naming the option and the field. So
263
+ * is an entry that is no declaration at all, such as a number or an uncalled `m.int`, and an
264
+ * event type whose payload is not a plain record of fields, a whole `m.record(...)` included.
265
+ */
266
+ export const checkMachine = (machine, options) => check(machine, options);
@@ -0,0 +1,5 @@
1
+ export { checkMachine } from "./check.ts";
2
+ export type { CheckMachineOptions, MachineCheck, MachineContextSchema, MachineEventSchema, MachineEvents, MachineFinding, MachinePath, MachinePayloadSchema, MachineRule, MachineRuleResult, MachineStep, } from "./check.ts";
3
+ export { earnestPaths } from "./paths.ts";
4
+ export { MOST_TABLE_ROWS, modelFileOf } from "./model-file.ts";
5
+ export type { MachineModelFile, MachineThrow, ModelFileOptions } from "./model-file.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { checkMachine } from "./check.js";
2
+ export { earnestPaths } from "./paths.js";
3
+ export { MOST_TABLE_ROWS, modelFileOf } from "./model-file.js";
@@ -0,0 +1,26 @@
1
+ import type { SearchInput } from "@earnestjs/model";
2
+ import type { TraversalOptions } from "@xstate/graph";
3
+ import { type ActorLogic, type AnyActorScope, type EventObject, type Snapshot } from "xstate";
4
+ /**
5
+ * A snapshot the search reached, with the event that led to it and the snapshot before that
6
+ * event. A start has neither. `serializeState` is given all three, as XState gives them.
7
+ */
8
+ export interface Arrival<TSnapshot, TEvent> {
9
+ readonly snapshot: TSnapshot;
10
+ readonly event: TEvent | undefined;
11
+ readonly before: TSnapshot | undefined;
12
+ }
13
+ /**
14
+ * The actor scope `@xstate/graph` steps logic with: built on `createEmptyActor()`, it runs no
15
+ * side effect, so a transition only computes the next snapshot.
16
+ */
17
+ export declare const quietScope: () => AnyActorScope;
18
+ /**
19
+ * What `search` needs to step XState logic as `@xstate/graph` does with the options
20
+ * `TestModel.getPaths` passes on: the start is `fromState`, or the initial snapshot made with
21
+ * `input`; states are keyed by `serializeState`, which defaults to `JSON.stringify` of the
22
+ * snapshot; the moves are the events `events` lists (none by default), each sent through
23
+ * `logic.transition`; and no event is sent from a snapshot for which `stopWhen` is true, or,
24
+ * without `stopWhen`, for which `toState` is.
25
+ */
26
+ export declare const stepping: <TSnapshot extends Snapshot<unknown>, TEvent extends EventObject, TInput>(logic: ActorLogic<TSnapshot, TEvent, TInput>, options: TraversalOptions<TSnapshot, TEvent, TInput>) => Pick<SearchInput<Arrival<TSnapshot, TEvent>, TEvent>, "starts" | "key" | "moves">;
@@ -0,0 +1,48 @@
1
+ import { createEmptyActor, } from "xstate";
2
+ /**
3
+ * The actor scope `@xstate/graph` steps logic with: built on `createEmptyActor()`, it runs no
4
+ * side effect, so a transition only computes the next snapshot.
5
+ */
6
+ export const quietScope = () => {
7
+ const emptyActor = createEmptyActor();
8
+ return {
9
+ self: emptyActor,
10
+ logger: console.log,
11
+ id: "",
12
+ sessionId: Math.random().toString(32).slice(2),
13
+ defer: () => { },
14
+ system: emptyActor.system,
15
+ stopChild: () => { },
16
+ emit: () => { },
17
+ actionExecutor: () => { },
18
+ };
19
+ };
20
+ /**
21
+ * What `search` needs to step XState logic as `@xstate/graph` does with the options
22
+ * `TestModel.getPaths` passes on: the start is `fromState`, or the initial snapshot made with
23
+ * `input`; states are keyed by `serializeState`, which defaults to `JSON.stringify` of the
24
+ * snapshot; the moves are the events `events` lists (none by default), each sent through
25
+ * `logic.transition`; and no event is sent from a snapshot for which `stopWhen` is true, or,
26
+ * without `stopWhen`, for which `toState` is.
27
+ */
28
+ export const stepping = (logic, options) => {
29
+ const scope = quietScope();
30
+ const snapshot = options.fromState ?? logic.getInitialSnapshot(scope, options.input);
31
+ const serializeState = options.serializeState ?? ((state) => JSON.stringify(state));
32
+ const events = options.events ?? [];
33
+ const stopWhen = options.stopWhen ?? options.toState;
34
+ return {
35
+ starts: [{ snapshot, event: undefined, before: undefined }],
36
+ key: ({ snapshot, event, before }) => serializeState(snapshot, event, before),
37
+ moves: ({ snapshot }) => {
38
+ if (stopWhen?.(snapshot) ?? false) {
39
+ return [];
40
+ }
41
+ const sent = typeof events === "function" ? events(snapshot) : events;
42
+ return sent.map((event) => ({
43
+ move: event,
44
+ next: { snapshot: logic.transition(snapshot, event, scope), event, before: snapshot },
45
+ }));
46
+ },
47
+ };
48
+ };
@@ -0,0 +1,74 @@
1
+ import { type Row } from "@earnestjs/model";
2
+ import type { AnyStateMachine } from "xstate";
3
+ import { type CheckMachineOptions } from "./check.ts";
4
+ /**
5
+ * The most rows `modelFileOf` tabulates: for every state of the machine, one row for each
6
+ * combination of declared context values with each event and payload, and one with each rule.
7
+ */
8
+ export declare const MOST_TABLE_ROWS = 100000;
9
+ /** What `modelFileOf` is given: what `checkMachine` is given, and the name of the model. */
10
+ export interface ModelFileOptions<TMachine extends AnyStateMachine> extends CheckMachineOptions<TMachine> {
11
+ readonly name: string;
12
+ }
13
+ /**
14
+ * A point of the table where the machine's own code threw, or XState caught an error into a
15
+ * snapshot whose status is `error`. `part` says whether it was an event's guard or transition
16
+ * (`id` is the event type) or a rule (`id` is the rule's id). `state` is the label of the
17
+ * machine's state in the model file, `context` and `payload` the values it was tried with.
18
+ */
19
+ export interface MachineThrow {
20
+ readonly part: "transition" | "rule";
21
+ readonly id: string;
22
+ readonly state: string;
23
+ readonly context: Row;
24
+ readonly payload: Row;
25
+ readonly error: unknown;
26
+ }
27
+ /**
28
+ * A machine written out as a model file. `text` is the file. `threw` lists every point of the
29
+ * table where the machine's code threw; the file makes reaching one visible: an event there
30
+ * sets the field `threw` out of its range, and a rule there is broken. `actions` gives the event
31
+ * type of each action the file exports, by its id, and `rules` the id in `rules` of each rule it
32
+ * exports, by its id, for an id that had to change to be a name in the file.
33
+ */
34
+ export interface MachineModelFile {
35
+ readonly text: string;
36
+ readonly threw: readonly MachineThrow[];
37
+ readonly actions: Readonly<Record<string, string>>;
38
+ readonly rules: Readonly<Record<string, string>>;
39
+ }
40
+ /**
41
+ * Writes an XState v5 machine out as the text of a `.model.ts` file, so `earnest verify` and
42
+ * TLC can redo the search `checkMachine` does without running JavaScript. It takes what
43
+ * `checkMachine` takes, and `name`, the model's name. Every value must be declared: each
44
+ * context field in `context`, and each payload field in an `events` record; `events` may also be
45
+ * a list of events without payloads. The machine's own `transition` is run with every declared
46
+ * event and payload on every state value it can take, with every combination of declared context
47
+ * values, not only the ones `checkMachine` reaches, and the results are written as tables. No
48
+ * guard or `assign` is read as source, so they may call any code. The model has a field `state`
49
+ * (`state_2` if the context has a `state`), a readable label for the state value and what the
50
+ * history states remember, and one field per declared context field, starting where the initial
51
+ * snapshot made with `input` starts. Each event type is an action, each rule a rule with the
52
+ * same sentence, and a top-level final state an end. An id that is not a name in a model file,
53
+ * such as `user.click`, is changed to one, such as `user_click`. Where `checkMachine` reaches a
54
+ * state, the machine is given the context `checkMachine` reaches there, so a field missing,
55
+ * `undefined` or `null` stays as the machine left it. Elsewhere an optional context field's
56
+ * `null` is given as a missing field when the initial context lacks the field or holds
57
+ * `undefined`, and as `null` otherwise, and inside a record as `null`. A missing field and
58
+ * `undefined` read back as `null`.
59
+ * A rule is judged on a snapshot rebuilt with `resolveState`, which has no output and no child
60
+ * actors, so a rule must not read them.
61
+ * `maxStates` is not written; pass `--max-states` to `earnest verify`. The same machine and
62
+ * options give the same text. Refused before any event is tried, with an error that names what
63
+ * is wrong: a context field without a declaration, a field name that is not an identifier,
64
+ * `events` given as a function or a list entry with a payload, a model name that is not an
65
+ * identifier, an initial context outside its declarations, and context declarations and events
66
+ * whose table has more than `MOST_TABLE_ROWS` rows for one state. A table that passes the limit
67
+ * as states are found is refused then. So is a machine that reaches an optional field, at any
68
+ * depth, as `null` in one state and missing or `undefined` in another that is otherwise the
69
+ * same, naming the event and the field: `checkMachine` counts two states there, and the file
70
+ * has one `null` for both. A next context the declaration's type can't hold, such as text in a
71
+ * field declared `m.int`, is refused with the event and the field; one of the right
72
+ * type outside the declaration is written as it is, so `earnest verify` reports it out of range.
73
+ */
74
+ export declare const modelFileOf: <TMachine extends AnyStateMachine>(machine: TMachine, options: NoInfer<ModelFileOptions<TMachine>>) => MachineModelFile;