Serialization
Convert models to and from JSON, and change the JSON form of a field.
Convert to and from JSON
The JSON form of a value is the value as JSON holds it, also called its JSON value. The API names it "wire" in toWireFormat, fromWireFormat and WireFormat<T>.
These calls convert a named IObject or IModel.
stringify<T>andparse<T>use JSON text.toWireFormat<T>andfromWireFormat<T>use a plain object.
import type { IObject } from '@exprtlabs/golem/model';
import type { Pattern } from '@exprtlabs/golem/tags';
// Amounts are decimal strings and currencies are ISO 4217 codes; no float carries money.
export type TMoney = IObject<{
amount: string & Pattern<'^[0-9]+(?:\\.[0-9]{1,2})?$'>;
currency: string & Pattern<'^[A-Z]{3}$'>;
}>;import { parse, stringify } from '@exprtlabs/golem/serde';
import { validate } from '@exprtlabs/golem/validation';
import type { TMoney } from './estimate.model.js';
export function readMoney(text: string): TMoney {
return parse<TMoney>(text); // plain object, validated
}
export function writeMoney(money: TMoney): string {
return stringify<TMoney>(money);
}
export function isMoney(value: unknown): value is TMoney {
return validate<TMoney>(value); // for data you did not parse yourself
}import { parse } from '@exprtlabs/golem/serde';
import { Task } from './task.model.js';
import type { TTask } from './task.model.js';
export function readTask(text: string): Task {
return parse<Task>(text); // a Task instance with toggle()
}
export function readTaskData(text: string): TTask {
return parse<TTask>(text); // a plain object with the same fields
}The type argument picks the model and the result:
parse<TMoney>returns a plain object, andparse<Task>returns aTask.new Task(parse<TTask>(text))parses anIObjectand passes it to theTaskconstructor. Use it when the constructor takes extra arguments.- Nested fields follow the field type, not the root type argument.
Build with golem
parse, stringify, fromWireFormat, toWireFormat, validate and assertValue throw unless a build rewrote them. Choose a build tool in Build tools. tsc does not rewrite them.
Tmust be a named generatedIObjectorIModel. An inline object type is not enough.- Unsupported unions fail generation.
- Write these calls in your own source files. Golem does not rewrite a call inside a generated
*.generated.tsfile, so it throws at run time. - A class whose model has a dynamic map keeps the extra keys of the input and converts each by the type of the map value.
Do not write stringify(toWireFormat(x)) or fromWireFormat(parse(text)) on the JSON path. stringify writes JSON for the declared fields and applies each TSerde serialize formatter. parse reads that JSON back. JSON.stringify(model) does not run conversion or validation.
Model value and JSON value
The model value is what your code holds. The JSON form is what toWireFormat returns and stringify writes. For most fields the two are equal. These differ:
- A
Dateis aDatein the model and an ISO string in JSON. The Temporal classes are strings in JSON too. Golem converts them with built-inTSerdefunctions. - A
TSerdefield has the form that its functions give.
A Date converts in these ways:
- It decodes a
date-timestring at every validation level, off included. A value that is not a string, or that is not adate-timestring, throwsDeserializationwithcausedByInput: true. - It encodes as UTC ISO text with milliseconds. A year outside 0000-9999 throws
Serialization. - Validation of the model value requires a
Datethat holds a time. Another value, andnew Date(NaN), fail with aninstanceissue (Check a Date or Temporal field). - Put your own rule on a
DatewithTValidation.
A function, a symbol or an array hole is not a JSON value and fails the JSON check.
WireFormat<T> names the JSON shape of a model (IModel or IObject). For IObject declarations, Golem also generates <Alias>JSON type aliases (such as TMoneyJSON); IModel declarations use WireFormat<T>.
Change the JSON form
TSerde<typeof encode, typeof decode> is a serialize formatter. encode turns the model value into its JSON value, and decode turns the JSON value back into the model value. Both are synchronous.
TPermissionInput is an IModel. fromWireFormat<TPermissionInput> returns a plain object, and fromWireFormat<PermissionInput> constructs your class.
import type { Integer, Maximum, Minimum, Pattern, TSerde, TValidation } from '@exprtlabs/golem/tags';
// A project member's access bits: 1 reads, 2 writes, 4 administers.
export function hasReadPermission(value: number): boolean | string {
return (value & 1) !== 0 ? true : 'Read permission is required.';
}
export type PermissionWire = string & Pattern<'^0x[0-9a-fA-F]+$'>;
// TSerde functions live in their own module: generated files import them, and a model file cannot be imported back.
export function encodePermissions(value: number): PermissionWire {
return `0x${value.toString(16)}`;
}
export function decodePermissions(value: PermissionWire): number {
return Number.parseInt(value.slice(2), 16);
}
export type PermissionBits = number
& Integer
& Minimum<0>
& Maximum<255>
& TValidation<typeof hasReadPermission>
& TSerde<typeof encodePermissions, typeof decodePermissions>;import { model, type IModel } from '@exprtlabs/golem/model';
import type { PermissionBits } from './permission-rules.js';
import { fromWireFormat, toWireFormat } from '@exprtlabs/golem/serde';
import { validateInstance } from '@exprtlabs/golem/validation';
export type TPermissionInput = IModel<{
permissions: PermissionBits;
}>;
export class PermissionInput extends model<TPermissionInput>() {}
export async function checkPermissionInput() {
const access = fromWireFormat<TPermissionInput>({ permissions: '0x5' });
const wire = toWireFormat<TPermissionInput>(access);
const issues = await validateInstance(new PermissionInput({ permissions: 2 }));
// -> { permissions: 5, wire: { permissions: '0x5' }, deniedMessage: 'Read permission is required.' }
return { permissions: access.permissions, wire, deniedMessage: issues[0]?.message };
}- The same behavior applies when the field is nested.
- Declare the encoder and decoder in their own module, like a
TValidationpredicate. The generated file imports them, and the model file imports the generated file. A function in the model file makes the two files import each other, and generation stops with RUNM1065. TSerdefunctions run during conversion, never during generation.- A
Deserializefunction reads wire input. When it throws, the call throws aLibErrorwith the exception as itscauseandcausedByInput: true. - A
Serializefunction writes your own value. When it throws, the exception reaches your code unchanged. It is not bad input. - An encoder must return JSON-compatible data. Non-finite numbers, cycles and other values that JSON cannot hold still fail with validation disabled.
- The signature and the failures are in the
TSerdereference.
Example: money and priority
An order holds an amount as integer cents and a priority as a number, so your code can add and sort them. Its JSON holds decimal text and a word, which people and other systems read.
| Field | Model value | JSON form |
|---|---|---|
amount | 1250, an integer in cents | "12.50", decimal text |
priority | 3 | "high" |
remindAt | a Date | "2025-01-02T03:04:05.000Z" |
Without TSerde, you write a mapper for each direction and call it wherever JSON enters or leaves your code. With TSerde, golem converts the field in every call and checks the value on both sides.
Write the two functions in their own module. Priority is a number in code and a word in JSON:
const PRIORITY_WORDS = ['low', 'normal', 'high'] as const;
export type PriorityWord = (typeof PRIORITY_WORDS)[number];
export function toPriorityWord(value: number): PriorityWord {
const word = PRIORITY_WORDS[value - 1];
if (!word) throw new RangeError('Priority must be 1, 2 or 3.');
return word;
}
export function fromPriorityWord(word: PriorityWord): number {
return PRIORITY_WORDS.indexOf(word) + 1;
}An amount is an integer in cents in code and decimal text in JSON:
import type { Pattern } from '@exprtlabs/golem/tags';
export type DecimalText = string & Pattern<'^[0-9]+(?:\\.[0-9]{2})$'>;
// The model keeps integer minor units (cents); JSON carries the exact decimal text.
export function writeAmount(minorUnits: number): DecimalText {
return `${Math.trunc(minorUnits / 100)}.${String(minorUnits % 100).padStart(2, '0')}`;
}
export function readAmount(text: DecimalText): number {
return Number(text.replace('.', ''));
}- Export each function. Each function is synchronous and takes one parameter.
- Type the parameter of the decoder as the JSON value.
PriorityWordlimits the words, andDecimalTextlimits the text to a pattern. Golem checks the JSON value against this type before it calls the function (Which type controls validation).
Write typeof each function in TSerde, and import the functions as types:
import { model, type IModel } from '@exprtlabs/golem/model';
import type { Integer, Maximum, Minimum, TSerde } from '@exprtlabs/golem/tags';
import type { readAmount, writeAmount } from './decimal-text.js';
import type { fromPriorityWord, toPriorityWord } from './priority-word.js';
export type TOrder = IModel<{
// Your code adds cents; the JSON carries decimal text.
amount: number & Integer & Minimum<0> & TSerde<typeof writeAmount, typeof readAmount>;
// Your code sorts by a number from 1 to 3; the JSON carries a word.
priority: number & Integer & Minimum<1> & Maximum<3> & TSerde<typeof toPriorityWord, typeof fromPriorityWord>;
// A Date needs no TSerde: the JSON carries ISO text.
remindAt: Date;
}>;
export class Order extends model<TOrder>() {}Integer,MinimumandMaximumcheck the model values:amountis a whole number of cents,priorityis 1 to 3.remindAtis aDateand needs noTSerdetag. Use Date fields shows how golem writes it and how to keep its exact text.
Run npx golem generate, then convert the JSON:
export function readOrder(text: string): Order {
return parse<Order>(text); // an Order instance: amount is 1250 for "12.50"
}export function writeOrder(order: Order): string {
return stringify<TOrder>(order); // '{"amount":"12.50","priority":"high","remindAt":"…"}'
}parse<Order>returns anOrder. For"12.50", itsamountis1250. For"high", itspriorityis3.parse<TOrder>returns a plain object with the same fields.- A JSON value that fails its type makes
parsethrow aLibError. Examples are a word that is not in the list and a text that does not match the pattern (Errors and issues). stringifycalls the encoder of eachTSerde. Priority3becomes"high", and1250becomes"12.50".- A model that is not valid makes
stringifythrow aLibError, so validate the model first.
Which type controls validation
Here PermissionWire is a string tagged with a hexadecimal pattern, and the model stores permissions as a number:
| Declaration or option | Effect |
|---|---|
decodePermissions(value: PermissionWire) | JSON validation includes the pattern. Generated validation checks it before decoding and after encoding. |
Change the decoder parameter to value: string | JSON validation keeps the string type check but drops the pattern, even if the encoder still returns PermissionWire. |
permissions: number & Integer & Minimum<0> & … | These are validation constraints on the model value. They run after decoding and before encoding, whether the decoder accepts plain string or not. |
{ validate: false } | Runs only the TSerde serialize formatter, without checks. |
- The decoder parameter type defines the JSON schema.
- The encoder return type is checked for TypeScript compatibility. Tags on the return type alone add no JSON validation.
- A plain
stringparameter keeps the string check and drops the tagged validation constraints on the JSON value. This also applies to aliases such asProjectName = string & MinLength<3>. - A parameter typed
anyorunknownfails withRUNM1011unlessallowAnyistrue, ingolem.yamlor in the options of the model. Type the parameter as the JSON value that the decoder reads. - Calling
encodePermissions()ordecodePermissions()directly runs only the function body. Type annotations do not perform runtime checks by themselves.
Class values
A TSerde field can hold a class instance, such as Uint8Array, or a bigint. The codec does all the conversion. Validation checks the JSON value, and for a class it checks that the model value is an instance of the class.
import type { Pattern } from '@exprtlabs/golem/tags';
export type Base64 = string & Pattern<'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$'>;
export function encodeBase64(value: Uint8Array): Base64 {
let binary = '';
// Chunks keep the argument list of fromCharCode short for large inputs.
for (let start = 0; start < value.length; start += 0x8000) {
binary += String.fromCharCode(...value.subarray(start, start + 0x8000));
}
return btoa(binary);
}
export function decodeBase64(value: Base64): Uint8Array {
return Uint8Array.from(atob(value), char => char.charCodeAt(0));
}import { model, type IModel } from '@exprtlabs/golem/model';
import type { TSerde } from '@exprtlabs/golem/tags';
import type { decodeBase64, encodeBase64 } from './base64-codec.js';
export type TAttachment = IModel<{
name: string;
content: Uint8Array & TSerde<typeof encodeBase64, typeof decodeBase64>;
}>;
export class Attachment extends model<TAttachment>() {}Converting the model writes the JSON form and restores the instance:
import { fromWireFormat, toWireFormat } from '@exprtlabs/golem/serde';
import { Attachment } from './attachment.model.js';
export function roundTripAttachment() {
const attachment = new Attachment({ name: 'checksum.bin', content: Uint8Array.of(1, 2, 3) });
const wire = toWireFormat<Attachment>(attachment);
const copy = fromWireFormat<Attachment>(wire);
// -> { wire: { name: 'checksum.bin', content: 'AQID' }, copy }, where copy.content is a Uint8Array
return { wire, copy };
}- The
Base64pattern accepts only well-formed base64. A malformed value fails the JSON check as input, beforeatobruns. - The class must have a name and have no type parameter without a default. A module must export it, under any name or as the default export (RUNM1063).
- A value that is not an instance of the class fails with one
instanceissue that names the class. A type with no class behind it at run time, such as aninterface, has no instance check. - A decoder whose JSON value is a string reads only a string. Another JSON value throws
Deserializationat every validation level, off included. - Declare the class in its own module. A class of a
TSerdefield that a*.model.tsfile declares stops generation with RUNM1065. Dateand the Temporal classes are this kind of field with the codec built in, so they need no tag. ATSerdetag on one of them replaces the built-in codec. The Temporal types have their own tags.
Checks during conversion
With validation on, the default, each call checks the value. The JSON value and the model value are checked at separate stages, and each rule runs once. Your decoders only see values that passed the JSON check.
| Call | Checks JSON | Converts | Checks model |
|---|---|---|---|
parse<T>(text) | ✓ | ✓ | ✓ |
parse<T>(text, { validate: false }) | ✓ | ||
stringify<T>(value) | ✓ | ✓ | ✓ |
stringify<T>(value, { validate: false }) | ✓ | ||
fromWireFormat<T>(json) | ✓ | ✓ | ✓ |
toWireFormat<T>(value) | ✓ | ✓ | ✓ |
validate<T>(value) | ✓ |
{ validate: false } skips the check for data you already trust. It does not update stored field errors.
import { fromWireFormat } from '@exprtlabs/golem/serde';
import { validateInstance } from '@exprtlabs/golem/validation';
import { TaskInput } from './task-input.model.js';
export async function loadInvalidTask() {
const draft = fromWireFormat<TaskInput>({ title: '', done: false }, { validate: false });
const issues = await validateInstance(draft);
// -> { message: 'Must be at least 1 character', title: '' }: the trusted conversion did not validate
return { message: issues[0]?.message, title: draft.title };
}parse,stringify,fromWireFormatandtoWireFormattakevalidate: true | 'sanity' | false.{ validate: 'sanity' }checks the shape only: JSON types, required and extra keys, union tags, enums, tuple length anddate-timevalues.- Without the option, the call uses the default level of its model (rules for a level).
- A level above the project level throws a
LibErrorof kindValidationUnavailable. For these four calls, any other value throws aTypeError. - A nested model is checked at the level of the call.
- After a successful
parseorfromWireFormatwith validation on, callvalidateInstance(model)again only after you edit the instance. CallgetValidator(model).validate()to store all field errors for display. failFast: falsethrows with every issue instead of the first one. It does not turn the check off.validate<T>(value)from@exprtlabs/golem/validationnarrowsvalueto the model and returns whether it matches, without throwing.validateInstance(model)returns the issues and does not throw for an ordinary invalid value.- When
validationis off, generated output has no checks.{ validate: true }and{ validate: 'sanity' }then throw aLibErrorof kindvalidation_unavailable. In a project atsanity,{ validate: true }throws it too. With validation off, a missing required field is not reported:stringifyleaves it out, andtoWireFormatreturns it asundefined.
Copies and references
fromWireFormatandparsecopy objects, maps (Record<string, V>) and arrays.- Values typed
unknownorany(the model setsallowAny: true) are carried by reference, including the undeclared properties of an open object. The result holds the same object as the input. - Cyclic input throws a
LibErrorof kinddeserialization. - Encoding a cyclic value throws a
LibErrorof kindserialization.
Full example: examples/models.
