# The SpacePress Handbook

> For AI coding agents: start with [/start.md](/start.md) (build playbook) and [/rules.md](/rules.md) (compiler rules), see [/llms.txt](/llms.txt) for the complete documentation index, or read this page as Markdown at [/md/handbook.md](/md/handbook.md).

[View Markdown.md source ↗](/md/handbook.md)[Open in ChatGPTAsk about this page ↗](https://chatgpt.com/?q=Read%20https%3A%2F%2Fspacepress.dev%2Fmd%2Fhandbook.md%20%28The%20SpacePress%20Handbook%29%20and%20help%20me%20with%20questions%20about%20it.)[Open in ClaudeAsk about this page ↗](https://claude.ai/new?q=Read%20https%3A%2F%2Fspacepress.dev%2Fmd%2Fhandbook.md%20%28The%20SpacePress%20Handbook%29%20and%20help%20me%20with%20questions%20about%20it.)[start.mdAgent build playbook ↗](/start.md)[rules.mdCompiler rules ↗](/rules.md)[llms.txtFull site index ↗](/llms.txt)

A thorough, single-page engineering handbook covering every layer of SpacePress — with live, editable WebAssembly compiler sandboxes embedded throughout so you can test every feature as you read.

[3-Minute Quick Start →](https://spacepress.dev/quick-start/)[Open Full Playground](https://spacepress.dev/play/)[Browse Reference](https://spacepress.dev/docs/)

In this handbook

1. [01Project Layout & Mental Model](#mental-model)
2. [02Rust & OXC Compiler](#compiler)
3. [03Data Modeling & Migrations](#data-modeling)
4. [04Queries, Validation & Access](#queries-access)
5. [05Hooks & Lifecycle Events](#hooks)
6. [06Actions, Jobs, Routes & Files](#actions-jobs-routes)
7. [07Pages, Layouts & Islands](#pages-islands)
8. [08Typed Client, React & Astro](#clients-astro)
9. [09WooCommerce Storefront](#woocommerce)
10. [10React Email Templates](#react-email)
11. [11Admin, Gutenberg & Plugins](#admin-plugins)
12. [12Two-Way Markdown Git Sync](#markdown-sync)
13. [13MCP, Abilities & AI Agents](#mcp-agents)
14. [14Hosting, Deploy & CLI](#deploy-cli)

01

## Project Layout & Mental Model

A SpacePress application is a regular TypeScript repository whose single source of truth is `typedpress.config.ts` and the modules under `tp/`. Instead of running a separate Node.js backend beside WordPress, SpacePress compiles your TypeScript directly into native PHP, SQL migrations, TypeScript types, OpenAPI 3.1, and standard WordPress plugins.

**Pre-release package & CLI naming:** SpacePress is the framework and platform brand (`spacepress.dev`). While preparing its 1.0 release, the Rust CLI binary, npm package, config filename, and virtual imports remain spelled `typedpress` (`typedpress.config.ts`, `tp/`, `import ... from "typedpress"`, `typedpress:db`).

my-app/ typedpress.config.ts Config entry & re-exports tsconfig.json TypeScript paths ("typedpress", "typedpress:db") tp/ schema.ts Collections, SQL tables, globals, taxonomies server.ts Actions, background jobs, helpers app/ layout.tsx Root layout & shared metadata page.tsx Home page (/) not-found.tsx Custom 404 page posts/\[slug\]/page.tsx Dynamic item route api/feed.json/route.ts Custom HTTP route components/ Server & "use client" components wp-hooks/ Typed WordPress core actions & filters \_generated/ Compiler-emitted db.d.ts, routes.d.ts, client/, migrations/ dist/wp-content/ Built WordPress plugins (ready to deploy) content/ Markdown/JSON files synced with WordPress emails/ React Email templates rendered by mail.render() public/ Static assets served at site root

### Explore a complete multi-file SpacePress app

Click any file in the tree below to inspect how schema, server actions, layouts, dynamic routes, and interactive client islands fit together in a single project.

import { action, integer, HttpError } from "typedpress"; import { articles, claps } from "typedpress:db"; export const clap = action({ access: "anyone", input: { articleId: integer() }, async handler({ articleId }) { const article = await articles.get(articleId); if (!article) throw new HttpError(404, "not\_found", "Article not found"); const existing = await claps.system.get({ articleId }); if (existing) { const updated = await claps.system.update(existing.id, { count: existing.count + 1 }); return { count: updated.count }; } const created = await claps.system.create({ articleId, count: 1 }); return { count: created.count }; }, }); import { Content, Link, type PageProps } from "typedpress/app"; import { claps } from "typedpress:db"; import { ClapButton } from "../../../components/ClapButton"; export const metadata = ({ item }: PageProps<"articles/\[slug\]">) => ({ title: item.title, description: item.summary ?? undefined, }); export default async function ArticlePage({ item }: PageProps<"articles/\[slug\]">) { const row = await claps.get({ articleId: item.id }); return ( \<article> \<p>\<Link href="/">← All articles\</Link>\</p> \<h1>{item.title}\</h1> \<Content value={item.body} /> \<ClapButton articleId={item.id} initial={row?.count ?? 0} /> \</article> ); } import { Link, type LayoutProps } from "typedpress/app"; export const template = "blank"; export const metadata = { title: { default: "Editorial", template: "%s · Editorial" }, description: "Server-rendered TSX pages backed by WordPress.", }; export default function Layout({ children }: LayoutProps) { return ( \<div className="shell"> \<header> \<Link href="/">Editorial\</Link> \</header> \<main>{children}\</main> \</div> ); } "use client"; import { useState } from "typedpress/client"; import { clap } from "../actions"; export function ClapButton({ articleId, initial }: { articleId: number; initial: number }) { const \[count, setCount\] = useState(initial); const \[busy, setBusy\] = useState(false); return ( \<button type="button" disabled={busy} onClick={async () => { setBusy(true); const res = await clap({ articleId }); setCount(res.count); setBusy(false); }} > {count} {count === 1 ? "clap" : "claps"} \</button> ); } import { collection, table, text, integer, richText, slug, ref, timestamp } from "typedpress"; export const articles = collection({ title: text().min(1).max(140), slug: slug({ source: "title" }).optional(), summary: text({ multiline: true }).max(260).optional(), body: richText().optional(), updatedAt: timestamp().defaultNow().$onUpdate(() => new Date()), }, { label: "Articles", title: "title", content: "body", url: "/articles/:slug", sync: "content/articles/\*.md", access: { read: "anyone", create: "author", update: "editor", delete: "editor" }, }); export const claps = table({ articleId: ref(articles).unique().onDelete("cascade"), count: integer().default(0), }, { access: { read: "anyone", create: "admin", update: "admin", delete: "admin" }, }); import { defineConfig } from "typedpress"; export \* from "./tp/schema"; export \* from "./tp/actions"; export default defineConfig({ name: "editorial", seed: true, });

02

## How the Rust & OXC Compiler Works

SpacePress parses your TypeScript and TSX files with **OXC** in Rust. There is no Node.js runtime, V8 isolate, or JavaScript execution layer in production — every server artifact runs as plain, idiomatic PHP inside WordPress. During compilation, the OXC AST pass also runs non-fatal lint checks including `capital\_P\_dangit` (flagging a lowercase “p” in WordPress or SpacePress copy, auto-fixable via `typedpress check --fix` or in the live sandboxes below).

| What you author | What the compiler emits | Where it runs |
|---|---|---|
| `collection()`, `table()`, `global()`, `taxonomy()`, `store()` | `tp/app/schema.php` + numbered SQL migrations in `tp/\_generated/migrations/` | WordPress PHP runtime & MySQL/SQLite |
| `action()`, `job()`, `.on()` hooks, `.validate()`, access functions, `route.ts` | `tp/app/functions.php` | Native PHP in WordPress / Action Scheduler |
| `tp/app/\*\*/page.tsx` & `layout.tsx` | Server-rendered PHP functions inside `functions.php` | Native PHP (or prebuilt HTML with `output: "static"`) |
| `"use client"` components | Server-rendered PHP HTML + WordPress Interactivity API ES module | PHP first paint + browser Interactivity API hydration |
| Schema & actions graph | `tp/\_generated/db.d.ts`, `routes.d.ts`, `openapi.json`, `client/` | IDE type checking, external browsers, React & Astro |

### Try the live compiler right here

Switch output tabs on the right to inspect every generated artifact from this single TypeScript file, or edit the code on the left to watch compilation happen in milliseconds inside WebAssembly.

03

## Data Modeling: Collections, Tables, Globals & WordPress Kinds

SpacePress gives you six storage primitives — each chosen for a distinct job, all unified under one query and access API:

| Builder | Backing Storage | Best For |
|---|---|---|
| `collection(fields, opts)` | WordPress custom post type (`wp\_posts` + meta) | Editorial content needing Gutenberg, drafts, revisions, staged versions, comments, hierarchical paths, or Markdown sync |
| `table(fields, opts)` | Dedicated SQL table with automatic migrations | Relational app data, high-volume records, logs, shares, votes, compound indexes (`.index(\[...\])`) |
| `global(fields, opts)` | Singleton WordPress options record | Site settings, navigation links, banner copy, feature flags (`db.globals.<key>`) |
| `wp.posts.extend()` / `.clone()` | WordPress built-in `post` type (or cloned CPT) | Extending native WordPress blog posts with typed custom fields, URL pattern, and sync |
| `userProjection(fields, opts)` | `wp\_users` + `wp\_usermeta` | Typed member profiles and account attributes without creating a duplicate user table |
| `taxonomy(fields, opts)` | WordPress taxonomy & term tables | Hierarchical or flat vocabularies attached to collections via `on: \[posts\]` or `terms(tax)` |

### Field Builders & Modifiers

Every field is **required (NOT NULL) by default** unless marked `.optional()`. Defaults (`.default()`, `.defaultNow()`, `.$default()`, `.$onUpdate()`) make fields omittable on insert.

| Category | Builders | Key Modifiers |
|---|---|---|
| Scalars | `text({ multiline? })`, `integer()`, `number()`, `boolean()`, `date()`, `timestamp()`, `json<T>()` | `.optional()`, `.default(v)`, `.defaultNow()`, `.$default(fn)`, `.$onUpdate(fn)`, `.unique()`, `.min(n)`, `.max(n)`, `.pattern(/re/)` |
| Semantic & Editorial | `email()`, `url()`, `slug({ source })`, `richText()`, `select(\[...\])` | `select(\[...\]).many()` (JSON list filtered with `{ has: x }`), `.validate((v, ctx) => ...)` |
| Media, Files & Relations | `media({ accept })`, `file(bucket)`, `ref(kind)`, `terms(tax)` | `.many()`, `.onDelete("cascade" \| "restrict" \| "setNull")`, `.reverse("name")` |
| Structured & Flexible | `group(fields)`, `repeater(fields)`, `blocks(layouts)` | `.min(n)` / `.max(n)` item counts, `.ui({ label, help, placeholder, width })`, `.showIf({ ... })` |
| Migrations & Renames | `field.was("oldName")`, `table(..., { was: "old\_table", existingTable })` | Preserves existing rows and column values across deploys without data loss |

### Interactive Schema Evolution & SQL Migration Diff

The sandbox below compiles against a baseline snapshot containing a 3-column `bookmarks` table. Edit the evolved schema — add a field, change a constraint, or rename `title` using `.was("title")` — and watch the numbered `0002\_\*.sql` migration update live.

import { table, text, boolean, select, integer, timestamp, defineConfig } from "typedpress"; // Try renaming \`title\` -> \`label: text().max(140).was("title")\` or adding another column! export const bookmarks = table({ title: text().max(140), url: text().max(191).unique(), category: select(\["docs", "article", "tool"\]).default("article"), rating: integer().min(1).max(5).optional(), archived: boolean().default(false), updatedAt: timestamp().defaultNow().$onUpdate(() => new Date()), }).index(\["category", "archived"\]); export default defineConfig({ name: "bookmarks" });

04

## Queries, Mutations, Validation & Declarative Access Rules

SpacePress provides two database interfaces so authorization is always explicit:

- **Visitor-scoped Kind API (`import { posts } from "typedpress:db"`):** Every call (`list`, `paginate`, `get`, `count`, `create`, `update`, `delete`) enforces the current visitor's access rules, draft visibility, and field masks. Use `posts.system.\*` only when intentionally escalating to trusted system access.
- **Trusted Database API (`import { db } from "typedpress"`):** Drizzle-inspired relational queries (`db.query.<kind>.findMany()`, `findFirst()`), writes (`db.insert()`, `db.update()`, `db.delete()` with `.returning()`), and `db.globals.<key>.get()` / `.update()`. Ideal inside hooks, background jobs, and already-authorized server actions.

import { db } from "typedpress"; import { posts } from "typedpress:db"; // Visitor-scoped: enforces read rules, draft visibility & field masks const { rows, cursor } = await posts.paginate({ where: { tags: { has: "release" } }, orderBy: { publishedAt: "desc" }, with: { authorId: true, cover: true }, limit: 20, }); // Trusted system query inside an action or background job const draftCount = await db.query.posts.findMany({ where: { OR: \[{ status: "draft" }, { status: "scheduled" }\] }, columns: { id: true }, });

### Role Ladder & Declarative Access Control

Roles form an ordered ladder: `guest < subscriber < author < editor < admin`. Naming a role admits that role and every role above it. Shorthands also include `"anyone"`, `"authenticated"`, `"self"` (for user projections), or a boolean. For row-level authorization, pass a function returning either a boolean or a filter object — SpacePress compiles it to PHP and pushes row filters into SQL queries so unauthorized rows return 404.

05

## Hooks & Lifecycle Events

Attach lifecycle hooks directly to any collection or SQL table with `.on({ ... })`. Every hook compiles to native PHP and executes inside the write's transaction: throwing an `HttpError` (or any error) aborts the request and rolls back all changes cleanly.

- `beforeCreate(data, ctx)` / `afterCreate(row, ctx)` — normalize input, enforce invariants, compute derived fields, or enqueue post-commit jobs.
- `beforeUpdate(patch, existing, ctx)` / `afterUpdate(row, previous, ctx)` — react to field transitions with both old and new rows.
- `beforeDelete(row, ctx)` / `afterDelete(row, ctx)` — run on permanent delete (trashing a WordPress post fires update hooks; emptying trash fires delete hooks).
- `afterPublish(row, ctx)` — fires whenever a collection item transitions to published (on create, update, or scheduled publish).

### Typed WordPress Core Hooks (`tp/wp-hooks/`)

Need to tap directly into WordPress core filters or actions (`the\_content`, `pre\_get\_posts`, `wp\_head`, `wp\_mail`, `save\_post`, etc.)? Place a file in `tp/wp-hooks/<hook>.ts` using the typed `Handler<"...">` helper from `"php/wordpress"`.

// tp/wp-hooks/the\_content.ts import type { Handler } from "php/wordpress"; export const priority = 20; const wrapContent: Handler<"the\_content"> = (content) => { return \`<div class="prose-frame">${content}</div>\`; }; export default wrapContent;

06

## Server Actions, Background Jobs, HTTP Routes & Files

Beyond CRUD endpoints, SpacePress compiles three server primitives directly into WordPress:

- **Server Actions (`action()`):** Mounted at `POST /\_\_tp/api/v1/actions/<name>`, validated with the same column builders, protected by `access` (default `"editor"`), optionally signed via HMAC webhook verification (`signature`), and annotated with `idempotent`, `readonly`, or `destructive` for AI agents.
- **Background Jobs (`job()`):** Dispatched via `jobs.<name>.enqueue(input, { delay?, key? })` onto WordPress's **Action Scheduler**. Enqueueing inside a hook or action commits atomically with the database write, supports automatic `retries`, dedupe `key`s, and idempotency guards via `once(key, fn)`.
- **Custom HTTP Routes (`tp/app/.../route.ts`):** Export `GET`, `POST`, `PUT`, `PATCH`, or `DELETE` handlers plus `export const guard` to serve JSON feeds, webhooks, robots.txt, or custom endpoints at any clean URL outside `/wp-json`.
- **Private File Buckets (`files()`) & Signed Webhooks:** Store private uploads locally or on S3-compatible storage (`uploads: { backend: "s3", ... }`) with automatic 5-minute signed download URLs, and emit signed `TypedPress-Signature` HMAC webhooks on any `<kind>.created|updated|deleted` event.

// tp/app/api/feed.json/route.ts import { db, type RouteRequest } from "typedpress"; export const guard = "anyone"; export async function GET(req: RouteRequest) { const limit = Number(req.query.get("limit") ?? "10"); const rows = await db.query.posts.findMany({ where: { status: "published" }, orderBy: { id: "desc" }, limit: limit > 0 && limit <= 50 ? limit : 10, }); return { headers: { "content-type": "application/feed+json" }, body: JSON.stringify({ version: "https://jsonfeed.org/version/1.1", title: "SpacePress Feed", items: rows.map((p) => ({ id: String(p.id), title: p.title })), }), }; }

07

## Pages, Layouts, Server Components & "use client" Islands

Drop TSX files into `tp/app/` to build full server-rendered websites and apps without leaving TypeScript. SpacePress compiles every page and layout into PHP that executes directly inside WordPress.

| Convention / Export | Behavior |
|---|---|
| `tp/app/page.tsx`, `\[slug\]/page.tsx`, `\[...path\]/page.tsx`, `(group)/` | File-based routing. When a folder matches a collection's `url` pattern (e.g. `/blog/:slug`), SpacePress injects the fetched `item` automatically and returns 404 for drafts/missing slugs. |
| `layout.tsx`, `not-found.tsx`, `login.tsx` | Nested shared layouts, custom 404 view, and custom `wp-login.php` screen with `<LoginForm />`. |
| `export const metadata` / function | Title templates (`{ default, template }`), description, canonical, robots, Open Graph, Twitter cards, custom `<link>` tags, and `scripts` from `public/`. |
| `export const template` | `"theme"` (wraps page in active block theme header/footer), `"blank"` (layout draws its own shell), or any block template slug. |
| `export const search` & `guard` | Typed query-string parsing (e.g. `{ page: integer().default(1) }`) and route-level access guards. |
| `output: "static"` + `staticParams()` | Prebuilds pages into standalone HTML via `typedpress export` — no WordPress server needed at serve time. |
| Built-in UI primitives (`typedpress/app`) | `<Link>` (client-side router navigation), `<Content>`, `<Html>`, `<Comments>`, `<Pagination>`, `<Search>`, `<SearchResults>`, `<TemplatePart>`, `<Live>`, `useFormState()`. |
| `"use client"` (`typedpress/client`) | Compiles server HTML + a WordPress Interactivity API module supporting `useState`, `useEffect`, `useMount`, `useEvent`, `useRef`, `sharedState`, and real-time `useLive()` subscriptions. |

CSS imports (`import "./site.css"`) and CSS Modules (`import styles from "./card.module.css"`) are content-hashed and copied automatically into the built app plugin. Inspect the layout, page, and `"use client"` island from our editorial example:

import { action, integer, HttpError } from "typedpress"; import { articles, claps } from "typedpress:db"; export const clap = action({ access: "anyone", input: { articleId: integer() }, async handler({ articleId }) { const article = await articles.get(articleId); if (!article) throw new HttpError(404, "not\_found", "Article not found"); const existing = await claps.system.get({ articleId }); if (existing) { const updated = await claps.system.update(existing.id, { count: existing.count + 1 }); return { count: updated.count }; } const created = await claps.system.create({ articleId, count: 1 }); return { count: created.count }; }, }); import { Content, Link, type PageProps } from "typedpress/app"; import { claps } from "typedpress:db"; import { ClapButton } from "../../../components/ClapButton"; export const metadata = ({ item }: PageProps<"articles/\[slug\]">) => ({ title: item.title, description: item.summary ?? undefined, }); export default async function ArticlePage({ item }: PageProps<"articles/\[slug\]">) { const row = await claps.get({ articleId: item.id }); return ( \<article> \<p>\<Link href="/">← All articles\</Link>\</p> \<h1>{item.title}\</h1> \<Content value={item.body} /> \<ClapButton articleId={item.id} initial={row?.count ?? 0} /> \</article> ); } import { Link, type LayoutProps } from "typedpress/app"; export const template = "blank"; export const metadata = { title: { default: "Editorial", template: "%s · Editorial" }, description: "Server-rendered TSX pages backed by WordPress.", }; export default function Layout({ children }: LayoutProps) { return ( \<div className="shell"> \<header> \<Link href="/">Editorial\</Link> \</header> \<main>{children}\</main> \</div> ); } "use client"; import { useState } from "typedpress/client"; import { clap } from "../actions"; export function ClapButton({ articleId, initial }: { articleId: number; initial: number }) { const \[count, setCount\] = useState(initial); const \[busy, setBusy\] = useState(false); return ( \<button type="button" disabled={busy} onClick={async () => { setBusy(true); const res = await clap({ articleId }); setCount(res.count); setBusy(false); }} > {count} {count === 1 ? "clap" : "claps"} \</button> ); } import { collection, table, text, integer, richText, slug, ref, timestamp } from "typedpress"; export const articles = collection({ title: text().min(1).max(140), slug: slug({ source: "title" }).optional(), summary: text({ multiline: true }).max(260).optional(), body: richText().optional(), updatedAt: timestamp().defaultNow().$onUpdate(() => new Date()), }, { label: "Articles", title: "title", content: "body", url: "/articles/:slug", sync: "content/articles/\*.md", access: { read: "anyone", create: "author", update: "editor", delete: "editor" }, }); export const claps = table({ articleId: ref(articles).unique().onDelete("cascade"), count: integer().default(0), }, { access: { read: "anyone", create: "admin", update: "admin", delete: "admin" }, }); import { defineConfig } from "typedpress"; export \* from "./tp/schema"; export \* from "./tp/actions"; export default defineConfig({ name: "editorial", seed: true, });

08

## Generated Typed Client, React Hooks & Astro Integration

Want to pair a SpacePress backend with a React SPA, Next.js, TanStack Start, Vite, or Astro frontend? Every build writes a zero-dependency typed client into `tp/\_generated/client/` alongside framework-agnostic React hooks (`react.ts`) that accept your own React 18+ or Preact instance via `createHooks(React)`.

import \* as React from "react"; import { createClient } from "./tp/\_generated/client/index"; import { createHooks } from "./tp/\_generated/client/react"; export const client = createClient({ baseUrl: "https://api.example.com" }); export const { useQuery, useMutation } = createHooks(React); export function TaskCounter() { const { data, loading } = useQuery(client.tasks.list({ where: { done: false } })); const toggle = useMutation( (id: number) => client.actions.completeTask({ id }), { optimistic: (apply, id) => { apply(client.tasks.list({ where: { done: false } }), (rows) => rows.filter((t) => t.id !== id), ); }, }, ); if (loading) return \<p>Loading…\</p>; return \<p>{data?.length ?? 0} open tasks\</p>; }

### First-Class Astro Integration (`@typedpress/astro`)

Use `@typedpress/astro` to connect any SpacePress backend to Astro's Content Layer with build-time (`tpLoader`) or on-demand live collections (`tpLiveLoader`), automatic cache tags, signed webhook invalidation (`tpWebhook`), and `frontend: "https://..."` in `defineConfig()` so WordPress permalinks and previews point to your external frontend.

// src/content.config.ts (Astro 7+) import { defineCollection } from "astro:content"; import { tpLoader, tpLiveLoader } from "@typedpress/astro"; export const collections = { // Build-time static collection docs: defineCollection({ loader: tpLoader("docs", { where: { status: "published" } }), }), // Live on-demand collection with cacheHint.tags (\<kind>, \<kind>:\<id>) posts: defineCollection({ loader: tpLiveLoader("posts", { rendered: "entries" }), }), }; // src/pages/api/tp-webhook.ts — verifies TypedPress-Signature & invalidates tags import { tpWebhook } from "@typedpress/astro"; export const POST = tpWebhook();

09

## WooCommerce Native Storefront

SpacePress treats WooCommerce as a first-class typed runtime rather than an afterthought. Declare `store()`, `product()`, `productCategory()`, `productTag()`, and `order()` in TypeScript — or scaffold a complete storefront into any project with `typedpress add shop`.

- **Declarative Store Settings:** Currency, store country & address, selling regions, weight/dimension units, shipping zones & methods (`flatRate`, `freeShipping`, `localPickup`), payment gateways, and store email sender.
- **Synced Catalogs:** Products, categories, and tags support `sync: "content/products/\*.md"` and clean URL patterns like `/products/:slug`.
- **Optimistic Cart Client & React Hooks:** Whenever a project exports a `store()`, `typedpress build` automatically emits `commerce.ts`, `cart-store.ts`, and `cart-react.ts` into `tp/\_generated/client/` with optimistic quantity updates and rollback.

import \* as React from "react"; import { createCartHooks } from "./tp/\_generated/client/cart-react"; export const { useCart, useCartCount } = createCartHooks(React); export function CartBadge() { const count = useCartCount(); return \<a href="/cart">Cart ({count ?? 0})\</a>; }

10

## React Email Templates & Transactional Mail

Author transactional emails as React components under `emails/\*.tsx` using `react-email`. Inside hooks, actions, routes, or background jobs, render them to both HTML and plain text with `mail.render(Template, props)` and queue delivery with `mail.send()`.

Every `mail.send()` call participates in the handler's database transaction: the message is handed off to the site's mail transport only after commit (with automatic retries on failure), and a rollback sends nothing.

// emails/invitation.tsx import { Body, Button, Html, Text } from "react-email"; export interface InvitationProps { name: string; url: string; } export default function Invitation({ name, url }: InvitationProps) { return ( \<Html lang="en"> \<Body> \<Text>Hello, {name}!\</Text> \<Button href={url}>Accept invitation\</Button> \</Body> \</Html> ); } // tp/server.ts — transactional send queued in-transaction & retried after commit import { action, email, text, mail } from "typedpress"; import Invitation from "../emails/invitation"; export const inviteMember = action({ access: "admin", input: { to: email(), name: text().max(80) }, async handler({ to, name }) { const rendered = mail.render(Invitation, { name, url: "https://example.com/accept", }); return await mail.send({ to, subject: \`You're invited, ${name}\`, html: rendered.html, text: rendered.text, }); }, });

11

## WordPress Admin, Gutenberg, Custom Screens & Plugins

Every SpacePress build ships **SpacePress Admin** (`typedpress-admin`) at `/wp-admin/new/` alongside classic `wp-admin` (opt out with `admin: false`). Collections automatically get Gutenberg editing, drafts, revisions, and **staged versions** (save a parallel staged edit, compare, promote, or discard via CLI or Admin).

- **Custom Admin Screens (`adminScreen()`):** Build rich DataViews tables/grids or DataForms backed by your `readonly: true` and mutation actions. One declarative definition renders in both `/wp-admin/new/screens/<slug>` and classic `wp-admin`.
- **Gutenberg Blocks & Block Themes in TSX (`@typedpress/blocks`):** Author real Gutenberg post content and complete block themes in TSX — HTML tags map to core blocks (`<p>` → `core/paragraph`) while `blockComponent()` and `<Block name="..." />` target any registered block.
- **Locked WordPress Plugins & Sealed Mode:** Declare WordPress.org or URL plugins in `defineConfig({ plugins: { ... }, sealed: true })` with exact versions and SHA-256 checksums locked in `tp/\_generated/wp-plugins.lock.json`. In `sealed: true` mode, activating any undeclared plugin is refused.
- **TypeScript Plugin Packages (`definePlugin()` + `use`):** Compose reusable SpacePress packages with `use: \[myPlugin(...)\]`. The compiler infers exact capabilities from compiled code and locks grants in `tp/\_generated/plugins.lock.json`.

12

## Two-Way Markdown & Git Sync

Add `sync: "content/docs/\*\*/\*.md"` (hierarchical folder tree) or `sync: "content/posts/\*.md"` (flat folder) to any collection or taxonomy. SpacePress assigns each record a permanent `uid` and keeps your repository and WordPress database synchronized in both directions.

\--- uid: zr\_8f31c902a1d44b8e72a1 title: Getting Started with SpacePress description: Install the CLI and launch your first local WordPress site. order: 1 status: published publishedAt: 2026-11-21T09:00:00.000Z --- Write documentation or blog posts in plain Markdown. Front matter keys are validated against your TypeScript schema at sync time — typos fail with the exact file and line.npx typedpress sync

- **3-way merge & conflict detection:** Tracks the last synced base state so non-overlapping edits in Git and WordPress merge cleanly, while true conflicts are flagged explicitly.
- **GitHub workflow automation:** Run `typedpress init --github` to scaffold automated sync workflows and configure `typedpress git-dispatch` so saves in WordPress Admin notify your repository automatically.
- **Standalone seeding:** Enable `seed: true` in `defineConfig()` so fresh deployments seed synced content on plugin activation without overwriting existing editorial changes.

13

## MCP, WordPress Abilities & AI Agents

SpacePress is built from day one for coding agents and runtime AI workflows:

- **Project MCP Server (`typedpress mcp`):** Serves your project's schema, routes, diagnostics, and embedded version-matched documentation over stdio MCP. Run `typedpress init` to generate `AGENTS.md`, `.mcp.json`, and agent skills automatically.
- **WordPress Abilities API:** Collections, globals, actions, and jobs are exposed as WordPress Abilities by default (`agents: false` opts out). Annotate actions with `readonly: true` or `destructive: true` so AI agents know when to ask for confirmation. Call any installed site ability with full type safety via `abilities.call()` after running `typedpress abilities pull --site <url>`.
- **Runtime Schema Versions (`runtimeSchema: true`):** Allow live sites to evolve collections and fields as numbered schema versions, then pull them back into source control with `typedpress pull`.

import { action, text } from "typedpress"; import { abilities } from "php/wordpress"; // Call any registered WordPress Ability with compiled input/output types export const runSiteCheck = action({ access: "admin", readonly: true, input: { target: text().max(120) }, async handler({ target }) { return await abilities.call("core/get-site-info", {}); }, });

14

## Hosting, Deployment, Packaging & CLI Reference

Because SpacePress compiles down to standard PHP and WordPress plugins, you can deploy anywhere WordPress runs — **Spacefast**, **Pressable**, **WordPress.com**, **self-hosted WordPress** (VPS/Docker/LAMP), or static CDN hosting (with `output: "static"`).

| Command | Purpose |
|---|---|
| `typedpress dev` / `dev stop` / `dev status` | Start, stop, or inspect the local WordPress + SQLite dev server with automatic rebuilds on file change. |
| `typedpress check` | Type-check and validate schemas, hooks, actions, pages, and migrations without writing output (supports `--json` and `--frozen` for CI). |
| `typedpress build` | Emit WordPress plugins into `tp/dist/wp-content/plugins/`, SQL migrations, `db.d.ts`, `openapi.json`, and typed client. |
| `typedpress export` | Export `tp/app/` as a standalone static HTML site to `tp/dist/static/` (when `output: "static"`). |
| `typedpress sync` | Two-way sync between local Markdown/JSON content files and the WordPress database. |
| `typedpress add <shop\|db\|api-reference>` | Add starter modules into your project as source files you own (never overwrites existing files). |
| `typedpress plugin` | Write uploadable `typedpress.zip` for manual activation inside `wp-admin`. |
| `typedpress login <url>` & `typedpress push` | Authenticate via WordPress Application Passwords and deploy your compiled app, plugins, and migrations directly to a live site. |
| `typedpress doctor` | Verify build integrity, plugin versions, live site state, and (with `--links`) crawl every internal link and anchor. |
| `typedpress wp ...`, `migrate`, `jobs`, `staged`, `identity` | Direct site operations via WP-CLI against local dev or remote `--site` targets. |

### Boot a full multi-file SpacePress app in WordPress Playground

Try editing **Field Notes** (`full-site`) below — it combines collections, field-level access rules, a SQL applause table, a server action, dynamic TSX routes, a custom JSON Feed route, and a `"use client"` island. Compile it live and click **Run in WordPress** to test it in-tab.
