@20baht/validator 0.0.0-stage → 0.1.0
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 +56 -0
- package/dist/common.js +45 -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 +64 -4
package/dist/schema.js
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
import { approvalFields, conditionRowRefs, parseDisabledEntry, parseIsoDate, parseRowRef, rangeBounds, rowSubFields, UNSAFE_KEYS, isUnsafePattern, normalizeLegacySchema, } from '@20baht/engine';
|
|
2
|
+
import { isFormDefinition, isRecord, isStatic, isWorkflowDefinition, } from './common.js';
|
|
3
|
+
import { isTimeOfDay } from './shape.js';
|
|
4
|
+
const DATE_MODES = new Set(['single', 'range', 'multiple']);
|
|
5
|
+
/** Every `FieldType`; `satisfies` rejects a name that is not one, the check below a type left out. */
|
|
6
|
+
const FIELD_TYPE_LIST = [
|
|
7
|
+
'text',
|
|
8
|
+
'textarea',
|
|
9
|
+
'markdown',
|
|
10
|
+
'number',
|
|
11
|
+
'currency',
|
|
12
|
+
'email',
|
|
13
|
+
'password',
|
|
14
|
+
'dropdown',
|
|
15
|
+
'multiselect',
|
|
16
|
+
'checkbox',
|
|
17
|
+
'radio',
|
|
18
|
+
'toggle',
|
|
19
|
+
'date',
|
|
20
|
+
'time',
|
|
21
|
+
'file',
|
|
22
|
+
'label',
|
|
23
|
+
'section',
|
|
24
|
+
'repeater',
|
|
25
|
+
'tags',
|
|
26
|
+
'rating',
|
|
27
|
+
'range',
|
|
28
|
+
'reference',
|
|
29
|
+
];
|
|
30
|
+
const FIELD_TYPES = new Set(FIELD_TYPE_LIST);
|
|
31
|
+
/** Fails to compile when the engine gains a field type this list does not have. */
|
|
32
|
+
const _everyFieldTypeListed = true;
|
|
33
|
+
void _everyFieldTypeListed;
|
|
34
|
+
/**
|
|
35
|
+
* Structural gate for storing builder output — the same checks the builder's
|
|
36
|
+
* Import applies, so the server only ever stores schemas the client could
|
|
37
|
+
* render. Throws with a human-readable message on bad input.
|
|
38
|
+
*
|
|
39
|
+
* Beyond shape it validates referential integrity (rule targets, condition
|
|
40
|
+
* refs, transition endpoints, on_reject.goto) and compiles every `pattern`
|
|
41
|
+
* validator, so authoring defects surface at store time — not as a 500 or a
|
|
42
|
+
* submission that can never pass.
|
|
43
|
+
*/
|
|
44
|
+
export function parseSchema(json) {
|
|
45
|
+
const raw = typeof json === 'string' ? JSON.parse(json) : json;
|
|
46
|
+
if (!isRecord(raw))
|
|
47
|
+
throw new Error('not an object');
|
|
48
|
+
// pre-0.3 JSON (formId / field_data / maxLength …) still parses — keys are
|
|
49
|
+
// migrated forward; the returned schema is always the current spelling.
|
|
50
|
+
const { schema: parsed, renamed } = normalizeLegacySchema(raw);
|
|
51
|
+
if (renamed.length > 0) {
|
|
52
|
+
console.warn(`[@20baht/validator] legacy camelCase schema keys migrated (${renamed.length}): ${renamed.slice(0, 5).join(', ')}${renamed.length > 5 ? ', …' : ''} — re-save the schema with snake_case keys.`);
|
|
53
|
+
}
|
|
54
|
+
if (isWorkflowDefinition(parsed)) {
|
|
55
|
+
assertValidWorkflow(parsed);
|
|
56
|
+
return parsed;
|
|
57
|
+
}
|
|
58
|
+
if (isFormDefinition(parsed)) {
|
|
59
|
+
assertFormParts(parsed);
|
|
60
|
+
return parsed;
|
|
61
|
+
}
|
|
62
|
+
throw new Error('missing workflow_id/forms/rules (workflow) or form_id/form_name/fields (form)');
|
|
63
|
+
}
|
|
64
|
+
function assertFormParts(form) {
|
|
65
|
+
assertValidFields(form);
|
|
66
|
+
assertValidViews(form);
|
|
67
|
+
assertValidRepeaters(form);
|
|
68
|
+
assertValidScripts(form);
|
|
69
|
+
}
|
|
70
|
+
function assertWorkflowForm(f) {
|
|
71
|
+
if (!isRecord(f))
|
|
72
|
+
throw new Error('invalid form: expected an object');
|
|
73
|
+
if (typeof f.form_name !== 'string' || f.form_name === '' || !Array.isArray(f.fields)) {
|
|
74
|
+
throw new Error(`invalid form ${JSON.stringify(f.form_id)}`);
|
|
75
|
+
}
|
|
76
|
+
if (UNSAFE_KEYS.has(f.form_name) || f.form_name.includes('.')) {
|
|
77
|
+
throw new Error(`invalid form_name ${JSON.stringify(f.form_name)}`);
|
|
78
|
+
}
|
|
79
|
+
if (typeof f.order !== 'number' || !Number.isFinite(f.order)) {
|
|
80
|
+
throw new Error(`form ${f.form_name} needs a numeric order`);
|
|
81
|
+
}
|
|
82
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime guard: value is untrusted JSON
|
|
83
|
+
if (f.kind !== undefined && f.kind !== 'form' && f.kind !== 'approval') {
|
|
84
|
+
throw new Error(`invalid form kind ${JSON.stringify(f.kind)} on ${f.form_name}`);
|
|
85
|
+
}
|
|
86
|
+
assertFormParts(f);
|
|
87
|
+
if (f.view !== undefined && !f.views?.some((v) => v.name === f.view)) {
|
|
88
|
+
throw new Error(`step view ${JSON.stringify(f.view)} on ${f.form_name} matches no view`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function assertApprovalConfig(f, nameSet) {
|
|
92
|
+
const approval = f.approval;
|
|
93
|
+
if (approval === undefined)
|
|
94
|
+
return;
|
|
95
|
+
if (!isRecord(approval))
|
|
96
|
+
throw new Error(`invalid approval config on ${f.form_name}`);
|
|
97
|
+
const on_reject = approval.on_reject;
|
|
98
|
+
if (on_reject === undefined)
|
|
99
|
+
return;
|
|
100
|
+
if (!isRecord(on_reject) || (on_reject.action !== 'end' && on_reject.action !== 'goto')) {
|
|
101
|
+
throw new Error(`invalid on_reject on ${f.form_name}`);
|
|
102
|
+
}
|
|
103
|
+
if (on_reject.action === 'goto' &&
|
|
104
|
+
(typeof on_reject.form !== 'string' || !nameSet.has(on_reject.form))) {
|
|
105
|
+
throw new Error(`on_reject.goto targets unknown form ${JSON.stringify(on_reject.form)} on ${f.form_name}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function assertTransitions(wf, nameSet, refs) {
|
|
109
|
+
if (wf.transitions === undefined)
|
|
110
|
+
return;
|
|
111
|
+
if (!Array.isArray(wf.transitions))
|
|
112
|
+
throw new Error('transitions must be an array');
|
|
113
|
+
for (const tr of wf.transitions) {
|
|
114
|
+
if (!isRecord(tr) || typeof tr.from !== 'string' || typeof tr.to !== 'string') {
|
|
115
|
+
throw new Error('invalid transition: expected { from, to }');
|
|
116
|
+
}
|
|
117
|
+
if (!nameSet.has(tr.from)) {
|
|
118
|
+
throw new Error(`transition from unknown form ${JSON.stringify(tr.from)}`);
|
|
119
|
+
}
|
|
120
|
+
if (tr.to !== 'end' && !nameSet.has(tr.to)) {
|
|
121
|
+
throw new Error(`transition to unknown form ${JSON.stringify(tr.to)}`);
|
|
122
|
+
}
|
|
123
|
+
assertValidCondition(tr.when, refs, `transition ${tr.from} -> ${tr.to}`, false);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function assertValidWorkflow(parsed) {
|
|
127
|
+
for (const f of parsed.forms)
|
|
128
|
+
assertWorkflowForm(f);
|
|
129
|
+
const names = parsed.forms.map((f) => f.form_name);
|
|
130
|
+
if (new Set(names).size !== names.length) {
|
|
131
|
+
throw new Error('formName must be unique in a workflow');
|
|
132
|
+
}
|
|
133
|
+
const nameSet = new Set(names);
|
|
134
|
+
const refs = fieldRefs(parsed);
|
|
135
|
+
for (const f of parsed.forms)
|
|
136
|
+
assertApprovalConfig(f, nameSet);
|
|
137
|
+
assertValidRules(parsed, nameSet, refs);
|
|
138
|
+
assertTransitions(parsed, nameSet, refs);
|
|
139
|
+
}
|
|
140
|
+
// ---- parseSchema internals ----------------------------------------------------
|
|
141
|
+
/** Every addressable "formName.key" a rule/condition/expression may reference. */
|
|
142
|
+
function fieldRefs(wf) {
|
|
143
|
+
const refs = new Set();
|
|
144
|
+
for (const form of wf.forms) {
|
|
145
|
+
for (const field of [...form.fields, ...approvalFields(form)]) {
|
|
146
|
+
if (isStatic(field))
|
|
147
|
+
continue;
|
|
148
|
+
refs.add(`${form.form_name}.${field.key}`);
|
|
149
|
+
for (const ref of rowRefsOf(form.form_name, field))
|
|
150
|
+
refs.add(ref);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return refs;
|
|
154
|
+
}
|
|
155
|
+
/** `Form.repeater[].sub`: the same-row references rules may use (spec 02 §2a). */
|
|
156
|
+
function rowRefsOf(form_name, field) {
|
|
157
|
+
if (field.type !== 'repeater')
|
|
158
|
+
return [];
|
|
159
|
+
return rowSubFields(field).map((sub) => `${form_name}.${field.key}[].${sub.key}`);
|
|
160
|
+
}
|
|
161
|
+
function assertSubFields(field, form_name) {
|
|
162
|
+
if (field.fields === undefined)
|
|
163
|
+
return;
|
|
164
|
+
if (!Array.isArray(field.fields)) {
|
|
165
|
+
throw new Error(`fields[] on ${form_name}.${field.key} must be an array`);
|
|
166
|
+
}
|
|
167
|
+
for (const sub of field.fields) {
|
|
168
|
+
if (!isRecord(sub)) {
|
|
169
|
+
throw new Error(`invalid sub-field on ${form_name}.${field.key}: expected an object`);
|
|
170
|
+
}
|
|
171
|
+
assertFieldShape(sub, form_name);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function assertValidFields(form) {
|
|
175
|
+
const seen = new Set();
|
|
176
|
+
for (const raw of form.fields) {
|
|
177
|
+
if (!isRecord(raw))
|
|
178
|
+
throw new Error(`invalid field on ${form.form_name}: expected an object`);
|
|
179
|
+
const field = raw;
|
|
180
|
+
assertFieldShape(field, form.form_name);
|
|
181
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime guard: value is untrusted JSON
|
|
182
|
+
if (field.key !== undefined) {
|
|
183
|
+
if (seen.has(field.key)) {
|
|
184
|
+
throw new Error(`duplicate field key ${JSON.stringify(field.key)} on ${form.form_name}`);
|
|
185
|
+
}
|
|
186
|
+
seen.add(field.key);
|
|
187
|
+
}
|
|
188
|
+
assertSubFields(field, form.form_name);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function assertFieldKey(field, form_name) {
|
|
192
|
+
// labels/sections are static blocks and may omit the key; everything else needs one
|
|
193
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime guard: value is untrusted JSON
|
|
194
|
+
if (isStatic(field) && field.key === undefined)
|
|
195
|
+
return;
|
|
196
|
+
if (typeof field.key !== 'string' || field.key === '') {
|
|
197
|
+
throw new Error(`field on ${form_name} needs a non-empty string key`);
|
|
198
|
+
}
|
|
199
|
+
if (UNSAFE_KEYS.has(field.key) || field.key.includes('.')) {
|
|
200
|
+
throw new Error(`invalid field key ${JSON.stringify(field.key)} on ${form_name}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function assertPatternValidator(v, where) {
|
|
204
|
+
// compile now — an invalid regex would otherwise throw (or hang, if
|
|
205
|
+
// catastrophic) inside validateField on every future submission
|
|
206
|
+
const pattern = String(v.value);
|
|
207
|
+
try {
|
|
208
|
+
new RegExp(pattern);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw new Error(`invalid pattern ${JSON.stringify(v.value)} on ${where}`);
|
|
212
|
+
}
|
|
213
|
+
if (isUnsafePattern(pattern)) {
|
|
214
|
+
throw new Error(`pattern on ${where} nests or overlaps unbounded quantifiers ` +
|
|
215
|
+
`(e.g. "(a+)+", "(\\w|\\d)+") — this backtracks catastrophically on hostile input; ` +
|
|
216
|
+
`rewrite it so each character can match only one way`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const SCHEME_NAME = /^[a-z][a-z\d+.-]*$/i;
|
|
220
|
+
/** `url` validator: `schemes`, when given, lists scheme names (no colon). */
|
|
221
|
+
function assertUrlValidator(v, where) {
|
|
222
|
+
const { schemes } = v;
|
|
223
|
+
if (schemes === undefined)
|
|
224
|
+
return;
|
|
225
|
+
const ok = Array.isArray(schemes) &&
|
|
226
|
+
schemes.length > 0 &&
|
|
227
|
+
schemes.every((s) => typeof s === 'string' && SCHEME_NAME.test(s));
|
|
228
|
+
if (!ok) {
|
|
229
|
+
throw new Error(`url validator on ${where}: schemes must be a non-empty list of scheme names such as "https"`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function assertFieldValidators(field, form_name) {
|
|
233
|
+
if (field.validators === undefined)
|
|
234
|
+
return;
|
|
235
|
+
const where = `${form_name}.${field.key}`;
|
|
236
|
+
if (!Array.isArray(field.validators)) {
|
|
237
|
+
throw new Error(`validators on ${where} must be an array`);
|
|
238
|
+
}
|
|
239
|
+
for (const v of field.validators) {
|
|
240
|
+
if (!isRecord(v) || typeof v.type !== 'string') {
|
|
241
|
+
throw new Error(`invalid validator on ${where}`);
|
|
242
|
+
}
|
|
243
|
+
if (v.type === 'pattern')
|
|
244
|
+
assertPatternValidator(v, where);
|
|
245
|
+
if (v.type === 'url')
|
|
246
|
+
assertUrlValidator(v, where);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function assertFieldShape(field, form_name) {
|
|
250
|
+
if (typeof field.type !== 'string' || !FIELD_TYPES.has(field.type)) {
|
|
251
|
+
throw new Error(`unknown field type ${JSON.stringify(field.type)} on ${form_name}`);
|
|
252
|
+
}
|
|
253
|
+
assertFieldKey(field, form_name);
|
|
254
|
+
if (field.type === 'date')
|
|
255
|
+
assertDateProps(field, form_name);
|
|
256
|
+
if (field.type === 'time')
|
|
257
|
+
assertTimeProps(field, form_name);
|
|
258
|
+
if (field.type === 'rating')
|
|
259
|
+
assertRatingProps(field, form_name);
|
|
260
|
+
if (field.type === 'range')
|
|
261
|
+
assertRangeProps(field, form_name);
|
|
262
|
+
if (field.type === 'reference' && (typeof field.reference !== 'string' || !field.reference)) {
|
|
263
|
+
throw new Error(`reference on ${form_name}.${field.key} must name a registry lookup (registry.references)`);
|
|
264
|
+
}
|
|
265
|
+
if (field.options !== undefined &&
|
|
266
|
+
(!Array.isArray(field.options) ||
|
|
267
|
+
field.options.some((o) => !isRecord(o) || typeof o.key !== 'string'))) {
|
|
268
|
+
throw new Error(`invalid options on ${form_name}.${field.key}: expected { key, label } items`);
|
|
269
|
+
}
|
|
270
|
+
assertFieldValidators(field, form_name);
|
|
271
|
+
}
|
|
272
|
+
/** Calendar constraints must be well-formed or the picker silently ignores them. */
|
|
273
|
+
function assertRatingProps(field, form_name) {
|
|
274
|
+
const max = field.max;
|
|
275
|
+
if (max === undefined)
|
|
276
|
+
return;
|
|
277
|
+
if (typeof max !== 'number' || !Number.isInteger(max) || max < 1 || max > 10) {
|
|
278
|
+
throw new Error(`max on ${form_name}.${field.key} must be a whole number from 1 to 10 (star count)`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
function assertRangeProps(field, form_name) {
|
|
282
|
+
const where = `${form_name}.${field.key}`;
|
|
283
|
+
const { min, max, step } = field;
|
|
284
|
+
const notNumber = (v) => v !== undefined && (typeof v !== 'number' || !Number.isFinite(v));
|
|
285
|
+
if (notNumber(min) || notNumber(max))
|
|
286
|
+
throw new Error(`min and max on ${where} must be numbers`);
|
|
287
|
+
const bounds = rangeBounds(field);
|
|
288
|
+
if (bounds.min >= bounds.max)
|
|
289
|
+
throw new Error(`min on ${where} must be below max`);
|
|
290
|
+
if (step !== undefined && (typeof step !== 'number' || !(step > 0))) {
|
|
291
|
+
throw new Error(`step on ${where} must be a positive number`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function assertDateProps(field, form_name) {
|
|
295
|
+
const where = `${form_name}.${field.key}`;
|
|
296
|
+
if (field.date_mode !== undefined && !DATE_MODES.has(field.date_mode)) {
|
|
297
|
+
throw new Error(`invalid date_mode ${JSON.stringify(field.date_mode)} on ${where}`);
|
|
298
|
+
}
|
|
299
|
+
for (const bound of ['min', 'max']) {
|
|
300
|
+
const v = field[bound];
|
|
301
|
+
if (v !== undefined && parseIsoDate(v) === null) {
|
|
302
|
+
throw new Error(`${bound} on ${where} must be an ISO date (yyyy-mm-dd)`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (field.disabled_dates !== undefined) {
|
|
306
|
+
const bad = !Array.isArray(field.disabled_dates) ||
|
|
307
|
+
field.disabled_dates.some((d) => typeof d !== 'string' || parseDisabledEntry(d) === null);
|
|
308
|
+
if (bad) {
|
|
309
|
+
throw new Error(`disabled_dates on ${where} must be ISO days ("2026-04-13") or intervals ("2026-04-13/2026-04-15")`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (field.disabled_weekdays !== undefined) {
|
|
313
|
+
const bad = !Array.isArray(field.disabled_weekdays) ||
|
|
314
|
+
field.disabled_weekdays.some((d) => !Number.isInteger(d) || d < 0 || d > 6);
|
|
315
|
+
if (bad)
|
|
316
|
+
throw new Error(`disabled_weekdays on ${where} must be integers 0 (Sun) … 6 (Sat)`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function assertTimeProps(field, form_name) {
|
|
320
|
+
for (const bound of ['min', 'max']) {
|
|
321
|
+
const v = field[bound];
|
|
322
|
+
if (v !== undefined && !isTimeOfDay(v)) {
|
|
323
|
+
throw new Error(`${bound} on ${form_name}.${field.key} must be a time (HH:mm)`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function assertRuleAction(rawAction, where, formNames, refs) {
|
|
328
|
+
if (!isRecord(rawAction) || typeof rawAction.action !== 'string') {
|
|
329
|
+
throw new Error(`${where}: invalid action`);
|
|
330
|
+
}
|
|
331
|
+
const target = rawAction.target;
|
|
332
|
+
if (!isRecord(target) || typeof target.form !== 'string') {
|
|
333
|
+
throw new Error(`${where}: action needs a target form`);
|
|
334
|
+
}
|
|
335
|
+
if (!formNames.has(target.form)) {
|
|
336
|
+
throw new Error(`${where} targets unknown form ${JSON.stringify(target.form)}`);
|
|
337
|
+
}
|
|
338
|
+
const formLevel = rawAction.action === 'showForm' ||
|
|
339
|
+
rawAction.action === 'hideForm' ||
|
|
340
|
+
rawAction.action === 'skipForm';
|
|
341
|
+
if (!formLevel) {
|
|
342
|
+
const ref = `${target.form}.${String(target.field)}`;
|
|
343
|
+
if (typeof target.field !== 'string' || !refs.has(ref)) {
|
|
344
|
+
throw new Error(`${where} targets unknown field ${JSON.stringify(ref)}`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (rawAction.action === 'setValue') {
|
|
348
|
+
if (parseRowRef(`${target.form}.${String(target.field)}`)) {
|
|
349
|
+
throw new Error(`${where}: setValue cannot target a repeater row field`);
|
|
350
|
+
}
|
|
351
|
+
assertValidExpr(rawAction.value, refs, where);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function assertRule(raw, i, formNames, refs) {
|
|
355
|
+
if (!isRecord(raw))
|
|
356
|
+
throw new Error(`invalid rule at index ${i}: expected an object`);
|
|
357
|
+
const rule = raw;
|
|
358
|
+
const where = `rule ${typeof rule.id === 'string' ? JSON.stringify(rule.id) : i}`;
|
|
359
|
+
if (rule.priority !== undefined && typeof rule.priority !== 'number') {
|
|
360
|
+
throw new Error(`${where}: priority must be a number`);
|
|
361
|
+
}
|
|
362
|
+
assertValidCondition(rule.when, refs, where);
|
|
363
|
+
for (const branch of ['then', 'else']) {
|
|
364
|
+
const actions = rule[branch];
|
|
365
|
+
if (actions === undefined)
|
|
366
|
+
continue;
|
|
367
|
+
if (!Array.isArray(actions))
|
|
368
|
+
throw new Error(`${where}: ${branch} must be an array`);
|
|
369
|
+
for (const rawAction of actions)
|
|
370
|
+
assertRuleAction(rawAction, where, formNames, refs);
|
|
371
|
+
}
|
|
372
|
+
assertSingleRowScope(rule, where);
|
|
373
|
+
}
|
|
374
|
+
/** A row-scoped rule is evaluated per row of ONE repeater (spec 02 §2a). */
|
|
375
|
+
function assertSingleRowScope(rule, where) {
|
|
376
|
+
const scoped = new Set(conditionRowRefs(rule.when).map((r) => `${r.form}.${r.repeater}`));
|
|
377
|
+
const whenIsRow = scoped.size > 0;
|
|
378
|
+
for (const branch of [rule.then, rule.else]) {
|
|
379
|
+
for (const action of Array.isArray(branch) ? branch : []) {
|
|
380
|
+
const row = actionRowRef(action);
|
|
381
|
+
if (row)
|
|
382
|
+
scoped.add(`${row.form}.${row.repeater}`);
|
|
383
|
+
else if (whenIsRow)
|
|
384
|
+
throw new Error(rowTargetMessage(where, action));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (scoped.size > 1)
|
|
388
|
+
throw new Error(`${where}: a rule may be row-scoped to one repeater only`);
|
|
389
|
+
}
|
|
390
|
+
function rowTargetMessage(where, action) {
|
|
391
|
+
const target = isRecord(action) && isRecord(action.target) ? action.target : {};
|
|
392
|
+
const name = typeof target.field === 'string'
|
|
393
|
+
? `${String(target.form)}.${target.field}`
|
|
394
|
+
: String(target.form);
|
|
395
|
+
return `${where}: its condition reads a row-scoped ref, so every target must be a row field (got ${name})`;
|
|
396
|
+
}
|
|
397
|
+
/** The row-scoped ref an action targets, if any. */
|
|
398
|
+
function actionRowRef(action) {
|
|
399
|
+
const target = isRecord(action) && isRecord(action.target) ? action.target : undefined;
|
|
400
|
+
if (!target || typeof target.field !== 'string')
|
|
401
|
+
return null;
|
|
402
|
+
return parseRowRef(`${String(target.form)}.${target.field}`);
|
|
403
|
+
}
|
|
404
|
+
function assertValidRules(wf, formNames, refs) {
|
|
405
|
+
wf.rules.forEach((raw, i) => {
|
|
406
|
+
assertRule(raw, i, formNames, refs);
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* `allowRow`: a row-scoped ref (`Form.repeater[].sub`) only means something in
|
|
411
|
+
* a rule's `when` (spec 02 §2a) — transitions and value expressions have no row.
|
|
412
|
+
*/
|
|
413
|
+
function assertValidCondition(cond, refs, where, allowRow = true) {
|
|
414
|
+
if (cond === undefined)
|
|
415
|
+
return; // omitted = always true
|
|
416
|
+
if (!isRecord(cond))
|
|
417
|
+
throw new Error(`invalid condition in ${where}`);
|
|
418
|
+
if ('and' in cond || 'or' in cond) {
|
|
419
|
+
const list = cond.and ?? cond.or;
|
|
420
|
+
if (!Array.isArray(list))
|
|
421
|
+
throw new Error(`invalid condition in ${where}`);
|
|
422
|
+
for (const c of list)
|
|
423
|
+
assertValidCondition(c, refs, where, allowRow);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if ('not' in cond) {
|
|
427
|
+
assertValidCondition(cond.not, refs, where, allowRow);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
assertKnownRef(cond.field, refs, where, allowRow);
|
|
431
|
+
if (cond.value_field !== undefined)
|
|
432
|
+
assertKnownRef(cond.value_field, refs, where, allowRow);
|
|
433
|
+
}
|
|
434
|
+
function assertKnownRef(ref, refs, where, allowRow) {
|
|
435
|
+
if (typeof ref !== 'string' || !refs.has(ref)) {
|
|
436
|
+
throw new Error(`${where} references unknown field ${JSON.stringify(ref)}`);
|
|
437
|
+
}
|
|
438
|
+
if (!allowRow && parseRowRef(ref)) {
|
|
439
|
+
throw new Error(`${where}: a row-scoped ref is only valid in a rule condition`);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function assertValidExpr(expr, refs, where) {
|
|
443
|
+
if (!isRecord(expr))
|
|
444
|
+
throw new Error(`${where}: invalid value expression`);
|
|
445
|
+
if ('ref' in expr) {
|
|
446
|
+
assertKnownRef(expr.ref, refs, where, false);
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
if ('const' in expr)
|
|
450
|
+
return;
|
|
451
|
+
if ('op' in expr) {
|
|
452
|
+
if (!Array.isArray(expr.args)) {
|
|
453
|
+
throw new Error(`${where}: expression args must be an array`);
|
|
454
|
+
}
|
|
455
|
+
for (const a of expr.args)
|
|
456
|
+
assertValidExpr(a, refs, where);
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
if ('if' in expr) {
|
|
460
|
+
const triple = expr.if;
|
|
461
|
+
if (!Array.isArray(triple) || triple.length !== 3) {
|
|
462
|
+
throw new Error(`${where}: if expression needs [condition, then, else]`);
|
|
463
|
+
}
|
|
464
|
+
assertValidCondition(triple[0], refs, where, false);
|
|
465
|
+
assertValidExpr(triple[1], refs, where);
|
|
466
|
+
assertValidExpr(triple[2], refs, where);
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
throw new Error(`${where}: invalid value expression`);
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* View integrity — views are client-side display projections, but a stored
|
|
473
|
+
* one must always resolve on the client: names unique and shaped right, every
|
|
474
|
+
* listed key present in fields. Catches builder typos at store time
|
|
475
|
+
* instead of as a silently empty form.
|
|
476
|
+
*/
|
|
477
|
+
/**
|
|
478
|
+
* Repeater integrity (spec 01 §10): a repeater must carry sub-fields with
|
|
479
|
+
* unique keys, and repeaters never nest.
|
|
480
|
+
*/
|
|
481
|
+
function assertValidRepeaters(form) {
|
|
482
|
+
for (const field of form.fields) {
|
|
483
|
+
if (field.type !== 'repeater')
|
|
484
|
+
continue;
|
|
485
|
+
if (!Array.isArray(field.fields) || field.fields.length === 0) {
|
|
486
|
+
throw new Error(`repeater ${JSON.stringify(field.key)} on ${form.form_name} needs fields[]`);
|
|
487
|
+
}
|
|
488
|
+
const keys = field.fields.map((f) => f.key);
|
|
489
|
+
if (new Set(keys).size !== keys.length) {
|
|
490
|
+
throw new Error(`repeater ${JSON.stringify(field.key)} on ${form.form_name} has duplicate sub-keys`);
|
|
491
|
+
}
|
|
492
|
+
if (field.fields.some((f) => f.type === 'repeater')) {
|
|
493
|
+
throw new Error(`repeater ${JSON.stringify(field.key)} on ${form.form_name} nests a repeater`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const SCRIPT_EVENTS = new Set(['load', 'change', 'submit']);
|
|
498
|
+
/** `scripts[]` (spec 01 §14): known `on`, a handler name, and a real field for `change`. */
|
|
499
|
+
function assertScript(s, form_name, keys) {
|
|
500
|
+
if (!isRecord(s))
|
|
501
|
+
throw new Error(`invalid script on ${form_name}: expected an object`);
|
|
502
|
+
if (typeof s.on !== 'string' || !SCRIPT_EVENTS.has(s.on)) {
|
|
503
|
+
throw new Error(`invalid script on=${JSON.stringify(s.on)} on ${form_name}`);
|
|
504
|
+
}
|
|
505
|
+
if (typeof s.handler !== 'string' || s.handler === '') {
|
|
506
|
+
throw new Error(`script on ${form_name} needs a handler name`);
|
|
507
|
+
}
|
|
508
|
+
if (s.on !== 'change')
|
|
509
|
+
return;
|
|
510
|
+
if (typeof s.field !== 'string' || s.field === '') {
|
|
511
|
+
throw new Error(`change script "${s.handler}" on ${form_name} needs a field`);
|
|
512
|
+
}
|
|
513
|
+
if (!keys.has(s.field)) {
|
|
514
|
+
throw new Error(`change script "${s.handler}" on ${form_name} targets unknown field ${JSON.stringify(s.field)}`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function assertValidScripts(form) {
|
|
518
|
+
if (form.scripts === undefined)
|
|
519
|
+
return;
|
|
520
|
+
if (!Array.isArray(form.scripts)) {
|
|
521
|
+
throw new Error(`scripts must be an array on ${form.form_name}`);
|
|
522
|
+
}
|
|
523
|
+
const keys = new Set(form.fields.map((f) => f.key));
|
|
524
|
+
for (const s of form.scripts)
|
|
525
|
+
assertScript(s, form.form_name, keys);
|
|
526
|
+
}
|
|
527
|
+
function assertValidViews(form) {
|
|
528
|
+
if (form.views === undefined)
|
|
529
|
+
return;
|
|
530
|
+
if (!Array.isArray(form.views))
|
|
531
|
+
throw new Error(`views must be an array on ${form.form_name}`);
|
|
532
|
+
const keys = new Set(form.fields.map((f) => f.key));
|
|
533
|
+
const names = new Set();
|
|
534
|
+
for (const view of form.views) {
|
|
535
|
+
if (!isRecord(view) || typeof view.name !== 'string' || !Array.isArray(view.fields)) {
|
|
536
|
+
throw new Error(`invalid view on ${form.form_name}: expected { name, fields[] }`);
|
|
537
|
+
}
|
|
538
|
+
if (names.has(view.name)) {
|
|
539
|
+
throw new Error(`view names must be unique on ${form.form_name}: ${JSON.stringify(view.name)}`);
|
|
540
|
+
}
|
|
541
|
+
names.add(view.name);
|
|
542
|
+
for (const key of view.fields) {
|
|
543
|
+
if (typeof key !== 'string' || !keys.has(key)) {
|
|
544
|
+
throw new Error(`view ${JSON.stringify(view.name)} on ${form.form_name} references unknown field ${JSON.stringify(key)}`);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
package/dist/shape.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type FieldDescriptor, type NestedData, type WorkflowDefinition } from '@20baht/engine';
|
|
2
|
+
import { type ValidationIssue } from './common.js';
|
|
3
|
+
export declare const isTimeOfDay: (v: unknown) => boolean;
|
|
4
|
+
/** Shape issues for one field, recursing one level into repeater rows. */
|
|
5
|
+
export declare function shapeIssues(field: FieldDescriptor, value: unknown, ref: string): ValidationIssue[];
|
|
6
|
+
/**
|
|
7
|
+
* Canonical value for one field, as the client would emit it: `tags` via
|
|
8
|
+
* `canonicalTags` (the transform `validateField` applies internally, so the
|
|
9
|
+
* persisted `data` matches byte-for-byte); a file ref keeps only its ref
|
|
10
|
+
* fields; `-0` becomes `0`; a repeater row is rebuilt from its declared
|
|
11
|
+
* columns only (a repeater never nests, spec 01 §10). Every other value
|
|
12
|
+
* passes through. Runs after `shapeIssues`, or on rule input where a
|
|
13
|
+
* wrong-shaped value is left for `shapeIssues` to reject.
|
|
14
|
+
*/
|
|
15
|
+
export declare function normalizeCanonicalValue(field: FieldDescriptor, raw: unknown): unknown;
|
|
16
|
+
/**
|
|
17
|
+
* Copy of the workflow input with every tags value (and tags column)
|
|
18
|
+
* canonical — rules and transitions must read tags the way the client emits
|
|
19
|
+
* them, else `[" urgent "]` dodges a `contains "urgent"` rule.
|
|
20
|
+
*/
|
|
21
|
+
export declare function withNormalizedTags(workflow: WorkflowDefinition, input: NestedData): NestedData;
|