@20baht/engine 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/approval.d.ts +15 -0
  4. package/dist/approval.js +18 -0
  5. package/dist/dates.d.ts +34 -0
  6. package/dist/dates.js +91 -0
  7. package/dist/defaults.d.ts +6 -0
  8. package/dist/defaults.js +37 -0
  9. package/dist/display.d.ts +33 -0
  10. package/dist/display.js +110 -0
  11. package/dist/engine/conditions.d.ts +27 -0
  12. package/dist/engine/conditions.js +123 -0
  13. package/dist/engine/evaluate.d.ts +8 -0
  14. package/dist/engine/evaluate.js +368 -0
  15. package/dist/engine/expressions.d.ts +3 -0
  16. package/dist/engine/expressions.js +70 -0
  17. package/dist/engine/form-session.d.ts +135 -0
  18. package/dist/engine/form-session.js +313 -0
  19. package/dist/engine/graph.d.ts +40 -0
  20. package/dist/engine/graph.js +59 -0
  21. package/dist/engine/runtime.d.ts +194 -0
  22. package/dist/engine/runtime.js +268 -0
  23. package/dist/engine/scripts.d.ts +34 -0
  24. package/dist/engine/scripts.js +98 -0
  25. package/dist/flags.d.ts +19 -0
  26. package/dist/flags.js +49 -0
  27. package/dist/form-values.d.ts +78 -0
  28. package/dist/form-values.js +6 -0
  29. package/dist/i18n.d.ts +177 -0
  30. package/dist/i18n.js +310 -0
  31. package/dist/index.d.ts +25 -0
  32. package/dist/index.js +23 -0
  33. package/dist/keys.d.ts +14 -0
  34. package/dist/keys.js +4 -0
  35. package/dist/legacy.d.ts +14 -0
  36. package/dist/legacy.js +47 -0
  37. package/dist/pattern-safety.d.ts +34 -0
  38. package/dist/pattern-safety.js +267 -0
  39. package/dist/same-data.d.ts +5 -0
  40. package/dist/same-data.js +23 -0
  41. package/dist/shortcut.d.ts +44 -0
  42. package/dist/shortcut.js +176 -0
  43. package/dist/types.d.ts +541 -0
  44. package/dist/types.js +1 -0
  45. package/dist/urls.d.ts +8 -0
  46. package/dist/urls.js +30 -0
  47. package/dist/validators.d.ts +39 -0
  48. package/dist/validators.js +372 -0
  49. package/dist/views.d.ts +12 -0
  50. package/dist/views.js +11 -0
  51. package/package.json +52 -4
