Learn / Quickstart

Declare what one feature reads and sends

A plain selector like m => m.todos works for rendering, but a server fetcher, offline sync, or AI agent cannot inspect an arbitrary function to learn which fields it reads or which events it triggers. To make those dependencies explicit, register your Model and Message schemas with Surface.application, then call App.surface(...) to declare one feature boundary.

In an ESM project (Node 22+ with "type": "module" in package.json), save this as quickstart.ts and run npx tsx quickstart.ts:

ts
import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import { Surface } from 'foldkit-plus'

const Todo = Schema.Struct({ id: Schema.String, title: Schema.String, done: Schema.Boolean })
const Model = Schema.Struct({ todos: Schema.Array(Todo), filter: Schema.String })
const Message = defineMessageUnion({
  Added: { id: Schema.String, title: Schema.String },
  Filtered: { filter: Schema.String },
})

const update = (model: typeof Model.Type, message: typeof Message.Type) =>
  Message.match(message, {
    Added: ({ id, title }) => ({
      model: modifyFields(model, { todos: list => [...list, { id, title, done: false }] }),
    }),
    Filtered: ({ filter }) => ({ model: modifyFields(model, { filter: () => filter }) }),
  })

const App = Surface.application({ Model, Message })
const TodoList = App.surface('TodoList', {
  model: ({ model }) => ({ todos: model.todos }),
  messages: [Message.Added],
})

const next = update({ todos: [], filter: 'all' }, Message.Added({ id: '1', title: 'Try Foldkit' }))
console.log(Surface.read(TodoList, next.model))
console.log(TodoList.projection().dependencies)

Running npx tsx quickstart.ts prints:

{ todos: [ { id: '1', title: 'Try Foldkit', done: false } ] }
[ [ 'todos' ] ]

What happened:

  • Schema.Struct defines the data shapes and their TypeScript types via .Type.
  • defineMessageUnion creates tagged event constructors (Message.Added(...)) and an exhaustive Message.match helper.
  • update returns { model } with the updated todos array (via modifyFields), leaving filter as 'all'.
  • Surface.read(TodoList, next.model) extracts { todos: [...] } without filter, because TodoList only reads model.todos.
  • TodoList.projection().dependencies returns [['todos']] — the list of Model field paths read by model.todos — without mounting a UI. Server fetching, offline sync, and agent adapters inspect that list to load only what the feature uses, while messages: [Message.Added] restricts which events this feature can send.