@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.
- package/LICENSE +21 -0
- package/README.md +52 -2
- package/dist/approval.d.ts +15 -0
- package/dist/approval.js +18 -0
- package/dist/dates.d.ts +34 -0
- package/dist/dates.js +91 -0
- package/dist/defaults.d.ts +6 -0
- package/dist/defaults.js +37 -0
- package/dist/display.d.ts +33 -0
- package/dist/display.js +110 -0
- package/dist/engine/conditions.d.ts +27 -0
- package/dist/engine/conditions.js +123 -0
- package/dist/engine/evaluate.d.ts +8 -0
- package/dist/engine/evaluate.js +368 -0
- package/dist/engine/expressions.d.ts +3 -0
- package/dist/engine/expressions.js +70 -0
- package/dist/engine/form-session.d.ts +135 -0
- package/dist/engine/form-session.js +313 -0
- package/dist/engine/graph.d.ts +40 -0
- package/dist/engine/graph.js +59 -0
- package/dist/engine/runtime.d.ts +194 -0
- package/dist/engine/runtime.js +268 -0
- package/dist/engine/scripts.d.ts +34 -0
- package/dist/engine/scripts.js +98 -0
- package/dist/flags.d.ts +19 -0
- package/dist/flags.js +49 -0
- package/dist/form-values.d.ts +78 -0
- package/dist/form-values.js +6 -0
- package/dist/i18n.d.ts +177 -0
- package/dist/i18n.js +310 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +23 -0
- package/dist/keys.d.ts +14 -0
- package/dist/keys.js +4 -0
- package/dist/legacy.d.ts +14 -0
- package/dist/legacy.js +47 -0
- package/dist/pattern-safety.d.ts +34 -0
- package/dist/pattern-safety.js +267 -0
- package/dist/same-data.d.ts +5 -0
- package/dist/same-data.js +23 -0
- package/dist/shortcut.d.ts +44 -0
- package/dist/shortcut.js +176 -0
- package/dist/types.d.ts +541 -0
- package/dist/types.js +1 -0
- package/dist/urls.d.ts +8 -0
- package/dist/urls.js +30 -0
- package/dist/validators.d.ts +39 -0
- package/dist/validators.js +372 -0
- package/dist/views.d.ts +12 -0
- package/dist/views.js +11 -0
- package/package.json +52 -4
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { approvalCommentRequired } from '../approval.js';
|
|
2
|
+
import { isBlank } from '../validators.js';
|
|
3
|
+
import { evaluate } from './evaluate.js';
|
|
4
|
+
import { resolveNext, visibleForms } from './graph.js';
|
|
5
|
+
export function currentForm(workflow, state) {
|
|
6
|
+
return visibleForms(workflow, state.derived).find((f) => f.form_name === state.current) ?? null;
|
|
7
|
+
}
|
|
8
|
+
export function nextTarget(workflow, state, visible = visibleForms(workflow, state.derived)) {
|
|
9
|
+
if (!state.current)
|
|
10
|
+
return 'end';
|
|
11
|
+
if (workflow.transitions && workflow.transitions.length > 0) {
|
|
12
|
+
const shown = new Set(visible.map((f) => f.form_name));
|
|
13
|
+
return resolveNext(workflow, state.current, state.derived.data, shown);
|
|
14
|
+
}
|
|
15
|
+
const idx = visible.findIndex((f) => f.form_name === state.current);
|
|
16
|
+
return visible[idx + 1]?.form_name ?? 'end';
|
|
17
|
+
}
|
|
18
|
+
export function updateWorkflow(workflow, state, msg) {
|
|
19
|
+
const events = [];
|
|
20
|
+
const emit = (event) => {
|
|
21
|
+
events.push(event);
|
|
22
|
+
};
|
|
23
|
+
if (msg.type === 'start')
|
|
24
|
+
return { state: start(workflow, state, msg.value, emit), events };
|
|
25
|
+
if (msg.type === 'restore')
|
|
26
|
+
return { state: restore(workflow, state, msg.snapshot, emit), events };
|
|
27
|
+
const from = state ?? start(workflow, null, {}, emit);
|
|
28
|
+
return { state: step(workflow, from, msg, emit), events };
|
|
29
|
+
}
|
|
30
|
+
export function replayWorkflow(workflow, msgs, from = null) {
|
|
31
|
+
const events = [];
|
|
32
|
+
let state = from;
|
|
33
|
+
for (const msg of msgs) {
|
|
34
|
+
const update = updateWorkflow(workflow, state, msg);
|
|
35
|
+
state = update.state;
|
|
36
|
+
events.push(...update.events);
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
state: state ?? updateWorkflow(workflow, null, { type: 'start', value: {} }).state,
|
|
40
|
+
events,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function step(workflow, state, msg, emit) {
|
|
44
|
+
if (state.ended && ENDED_IGNORES.has(msg.type))
|
|
45
|
+
return state;
|
|
46
|
+
switch (msg.type) {
|
|
47
|
+
case 'flags':
|
|
48
|
+
return onVisibleStep(workflow, withData(workflow, state, state.derived.data, emit));
|
|
49
|
+
case 'edit':
|
|
50
|
+
return write(workflow, state, msg.form_name, { [msg.key]: msg.value }, emit);
|
|
51
|
+
case 'patch':
|
|
52
|
+
return write(workflow, state, msg.form_name, msg.patch, emit);
|
|
53
|
+
case 'comment':
|
|
54
|
+
return comment(workflow, state, msg.form_name, msg.value, emit);
|
|
55
|
+
case 'next':
|
|
56
|
+
return next(workflow, state, msg.validity, msg.gate, emit);
|
|
57
|
+
case 'decide':
|
|
58
|
+
if (msg.gate && msg.validity && !msg.validity.valid)
|
|
59
|
+
return state;
|
|
60
|
+
return decide(workflow, state, msg.decision, emit);
|
|
61
|
+
case 'back':
|
|
62
|
+
return back(workflow, state, emit);
|
|
63
|
+
case 'gotoStart':
|
|
64
|
+
return gotoStart(workflow, state, emit);
|
|
65
|
+
default:
|
|
66
|
+
return state;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const ENDED_IGNORES = new Set([
|
|
70
|
+
'next',
|
|
71
|
+
'decide',
|
|
72
|
+
'back',
|
|
73
|
+
'gotoStart',
|
|
74
|
+
]);
|
|
75
|
+
function start(workflow, previous, value, emit) {
|
|
76
|
+
const derived = evaluated(workflow, structuredClone(value), previous?.derived.errors, emit);
|
|
77
|
+
return {
|
|
78
|
+
workflow_id: workflow.workflow_id,
|
|
79
|
+
derived,
|
|
80
|
+
current: visibleForms(workflow, derived)[0]?.form_name ?? null,
|
|
81
|
+
history: [],
|
|
82
|
+
approvalError: null,
|
|
83
|
+
direction: previous?.direction ?? null,
|
|
84
|
+
ended: null,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
export function snapshotOf(state) {
|
|
88
|
+
return {
|
|
89
|
+
workflow_id: state.workflow_id,
|
|
90
|
+
data: structuredClone(state.derived.data),
|
|
91
|
+
current: state.current,
|
|
92
|
+
history: [...state.history],
|
|
93
|
+
ended: state.ended,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
97
|
+
function restore(workflow, previous, snapshot, emit) {
|
|
98
|
+
const record = isRecord(snapshot) ? snapshot : {};
|
|
99
|
+
const foreign = typeof record.workflow_id === 'string' && record.workflow_id !== workflow.workflow_id;
|
|
100
|
+
const kept = foreign ? {} : record;
|
|
101
|
+
const data = isRecord(kept.data) ? kept.data : {};
|
|
102
|
+
const begun = start(workflow, previous, data, emit);
|
|
103
|
+
const ended = kept.ended === 'completed' || kept.ended === 'rejected' ? kept.ended : null;
|
|
104
|
+
const visible = new Set(visibleForms(workflow, begun.derived).map((f) => f.form_name));
|
|
105
|
+
const current = typeof kept.current === 'string' && visible.has(kept.current) ? kept.current : null;
|
|
106
|
+
if (current === null)
|
|
107
|
+
return { ...begun, direction: null, ended };
|
|
108
|
+
const walked = Array.isArray(kept.history) ? kept.history : [];
|
|
109
|
+
const history = walked.filter((name) => typeof name === 'string' && name !== current && visible.has(name));
|
|
110
|
+
return { ...begun, current, history, direction: null, ended };
|
|
111
|
+
}
|
|
112
|
+
function evaluated(workflow, data, before, emit) {
|
|
113
|
+
const derived = evaluate(workflow, data);
|
|
114
|
+
if (JSON.stringify(derived.errors) !== JSON.stringify(before ?? [])) {
|
|
115
|
+
emit({ name: 'baht-rule-error', detail: { errors: derived.errors } });
|
|
116
|
+
}
|
|
117
|
+
return derived;
|
|
118
|
+
}
|
|
119
|
+
function withData(workflow, state, data, emit) {
|
|
120
|
+
return { ...state, derived: evaluated(workflow, data, state.derived.errors, emit) };
|
|
121
|
+
}
|
|
122
|
+
function onVisibleStep(workflow, state) {
|
|
123
|
+
const visible = visibleForms(workflow, state.derived);
|
|
124
|
+
if (!state.current || visible.some((f) => f.form_name === state.current))
|
|
125
|
+
return state;
|
|
126
|
+
return { ...state, current: visible[0]?.form_name ?? null };
|
|
127
|
+
}
|
|
128
|
+
function merged(data, form_name, patch) {
|
|
129
|
+
return { ...data, [form_name]: { ...data[form_name], ...patch } };
|
|
130
|
+
}
|
|
131
|
+
function write(workflow, state, form_name, patch, emit) {
|
|
132
|
+
const data = merged(state.derived.data, form_name, structuredClone(patch));
|
|
133
|
+
const after = onVisibleStep(workflow, withData(workflow, state, data, emit));
|
|
134
|
+
emit({ name: 'baht-data-change', detail: { data: after.derived.data } });
|
|
135
|
+
return after;
|
|
136
|
+
}
|
|
137
|
+
function comment(workflow, state, form_name, value, emit) {
|
|
138
|
+
const data = merged(state.derived.data, form_name, { comment: value });
|
|
139
|
+
const after = withData(workflow, state, data, emit);
|
|
140
|
+
emit({ name: 'baht-data-change', detail: { data: after.derived.data } });
|
|
141
|
+
return isBlank(value) ? after : { ...after, approvalError: null };
|
|
142
|
+
}
|
|
143
|
+
function next(workflow, state, validity, gate, emit) {
|
|
144
|
+
const form = currentForm(workflow, state);
|
|
145
|
+
if (!form)
|
|
146
|
+
return state;
|
|
147
|
+
if (form.kind === 'approval')
|
|
148
|
+
return decide(workflow, state, 'approved', emit);
|
|
149
|
+
if (gate && !validity.valid)
|
|
150
|
+
return state;
|
|
151
|
+
const after = withData(workflow, state, state.derived.data, emit);
|
|
152
|
+
return advance(workflow, after, validity, emit);
|
|
153
|
+
}
|
|
154
|
+
function advance(workflow, state, extra, emit) {
|
|
155
|
+
const data = state.derived.data;
|
|
156
|
+
const targetName = nextTarget(workflow, state);
|
|
157
|
+
if (targetName === 'end') {
|
|
158
|
+
if (state.derived.errors.some((e) => e.kind === 'data')) {
|
|
159
|
+
emit({
|
|
160
|
+
name: 'baht-nav-blocked',
|
|
161
|
+
detail: { form_name: state.current, target: 'end', reason: 'rule-error', data },
|
|
162
|
+
});
|
|
163
|
+
return state;
|
|
164
|
+
}
|
|
165
|
+
emit({ name: 'baht-submit', detail: { ...extra, data } });
|
|
166
|
+
emit({ name: 'baht-complete', detail: { data, status: 'completed' } });
|
|
167
|
+
return { ...state, ended: 'completed' };
|
|
168
|
+
}
|
|
169
|
+
const target = visibleForms(workflow, state.derived).find((f) => f.form_name === targetName);
|
|
170
|
+
if (!target || target.form_name === state.current || state.current === null) {
|
|
171
|
+
emit({
|
|
172
|
+
name: 'baht-nav-blocked',
|
|
173
|
+
detail: {
|
|
174
|
+
form_name: state.current,
|
|
175
|
+
target: targetName,
|
|
176
|
+
reason: target ? 'self-transition' : 'target-hidden',
|
|
177
|
+
data,
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
return state;
|
|
181
|
+
}
|
|
182
|
+
emit({
|
|
183
|
+
name: 'baht-next',
|
|
184
|
+
detail: { form_name: target.form_name, order: target.order, ...extra, data },
|
|
185
|
+
});
|
|
186
|
+
emit(stepChange(target.form_name, target.order, 'forward'));
|
|
187
|
+
const seen = state.history.indexOf(target.form_name);
|
|
188
|
+
return {
|
|
189
|
+
...state,
|
|
190
|
+
history: seen >= 0 ? state.history.slice(0, seen) : [...state.history, state.current],
|
|
191
|
+
current: target.form_name,
|
|
192
|
+
direction: 'forward',
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
function stepChange(form_name, order, direction) {
|
|
196
|
+
return { name: 'baht-step-change', detail: { form_name, order, direction } };
|
|
197
|
+
}
|
|
198
|
+
function orderOf(workflow, form_name) {
|
|
199
|
+
return workflow.forms.find((f) => f.form_name === form_name)?.order ?? 0;
|
|
200
|
+
}
|
|
201
|
+
function commentText(value) {
|
|
202
|
+
if (typeof value === 'string')
|
|
203
|
+
return value;
|
|
204
|
+
return typeof value === 'number' || typeof value === 'boolean' ? String(value) : '';
|
|
205
|
+
}
|
|
206
|
+
function decide(workflow, state, decision, emit) {
|
|
207
|
+
const form = currentForm(workflow, state);
|
|
208
|
+
if (form?.kind !== 'approval')
|
|
209
|
+
return state;
|
|
210
|
+
const text = commentText(state.derived.data[form.form_name]?.comment);
|
|
211
|
+
if (approvalCommentRequired(form, decision) && isBlank(text)) {
|
|
212
|
+
return { ...state, approvalError: 'commentRequired' };
|
|
213
|
+
}
|
|
214
|
+
const data = merged(state.derived.data, form.form_name, { decision, comment: text });
|
|
215
|
+
const decided = withData(workflow, { ...state, approvalError: null }, data, emit);
|
|
216
|
+
const detail = {
|
|
217
|
+
form_name: form.form_name,
|
|
218
|
+
decision,
|
|
219
|
+
comment: text,
|
|
220
|
+
data: decided.derived.data,
|
|
221
|
+
};
|
|
222
|
+
if (decision === 'approved') {
|
|
223
|
+
emit({ name: 'baht-approve', detail });
|
|
224
|
+
return advance(workflow, decided, { decision, comment: text }, emit);
|
|
225
|
+
}
|
|
226
|
+
emit({ name: 'baht-reject', detail });
|
|
227
|
+
const onReject = form.approval?.on_reject ?? { action: 'end' };
|
|
228
|
+
const visible = visibleForms(workflow, decided.derived);
|
|
229
|
+
if (onReject.action === 'goto' && visible.some((f) => f.form_name === onReject.form)) {
|
|
230
|
+
return gotoForm(workflow, decided, onReject.form, emit);
|
|
231
|
+
}
|
|
232
|
+
emit({ name: 'baht-complete', detail: { data: decided.derived.data, status: 'rejected' } });
|
|
233
|
+
return { ...decided, ended: 'rejected' };
|
|
234
|
+
}
|
|
235
|
+
function gotoForm(workflow, state, form_name, emit) {
|
|
236
|
+
const idx = state.history.indexOf(form_name);
|
|
237
|
+
emit(stepChange(form_name, orderOf(workflow, form_name), 'back'));
|
|
238
|
+
return {
|
|
239
|
+
...state,
|
|
240
|
+
history: idx >= 0 ? state.history.slice(0, idx) : [],
|
|
241
|
+
current: form_name,
|
|
242
|
+
direction: 'back',
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function back(workflow, state, emit) {
|
|
246
|
+
const visible = new Set(visibleForms(workflow, state.derived).map((f) => f.form_name));
|
|
247
|
+
const history = [...state.history];
|
|
248
|
+
let prev = history.pop();
|
|
249
|
+
while (prev !== undefined && !visible.has(prev))
|
|
250
|
+
prev = history.pop();
|
|
251
|
+
if (prev === undefined)
|
|
252
|
+
return history.length === state.history.length ? state : { ...state, history };
|
|
253
|
+
emit(stepChange(prev, orderOf(workflow, prev), 'back'));
|
|
254
|
+
return { ...state, history, current: prev, direction: 'back', approvalError: null };
|
|
255
|
+
}
|
|
256
|
+
function gotoStart(workflow, state, emit) {
|
|
257
|
+
const first = visibleForms(workflow, state.derived)[0];
|
|
258
|
+
if (first && first.form_name !== state.current) {
|
|
259
|
+
emit(stepChange(first.form_name, first.order, 'back'));
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
...state,
|
|
263
|
+
history: [],
|
|
264
|
+
current: first?.form_name ?? null,
|
|
265
|
+
direction: 'back',
|
|
266
|
+
approvalError: null,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { DerivedFieldState, FormDefinition, Registry, ScriptContext, ScriptEvent, ScriptEventDetail, ScriptMessage } from '../types.js';
|
|
2
|
+
/** Script-set per-field overrides (only the keys a script touched). */
|
|
3
|
+
export type ScriptFieldState = Partial<Omit<DerivedFieldState, 'computed'>>;
|
|
4
|
+
/** Where a ScriptContext writes. Each method is called synchronously from a script. */
|
|
5
|
+
export interface ScriptSink {
|
|
6
|
+
getData(): Record<string, unknown>;
|
|
7
|
+
setValue(key: string, value: unknown): void;
|
|
8
|
+
setState(key: string, patch: ScriptFieldState): void;
|
|
9
|
+
resetState(key?: string): void;
|
|
10
|
+
setFieldMessage(key: string, message: ScriptMessage | null): void;
|
|
11
|
+
addFormMessage(message: ScriptMessage): void;
|
|
12
|
+
clearFormMessages(): void;
|
|
13
|
+
}
|
|
14
|
+
/** Bounds a setValue ping-pong between change scripts (like the engine's MAX_PASSES). */
|
|
15
|
+
export declare const MAX_SCRIPT_DEPTH = 20;
|
|
16
|
+
export declare function createScriptContext(form: FormDefinition, sink: ScriptSink): ScriptContext;
|
|
17
|
+
export interface RunScriptsOptions {
|
|
18
|
+
form: FormDefinition;
|
|
19
|
+
registry: Registry;
|
|
20
|
+
g: ScriptContext;
|
|
21
|
+
on: ScriptEvent;
|
|
22
|
+
/** `change` only: which field's scripts run. */
|
|
23
|
+
key?: string;
|
|
24
|
+
detail: Omit<ScriptEventDetail, 'on' | 'form_name' | 'key'>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Run every `scripts[]` entry matching `on` (and `key` for change) in array
|
|
28
|
+
* order. Unknown handler names warn once and are skipped; a throwing handler
|
|
29
|
+
* is logged and the rest still run. Returns false when a `submit` handler
|
|
30
|
+
* returned `false` (block), else true.
|
|
31
|
+
*/
|
|
32
|
+
export declare function runScripts(opts: RunScriptsOptions): boolean;
|
|
33
|
+
/** True when the form declares at least one script of this kind (cheap pre-check). */
|
|
34
|
+
export declare function hasScripts(form: FormDefinition | undefined, on: ScriptEvent, key?: string): boolean;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { defaultValue } from '../defaults.js';
|
|
2
|
+
export const MAX_SCRIPT_DEPTH = 20;
|
|
3
|
+
export function createScriptContext(form, sink) {
|
|
4
|
+
const field = (key) => form.fields.find((f) => f.key === key);
|
|
5
|
+
const known = (key, op) => {
|
|
6
|
+
if (field(key))
|
|
7
|
+
return true;
|
|
8
|
+
console.warn(`[bahtui] script ${op}("${key}"): no such field in "${form.form_name}"`);
|
|
9
|
+
return false;
|
|
10
|
+
};
|
|
11
|
+
return {
|
|
12
|
+
formName: form.form_name,
|
|
13
|
+
getValue: (key) => sink.getData()[key],
|
|
14
|
+
getData: () => sink.getData(),
|
|
15
|
+
getField: field,
|
|
16
|
+
setValue(key, value) {
|
|
17
|
+
if (known(key, 'setValue'))
|
|
18
|
+
sink.setValue(key, value);
|
|
19
|
+
},
|
|
20
|
+
clearValue(key) {
|
|
21
|
+
const f = field(key);
|
|
22
|
+
if (known(key, 'clearValue') && f)
|
|
23
|
+
sink.setValue(key, defaultValue(f));
|
|
24
|
+
},
|
|
25
|
+
setVisible(key, visible) {
|
|
26
|
+
if (known(key, 'setVisible'))
|
|
27
|
+
sink.setState(key, { visible });
|
|
28
|
+
},
|
|
29
|
+
setReadOnly(key, readonly) {
|
|
30
|
+
if (known(key, 'setReadOnly'))
|
|
31
|
+
sink.setState(key, { readonly });
|
|
32
|
+
},
|
|
33
|
+
setRequired(key, required) {
|
|
34
|
+
if (known(key, 'setRequired'))
|
|
35
|
+
sink.setState(key, { required });
|
|
36
|
+
},
|
|
37
|
+
setDisabled(key, disabled) {
|
|
38
|
+
if (known(key, 'setDisabled'))
|
|
39
|
+
sink.setState(key, { enabled: !disabled });
|
|
40
|
+
},
|
|
41
|
+
resetState: (key) => {
|
|
42
|
+
sink.resetState(key);
|
|
43
|
+
},
|
|
44
|
+
showFieldMsg(key, message, type = 'info') {
|
|
45
|
+
if (known(key, 'showFieldMsg'))
|
|
46
|
+
sink.setFieldMessage(key, { message, type });
|
|
47
|
+
},
|
|
48
|
+
hideFieldMsg: (key) => {
|
|
49
|
+
sink.setFieldMessage(key, null);
|
|
50
|
+
},
|
|
51
|
+
addErrorMessage: (message) => {
|
|
52
|
+
sink.addFormMessage({ message, type: 'error' });
|
|
53
|
+
},
|
|
54
|
+
addInfoMessage: (message) => {
|
|
55
|
+
sink.addFormMessage({ message, type: 'info' });
|
|
56
|
+
},
|
|
57
|
+
clearMessages: () => {
|
|
58
|
+
sink.clearFormMessages();
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const warnedHandlers = new WeakMap();
|
|
63
|
+
function warnUnknownHandler(form, name) {
|
|
64
|
+
let seen = warnedHandlers.get(form);
|
|
65
|
+
if (!seen)
|
|
66
|
+
warnedHandlers.set(form, (seen = new Set()));
|
|
67
|
+
if (seen.has(name))
|
|
68
|
+
return;
|
|
69
|
+
seen.add(name);
|
|
70
|
+
console.warn(`[bahtui] unknown script "${name}" — skipped`);
|
|
71
|
+
}
|
|
72
|
+
export function runScripts(opts) {
|
|
73
|
+
const { form, registry, g, on, key, detail } = opts;
|
|
74
|
+
let ok = true;
|
|
75
|
+
for (const spec of form.scripts ?? []) {
|
|
76
|
+
if (spec.on !== on)
|
|
77
|
+
continue;
|
|
78
|
+
if (on === 'change' && spec.field !== key)
|
|
79
|
+
continue;
|
|
80
|
+
const handler = registry.scripts?.[spec.handler];
|
|
81
|
+
if (!handler) {
|
|
82
|
+
warnUnknownHandler(form, spec.handler);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const out = handler(g, { ...detail, on, form_name: form.form_name, ...(key ? { key } : {}) });
|
|
87
|
+
if (on === 'submit' && out === false)
|
|
88
|
+
ok = false;
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
console.error(`[bahtui] script "${spec.handler}" threw`, err);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return ok;
|
|
95
|
+
}
|
|
96
|
+
export function hasScripts(form, on, key) {
|
|
97
|
+
return (form?.scripts ?? []).some((s) => s.on === on && (on !== 'change' || s.field === key));
|
|
98
|
+
}
|
package/dist/flags.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { FeatureFlags, FormDefinition, WorkflowDefinition } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Is a `flag` expression on (spec 01 §12)?
|
|
4
|
+
* - no flag -> always on
|
|
5
|
+
* - 'name' -> on only while flags.name is true
|
|
6
|
+
* - '!name' -> on only while flags.name is NOT true
|
|
7
|
+
* A missing key counts as false — new features stay dark until the flags
|
|
8
|
+
* file explicitly turns them on.
|
|
9
|
+
*/
|
|
10
|
+
export declare function flagEnabled(flag: string | undefined, flags: FeatureFlags): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Resolve every `flag` in a definition against the current flag values:
|
|
13
|
+
* flag-off fields/steps/rules come back REMOVED, as if never authored —
|
|
14
|
+
* they don't render, don't validate, and never reach the payload. Run the
|
|
15
|
+
* same call server-side (@20baht/validator re-exports it) with the same
|
|
16
|
+
* flags JSON so both sides agree. Returns the input untouched when nothing
|
|
17
|
+
* in it carries a flag.
|
|
18
|
+
*/
|
|
19
|
+
export declare function applyFlags<T extends FormDefinition | WorkflowDefinition>(schema: T, flags?: FeatureFlags): T;
|
package/dist/flags.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export function flagEnabled(flag, flags) {
|
|
2
|
+
if (!flag)
|
|
3
|
+
return true;
|
|
4
|
+
return flag.startsWith('!') ? flags[flag.slice(1)] !== true : flags[flag] === true;
|
|
5
|
+
}
|
|
6
|
+
function filterFields(fields, flags) {
|
|
7
|
+
return fields
|
|
8
|
+
.filter((f) => flagEnabled(f.flag, flags))
|
|
9
|
+
.map((f) => (f.fields ? { ...f, fields: filterFields(f.fields, flags) } : f));
|
|
10
|
+
}
|
|
11
|
+
function hasFlags(fields) {
|
|
12
|
+
return fields.some((f) => f.flag !== undefined || (f.fields ? hasFlags(f.fields) : false));
|
|
13
|
+
}
|
|
14
|
+
function applyToForm(form, flags) {
|
|
15
|
+
if (!hasFlags(form.fields))
|
|
16
|
+
return form;
|
|
17
|
+
const fields = filterFields(form.fields, flags);
|
|
18
|
+
const keys = new Set(fields.map((f) => f.key));
|
|
19
|
+
return {
|
|
20
|
+
...form,
|
|
21
|
+
fields,
|
|
22
|
+
...(form.views
|
|
23
|
+
? { views: form.views.map((v) => ({ ...v, fields: v.fields.filter((k) => keys.has(k)) })) }
|
|
24
|
+
: {}),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function isWorkflow(schema) {
|
|
28
|
+
return 'workflow_id' in schema;
|
|
29
|
+
}
|
|
30
|
+
export function applyFlags(schema, flags = {}) {
|
|
31
|
+
if (isWorkflow(schema)) {
|
|
32
|
+
const wf = schema;
|
|
33
|
+
const gated = wf.forms.some((f) => f.flag !== undefined || hasFlags(f.fields)) ||
|
|
34
|
+
wf.rules.some((r) => r.flag !== undefined) ||
|
|
35
|
+
(wf.transitions ?? []).some((tr) => tr.flag !== undefined);
|
|
36
|
+
if (!gated)
|
|
37
|
+
return schema;
|
|
38
|
+
const forms = wf.forms.filter((f) => flagEnabled(f.flag, flags));
|
|
39
|
+
const kept = new Set(forms.map((f) => f.form_name));
|
|
40
|
+
const edgeStands = (tr) => flagEnabled(tr.flag, flags) && kept.has(tr.from) && (tr.to === 'end' || kept.has(tr.to));
|
|
41
|
+
return {
|
|
42
|
+
...wf,
|
|
43
|
+
forms: forms.map((f) => applyToForm(f, flags)),
|
|
44
|
+
rules: wf.rules.filter((r) => flagEnabled(r.flag, flags)),
|
|
45
|
+
...(wf.transitions ? { transitions: wf.transitions.filter(edgeStands) } : {}),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return applyToForm(schema, flags);
|
|
49
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { FormDefinition, UploadedFile, WorkflowDefinition } from './types.js';
|
|
2
|
+
/** The option keys a choice field offers: the literal keys when known, else `string`. */
|
|
3
|
+
type OptionKey<F> = F extends {
|
|
4
|
+
readonly options_from: string;
|
|
5
|
+
} ? string : F extends {
|
|
6
|
+
readonly options: readonly (infer O)[];
|
|
7
|
+
} ? O extends {
|
|
8
|
+
readonly key: infer K extends string;
|
|
9
|
+
} ? K : string : string;
|
|
10
|
+
/** A file field's value: uploaded refs with an `uploader`, else the picked `File` handles. */
|
|
11
|
+
type FileValue<F> = F extends {
|
|
12
|
+
readonly uploader: string;
|
|
13
|
+
} ? UploadedFile : File;
|
|
14
|
+
type DateValue<F> = F extends {
|
|
15
|
+
readonly date_mode: 'range';
|
|
16
|
+
} ? [string, string] : F extends {
|
|
17
|
+
readonly date_mode: 'multiple';
|
|
18
|
+
} ? string[] : string;
|
|
19
|
+
/** The value one descriptor holds in `getData()` (its empty default included). */
|
|
20
|
+
type ValueOf<F> = F extends {
|
|
21
|
+
readonly type: 'text' | 'textarea' | 'markdown' | 'email' | 'password' | 'time' | 'reference';
|
|
22
|
+
} ? string | null : F extends {
|
|
23
|
+
readonly type: 'number' | 'currency' | 'range' | 'rating';
|
|
24
|
+
} ? number | null : F extends {
|
|
25
|
+
readonly type: 'checkbox' | 'toggle';
|
|
26
|
+
} ? boolean : F extends {
|
|
27
|
+
readonly type: 'dropdown' | 'radio';
|
|
28
|
+
} ? OptionKey<F> | null : F extends {
|
|
29
|
+
readonly type: 'multiselect';
|
|
30
|
+
} ? OptionKey<F>[] : F extends {
|
|
31
|
+
readonly type: 'tags';
|
|
32
|
+
} ? string[] : F extends {
|
|
33
|
+
readonly type: 'date';
|
|
34
|
+
} ? DateValue<F> | null : F extends {
|
|
35
|
+
readonly type: 'file';
|
|
36
|
+
} ? F extends {
|
|
37
|
+
readonly multiple: true;
|
|
38
|
+
} ? FileValue<F>[] : FileValue<F> | null : F extends {
|
|
39
|
+
readonly type: 'repeater';
|
|
40
|
+
readonly fields: readonly unknown[];
|
|
41
|
+
} ? ValuesOf<F['fields'][number]>[] : unknown;
|
|
42
|
+
/** Keyed values of a union of descriptors; static blocks (label, section) carry none. */
|
|
43
|
+
type ValuesOf<D> = string extends (D extends {
|
|
44
|
+
readonly key: infer K;
|
|
45
|
+
} ? K : never) ? Record<string, unknown> : {
|
|
46
|
+
-readonly [F in Exclude<D, {
|
|
47
|
+
readonly type: 'label' | 'section';
|
|
48
|
+
}> as F extends {
|
|
49
|
+
readonly key: infer K extends string;
|
|
50
|
+
} ? K : never]: ValueOf<F>;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The data a form holds, derived from its descriptors: what `<baht-form>.getData()` returns
|
|
54
|
+
* and what `validateSubmission(form, …).data` is. Needs literal descriptor types: declare the
|
|
55
|
+
* form with `defineForm({...})` (or `as const`); a form typed as plain `FormDefinition` gives
|
|
56
|
+
* `Record<string, unknown>`.
|
|
57
|
+
*
|
|
58
|
+
* text / textarea / markdown / email / password / reference → `string | null`;
|
|
59
|
+
* number / currency / range / rating → `number | null`; checkbox / toggle → `boolean`;
|
|
60
|
+
* dropdown / radio → the option keys `| null` (`string` with `options_from`); multiselect →
|
|
61
|
+
* option keys `[]`; tags → `string[]`; date → `string`, `[string, string]` (range) or
|
|
62
|
+
* `string[]` (multiple), `| null`; file → `UploadedFile` with an `uploader` (else `File`),
|
|
63
|
+
* `| null`, or an array with `multiple`; repeater → an array of its rows. Inside a workflow,
|
|
64
|
+
* a field a rule hides is absent from the data: read those keys as optional there.
|
|
65
|
+
*/
|
|
66
|
+
export type FormValues<F extends {
|
|
67
|
+
readonly fields: readonly unknown[];
|
|
68
|
+
}> = ValuesOf<F['fields'][number]>;
|
|
69
|
+
/**
|
|
70
|
+
* Returns `form` unchanged, typed with its literal keys, option keys and field types (a
|
|
71
|
+
* `const` type parameter), so `FormValues<typeof form>` is exact while `form` stays
|
|
72
|
+
* assignable to `FormDefinition`. `as const` alone makes the arrays readonly, which
|
|
73
|
+
* `FormDefinition` does not accept.
|
|
74
|
+
*/
|
|
75
|
+
export declare function defineForm<const F extends FormDefinition>(form: F): F;
|
|
76
|
+
/** `defineForm` for a workflow: `FormValues<(typeof wf)['forms'][0]>` is exact. */
|
|
77
|
+
export declare function defineWorkflow<const W extends WorkflowDefinition>(workflow: W): W;
|
|
78
|
+
export {};
|