YAML Forms

A form config is plain data, so it can live in a .form.yaml file that people without TypeScript can edit. The @schema-engine/registry/yaml subpath parses the file, hands the value to your engine to validate, and turns every problem into a file, line and column.

Bun's import form from './contact.form.yaml' or a Vite plugin gives you an object, but a validation error then names a config path (steps[0].elements[2].grid.width), not the line the author has to fix. parseYaml keeps the text, so it can do both.

Install

yaml is an optional peer dependency of @schema-engine/registry. Install it in the app that imports the subpath:

pnpm add @schema-engine/forms @schema-engine/registry yaml zod

An app that never imports @schema-engine/registry/yaml does not need yaml and does not bundle it. The subpath uses no node: imports, so it runs in Node, Bun, Deno and the browser.

A form file

# contact.form.yaml
id: contact
steps:
    - id: details
      title: Your details
      elements:
          - $type: input
            id: name
            name: name
            label: Name
            grid: { width: half }
          - $type: input
            id: email
            name: email
            label: Email
            grid:
                width: half

Parse and validate

Pass the text and a validator. engine.safeValidateForm returns the Standard Schema issues parseYaml expects, so it is the validator as it is:

import { parseYaml } from '@schema-engine/registry/yaml';
import { engine } from './engine';

export function parseForm(text: string, filename: string) {
	return parseYaml(text, (value) => engine.safeValidateForm(value), { filename });
}

The result is the same frozen NormalizedFormConfig that engine.validateForm returns for the equivalent JSON. parseYaml throws a YamlDocumentError when the text is not valid YAML or the form does not validate; safeParseYaml takes the same arguments and returns { success: true, data } or { success: false, issues }.

Load the file

The parser takes text, so loading is yours. Pick the one that fits your runtime.

Node and Bun

import { readFile } from 'node:fs/promises';
import { parseForm } from './parse-form';

export async function loadForm(path: string) {
	return parseForm(await readFile(path, 'utf8'), path);
}

Bun can also read it with await Bun.file(path).text().

Vite

Import the file as raw text and parse it in the app:

import contactYaml from './contact.form.yaml?raw';
import { parseForm } from './parse-form';

export const contactForm = parseForm(contactYaml, 'contact.form.yaml');

Vite's vite/client types already declare ?raw imports as strings. Bun does the same with import text from './contact.form.yaml' with { type: 'text' }.

Fetch

import { parseForm } from './parse-form';

export async function fetchForm(url: string) {
	const response = await fetch(url);
	if (!response.ok) {
		throw new Error(`${url}: ${response.status}`);
	}
	return parseForm(await response.text(), url);
}

Show errors with the file and line

A YamlDocumentError lists every issue in error.issues, each with its line, column (counting from 1), filename and config path. Its message has one line per issue, in the file:line:column form that terminals and editors turn into links:

import { YamlDocumentError } from '@schema-engine/registry/yaml';
import { loadForm } from './load-form';

try {
	await loadForm('contact.form.yaml');
} catch (error) {
	if (!(error instanceof YamlDocumentError)) {
		throw error;
	}
	console.error(error.message);
	for (const issue of error.issues) {
		console.error(`${issue.filename}:${issue.line}:${issue.column}`, issue.message);
	}
}

With width: halve on line 17, the message reads:

contact.form.yaml:17:24 steps[0].elements[1].grid.width: Expected one of full, three-quarters, ...

A validation issue points at the start of the value its path names. When the path names a key the file does not have, such as a missing id, it points at the nearest ancestor that exists, here the element's first line. A syntax error, such as a bad indent, has an empty path and the position the parser reports, and the engine is not called. Use safeParseYaml to render the issues yourself, for example in a form builder UI.

Editor autocomplete

Editors with the YAML language server (VS Code's YAML extension, Zed, Neovim) complete keys and flag unknown values from a JSON Schema named in a header comment. The engine generates that schema from what it has registered:

import { writeFile } from 'node:fs/promises';
import { engine } from './engine';

const schema = engine.generateFormConfigSchema({ io: 'input', target: 'draft-7' });
await writeFile('contact.schema.json', JSON.stringify(schema, null, 2));

The schema is generated from the authored side (io: 'input', the default), so fields with defaults stay optional. Use target: 'draft-7' because the YAML language server only learned JSON Schema 2019-09 and 2020-12 in version 1.20.0; an editor extension that bundles an older server reads the schema as draft-07, which every version supports. Then name the schema at the top of the YAML file:

# yaml-language-server: $schema=./contact.schema.json
id: contact

Regenerate the schema when you register another element, recipe or action.

Write a form as YAML

stringifyYaml writes a config back out, for a form builder or a migration. A short map of scalars under a key stays on one line (grid: { width: half }) and every other collection is written in block style. Pass schemaUrl to add the language-server header:

import { stringifyYaml } from '@schema-engine/registry/yaml';
import { engine } from './engine';

const form = engine.validateForm({
	id: 'contact',
	steps: [{ id: 'details', title: 'Details', elements: [] }],
});

export const text = stringifyYaml(form, { schemaUrl: './contact.schema.json' });

Caveats

  • The file is YAML 1.2. no, yes, on and off stay strings, so a label no or an option value on is what it looks like. 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 an id or option 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 field can be written once:

    defaults: &input
        $type: input
        grid: { width: half }
    steps:
        - id: details
          title: Details
          elements:
              - <<: *input
                id: name
                name: name

    A text with more than 100 alias expansions in all is reported as an issue, which guards against files that expand to enormous values. An issue inside merged values points at the map that merges them, and a merge source that is not a map (<<: 5) is reported at line 1, column 1.

  • Tags are not supported. !!binary, !!set, !!timestamp, !custom and the like are reported as issues, so the engine 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.