Skip to content
Logo

TypeBox

Any Schema can be converted to a TypeBox schema. Use this to validate fabricated data, or to use one shape for both test data and runtime validation.

import { toTypeBox } from "@ghostry/fabricator-adapter-typebox-v0";
 
const TProduct = toTypeBox(ProductSchema);

Adapters are values, not names

An adapter is an ordinary value you import. There is nothing to register, and fabricator itself doesn't know about any schema library. Each adapter carries its own key, and .adapt() stores an override under that key. So two adapters never collide, and naming the wrong adapter is an import error instead of an override that is silently ignored.

This also lets adapters for two versions of the same library work side by side: one schema can carry an override for each.

The default mapping

Each kind maps to one fixed TypeBox counterpart:

KindTypeBox
objectType.Object({ ...fields })
arrayType.Array(element, { minItems, maxItems })
tupleType.Tuple([...items])
recordType.Record(key, value, { maxProperties })
object.omittableType.Optional(inner)
object.optionalType.Optional(Type.Union([inner, Type.Undefined()]))
alwaysa pinned literal (see below)
opaqueType.Unknown()
bigintType.BigInt(bounds)
booleanType.Boolean()
enumType.Union([...pinned literals])
choiceType.Union([...option schemas])
dateType.Date(timestamp bounds)
numberType.Number(bounds) or Type.Integer(bounds)
stringType.String({ minLength, maxLength })
symbolType.Symbol()
undefinedType.Undefined()
undefinableType.Union([inner, Type.Undefined()])
nullType.Null()
nullableType.Union([inner, Type.Null()])
nullishType.Union([inner, Type.Null(), Type.Undefined()])
recursiveType.Recursive(...), $ref-based

A record over a fixed set of literal keys, such as a T.enum key, becomes a Type.Object whose properties are all optional, because a record's size is random and may not cover every key. A T.unique.array adds uniqueItems: true, and a T.unique.record states its size as minProperties and maxProperties.

Which bounds are stated

Bounds are stated as you wrote them. A min, max, length, or size you wrote in .whereby() becomes a JSON Schema keyword, even under .as(produce). Everything else in .whereby() only shapes the draw and is never stated: weights, composition, distribution, redraws, depth, and a plain record's minTried. An end you never wrote isn't stated either, such as an omitted number end or the "now" end of T.date.past.

Inclusive bounds become minimum, minLength, or minItems. An exclusive value bound becomes exclusiveMinimum with the value you gave. JSON Schema has no exclusive length keyword, so an exclusive length becomes the nearest inclusive whole number.

Accepting more than you fabricate

Test data usually wants tight bounds, and validation usually wants loose ones. .admits(...) sets what the adapter states without changing what is drawn:

const Comment = T.string
  .whereby({ length: { min: 1, max: 40 } }) // short test data
  .admits({ length: { max: Infinity } }); // any length passes validation
 
toTypeBox(Comment); // Type.String({ minLength: 1 })

It can only widen. An end that would reject a value the schema can fabricate throws AdmitsExcludesDrawError. It is also where JSON Schema's format, pattern, and multipleOf go:

T.string.as(() => crypto.randomUUID()).admits({ format: "uuid" });
// Type.String({ format: "uuid" })

Nothing checks generated values against format, pattern, or multipleOf. See .admits(...) for every kind that has it and how calls combine.

When the default is wrong

import { typebox } from "@ghostry/fabricator-adapter-typebox-v0";
 
T.string
  .whereby({ length: { max: 254 } })
  .adapt(typebox, () => Type.String({ format: "email" }));

.adapt(adapter, produce) overrides the mapping for one schema. The override stays through later calls, so .whereby(), .as(), or .extend() after .adapt() keep it. To adapt to several libraries, chain several .adapt() calls. Each one only replaces its own adapter's override.

Because you pass the adapter itself, its types are known at the call site. A producer that returns something TypeBox can't produce is a type error right there, not a silent problem at conversion time.

What the producer is handed

The producer gets one argument, { schema, meta }. Destructure whichever part you need.

meta is the schema's own config, so an override can build on what you already told fabricator instead of repeating it:

T.string
  .whereby({ length: { max: 254 } })
  .adapt(typebox, ({ meta }) =>
    Type.String({ format: "email", maxLength: meta.whereby.length.max.value }),
  );

Its shape depends on the kind: whereby for a string, definition for an object, and so on. You can read it, but it isn't a stable API. An override that reads meta may break when its shape changes between versions.

schema is the schema being adapted, with the override it replaced. So toTypeBox(schema) inside a producer gives the previous override, or the default mapping if there was none. That is what makes intersecting with it work the way it reads:

email.adapt(typebox, ({ schema }) =>
  Type.Intersect([toTypeBox(schema), Type.String({ minLength: 3 })]),
);

Both are read at conversion time, not when .adapt() is called, so the producer sees any builder methods chained after it.

Kinds that need .adapt() more than most

A record keyed by T.symbol throws. TypeBox's Type.Record can't represent a symbol key, and returning a schema nothing can pass would be worse than an error. Use .adapt(typebox, ...) to supply your own.

opaque always maps to Type.Unknown(), because the adapter can't know what your producer returns. If the static type matters, adapt it.

Where Static<ToTypeBox<S>> and the fabricated value type can legitimately diverge

These cases are all expected, and none is a bug:

  1. An adaptation. You told TypeBox something fabricator doesn't follow, so keeping the two compatible is up to you.
  2. always/enum over a value TypeBox can't type exactly. TypeBox has no literal type for a bigint, Date, symbol, or Uint8Array, so the static type is the general one, such as bigint. TypeBox still checks a bigint or Date against the exact value at runtime, but it can't check a symbol or a Uint8Array's contents.
  3. opaque. Static<TUnknown> is unknown, while the fabricated value has the producer's exact return type.

Only the last is purely wider, and always safe. In the others, the two types say genuinely different things about the same field.