@@ -0,0 +1,372 @@
1
+ import { defaultValue } from './defaults.js';
2
+ import { rowSubFields } from './keys.js';
3
+ import { compareValues } from './engine/conditions.js';
4
+ import { isUnsafePattern } from './pattern-safety.js';
5
+ import { dateModeOf, isDateDisabled, isoDaysOf, rangeInteriorDays } from './dates.js';
6
+ import { t } from './i18n.js';
7
+ import { isAllowedUrl, isSafeUrl } from './urls.js';
8
+ const DEFAULT_URL_SCHEMES = ['http', 'https'];
9
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
10
+ const BLANK_RE = /^[\s\u00AD\u180E\u200B-\u200F\u2060-\u2064\uFEFF]*$/;
11
+ const DEFAULT_MAX_LENGTH = {
12
+ text: 1024,
13
+ email: 1024,
14
+ password: 1024,
15
+ textarea: 10_000,
16
+ markdown: 100_000,
17
+ };
18
+ const PATTERN_INPUT_CAP = 1024;
19
+ const PATTERN_INPUT_CEILING = 10_000;
20
+ const PATTERN_CACHE_LIMIT = 500;
21
+ export function isBlank(text) {
22
+ return BLANK_RE.test(text);
23
+ }
24
+ function isEmpty(v) {
25
+ if (v === null || v === undefined)
26
+ return true;
27
+ if (typeof v === 'string')
28
+ return isBlank(v);
29
+ if (Array.isArray(v))
30
+ return v.length === 0;
31
+ if (typeof v === 'boolean')
32
+ return !v;
33
+ return false;
34
+ }
35
+ function effectiveValidators(field) {
36
+ const list = [...(field.validators ?? [])];
37
+ const has = (t) => list.some((v) => v.type === t);
38
+ if (field.required && !has('required'))
39
+ list.push({ type: 'required' });
40
+ const maxLength = field.max_length ?? DEFAULT_MAX_LENGTH[field.type];
41
+ if (maxLength !== undefined && !has('maxLength'))
42
+ list.push({ type: 'maxLength', value: maxLength });
43
+ if (field.min_length !== undefined && !has('minLength'))
44
+ list.push({ type: 'minLength', value: field.min_length });
45
+ const { min, max } = field.type === 'range' ? rangeBounds(field) : field;
46
+ if (min !== undefined && !has('min'))
47
+ list.push({ type: 'min', value: min });
48
+ if (max !== undefined && field.type !== 'rating' && !has('max'))
49
+ list.push({ type: 'max', value: max });
50
+ if (field.type === 'email' && !has('email'))
51
+ list.push({ type: 'email' });
52
+ return list;
53
+ }
54
+ const eachValue = (v) => (Array.isArray(v) ? v : [v]);
55
+ function checkLength(kind, label) {
56
+ return (spec, value) => {
57
+ const n = Number(spec.value);
58
+ if (Number.isNaN(n)) {
59
+ console.warn(`[bahtui] ${label} validator has non-numeric value ${JSON.stringify(spec.value)} — skipped`);
60
+ return null;
61
+ }
62
+ if (typeof value !== 'string')
63
+ return null;
64
+ const bad = kind === 'minLength' ? value.length < n : value.length > n;
65
+ return bad ? (spec.message ?? t(kind, { n: spec.value })) : null;
66
+ };
67
+ }
68
+ function checkBound(kind) {
69
+ return (spec, value) => {
70
+ const out = eachValue(value).some((v) => {
71
+ const c = compareValues(v, spec.value);
72
+ return c !== null && (kind === 'min' ? c < 0 : c > 0);
73
+ });
74
+ return out ? (spec.message ?? t(kind, { n: spec.value })) : null;
75
+ };
76
+ }
77
+ const COMPARE_PASS = {
78
+ gt: (c) => c > 0,
79
+ gte: (c) => c >= 0,
80
+ lt: (c) => c < 0,
81
+ lte: (c) => c <= 0,
82
+ };
83
+ const checkCompare = (spec, value, _registry, data) => {
84
+ const other = data?.[spec.field ?? ''];
85
+ if (other === undefined || isEmpty(other))
86
+ return null;
87
+ const op = spec.op ?? 'eq';
88
+ if (op === 'eq' || op === 'ne') {
89
+ if ((value === other) === (op === 'eq'))
90
+ return null;
91
+ }
92
+ else {
93
+ const c = compareValues(value, other);
94
+ if (c === null)
95
+ return null;
96
+ if (COMPARE_PASS[op](c))
97
+ return null;
98
+ }
99
+ const key = `compare${op[0].toUpperCase()}${op.slice(1)}`;
100
+ return spec.message ?? t(key, { other: spec.field });
101
+ };
102
+ const checkPattern = (spec, value, _registry, _data, field) => {
103
+ if (typeof value !== 'string')
104
+ return null;
105
+ const re = compilePattern(String(spec.value));
106
+ if (!re)
107
+ return null;
108
+ const fail = spec.message ?? t('pattern');
109
+ const cap = Math.min(field.max_length ?? PATTERN_INPUT_CAP, PATTERN_INPUT_CEILING);
110
+ if (value.length > cap)
111
+ return fail;
112
+ return re.test(value) ? null : fail;
113
+ };
114
+ const checkCustom = (spec, value, registry, data, field) => {
115
+ const fn = registry?.validators?.[spec.fn ?? ''];
116
+ if (!fn) {
117
+ console.warn(`[bahtui] unknown custom validator "${spec.fn}" — skipped`);
118
+ return null;
119
+ }
120
+ const out = fn(value, data ?? {}, field);
121
+ return out === null ? null : (spec.message ?? out);
122
+ };
123
+ const checkUrl = (spec, value) => {
124
+ if (typeof value !== 'string')
125
+ return null;
126
+ const schemes = Array.isArray(spec.schemes)
127
+ ? spec.schemes.filter((s) => typeof s === 'string').map((s) => s.toLowerCase())
128
+ : DEFAULT_URL_SCHEMES;
129
+ return isAllowedUrl(value, schemes) ? null : (spec.message ?? t('url'));
130
+ };
131
+ const CHECKERS = {
132
+ required: (spec, value) => (isEmpty(value) ? (spec.message ?? t('required')) : null),
133
+ minLength: checkLength('minLength', 'min_length'),
134
+ maxLength: checkLength('maxLength', 'max_length'),
135
+ min: checkBound('min'),
136
+ max: checkBound('max'),
137
+ pattern: checkPattern,
138
+ email: (spec, value) => typeof value === 'string' && !EMAIL_RE.test(value) ? (spec.message ?? t('email')) : null,
139
+ compare: checkCompare,
140
+ custom: checkCustom,
141
+ url: checkUrl,
142
+ };
143
+ function hasAtMostTwoDecimals(n) {
144
+ const cents = n * 100;
145
+ return Math.abs(cents - Math.round(cents)) <= 8 * Number.EPSILON * Math.max(1, Math.abs(cents));
146
+ }
147
+ export function ratingMax(field) {
148
+ const max = field.max;
149
+ return typeof max === 'number' && Number.isInteger(max) && max >= 1 && max <= 10 ? max : 5;
150
+ }
151
+ function ratingErrors(field, value) {
152
+ const max = ratingMax(field);
153
+ const ok = typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= max;
154
+ return ok ? [] : [{ key: field.key, message: t('ratingRange', { max }) }];
155
+ }
156
+ export function rangeBounds(field) {
157
+ const num = (v, fallback) => typeof v === 'number' && Number.isFinite(v) ? v : fallback;
158
+ const step = num(field.step, 1);
159
+ return { min: num(field.min, 0), max: num(field.max, 100), step: step > 0 ? step : 1 };
160
+ }
161
+ function rangeErrors(field, value) {
162
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
163
+ return [{ key: field.key, message: t('pattern') }];
164
+ }
165
+ const { min, step } = rangeBounds(field);
166
+ const steps = (value - min) / step;
167
+ const onGrid = Math.abs(steps - Math.round(steps)) <= 1e-9 * Math.max(1, Math.abs(steps));
168
+ return onGrid ? [] : [{ key: field.key, message: t('stepOf', { step }) }];
169
+ }
170
+ function referenceErrors(field, value) {
171
+ return typeof value === 'string' ? [] : [{ key: field.key, message: t('pattern') }];
172
+ }
173
+ function numberErrors(field, value) {
174
+ if (typeof value !== 'number')
175
+ return [];
176
+ if (!Number.isFinite(value))
177
+ return [{ key: field.key, message: t('pattern') }];
178
+ if (field.type === 'currency' && !hasAtMostTwoDecimals(value)) {
179
+ return [{ key: field.key, message: t('decimals') }];
180
+ }
181
+ if (field.integer && !Number.isInteger(value))
182
+ return [{ key: field.key, message: t('integer') }];
183
+ return [];
184
+ }
185
+ const PATTERN_CACHE = new Map();
186
+ function compilePattern(source) {
187
+ let re = PATTERN_CACHE.get(source);
188
+ if (re === undefined) {
189
+ try {
190
+ re = new RegExp(source);
191
+ }
192
+ catch {
193
+ console.warn(`[bahtui] invalid pattern ${JSON.stringify(source)} — skipped`);
194
+ re = null;
195
+ }
196
+ if (re && isUnsafePattern(source)) {
197
+ console.warn(`[bahtui] unsafe pattern ${JSON.stringify(source)} (nested or overlapping unbounded quantifiers) — skipped`);
198
+ re = null;
199
+ }
200
+ if (PATTERN_CACHE.size >= PATTERN_CACHE_LIMIT)
201
+ PATTERN_CACHE.clear();
202
+ PATTERN_CACHE.set(source, re);
203
+ }
204
+ return re;
205
+ }
206
+ export function normalizeTagsValue(value, options) {
207
+ if (!Array.isArray(value))
208
+ return [];
209
+ const keyFor = optionKeyLookup(options);
210
+ const seen = new Set();
211
+ const out = [];
212
+ for (const raw of value) {
213
+ if (typeof raw !== 'string')
214
+ continue;
215
+ const trimmed = raw.trim();
216
+ if (!trimmed)
217
+ continue;
218
+ const lower = trimmed.toLowerCase();
219
+ const tag = keyFor.get(lower) ?? trimmed;
220
+ if (seen.has(lower))
221
+ continue;
222
+ seen.add(lower);
223
+ out.push(tag);
224
+ }
225
+ return out;
226
+ }
227
+ export function optionKeyLookup(options) {
228
+ const map = new Map();
229
+ for (const o of options ?? []) {
230
+ const lower = o.key.toLowerCase();
231
+ if (!map.has(lower))
232
+ map.set(lower, o.key);
233
+ }
234
+ return map;
235
+ }
236
+ function tagsErrors(field, tags) {
237
+ const errors = [];
238
+ if (field.max_items !== undefined && tags.length > field.max_items) {
239
+ errors.push({ key: field.key, message: t('maxItems', { n: field.max_items }) });
240
+ }
241
+ const maxLen = field.max_length ?? 32;
242
+ if (tags.some((tag) => tag.length > maxLen)) {
243
+ errors.push({ key: field.key, message: t('tagTooLong', { n: maxLen }) });
244
+ }
245
+ return errors;
246
+ }
247
+ export function validateField(field, value, registry, data, rowStates) {
248
+ const errors = [];
249
+ const effectiveValue = field.type === 'tags' ? normalizeTagsValue(value) : value;
250
+ const validators = effectiveValidators(field);
251
+ const empty = isEmpty(effectiveValue);
252
+ for (const spec of validators) {
253
+ if (spec.type !== 'required' && empty)
254
+ continue;
255
+ const message = CHECKERS[spec.type](spec, effectiveValue, registry, data, field);
256
+ if (message !== null)
257
+ errors.push({ key: field.key, message });
258
+ }
259
+ if (field.type === 'repeater') {
260
+ errors.push(...repeaterErrors(field, effectiveValue, registry, rowStates));
261
+ }
262
+ errors.push(...typeErrors(field, effectiveValue, empty));
263
+ return errors;
264
+ }
265
+ const TYPE_CHECKS = {
266
+ file: { check: fileErrors },
267
+ number: { check: numberErrors },
268
+ currency: { check: numberErrors },
269
+ tags: { check: (f, v) => tagsErrors(f, v) },
270
+ date: { check: dateErrors, onValue: true },
271
+ time: { check: timeErrors, onValue: true },
272
+ rating: { check: ratingErrors, onValue: true },
273
+ range: { check: rangeErrors, onValue: true },
274
+ reference: { check: referenceErrors, onValue: true },
275
+ };
276
+ function typeErrors(field, value, empty) {
277
+ const rule = TYPE_CHECKS[field.type];
278
+ if (!rule || (rule.onValue && empty))
279
+ return [];
280
+ return rule.check(field, value);
281
+ }
282
+ function dateErrors(field, value) {
283
+ if (!field.disabled_dates?.length && !field.disabled_weekdays?.length)
284
+ return [];
285
+ const days = isoDaysOf(value);
286
+ if (dateModeOf(field) === 'range' && days.length === 2) {
287
+ days.push(...rangeInteriorDays(days[0], days[1]));
288
+ }
289
+ return days.some((d) => isDateDisabled(field, d))
290
+ ? [{ key: field.key, message: t('dateDisabled') }]
291
+ : [];
292
+ }
293
+ export const isTimeOfDay = (value) => typeof value === 'string' && /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value);
294
+ function timeErrors(field, value) {
295
+ return isTimeOfDay(value) ? [] : [{ key: field.key, message: t('timeInvalid') }];
296
+ }
297
+ export function isUploadedFile(v) {
298
+ if (v === null || typeof v !== 'object')
299
+ return false;
300
+ const r = v;
301
+ return (typeof r.name === 'string' &&
302
+ typeof r.size === 'number' &&
303
+ Number.isFinite(r.size) &&
304
+ r.size >= 0 &&
305
+ typeof r.url === 'string' &&
306
+ isSafeUrl(r.url) &&
307
+ (r.type === undefined || typeof r.type === 'string'));
308
+ }
309
+ function acceptMatches(accept, name, type) {
310
+ return accept.split(',').some((raw) => {
311
+ const token = raw.trim().toLowerCase();
312
+ if (!token)
313
+ return false;
314
+ if (token.startsWith('.'))
315
+ return name.toLowerCase().endsWith(token);
316
+ if (token.endsWith('/*'))
317
+ return type.toLowerCase().startsWith(token.slice(0, -1));
318
+ return type.toLowerCase() === token;
319
+ });
320
+ }
321
+ function fileErrors(field, value) {
322
+ const errors = [];
323
+ for (const ref of (Array.isArray(value) ? value : [value]).filter(isUploadedFile)) {
324
+ if (field.max_size !== undefined && ref.size > field.max_size) {
325
+ errors.push({ key: field.key, message: t('fileTooLarge') });
326
+ }
327
+ if (field.accept && !acceptMatches(field.accept, ref.name, ref.type ?? '')) {
328
+ errors.push({ key: field.key, message: t('fileTypeNotAllowed') });
329
+ }
330
+ }
331
+ return errors;
332
+ }
333
+ function repeaterErrors(field, value, registry, rowStates) {
334
+ if (value !== null && value !== undefined && !Array.isArray(value)) {
335
+ return [{ key: field.key, message: t('pattern') }];
336
+ }
337
+ const rows = Array.isArray(value) ? value : [];
338
+ const errors = [];
339
+ if (field.min_rows !== undefined && rows.length < field.min_rows) {
340
+ const message = field.min_rows === 1 ? t('minRowsOne') : t('minRows', { n: field.min_rows });
341
+ errors.push({ key: field.key, message });
342
+ }
343
+ if (field.max_rows !== undefined && rows.length > field.max_rows) {
344
+ const message = field.max_rows === 1 ? t('maxRowsOne') : t('maxRows', { n: field.max_rows });
345
+ errors.push({ key: field.key, message });
346
+ }
347
+ const subs = rowSubFields(field).sort((a, b) => a.order - b.order);
348
+ rows.forEach((row, i) => {
349
+ errors.push(...rowErrors(field, subs, row, i, registry, rowStates));
350
+ });
351
+ return errors;
352
+ }
353
+ function rowErrors(field, subs, row, i, registry, rowStates) {
354
+ const rec = row !== null && typeof row === 'object' && !Array.isArray(row)
355
+ ? row
356
+ : {};
357
+ const rowData = {};
358
+ for (const sub of subs) {
359
+ rowData[sub.key] = Object.hasOwn(rec, sub.key) ? rec[sub.key] : defaultValue(sub);
360
+ }
361
+ const errors = [];
362
+ for (const sub of subs) {
363
+ const state = rowStates?.[`${field.key}[${i}].${sub.key}`];
364
+ if (state && !state.visible)
365
+ continue;
366
+ const descriptor = state && state.required !== !!sub.required ? { ...sub, required: state.required } : sub;
367
+ for (const err of validateField(descriptor, rowData[sub.key], registry, rowData)) {
368
+ errors.push({ key: `${field.key}[${i}].${err.key}`, message: err.message });
369
+ }
370
+ }
371
+ return errors;
372
+ }
@@ -0,0 +1,12 @@
1
+ import type { FieldDescriptor, FormDefinition } from './types.js';
2
+ /**
3
+ * Resolve the fields a consumer of `form` should DISPLAY. Views are
4
+ * client-side projections only — data and server validation always cover the
5
+ * full form.
6
+ *
7
+ * - No `view` → every field, sorted by `order` (the full form).
8
+ * - A known view → only its fields, in the order the view lists them.
9
+ * - An unknown view → `null`; the caller decides the fallback (<baht-form>
10
+ * warns and shows the full form).
11
+ */
12
+ export declare function resolveViewFields(form: FormDefinition, view?: string): FieldDescriptor[] | null;
package/dist/views.js ADDED
@@ -0,0 +1,11 @@
1
+ export function resolveViewFields(form, view) {
2
+ if (!view)
3
+ return [...form.fields].sort((a, b) => a.order - b.order);
4
+ const spec = form.views?.find((v) => v.name === view);
5
+ if (!spec)
6
+ return null;
7
+ const byKey = new Map(form.fields.map((f) => [f.key, f]));
8
+ return spec.fields
9
+ .map((key) => byKey.get(key))
10
+ .filter((f) => f !== undefined);
11
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@20baht/engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=20.19.0"
7
+ },
8
+ "description": "The headless half of bahtui: schema types, rules, validation, workflow runtime and form session for form/workflow JSON. No DOM, no dependencies.",
9
+ "license": "MIT",
10
+ "author": "Nattapong Promthong",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/bank20baht/20baht.git",
14
+ "directory": "packages/core/engine"
15
+ },
16
+ "homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/engine#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/bank20baht/20baht/issues"
19
+ },
20
+ "keywords": [
21
+ "forms",
22
+ "workflow",
23
+ "rules-engine",
24
+ "validation",
25
+ "headless"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "scripts": {
42
+ "build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest",
45
+ "test:coverage": "vitest run --coverage"
46
+ },
47
+ "devDependencies": {
48
+ "typescript": "^5.8.3",
49
+ "vitest": "^3.2.4"
50
+ },
51
+ "main": "./dist/index.js",
52
+ "types": "./dist/index.d.ts",
53
+ "sideEffects": false
54
+ }