Serialized documents

A document is plain data: strings, numbers, booleans, arrays and objects. It names registered pieces by $type, so it carries no code. That is what lets a server build an interface and send it, a CMS store it and a tool generate it, and what lets the receiving side check it before it trusts it.

The examples continue from the Quick start: its actions.ts holds the action registry used here. The nodes are drawn with React components, so this page registers them again as React components.

What a document can hold

A document is whatever survives JSON.stringify and JSON.parse. It cannot hold a function, a class instance, a Date or undefined: a Date arrives as a string and the rest are dropped or fail. Behaviour stays in the registrations on the receiving side, and the document refers to it by $type. A YAML file parses to the same data, with the caveats below.

What arrives from a file or a network is unknown. Nothing in it is trusted until a schema has checked it.

Validate at the boundary

Two kinds of node cross the boundary, and each has one check.

Nodes: the registry

A node is checked against the schema of the registration its $type names. A registration here is a $type, a schema and a render that draws the component in React:

import type { ReactNode } from 'react';
import * as z from 'zod/mini';
import { createRegistry, type ComponentRegistration } from '@schema-engine/registry';

z.config(z.locales.en());

interface Component extends ComponentRegistration {
	render(config: unknown): ReactNode;
}

const badgeSchema = z.object({
	$type: z.literal('badge'),
	label: z.string(),
	tone: z.optional(z.enum(['info', 'success', 'warning'])),
});

const calloutSchema = z.object({
	$type: z.literal('callout'),
	title: z.string(),
	text: z.string(),
});

const badge: Component = {
	$type: 'badge',
	schema: badgeSchema,
	metadata: { name: 'Badge', description: 'A short status label.' },
	render({ label, tone = 'info' }: z.output<typeof badgeSchema>) {
		return <span className={`badge badge-${tone}`}>{label}</span>;
	},
};

const callout: Component = {
	$type: 'callout',
	schema: calloutSchema,
	metadata: { name: 'Callout', description: 'A boxed message with a title.' },
	render({ title, text }: z.output<typeof calloutSchema>) {
		return (
			<aside className="callout">
				<strong>{title}</strong> {text}
			</aside>
		);
	},
};

export const components = createRegistry('Component', [badge, callout]);

safeParseNode(registry, node, path) looks the node's $type up and validates the node against the registration's schema, without throwing. It returns the registration with the validated configuration, or every issue. Pass the position of the node in its document as path, and the path of each issue starts there. DocumentView draws a list of nodes, and a node that fails is drawn as its issues, in its own place, so the others still render:

import { Fragment } from 'react';
import { formatIssuePath, safeParseNode } from '@schema-engine/registry';
import { components } from './components.react';

export function DocumentView({ nodes }: { nodes: unknown[] }) {
	return (
		<>
			{nodes.map((node, index) => {
				const parsed = safeParseNode(components, node, [index]);
				if (parsed.success) return <Fragment key={index}>{parsed.registration.render(parsed.data)}</Fragment>;
				return (
					<ul key={index} role="alert">
						{parsed.issues.map(({ path, message }, issue) => (
							<li key={issue}>{`${formatIssuePath(path)}: ${message}`}</li>
						))}
					</ul>
				);
			})}
		</>
	);
}

Actions: parseActions

A workflow is checked by parseActions. It validates each entry, and each member of a group, against the schema of its registration, and returns either the parsed sequence or every issue. The parseActions reference says where each issue's path points.

The ActionDispatcher takes only what parseActions returned, as a type, so dispatching a workflow that was not checked does not type-check.

See the issues

A document with a wrong label, an unregistered $type and a missing field, and a workflow with a bad address, a missing subject inside a group and an unregistered action:

import { renderToStaticMarkup } from 'react-dom/server';
import { parseActions } from '@schema-engine/actions';
import { formatIssuePath } from '@schema-engine/registry';
import { actions } from './actions';
import { DocumentView } from './document.react';

const badDocument = [
	{ $type: 'badge', label: 5 },
	{ $type: 'banner', text: 'Sale' },
	{ $type: 'callout', title: 'Order 1042 confirmed' },
];

