@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,905 @@
1
+ import { combinationsOf } from "@earnestjs/model";
2
+ import { EACH_FIELD, described, fieldRecord, historyOf, inRange, isPlain, keyOf, payloadsOf, plainFields, } from "./check.js";
3
+ import { quietScope } from "./machine.js";
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 const MOST_TABLE_ROWS = 100_000;
9
+ const CALLER = "modelFileOf";
10
+ const WIDTH = 100;
11
+ const RESERVED = new Set([
12
+ "m",
13
+ "s",
14
+ "input",
15
+ "State",
16
+ "arguments",
17
+ "as",
18
+ "async",
19
+ "await",
20
+ "break",
21
+ "case",
22
+ "catch",
23
+ "class",
24
+ "const",
25
+ "continue",
26
+ "debugger",
27
+ "default",
28
+ "delete",
29
+ "do",
30
+ "else",
31
+ "enum",
32
+ "eval",
33
+ "export",
34
+ "extends",
35
+ "false",
36
+ "finally",
37
+ "for",
38
+ "from",
39
+ "function",
40
+ "if",
41
+ "implements",
42
+ "import",
43
+ "in",
44
+ "Infinity",
45
+ "instanceof",
46
+ "interface",
47
+ "let",
48
+ "NaN",
49
+ "new",
50
+ "null",
51
+ "of",
52
+ "package",
53
+ "private",
54
+ "protected",
55
+ "public",
56
+ "return",
57
+ "static",
58
+ "super",
59
+ "switch",
60
+ "this",
61
+ "throw",
62
+ "true",
63
+ "try",
64
+ "type",
65
+ "typeof",
66
+ "undefined",
67
+ "var",
68
+ "void",
69
+ "while",
70
+ "with",
71
+ "yield",
72
+ ]);
73
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
74
+ const isName = (text) => IDENTIFIER.test(text) && !RESERVED.has(text);
75
+ const isFieldName = (text) => IDENTIFIER.test(text) && text !== "__proto__";
76
+ const nameLike = (text) => {
77
+ const replaced = text.replace(/[^A-Za-z0-9_]/g, "_");
78
+ const started = /^[A-Za-z_]/.test(replaced) ? replaced : `_${replaced}`;
79
+ return RESERVED.has(started) ? `${started}_` : started;
80
+ };
81
+ class Names {
82
+ #taken;
83
+ constructor(taken) {
84
+ this.#taken = new Set(taken);
85
+ }
86
+ claim(wanted) {
87
+ const base = nameLike(wanted);
88
+ let name = base;
89
+ for (let count = 2; this.#taken.has(name); count += 1) {
90
+ name = `${base}_${count}`;
91
+ }
92
+ this.#taken.add(name);
93
+ return name;
94
+ }
95
+ }
96
+ const fieldOf = (value, name) => typeof value === "object" && value !== null && Object.hasOwn(value, name)
97
+ ? Reflect.get(value, name)
98
+ : undefined;
99
+ const shapeOf = (option, values) => {
100
+ const nullable = values.includes(null);
101
+ const held = values.filter((value) => value !== null);
102
+ const first = held[0];
103
+ if (typeof first !== "object" || first === null) {
104
+ return { kind: "plain", type: first === undefined ? "null" : typeof first, nullable };
105
+ }
106
+ return {
107
+ kind: "record",
108
+ nullable,
109
+ fields: Object.keys(first).map((name) => {
110
+ if (!isFieldName(name)) {
111
+ throw new TypeError(`${CALLER} can't take ${option}.${name}: a model file reads a record's field by its name, so the name must be an identifier, such as ${nameLike(name)}`);
112
+ }
113
+ return [
114
+ name,
115
+ shapeOf(`${option}.${name}`, held.map((value) => fieldOf(value, name))),
116
+ ];
117
+ }),
118
+ };
119
+ };
120
+ const NOT_WRITTEN = Symbol("not written");
121
+ const written = (shape, value) => {
122
+ if (value === undefined || value === null) {
123
+ return shape.nullable || (shape.kind === "plain" && shape.type === "null") ? null : NOT_WRITTEN;
124
+ }
125
+ if (shape.kind === "plain") {
126
+ if (typeof value !== shape.type) {
127
+ return NOT_WRITTEN;
128
+ }
129
+ return typeof value === "number" && !Number.isSafeInteger(value) ? NOT_WRITTEN : value;
130
+ }
131
+ if (typeof value !== "object" || Array.isArray(value) || !isPlain(value)) {
132
+ return NOT_WRITTEN;
133
+ }
134
+ const held = Object.keys(value).filter((name) => fieldOf(value, name) !== undefined);
135
+ if (held.some((name) => !shape.fields.some(([field]) => field === name))) {
136
+ return NOT_WRITTEN;
137
+ }
138
+ const fields = shape.fields.map(([name, inner]) => [name, written(inner, fieldOf(value, name))]);
139
+ return fields.some(([, inner]) => inner === NOT_WRITTEN)
140
+ ? NOT_WRITTEN
141
+ : Object.fromEntries(fields);
142
+ };
143
+ const literal = (value) => {
144
+ if (typeof value === "object" && value !== null) {
145
+ const fields = Object.entries(value).map(([name, inner]) => `${name}: ${literal(inner)}`);
146
+ return fields.length === 0 ? "{}" : `{ ${fields.join(", ")} }`;
147
+ }
148
+ return typeof value === "number" && Object.is(value, -0) ? "0" : JSON.stringify(value);
149
+ };
150
+ const fieldsOf = (option, fields) => fields.map(([name, declared]) => {
151
+ if (!isFieldName(name)) {
152
+ throw new TypeError(`${CALLER} can't take ${option}.${name}: a model file reads a field by its name, so the name must be an identifier, such as ${nameLike(name)}`);
153
+ }
154
+ if (typeof declared.source !== "string") {
155
+ 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`);
156
+ }
157
+ return { name, declared, shape: shapeOf(`${option}.${name}`, declared.values()) };
158
+ });
159
+ const PAYLOAD_ADVICE = "write the events as a record of event types, each with a declaration for each payload field, such as { ENTER: { group: m.int(1, 2) } }";
160
+ const eventKindsOf = (events) => {
161
+ if (typeof events === "function") {
162
+ throw new TypeError(`${CALLER} can't take events as a function of the snapshot: a model file gives each event once, for every state; ${PAYLOAD_ADVICE}, or list the events`);
163
+ }
164
+ if (Array.isArray(events)) {
165
+ const types = [];
166
+ events.forEach((event, index) => {
167
+ const type = fieldOf(event, "type");
168
+ if (typeof type !== "string") {
169
+ throw new TypeError(`${CALLER} can't take events[${index}]: it is ${described(event)}, not an event with a type`);
170
+ }
171
+ const payload = Object.keys(event).find((name) => name !== "type" && fieldOf(event, name) !== undefined);
172
+ if (payload !== undefined) {
173
+ throw new TypeError(`${CALLER} can't take events[${index}], ${type} with the payload field ${payload}: a model file declares a payload's values; ${PAYLOAD_ADVICE}`);
174
+ }
175
+ if (!types.includes(type)) {
176
+ types.push(type);
177
+ }
178
+ });
179
+ return types.map((type) => ({ type, fields: [] }));
180
+ }
181
+ const schema = fieldRecord(CALLER, "events", events, "a list of events or a record of event types, such as { ENTER: { group: m.int(1, 2) } }");
182
+ return payloadsOf(CALLER, schema).map(([type, fields]) => ({ type, fields }));
183
+ };
184
+ const countOf = (declarations) => declarations.reduce((total, declared) => total * declared.count, 1);
185
+ const rowsOf = (fields) => combinationsOf(Object.fromEntries(fields.map(({ name, declared }) => [name, declared])));
186
+ const OFF = { kind: "off" };
187
+ const THREW = { kind: "threw" };
188
+ const leavesOf = (value, prefix) => {
189
+ if (typeof value === "string") {
190
+ return [`${prefix}${value}`];
191
+ }
192
+ const entries = Object.entries(value);
193
+ return entries.length === 0
194
+ ? [prefix.slice(0, -1)].filter((leaf) => leaf !== "")
195
+ : entries.flatMap(([key, inner]) => inner === undefined ? [`${prefix}${key}`] : leavesOf(inner, `${prefix}${key}.`));
196
+ };
197
+ const labelsOf = (machine, configurations) => {
198
+ const root = `${machine.root.id}.`;
199
+ const local = (id) => (id.startsWith(root) ? id.slice(root.length) : id);
200
+ const named = (labels, more) => labels.map((label, index) => labels.filter((other) => other === label).length > 1 ? more(index) : label);
201
+ const bases = configurations.map(({ value }) => leavesOf(value, "").join(", ") || machine.id);
202
+ const remembered = named(bases, (index) => {
203
+ const configuration = configurations[index];
204
+ const history = configuration === undefined
205
+ ? []
206
+ : Object.entries(configuration.history)
207
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
208
+ .map(([node, held]) => `${local(node)}: ${held.map(local).join(" + ")}`);
209
+ return history.length === 0 ? `${bases[index]}` : `${bases[index]} (${history.join("; ")})`;
210
+ });
211
+ const statused = named(remembered, (index) => {
212
+ const status = configurations[index]?.status ?? "active";
213
+ return status === "active" ? `${remembered[index]}` : `${remembered[index]} (${status})`;
214
+ });
215
+ return named(statused, (index) => {
216
+ const label = statused[index] ?? "";
217
+ return `${label} #${statused.slice(0, index + 1).filter((other) => other === label).length}`;
218
+ });
219
+ };
220
+ const ABSENT = Symbol("absent");
221
+ const atomsOf = (scope, name, shape, read, expression, guards) => {
222
+ if (shape.kind === "plain") {
223
+ return [
224
+ {
225
+ scope,
226
+ name,
227
+ test: "value",
228
+ nullable: shape.nullable,
229
+ read: (point) => {
230
+ const value = read(point);
231
+ return value === ABSENT ? ABSENT : value;
232
+ },
233
+ expression,
234
+ guards,
235
+ },
236
+ ];
237
+ }
238
+ const nullAtoms = shape.nullable
239
+ ? [
240
+ {
241
+ scope,
242
+ name,
243
+ test: "null",
244
+ nullable: false,
245
+ read: (point) => {
246
+ const value = read(point);
247
+ return value === ABSENT ? ABSENT : value === null;
248
+ },
249
+ expression,
250
+ guards,
251
+ },
252
+ ]
253
+ : [];
254
+ const inner = shape.nullable ? (root) => `m.some(${expression(root)})` : expression;
255
+ const innerGuards = shape.nullable
256
+ ? (root) => [...guards(root), `${expression(root)} !== null`]
257
+ : guards;
258
+ const innerRead = (point) => {
259
+ const value = read(point);
260
+ return value === null ? ABSENT : value;
261
+ };
262
+ return [
263
+ ...nullAtoms,
264
+ ...shape.fields.flatMap(([field, fieldShape]) => atomsOf(scope, name, fieldShape, (point) => {
265
+ const value = innerRead(point);
266
+ return value === ABSENT ? ABSENT : fieldOf(value, field);
267
+ }, (root) => `${inner(root)}.${field}`, innerGuards)),
268
+ ];
269
+ };
270
+ const fieldAtoms = (scope, field, read) => atomsOf(scope, field.name, field.shape, read, (root) => root, () => []);
271
+ const valueKey = (value) => value.kind === "literal" ? `=${value.text}` : `${value.kind}:${value.name}`;
272
+ const atomKey = (value) => value === ABSENT ? "absent" : keyOf(value);
273
+ const grow = (atoms, points, outputs, candidates) => {
274
+ const leaves = [];
275
+ const readAt = (atom, index) => {
276
+ const point = points[index];
277
+ return point === undefined ? ABSENT : atom.read(point);
278
+ };
279
+ const literalAt = (index) => outputs[index]?.literal ?? "";
280
+ const decides = (others, cared) => {
281
+ const seen = new Map();
282
+ for (const index of cared) {
283
+ const key = others.map((atom) => atomKey(readAt(atom, index))).join("|");
284
+ const found = seen.get(key);
285
+ if (found === undefined) {
286
+ seen.set(key, literalAt(index));
287
+ }
288
+ else if (found !== literalAt(index)) {
289
+ return false;
290
+ }
291
+ }
292
+ return true;
293
+ };
294
+ const visit = (cared, available, path) => {
295
+ const [first] = cared;
296
+ if (first === undefined) {
297
+ return;
298
+ }
299
+ if (cared.every((index) => literalAt(index) === literalAt(first))) {
300
+ leaves.push({ path, value: { kind: "literal", text: literalAt(first) } });
301
+ return;
302
+ }
303
+ const shared = candidates.find((candidate) => cared.every((index) => outputs[index]?.matches.has(valueKey(candidate)) === true));
304
+ if (shared !== undefined) {
305
+ leaves.push({ path, value: shared });
306
+ return;
307
+ }
308
+ const varying = available.filter((atom) => cared.some((index) => atomKey(readAt(atom, index)) !== atomKey(readAt(atom, first))));
309
+ const chosen = varying.find((atom) => !decides(varying.filter((other) => other !== atom), cared)) ?? varying[0];
310
+ if (chosen === undefined) {
311
+ throw new Error(`${CALLER} found two outcomes for the same state and event`);
312
+ }
313
+ const groups = new Map();
314
+ for (const index of cared) {
315
+ const value = readAt(chosen, index);
316
+ const key = atomKey(value);
317
+ const group = groups.get(key);
318
+ if (group === undefined) {
319
+ groups.set(key, { value, cared: [index] });
320
+ }
321
+ else {
322
+ group.cared.push(index);
323
+ }
324
+ }
325
+ const rest = varying.filter((atom) => atom !== chosen);
326
+ for (const group of groups.values()) {
327
+ visit(group.cared, rest, [...path, [chosen, group.value]]);
328
+ }
329
+ };
330
+ visit(outputs.flatMap((output, index) => (output === null ? [] : [index])), atoms, []);
331
+ return leaves;
332
+ };
333
+ const rendered = (value, rendering) => {
334
+ if (value.kind === "literal") {
335
+ return value.text;
336
+ }
337
+ return value.kind === "state" ? `s.${value.name}` : rendering.input(value.name);
338
+ };
339
+ const termsOf = ([atom, value], { root }) => {
340
+ const base = root(atom);
341
+ const guards = atom.guards(base);
342
+ if (value === ABSENT) {
343
+ const last = guards.at(-1);
344
+ return guards.length === 1 && last !== undefined
345
+ ? [last.replace(/ !== null$/, " === null")]
346
+ : [`!(${guards.join(" && ")})`];
347
+ }
348
+ const expression = atom.expression(base);
349
+ if (atom.test === "null") {
350
+ return [...guards, `${expression} ${value === true ? "===" : "!=="} null`];
351
+ }
352
+ if (typeof value === "boolean" && !atom.nullable) {
353
+ return [...guards, value ? expression : `!${expression}`];
354
+ }
355
+ return [...guards, `${expression} === ${literal(value)}`];
356
+ };
357
+ const conditionOf = (leaf, rendering) => [
358
+ ...new Set(leaf.path.flatMap((step) => termsOf(step, rendering))),
359
+ ];
360
+ const negated = (terms) => {
361
+ const [only] = terms;
362
+ if (terms.length !== 1 || only === undefined) {
363
+ return `!(${terms.join(" && ")})`;
364
+ }
365
+ if (/^[\w.()]+ === /.test(only)) {
366
+ return only.replace(" === ", " !== ");
367
+ }
368
+ if (/^[\w.()]+ !== /.test(only)) {
369
+ return only.replace(" !== ", " === ");
370
+ }
371
+ if (/^![\w.()]+$/.test(only)) {
372
+ return only.slice(1);
373
+ }
374
+ return /^[\w.()]+$/.test(only) ? `!${only}` : `!(${only})`;
375
+ };
376
+ const FALSE = { kind: "literal", text: "false" };
377
+ const tableOf = (leaves) => {
378
+ const counts = new Map();
379
+ for (const { value } of leaves) {
380
+ const key = valueKey(value);
381
+ counts.set(key, { value, count: (counts.get(key)?.count ?? 0) + 1 });
382
+ }
383
+ let fallback = counts.get(valueKey(FALSE)) ?? { value: leaves[0]?.value ?? FALSE, count: 0 };
384
+ for (const each of counts.values()) {
385
+ if (each.count > fallback.count) {
386
+ fallback = each;
387
+ }
388
+ }
389
+ const kept = leaves.filter(({ value }) => valueKey(value) !== valueKey(fallback.value));
390
+ const values = [fallback.value, ...kept.map(({ value }) => value)];
391
+ const atoms = kept.flatMap(({ path }) => path.map(([atom]) => atom));
392
+ return {
393
+ leaves: kept,
394
+ fallback: fallback.value,
395
+ usesState: values.some(({ kind }) => kind === "state") || atoms.some(({ scope }) => scope === "state"),
396
+ inputs: new Set([
397
+ ...values.flatMap((value) => (value.kind === "input" ? [value.name] : [])),
398
+ ...atoms.filter(({ scope }) => scope === "input").map(({ name }) => name),
399
+ ]),
400
+ };
401
+ };
402
+ const ifLine = (terms, expression) => {
403
+ const head = ` if (${terms.join(" && ")})`;
404
+ const line = `${head} return ${expression};`;
405
+ if (line.length <= WIDTH) {
406
+ return line;
407
+ }
408
+ return head.length <= WIDTH
409
+ ? `${head}\n return ${expression};`
410
+ : ` if (\n ${terms.join(" &&\n ")}\n )\n return ${expression};`;
411
+ };
412
+ const helperOf = (name, table, result, parameters) => {
413
+ const parameterOf = (input) => parameters.find((parameter) => parameter.input === input)?.name ?? input;
414
+ const rendering = {
415
+ root: (atom) => (atom.scope === "state" ? `s.${atom.name}` : parameterOf(atom.name)),
416
+ input: parameterOf,
417
+ };
418
+ const used = parameters.filter(({ input }) => input === null ? table.usesState : table.inputs.has(input));
419
+ const typed = used.map(({ name: each, type }) => `${each}: ${type}`);
420
+ const signature = `const ${name} = (${typed.join(", ")}): ${result} => {`;
421
+ const head = signature.length <= WIDTH
422
+ ? signature
423
+ : `const ${name} = (\n${typed.map((each) => ` ${each},\n`).join("")}): ${result} => {`;
424
+ const lines = table.leaves.map((leaf) => ifLine(conditionOf(leaf, rendering), rendered(leaf.value, rendering)));
425
+ return {
426
+ text: [head, ...lines, ` return ${rendered(table.fallback, rendering)};`, "};"].join("\n"),
427
+ written: {
428
+ expression: `${name}(${used.map(({ input }) => (input === null ? "s" : `input.${input}`)).join(", ")})`,
429
+ usesState: used.some(({ input }) => input === null),
430
+ usesInput: used.some(({ input }) => input !== null),
431
+ },
432
+ };
433
+ };
434
+ const INLINE = {
435
+ root: (atom) => (atom.scope === "state" ? `s.${atom.name}` : `input.${atom.name}`),
436
+ input: (name) => `input.${name}`,
437
+ };
438
+ const MOST_INLINE = 60;
439
+ const writeTable = (leaves, boolean, helper, helpers) => {
440
+ const table = tableOf(leaves);
441
+ const usesInput = table.inputs.size > 0;
442
+ if (table.leaves.length === 0) {
443
+ return { expression: rendered(table.fallback, INLINE), usesState: table.usesState, usesInput };
444
+ }
445
+ const [only] = table.leaves;
446
+ if (boolean && table.leaves.length === 1 && only !== undefined) {
447
+ const terms = conditionOf(only, INLINE);
448
+ const expression = valueKey(table.fallback) === valueKey(FALSE) ? terms.join(" && ") : negated(terms);
449
+ if (expression.length <= MOST_INLINE) {
450
+ return { expression, usesState: table.usesState, usesInput };
451
+ }
452
+ }
453
+ const { text, written } = helper(table);
454
+ helpers.push(text);
455
+ return written;
456
+ };
457
+ const arrow = (uses, body) => {
458
+ const state = uses.some(({ usesState }) => usesState);
459
+ const input = uses.some(({ usesInput }) => usesInput);
460
+ const parameters = input ? (state ? "(s, input)" : "(_, input)") : state ? "(s)" : "()";
461
+ return `${parameters} => ${body}`;
462
+ };
463
+ const callLines = (head, items, tail) => {
464
+ const line = `${head}${items.join(", ")}${tail}`;
465
+ return line.length <= WIDTH ? line : `${head}\n ${items.join(",\n ")},\n${tail}`;
466
+ };
467
+ const heldAs = (value) => value === undefined ? "missing or undefined" : described(value);
468
+ const differing = (shape, now, before, path) => {
469
+ if (shape.kind === "record") {
470
+ for (const [name, inner] of shape.fields) {
471
+ if (keyOf(fieldOf(now, name)) !== keyOf(fieldOf(before, name))) {
472
+ return differing(inner, fieldOf(now, name), fieldOf(before, name), `${path}.${name}`);
473
+ }
474
+ }
475
+ }
476
+ return { path, now, before };
477
+ };
478
+ const reachedContexts = (machine, initial, { events, context, limit, configurationKey, contextRow }) => {
479
+ const reached = new Map();
480
+ const configurations = new Set();
481
+ const pending = [];
482
+ const reach = (snapshot, where) => {
483
+ const held = snapshot.context;
484
+ const configuration = configurationKey(snapshot);
485
+ const at = `${configuration}|${keyOf(contextRow(snapshot, where))}`;
486
+ if (reached.has(at)) {
487
+ const before = reached.get(at);
488
+ const field = context.find(({ name }) => keyOf(fieldOf(held, name)) !== keyOf(fieldOf(before, name)));
489
+ if (field !== undefined) {
490
+ const found = differing(field.shape, fieldOf(held, field.name), fieldOf(before, field.name), field.name);
491
+ throw new TypeError(`${CALLER} can't write the context field \`${found.path}\` ${where}: it is ${heldAs(found.now)} here and ${heldAs(found.before)} in a state reached before that is otherwise the same; checkMachine counts them as two states, and a model file has one null for both, so keep the field to one of null and missing`);
492
+ }
493
+ return;
494
+ }
495
+ configurations.add(configuration);
496
+ limit(configurations.size);
497
+ const kept = structuredClone(held);
498
+ reached.set(at, kept);
499
+ if (context.every(({ name, declared }) => inRange(declared, fieldOf(held, name)))) {
500
+ pending.push({ snapshot, context: kept });
501
+ }
502
+ };
503
+ reach(initial, "of the initial snapshot");
504
+ const scope = quietScope();
505
+ for (const { snapshot, context: kept } of pending) {
506
+ if (snapshot.status !== "active") {
507
+ continue;
508
+ }
509
+ for (const { type, payloads } of events) {
510
+ for (const payload of payloads) {
511
+ const event = { ...structuredClone(payload), type };
512
+ const fresh = machine.resolveState({
513
+ value: snapshot.value,
514
+ context: structuredClone(kept),
515
+ historyValue: snapshot.historyValue,
516
+ status: snapshot.status,
517
+ });
518
+ const next = stepped(machine, fresh, event, scope);
519
+ if (next !== null) {
520
+ reach(next, `after the event ${JSON.stringify(event)}`);
521
+ }
522
+ }
523
+ }
524
+ }
525
+ return reached;
526
+ };
527
+ const stepped = (machine, snapshot, event, scope) => {
528
+ try {
529
+ const next = snapshot.can(event)
530
+ ? machine.transition(snapshot, event, scope)
531
+ : null;
532
+ return next?.status === "error" ? null : next;
533
+ }
534
+ catch {
535
+ return null;
536
+ }
537
+ };
538
+ const write = (machine, options) => {
539
+ const modelName = options.name;
540
+ if (typeof modelName !== "string" || !isName(modelName)) {
541
+ throw new TypeError(`${CALLER} can't take name: it is ${described(modelName)}, not an identifier that can name the model, such as Turnstile`);
542
+ }
543
+ const kinds = eventKindsOf(options.events);
544
+ const contextFields = options.context === undefined
545
+ ? []
546
+ : plainFields(CALLER, "context", fieldRecord(CALLER, "context", options.context, `a record of context fields; ${EACH_FIELD}, such as { visitors: m.int(0, 3) }`));
547
+ const ruleEntries = Object.entries(options.rules ?? {});
548
+ const contextCount = countOf(contextFields.map(([, declared]) => declared));
549
+ const eventCount = kinds.reduce((total, { fields }) => total + countOf(fields.map(([, declared]) => declared)), 0);
550
+ const rowsPerState = contextCount * Math.max(1, eventCount + ruleEntries.length);
551
+ const tooMany = (states) => new RangeError(`${CALLER} can't write a table of ${states * rowsPerState} rows or more, past its limit of ${MOST_TABLE_ROWS}: ${states} × ${contextCount} × ${Math.max(1, eventCount + ruleEntries.length)}, the states of the machine found, the combinations of context values, and the events with each payload and the rules; declare fewer values`);
552
+ if (rowsPerState > MOST_TABLE_ROWS) {
553
+ throw tooMany(1);
554
+ }
555
+ const context = fieldsOf("context", contextFields);
556
+ const events = kinds.map(({ type, fields }) => {
557
+ const inputs = fieldsOf(`events.${type}`, fields);
558
+ return { type, inputs, payloads: rowsOf(inputs) };
559
+ });
560
+ const contexts = rowsOf(context);
561
+ const rowKeys = contexts.map(keyOf);
562
+ const declaredNames = new Set(context.map(({ name }) => name));
563
+ const contextRow = (snapshot, where) => {
564
+ const held = snapshot.context;
565
+ const extra = Object.keys(typeof held === "object" && held !== null ? held : {}).find((name) => fieldOf(held, name) !== undefined && !declaredNames.has(name));
566
+ if (extra !== undefined) {
567
+ throw new TypeError(`${CALLER} can't write the context field \`${extra}\` ${where}: it has no declaration in context; declare its values, such as context: { ${extra}: m.int(0, 3) }`);
568
+ }
569
+ return Object.fromEntries(context.map(({ name, declared, shape }) => {
570
+ const value = written(shape, fieldOf(held, name));
571
+ if (value === NOT_WRITTEN) {
572
+ throw new TypeError(`${CALLER} can't write the context field \`${name}\` ${where}: it holds ${described(fieldOf(held, name))}, which a field declared ${declared.source} can't hold`);
573
+ }
574
+ return [name, value];
575
+ }));
576
+ };
577
+ const scope = quietScope();
578
+ const initial = machine.getInitialSnapshot(scope, options.input);
579
+ if (initial.status === "error") {
580
+ throw initial.error;
581
+ }
582
+ const start = contextRow(initial, "of the initial snapshot");
583
+ const missing = new Set(context.flatMap(({ name }) => (fieldOf(initial.context, name) === undefined ? [name] : [])));
584
+ const contextFor = (row) => structuredClone(Object.fromEntries(Object.entries(row).filter(([name, value]) => value !== null || !missing.has(name))));
585
+ for (const { name, declared } of context) {
586
+ if (!declared.has(start[name])) {
587
+ throw new RangeError(`${CALLER} can't write the initial context field \`${name}\`: it is ${literal(start[name])}, outside ${declared.source}, and a model starts inside its declarations`);
588
+ }
589
+ }
590
+ const configurationKey = (snapshot) => keyOf({ value: snapshot.value, status: snapshot.status, history: historyOf(snapshot) });
591
+ const reached = reachedContexts(machine, initial, {
592
+ events,
593
+ context,
594
+ limit: (found) => {
595
+ if (found * rowsPerState > MOST_TABLE_ROWS) {
596
+ throw tooMany(found);
597
+ }
598
+ },
599
+ configurationKey,
600
+ contextRow,
601
+ });
602
+ const configurations = [];
603
+ const known = new Map();
604
+ const configurationOf = (snapshot) => {
605
+ const key = configurationKey(snapshot);
606
+ const found = known.get(key);
607
+ if (found !== undefined) {
608
+ return found;
609
+ }
610
+ if ((configurations.length + 1) * rowsPerState > MOST_TABLE_ROWS) {
611
+ throw tooMany(configurations.length + 1);
612
+ }
613
+ known.set(key, configurations.length);
614
+ configurations.push({
615
+ key,
616
+ value: snapshot.value,
617
+ status: snapshot.status,
618
+ historyValue: snapshot.historyValue,
619
+ history: historyOf(snapshot),
620
+ });
621
+ return configurations.length - 1;
622
+ };
623
+ configurationOf(initial);
624
+ const threw = [];
625
+ const outcomes = events.map(() => []);
626
+ const verdicts = ruleEntries.map(() => []);
627
+ for (let state = 0; state < configurations.length; state += 1) {
628
+ const configuration = configurations[state];
629
+ if (configuration === undefined) {
630
+ break;
631
+ }
632
+ const rows = events.map(() => []);
633
+ const judged = ruleEntries.map(() => []);
634
+ for (const [rowIndex, row] of contexts.entries()) {
635
+ const at = `${configuration.key}|${rowKeys[rowIndex]}`;
636
+ const resolved = () => machine.resolveState({
637
+ value: configuration.value,
638
+ context: reached.has(at) ? structuredClone(reached.get(at)) : contextFor(row),
639
+ historyValue: configuration.historyValue,
640
+ status: configuration.status,
641
+ });
642
+ events.forEach(({ type, payloads }, kind) => {
643
+ for (const payload of payloads) {
644
+ const event = { ...structuredClone(payload), type };
645
+ const snapshot = resolved();
646
+ let next = null;
647
+ let error = null;
648
+ try {
649
+ if (snapshot.status === "active" && snapshot.can(event)) {
650
+ next = machine.transition(snapshot, event, scope);
651
+ if (next.status === "error") {
652
+ error = next.error;
653
+ next = null;
654
+ }
655
+ }
656
+ else {
657
+ rows[kind]?.push(OFF);
658
+ continue;
659
+ }
660
+ }
661
+ catch (caught) {
662
+ error = caught;
663
+ }
664
+ if (next === null) {
665
+ threw.push({
666
+ state,
667
+ throw: { part: "transition", id: type, context: row, payload, error },
668
+ });
669
+ rows[kind]?.push(THREW);
670
+ continue;
671
+ }
672
+ rows[kind]?.push({
673
+ kind: "on",
674
+ state: configurationOf(next),
675
+ context: contextRow(next, `after the event ${JSON.stringify(event)}`),
676
+ });
677
+ }
678
+ });
679
+ ruleEntries.forEach(([id, rule], index) => {
680
+ let holds = false;
681
+ try {
682
+ holds = Boolean(rule.holds(resolved()));
683
+ }
684
+ catch (error) {
685
+ threw.push({ state, throw: { part: "rule", id, context: row, payload: {}, error } });
686
+ }
687
+ judged[index]?.push(holds);
688
+ });
689
+ }
690
+ rows.forEach((row, kind) => outcomes[kind]?.push(row));
691
+ judged.forEach((row, index) => verdicts[index]?.push(row));
692
+ }
693
+ const labels = labelsOf(machine, configurations);
694
+ const fieldNames = new Names(context.map(({ name }) => name));
695
+ const control = fieldNames.claim("state");
696
+ const threwField = threw.some(({ throw: { part } }) => part === "transition")
697
+ ? fieldNames.claim("threw")
698
+ : null;
699
+ const names = new Names([modelName]);
700
+ const actionIds = events.map(({ type }) => names.claim(type));
701
+ const ruleIds = ruleEntries.map(([id]) => names.claim(id));
702
+ const doneStates = configurations.flatMap((configuration, index) => configuration.status === "done" ? [index] : []);
703
+ const endId = doneStates.length > 0 ? names.claim("done") : null;
704
+ const statesConst = names.claim("States");
705
+ const controlShape = { kind: "plain", type: "string", nullable: false };
706
+ const controlAtoms = atomsOf("state", control, controlShape, (point) => labels[point.state], (root) => root, () => []);
707
+ const contextAtoms = context.flatMap((field) => fieldAtoms("state", field, (point) => point.context[field.name]));
708
+ const statePoints = configurations.flatMap((_, state) => contexts.map((row) => ({ state, context: row, payload: {} })));
709
+ const NOTHING = new Set();
710
+ const booleanOutput = (value) => ({
711
+ literal: String(value),
712
+ matches: NOTHING,
713
+ });
714
+ const helpers = [];
715
+ const declarationConsts = [];
716
+ const stateParameter = { name: "s", type: "State", input: null };
717
+ const actionTexts = events.flatMap(({ type, inputs, payloads }, kind) => {
718
+ const id = actionIds[kind] ?? type;
719
+ const table = outcomes[kind] ?? [];
720
+ const points = [];
721
+ const results = [];
722
+ table.forEach((rows, state) => {
723
+ contexts.forEach((row, at) => {
724
+ payloads.forEach((payload, index) => {
725
+ points.push({ state, context: row, payload });
726
+ results.push(rows[at * payloads.length + index] ?? OFF);
727
+ });
728
+ });
729
+ });
730
+ if (results.every(({ kind: each }) => each === "off")) {
731
+ return [];
732
+ }
733
+ const inputConsts = inputs.map(({ name, declared }) => {
734
+ const constName = names.claim(`${id}_${name}`);
735
+ declarationConsts.push(`const ${constName} = ${declared.source};`);
736
+ return { name, constName };
737
+ });
738
+ const inputNames = new Names([]);
739
+ const parameters = [
740
+ stateParameter,
741
+ ...inputConsts.map(({ name, constName }) => ({
742
+ name: inputNames.claim(name),
743
+ type: `m.Infer<typeof ${constName}>`,
744
+ input: name,
745
+ })),
746
+ ];
747
+ const atoms = [
748
+ ...controlAtoms,
749
+ ...contextAtoms,
750
+ ...inputs.flatMap((field) => fieldAtoms("input", field, (point) => point.payload[field.name])),
751
+ ];
752
+ const makeHelper = (suffix, result) => (table) => helperOf(names.claim(`${id}_${suffix}`), table, result, parameters);
753
+ const when = writeTable(grow(atoms, points, results.map(({ kind: each }) => booleanOutput(each !== "off")), []), true, makeHelper("when", "boolean"), helpers);
754
+ const valueOutput = (value, field, current, payload, fitting) => {
755
+ const key = keyOf(value);
756
+ return {
757
+ literal: literal(value),
758
+ matches: new Set([
759
+ ...(keyOf(current) === key ? [`state:${field}`] : []),
760
+ ...(payload === null
761
+ ? []
762
+ : inputs.flatMap(({ name }) => fitting.has(name) && keyOf(payload[name]) === key ? [`input:${name}`] : [])),
763
+ ]),
764
+ };
765
+ };
766
+ const changed = [];
767
+ const fieldChange = (name, result, output, candidates) => {
768
+ const outputs = results.map((outcome, index) => {
769
+ const point = points[index];
770
+ return point === undefined ? null : output(outcome, point);
771
+ });
772
+ if (outputs.every((each) => each === null || each.matches.has(`state:${name}`))) {
773
+ return;
774
+ }
775
+ changed.push([
776
+ name,
777
+ writeTable(grow(atoms, points, outputs, candidates), false, makeHelper(`next_${name}`, result), helpers),
778
+ ]);
779
+ };
780
+ fieldChange(control, `State["${control}"]`, (outcome, point) => outcome.kind === "on"
781
+ ? valueOutput(labels[outcome.state], control, labels[point.state], null, NOTHING)
782
+ : null, [{ kind: "state", name: control }]);
783
+ for (const { name, declared } of context) {
784
+ const fitting = new Set(inputs.flatMap((input) => input.declared.values().every((value) => declared.has(value)) ? [input.name] : []));
785
+ fieldChange(name, `State["${name}"]`, (outcome, point) => outcome.kind === "on"
786
+ ? valueOutput(outcome.context[name], name, point.context[name], point.payload, fitting)
787
+ : null, [
788
+ { kind: "state", name },
789
+ ...inputs.map((input) => ({ kind: "input", name: input.name })),
790
+ ]);
791
+ }
792
+ if (threwField !== null) {
793
+ fieldChange(threwField, `State["${threwField}"]`, (outcome) => outcome.kind === "off"
794
+ ? null
795
+ : valueOutput(outcome.kind === "threw" ? 1 : 0, threwField, 0, null, NOTHING), []);
796
+ }
797
+ const changes = changed.map(([name, { expression }]) => `${name}: ${expression}`);
798
+ const changesLine = ` changes: ${arrow(changed.map(([, each]) => each), `({ ${changes.join(", ")} }),`)}`;
799
+ const changesText = changes.length === 0
800
+ ? " changes: () => ({}),"
801
+ : changesLine.length <= WIDTH
802
+ ? changesLine
803
+ : ` changes: ${arrow(changed.map(([, each]) => each), `({\n${changes.map((change) => ` ${change},\n`).join("")} }),`)}`;
804
+ const inputText = inputConsts.length === 0
805
+ ? []
806
+ : [
807
+ ` input: { ${inputConsts.map(({ name, constName }) => `${name}: ${constName}`).join(", ")} },`,
808
+ ];
809
+ const whenText = when.expression === "true" ? [] : [` when: ${arrow([when], when.expression)},`];
810
+ return [
811
+ [
812
+ `export const ${id} = m.action(${modelName}, ${JSON.stringify(type)}, {`,
813
+ ...inputText,
814
+ ...whenText,
815
+ changesText,
816
+ "});",
817
+ ].join("\n"),
818
+ ];
819
+ });
820
+ const holdsText = (id, sentence, builder, truth) => {
821
+ const holds = writeTable(grow([...controlAtoms, ...contextAtoms], statePoints, statePoints.map((point, index) => booleanOutput(truth(point, index))), []), true, (table) => helperOf(names.claim(`${id}_holds`), table, "boolean", [stateParameter]), helpers);
822
+ return `${callLines(`export const ${id} = m.${builder}(`, [modelName, JSON.stringify(sentence), arrow([holds], holds.expression)], ");")}`;
823
+ };
824
+ const ruleTexts = ruleEntries.map(([, rule], index) => holdsText(ruleIds[index] ?? "", rule.says, "rule", (point, at) => verdicts[index]?.[point.state]?.[at % contexts.length] ?? false));
825
+ const endTexts = endId === null
826
+ ? []
827
+ : [
828
+ holdsText(endId, "The machine is in a top-level final state", "end", (point) => doneStates.includes(point.state)),
829
+ ];
830
+ const enumLine = `m.enum([${labels.map((label) => JSON.stringify(label)).join(", ")}])`;
831
+ const initialLabel = JSON.stringify(labels[0]);
832
+ const controlLine = ` ${control}: ${enumLine}.initial(${initialLabel}),`;
833
+ const statesText = controlLine.length <= WIDTH
834
+ ? []
835
+ : [
836
+ `const ${statesConst} = m.enum([\n${labels.map((label) => ` ${JSON.stringify(label)},\n`).join("")}]);`,
837
+ ];
838
+ const modelText = [
839
+ `export const ${modelName} = m.model(${JSON.stringify(modelName)}, {`,
840
+ statesText.length === 0
841
+ ? controlLine
842
+ : ` ${control}: ${statesConst}.initial(${initialLabel}),`,
843
+ ...context.map(({ name, declared }) => ` ${name}: ${declared.source}.initial(${literal(start[name])}),`),
844
+ ...(threwField === null ? [] : [` ${threwField}: m.int(0, 0).initial(0),`]),
845
+ "});",
846
+ ].join("\n");
847
+ const text = `${[
848
+ 'import { m } from "@earnestjs/model";',
849
+ ...statesText,
850
+ ...(declarationConsts.length === 0 ? [] : [declarationConsts.join("\n")]),
851
+ ...helpers,
852
+ modelText,
853
+ ...actionTexts,
854
+ ...ruleTexts,
855
+ ...endTexts,
856
+ `export type State = m.Infer<typeof ${modelName}>;`,
857
+ ].join("\n\n")}\n`;
858
+ return {
859
+ text,
860
+ threw: threw.map(({ state, throw: each }) => ({ ...each, state: labels[state] ?? "" })),
861
+ actions: Object.fromEntries(events.flatMap(({ type }, kind) => {
862
+ const id = actionIds[kind];
863
+ return id === undefined ||
864
+ !actionTexts.some((each) => each.startsWith(`export const ${id} =`))
865
+ ? []
866
+ : [[id, type]];
867
+ })),
868
+ rules: Object.fromEntries(ruleEntries.map(([id], index) => [ruleIds[index] ?? id, id])),
869
+ };
870
+ };
871
+ /**
872
+ * Writes an XState v5 machine out as the text of a `.model.ts` file, so `earnest verify` and
873
+ * TLC can redo the search `checkMachine` does without running JavaScript. It takes what
874
+ * `checkMachine` takes, and `name`, the model's name. Every value must be declared: each
875
+ * context field in `context`, and each payload field in an `events` record; `events` may also be
876
+ * a list of events without payloads. The machine's own `transition` is run with every declared
877
+ * event and payload on every state value it can take, with every combination of declared context
878
+ * values, not only the ones `checkMachine` reaches, and the results are written as tables. No
879
+ * guard or `assign` is read as source, so they may call any code. The model has a field `state`
880
+ * (`state_2` if the context has a `state`), a readable label for the state value and what the
881
+ * history states remember, and one field per declared context field, starting where the initial
882
+ * snapshot made with `input` starts. Each event type is an action, each rule a rule with the
883
+ * same sentence, and a top-level final state an end. An id that is not a name in a model file,
884
+ * such as `user.click`, is changed to one, such as `user_click`. Where `checkMachine` reaches a
885
+ * state, the machine is given the context `checkMachine` reaches there, so a field missing,
886
+ * `undefined` or `null` stays as the machine left it. Elsewhere an optional context field's
887
+ * `null` is given as a missing field when the initial context lacks the field or holds
888
+ * `undefined`, and as `null` otherwise, and inside a record as `null`. A missing field and
889
+ * `undefined` read back as `null`.
890
+ * A rule is judged on a snapshot rebuilt with `resolveState`, which has no output and no child
891
+ * actors, so a rule must not read them.
892
+ * `maxStates` is not written; pass `--max-states` to `earnest verify`. The same machine and
893
+ * options give the same text. Refused before any event is tried, with an error that names what
894
+ * is wrong: a context field without a declaration, a field name that is not an identifier,
895
+ * `events` given as a function or a list entry with a payload, a model name that is not an
896
+ * identifier, an initial context outside its declarations, and context declarations and events
897
+ * whose table has more than `MOST_TABLE_ROWS` rows for one state. A table that passes the limit
898
+ * as states are found is refused then. So is a machine that reaches an optional field, at any
899
+ * depth, as `null` in one state and missing or `undefined` in another that is otherwise the
900
+ * same, naming the event and the field: `checkMachine` counts two states there, and the file
901
+ * has one `null` for both. A next context the declaration's type can't hold, such as text in a
902
+ * field declared `m.int`, is refused with the event and the field; one of the right
903
+ * type outside the declaration is written as it is, so `earnest verify` reports it out of range.
904
+ */
905
+ export const modelFileOf = (machine, options) => write(machine, options);