@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/dist/verify.js ADDED
@@ -0,0 +1,165 @@
1
+ import { t, } from '@20baht/engine';
2
+ import { isFormDefinition, isRecord, isWorkflowDefinition, ownEntry, withLocale, } from './common.js';
3
+ /**
4
+ * A catalog message read now, before the first `await`: the catalog is module-global, so by
5
+ * the time a lookup answers another request may have switched it.
6
+ */
7
+ function messageNow(key, options) {
8
+ return withLocale(options?.locale, () => t(key));
9
+ }
10
+ /** The forms of `schema` paired with their data, as the async checks walk them. */
11
+ function formSlices(schema, data, options) {
12
+ if (!isRecord(data))
13
+ return [];
14
+ if (isWorkflowDefinition(schema)) {
15
+ const only = options?.form;
16
+ if (only !== undefined) {
17
+ const form = schema.forms.find((f) => f.form_name === only);
18
+ return form ? [{ fields: form.fields, values: data, prefix: '' }] : [];
19
+ }
20
+ return schema.forms.flatMap((form) => {
21
+ const values = Object.hasOwn(data, form.form_name) ? data[form.form_name] : undefined;
22
+ return isRecord(values)
23
+ ? [{ fields: form.fields, values, prefix: `${form.form_name}.` }]
24
+ : [];
25
+ });
26
+ }
27
+ return isFormDefinition(schema) ? [{ fields: schema.fields, values: data, prefix: '' }] : [];
28
+ }
29
+ /**
30
+ * Do the records picked in `reference` fields exist? `validateSubmission` only checks that a
31
+ * reference value is an id string — existence needs the lookup, which is async. Call this
32
+ * after it, with the same registry the client uses:
33
+ *
34
+ * const result = validateSubmission(schema, body.data, registry);
35
+ * const missing = await verifyReferences(schema, result.data, registry);
36
+ *
37
+ * Each distinct `lookup + id` is resolved once (in parallel). An id `resolve` returns `null`
38
+ * for is an issue on that field ("Record not found"); a lookup the schema names but the
39
+ * registry lacks is an issue too; a lookup without `resolve` is trusted. Workflow refs are
40
+ * `form_name.key` (field keys with `{ form }`). Top-level fields only (reference fields
41
+ * inside repeater rows are not resolved).
42
+ */
43
+ export async function verifyReferences(schema, data, registry, options) {
44
+ const checks = [];
45
+ for (const { fields, values, prefix } of formSlices(schema, data, options)) {
46
+ for (const field of fields) {
47
+ if (field.type !== 'reference' || !Object.hasOwn(values, field.key))
48
+ continue;
49
+ const id = values[field.key];
50
+ if (typeof id === 'string' && id !== '') {
51
+ checks.push({ ref: `${prefix}${field.key}`, lookup: field.reference ?? '', id });
52
+ }
53
+ }
54
+ }
55
+ const notFound = messageNow('referenceNotFound', options);
56
+ const lookups = registry?.references ?? {};
57
+ const found = new Map();
58
+ const exists = (lookup, id) => {
59
+ const resolve = Object.hasOwn(lookups, lookup) ? lookups[lookup]?.resolve : undefined;
60
+ if (!resolve)
61
+ return null;
62
+ const key = `${lookup}\u0000${id}`;
63
+ let pending = found.get(key);
64
+ if (!pending) {
65
+ pending = Promise.resolve(resolve(id)).then((record) => record !== null, () => false);
66
+ found.set(key, pending);
67
+ }
68
+ return pending;
69
+ };
70
+ const issues = await Promise.all(checks.map(async ({ ref, lookup, id }) => {
71
+ if (!Object.hasOwn(lookups, lookup)) {
72
+ return { ref, message: `unknown reference lookup ${JSON.stringify(lookup)}` };
73
+ }
74
+ const pending = exists(lookup, id);
75
+ if (pending === null)
76
+ return null; // no resolver: trusted
77
+ return (await pending) ? null : { ref, message: notFound };
78
+ }));
79
+ return issues.filter((issue) => issue !== null);
80
+ }
81
+ /** The option keys a field's value picks, or null when the field has nothing to check. */
82
+ function pickedKeys(field, value) {
83
+ if (!field.options_from)
84
+ return null;
85
+ if (field.type === 'dropdown' || field.type === 'radio') {
86
+ return typeof value === 'string' && value !== '' ? [value] : null;
87
+ }
88
+ const listed = field.type === 'multiselect' || (field.type === 'tags' && field.allow_new === false);
89
+ if (!listed || !Array.isArray(value))
90
+ return null;
91
+ const keys = value.filter((v) => typeof v === 'string');
92
+ return keys.length > 0 ? keys : null;
93
+ }
94
+ /**
95
+ * Are the values of `options_from` fields among the options the fetcher offers?
96
+ * `validateSubmission` cannot tell (the options are async), so it trusts the client for
97
+ * them; call this after it, with the same registry the client uses:
98
+ *
99
+ * const result = validateSubmission(schema, body.data, registry);
100
+ * const issues = await verifyOptions(schema, result.data, registry);
101
+ *
102
+ * Each source is resolved once per form, as `registry.options[name](data)` with that form's
103
+ * data, exactly as `<baht-form>` calls it. Checked: `dropdown`, `radio`, `multiselect`, and
104
+ * `tags` with `allow_new: false` (case-insensitive), top-level fields and repeater columns
105
+ * (refs `key[i].sub`; a column's fetcher sees the form's data, as on the client). A key the
106
+ * fetcher does not offer is an issue with the static-dropdown message; a source the registry
107
+ * lacks, or a fetcher that throws or rejects, is an issue too (fail closed). Workflow refs are
108
+ * `form_name.key` (field keys with `{ form }`).
109
+ */
110
+ export async function verifyOptions(schema, data, registry, options) {
111
+ const notOffered = messageNow('pattern', options);
112
+ const sources = registry?.options ?? {};
113
+ const checks = [];
114
+ for (const { fields, values, prefix } of formSlices(schema, data, options)) {
115
+ const fetched = new Map();
116
+ const offered = (source) => () => {
117
+ let pending = fetched.get(source);
118
+ if (!pending) {
119
+ const fetch = ownEntry(sources, source);
120
+ pending = fetch
121
+ ? Promise.resolve()
122
+ .then(() => fetch(values))
123
+ .catch(() => null)
124
+ : Promise.resolve(null);
125
+ fetched.set(source, pending);
126
+ }
127
+ return pending;
128
+ };
129
+ const add = (field, value, ref) => {
130
+ const keys = pickedKeys(field, value);
131
+ const source = field.options_from;
132
+ if (!keys || !source)
133
+ return;
134
+ checks.push({ ref, source, keys, caseless: field.type === 'tags', offered: offered(source) });
135
+ };
136
+ for (const field of fields) {
137
+ if (!Object.hasOwn(values, field.key))
138
+ continue;
139
+ const value = values[field.key];
140
+ add(field, value, `${prefix}${field.key}`);
141
+ if (field.type !== 'repeater' || !Array.isArray(value))
142
+ continue;
143
+ value.forEach((row, i) => {
144
+ if (!isRecord(row))
145
+ return;
146
+ for (const sub of field.fields ?? []) {
147
+ if (Object.hasOwn(row, sub.key))
148
+ add(sub, row[sub.key], `${prefix}${field.key}[${i}].${sub.key}`);
149
+ }
150
+ });
151
+ }
152
+ }
153
+ const issues = await Promise.all(checks.map(async ({ ref, source, keys, caseless, offered }) => {
154
+ if (!ownEntry(sources, source)) {
155
+ return { ref, message: `unknown options source ${JSON.stringify(source)}` };
156
+ }
157
+ const list = await offered();
158
+ if (list === null)
159
+ return { ref, message: `options source ${JSON.stringify(source)} failed` };
160
+ const norm = (k) => (caseless ? k.toLowerCase() : k);
161
+ const allowed = new Set(list.map((o) => norm(o.key)));
162
+ return keys.every((k) => allowed.has(norm(k))) ? null : { ref, message: notOffered };
163
+ }));
164
+ return issues.filter((issue) => issue !== null);
165
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@20baht/validator",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Runtime validation for bahtui form/workflow JSON — the exact engine rules the client runs, on the server.",
6
+ "license": "MIT",
7
+ "author": "Nattapong Promthong",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/bank20baht/20baht.git",
11
+ "directory": "packages/core/validator"
12
+ },
13
+ "homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/validator#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/bank20baht/20baht/issues"
16
+ },
17
+ "keywords": [
18
+ "forms",
19
+ "workflow",
20
+ "validation",
21
+ "server"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "./elysia": {
36
+ "types": "./dist/elysia.d.ts",
37
+ "import": "./dist/elysia.js",
38
+ "default": "./dist/elysia.js"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "scripts": {
43
+ "build": "rm -rf dist && tsc -p tsconfig.json",
44
+ "test": "vitest run",
45
+ "test:watch": "vitest",
46
+ "test:coverage": "vitest run --coverage"
47
+ },
48
+ "devDependencies": {
49
+ "@20baht/engine": "workspace:*",
50
+ "elysia": "^1.4.0",
51
+ "typescript": "^5.8.3",
52
+ "vitest": "^3.2.4"
53
+ },
54
+ "peerDependencies": {
55
+ "@20baht/engine": ">=0.1.0 <0.2.0",
56
+ "elysia": ">=1.4.0 <2.0.0"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "elysia": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "main": "./dist/index.js",
64
+ "types": "./dist/index.d.ts",
65
+ "sideEffects": false
66
+ }