@earnestjs/model 0.1.0 → 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.
@@ -5,9 +5,12 @@ const shown = (value) => value === undefined || typeof value === "function" || t
5
5
  ? String(value)
6
6
  : JSON.stringify(isRecord(value) || value instanceof ModelValue ? toJson(value) : value);
7
7
  const unreadable = (kind, json) => new Error(`${JSON.stringify(json)} can't be read as a ${kind}`);
8
- const optionalOf = (inner) => ({
8
+ const optionalOf = (inner, declared) => ({
9
9
  kind: "optional",
10
+ source: `${inner.source}.optional()`,
10
11
  count: inner.count + 1,
12
+ libraryKind: inner.libraryKind,
13
+ inner: declared,
11
14
  rest: null,
12
15
  values: () => [null, ...inner.values()],
13
16
  has: (value) => value === null || inner.has(value),
@@ -36,6 +39,40 @@ export class Declaration {
36
39
  get count() {
37
40
  return this.#shape.count;
38
41
  }
42
+ /**
43
+ * Where the values are not plain JavaScript, the kind of the first part that holds objects of
44
+ * this library, such as `SetValue`: `"set"` for `m.set(item)`, also inside `.optional()` or a
45
+ * record. `null` when every value is a boolean, a number, a text, `null` or a record of those,
46
+ * values that any JavaScript code can hold, copy and compare by content.
47
+ */
48
+ get libraryKind() {
49
+ return this.#shape.libraryKind;
50
+ }
51
+ /**
52
+ * The `m` expression that declares the same values, as a model file writes it, such as
53
+ * `m.int(0, 3).optional()` or `m.record({ seat: m.enum(["A", "B"]) })`. It leaves out
54
+ * `.initial`. Code that writes model files puts it after `m.model`'s field names.
55
+ */
56
+ get source() {
57
+ return this.#shape.source;
58
+ }
59
+ /**
60
+ * For a declaration made with `m.record`, the declaration of each field, as given to
61
+ * `m.record`; `null` for every other kind, an optional record included. Code that checks a
62
+ * value field by field reads it, as `@earnestjs/xstate` does to let an optional field inside a
63
+ * record be missing.
64
+ */
65
+ get fields() {
66
+ return this.#shape.fields ?? null;
67
+ }
68
+ /**
69
+ * For a declaration made with `.optional()`, the same declaration without `null` and without
70
+ * `.initial`; `null` for every other kind. Code that checks a value against the declaration
71
+ * step by step reads it, as `fields` is read for a record.
72
+ */
73
+ get inner() {
74
+ return this.#shape.inner ?? null;
75
+ }
39
76
  /**
40
77
  * Every value, in the order the checker tries them: `false` before `true`, numbers upward,
41
78
  * enum values as listed, `null` before the values of an optional, a record's fields in the
@@ -88,9 +125,37 @@ export class Declaration {
88
125
  if (this.kind === "optional" || this.kind === "owned lock") {
89
126
  throw new Error(`an ${this.kind} can't be made optional: it already has a null value`);
90
127
  }
91
- return new Declaration(optionalOf(this.#shape), this.#initial);
128
+ return new Declaration(optionalOf(this.#shape, new Declaration(this.#shape)), this.#initial);
92
129
  }
93
130
  }
131
+ /**
132
+ * The value a field declared as `declared` starts at when it is given `value` as `.initial`
133
+ * would be. Throws when `value` is not a value of the declaration.
134
+ */
135
+ export const startingAt = (declared, value) => {
136
+ const given = declared;
137
+ return given.initial(value).starts()[0];
138
+ };
139
+ const combinationCount = (entries) => entries.reduce((total, [, declared]) => total * declared.count, 1);
140
+ /**
141
+ * Every row of values the declarations in `entries` give, in the order the checker tries an
142
+ * action's inputs: the first name varies fastest.
143
+ */
144
+ export const rowsOf = (entries) => entries.reduceRight((rest, [name, declared]) => rest.flatMap((later) => declared.values().map((value) => ({ [name]: value, ...later }))), [{}]);
145
+ /**
146
+ * Every combination of one value for each of `fields`, in the order `explore` tries an action's
147
+ * inputs: the first field varies fastest, each through its values in the order of `values()`.
148
+ * Gives one empty row when there are no fields. Throws, before it lists any, when there are more
149
+ * than `MOST_VALUES_LISTED` combinations.
150
+ */
151
+ export const combinationsOf = (fields) => {
152
+ const entries = Object.entries(fields);
153
+ const count = combinationCount(entries);
154
+ if (count > MOST_VALUES_LISTED) {
155
+ throw new Error(`these fields have ${count} combinations of values, too many to list; declare fewer values`);
156
+ }
157
+ return rowsOf(entries);
158
+ };
94
159
  const plain = (kind, json) => {
95
160
  if (typeof json === "object") {
96
161
  throw unreadable(kind, json);
@@ -101,6 +166,8 @@ const same = (value) => value;
101
166
  /** Declares a field that is `true` or `false`. */
102
167
  export const booleanOf = () => new Declaration({
103
168
  kind: "boolean",
169
+ source: "m.boolean()",
170
+ libraryKind: null,
104
171
  count: 2,
105
172
  rest: null,
106
173
  values: () => [false, true],
@@ -119,6 +186,8 @@ export const int = (lo, hi) => {
119
186
  }
120
187
  return new Declaration({
121
188
  kind: "number",
189
+ source: `m.int(${lo}, ${hi})`,
190
+ libraryKind: null,
122
191
  count: hi - lo + 1,
123
192
  rest: null,
124
193
  values: () => Array.from({ length: hi - lo + 1 }, (_, position) => lo + position),
@@ -140,6 +209,8 @@ const choice = (builder, options) => {
140
209
  }
141
210
  return new Declaration({
142
211
  kind: "enum",
212
+ source: `${builder}([${listed.map((option) => JSON.stringify(option)).join(", ")}])`,
213
+ libraryKind: null,
143
214
  count: listed.length,
144
215
  rest: null,
145
216
  values: () => listed,
@@ -155,6 +226,7 @@ export const enumOf = (options) => choice("m.enum", options);
155
226
  * booleans. Its type is the union of those literals.
156
227
  */
157
228
  export const oneOf = (options) => choice("m.oneOf", options);
229
+ const propertyName = (name) => /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
158
230
  const product = (prefixes, options) => prefixes.flatMap((prefix) => options.map((option) => [...prefix, option]));
159
231
  /**
160
232
  * Declares a record: an object with exactly the given fields. Read a field with `r.field` and
@@ -168,7 +240,10 @@ export const record = (fields) => {
168
240
  entries.every(([name, declared]) => declared.has(value[name]));
169
241
  return new Declaration({
170
242
  kind: "record",
171
- count: entries.reduce((total, [, declared]) => total * declared.count, 1),
243
+ source: `m.record({${entries.length === 0 ? "" : ` ${entries.map(([name, declared]) => `${propertyName(name)}: ${declared.source}`).join(", ")} `}})`,
244
+ count: combinationCount(entries),
245
+ fields: Object.freeze({ ...fields }),
246
+ libraryKind: entries.find(([, declared]) => declared.libraryKind !== null)?.[1].libraryKind ?? null,
172
247
  rest: null,
173
248
  values: () => entries
174
249
  .reduce((partial, [name, declared]) => partial.flatMap((prefix) => declared.values().map((value) => ({ ...prefix, [name]: value }))), [{}])
@@ -204,6 +279,8 @@ const mapsOver = (keys, values) => keys.reduce((smaller, key) => [
204
279
  /** Declares a set of values of `item`. Without `.initial` it starts empty. */
205
280
  export const set = (item) => new Declaration({
206
281
  kind: "set",
282
+ source: `m.set(${item.source})`,
283
+ libraryKind: "set",
207
284
  count: 2 ** item.count,
208
285
  rest: { value: SetValue.of([]) },
209
286
  values: () => subsets(item.values()),
@@ -225,6 +302,8 @@ export const map = (key, valueDeclared) => {
225
302
  const value = holdable("m.map", valueDeclared);
226
303
  return new Declaration({
227
304
  kind: "map",
305
+ source: `m.map(${key.source}, ${value.source})`,
306
+ libraryKind: "map",
228
307
  count: (value.count + 1) ** key.count,
229
308
  rest: { value: MapValue.of([]) },
230
309
  values: () => mapsOver(key.values(), value.values()),
@@ -266,6 +345,8 @@ export const seq = (itemDeclared, limit) => {
266
345
  const max = wholeLimit("m.seq's max", limit.max);
267
346
  return new Declaration({
268
347
  kind: "sequence",
348
+ source: `m.seq(${item.source}, { max: ${max} })`,
349
+ libraryKind: "sequence",
269
350
  count: listCount(item.count, max),
270
351
  rest: { value: SeqValue.of([]) },
271
352
  values: () => lists(item.values(), max).map((items) => SeqValue.of(items)),
@@ -285,6 +366,8 @@ export const queue = (itemDeclared, limit) => {
285
366
  const capacity = wholeLimit("m.queue's capacity", limit.capacity);
286
367
  return new Declaration({
287
368
  kind: "queue",
369
+ source: `m.queue(${item.source}, { capacity: ${capacity} })`,
370
+ libraryKind: "queue",
288
371
  count: listCount(item.count, capacity),
289
372
  rest: { value: QueueValue.of(capacity, []) },
290
373
  values: () => lists(item.values(), capacity).map((items) => QueueValue.of(capacity, items)),
@@ -298,6 +381,8 @@ export const queue = (itemDeclared, limit) => {
298
381
  };
299
382
  const plainLock = () => new Declaration({
300
383
  kind: "lock",
384
+ source: "m.lock()",
385
+ libraryKind: "lock",
301
386
  count: 2,
302
387
  rest: { value: LockValue.of(false) },
303
388
  values: () => [LockValue.of(false), LockValue.of(true)],
@@ -316,6 +401,8 @@ const ownedLock = (owner) => {
316
401
  }
317
402
  return new Declaration({
318
403
  kind: "owned lock",
404
+ source: `m.lock(${owner.source})`,
405
+ libraryKind: "owned lock",
319
406
  count: owner.count + 1,
320
407
  rest: { value: OwnedLockValue.of(null) },
321
408
  values: () => [
@@ -334,6 +421,8 @@ const staged = (kind, stages, at, has) => {
334
421
  const values = stages.map(at);
335
422
  return new Declaration({
336
423
  kind,
424
+ source: `m.${kind}()`,
425
+ libraryKind: kind,
337
426
  count: values.length,
338
427
  rest: values[0] === undefined ? null : { value: values[0] },
339
428
  values: () => values,
@@ -364,6 +453,8 @@ export const retry = (limit) => {
364
453
  const max = wholeLimit("m.retry's max", limit.max);
365
454
  return new Declaration({
366
455
  kind: "retry",
456
+ source: `m.retry({ max: ${max} })`,
457
+ libraryKind: "retry",
367
458
  count: max + 1,
368
459
  rest: { value: RetryValue.of(max, 0) },
369
460
  values: () => Array.from({ length: max + 1 }, (_, attempts) => RetryValue.of(max, attempts)),
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  export * as m from "./m.ts";
2
- export { Declaration, MOST_VALUES_LISTED } from "./declarations.ts";
2
+ export { Declaration, MOST_VALUES_LISTED, combinationsOf } from "./declarations.ts";
3
3
  export type { Fields, StateOf, ValueOf } from "./declarations.ts";
4
4
  export { Model } from "./model.ts";
5
- export type { Action, ActionRunner, ActionSpec, AnyModel, End, EndRunner, NoInput, Rule, RuleRunner, Runners, View, ViewSpec, } from "./model.ts";
5
+ export type { Action, ActionOf, ActionRunner, ActionSpec, AnyModel, End, EndRunner, Eventually, EventuallyRunner, EventuallySpec, NoInput, Rule, RuleRunner, Runners, Setup, SetupRunner, Step as WitnessStep, View, ViewSpec, Witness, WitnessRunner, WitnessSpec, } from "./model.ts";
6
6
  export { replay } from "./replay.ts";
7
7
  export type { ReplayOptions, ReplayPath, ReplayStep, StateJson } from "./replay.ts";
8
- export { DEFAULT_MAX_STATES, explore } from "./search.ts";
9
- export type { Change, Exploration, ExploreOptions, Exports, Finding, FindingKind, Named, Path, RuleResult, Status, Step, Verdict, } from "./search.ts";
8
+ export { DEFAULT_MAX_STATES, search } from "./breadth.ts";
9
+ export type { SearchFinding, SearchFindingKind, SearchInput, SearchMove, SearchResult, SearchRule, SearchRuleResult, Status, Trail, TrailStep, Verdict, } from "./breadth.ts";
10
+ export { explore } from "./search.ts";
11
+ export type { Change, Exploration, ExploreOptions, Exports, Finding, FindingKind, Named, Path, RuleResult, Step, } from "./search.ts";
10
12
  export { LockValue, MapValue, ModelValue, OwnedLockValue, QueueValue, RequestValue, RetryValue, SeqValue, SetValue, TimerValue, compareText, } from "./values.ts";
11
13
  export type { Json, RequestStage, Row, TimerStage } from "./values.ts";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export * as m from "./m.js";
2
- export { Declaration, MOST_VALUES_LISTED } from "./declarations.js";
2
+ export { Declaration, MOST_VALUES_LISTED, combinationsOf } from "./declarations.js";
3
3
  export { Model } from "./model.js";
4
4
  export { replay } from "./replay.js";
5
- export { DEFAULT_MAX_STATES, explore } from "./search.js";
5
+ export { DEFAULT_MAX_STATES, search } from "./breadth.js";
6
+ export { explore } from "./search.js";
6
7
  export { LockValue, MapValue, ModelValue, OwnedLockValue, QueueValue, RequestValue, RetryValue, SeqValue, SetValue, TimerValue, compareText, } from "./values.js";
package/dist/m.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Declaration, Fields, StateOf } from "./declarations.ts";
2
2
  import type { Model } from "./model.ts";
3
3
  export { booleanOf as boolean, enumOf as enum, exists, forall, int, lock, map, oneOf, queue, record, request, retry, seq, set, timer, } from "./declarations.ts";
4
- export { action, end, model, rule, view } from "./model.ts";
4
+ export { action, end, eventually, model, rule, setup, step, view, witness } from "./model.ts";
5
5
  export { div, mapOf, rem, seqOf, setOf, some } from "./values.ts";
6
6
  /**
7
7
  * The type a model's state has, or the type of a declaration's values:
package/dist/m.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { booleanOf as boolean, enumOf as enum, exists, forall, int, lock, map, oneOf, queue, record, request, retry, seq, set, timer, } from "./declarations.js";
2
- export { action, end, model, rule, view } from "./model.js";
2
+ export { action, end, eventually, model, rule, setup, step, view, witness } from "./model.js";
3
3
  export { div, mapOf, rem, seqOf, setOf, some } from "./values.js";
package/dist/model.d.ts CHANGED
@@ -14,12 +14,15 @@ export type OnlyFields<F extends Fields, Changes> = Changes & {
14
14
  * given when it happens, and types the second parameter of `when` and `changes`; leave it out
15
15
  * for an action that takes none. `when` says in which states, and for which inputs, the action
16
16
  * can happen; leave it out for an action that always can. `changes` gives back only the fields
17
- * that change, and must not change the state it is given.
17
+ * that change, and must not change the state it is given. `fair: true` says the action is not
18
+ * put off forever: a run in which it stays possible and never changes the state breaks no
19
+ * `m.eventually` rule.
18
20
  */
19
21
  export interface ActionSpec<F extends Fields, I extends Fields, Changes extends Partial<StateOf<F>> = Partial<StateOf<F>>> {
20
22
  readonly input?: I;
21
23
  readonly when?: (state: StateOf<F>, input: StateOf<I>) => boolean;
22
24
  readonly changes: (state: StateOf<F>, input: StateOf<I>) => OnlyFields<F, Changes>;
25
+ readonly fair?: boolean;
23
26
  }
24
27
  /**
25
28
  * One thing that can happen in a model. Export it from the model file: the name of the export is
@@ -47,6 +50,68 @@ export interface End<F extends Fields> {
47
50
  readonly says: string;
48
51
  readonly when: (state: StateOf<F>) => boolean;
49
52
  }
53
+ /**
54
+ * Other values for some fields to start at: `earnest verify` checks the model once more from
55
+ * them, and `explore` does when it is given the setup. The name of its export is its id.
56
+ */
57
+ export interface Setup<F extends Fields> {
58
+ readonly kind: "setup";
59
+ readonly says: string;
60
+ readonly starts: Partial<StateOf<F>>;
61
+ }
62
+ /**
63
+ * What `m.eventually` is given. `reaches` is the condition every run must come to. `after` says
64
+ * where the rule starts: in every reachable state where it is true. Without `after` the rule
65
+ * starts in every start state.
66
+ */
67
+ export interface EventuallySpec<F extends Fields> {
68
+ readonly after?: (state: StateOf<F>) => boolean;
69
+ readonly reaches: (state: StateOf<F>) => boolean;
70
+ }
71
+ /** A rule about whole runs: a state every run reaches. The name of its export is its id. */
72
+ export interface Eventually<F extends Fields> {
73
+ readonly kind: "eventually";
74
+ readonly says: string;
75
+ readonly after: ((state: StateOf<F>) => boolean) | undefined;
76
+ readonly reaches: (state: StateOf<F>) => boolean;
77
+ }
78
+ /**
79
+ * One step of a witness: an action with the value of each of its inputs. Make one with
80
+ * `m.step(action, { name: value })`; an action without inputs is a step as it is.
81
+ */
82
+ export interface Step<F extends Fields> {
83
+ readonly kind: "step";
84
+ readonly action: ActionOf<F>;
85
+ readonly input: Row;
86
+ }
87
+ /** An action of a model with the fields `F`, whatever its inputs are. */
88
+ export interface ActionOf<F extends Fields> {
89
+ readonly kind: "action";
90
+ readonly sentence: string;
91
+ readonly when: (state: StateOf<F>, input: never) => boolean;
92
+ readonly changes: (state: StateOf<F>, input: never) => Partial<StateOf<F>>;
93
+ }
94
+ /**
95
+ * What `m.witness` is given: the actions to take in order, and the condition that must be true
96
+ * after the last one. With `setup`, the path is played from that setup's start states and the
97
+ * witness is reported with that setup; without it, from the model's own start states.
98
+ */
99
+ export interface WitnessSpec<F extends Fields> {
100
+ readonly setup?: Setup<F>;
101
+ readonly steps: readonly (Action<F> | Step<F>)[];
102
+ readonly expect: (state: StateOf<F>) => boolean;
103
+ }
104
+ /**
105
+ * A path the model must be able to take from every start state, with a condition on the state
106
+ * it ends in. The name of its export is its id.
107
+ */
108
+ export interface Witness<F extends Fields> {
109
+ readonly kind: "witness";
110
+ readonly says: string;
111
+ readonly setup: Setup<F> | undefined;
112
+ readonly steps: readonly Step<F>[];
113
+ readonly expect: (state: StateOf<F>) => boolean;
114
+ }
50
115
  /**
51
116
  * What `m.view` is given, all of it optional: the chart's title, the label of a state, the
52
117
  * group a state is drawn in, arrow labels by action id (the default is the action's sentence)
@@ -75,6 +140,7 @@ export interface View<F extends Fields> extends ViewSpec<F> {
75
140
  export interface ActionRunner {
76
141
  readonly part: object;
77
142
  readonly sentence: string;
143
+ readonly fair?: boolean;
78
144
  readonly inputs: readonly (readonly [string, Declaration<unknown, never>])[];
79
145
  when(state: Row, input: Row): boolean;
80
146
  changes(state: Row, input: Row): Row;
@@ -91,11 +157,45 @@ export interface EndRunner {
91
157
  readonly says: string;
92
158
  when(state: Row): boolean;
93
159
  }
160
+ /**
161
+ * A rule about runs as a search judges it. `after` is `null` for a rule that starts in every
162
+ * start state. Both throw when the state is outside what was declared.
163
+ */
164
+ export interface EventuallyRunner {
165
+ readonly part: object;
166
+ readonly says: string;
167
+ readonly after: ((state: Row) => boolean) | null;
168
+ reaches(state: Row): boolean;
169
+ }
170
+ /**
171
+ * A witness as a search plays it: each step is an action of the same `Runners` with its input.
172
+ * `setup` is the `part` of the setup it is played in, when it names one. `expect` throws when
173
+ * the state is outside what was declared.
174
+ */
175
+ export interface WitnessRunner {
176
+ readonly part: object;
177
+ readonly says: string;
178
+ readonly setup?: object;
179
+ readonly steps: readonly {
180
+ readonly action: ActionRunner;
181
+ readonly input: Row;
182
+ }[];
183
+ expect(state: Row): boolean;
184
+ }
185
+ /** A setup as a search starts in it: `starts` holds the fields that start elsewhere. */
186
+ export interface SetupRunner {
187
+ readonly part: object;
188
+ readonly says: string;
189
+ readonly starts: Row;
190
+ }
94
191
  /** Everything declared on a model so far, each list in declaration order. */
95
192
  export interface Runners {
96
193
  readonly actions: readonly ActionRunner[];
97
194
  readonly rules: readonly RuleRunner[];
98
195
  readonly ends: readonly EndRunner[];
196
+ readonly eventually?: readonly EventuallyRunner[];
197
+ readonly witnesses?: readonly WitnessRunner[];
198
+ readonly setups?: readonly SetupRunner[];
99
199
  }
100
200
  /**
101
201
  * What `explore` and `replay` need of a model, whatever its fields are. Every `Model` is one.
@@ -127,7 +227,7 @@ export declare class Model<F extends Fields> {
127
227
  /** The views declared so far, in declaration order. */
128
228
  get views(): readonly View<F>[];
129
229
  /**
130
- * The actions, rules and ends declared so far, in a form a search can run without knowing
230
+ * The actions, rules, ends, rules about runs, witnesses and setups declared so far, in a form a search can run without knowing
131
231
  * the model's types. `explore` and `replay` are built on this.
132
232
  */
133
233
  runners(): Runners;
@@ -156,6 +256,39 @@ export declare const rule: <F extends Fields>(model: Model<F>, sentence: string,
156
256
  * name of the export is the end's id.
157
257
  */
158
258
  export declare const end: <F extends Fields>(model: Model<F>, sentence: string, when: (state: StateOf<F>) => boolean) => End<F>;
259
+ /**
260
+ * Declares a rule about whole runs of `model`: every run comes to a state where `reaches` is
261
+ * true. With `after`, the rule starts in every reachable state where `after` is true, and the
262
+ * state `reaches` wants may be that state or any later one; without it, the rule starts in every
263
+ * start state. A run never stops while an action can still change the state, and never puts off
264
+ * forever an action declared with `fair: true` that stays possible. `sentence` says the rule in
265
+ * the reviewer's words. Export the result from the model file: the name of the export is the
266
+ * rule's id.
267
+ */
268
+ export declare const eventually: <F extends Fields>(model: Model<F>, sentence: string, spec: EventuallySpec<F>) => Eventually<F>;
269
+ /**
270
+ * Declares a setup of `model`: the model checked once more, with the fields in `starts` starting
271
+ * at the values given and every other field starting where the model declares. A field no action
272
+ * changes works as a parameter of the model this way. `sentence` says what the setup stands for.
273
+ * Export the result from the model file: the name of the export is the setup's id. Throws when
274
+ * `starts` is empty, names something that is not a field, or gives a field a value it does not
275
+ * declare.
276
+ */
277
+ export declare const setup: <F extends Fields, const Starts extends Partial<StateOf<F>>>(model: Model<F>, sentence: string, starts: OnlyFields<F, Starts>) => Setup<F>;
278
+ /**
279
+ * Makes a step of a witness from an action that takes inputs: `m.step(press, { by: "mouse" })`.
280
+ * `input` gives every input of the action a value it declares.
281
+ */
282
+ export declare const step: <F extends Fields, I extends Fields>(taken: Action<F, I>, input: StateOf<I>) => Step<F>;
283
+ /**
284
+ * Declares a witness of `model`: a path it must be able to take. From every start state, each
285
+ * step in `steps` must be able to happen in turn, and `expect` must be true in the state after
286
+ * the last one. `sentence` says it in the reviewer's words. Export the result from the model
287
+ * file: the name of the export is the witness's id. `earnest verify` and `explore` play it and
288
+ * report it with the rules. Throws when a step is not an action declared on `model` before the
289
+ * witness, or gives an input the action does not declare.
290
+ */
291
+ export declare const witness: <F extends Fields>(model: Model<F>, sentence: string, spec: WitnessSpec<F>) => Witness<F>;
159
292
  /**
160
293
  * Declares how `earnest chart` draws `model`. A model needs no view, and a view has no id, so
161
294
  * its constant needs no export. In a model file, write the second argument, even as `{}`: the
package/dist/model.js CHANGED
@@ -1,4 +1,4 @@
1
- import { record } from "./declarations.js";
1
+ import { record, startingAt } from "./declarations.js";
2
2
  import { frozen, isRecord } from "./values.js";
3
3
  let partsOf;
4
4
  /**
@@ -10,7 +10,15 @@ export class Model {
10
10
  name;
11
11
  fields;
12
12
  #state;
13
- #parts = { actions: [], rules: [], ends: [], views: [] };
13
+ #parts = {
14
+ actions: [],
15
+ rules: [],
16
+ ends: [],
17
+ eventually: [],
18
+ witnesses: [],
19
+ setups: [],
20
+ views: [],
21
+ };
14
22
  static {
15
23
  partsOf = (model) => model.#parts;
16
24
  }
@@ -40,12 +48,19 @@ export class Model {
40
48
  return [...this.#parts.views];
41
49
  }
42
50
  /**
43
- * The actions, rules and ends declared so far, in a form a search can run without knowing
51
+ * The actions, rules, ends, rules about runs, witnesses and setups declared so far, in a form a search can run without knowing
44
52
  * the model's types. `explore` and `replay` are built on this.
45
53
  */
46
54
  runners() {
47
- const { actions, rules, ends } = this.#parts;
48
- return { actions: [...actions], rules: [...rules], ends: [...ends] };
55
+ const { actions, rules, ends, eventually, witnesses, setups } = this.#parts;
56
+ return {
57
+ actions: [...actions],
58
+ rules: [...rules],
59
+ ends: [...ends],
60
+ eventually: [...eventually],
61
+ witnesses: [...witnesses],
62
+ setups: [...setups],
63
+ };
49
64
  }
50
65
  }
51
66
  const known = (model, state) => {
@@ -94,6 +109,7 @@ export const action = (model, sentence, spec) => {
94
109
  partsOf(model).actions.push({
95
110
  part: declaredAction,
96
111
  sentence,
112
+ fair: spec.fair ?? false,
97
113
  inputs: spec.input === undefined ? [] : Object.entries(spec.input),
98
114
  when: (state, input) => declaredAction.when(known(model, state), knownInput(input)),
99
115
  changes: (state, input) => changed(model, state, declaredAction.changes(known(model, state), knownInput(input)), sentence),
@@ -128,6 +144,112 @@ export const end = (model, sentence, when) => {
128
144
  });
129
145
  return declaredEnd;
130
146
  };
147
+ /**
148
+ * Declares a rule about whole runs of `model`: every run comes to a state where `reaches` is
149
+ * true. With `after`, the rule starts in every reachable state where `after` is true, and the
150
+ * state `reaches` wants may be that state or any later one; without it, the rule starts in every
151
+ * start state. A run never stops while an action can still change the state, and never puts off
152
+ * forever an action declared with `fair: true` that stays possible. `sentence` says the rule in
153
+ * the reviewer's words. Export the result from the model file: the name of the export is the
154
+ * rule's id.
155
+ */
156
+ export const eventually = (model, sentence, spec) => {
157
+ const declaredRule = Object.freeze({
158
+ kind: "eventually",
159
+ says: sentence,
160
+ after: spec.after,
161
+ reaches: spec.reaches,
162
+ });
163
+ const { after } = declaredRule;
164
+ partsOf(model).eventually.push({
165
+ part: declaredRule,
166
+ says: sentence,
167
+ after: after === undefined ? null : (state) => after(known(model, state)),
168
+ reaches: (state) => declaredRule.reaches(known(model, state)),
169
+ });
170
+ return declaredRule;
171
+ };
172
+ /**
173
+ * Declares a setup of `model`: the model checked once more, with the fields in `starts` starting
174
+ * at the values given and every other field starting where the model declares. A field no action
175
+ * changes works as a parameter of the model this way. `sentence` says what the setup stands for.
176
+ * Export the result from the model file: the name of the export is the setup's id. Throws when
177
+ * `starts` is empty, names something that is not a field, or gives a field a value it does not
178
+ * declare.
179
+ */
180
+ export const setup = (model, sentence, starts) => {
181
+ const names = Object.keys(starts);
182
+ if (names.length === 0) {
183
+ throw new Error(`${model.name}: the setup "${sentence}" starts no field at another value`);
184
+ }
185
+ const adopted = {};
186
+ for (const [name, value] of Object.entries(starts)) {
187
+ const declared = Object.hasOwn(model.fields, name)
188
+ ? model.fields[name]
189
+ : undefined;
190
+ if (declared === undefined) {
191
+ throw new Error(`${model.name}: the setup "${sentence}" starts \`${name}\`, which is not a field of the model`);
192
+ }
193
+ try {
194
+ adopted[name] = startingAt(declared, value);
195
+ }
196
+ catch (error) {
197
+ const why = error instanceof Error ? error.message : String(error);
198
+ throw new Error(`${model.name}: the setup "${sentence}" starts \`${name}\` at a value the field does not declare: ${why}`, { cause: error });
199
+ }
200
+ }
201
+ const declaredSetup = Object.freeze({ kind: "setup", says: sentence, starts });
202
+ partsOf(model).setups.push({ part: declaredSetup, says: sentence, starts: frozen(adopted) });
203
+ return declaredSetup;
204
+ };
205
+ /**
206
+ * Makes a step of a witness from an action that takes inputs: `m.step(press, { by: "mouse" })`.
207
+ * `input` gives every input of the action a value it declares.
208
+ */
209
+ export const step = (taken, input) => Object.freeze({ kind: "step", action: taken, input: frozen({ ...input }) });
210
+ /**
211
+ * Declares a witness of `model`: a path it must be able to take. From every start state, each
212
+ * step in `steps` must be able to happen in turn, and `expect` must be true in the state after
213
+ * the last one. `sentence` says it in the reviewer's words. Export the result from the model
214
+ * file: the name of the export is the witness's id. `earnest verify` and `explore` play it and
215
+ * report it with the rules. Throws when a step is not an action declared on `model` before the
216
+ * witness, or gives an input the action does not declare.
217
+ */
218
+ export const witness = (model, sentence, spec) => {
219
+ const { actions, witnesses, setups } = partsOf(model);
220
+ if (spec.setup !== undefined && !setups.some((declared) => declared.part === spec.setup)) {
221
+ throw new Error(`${model.name}: the setup of "${sentence}" is not one declared on this model before the witness`);
222
+ }
223
+ const played = spec.steps.map((written, position) => {
224
+ const taken = written.kind === "step"
225
+ ? written
226
+ : Object.freeze({ kind: "step", action: written, input: frozen({}) });
227
+ const runner = actions.find((declared) => declared.part === taken.action);
228
+ const number = position + 1;
229
+ if (runner === undefined) {
230
+ throw new Error(`${model.name}: step ${number} of "${sentence}" is not an action declared on this model before the witness`);
231
+ }
232
+ if (!record(Object.fromEntries(runner.inputs)).has(taken.input)) {
233
+ throw new Error(`${model.name}: step ${number} of "${sentence}" gives "${runner.sentence}" an input it does not declare`);
234
+ }
235
+ return { taken, runner };
236
+ });
237
+ const declaredWitness = Object.freeze({
238
+ kind: "witness",
239
+ says: sentence,
240
+ setup: spec.setup,
241
+ steps: Object.freeze(played.map(({ taken }) => taken)),
242
+ expect: spec.expect,
243
+ });
244
+ witnesses.push({
245
+ part: declaredWitness,
246
+ says: sentence,
247
+ ...(spec.setup === undefined ? {} : { setup: spec.setup }),
248
+ steps: played.map(({ taken, runner }) => ({ action: runner, input: taken.input })),
249
+ expect: (state) => declaredWitness.expect(known(model, state)),
250
+ });
251
+ return declaredWitness;
252
+ };
131
253
  /**
132
254
  * Declares how `earnest chart` draws `model`. A model needs no view, and a view has no id, so
133
255
  * its constant needs no export. In a model file, write the second argument, even as `{}`: the
package/dist/replay.d.ts CHANGED
@@ -17,9 +17,15 @@ export interface ReplayPath {
17
17
  readonly start: readonly Named[];
18
18
  readonly steps: readonly ReplayStep[];
19
19
  }
20
- /** `exports` is the model file's exports, which let a step's `action` id be matched. */
20
+ /**
21
+ * `exports` is the model file's exports, which let a step's `action` id be matched. `setup` is
22
+ * a setup declared on the model with `m.setup`, as `explore` takes it: the path must then begin
23
+ * at one of the setup's start states, as a path of the setup's result in `earnest verify
24
+ * --json` does. Without it the path must begin where the model declares.
25
+ */
21
26
  export interface ReplayOptions {
22
27
  readonly exports?: Exports;
28
+ readonly setup?: object;
23
29
  }
24
30
  /** A state with each field in JSON form. */
25
31
  export type StateJson = {
@@ -28,7 +34,7 @@ export type StateJson = {
28
34
  /**
29
35
  * Applies a path one action at a time and gives every state it passes through, the start state
30
36
  * first, each with its fields in JSON form. Throws an error that names the step when the path
31
- * does not begin at a start state, a step names no action of the model, an input is missing or
37
+ * does not begin at a start state of the model, or of `options.setup` when it is given, a step names no action of the model, an input is missing or
32
38
  * undeclared, the action's `when` is false, the action can't be evaluated, or the state after
33
39
  * the action differs from the step's `state`. Set members may be listed in any order.
34
40
  */
package/dist/replay.js CHANGED
@@ -1,4 +1,4 @@
1
- import { attempt, namer, nextState } from "./search.js";
1
+ import { attempt, namer, nextState, startsOf } from "./search.js";
2
2
  import { keyOf, toJson } from "./values.js";
3
3
  const messageOf = (thrown) => thrown instanceof Error ? thrown.message : String(thrown);
4
4
  const readAll = (where, declared, named) => {
@@ -64,7 +64,7 @@ const applied = (where, fields, action, state, input) => {
64
64
  /**
65
65
  * Applies a path one action at a time and gives every state it passes through, the start state
66
66
  * first, each with its fields in JSON form. Throws an error that names the step when the path
67
- * does not begin at a start state, a step names no action of the model, an input is missing or
67
+ * does not begin at a start state of the model, or of `options.setup` when it is given, a step names no action of the model, an input is missing or
68
68
  * undeclared, the action's `when` is false, the action can't be evaluated, or the state after
69
69
  * the action differs from the step's `state`. Set members may be listed in any order.
70
70
  */
@@ -72,9 +72,11 @@ export const replay = (model, path, options = {}) => {
72
72
  const fields = Object.entries(model.fields);
73
73
  const actions = model.runners().actions;
74
74
  const given = readAll(`${model.name}: the start of the path`, fields, path.start);
75
- const start = model.starts().find((each) => stateKey(fields, each) === stateKey(fields, given));
75
+ const starts = startsOf(model, options.setup, "replay");
76
+ const start = starts.find((each) => stateKey(fields, each) === stateKey(fields, given));
76
77
  if (start === undefined) {
77
- throw new Error(`${model.name}: the path does not begin at a start state of the model`);
78
+ const whose = options.setup === undefined ? "the model" : "the setup";
79
+ throw new Error(`${model.name}: the path does not begin at a start state of ${whose}`);
78
80
  }
79
81
  const states = [start];
80
82
  let state = start;