@20baht/engine 0.0.0-stage → 0.1.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/approval.d.ts +15 -0
  4. package/dist/approval.js +18 -0
  5. package/dist/dates.d.ts +34 -0
  6. package/dist/dates.js +91 -0
  7. package/dist/defaults.d.ts +6 -0
  8. package/dist/defaults.js +37 -0
  9. package/dist/display.d.ts +33 -0
  10. package/dist/display.js +110 -0
  11. package/dist/engine/conditions.d.ts +27 -0
  12. package/dist/engine/conditions.js +123 -0
  13. package/dist/engine/evaluate.d.ts +8 -0
  14. package/dist/engine/evaluate.js +368 -0
  15. package/dist/engine/expressions.d.ts +3 -0
  16. package/dist/engine/expressions.js +70 -0
  17. package/dist/engine/form-session.d.ts +135 -0
  18. package/dist/engine/form-session.js +313 -0
  19. package/dist/engine/graph.d.ts +40 -0
  20. package/dist/engine/graph.js +59 -0
  21. package/dist/engine/runtime.d.ts +194 -0
  22. package/dist/engine/runtime.js +268 -0
  23. package/dist/engine/scripts.d.ts +34 -0
  24. package/dist/engine/scripts.js +98 -0
  25. package/dist/flags.d.ts +19 -0
  26. package/dist/flags.js +49 -0
  27. package/dist/form-values.d.ts +78 -0
  28. package/dist/form-values.js +6 -0
  29. package/dist/i18n.d.ts +177 -0
  30. package/dist/i18n.js +310 -0
  31. package/dist/index.d.ts +25 -0
  32. package/dist/index.js +23 -0
  33. package/dist/keys.d.ts +14 -0
  34. package/dist/keys.js +4 -0
  35. package/dist/legacy.d.ts +14 -0
  36. package/dist/legacy.js +47 -0
  37. package/dist/pattern-safety.d.ts +34 -0
  38. package/dist/pattern-safety.js +267 -0
  39. package/dist/same-data.d.ts +5 -0
  40. package/dist/same-data.js +23 -0
  41. package/dist/shortcut.d.ts +44 -0
  42. package/dist/shortcut.js +176 -0
  43. package/dist/types.d.ts +541 -0
  44. package/dist/types.js +1 -0
  45. package/dist/urls.d.ts +8 -0
  46. package/dist/urls.js +30 -0
  47. package/dist/validators.d.ts +39 -0
  48. package/dist/validators.js +372 -0
  49. package/dist/views.d.ts +12 -0
  50. package/dist/views.js +11 -0
  51. package/package.json +52 -4
