> **Status:** Published
> **Date:** 2026-09-12
> **Scope**: API Reference
> **Standard**: Memorio API Specification v5
>
---
# Schema Validation - Memorio

> ✅ **Universal**: Works in Browser, Node.js, Deno, and Edge Workers

Schema validation guards your `state` against invalid writes. It runs inside the state proxy's `set` trap, so any `state.somePath = value` that violates a registered schema is rejected at runtime - before the value is ever stored.

Schema validation is **opt-in** and **zero-dependency**.

---

## Quick Start

```javascript
import { memorio, state } from 'memorio'

// Register a validator for a top-level state key
memorio.registerSchema('user', {
  type: 'object',
  required: ['name', 'email'],
  properties: {
    name: { type: 'string', min: 1 },
    email: { type: 'string', pattern: /^[^@]+@[^@]+$/ },
    age: { type: 'number', min: 0, max: 150 }
  }
})

// Valid write - accepted
state.user = { name: 'Sara', email: 'sara@test.com', age: 30 }

// Invalid write - rejected, returns false
state.user = { name: 'Sara' }           // missing 'email'
state.user = { name: 42, email: 'x' }   // wrong type for 'name'
state.user = { age: -5 }                // out of range
```

---

## Schema Definition

A `Schema` object supports the following fields:

| Field | Type | Description |
|-------|------|-------------|
| `type` | `'string' \| 'number' \| 'boolean' \| 'object' \| 'array' \| 'any'` | Runtime type check |
| `required` | `string[]` | Property names that must exist (objects only) |
| `properties` | `Record<string, Schema>` | Nested property schemas (validated recursively) |
| `min` | `number` | Number: minimum value. String: minimum length |
| `max` | `number` | Number: maximum value. String: maximum length |
| `pattern` | `RegExp` | Regex the string value must match |
| `enum` | `any[]` | Whitelist of allowed values |
| `validator` | `(value) => boolean \| string` | Custom validator function |

### Custom validator functions

For logic that's hard to express declaratively, pass a function instead of a schema object:

```javascript
memorio.registerSchema('counter', (value) => {
  if (typeof value !== 'number') return 'counter must be a number'
  if (value < 0) return 'counter must be >= 0'
  return true
})
```

A custom validator receives the raw value. Return `true` to accept, or a **string** describing the error to reject.

---

## Path-based registration

Schemas are keyed by their **state path**, relative to `state`:

| API call | Catches |
|----------|---------|
| `registerSchema('user', schema)` | `state.user = value` |
| `registerSchema('user.age', schema)` | `state.user.age = value` |
| `registerSchema('items', schema)` | `state.items = value` |

The full dotted path is constructed from the proxy's tree depth. Nested sets propagate the full path automatically.

---

## Manual validation

You can validate a value without writing it to state:

```javascript
memorio.validate('user', { name: 'Sara', email: 'sara@test.com' })
// { valid: true }

memorio.validate('user', { name: 'Sara' })
// { valid: false, errors: ["user: missing required property 'email'"] }
```

When no schema is registered for a path, `validate` returns `{ valid: true }`.

---

## Schema management

```javascript
memorio.listSchemas()           // ['user', 'theme', 'items', 'counter']
memorio.unregisterSchema('counter')  // removes the schema
```

---

## Full API

| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| `memorio.registerSchema(path, schema)` | `string`, `Schema \| fn` | `void` | Register a validator |
| `memorio.validate(path, value)` | `string`, `any` | `{ valid, errors? }` | Manually validate a value |
| `memorio.unregisterSchema(path)` | `string` | `boolean` | Remove a registered schema |
| `memorio.listSchemas()` | none | `string[]` | List all registered paths |
| `memorio.registerSchema()` is also importable | `registerSchema` | named export | same function |

---

## Combine with Typed Stores

Schema validation gives you **runtime** safety; typed stores give you **compile-time** safety. Use both for full coverage:

```typescript
import { memorio, state } from 'memorio'

interface AppState {
  user: { name: string; email: string; age: number }
  theme: 'light' | 'dark'
}

const app = memorio.typed<AppState>()

memorio.registerSchema('user', {
  type: 'object',
  required: ['name', 'email'],
  properties: {
    name: { type: 'string', min: 1 },
    email: { type: 'string', pattern: /^[^@]+@[^@]+$/ },
    age: { type: 'number', min: 0, max: 150 }
  }
})

app.user = { name: '', email: 'bad' }   // ❌ TypeScript: age missing
                                         // ❌ Runtime: missing required fields
app.user = { name: 'Sara', email: 'ok', age: 30 } // ✅ both checks pass
```

See [Typed Stores](TYPED.md) for compile-time type safety.

---

## How it works

1. When you call `registerSchema(path, schema)`, the schema is stored in an internal `Map`.
2. On every `state.set` operation, the proxy's `set` trap computes the full path (e.g. `'user.name'`).
3. If a schema is registered for that path, the value is validated.
4. If validation fails, the write is rejected (`return false`), and an error is logged via `console.error` (when `memorio.debug = true`) or `console.debug` (via the internal `message` helper).
5. If no schema is registered, the write proceeds normally.

The validation adds negligible overhead when no schemas are registered (a single `Map` lookup that returns `undefined`).

---

## Limitations

- Schema validation hooks into the `state` proxy only. `store`, `session`, and `cache` are not validated (they use separate storage). Use `validate()` before writing to other modules.
- Path matching is **exact**: `registerSchema('user')` guards `state.user = ...`, but does **not** recursively validate `state.user.name = 'new'`. Register schemas at each path you need to guard.
- The schema system is not a replacement for server-side validation. It protects against accidental misuse and provides defense-in-depth in the browser.
