@samveys/validator
Dari packages/validator/README.md di repository framework.
Halaman ini belum diterjemahkan. Kamu sedang membaca versi bahasa Inggris.
@samveys/validator provides immutable, typed schemas that implement Standard Schema v1 (vendor: 'samveys'). Schemas can parse values synchronously or validate through the Standard Schema interface; @samveys/http accepts them directly. The examples below are checked against the public exports and types (tested).
1. Install
Samveys packages are internal-only. Use the organization’s restricted registry and workspace tooling; never publish or install this package through the public npm registry. In this monorepo, @samveys/validator is a workspace package.
2. Builders
Import schema and compose schemas for primitives and collections. Infer<S> extracts the output type, and InferInput<S> extracts the accepted input type.
| Builder | Accepted value and output | Example |
|---|---|---|
schema.string() | String | schema.string().email() |
schema.number() | Finite number | schema.number().int().positive() |
schema.coerceNumber() | Number or numeric string → number | schema.coerceNumber().int() |
schema.boolean() | Boolean | schema.boolean() |
schema.coerceBoolean() | Boolean or 'true', 'false', '1', '0' → boolean | schema.coerceBoolean() |
schema.literal(value) | Exact string, number, boolean, or null | schema.literal('active') |
schema.enum(values) | One string from a non-empty tuple | schema.enum(['admin', 'user']) |
schema.array(item) | Array validated item-by-item | schema.array(schema.string()) |
schema.object(shape) | Object described by its fields | schema.object({ name: schema.string() }) |
schema.union(members) | Output of the first matching member | schema.union([schema.string(), schema.number()]) |
schema.record(value) | Record whose values use one schema | schema.record(schema.number()) |
schema.unknown() | Any value | schema.unknown() |
import { schema } from '@samveys/validator'
import type { Infer, InferInput } from '@samveys/validator'
const userSchema = schema.object({
name: schema.string().trim().min(1),
role: schema.enum(['admin', 'member']),
age: schema.coerceNumber().int().optional(),
})
type User = Infer<typeof userSchema>
type UserInput = InferInput<typeof userSchema>
const user: User = userSchema.parse({ name: ' Ada ', role: 'admin', age: '37' })
const input: UserInput = { name: 'Ada', role: 'member', age: 37 }
void user
void input3. Modifiers
Modifiers return new schema instances; they do not mutate the original schema. The common Schema modifiers are optional(), nullable(), default(valueOrFactory), refine(predicate, message), and transform(mapper). Strings also support min, max, length, email, url, uuid, regex, trim, and toLowerCase. Numbers support min, max, int, and positive; arrays support min and max.
Object schemas support extend, pick, omit, and partial.
import { schema } from '@samveys/validator'
const original = schema.string()
const normalized = original.trim().toLowerCase().min(2)
const optionalName = normalized.optional()
const withDefault = schema.string().optional().default('guest')
const even = schema.number().int().refine((value) => value % 2 === 0, 'Must be even')
const labelLength = schema.string().transform((value) => value.length)
void original
void optionalName
void withDefault
void even
void labelLengthModifier order matters: .optional().default(x) keeps the default, but .default(x).optional() drops it. Put default() after optional() when the default should apply to an absent value.
4. Object unknown-key modes
Object schemas strip unknown keys by default. .strip() selects that behavior explicitly; .strict() reports unknown keys as issues; .passthrough() copies unknown keys except __proto__, constructor, and prototype. Parsed object and record outputs are prototype-less objects.
import { schema } from '@samveys/validator'
const fields = { name: schema.string() }
const strip = schema.object(fields).parse({ name: 'Ada', extra: true })
const strict = schema.object(fields).strict().safeParse({ name: 'Ada', extra: true })
const passthrough = schema.object(fields).passthrough().parse({ name: 'Ada', extra: true })
void strip
void strict
void passthrough5. Standard Schema interop
Every built-in schema implements Standard Schema v1 and can be passed directly to packages that accept that contract. parse() throws ValidationError with all issues; safeParse() returns a Standard Schema success or failure result without throwing. Foreign Standard Schema objects can be nested in objects, arrays, unions, and records. Their validators may be asynchronous when used through ['~standard'].validate() or by an integrating package.
import type { StandardSchemaV1 } from '@samveys/core'
import { schema, ValidationError } from '@samveys/validator'
const upper = {
'~standard': {
version: 1,
vendor: 'example',
validate(value: unknown) {
return typeof value === 'string'
? { value: value.toUpperCase() }
: { issues: [{ message: 'Expected string' }] }
},
},
} satisfies StandardSchemaV1<string, string>
const combined = schema.object({ label: upper })
const parsed = combined.parse({ label: 'hello' })
const result = combined.safeParse({ label: 4 })
try {
combined.parse({ label: 4 })
} catch (error) {
if (error instanceof ValidationError) console.log(error.issues)
}
void parsed
void result6. Union failures
schema.union([...]) tries members in order and returns the first successful result. If no member matches, it reports one issue at the union path (No union member matched); it does not combine the individual member failures.
import { schema } from '@samveys/validator'
const id = schema.union([schema.string(), schema.coerceNumber()])
const result = id.safeParse(true)
// result.issues contains one issue: “No union member matched”.
void result7. Reference
Value exports from @samveys/validator:
| Export | Purpose |
|---|---|
schema | Schema builder for primitive, object, array, union, and record schemas. |
ValidationError | Error thrown by parse() with structured issues. |