@20baht/validator 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 +140 -2
- package/dist/common.d.ts +51 -0
- package/dist/common.js +29 -0
- package/dist/elysia.d.ts +217 -0
- package/dist/elysia.js +56 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +25 -0
- package/dist/schema.d.ts +12 -0
- package/dist/schema.js +548 -0
- package/dist/shape.d.ts +21 -0
- package/dist/shape.js +216 -0
- package/dist/submission.d.ts +28 -0
- package/dist/submission.js +358 -0
- package/dist/verify.d.ts +41 -0
- package/dist/verify.js +165 -0
- package/package.json +67 -4
package/dist/shape.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { normalizeTagsValue, parseIsoDate, parseIsoDateTime, ratingMax, rowSubFields, UNSAFE_KEYS, t, isUploadedFile, } from '@20baht/engine';
|
|
2
|
+
import { isRecord } from './common.js';
|
|
3
|
+
// ---- value-shape conformance -------------------------------------------------
|
|
4
|
+
/**
|
|
5
|
+
* Client/server parity gate: the UI can only emit values of the field's shape
|
|
6
|
+
* (a dropdown emits one of its option keys, a number input a number, a toggle
|
|
7
|
+
* a boolean). A direct API call can send anything — `{"$gt":""}` is not
|
|
8
|
+
* "empty", `123` skips the email regex — so wrong shapes are rejected before
|
|
9
|
+
* the authored validators run and never reach canonical data.
|
|
10
|
+
* Returns a message, or null when the shape is fine. Empty values pass —
|
|
11
|
+
* `required` owns those.
|
|
12
|
+
*/
|
|
13
|
+
function shapeMessage(ok) {
|
|
14
|
+
return ok ? null : t('pattern');
|
|
15
|
+
}
|
|
16
|
+
// value shape follows date_mode; every entry must be a real ISO calendar
|
|
17
|
+
// day. `enable_time` also accepts an ISO local datetime (what the
|
|
18
|
+
// picker actually emits) - a bare day is still fine on that field too,
|
|
19
|
+
// for callers that only ever cared about the date part.
|
|
20
|
+
function dateIssue(field, value) {
|
|
21
|
+
const isDay = (v) => parseIsoDate(v) !== null || (field.enable_time === true && parseIsoDateTime(v) !== null);
|
|
22
|
+
const mode = field.date_mode ?? 'single';
|
|
23
|
+
if (mode === 'range') {
|
|
24
|
+
return shapeMessage(Array.isArray(value) && value.length === 2 && value.every(isDay));
|
|
25
|
+
}
|
|
26
|
+
if (mode === 'multiple')
|
|
27
|
+
return shapeMessage(Array.isArray(value) && value.every(isDay));
|
|
28
|
+
return shapeMessage(isDay(value));
|
|
29
|
+
}
|
|
30
|
+
// A time of day, 24-hour, to the minute. Kept here rather than imported from the engine so this
|
|
31
|
+
// release still runs against a @20baht/ui 0.19.0 peer, whose engine has no time type.
|
|
32
|
+
const TIME_OF_DAY = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
|
|
33
|
+
export const isTimeOfDay = (v) => typeof v === 'string' && TIME_OF_DAY.test(v);
|
|
34
|
+
function choiceIssue(value, optionKeys) {
|
|
35
|
+
if (typeof value !== 'string')
|
|
36
|
+
return t('pattern');
|
|
37
|
+
return shapeMessage(!optionKeys || optionKeys.includes(value));
|
|
38
|
+
}
|
|
39
|
+
function multiChoiceIssue(value, optionKeys) {
|
|
40
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string'))
|
|
41
|
+
return t('pattern');
|
|
42
|
+
if (new Set(value).size !== value.length)
|
|
43
|
+
return t('pattern'); // a duplicate key is never canonical
|
|
44
|
+
return shapeMessage(!optionKeys || value.every((v) => optionKeys.includes(v)));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* tags: an array of strings — free text, unlike dropdown/multiselect. Only
|
|
48
|
+
* `allow_new: false` restricts chips to the static `options` list, matched
|
|
49
|
+
* case-insensitively against the (already-trimmed) tag; `options_from` is
|
|
50
|
+
* skipped exactly like a dropdown's dynamic options (`optionKeys === null`
|
|
51
|
+
* here too — the server cannot resolve it, so it trusts the client that did).
|
|
52
|
+
*/
|
|
53
|
+
function tagsShapeIssue(field, value, optionKeys) {
|
|
54
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string'))
|
|
55
|
+
return t('pattern');
|
|
56
|
+
if (field.allow_new === false && optionKeys) {
|
|
57
|
+
const allowed = new Set(optionKeys.map((k) => k.toLowerCase()));
|
|
58
|
+
// judged on the canonical value: a blank entry is dropped, not "not allowed"
|
|
59
|
+
const bad = normalizeTagsValue(value).some((v) => !allowed.has(v.toLowerCase()));
|
|
60
|
+
return shapeMessage(!bad);
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
function canonicalRef({ name, size, url, type }) {
|
|
65
|
+
return type === undefined ? { name, size, url } : { name, size, url, type };
|
|
66
|
+
}
|
|
67
|
+
function fileIssue(field, value) {
|
|
68
|
+
if (field.multiple)
|
|
69
|
+
return shapeMessage(Array.isArray(value) && value.every(isUploadedFile));
|
|
70
|
+
return shapeMessage(isUploadedFile(value));
|
|
71
|
+
}
|
|
72
|
+
function typeIssue(field, value) {
|
|
73
|
+
if (value === null || value === undefined)
|
|
74
|
+
return null;
|
|
75
|
+
// dynamic options (options_from) can't be checked without the registry fetch
|
|
76
|
+
const optionKeys = field.options_from ? null : field.options?.map((o) => o.key);
|
|
77
|
+
switch (field.type) {
|
|
78
|
+
case 'text':
|
|
79
|
+
case 'textarea':
|
|
80
|
+
case 'markdown':
|
|
81
|
+
case 'email':
|
|
82
|
+
case 'password':
|
|
83
|
+
case 'reference':
|
|
84
|
+
return shapeMessage(typeof value === 'string');
|
|
85
|
+
case 'date':
|
|
86
|
+
return dateIssue(field, value);
|
|
87
|
+
case 'time':
|
|
88
|
+
return shapeMessage(isTimeOfDay(value));
|
|
89
|
+
case 'number':
|
|
90
|
+
case 'currency':
|
|
91
|
+
case 'range':
|
|
92
|
+
return shapeMessage(typeof value === 'number' && Number.isFinite(value));
|
|
93
|
+
case 'checkbox':
|
|
94
|
+
case 'toggle':
|
|
95
|
+
return shapeMessage(typeof value === 'boolean');
|
|
96
|
+
case 'dropdown':
|
|
97
|
+
case 'radio':
|
|
98
|
+
return choiceIssue(value, optionKeys);
|
|
99
|
+
case 'multiselect':
|
|
100
|
+
return multiChoiceIssue(value, optionKeys);
|
|
101
|
+
case 'tags':
|
|
102
|
+
return tagsShapeIssue(field, value, optionKeys);
|
|
103
|
+
case 'rating':
|
|
104
|
+
return shapeMessage(typeof value === 'number' &&
|
|
105
|
+
Number.isInteger(value) &&
|
|
106
|
+
value >= 1 &&
|
|
107
|
+
value <= ratingMax(field));
|
|
108
|
+
case 'file':
|
|
109
|
+
return fileIssue(field, value);
|
|
110
|
+
case 'repeater':
|
|
111
|
+
return shapeMessage(Array.isArray(value));
|
|
112
|
+
case 'label':
|
|
113
|
+
case 'section':
|
|
114
|
+
return null; // static blocks carry no value
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Shape issues for one field, recursing one level into repeater rows. */
|
|
118
|
+
export function shapeIssues(field, value, ref) {
|
|
119
|
+
const message = typeIssue(field, value);
|
|
120
|
+
if (message !== null)
|
|
121
|
+
return [{ ref, message }];
|
|
122
|
+
const issues = [];
|
|
123
|
+
if (field.type === 'repeater' && Array.isArray(value)) {
|
|
124
|
+
value.forEach((row, i) => {
|
|
125
|
+
if (!isRecord(row)) {
|
|
126
|
+
issues.push({ ref: `${ref}[${i}]`, message: t('pattern') });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (Object.hasOwn(row, '__proto__')) {
|
|
130
|
+
issues.push({ ref: `${ref}[${i}]`, message: t('pattern') });
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
for (const sub of rowSubFields(field)) {
|
|
134
|
+
if (UNSAFE_KEYS.has(sub.key))
|
|
135
|
+
continue;
|
|
136
|
+
const v = Object.hasOwn(row, sub.key) ? row[sub.key] : undefined;
|
|
137
|
+
const m = typeIssue(sub, v);
|
|
138
|
+
if (m !== null)
|
|
139
|
+
issues.push({ ref: `${ref}[${i}].${sub.key}`, message: m });
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return issues;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* A tags value as the client emits it: trimmed, case-insensitive deduped
|
|
147
|
+
* (first spelling kept, a static option's key spelling when it matches one),
|
|
148
|
+
* `[]` for missing. A wrong-shaped value passes
|
|
149
|
+
* through untouched — `shapeIssues` owns rejecting it (and it runs AFTER
|
|
150
|
+
* rule evaluation, which also reads this).
|
|
151
|
+
*/
|
|
152
|
+
function canonicalTags(field, v) {
|
|
153
|
+
if (v === null || v === undefined)
|
|
154
|
+
return [];
|
|
155
|
+
if (!Array.isArray(v) || v.some((x) => typeof x !== 'string'))
|
|
156
|
+
return v;
|
|
157
|
+
// static options only: options_from can't be resolved here, so its
|
|
158
|
+
// suggestions keep the spelling the client sent (the client already mapped them)
|
|
159
|
+
return normalizeTagsValue(v, field.options_from ? undefined : field.options);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Canonical value for one field, as the client would emit it: `tags` via
|
|
163
|
+
* `canonicalTags` (the transform `validateField` applies internally, so the
|
|
164
|
+
* persisted `data` matches byte-for-byte); a file ref keeps only its ref
|
|
165
|
+
* fields; `-0` becomes `0`; a repeater row is rebuilt from its declared
|
|
166
|
+
* columns only (a repeater never nests, spec 01 §10). Every other value
|
|
167
|
+
* passes through. Runs after `shapeIssues`, or on rule input where a
|
|
168
|
+
* wrong-shaped value is left for `shapeIssues` to reject.
|
|
169
|
+
*/
|
|
170
|
+
export function normalizeCanonicalValue(field, raw) {
|
|
171
|
+
if (field.type === 'tags')
|
|
172
|
+
return canonicalTags(field, raw);
|
|
173
|
+
if (field.type === 'number' || field.type === 'currency')
|
|
174
|
+
return Object.is(raw, -0) ? 0 : raw;
|
|
175
|
+
if (field.type === 'file') {
|
|
176
|
+
if (isUploadedFile(raw))
|
|
177
|
+
return canonicalRef(raw);
|
|
178
|
+
return Array.isArray(raw) && raw.every(isUploadedFile) ? raw.map(canonicalRef) : raw;
|
|
179
|
+
}
|
|
180
|
+
if (field.type === 'repeater' && Array.isArray(raw)) {
|
|
181
|
+
return raw.map((row) => canonicalRow(field, row));
|
|
182
|
+
}
|
|
183
|
+
return raw;
|
|
184
|
+
}
|
|
185
|
+
function canonicalRow(field, row) {
|
|
186
|
+
if (!isRecord(row))
|
|
187
|
+
return row;
|
|
188
|
+
const next = {};
|
|
189
|
+
for (const sub of rowSubFields(field)) {
|
|
190
|
+
if (UNSAFE_KEYS.has(sub.key) || !Object.hasOwn(row, sub.key))
|
|
191
|
+
continue;
|
|
192
|
+
next[sub.key] = normalizeCanonicalValue(sub, row[sub.key]);
|
|
193
|
+
}
|
|
194
|
+
return next;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Copy of the workflow input with every tags value (and tags column)
|
|
198
|
+
* canonical — rules and transitions must read tags the way the client emits
|
|
199
|
+
* them, else `[" urgent "]` dodges a `contains "urgent"` rule.
|
|
200
|
+
*/
|
|
201
|
+
export function withNormalizedTags(workflow, input) {
|
|
202
|
+
const out = { ...input };
|
|
203
|
+
for (const form of workflow.forms) {
|
|
204
|
+
const values = Object.hasOwn(input, form.form_name) ? input[form.form_name] : undefined;
|
|
205
|
+
if (!isRecord(values))
|
|
206
|
+
continue;
|
|
207
|
+
const next = { ...values };
|
|
208
|
+
for (const field of form.fields) {
|
|
209
|
+
if (Object.hasOwn(next, field.key)) {
|
|
210
|
+
next[field.key] = normalizeCanonicalValue(field, next[field.key]);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
out[form.form_name] = next;
|
|
214
|
+
}
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type FormDefinition, type Locale, type Registry, type WorkflowDefinition } from '@20baht/engine';
|
|
2
|
+
import { type SchemaDefinition, type ValidateOptions, type ValidationResult } from './common.js';
|
|
3
|
+
/**
|
|
4
|
+
* Validate a standalone form submission — mirrors `<baht-form>.validate()`
|
|
5
|
+
* with no derived field states: every non-label field, missing values fall
|
|
6
|
+
* back to the field default before checking. `form.views` are ignored here:
|
|
7
|
+
* views are client-side display only, the server always validates the full
|
|
8
|
+
* form (a view can never weaken a validation rule).
|
|
9
|
+
*/
|
|
10
|
+
export declare function validateFormData(form: FormDefinition, input: unknown, registry?: Registry, locale?: Locale, options?: ValidateOptions): ValidationResult;
|
|
11
|
+
/**
|
|
12
|
+
* Validate a whole workflow submission — mirrors what `<baht-workflow>`
|
|
13
|
+
* enforces across its steps: rules are evaluated first (`evaluate`), invisible
|
|
14
|
+
* forms/fields are excluded, rule-derived `required` overrides the descriptor,
|
|
15
|
+
* approval steps demand a decision plus their comment policy, and a rejected
|
|
16
|
+
* approval with `on_reject: end` (the default) stops validation there — the
|
|
17
|
+
* client fires `baht-complete { status: 'rejected' }` immediately, so later
|
|
18
|
+
* forms are never visited.
|
|
19
|
+
*/
|
|
20
|
+
export declare function validateWorkflowData(workflow: WorkflowDefinition, input: unknown, registry?: Registry, locale?: Locale, options?: ValidateOptions): ValidationResult;
|
|
21
|
+
/**
|
|
22
|
+
* Validate a submission body's `data` against whichever schema kind `id`
|
|
23
|
+
* resolved to. This is the single server entry point:
|
|
24
|
+
*
|
|
25
|
+
* const schema = store.get(body.id);
|
|
26
|
+
* const result = validateSubmission(schema, body.data);
|
|
27
|
+
*/
|
|
28
|
+
export declare function validateSubmission(schema: SchemaDefinition, data: unknown, registry?: Registry, locale?: Locale, options?: ValidateOptions): ValidationResult;
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { approvalCommentRequired, approvalFields, defaultValue, evaluate, hasScripts, UNSAFE_KEYS, t, isBlank, submitScriptErrors, validateField, validateShownField, visibleForms, walkPath, } from '@20baht/engine';
|
|
2
|
+
import { isFormDefinition, isRecord, isStatic, isWorkflowDefinition, ownEntry, sorted, withLocale, } from './common.js';
|
|
3
|
+
import { normalizeCanonicalValue, shapeIssues, withNormalizedTags } from './shape.js';
|
|
4
|
+
// ---- form validation -----------------------------------------------------------
|
|
5
|
+
/**
|
|
6
|
+
* Validate a standalone form submission — mirrors `<baht-form>.validate()`
|
|
7
|
+
* with no derived field states: every non-label field, missing values fall
|
|
8
|
+
* back to the field default before checking. `form.views` are ignored here:
|
|
9
|
+
* views are client-side display only, the server always validates the full
|
|
10
|
+
* form (a view can never weaken a validation rule).
|
|
11
|
+
*/
|
|
12
|
+
export function validateFormData(form, input, registry, locale, options) {
|
|
13
|
+
const reg = serverRegistry([form], registry, options);
|
|
14
|
+
return withLocale(locale, () => formDataResult(form, input, reg));
|
|
15
|
+
}
|
|
16
|
+
function guardedScript(name, handler) {
|
|
17
|
+
return (g, detail) => {
|
|
18
|
+
try {
|
|
19
|
+
return handler(g, detail);
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
console.error(`[@20baht/validator] submit script "${name}" threw`, err);
|
|
23
|
+
g.addErrorMessage(`submit script "${name}" failed`);
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The registry the engine sees. In strict mode every `custom` validator and
|
|
30
|
+
* `submit` script the schema names resolves to something that fails closed:
|
|
31
|
+
* the caller's own entry (scripts wrapped so a throw is an issue), else a stub
|
|
32
|
+
* that reports the missing name. Own entries only, so `toString` never
|
|
33
|
+
* resolves through Object.prototype.
|
|
34
|
+
*/
|
|
35
|
+
function serverRegistry(forms, registry, options) {
|
|
36
|
+
if (options?.strict === false)
|
|
37
|
+
return registry;
|
|
38
|
+
const validators = new Map();
|
|
39
|
+
const scripts = new Map();
|
|
40
|
+
for (const form of forms) {
|
|
41
|
+
const fields = form.fields.flatMap((f) => [
|
|
42
|
+
f,
|
|
43
|
+
...(f.type === 'repeater' ? (f.fields ?? []) : []),
|
|
44
|
+
]);
|
|
45
|
+
for (const spec of fields.flatMap((f) => f.validators ?? [])) {
|
|
46
|
+
if (spec.type !== 'custom')
|
|
47
|
+
continue;
|
|
48
|
+
const name = spec.fn ?? '';
|
|
49
|
+
validators.set(name, ownEntry(registry?.validators, name) ?? (() => `unknown custom validator "${name}"`));
|
|
50
|
+
}
|
|
51
|
+
for (const spec of form.scripts ?? []) {
|
|
52
|
+
if (spec.on !== 'submit')
|
|
53
|
+
continue;
|
|
54
|
+
const name = spec.handler;
|
|
55
|
+
const handler = ownEntry(registry?.scripts, name);
|
|
56
|
+
scripts.set(name, handler
|
|
57
|
+
? guardedScript(name, handler)
|
|
58
|
+
: (g) => {
|
|
59
|
+
g.addErrorMessage(`submit script "${name}" is not registered`);
|
|
60
|
+
return false;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
...registry,
|
|
66
|
+
validators: Object.fromEntries(validators),
|
|
67
|
+
scripts: Object.fromEntries(scripts),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* One field's shape check + canonical value + declarative/custom validators.
|
|
72
|
+
* Junk (wrong shape) never reaches canonical data — it resets to the
|
|
73
|
+
* descriptor default.
|
|
74
|
+
*/
|
|
75
|
+
function validatedFieldData(field, raw, registry, data) {
|
|
76
|
+
const shape = shapeIssues(field, raw, field.key);
|
|
77
|
+
if (shape.length > 0)
|
|
78
|
+
return { value: defaultValue(field), issues: shape };
|
|
79
|
+
const value = normalizeCanonicalValue(field, raw);
|
|
80
|
+
const issues = validateField(field, value, registry, data).map((err) => ({
|
|
81
|
+
ref: err.key,
|
|
82
|
+
message: err.message,
|
|
83
|
+
}));
|
|
84
|
+
return { value, issues };
|
|
85
|
+
}
|
|
86
|
+
function formDataResult(form, input, registry) {
|
|
87
|
+
if (!isRecord(input)) {
|
|
88
|
+
return { valid: false, issues: [{ ref: '$', message: 'data must be an object' }], data: {} };
|
|
89
|
+
}
|
|
90
|
+
const issues = [];
|
|
91
|
+
const fields = [];
|
|
92
|
+
for (const f of sorted(form.fields)) {
|
|
93
|
+
if (isStatic(f))
|
|
94
|
+
continue;
|
|
95
|
+
if (UNSAFE_KEYS.has(f.key)) {
|
|
96
|
+
issues.push({ ref: f.key, message: 'unsafe field key' });
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
fields.push(f);
|
|
100
|
+
}
|
|
101
|
+
// canonical data first, so compare validators see every sibling.
|
|
102
|
+
// Own-property reads only: `'toString' in input` is true via the prototype
|
|
103
|
+
// chain and would smuggle the inherited function in as the value.
|
|
104
|
+
const data = {};
|
|
105
|
+
for (const field of fields) {
|
|
106
|
+
data[field.key] = Object.hasOwn(input, field.key) ? input[field.key] : defaultValue(field);
|
|
107
|
+
}
|
|
108
|
+
for (const field of fields) {
|
|
109
|
+
const { value, issues: fieldIssues } = validatedFieldData(field, data[field.key], registry, data);
|
|
110
|
+
data[field.key] = value;
|
|
111
|
+
issues.push(...fieldIssues);
|
|
112
|
+
}
|
|
113
|
+
issues.push(...submitScriptIssues(form, data, registry));
|
|
114
|
+
return { valid: issues.length === 0, issues, data };
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Re-run the form's `submit` client scripts (spec 01 §14) headlessly — the
|
|
118
|
+
* same gate `<baht-form>.validate()` applies after its validators. `load` and
|
|
119
|
+
* `change` scripts are UI-only and never run here. `g.setValue()` writes into
|
|
120
|
+
* canonical `data`; UI state/message calls are accepted and discarded, except
|
|
121
|
+
* `addErrorMessage()`, which becomes an issue on `$` (prefixed by the form name
|
|
122
|
+
* inside a workflow). A handler returning `false` with no message falls back to
|
|
123
|
+
* the catalog's `scriptBlocked`.
|
|
124
|
+
*/
|
|
125
|
+
function submitScriptIssues(form, data, registry, refPrefix = '') {
|
|
126
|
+
const errors = submitScriptErrors(form, registry, {
|
|
127
|
+
getData: () => data,
|
|
128
|
+
setValue: (key, value) => {
|
|
129
|
+
data[key] = value;
|
|
130
|
+
},
|
|
131
|
+
setState: () => undefined,
|
|
132
|
+
resetState: () => undefined,
|
|
133
|
+
setFieldMessage: () => undefined,
|
|
134
|
+
addFormMessage: () => undefined,
|
|
135
|
+
clearFormMessages: () => undefined,
|
|
136
|
+
});
|
|
137
|
+
return errors.map((err) => ({ ref: `${refPrefix}$`, message: err.message }));
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Validate a whole workflow submission — mirrors what `<baht-workflow>`
|
|
141
|
+
* enforces across its steps: rules are evaluated first (`evaluate`), invisible
|
|
142
|
+
* forms/fields are excluded, rule-derived `required` overrides the descriptor,
|
|
143
|
+
* approval steps demand a decision plus their comment policy, and a rejected
|
|
144
|
+
* approval with `on_reject: end` (the default) stops validation there — the
|
|
145
|
+
* client fires `baht-complete { status: 'rejected' }` immediately, so later
|
|
146
|
+
* forms are never visited.
|
|
147
|
+
*/
|
|
148
|
+
export function validateWorkflowData(workflow, input, registry, locale, options) {
|
|
149
|
+
const reg = serverRegistry(workflow.forms, registry, options);
|
|
150
|
+
const form = options?.form;
|
|
151
|
+
if (form !== undefined) {
|
|
152
|
+
return withLocale(locale, () => oneFormResult(workflow, form, input, reg, options?.context));
|
|
153
|
+
}
|
|
154
|
+
return withLocale(locale, () => workflowDataResult(workflow, input, reg));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* `validateWorkflowData(…, { form, context })`: the body of one form, wrapped as the workflow
|
|
158
|
+
* input beside the other forms' `context`, its issues and data unwrapped again. Issues on other
|
|
159
|
+
* forms are dropped (they are not this step's to fix); a workflow-level issue (rules that never
|
|
160
|
+
* settle) lands on `$`.
|
|
161
|
+
*/
|
|
162
|
+
function oneFormResult(workflow, formName, input, registry, context) {
|
|
163
|
+
if (!isRecord(input)) {
|
|
164
|
+
return { valid: false, issues: [{ ref: '$', message: 'data must be an object' }], data: {} };
|
|
165
|
+
}
|
|
166
|
+
if (context !== undefined && !isRecord(context)) {
|
|
167
|
+
return { valid: false, issues: [{ ref: '$', message: 'context must be an object' }], data: {} };
|
|
168
|
+
}
|
|
169
|
+
if (!workflow.forms.some((f) => f.form_name === formName)) {
|
|
170
|
+
return {
|
|
171
|
+
valid: false,
|
|
172
|
+
issues: [{ ref: '$', message: `unknown form ${JSON.stringify(formName)}` }],
|
|
173
|
+
data: {},
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const result = workflowDataResult(workflow, { ...context, [formName]: input }, registry);
|
|
177
|
+
const prefix = `${formName}.`;
|
|
178
|
+
const others = workflow.forms
|
|
179
|
+
.filter((f) => f.form_name !== formName)
|
|
180
|
+
.map((f) => `${f.form_name}.`);
|
|
181
|
+
const issues = [];
|
|
182
|
+
for (const issue of result.issues) {
|
|
183
|
+
if (issue.ref.startsWith(prefix))
|
|
184
|
+
issues.push({ ...issue, ref: issue.ref.slice(prefix.length) });
|
|
185
|
+
else if (!others.some((p) => issue.ref.startsWith(p)))
|
|
186
|
+
issues.push({ ...issue, ref: '$' });
|
|
187
|
+
}
|
|
188
|
+
const data = result.data[formName] ?? {};
|
|
189
|
+
return { valid: issues.length === 0, issues, data };
|
|
190
|
+
}
|
|
191
|
+
/** Early-out for input that is not `{ formName: {…} }`, else null. */
|
|
192
|
+
function workflowInputRejection(input) {
|
|
193
|
+
if (!isRecord(input)) {
|
|
194
|
+
return { valid: false, issues: [{ ref: '$', message: 'data must be an object' }], data: {} };
|
|
195
|
+
}
|
|
196
|
+
for (const [name, values] of Object.entries(input)) {
|
|
197
|
+
if (values !== undefined && !isRecord(values)) {
|
|
198
|
+
return {
|
|
199
|
+
valid: false,
|
|
200
|
+
issues: [{ ref: name, message: 'form data must be an object' }],
|
|
201
|
+
data: {},
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Forms in the order the client visits them (path order in graph mode,
|
|
209
|
+
* ascending `order` among visible forms in linear mode), cut after a rejected
|
|
210
|
+
* end-on-reject approval: everything after it is unvisited on the client and
|
|
211
|
+
* must not be demanded here. Whatever the request sent for those forms is
|
|
212
|
+
* dropped from `derived.data`, since nothing validates it.
|
|
213
|
+
*/
|
|
214
|
+
function visitedForms(workflow, derived, pathList) {
|
|
215
|
+
const byName = new Map(workflow.forms.map((f) => [f.form_name, f]));
|
|
216
|
+
const ordered = pathList
|
|
217
|
+
? pathList.map((n) => byName.get(n)).filter((f) => f !== undefined)
|
|
218
|
+
: visibleForms(workflow, derived);
|
|
219
|
+
const cut = ordered.findIndex((form) => {
|
|
220
|
+
if (form.kind !== 'approval')
|
|
221
|
+
return false;
|
|
222
|
+
const on_reject = form.approval?.on_reject ?? { action: 'end' };
|
|
223
|
+
return on_reject.action === 'end' && derived.data[form.form_name]?.decision === 'rejected';
|
|
224
|
+
});
|
|
225
|
+
if (cut < 0)
|
|
226
|
+
return ordered;
|
|
227
|
+
for (const form of ordered.slice(cut + 1)) {
|
|
228
|
+
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete -- unvisited forms are not validated, so their data must not reach canonical data
|
|
229
|
+
delete derived.data[form.form_name];
|
|
230
|
+
}
|
|
231
|
+
return ordered.slice(0, cut + 1);
|
|
232
|
+
}
|
|
233
|
+
function workflowFieldIssues(form, field, derived, registry) {
|
|
234
|
+
const ref = `${form.form_name}.${field.key}`;
|
|
235
|
+
if (UNSAFE_KEYS.has(field.key))
|
|
236
|
+
return [{ ref, message: 'unsafe field key' }];
|
|
237
|
+
const state = derived.fields[ref];
|
|
238
|
+
if (state && !state.visible)
|
|
239
|
+
return []; // hidden fields excluded (spec 02 §5)
|
|
240
|
+
const formData = derived.data[form.form_name] ?? {};
|
|
241
|
+
const shape = shapeIssues(field, formData[field.key], ref);
|
|
242
|
+
if (shape.length > 0) {
|
|
243
|
+
formData[field.key] = defaultValue(field); // junk never reaches canonical data
|
|
244
|
+
return shape;
|
|
245
|
+
}
|
|
246
|
+
formData[field.key] = normalizeCanonicalValue(field, formData[field.key]);
|
|
247
|
+
const rowStates = field.type === 'repeater' ? rowStatesOf(form, field, derived) : undefined;
|
|
248
|
+
return validateShownField(field, state, formData[field.key], registry, formData, rowStates).map((err) => ({ ref: issueRef(form, field, err.key), message: err.message }));
|
|
249
|
+
}
|
|
250
|
+
/** A repeater's row errors keep their `key[i].sub` ref (spec 01 §10); the rest sit on the field. */
|
|
251
|
+
function issueRef(form, field, errKey) {
|
|
252
|
+
return errKey.startsWith(`${field.key}[`)
|
|
253
|
+
? `${form.form_name}.${errKey}`
|
|
254
|
+
: `${form.form_name}.${field.key}`;
|
|
255
|
+
}
|
|
256
|
+
/** The rule-derived states of one repeater's row sub-fields, keyed `key[i].sub` (spec 02 §2a). */
|
|
257
|
+
function rowStatesOf(form, field, derived) {
|
|
258
|
+
const prefix = `${form.form_name}.${field.key}[`;
|
|
259
|
+
const states = {};
|
|
260
|
+
for (const [ref, state] of Object.entries(derived.fields)) {
|
|
261
|
+
if (ref.startsWith(prefix))
|
|
262
|
+
states[ref.slice(form.form_name.length + 1)] = state;
|
|
263
|
+
}
|
|
264
|
+
return states;
|
|
265
|
+
}
|
|
266
|
+
function formFieldIssues(form, derived, registry) {
|
|
267
|
+
const issues = [];
|
|
268
|
+
for (const field of sorted([...form.fields, ...approvalFields(form)])) {
|
|
269
|
+
if (isStatic(field))
|
|
270
|
+
continue;
|
|
271
|
+
issues.push(...workflowFieldIssues(form, field, derived, registry));
|
|
272
|
+
}
|
|
273
|
+
return issues;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Graph mode (spec 03 §6): only the forms on the path this data takes
|
|
277
|
+
* validate; off-path branches are as good as skipped, their data dropped.
|
|
278
|
+
* Returns the path, or null in linear mode.
|
|
279
|
+
*/
|
|
280
|
+
/** The forms `derived` left visible: what `walkPath` would work out by evaluating again. */
|
|
281
|
+
function visibleFormNames(workflow, derived) {
|
|
282
|
+
return new Set(visibleForms(workflow, derived).map((f) => f.form_name));
|
|
283
|
+
}
|
|
284
|
+
function pruneOffPath(workflow, derived) {
|
|
285
|
+
const pathList = workflow.transitions && workflow.transitions.length > 0
|
|
286
|
+
? walkPath(workflow, derived.data, visibleFormNames(workflow, derived))
|
|
287
|
+
: null;
|
|
288
|
+
if (pathList) {
|
|
289
|
+
const path = new Set(pathList);
|
|
290
|
+
for (const name of Object.keys(derived.data)) {
|
|
291
|
+
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete -- pruning off-path forms from a plain-object map keyed by form_name
|
|
292
|
+
if (!path.has(name))
|
|
293
|
+
delete derived.data[name];
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return pathList;
|
|
297
|
+
}
|
|
298
|
+
function workflowDataResult(workflow, input, registry) {
|
|
299
|
+
const rejection = workflowInputRejection(input);
|
|
300
|
+
if (rejection)
|
|
301
|
+
return rejection;
|
|
302
|
+
const derived = evaluate(workflow, withNormalizedTags(workflow, input));
|
|
303
|
+
// Schema-integrity errors (unknown rule targets) belong at parseSchema /
|
|
304
|
+
// store time — the client never surfaces them, so failing submissions on
|
|
305
|
+
// them would reject data the client happily emits. Only data-dependent
|
|
306
|
+
// errors (rule non-convergence) gate the submission.
|
|
307
|
+
const issues = derived.errors
|
|
308
|
+
.filter((e) => e.kind === 'data')
|
|
309
|
+
.map((e) => ({ ref: e.ref, message: e.message }));
|
|
310
|
+
const pathList = pruneOffPath(workflow, derived);
|
|
311
|
+
for (const form of visitedForms(workflow, derived, pathList)) {
|
|
312
|
+
issues.push(...formFieldIssues(form, derived, registry));
|
|
313
|
+
if (form.kind === 'approval') {
|
|
314
|
+
issues.push(...approvalIssues(form, derived.data));
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (hasScripts(form, 'submit')) {
|
|
318
|
+
const formData = (derived.data[form.form_name] ??= {});
|
|
319
|
+
issues.push(...submitScriptIssues(form, formData, registry, `${form.form_name}.`));
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return { valid: issues.length === 0, issues, data: derived.data };
|
|
323
|
+
}
|
|
324
|
+
/** Approval step checks: the gate the client's runtime applies to a decision (`approvalCommentRequired`). */
|
|
325
|
+
function approvalIssues(form, data) {
|
|
326
|
+
const issues = [];
|
|
327
|
+
const values = data[form.form_name] ?? {};
|
|
328
|
+
const decision = values.decision;
|
|
329
|
+
if (decision !== 'approved' && decision !== 'rejected') {
|
|
330
|
+
issues.push({ ref: `${form.form_name}.decision`, message: t('decisionRequired') });
|
|
331
|
+
}
|
|
332
|
+
const commentRequired = approvalCommentRequired(form, decision === 'approved' || decision === 'rejected' ? decision : undefined);
|
|
333
|
+
// the comment's shape was already checked; a wrong shape was reset to null
|
|
334
|
+
const comment = typeof values.comment === 'string' ? values.comment : '';
|
|
335
|
+
if (commentRequired && isBlank(comment)) {
|
|
336
|
+
issues.push({ ref: `${form.form_name}.comment`, message: t('commentRequired') });
|
|
337
|
+
}
|
|
338
|
+
return issues;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Validate a submission body's `data` against whichever schema kind `id`
|
|
342
|
+
* resolved to. This is the single server entry point:
|
|
343
|
+
*
|
|
344
|
+
* const schema = store.get(body.id);
|
|
345
|
+
* const result = validateSubmission(schema, body.data);
|
|
346
|
+
*/
|
|
347
|
+
export function validateSubmission(schema, data, registry, locale, options) {
|
|
348
|
+
if (isWorkflowDefinition(schema)) {
|
|
349
|
+
return validateWorkflowData(schema, data, registry, locale, options);
|
|
350
|
+
}
|
|
351
|
+
if (isFormDefinition(schema))
|
|
352
|
+
return validateFormData(schema, data, registry, locale, options);
|
|
353
|
+
return {
|
|
354
|
+
valid: false,
|
|
355
|
+
issues: [{ ref: '$', message: 'unrecognized schema: neither a form nor a workflow' }],
|
|
356
|
+
data: {},
|
|
357
|
+
};
|
|
358
|
+
}
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Locale, type Registry } from '@20baht/engine';
|
|
2
|
+
import { type SchemaDefinition, type ValidationIssue } from './common.js';
|
|
3
|
+
/** What the async checks (`verifyReferences`, `verifyOptions`) accept beside the data. */
|
|
4
|
+
export interface VerifyOptions {
|
|
5
|
+
/** Workflows only: `data` is the flat body of this one form; refs are field keys (VAL-2). */
|
|
6
|
+
form?: string;
|
|
7
|
+
/** Locale of the issue messages. Unset: the engine's catalog as it is when the call starts. */
|
|
8
|
+
locale?: Locale;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Do the records picked in `reference` fields exist? `validateSubmission` only checks that a
|
|
12
|
+
* reference value is an id string — existence needs the lookup, which is async. Call this
|
|
13
|
+
* after it, with the same registry the client uses:
|
|
14
|
+
*
|
|
15
|
+
* const result = validateSubmission(schema, body.data, registry);
|
|
16
|
+
* const missing = await verifyReferences(schema, result.data, registry);
|
|
17
|
+
*
|
|
18
|
+
* Each distinct `lookup + id` is resolved once (in parallel). An id `resolve` returns `null`
|
|
19
|
+
* for is an issue on that field ("Record not found"); a lookup the schema names but the
|
|
20
|
+
* registry lacks is an issue too; a lookup without `resolve` is trusted. Workflow refs are
|
|
21
|
+
* `form_name.key` (field keys with `{ form }`). Top-level fields only (reference fields
|
|
22
|
+
* inside repeater rows are not resolved).
|
|
23
|
+
*/
|
|
24
|
+
export declare function verifyReferences(schema: SchemaDefinition, data: unknown, registry?: Registry, options?: VerifyOptions): Promise<ValidationIssue[]>;
|
|
25
|
+
/**
|
|
26
|
+
* Are the values of `options_from` fields among the options the fetcher offers?
|
|
27
|
+
* `validateSubmission` cannot tell (the options are async), so it trusts the client for
|
|
28
|
+
* them; call this after it, with the same registry the client uses:
|
|
29
|
+
*
|
|
30
|
+
* const result = validateSubmission(schema, body.data, registry);
|
|
31
|
+
* const issues = await verifyOptions(schema, result.data, registry);
|
|
32
|
+
*
|
|
33
|
+
* Each source is resolved once per form, as `registry.options[name](data)` with that form's
|
|
34
|
+
* data, exactly as `<baht-form>` calls it. Checked: `dropdown`, `radio`, `multiselect`, and
|
|
35
|
+
* `tags` with `allow_new: false` (case-insensitive), top-level fields and repeater columns
|
|
36
|
+
* (refs `key[i].sub`; a column's fetcher sees the form's data, as on the client). A key the
|
|
37
|
+
* fetcher does not offer is an issue with the static-dropdown message; a source the registry
|
|
38
|
+
* lacks, or a fetcher that throws or rejects, is an issue too (fail closed). Workflow refs are
|
|
39
|
+
* `form_name.key` (field keys with `{ form }`).
|
|
40
|
+
*/
|
|
41
|
+
export declare function verifyOptions(schema: SchemaDefinition, data: unknown, registry?: Registry, options?: VerifyOptions): Promise<ValidationIssue[]>;
|