@k8ordo/field

A value’s kind and constraints, declared once

bash
npm install @k8ordo/field
src/lib/filter.ts
import { field } from '@k8ordo/field';

export const filter = {
  q: field.string({ maxLength: 100 }),
  page: field.integer({ min: 1, default: 1 }),
  sort: field.enum(['new', 'price'], { default: 'new' }),
};
ts
type Filter = ValuesOf<typeof filter>;
// { q: string; page: number; sort: 'new' | 'price' }

Plain data

field.integer({ min: 1, default: 1 }) returns { '~kind': 'integer', min: 1, default: 1 }, a frozen object. It holds no function and no class.

Every package reads the same data, so one declaration can serve two places. There is no transform and no union. A date is read as its YYYY-MM-DD string.

ts
field.integer({ min: 1, default: 1 });
// { '~kind': 'integer', min: 1, default: 1 }

Value types from the declaration

ValueOf and ValuesOf give the type of what a declaration reads. A default or required: true drops undefined, and an enum’s values are literal types without as const.

An option the kind does not take is a type error. A contradiction such as min above max throws where the declaration is built.

ts
field.integer(); // number | undefined
field.integer({ default: 1 }); // number
field.enum(['new', 'price']); // 'new' | 'price' | undefined

Refusals named as the browser names them

A refusal is named by the same flag HTML’s ValidityState uses, such as tooShort or rangeUnderflow. A form shows one message for it on both the browser and the server.

read never throws: it returns what it read and the list of refusals. explain words a refusal in English without the value itself.

ts
read(field.integer({ min: 1 }), '0').issues;
// [{ path: [], flag: 'rangeUnderflow', … }]

explain(issues[0]);
// 'is below 1'