const badWorkflow = [
	{ id: 'receipt', $type: 'sendEmail', to: 'not-an-email', subject: 'Your receipt' },
	[
		{ id: 'warehouse', $type: 'sendEmail', to: '[email protected]' },
		{ id: 'refund', $type: 'refundCard', orderId: '1042' },
	],
];

console.log(renderToStaticMarkup(<DocumentView nodes={badDocument} />));

const workflow = parseActions(actions, badWorkflow);
if (!workflow.success)
	for (const issue of workflow.issues) console.log(`workflow ${formatIssuePath(issue.path)}: ${issue.message}`);
<ul role="alert">
	<li>[0].label: Invalid input: expected string, received number</li>
</ul>
<ul role="alert">
	<li>[1].$type: No registration for $type &#x27;banner&#x27;.</li>
</ul>
<ul role="alert">
	<li>[2].text: Invalid input: expected string, received undefined</li>
</ul>
workflow [0].to: Invalid email address
workflow [1][0].subject: Invalid input: expected string, received undefined
workflow [1][1].$type: No registration for $type 'refundCard'. Register it in the action registry.

Every bad node and entry is reported, in the order it appears, so a caller can show all of them at once. path is the position in the document, so an editor can mark the node and a log can name it.

From a server to a client

A server builds the document and sends it as JSON. The client parses it and hands it to the component above, which validates each node before it draws it:

const document = [
	{ $type: 'callout', title: 'Order 1042 confirmed', text: 'Thanks for shopping with us.' },
	{ $type: 'badge', label: 'Paid', tone: 'success' },
];

export function GET(): Response {
	return Response.json(document);
}

The client registers the components and actions, so the server decides what to show and the client decides how it is drawn and what the actions do. A $type the client has not registered is an issue in that node's place, not a crash. A document is data, so a server can also store it and a test can replay it. Render a server-sent document is the full round trip, with a ServerDocument component that fetches the document and draws it.

YAML

A document can be written as YAML. Install the optional peer dependency of the registry in the app that imports the subpath:

pnpm add yaml

The @schema-engine/registry/yaml subpath parses the text, hands the value to a validator of your choice and turns every issue into a file, line and column. A function that returns { success, data } or { success: false, issues }, such as safeParseNode and parseActions, is that validator:

import { formatIssuePath, safeParseNode } from '@schema-engine/registry';
import { parseYaml, YamlDocumentError } from '@schema-engine/registry/yaml';
import { components } from './components.react';

const text = `$type: badge
label: Paid
tone: succes
`;

try {
	parseYaml(text, (value) => safeParseNode(components, value), { filename: 'welcome.yaml' });
} catch (error) {
	if (!(error instanceof YamlDocumentError)) throw error;
	console.log(error.message);
}
welcome.yaml:3:7 tone: Invalid option: expected one of "info"|"success"|"warning"

A YamlDocumentError lists every issue in error.issues, each with its line, column (counting from 1), filename and path. Its message has one line per issue, in the file:line:column form that terminals and editors turn into links. Use safeParseYaml, which takes the same arguments, to get { success: true, data } or { success: false, issues } without a throw. stringifyYaml writes a value back out as YAML.

A validation issue points at the start of the value its path names. When the path names a key the file does not have, it points at the nearest ancestor that exists. A syntax error, such as a bad indent, has an empty path and the position the parser reports, and the validator is not called.

The subpath uses no node: imports, so it runs in Node, Bun, Deno and the browser. It takes text: reading the file, importing it as raw text or fetching it is yours.

Caveats

  • The file is YAML 1.2. no, yes, on and off stay strings. A YAML 1.1 reader (PyYAML, some older editor plugins) reads them as booleans.
  • An unquoted 1.10 is the number 1.1 in every YAML version. Quote it to keep a string: version: "1.10". The same goes for a value such as 007 or 1e3.
  • One document per file. There are no includes across files.
  • Anchors, aliases and merge keys work inside a file, so a shared value can be written once. A text with more than 100 alias expansions in all is reported as an issue, which guards against files that expand to enormous values.
  • Tags are not supported. !!binary, !!set, !!timestamp, !custom and the like are reported as issues, so the validator only ever sees plain values.
  • Mapping keys are read as strings, so 1: a is the key "1".
  • Duplicate keys in a map are a syntax error.
  • There is no build-time loader, plugin or CLI: parse where you load.

Where to go next