Write it like Zod. It won all 12 cells of our workload bench.
s is a schema library with the chain you already know, compiled to one flat function on first parse. The same schema runs light in the browser and strict on the server, and Zod, Valibot or ArkType schemas plug into every Pyreon package that takes one.
bun add @pyreon/validate - workload bench
- 12 of 12 cells fastestvs Zod, Valibot, ArkType; one run.
- results
parse()never throws{ ok, value }or{ ok, issues };parseOrThrow()when you want one.- also accepts
- Zod, Valibot, ArkTypeAny Standard Schema, in forms, stores and state trees.
- mini entry
- 5.2 KB gz for a 4-field schemaNext release, author-measured; 13.8 KB through the main entry.
- 12 / 12 cells won on a multi-schema workload against Zod, Valibot and ArkType.BENCHMARKS.md §9 'Validate — multi-schema megamorphic workload', final pass 2026-11-05, one run
- 18 / 24 cells won or tied in a 10-library bench, including every invalid-input parse.BENCHMARKS.md §9 'Validate — 10-library protocol bench', final pass, one run
- 1.40× faster than Zod rejecting a bad string: the closest of the twelve cells (34.9 vs 48.7 ns).BENCHMARKS.md §9 megamorphic, invalid scalar string, one run
synthetic · author-run · M3 Max · record of 2026-11-05
Every result, including where we lose →Why it is worth a new import.
Fast where forms and APIs live
Each schema compiles to one monomorphic function the first time it parses. Rejecting bad input, which every form and endpoint does all day, is where it is strongest: in the 10-library bench it never loses an invalid-input parse.
Light in the browser, strict on the server
Import
@pyreon/validate/serveron the server and every.email()and.phone()upgrades to strict RFC 5322 and full E.164, with a disposable-domain blocklist. None of that code reaches the client bundle.Checks that need your database
.serverCheck('email-unique')passes in the browser and is listed inr.pendingso the UI can say "checking". On the server,parseAsyncruns the check you registered. One schema, no second copy.Errors ready to translate
Every issue carries a
code, an i18nkeylikevalidate.string.emailand itsparams.formatErrorsByPath(issues, t)turns them into one message per field, in any language.
One schema for both sides, and the browser knows what it skipped.
A second schema for the server, so the DB call stays out of the bundle. The two drift, and the client never learns a check is pending.
// shared/signup.ts
import { z } from 'zod'
const Signup = z.object({
email: z.email(),
password: z.string().min(10),
})
// server/signup.ts: a second schema, so the DB call never reaches the bundle
const ServerSignup = Signup.superRefine(async (v, ctx) => {
if (await db.users.exists(v.email)) {
ctx.addIssue({ code: 'custom', path: ['email'], message: 'Email already taken' })
}
})
// ...and the browser has no idea a server check existsThe check is part of the shared schema. The browser records it as pending; the server runs it, plus strict email rules.
// shared/signup.ts: imported by the browser and the server
import { s } from '@pyreon/validate'
export const Signup = s.object({
email: s.string().email().serverCheck('email-unique', { message: 'Email already taken' }),
password: s.string().min(10),
})
// client/signup.ts: cheap checks run, the server check is recorded as pending
import { Signup } from '../shared/signup'
const r = Signup.parse({ email: 'ada@example.com', password: 'correct horse' })
// r.ok === true, r.pending → [{ path: ['email'], key: 'email-unique' }]
// server/signup.ts: strict RFC 5322 email, disposable-domain blocklist, the DB check
import { registerServerCheck } from '@pyreon/validate/server'
import { Signup } from '../shared/signup'
registerServerCheck('email-unique', async (email) => !(await db.users.exists(email as string)))
async function handleSignup(body: unknown) {
const verdict = await Signup.parseAsync(body)
return verdict.ok ? { ok: true } : { ok: false, issues: verdict.issues }
}One product, two packages.
Validation ships as two npm packages with similar names. Most apps install only the first.
@pyreon/validate
The validator you write schemas with: s.object, s.string().email() and the rest. Plus helpers for labels, translated errors and live validation that also work on Zod, Valibot and ArkType schemas.
bun add @pyreon/validate The plumbing. Forms, Store and State-tree use it to accept any schema, and it's installed with them. You only import it yourself for its typed Zod, Valibot or ArkType adapters.
Coming from Zod or Valibot?
Rename z to s, read ok instead of success.
import { z } from 'zod'
const User = z.object({
name: z.string().min(1),
email: z.email(),
age: z.number().int().min(18).optional(),
})
type User = z.infer<typeof User>
const r = User.safeParse(input)
if (r.success) save(r.data)
else show(r.error.issues)The chain is the same for the common cases. Or keep Zod: Pyreon's form, store and state-tree accept a Zod schema as it is.
import { s, type Infer } from '@pyreon/validate'
const User = s.object({
name: s.string().min(1),
email: s.string().email(),
age: s.number().int().min(18).optional(),
})
type User = Infer<typeof User>
const r = User.parse(input) // never throws
if (r.ok) save(r.value)
else show(r.issues)Same functional style, same tree-shaking, from /mini.
import * as v from 'valibot'
const User = v.object({
name: v.pipe(v.string(), v.minLength(1)),
email: v.pipe(v.string(), v.email()),
age: v.optional(v.pipe(v.number(), v.integer(), v.minValue(18))),
})
type User = v.InferOutput<typeof User>
const r = v.safeParse(User, input)
if (r.success) save(r.output)
else show(r.issues)From the next release @pyreon/validate/mini ships without the runtime JIT; call enableJit() from @pyreon/validate/jit once if you want its speed back.
import { email, integer, minLength, minValue, number, object, optional, pipe, string, type Infer } from '@pyreon/validate/mini'
const User = object({
name: pipe(string(), minLength(1)),
email: pipe(string(), email()),
age: optional(pipe(number(), integer(), minValue(18))),
})
type User = Infer<typeof User>
const r = User.parse(input)
if (r.ok) save(r.value)
else show(r.issues)One schema, validated twice.
Type an email and validate. The browser runs the light format check and lists email-unique as pending; the server pass runs the strict email rules, the disposable-domain blocklist and the uniqueness check. Try ada@example.com (taken) and test@mailinator.com (disposable).
- browser · format—
- browser · email-unique—
- server · strict format—
- server · email-unique—
The server half runs in a Web Worker in this page, with its own copy of @pyreon/validate/server. The round-trip delay and the user table are simulated.
Fastest in all 12 cells of the multi-schema workload.
The workload bench runs many schemas through one call site, the way a real app does. In the 10-library protocol bench, Zod's compiled mode, ArkType and typia take six cells, all on valid input or email; they are in the table.
- multi-schema workload, 12 cellswinfastest in 12 of 12 vs Zod, Valibot, ArkType
- invalid scalar string (closest cell)34.9 ns44.7 nswin1.28× vs Valibot · 1.40× vs Zod (CI margin 0.1 ns)
- protocol bench, 24 cellssplitwins or ties 18, including every invalid-input parse
- parse email, valid29 ns24 nslossZod compiled mode ahead
- parse int, valid5 ns3 nslossZod compiled mode ahead
- parse array of 20, valid119 ns107 nslossZod compiled mode ahead
- parse user object, valid43 ns35 nslossArkType ahead (returns the input, no clone)
- check email, valid27 ns21 nslosstypia 21 · ArkType 22
- check email, invalid22 ns19 nslossArkType ahead
- adapter tax, @pyreon/validationloss−24 to +436 ns over raw Zod / Valibot / ArkType (overnight run)
What is in the box.
- The full chain strings, numbers, bigints, dates, literals, enums, objects, arrays, tuples, records, maps, sets, unions, discriminated unions, intersections, lazy recursion.
- String formats
email,url,uuid,ulid,nanoid,cuid,jwt,ip,cidr,phone,creditCard,emoji,iso.date,iso.dateTime,iso.time,duration. - Object algebra
.pick,.omit,.partial,.required,.extend,.merge,.keyof,.catchall,.strict. - Refine and transform
.refine,.superRefine,.transform,.pipe,s.preprocess,s.coerce; async members work inside every composition viaparseAsync. - Resilient parsing
.catch(fallback)for bad fields,.readonly()for frozen output. .is()for a boolean a verdict-only compiled path that builds no output and no issues.- JSON Schema out
toJsonSchema()emits draft 2020-12 for OpenAPI, editor autocomplete or an LLM's structured output. - Strict CSP
configure({ jit: false })runs the interpreter with identical results whenunsafe-evalis off. - Labels on any schema
withField(z.string().email(), { label, placeholder })attaches metadata to Zod, Valibot, ArkType orsschemas. - Shared native schemasnext release A declared
s.object({...})compiles to a native struct on iOS and Android, and itsparsereturns the same{ ok, value, issues }there. Experimental.
Things to build with it.
Every built-in issue has an i18n key and params, so translation is a lookup, not a regex over English text.
import { formatErrorsByPath, s } from '@pyreon/validate'
// every built-in issue carries an i18n key and params
const messages: Record<string, string> = {
'validate.string.too-short': 'Mindestens {min} Zeichen',
'validate.string.email': 'Ungültige E-Mail-Adresse',
}
const t = (key: string, params?: Record<string, unknown>) =>
(messages[key] ?? key).replace(/\{(\w+)\}/g, (_, k: string) => String(params?.[k] ?? ''))
const Signup = s.object({ name: s.string().min(2), email: s.string().email() })
const r = Signup.parse({ name: 'A', email: 'nope' })
if (!r.ok) console.log(formatErrorsByPath(r.issues, t))
// { name: 'Mindestens 2 Zeichen', email: 'Ungültige E-Mail-Adresse' }Emit JSON Schema from the same object you validate with, then check what comes back.
import { s } from '@pyreon/validate'
import { toJsonSchema } from '@pyreon/validate/json-schema'
const Ticket = s.object({
title: s.string().min(3).describe('One-line summary'),
priority: s.enum(['low', 'normal', 'urgent']),
tags: s.array(s.string()).max(5).optional(),
})
// draft 2020-12, ready for an OpenAPI spec or an LLM's structured output
console.log(JSON.stringify(toJsonSchema(Ticket), null, 2))
// ...and the same schema checks what comes back
const reply = Ticket.parse(JSON.parse('{"title":"Login loops","priority":"urgent"}'))
console.log(reply.ok) // trueparseReactive gives a computed result for templates; watchValid calls you only when validity flips.
import { signal } from '@pyreon/reactivity'
import { parseReactive, s, watchValid } from '@pyreon/validate'
const Coupon = s.string().regex(/^[A-Z]{4}-\d{4}$/, { message: 'Looks like ABCD-1234' })
const code = signal('')
// a Computed result for templates...
const result = parseReactive(Coupon, code)
// ...and a callback that fires only when validity flips
const stop = watchValid(Coupon, code, (valid) => console.log('valid:', valid)) // valid: false
code.set('SAVE-2026') // valid: true
code.set('save') // valid: false
console.log(result().issues?.[0]?.message) // 'Looks like ABCD-1234'
stop()One namespace for schemas, a few helpers for the rest.
Every export has a reference page with its signature, an example and the mistakes people make with it.
- s.string
- s.number
- s.boolean
- s.date
- s.enum
- s.literal
- s.object
- s.array
- s.tuple
- s.record
- s.union
- s.discriminatedUnion
- s.lazy
- s.coerce
- s.preprocess
- s.custom
- parse
- safeParse
- parseOrThrow
- parseAsync
- is
- optional
- refine
- transform
- catch
- serverCheck
- withField
- getMeta
- parseReactive
- parseReactiveAsync
- watchValid
- formatErrors
- formatErrorsByPath
- configure
- installFormatValidator
- registerServerCheck
- strictEmail
- strictPhone
- isDisposableEmail
- addDisposableDomains
- toJsonSchema
- @pyreon/validate/mini
- enableJit
- zodSchema
- valibotSchema
- arktypeSchema
- isStandardSchema
- standardSchemaToValidator
Good to know before you start.
The result shape is { ok }, not { success }
parse() and its alias safeParse() return { ok, value } or { ok, issues } and never throw. Use parseOrThrow() where an exception reads better.
Strict CSP: one line skips the JIT
The JIT uses new Function. Under a CSP without unsafe-eval it falls back to the interpreter after one blocked attempt; call configure({ jit: false }) at startup to skip that attempt. Results are identical, only slower.
The chain does not tree-shake
Chain methods live on prototypes. For the smallest bundle import from @pyreon/validate/mini, or let pyreon({ optimizeValidators: true }) rewrite module-level schemas for you.
A browser ok is not the final word
.serverCheck always passes in the browser and shows up in pending. Treat the server's parseAsync as the verdict.
What people ask first.
Where does it lose, and why?
Six of 24 protocol cells: Zod's compiled mode parses a valid email, int and 20-item array faster; ArkType parses a valid user object faster because it hands back your input instead of a clean copy; typia and ArkType check emails faster. On email the grammars also differ: ArkType accepts a..b@x.com and a@-x.com, which Zod, Valibot and s reject.
Are those numbers independent?
No. We wrote the bench, it is synthetic, and the validate rows are one run on one machine. Every library is checked for identical results before timing. Run it yourself: cd packages/fundamentals/validate && bun bench/validation.ts.
@pyreon/validate or @pyreon/validation?
Install @pyreon/validate: it is the s schema library plus helpers. @pyreon/validation is the small adapter layer (zodSchema, valibotSchema, arktypeSchema, the Standard Schema bridge) that forms, stores and state trees use to accept any validator. It comes with them.
Do I have to switch from Zod?
No. withField, parseReactive, formatErrors and every Pyreon package that takes a schema work with a Zod, Valibot or ArkType schema directly. Switch when the speed or the server split is worth it to you.
What about async rules?
.refine and .transform can be async anywhere in the tree; call parseAsync. A sync parse() of an async schema returns one issue telling you to use parseAsync, instead of a wrong answer.
Keep the chain. Lose the second schema.
bun add @pyreon/validate