Schema Validation
tosijs-platform uses tosijs-schema for schema-first type definitions and validation throughout the stack.
Overview
Schema validation provides:
- Type safety - Define schemas once, infer TypeScript types automatically
- Server-side validation - Automatic validation in doc endpoints before data is stored
- Client-side validation - Schema-driven form editors with built-in validation
- Structured LLM responses - Use schemas with the
/genendpoint for validated JSON output
Defining Schemas
Schemas are defined in functions/shared/ using tosijs-schema's builder syntax:
import { s, type Infer } from 'tosijs-schema'
export const PageSchema = s.object({
title: s.string,
description: s.string,
path: s.string,
imageUrl: s.string,
source: s.string,
tags: s.array(s.string).optional,
type: s.string.optional,
})
export type Page = Infer<typeof PageSchema>
Available Types
| Type | Example |
|---|---|
| String | s.string |
| Number | s.number |
| Integer | s.integer |
| Boolean | s.boolean |
| Array | s.array(s.string) |
| Object | s.object({ key: s.string }) |
| Enum | s.enum(['a', 'b', 'c']) |
| Optional | s.string.optional |
Constraints
// String constraints
s.string.min(1).max(100) // Length limits
s.string.pattern(/^\d+$/) // Regex pattern
s.string.email // Email format
s.string.url // URL format
// Number constraints
s.number.min(0).max(100) // Range
s.integer.min(0) // Non-negative integer
// Array constraints
s.array(s.string).min(1).max(10) // Array length limits
Metadata
Add metadata for documentation and UI hints:
export const RoleSchema = s
.object({
name: s.string.title('Name').describe('Display name for this role'),
roles: s.array(s.string).title('Roles'),
})
.title('Role')
.describe('User role assignment configuration')
Collection Schema Validation
Add schemas to collection configurations for automatic server-side validation:
// functions/src/page.ts
import { PageSchema } from '../shared/page'
COLLECTIONS.page = {
schema: PageSchema, // Automatic validation
unique: ['path'],
access: {
// ... access rules
},
}
Validation Flow
- Schema validation runs first - Checks types, constraints, and required fields
- Custom validate() runs second - Business logic like auto-generating paths
- Unique constraints checked last - Ensures field uniqueness
Error Response
When schema validation fails, the endpoint returns a detailed error:
{
"error": "schema validation failed",
"details": [
{ "path": "title", "message": "Required field missing" },
{ "path": "version", "message": "Pattern mismatch" }
]
}
Structured LLM Responses
The /gen endpoint supports schema-validated structured output:
// Request with schema
const response = await fetch('/gen', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
prompt: 'Extract the name and email from: John Doe <john@example.com>',
schema: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
}
})
})
const result = await response.json()
// {
// modelId: 'gemini-2.5-flash-lite',
// prompt: '...',
// data: { name: 'John Doe', email: 'john@example.com' },
// valid: true
// }
Using Schema Builders
You can pass the .schema property from tosijs-schema builders:
import { ContactSchema } from './shared/role'
const response = await fetch('/gen', {
method: 'POST',
body: JSON.stringify({
prompt: 'Parse this contact info...',
schema: ContactSchema.schema // Raw JSON Schema
})
})
Schema-Driven Editor Component
The <schema-editor> component generates forms from JSON schemas:
import { schemaEditor } from './schema-editor'
import { RoleSchema } from '../functions/shared/role'
// Render a form for editing roles
schemaEditor({
schema: RoleSchema.schema,
value: existingRole,
onChange: (value, isValid) => {
console.log('Form data:', value)
console.log('Is valid:', isValid)
}
})
Schema-to-Field Mapping
| Schema Property | Form Field |
|---|---|
type: 'string' |
Text input |
type: 'string' + multiline: true |
Textarea |
type: 'number' / type: 'integer' |
Number input |
type: 'boolean' |
Checkbox |
enum: [...] |
Select dropdown |
type: 'array' |
Repeatable field group |
type: 'object' |
Nested fieldset |
Metadata in UI
title→ Field labeldescription→ Tooltip/help textdefault→ Initial valueminimum/maximum→ Input min/max attributespattern→ Input pattern attribute
Role Manager
The Role Manager (<role-manager>) is a built-in admin tool for managing user roles:
- Available from the menu for admin, developer, and owner roles
- Uses the schema-driven editor for role editing
- Full CRUD operations for role records
Shared Schema Files
| File | Schemas |
|---|---|
functions/shared/page.ts |
PageSchema, PrefetchSchema |
functions/shared/module.ts |
ModuleSchema |
functions/shared/book.ts |
BookSchema, LinkSchema, BlockSchema, SectionSchema |
functions/shared/role.ts |
RoleSchema, ContactSchema |
functions/shared/post.ts |
PostSchema |
Best Practices
- Define schemas in
functions/shared/- Keeps them accessible to both server and client - Export both schema and type -
export const MySchema = ...andexport type My = Infer<typeof MySchema> - Use metadata for UX - Add
title()anddescribe()for better form labels - Keep validate() for business logic - Use schemas for structure, custom validate for computed fields
- Test with emulators - Run
bun start-emulatedto test validation locally