@cslug/validation 0.0.0-stage → 0.2.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/README.md +6 -2
- package/docs/README.md +48 -0
- package/docs/api.md +96 -0
- package/package.json +28 -4
- package/src/composites.ts +190 -0
- package/src/config.ts +10 -0
- package/src/domain.ts +242 -0
- package/src/icu.ts +95 -0
- package/src/index.ts +52 -0
- package/src/issue.ts +115 -0
- package/src/primitives.ts +305 -0
- package/src/schema.ts +268 -0
- package/src/standard-schema.ts +37 -0
- package/src/v.ts +75 -0
- package/src/validator.ts +81 -0
package/src/schema.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { formatMessage, type Issue, ValidationError } from './issue'
|
|
2
|
+
import type { StandardSchemaV1 } from './standard-schema'
|
|
3
|
+
|
|
4
|
+
/** Returned by `_run` when the value is invalid (issues were already recorded). */
|
|
5
|
+
export const INVALID: unique symbol = Symbol('cslug.invalid')
|
|
6
|
+
export type Invalid = typeof INVALID
|
|
7
|
+
|
|
8
|
+
export type Ctx = {
|
|
9
|
+
path: (string | number)[]
|
|
10
|
+
issues: Issue[]
|
|
11
|
+
/** Async refinements collected during `parseAsync`; null in `parse()` (sync). */
|
|
12
|
+
pending: Promise<void>[] | null
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type JsonSchema = Record<string, unknown>
|
|
16
|
+
|
|
17
|
+
type Refinement<T> = {
|
|
18
|
+
check: (value: T) => boolean | Promise<boolean>
|
|
19
|
+
message: string
|
|
20
|
+
code: string
|
|
21
|
+
path: (string | number)[]
|
|
22
|
+
params?: Record<string, unknown>
|
|
23
|
+
async: boolean
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type Def = {
|
|
27
|
+
description?: string
|
|
28
|
+
/** Custom message key used for every issue this schema reports (e.g. `bookings.terms_required`). */
|
|
29
|
+
message?: string
|
|
30
|
+
secret?: boolean
|
|
31
|
+
// biome-ignore lint/suspicious/noExplicitAny: refinements of any output type
|
|
32
|
+
refines?: Refinement<any>[]
|
|
33
|
+
[key: string]: unknown
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type RefineOptions = { message?: string; path?: (string | number)[]; params?: Record<string, unknown> }
|
|
37
|
+
|
|
38
|
+
export type SafeParseResult<T> = { success: true; data: T } | { success: false; error: ValidationError }
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Base class of every cslug schema. Schemas are immutable: every modifier returns a new schema.
|
|
42
|
+
* `Out` is the parsed type (`v.infer`), `In` the accepted input type (`v.input`).
|
|
43
|
+
*/
|
|
44
|
+
export abstract class Schema<Out = unknown, In = Out> implements StandardSchemaV1<In, Out> {
|
|
45
|
+
declare readonly _output: Out
|
|
46
|
+
declare readonly _input: In
|
|
47
|
+
_def: Def
|
|
48
|
+
|
|
49
|
+
constructor(def: Def = {}) {
|
|
50
|
+
this._def = def
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Validate the type and the schema's own rules. Record issues in `ctx` and return INVALID on failure. */
|
|
54
|
+
abstract _run(value: unknown, ctx: Ctx): Out | Invalid
|
|
55
|
+
|
|
56
|
+
/** JSON Schema for this schema alone (no `$schema`). */
|
|
57
|
+
abstract _json(): JsonSchema
|
|
58
|
+
|
|
59
|
+
/** Run the schema and its refinements. */
|
|
60
|
+
_parse(value: unknown, ctx: Ctx): Out | Invalid {
|
|
61
|
+
const result = this._run(value, ctx)
|
|
62
|
+
if (result === INVALID) return result
|
|
63
|
+
for (const r of this._def.refines ?? []) {
|
|
64
|
+
const at = [...ctx.path, ...r.path]
|
|
65
|
+
const report = () => {
|
|
66
|
+
ctx.issues.push({ path: at, code: r.code, message: r.message, params: r.params })
|
|
67
|
+
}
|
|
68
|
+
if (r.async) {
|
|
69
|
+
if (!ctx.pending) throw new Error('This schema has async refinements: use parseAsync() instead of parse().')
|
|
70
|
+
ctx.pending.push(Promise.resolve(r.check(result)).then((ok) => (ok ? undefined : report())))
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
if (!(r.check(result) as boolean)) report()
|
|
74
|
+
}
|
|
75
|
+
return result
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Record an issue at the current path, using the schema's custom message if it has one. */
|
|
79
|
+
protected _issue(ctx: Ctx, code: string, params?: Record<string, unknown>): Invalid {
|
|
80
|
+
ctx.issues.push({ path: [...ctx.path], code, message: this._def.message ?? `validation.${code}`, params })
|
|
81
|
+
return INVALID
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Clone with a patched definition (schemas are immutable). */
|
|
85
|
+
protected _with(patch: Def): this {
|
|
86
|
+
const copy = Object.create(Object.getPrototypeOf(this)) as this
|
|
87
|
+
Object.assign(copy, this)
|
|
88
|
+
copy._def = { ...this._def, ...patch }
|
|
89
|
+
return copy
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Parse or throw `ValidationError`. */
|
|
93
|
+
parse(value: unknown): Out {
|
|
94
|
+
const ctx: Ctx = { path: [], issues: [], pending: null }
|
|
95
|
+
const result = this._parse(value, ctx)
|
|
96
|
+
if (ctx.issues.length || result === INVALID) throw new ValidationError(ctx.issues)
|
|
97
|
+
return result
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Parse with async refinements (for example a file's type sniffed from its bytes). */
|
|
101
|
+
async parseAsync(value: unknown): Promise<Out> {
|
|
102
|
+
const ctx: Ctx = { path: [], issues: [], pending: [] }
|
|
103
|
+
const result = this._parse(value, ctx)
|
|
104
|
+
await Promise.all(ctx.pending ?? [])
|
|
105
|
+
if (ctx.issues.length || result === INVALID) throw new ValidationError(ctx.issues)
|
|
106
|
+
return result
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
safeParse(value: unknown): SafeParseResult<Out> {
|
|
110
|
+
try {
|
|
111
|
+
return { success: true, data: this.parse(value) }
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e instanceof ValidationError) return { success: false, error: e }
|
|
114
|
+
throw e
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ── modifiers ────────────────────────────────────────────────────────────────────────────────────
|
|
119
|
+
optional(): OptionalSchema<this> {
|
|
120
|
+
return new OptionalSchema(this)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
nullable(): NullableSchema<this> {
|
|
124
|
+
return new NullableSchema(this)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Value used when the input is `undefined`. Pass a function for fresh objects/arrays. */
|
|
128
|
+
default(value: Exclude<Out, undefined> | (() => Exclude<Out, undefined>)): DefaultSchema<this> {
|
|
129
|
+
return new DefaultSchema(this, value)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Human description, exported to JSON Schema (and so to AI tools and OpenAPI). */
|
|
133
|
+
describe(description: string): this {
|
|
134
|
+
return this._with({ description })
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Extra rule on the parsed value. Fails with `message` (a translation key) at `path` (relative). */
|
|
138
|
+
refine(check: (value: Out) => boolean, options: RefineOptions = {}): this {
|
|
139
|
+
return this._addRefine(check, options, false)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Async rule; requires `parseAsync()`. */
|
|
143
|
+
refineAsync(check: (value: Out) => Promise<boolean>, options: RefineOptions = {}): this {
|
|
144
|
+
return this._addRefine(check, options, true)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
protected _addRefine(check: Refinement<Out>['check'], options: RefineOptions, async: boolean): this {
|
|
148
|
+
const refinement: Refinement<Out> = {
|
|
149
|
+
check,
|
|
150
|
+
message: options.message ?? this._def.message ?? 'validation.custom',
|
|
151
|
+
code: 'custom',
|
|
152
|
+
path: options.path ?? [],
|
|
153
|
+
params: options.params,
|
|
154
|
+
async,
|
|
155
|
+
}
|
|
156
|
+
return this._with({ refines: [...(this._def.refines ?? []), refinement] })
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Map the parsed value to another type. */
|
|
160
|
+
transform<T>(fn: (value: Out) => T): TransformSchema<T, In> {
|
|
161
|
+
return new TransformSchema<T, In>(this as unknown as Schema<unknown, In>, fn as (value: unknown) => T)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** JSON Schema (draft 2020-12) describing the accepted input. */
|
|
165
|
+
toJSONSchema(): JsonSchema {
|
|
166
|
+
return { $schema: 'https://json-schema.org/draft/2020-12/schema', ...this._json() }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Shared JSON Schema fields: description, writeOnly for secrets. */
|
|
170
|
+
protected _jsonMeta(schema: JsonSchema): JsonSchema {
|
|
171
|
+
return {
|
|
172
|
+
...schema,
|
|
173
|
+
...(this._def.description ? { description: this._def.description } : {}),
|
|
174
|
+
...(this._def.secret ? { writeOnly: true } : {}),
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ── Standard Schema ──────────────────────────────────────────────────────────────────────────────
|
|
179
|
+
get '~standard'(): StandardSchemaV1.Props<In, Out> {
|
|
180
|
+
return {
|
|
181
|
+
version: 1,
|
|
182
|
+
vendor: 'cslug',
|
|
183
|
+
validate: async (value: unknown) => {
|
|
184
|
+
try {
|
|
185
|
+
return { value: await this.parseAsync(value) }
|
|
186
|
+
} catch (e) {
|
|
187
|
+
if (!(e instanceof ValidationError)) throw e
|
|
188
|
+
return { issues: e.issues.map((i) => ({ message: formatMessage(i), path: i.path })) }
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** `undefined` is accepted and returned as is. */
|
|
196
|
+
export class OptionalSchema<S extends Schema> extends Schema<S['_output'] | undefined, S['_input'] | undefined> {
|
|
197
|
+
constructor(readonly inner: S) {
|
|
198
|
+
super({})
|
|
199
|
+
}
|
|
200
|
+
_run(value: unknown, ctx: Ctx) {
|
|
201
|
+
return value === undefined ? undefined : this.inner._parse(value, ctx)
|
|
202
|
+
}
|
|
203
|
+
_json() {
|
|
204
|
+
return this._jsonMeta(this.inner._json())
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** `null` is accepted and returned as is. */
|
|
209
|
+
export class NullableSchema<S extends Schema> extends Schema<S['_output'] | null, S['_input'] | null> {
|
|
210
|
+
constructor(readonly inner: S) {
|
|
211
|
+
super({})
|
|
212
|
+
}
|
|
213
|
+
_run(value: unknown, ctx: Ctx) {
|
|
214
|
+
return value === null ? null : this.inner._parse(value, ctx)
|
|
215
|
+
}
|
|
216
|
+
_json() {
|
|
217
|
+
return this._jsonMeta({ anyOf: [this.inner._json(), { type: 'null' }] })
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** `undefined` becomes the default value; the output is never undefined. */
|
|
222
|
+
export class DefaultSchema<S extends Schema> extends Schema<Exclude<S['_output'], undefined>, S['_input'] | undefined> {
|
|
223
|
+
constructor(
|
|
224
|
+
readonly inner: S,
|
|
225
|
+
readonly fallback: Exclude<S['_output'], undefined> | (() => Exclude<S['_output'], undefined>),
|
|
226
|
+
) {
|
|
227
|
+
super({})
|
|
228
|
+
}
|
|
229
|
+
_run(value: unknown, ctx: Ctx) {
|
|
230
|
+
if (value === undefined) {
|
|
231
|
+
return typeof this.fallback === 'function'
|
|
232
|
+
? (this.fallback as () => Exclude<S['_output'], undefined>)()
|
|
233
|
+
: this.fallback
|
|
234
|
+
}
|
|
235
|
+
return this.inner._parse(value, ctx) as Exclude<S['_output'], undefined> | Invalid
|
|
236
|
+
}
|
|
237
|
+
_json() {
|
|
238
|
+
const fallback = typeof this.fallback === 'function' ? undefined : this.fallback
|
|
239
|
+
const serializable = typeof fallback === 'bigint' ? String(fallback) : fallback
|
|
240
|
+
return this._jsonMeta({ ...this.inner._json(), ...(serializable === undefined ? {} : { default: serializable }) })
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export class TransformSchema<Out, In> extends Schema<Out, In> {
|
|
245
|
+
constructor(
|
|
246
|
+
readonly inner: Schema<unknown, In>,
|
|
247
|
+
readonly fn: (value: unknown) => Out,
|
|
248
|
+
) {
|
|
249
|
+
super({})
|
|
250
|
+
}
|
|
251
|
+
_run(value: unknown, ctx: Ctx) {
|
|
252
|
+
const r = this.inner._parse(value, ctx)
|
|
253
|
+
return r === INVALID ? r : this.fn(r)
|
|
254
|
+
}
|
|
255
|
+
_json() {
|
|
256
|
+
return this._jsonMeta(this.inner._json())
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Accepts anything (escape hatch). */
|
|
261
|
+
export class UnknownSchema extends Schema<unknown> {
|
|
262
|
+
_run(value: unknown) {
|
|
263
|
+
return value
|
|
264
|
+
}
|
|
265
|
+
_json() {
|
|
266
|
+
return this._jsonMeta({})
|
|
267
|
+
}
|
|
268
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Standard Schema v1 interface (https://standardschema.dev), copied as the spec recommends so that no
|
|
3
|
+
* dependency is needed. Any library implementing it (Zod, Valibot, ArkType) is accepted where cslug takes a schema.
|
|
4
|
+
*/
|
|
5
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
6
|
+
readonly '~standard': StandardSchemaV1.Props<Input, Output>
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export declare namespace StandardSchemaV1 {
|
|
10
|
+
interface Props<Input = unknown, Output = Input> {
|
|
11
|
+
readonly version: 1
|
|
12
|
+
readonly vendor: string
|
|
13
|
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>
|
|
14
|
+
readonly types?: Types<Input, Output> | undefined
|
|
15
|
+
}
|
|
16
|
+
type Result<Output> = SuccessResult<Output> | FailureResult
|
|
17
|
+
interface SuccessResult<Output> {
|
|
18
|
+
readonly value: Output
|
|
19
|
+
readonly issues?: undefined
|
|
20
|
+
}
|
|
21
|
+
interface FailureResult {
|
|
22
|
+
readonly issues: ReadonlyArray<Issue>
|
|
23
|
+
}
|
|
24
|
+
interface Issue {
|
|
25
|
+
readonly message: string
|
|
26
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined
|
|
27
|
+
}
|
|
28
|
+
interface PathSegment {
|
|
29
|
+
readonly key: PropertyKey
|
|
30
|
+
}
|
|
31
|
+
interface Types<Input = unknown, Output = Input> {
|
|
32
|
+
readonly input: Input
|
|
33
|
+
readonly output: Output
|
|
34
|
+
}
|
|
35
|
+
type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input']
|
|
36
|
+
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output']
|
|
37
|
+
}
|
package/src/v.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `v` namespace: `import { v } from '@cslug/validation'`, then `v.object({ … })`, `v.infer<typeof X>`.
|
|
3
|
+
*/
|
|
4
|
+
import { ArraySchema, ObjectSchema, RecordSchema, type Shape, UnionSchema } from './composites'
|
|
5
|
+
import { CountrySchema, CurrencySchema, FileSchema, MoneySchema, PhoneSchema } from './domain'
|
|
6
|
+
import {
|
|
7
|
+
BigIntSchema,
|
|
8
|
+
BooleanSchema,
|
|
9
|
+
DateSchema,
|
|
10
|
+
DateTimeSchema,
|
|
11
|
+
EnumSchema,
|
|
12
|
+
LiteralSchema,
|
|
13
|
+
NumberSchema,
|
|
14
|
+
type Primitive,
|
|
15
|
+
StringSchema,
|
|
16
|
+
} from './primitives'
|
|
17
|
+
import { type Schema, UnknownSchema } from './schema'
|
|
18
|
+
|
|
19
|
+
/** The parsed type: `v.infer<typeof StoreTodoValidator>`. */
|
|
20
|
+
export type infer<T extends Schema> = T['_output']
|
|
21
|
+
/** The accepted input type, before parsing (what a form holds): `v.input<typeof StoreTodoValidator>`. */
|
|
22
|
+
export type input<T extends Schema> = T['_input']
|
|
23
|
+
|
|
24
|
+
export const string = () => new StringSchema()
|
|
25
|
+
export const email = () => new StringSchema().trim().email()
|
|
26
|
+
export const url = () => new StringSchema().trim().url()
|
|
27
|
+
export const uuid = () => new StringSchema().uuid()
|
|
28
|
+
export const uuid7 = () => new StringSchema().uuid7()
|
|
29
|
+
/** A string that must never be logged or shown: redacted by the logger and `cslug config:show`. */
|
|
30
|
+
export const secret = () => new StringSchema({ secret: true })
|
|
31
|
+
export const number = () => new NumberSchema()
|
|
32
|
+
export const int = () => new NumberSchema().int()
|
|
33
|
+
/** An integer as bigint; accepts bigint, a safe integer, or a string of digits. */
|
|
34
|
+
export const bigint = () => new BigIntSchema()
|
|
35
|
+
/** Money in minor units as bigint (`"220000"` → `220000n`). */
|
|
36
|
+
export const amount = () => new BigIntSchema()
|
|
37
|
+
export const boolean = () => new BooleanSchema()
|
|
38
|
+
/** A calendar date, `'YYYY-MM-DD'`. */
|
|
39
|
+
export const date = () => new DateSchema()
|
|
40
|
+
/** An instant, as a `Date` (ISO 8601 input). */
|
|
41
|
+
export const datetime = () => new DateTimeSchema()
|
|
42
|
+
export const unknown = () => new UnknownSchema()
|
|
43
|
+
|
|
44
|
+
const enum_ = <const T extends readonly [string, ...string[]]>(options: T) => new EnumSchema(options)
|
|
45
|
+
|
|
46
|
+
export { enum_ as enum }
|
|
47
|
+
export const literal = <const T extends Primitive>(value: T, options: { message?: string } = {}) =>
|
|
48
|
+
new LiteralSchema(value, options.message)
|
|
49
|
+
|
|
50
|
+
export const object = <S extends Shape>(shape: S) => new ObjectSchema(shape)
|
|
51
|
+
export const array = <T extends Schema>(element: T) => new ArraySchema(element)
|
|
52
|
+
export const union = <const T extends readonly [Schema, ...Schema[]]>(options: T) => new UnionSchema(options)
|
|
53
|
+
export const record = <T extends Schema>(value: T) => new RecordSchema(value)
|
|
54
|
+
|
|
55
|
+
export const currency = <const C extends string = string>(only?: readonly C[]) => new CurrencySchema<C>(only)
|
|
56
|
+
export const money = <const C extends string = string>(
|
|
57
|
+
options: { currencies?: readonly C[]; min?: bigint | number; max?: bigint | number } = {},
|
|
58
|
+
) => new MoneySchema<C>(options)
|
|
59
|
+
/** ISO 3166-1 alpha-2, normalised to upper case. */
|
|
60
|
+
export const country = () => new CountrySchema()
|
|
61
|
+
/** Normalised to E.164 (`+261341234567`). With `defaultCountry`, national numbers are accepted. */
|
|
62
|
+
export const phone = (options: { defaultCountry?: string } = {}) => new PhoneSchema(options.defaultCountry)
|
|
63
|
+
export const file = (options: { maxSize?: string | number; types?: readonly string[] } = {}) => new FileSchema(options)
|
|
64
|
+
|
|
65
|
+
/** Schemas that convert strings first: for query strings, form posts and env vars. */
|
|
66
|
+
export const coerce = {
|
|
67
|
+
string: () => new StringSchema({ coerce: true }),
|
|
68
|
+
number: () => new NumberSchema({ coerce: true }),
|
|
69
|
+
int: () => new NumberSchema({ coerce: true }).int(),
|
|
70
|
+
/** `'1'`, `'on'`, `'true'`, `'yes'` → true; `'0'`, `'off'`, `'false'`, `'no'`, `''` and absent → false. */
|
|
71
|
+
boolean: () => new BooleanSchema({ coerce: true }),
|
|
72
|
+
bigint: () => new BigIntSchema(),
|
|
73
|
+
/** A Date from an ISO string, a Date, or epoch milliseconds. */
|
|
74
|
+
date: () => new DateTimeSchema({ coerce: true }),
|
|
75
|
+
}
|
package/src/validator.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type Issue, ValidationError } from './issue'
|
|
2
|
+
import { Schema } from './schema'
|
|
3
|
+
import type { StandardSchemaV1 } from './standard-schema'
|
|
4
|
+
|
|
5
|
+
/** Add an error from `Validator.after()`: `fail('email', 'validation.unique')`. */
|
|
6
|
+
export type Fail = (path: string, message: string, params?: Record<string, unknown>) => void
|
|
7
|
+
|
|
8
|
+
/** The optional hook a Validator subclass may define: runs after the schema passed, with the parsed data. */
|
|
9
|
+
export type AfterHook = (data: never, fail: Fail) => void | Promise<void>
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A validator class, for validation that needs services (database checks) or custom messages. The container
|
|
13
|
+
* builds it (constructor injection with `@inject(...)`), so it can use repositories.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* @inject(OperatorRepository)
|
|
17
|
+
* export class RegisterOperatorValidator extends Validator {
|
|
18
|
+
* constructor(private operators: OperatorRepository) { super() }
|
|
19
|
+
* schema = v.object({ email: v.email() })
|
|
20
|
+
* async after(data: v.infer<this['schema']>, fail: Fail) {
|
|
21
|
+
* if (await this.operators.existsBy({ email: data.email })) fail('email', 'validation.unique')
|
|
22
|
+
* }
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export abstract class Validator {
|
|
27
|
+
abstract readonly schema: Schema
|
|
28
|
+
|
|
29
|
+
// `after(data, fail)` is an optional hook that subclasses may define. It is deliberately NOT declared here, so
|
|
30
|
+
// that apps compiled with `noImplicitOverride` don't have to write `override after(...)`.
|
|
31
|
+
|
|
32
|
+
/** Parse with the schema, then run `after`. Throws `ValidationError` with every problem found. */
|
|
33
|
+
async validate(input: unknown): Promise<this['schema']['_output']> {
|
|
34
|
+
const data = await this.schema.parseAsync(input)
|
|
35
|
+
const after = (this as { after?: AfterHook }).after
|
|
36
|
+
if (typeof after !== 'function') return data
|
|
37
|
+
const issues: Issue[] = []
|
|
38
|
+
const fail: Fail = (path, message, params) => {
|
|
39
|
+
issues.push({ path: path === '' ? [] : path.split('.'), code: 'custom', message, params })
|
|
40
|
+
}
|
|
41
|
+
await after.call(this, data as never, fail)
|
|
42
|
+
if (issues.length) throw new ValidationError(issues)
|
|
43
|
+
return data
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** What `validate()` accepts: a cslug schema, a Validator instance, or any Standard Schema (Zod, Valibot, …). */
|
|
48
|
+
export type Validatable = Schema | Validator | StandardSchemaV1
|
|
49
|
+
|
|
50
|
+
/** The parsed type of a validatable. */
|
|
51
|
+
export type Output<T> =
|
|
52
|
+
T extends Schema<infer O, unknown>
|
|
53
|
+
? O
|
|
54
|
+
: T extends Validator
|
|
55
|
+
? T['schema']['_output']
|
|
56
|
+
: T extends StandardSchemaV1
|
|
57
|
+
? StandardSchemaV1.InferOutput<T>
|
|
58
|
+
: never
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Validate input against a schema, a Validator instance or a Standard Schema. Always async (file sniffing,
|
|
62
|
+
* `after()` hooks). Used by `request.validate()`, job payloads and AI tool inputs.
|
|
63
|
+
*/
|
|
64
|
+
export async function validate<T extends Validatable>(target: T, input: unknown): Promise<Output<T>> {
|
|
65
|
+
if (target instanceof Schema) return (await target.parseAsync(input)) as Output<T>
|
|
66
|
+
if (target instanceof Validator) return (await target.validate(input)) as Output<T>
|
|
67
|
+
const result = await target['~standard'].validate(input)
|
|
68
|
+
if (result.issues) {
|
|
69
|
+
throw new ValidationError(
|
|
70
|
+
result.issues.map((i) => ({
|
|
71
|
+
path: (i.path ?? []).map((p) => {
|
|
72
|
+
const key = typeof p === 'object' ? p.key : p
|
|
73
|
+
return typeof key === 'number' ? key : String(key)
|
|
74
|
+
}),
|
|
75
|
+
code: 'custom',
|
|
76
|
+
message: i.message,
|
|
77
|
+
})),
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
return result.value as Output<T>
|
|
81
|
+
}
|