@20baht/validator 0.3.2 → 0.3.3

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/README.md CHANGED
@@ -98,8 +98,32 @@ new Elysia().post('/contact', ({ body }) => save(body), { body: formBody(contact
98
98
  whole of it. The types come from `defineForm` / `defineWorkflow`; a schema typed `FormDefinition`
99
99
  (parsed JSON, a stored definition) validates just the same and reads as `Record<string, unknown>`.
100
100
  The form is a [Standard Schema](https://standardschema.dev), which Elysia takes as a body since
101
- 1.4. An OpenAPI document lists the route without a request body: nothing static describes a form
102
- whose `required` a rule can change. Where the document matters, keep `validate` and a `t` body.
101
+ 1.4.
102
+
103
+ **OpenAPI and MCP.** The body also describes itself as JSON Schema (`jsonSchemaOf` of
104
+ `@20baht/engine`), so `@elysiajs/openapi` puts the form in the document as the route's request
105
+ body with no `t` schema beside it, and `@20baht/elysia-openapi-mcp` gives an agent a tool whose
106
+ arguments are the form's fields (label as `title`, help as `description`, option keys as `enum`,
107
+ lengths and bounds). The schema is a description, not the check: a form on its own lists its
108
+ `required` fields; a workflow lists none, because a rule can hide a field or lift `required`, and
109
+ `compare`, `custom` and `options_from` have no JSON Schema at all. The validator still decides,
110
+ and a refused call comes back as `422 { issues }`.
111
+
112
+ **The refusal, typed.** `formRoute(form, options?)` is `formBody` plus the 422 as a declared
113
+ response, so the answer is part of the route's type and of the document:
114
+
115
+ ```ts
116
+ new Elysia().post('/contact', ({ body }) => save(body), formRoute(contactForm, { registry }));
117
+
118
+ // an Eden client
119
+ const { error } = await api.contact.post(data);
120
+ if (error?.status === 422) error.value.issues[0].ref; // 'name' | 'age' | '$'
121
+ ```
122
+
123
+ `ref` is a field key, `lines[0].sku` for a repeater row, `$` for a script's own error
124
+ (`IssueRef`); a workflow's are `Form.key`. Spread it beside other options
125
+ (`{ ...formRoute(form), detail }`); a route that declares its own responses adds
126
+ `422: formIssues(form)` to them.
103
127
 
104
128
  ## Compatibility
105
129
 
package/dist/common.d.ts CHANGED
@@ -82,6 +82,36 @@ export type Validated<S, O = Record<never, never>> = {
82
82
  issues: ValidationIssue[];
83
83
  data: Record<string, unknown> | NestedData;
84
84
  };
85
+ /** The refs an issue of one form may carry: a field, a repeater row's column, or `$` (a script). */
86
+ type FormRefs<F> = F extends {
87
+ readonly fields: readonly (infer D)[];
88
+ } ? (keyof ValidValues<F> & string) | (D extends {
89
+ readonly type: 'repeater';
90
+ readonly key: infer K extends string;
91
+ readonly fields: readonly (infer Column)[];
92
+ } ? Column extends {
93
+ readonly key: infer C extends string;
94
+ } ? `${K}[${number}].${C}` : never : never) | (F extends {
95
+ readonly kind: 'approval';
96
+ } ? 'decision' | 'comment' : never) | '$' : string;
97
+ /**
98
+ * The `ref` of an issue of schema `S`: a field key for a form (`lines[0].sku` for a repeater
99
+ * row, `$` for a script's own error), `Form.key` for a workflow, a field key again with
100
+ * `{ form: 'Name' }`. A schema typed wide gives `string`.
101
+ */
102
+ export type IssueRef<S, O = Record<never, never>> = S extends {
103
+ readonly forms: readonly (infer F)[];
104
+ } ? string extends (F extends {
105
+ readonly form_name: infer N;
106
+ } ? N : never) ? string : O extends {
107
+ readonly form: infer N extends string;
108
+ } ? FormRefs<Extract<F, {
109
+ readonly form_name: N;
110
+ }>> : (F extends {
111
+ readonly form_name: infer N extends string;
112
+ } ? `${N}.${FormRefs<F>}` : never) | '$' : string extends keyof ValidValues<S & {
113
+ readonly fields: readonly unknown[];
114
+ }> ? string : FormRefs<S>;
85
115
  /** `fn` in `locale`'s catalog, the previous one put back after: the engine's, shared with the form session. */
86
116
  export { withLocale } from '@20baht/engine';
87
117
  /** Static blocks (`label`, `section`): no value, never in the payload, never validated. */
package/dist/elysia.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Elysia } from 'elysia';
2
- import { type SchemaDefinition, type SubmissionData, type ValidationIssue } from './index.js';
3
- import type { Locale, Registry } from '@20baht/engine';
2
+ import { type IssueRef, type SchemaDefinition, type SubmissionData, type ValidationIssue } from './index.js';
3
+ import { type JsonSchema, type Locale, type Registry } from '@20baht/engine';
4
4
  /** What `bahtValidator()` is configured with, once per app. */
5
5
  export interface ElysiaValidatorOptions {
6
6
  /** The registry the client uses: custom validators, submit scripts, option fetchers, lookups. */
@@ -234,6 +234,19 @@ export interface FormBody<Data> {
234
234
  readonly input: Data;
235
235
  readonly output: Data;
236
236
  };
237
+ /**
238
+ * The body as JSON Schema (Standard JSON Schema): what `@elysiajs/openapi` puts in the
239
+ * document. A description: see `jsonSchemaOf`. `target` is not read: the schema uses only
240
+ * what draft-07 and draft 2020-12 share.
241
+ */
242
+ readonly jsonSchema: {
243
+ readonly input: (options?: {
244
+ readonly target?: string;
245
+ }) => JsonSchema;
246
+ readonly output: (options?: {
247
+ readonly target?: string;
248
+ }) => JsonSchema;
249
+ };
237
250
  };
238
251
  }
239
252
  /**
@@ -245,8 +258,47 @@ export interface FormBody<Data> {
245
258
  * `422 { issues }`, exactly as the `validate` option does; a valid one reaches the handler as
246
259
  * `body`, the canonical data (defaults filled, hidden fields dropped, unknown keys gone), typed
247
260
  * from the schema when it is declared with `defineForm` / `defineWorkflow` (`SubmissionData`).
248
- * An Eden client of the route is asked for the same type.
261
+ * An Eden client of the route is asked for the same type, and an OpenAPI document
262
+ * (`@elysiajs/openapi`) describes the body from the form (`jsonSchemaOf`).
249
263
  *
250
264
  * Needs no plugin: the options `bahtValidator()` takes are the second argument. Elysia >= 1.4.
251
265
  */
252
266
  export declare function formBody<const T extends ValidateTarget>(target: T, options?: ElysiaValidatorOptions): FormBody<TargetData<T>>;
267
+ /** The refs the issues of `target` may carry: see `IssueRef`. */
268
+ export type TargetRef<T extends ValidateTarget> = T extends {
269
+ readonly schema: infer S;
270
+ readonly form: infer N;
271
+ } ? IssueRef<S, {
272
+ readonly form: N;
273
+ }> : IssueRef<T>;
274
+ /** The 422 answer of a route whose body is `target`: each issue's `ref` is one of its fields. */
275
+ export interface FormFailure<T extends ValidateTarget> {
276
+ issues: {
277
+ ref: TargetRef<T>;
278
+ message: string;
279
+ }[];
280
+ }
281
+ /**
282
+ * The `422 { issues }` a `formBody` route answers, as a response schema, so the answer is part
283
+ * of the route's type: an Eden client reads `error.value.issues[0].ref` as one of the form's
284
+ * field keys, and an OpenAPI document lists the 422.
285
+ *
286
+ * { body: formBody(contactForm), response: { 422: formIssues(contactForm) } }
287
+ *
288
+ * It describes the answer and checks nothing: `formBody` is what makes it.
289
+ */
290
+ export declare function formIssues<const T extends ValidateTarget>(_target: T): FormBody<FormFailure<T>>;
291
+ /**
292
+ * `formBody` and `formIssues` together, as the route's options:
293
+ *
294
+ * .post('/contact', ({ body }) => save(body), formRoute(contactForm, { registry }))
295
+ *
296
+ * Spread it beside other options (`{ ...formRoute(form), detail: { summary } }`). A route that
297
+ * declares responses of its own adds `422: formIssues(form)` to them instead.
298
+ */
299
+ export declare function formRoute<const T extends ValidateTarget>(target: T, options?: ElysiaValidatorOptions): {
300
+ body: FormBody<TargetData<T>>;
301
+ response: {
302
+ 422: FormBody<FormFailure<T>>;
303
+ };
304
+ };
package/dist/elysia.js CHANGED
@@ -16,6 +16,7 @@
16
16
  // ---------------------------------------------------------------------------
17
17
  import { Elysia, status } from 'elysia';
18
18
  import { validateSubmission, verifyOptions, verifyReferences, } from './index.js';
19
+ import { jsonSchemaOf } from '@20baht/engine';
19
20
  function split(target) {
20
21
  return 'schema' in target
21
22
  ? { schema: target.schema, form: target.form }
@@ -67,11 +68,14 @@ export function bahtValidator(options = {}) {
67
68
  * `422 { issues }`, exactly as the `validate` option does; a valid one reaches the handler as
68
69
  * `body`, the canonical data (defaults filled, hidden fields dropped, unknown keys gone), typed
69
70
  * from the schema when it is declared with `defineForm` / `defineWorkflow` (`SubmissionData`).
70
- * An Eden client of the route is asked for the same type.
71
+ * An Eden client of the route is asked for the same type, and an OpenAPI document
72
+ * (`@elysiajs/openapi`) describes the body from the form (`jsonSchemaOf`).
71
73
  *
72
74
  * Needs no plugin: the options `bahtValidator()` takes are the second argument. Elysia >= 1.4.
73
75
  */
74
76
  export function formBody(target, options = {}) {
77
+ const { schema, form } = split(target);
78
+ const describe = (io) => () => jsonSchemaOf(schema, { io, ...(form === undefined ? {} : { form }) });
75
79
  return {
76
80
  '~standard': {
77
81
  version: 1,
@@ -85,6 +89,57 @@ export function formBody(target, options = {}) {
85
89
  // the validator's promise: valid data has the shape the schema's types describe
86
90
  return { value: data };
87
91
  },
92
+ jsonSchema: { input: describe('input'), output: describe('output') },
88
93
  },
89
94
  };
90
95
  }
96
+ const ISSUES_SCHEMA = {
97
+ type: 'object',
98
+ title: 'The body was refused',
99
+ properties: {
100
+ issues: {
101
+ type: 'array',
102
+ items: {
103
+ type: 'object',
104
+ properties: {
105
+ ref: { type: 'string', description: 'The field at fault' },
106
+ message: { type: 'string' },
107
+ },
108
+ required: ['ref', 'message'],
109
+ },
110
+ },
111
+ },
112
+ required: ['issues'],
113
+ };
114
+ /**
115
+ * The `422 { issues }` a `formBody` route answers, as a response schema, so the answer is part
116
+ * of the route's type: an Eden client reads `error.value.issues[0].ref` as one of the form's
117
+ * field keys, and an OpenAPI document lists the 422.
118
+ *
119
+ * { body: formBody(contactForm), response: { 422: formIssues(contactForm) } }
120
+ *
121
+ * It describes the answer and checks nothing: `formBody` is what makes it.
122
+ */
123
+ export function formIssues(_target) {
124
+ const describe = () => ISSUES_SCHEMA;
125
+ return {
126
+ '~standard': {
127
+ version: 1,
128
+ vendor: '20baht',
129
+ // the answer is this package's own: there is nothing of a client's to check in it
130
+ validate: (value) => Promise.resolve({ value: value }),
131
+ jsonSchema: { input: describe, output: describe },
132
+ },
133
+ };
134
+ }
135
+ /**
136
+ * `formBody` and `formIssues` together, as the route's options:
137
+ *
138
+ * .post('/contact', ({ body }) => save(body), formRoute(contactForm, { registry }))
139
+ *
140
+ * Spread it beside other options (`{ ...formRoute(form), detail: { summary } }`). A route that
141
+ * declares responses of its own adds `422: formIssues(form)` to them instead.
142
+ */
143
+ export function formRoute(target, options = {}) {
144
+ return { body: formBody(target, options), response: { 422: formIssues(target) } };
145
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { SchemaDefinition, SubmissionData, ValidateOptions, Validated, ValidationIssue, ValidationResult, } from './common.js';
1
+ export type { SchemaDefinition, IssueRef, SubmissionData, ValidateOptions, Validated, ValidationIssue, ValidationResult, } from './common.js';
2
2
  export { isFormDefinition, isWorkflowDefinition } from './common.js';
3
3
  export { validateFormData, validateSubmission, validateWorkflowData } from './submission.js';
4
4
  export { verifyOptions, verifyReferences, type VerifyOptions } from './verify.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@20baht/validator",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
@@ -51,12 +51,13 @@
51
51
  "devDependencies": {
52
52
  "@20baht/engine": "workspace:*",
53
53
  "@20baht/formats": "workspace:*",
54
+ "@elysiajs/openapi": "^1.4.16",
54
55
  "elysia": "^1.4.0",
55
56
  "typescript": "^5.9.3",
56
57
  "vitest": "^3.2.4"
57
58
  },
58
59
  "peerDependencies": {
59
- "@20baht/engine": ">=0.3.2 <0.4.0",
60
+ "@20baht/engine": ">=0.3.3 <0.4.0",
60
61
  "elysia": ">=1.4.0 <2.0.0"
61
62
  },
62
63
  "peerDependenciesMeta": {