@@ -0,0 +1,313 @@
1
+ import { defaultValue } from '../defaults.js';
2
+ import { t, withLocale } from '../i18n.js';
3
+ import { sameData } from '../same-data.js';
4
+ import { validateField } from '../validators.js';
5
+ import { resolveViewFields } from '../views.js';
6
+ import { createScriptContext, hasScripts, MAX_SCRIPT_DEPTH, runScripts, } from './scripts.js';
7
+ export const emptyFormState = Object.freeze({
8
+ edits: Object.freeze({}),
9
+ errors: Object.freeze([]),
10
+ scriptStates: Object.freeze({}),
11
+ fieldMessages: Object.freeze({}),
12
+ formMessages: Object.freeze([]),
13
+ });
14
+ const isStatic = (field) => field.type === 'label' || field.type === 'section';
15
+ function valueOf(input, state, field) {
16
+ if (Object.hasOwn(state.edits, field.key))
17
+ return state.edits[field.key];
18
+ if (input.value && Object.hasOwn(input.value, field.key))
19
+ return input.value[field.key];
20
+ return defaultValue(field);
21
+ }
22
+ export function formData(input, state) {
23
+ const data = {};
24
+ for (const field of input.form.fields) {
25
+ if (!isStatic(field))
26
+ data[field.key] = valueOf(input, state, field);
27
+ }
28
+ return data;
29
+ }
30
+ export function formFieldState(input, state, field) {
31
+ const base = input.fieldStates?.[field.key] ?? {
32
+ visible: true,
33
+ enabled: !field.disabled,
34
+ readonly: !!field.readonly,
35
+ required: !!field.required,
36
+ computed: false,
37
+ };
38
+ const override = state.scriptStates[field.key];
39
+ const merged = override ? { ...base, ...override } : base;
40
+ return field.hidden ? { ...merged, visible: false } : merged;
41
+ }
42
+ export function validateShownField(field, shown, value, registry, data, rowStates) {
43
+ if (shown && !shown.visible)
44
+ return [];
45
+ const required = shown ? shown.required : !!field.required;
46
+ const descriptor = required === !!field.required ? field : { ...field, required };
47
+ return validateField(descriptor, value, registry, data, rowStates);
48
+ }
49
+ function blocking(ok, messages) {
50
+ const errors = messages
51
+ .filter((m) => m.type === 'error')
52
+ .map((m) => ({ key: '$', message: m.message }));
53
+ if (!ok && errors.length === 0)
54
+ errors.push({ key: '$', message: t('scriptBlocked') });
55
+ return errors;
56
+ }
57
+ export function submitScriptErrors(form, registry, sink) {
58
+ if (!hasScripts(form, 'submit'))
59
+ return [];
60
+ let messages = [];
61
+ const g = createScriptContext(form, {
62
+ ...sink,
63
+ addFormMessage: (message) => {
64
+ messages.push(message);
65
+ sink.addFormMessage(message);
66
+ },
67
+ clearFormMessages: () => {
68
+ messages = [];
69
+ sink.clearFormMessages();
70
+ },
71
+ });
72
+ const ok = runScripts({
73
+ form,
74
+ registry: registry ?? {},
75
+ g,
76
+ on: 'submit',
77
+ detail: { isLoading: false, data: { ...sink.getData() } },
78
+ });
79
+ return blocking(ok, messages);
80
+ }
81
+ class Step {
82
+ constructor(input, state, host) {
83
+ this.input = input;
84
+ this.state = state;
85
+ this.host = host;
86
+ this.events = [];
87
+ this.depth = 0;
88
+ this.context = null;
89
+ this.sink = {
90
+ getData: () => this.data(),
91
+ setValue: (key, value) => {
92
+ this.write(key, value);
93
+ },
94
+ setState: (key, patch) => {
95
+ const { scriptStates } = this.state;
96
+ this.patch({ scriptStates: { ...scriptStates, [key]: { ...scriptStates[key], ...patch } } });
97
+ },
98
+ resetState: (key) => {
99
+ if (key === undefined) {
100
+ this.patch({ scriptStates: {} });
101
+ return;
102
+ }
103
+ const { [key]: _dropped, ...scriptStates } = this.state.scriptStates;
104
+ this.patch({ scriptStates });
105
+ },
106
+ setFieldMessage: (key, message) => {
107
+ const { [key]: _dropped, ...rest } = this.state.fieldMessages;
108
+ this.patch({ fieldMessages: message ? { ...rest, [key]: message } : rest });
109
+ },
110
+ addFormMessage: (message) => {
111
+ this.patch({ formMessages: [...this.state.formMessages, message] });
112
+ },
113
+ clearFormMessages: () => {
114
+ this.patch({ formMessages: [] });
115
+ },
116
+ };
117
+ }
118
+ get form() {
119
+ return this.input.form;
120
+ }
121
+ field(key) {
122
+ return this.form.fields.find((f) => f.key === key);
123
+ }
124
+ data() {
125
+ return formData(this.input, this.state);
126
+ }
127
+ patch(next) {
128
+ this.state = { ...this.state, ...next };
129
+ }
130
+ g() {
131
+ this.context ??= (this.host.context ?? createScriptContext)(this.form, this.sink);
132
+ return this.context;
133
+ }
134
+ clearDependents(changed) {
135
+ const queue = [changed];
136
+ const cleared = new Set();
137
+ for (let key = queue.shift(); key !== undefined; key = queue.shift()) {
138
+ for (const f of this.form.fields) {
139
+ if (!f.options_deps?.includes(key) || cleared.has(f.key))
140
+ continue;
141
+ cleared.add(f.key);
142
+ this.patch({ edits: { ...this.state.edits, [f.key]: defaultValue(f) } });
143
+ queue.push(f.key);
144
+ }
145
+ }
146
+ }
147
+ write(key, value, revalidate = false) {
148
+ const before = this.data()[key];
149
+ this.patch({ edits: { ...this.state.edits, [key]: value } });
150
+ this.clearDependents(key);
151
+ if (revalidate && (this.input.validateOn ?? 'change') === 'change' && this.hasErrors()) {
152
+ this.patch({ errors: this.validators() });
153
+ }
154
+ this.events.push({
155
+ name: 'baht-change',
156
+ detail: { form_name: this.form.form_name, key, value, data: this.data() },
157
+ });
158
+ this.change(key, before, value, false);
159
+ }
160
+ hasErrors() {
161
+ return this.state.errors.length > 0;
162
+ }
163
+ input_(key, raw) {
164
+ const field = this.field(key);
165
+ if (!field || isStatic(field))
166
+ return;
167
+ const format = field.formatter ? this.input.registry?.formatters?.[field.formatter] : undefined;
168
+ if (field.formatter && !format) {
169
+ console.warn(`[bahtui] unknown formatter "${field.formatter}" — skipped`);
170
+ }
171
+ this.write(key, format ? format(raw) : raw, true);
172
+ }
173
+ set(patch) {
174
+ const before = this.data();
175
+ this.patch({ edits: { ...this.state.edits, ...patch } });
176
+ for (const key of Object.keys(patch))
177
+ this.change(key, before[key], patch[key], false);
178
+ }
179
+ revert(keys) {
180
+ if (!keys.some((key) => Object.hasOwn(this.state.edits, key)))
181
+ return;
182
+ this.patch({
183
+ edits: Object.fromEntries(Object.entries(this.state.edits).filter(([key]) => !keys.includes(key))),
184
+ });
185
+ }
186
+ valueReplaced(previous) {
187
+ const after = this.input.value ?? {};
188
+ const kept = Object.entries(this.state.edits).filter(([k]) => sameData(previous[k], after[k]));
189
+ if (kept.length !== Object.keys(this.state.edits).length) {
190
+ this.patch({ edits: Object.fromEntries(kept) });
191
+ }
192
+ }
193
+ formReplaced(previous) {
194
+ if (previous && previous.form_id !== this.form.form_id)
195
+ this.patch({ edits: {}, errors: [] });
196
+ this.patch({ scriptStates: {}, fieldMessages: {}, formMessages: [] });
197
+ }
198
+ change(key, oldValue, newValue, isLoading) {
199
+ if (!hasScripts(this.form, 'change', key))
200
+ return;
201
+ if (this.depth >= MAX_SCRIPT_DEPTH) {
202
+ console.warn(`[bahtui] script cascade on "${this.form.form_name}.${key}" exceeded ${String(MAX_SCRIPT_DEPTH)} levels — stopped (setValue ping-pong between change scripts?)`);
203
+ return;
204
+ }
205
+ this.depth++;
206
+ try {
207
+ runScripts({
208
+ form: this.form,
209
+ registry: this.input.registry ?? {},
210
+ g: this.g(),
211
+ on: 'change',
212
+ key,
213
+ detail: { oldValue, newValue, isLoading, data: this.data() },
214
+ });
215
+ }
216
+ finally {
217
+ this.depth--;
218
+ }
219
+ }
220
+ load() {
221
+ if (!this.form.scripts?.length)
222
+ return;
223
+ const data = this.data();
224
+ for (const f of this.form.fields) {
225
+ if (!isStatic(f))
226
+ this.change(f.key, undefined, data[f.key], true);
227
+ }
228
+ if (!hasScripts(this.form, 'load'))
229
+ return;
230
+ runScripts({
231
+ form: this.form,
232
+ registry: this.input.registry ?? {},
233
+ g: this.g(),
234
+ on: 'load',
235
+ detail: { isLoading: true, data: this.data() },
236
+ });
237
+ }
238
+ shown() {
239
+ const { form, view } = this.input;
240
+ return resolveViewFields(form, view) ?? resolveViewFields(form) ?? [];
241
+ }
242
+ validateOne(field, data) {
243
+ return validateShownField(field, formFieldState(this.input, this.state, field), valueOf(this.input, this.state, field), this.input.registry, data, this.input.fieldStates ?? {});
244
+ }
245
+ validators() {
246
+ const data = this.data();
247
+ return this.shown()
248
+ .filter((f) => !isStatic(f))
249
+ .flatMap((f) => this.validateOne(f, data));
250
+ }
251
+ validate() {
252
+ const errors = this.validators();
253
+ if (hasScripts(this.form, 'submit')) {
254
+ this.patch({ formMessages: [] });
255
+ const ok = runScripts({
256
+ form: this.form,
257
+ registry: this.input.registry ?? {},
258
+ g: this.g(),
259
+ on: 'submit',
260
+ detail: { isLoading: false, data: this.data() },
261
+ });
262
+ errors.push(...blocking(ok, this.state.formMessages));
263
+ }
264
+ this.patch({ errors });
265
+ this.events.push({ name: 'baht-validity', detail: { valid: errors.length === 0, errors } });
266
+ }
267
+ blur(key) {
268
+ const field = this.field(key);
269
+ if (!field || this.input.validateOn !== 'blur')
270
+ return;
271
+ const others = this.state.errors.filter((er) => er.key !== key);
272
+ this.patch({ errors: [...others, ...this.validateOne(field, this.data())] });
273
+ }
274
+ }
275
+ export function updateForm(input, state, msg, host = {}) {
276
+ return withLocale(input.locale, () => runStep(input, state, msg, host));
277
+ }
278
+ function runStep(input, state, msg, host) {
279
+ const step = new Step(input, state, host);
280
+ switch (msg.type) {
281
+ case 'input':
282
+ step.input_(msg.key, msg.value);
283
+ break;
284
+ case 'set':
285
+ step.set(msg.patch);
286
+ break;
287
+ case 'revert':
288
+ step.revert(msg.keys);
289
+ break;
290
+ case 'value':
291
+ step.valueReplaced(msg.previous);
292
+ break;
293
+ case 'form':
294
+ step.formReplaced(msg.previous);
295
+ break;
296
+ case 'load':
297
+ step.load();
298
+ break;
299
+ case 'validate':
300
+ step.validate();
301
+ break;
302
+ case 'blur':
303
+ step.blur(msg.key);
304
+ break;
305
+ case 'script':
306
+ msg.write(step.sink);
307
+ break;
308
+ case 'reset':
309
+ step.state = emptyFormState;
310
+ break;
311
+ }
312
+ return { state: step.state, events: step.events };
313
+ }
@@ -0,0 +1,40 @@
1
+ import type { Derived, DerivedFieldState, NestedData, WorkflowDefinition, WorkflowForm } from '../types.js';
2
+ /**
3
+ * Graph routing (spec 03 §6). `transitions` turn the linear wizard into a
4
+ * graph: from a form, the first edge whose `when` matches wins; `to: 'end'`
5
+ * submits. Forms without outgoing edges — or whose edges all miss — fall
6
+ * back to the next visible form in `order`, so branches are added only where
7
+ * needed. Invisible targets (rule-hidden/skipped) are passed through to
8
+ * their own next hop.
9
+ */
10
+ /**
11
+ * The forms a run can stand on, in `order`: every form the rules have not hidden or skipped.
12
+ * `derived` is what `evaluate()` returned for the data; without one, every form shows. The one
13
+ * definition for the element, the runtime and the server.
14
+ */
15
+ export declare function visibleForms(workflow: WorkflowDefinition, derived?: Pick<Derived, 'forms'> | null): WorkflowForm[];
16
+ /**
17
+ * One step of a workflow rendered on its own: the rule-derived state of `formName`'s fields for
18
+ * this data, keyed as `<baht-form>.fieldStates` reads them (`key`, and `key[i].sub` for a
19
+ * repeater row's sub-field). The rules are the whole workflow's, so a condition may read another
20
+ * step's data (`Review.scanned`); pass what is known of it in `data`. For a run that lives on a
21
+ * server and is filled one step at a time, by different people: `@20baht/validator`'s
22
+ * `validateSubmission(workflow, body, …, { form, context })` checks the same step the same way.
23
+ */
24
+ export declare function stepFieldStates(workflow: WorkflowDefinition, formName: string, data: NestedData): Record<string, DerivedFieldState>;
25
+ /**
26
+ * The step after `current` given the data: a form_name or 'end'. Rules run
27
+ * (via evaluate) to decide visibility; hidden targets pass through, cycles
28
+ * of invisible forms end the walk. `visibility` lets a caller that already
29
+ * ran the rules (walkPath — data never changes during a walk) skip the
30
+ * per-hop evaluate() fixpoint.
31
+ */
32
+ export declare function resolveNext(workflow: WorkflowDefinition, current: string, data: NestedData, visibility?: ReadonlySet<string>): string;
33
+ /**
34
+ * The full path a submission takes from the start form to 'end' under this
35
+ * data — what the server validates against (off-path forms are as good as
36
+ * skipped). Back-edges that revisit a form stop the walk instead of looping.
37
+ * A caller that has already run `evaluate()` on this data passes the visible
38
+ * form names as `visibility` and saves the second fixpoint.
39
+ */
40
+ export declare function walkPath(workflow: WorkflowDefinition, data: NestedData, visibility?: ReadonlySet<string>): string[];
@@ -0,0 +1,59 @@
1
+ import { evalCondition } from './conditions.js';
2
+ import { evaluate } from './evaluate.js';
3
+ export function visibleForms(workflow, derived) {
4
+ const forms = [...workflow.forms].sort((a, b) => a.order - b.order);
5
+ return derived ? forms.filter((f) => derived.forms[f.form_name]?.visible !== false) : forms;
6
+ }
7
+ export function stepFieldStates(workflow, formName, data) {
8
+ if (!workflow.forms.some((f) => f.form_name === formName))
9
+ return {};
10
+ const prefix = `${formName}.`;
11
+ const states = {};
12
+ for (const [ref, state] of Object.entries(evaluate(workflow, data).fields)) {
13
+ if (ref.startsWith(prefix))
14
+ states[ref.slice(prefix.length)] = state;
15
+ }
16
+ return states;
17
+ }
18
+ function visibleNames(workflow, data) {
19
+ return new Set(visibleForms(workflow, evaluate(workflow, data)).map((f) => f.form_name));
20
+ }
21
+ function hop(workflow, from, data) {
22
+ for (const t of workflow.transitions ?? []) {
23
+ if (t.from !== from)
24
+ continue;
25
+ if (evalCondition(t.when, data))
26
+ return t.to;
27
+ }
28
+ const sorted = [...workflow.forms].sort((a, b) => a.order - b.order);
29
+ const idx = sorted.findIndex((f) => f.form_name === from);
30
+ return idx >= 0 && idx + 1 < sorted.length ? sorted[idx + 1].form_name : 'end';
31
+ }
32
+ export function resolveNext(workflow, current, data, visibility) {
33
+ const visible = visibility ?? visibleNames(workflow, data);
34
+ const seen = new Set([current]);
35
+ let target = hop(workflow, current, data);
36
+ while (target !== 'end' && !visible.has(target)) {
37
+ if (seen.has(target))
38
+ return 'end';
39
+ seen.add(target);
40
+ target = hop(workflow, target, data);
41
+ }
42
+ return target;
43
+ }
44
+ export function walkPath(workflow, data, visibility) {
45
+ const visible = visibility ?? visibleNames(workflow, data);
46
+ const sorted = [...workflow.forms].sort((a, b) => a.order - b.order);
47
+ const start = sorted.find((f) => visible.has(f.form_name))?.form_name;
48
+ if (!start)
49
+ return [];
50
+ const path = [];
51
+ const seen = new Set();
52
+ let current = start;
53
+ while (current !== 'end' && !seen.has(current)) {
54
+ seen.add(current);
55
+ path.push(current);
56
+ current = resolveNext(workflow, current, data, visible);
57
+ }
58
+ return path;
59
+ }
@@ -0,0 +1,194 @@
1
+ import type { ApprovalDecision, Derived, NestedData, ValidationError, WorkflowDefinition, WorkflowForm } from '../types.js';
2
+ export type StepDirection = 'forward' | 'back';
3
+ /** A run: where it stands and what it holds. Plain data, safe to keep, compare and log. */
4
+ export interface WorkflowState {
5
+ /** The `workflow_id` of the definition the run began under. */
6
+ workflow_id: string;
7
+ /** `evaluate()` of the run's data. `derived.data` is the data: cleared and computed values included. */
8
+ derived: Derived;
9
+ /** `form_name` of the step showing, or `null` when no form is visible. */
10
+ current: string | null;
11
+ /** The steps walked to get here, oldest first: what `back` returns along. */
12
+ history: readonly string[];
13
+ /** The decision the user last tried needs a comment: a catalog key, `null` once it is given. */
14
+ approvalError: 'commentRequired' | null;
15
+ /** Which way the last navigation went; `null` before the first. */
16
+ direction: StepDirection | null;
17
+ /**
18
+ * How the run ended: `'completed'` once it submitted, `'rejected'` once a rejection ended it.
19
+ * An ended run takes no more presses, decisions or navigation (a second click submits nothing);
20
+ * `start` or `restore` begins again. `null` while it runs.
21
+ */
22
+ ended: WorkflowEnd | null;
23
+ }
24
+ export type WorkflowEnd = 'completed' | 'rejected';
25
+ /**
26
+ * A run as JSON: what to keep to pick it up again later (another page load, another device)
27
+ * or to step back to (undo). The rules are not in it: `restore` runs them on `data` again.
28
+ * A copy: changing it (dropping a password before it is stored) leaves the run alone. It holds
29
+ * every value entered, `password` fields included; redact what must not be kept.
30
+ */
31
+ export interface WorkflowSnapshot {
32
+ /** The workflow it was taken from: `restore` under another one starts an empty run. */
33
+ workflow_id: string;
34
+ data: NestedData;
35
+ current: string | null;
36
+ history: string[];
37
+ ended: WorkflowEnd | null;
38
+ }
39
+ interface Validity {
40
+ valid: boolean;
41
+ errors: ValidationError[];
42
+ }
43
+ /** What can happen to a run. */
44
+ export type WorkflowMsg =
45
+ /** Begin (or begin again) from this data: first visible step, no history. */
46
+ {
47
+ type: 'start';
48
+ value: NestedData;
49
+ }
50
+ /** The workflow passed in was re-resolved against other flags: same data, other steps. */
51
+ | {
52
+ type: 'flags';
53
+ }
54
+ /** The user edited one field. */
55
+ | {
56
+ type: 'edit';
57
+ form_name: string;
58
+ key: string;
59
+ value: unknown;
60
+ }
61
+ /** The host wrote values into one form. */
62
+ | {
63
+ type: 'patch';
64
+ form_name: string;
65
+ patch: Record<string, unknown>;
66
+ }
67
+ /** The approval comment changed. */
68
+ | {
69
+ type: 'comment';
70
+ form_name: string;
71
+ value: string;
72
+ }
73
+ /**
74
+ * Next/Submit was pressed on a form the caller validated. With `gate`, an invalid form
75
+ * stays put and nothing is emitted. On an approval step this approves.
76
+ */
77
+ | {
78
+ type: 'next';
79
+ validity: Validity;
80
+ gate: boolean;
81
+ }
82
+ /**
83
+ * Approve or reject the approval step showing. `validity` is that of the step's own fields,
84
+ * when it has any; with `gate`, invalid ones keep the decision from being taken.
85
+ */
86
+ | {
87
+ type: 'decide';
88
+ decision: ApprovalDecision;
89
+ validity?: Validity;
90
+ gate?: boolean;
91
+ } | {
92
+ type: 'back';
93
+ } | {
94
+ type: 'gotoStart';
95
+ }
96
+ /**
97
+ * Pick a kept run up again. The snapshot is untrusted (it was stored somewhere): the rules run
98
+ * on its data, a step that is not visible falls back to the first one that is, and history
99
+ * entries that are not visible steps are dropped; a snapshot of another workflow restores as an
100
+ * empty run. Navigation events are not emitted.
101
+ */
102
+ | {
103
+ type: 'restore';
104
+ snapshot: unknown;
105
+ };
106
+ /** The events a step can call for: the names and details `<baht-workflow>` dispatches. */
107
+ export interface WorkflowEventMap {
108
+ 'baht-data-change': {
109
+ data: NestedData;
110
+ };
111
+ 'baht-next': {
112
+ form_name: string;
113
+ order: number;
114
+ data: NestedData;
115
+ valid?: boolean;
116
+ errors?: ValidationError[];
117
+ decision?: ApprovalDecision;
118
+ comment?: string;
119
+ };
120
+ 'baht-step-change': {
121
+ form_name: string;
122
+ order: number;
123
+ direction: StepDirection;
124
+ };
125
+ 'baht-nav-blocked': {
126
+ form_name: string | null;
127
+ target: string;
128
+ /** `rule-error`: the last step would submit data whose rules never settled (the server refuses it). */
129
+ reason: 'self-transition' | 'target-hidden' | 'rule-error';
130
+ data: NestedData;
131
+ };
132
+ 'baht-submit': {
133
+ data: NestedData;
134
+ valid?: boolean;
135
+ errors?: ValidationError[];
136
+ decision?: ApprovalDecision;
137
+ comment?: string;
138
+ };
139
+ 'baht-complete': {
140
+ data: NestedData;
141
+ status: 'completed' | 'rejected';
142
+ };
143
+ 'baht-approve': ApprovalDetail;
144
+ 'baht-reject': ApprovalDetail;
145
+ 'baht-rule-error': {
146
+ errors: Derived['errors'];
147
+ };
148
+ }
149
+ interface ApprovalDetail {
150
+ form_name: string;
151
+ decision: ApprovalDecision;
152
+ comment: string;
153
+ data: NestedData;
154
+ }
155
+ export type WorkflowEvent = {
156
+ [K in keyof WorkflowEventMap]: {
157
+ name: K;
158
+ detail: WorkflowEventMap[K];
159
+ };
160
+ }[keyof WorkflowEventMap];
161
+ export interface WorkflowUpdate {
162
+ state: WorkflowState;
163
+ /** In the order to dispatch them. */
164
+ events: WorkflowEvent[];
165
+ }
166
+ /** One step of a run as it happened: what `<baht-workflow>` tells as `baht-transition`. */
167
+ export interface WorkflowTransition {
168
+ msg: WorkflowMsg;
169
+ /** `null` for the step that started the run. */
170
+ before: WorkflowState | null;
171
+ after: WorkflowState;
172
+ events: WorkflowEvent[];
173
+ }
174
+ /** The visible form the run stands on, or `null`. */
175
+ export declare function currentForm(workflow: WorkflowDefinition, state: Pick<WorkflowState, 'derived' | 'current'>): WorkflowForm | null;
176
+ /**
177
+ * Where Next would go from here: a `form_name`, or `'end'` (spec 03 §6). A caller that already
178
+ * holds `visibleForms(workflow, state.derived)` passes it as `visible` and saves the sort.
179
+ */
180
+ export declare function nextTarget(workflow: WorkflowDefinition, state: Pick<WorkflowState, 'derived' | 'current'>, visible?: readonly WorkflowForm[]): string;
181
+ /**
182
+ * One step of a run. `workflow` is the definition as the run sees it (flags already applied);
183
+ * `state` is `null` before the first step. Pure: same arguments, same result.
184
+ */
185
+ export declare function updateWorkflow(workflow: WorkflowDefinition, state: WorkflowState | null, msg: WorkflowMsg): WorkflowUpdate;
186
+ /**
187
+ * A log of messages, folded: the state the run reaches and every event on the way. From `from`,
188
+ * or from nothing. Exact for the rules and the navigation; what a host script wrote during the
189
+ * original run is in the log only as the edits it made.
190
+ */
191
+ export declare function replayWorkflow(workflow: WorkflowDefinition, msgs: readonly WorkflowMsg[], from?: WorkflowState | null): WorkflowUpdate;
192
+ /** What to keep of a run to `restore` it later. */
193
+ export declare function snapshotOf(state: WorkflowState): WorkflowSnapshot;
194
+ export {};