Skip to content

About

SpacePress is a toolkit for building sites to full-stack apps with ~TypeScript, fast.

Resources

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

1,165 Commits

Folders and files

Repository files navigation

SpacePress

The TypeScript framework that compiles directly to WordPress.

Write schemas, access rules, queries and mutations, background jobs, HTTP routes, and TSX pages in TypeScript. SpacePress compiles your project with Rust and oxc into readable PHP, forward-only SQL migrations, OpenAPI 3.1, a typed client, and standard WordPress plugins — with no Node.js in production.

spacepress.dev · Docs · Browser Playground · Contributing


Why SpacePress

  • TypeScript in, standard WordPress out. Production runs on standard WordPress 7.1+ and PHP 8.2+ (MySQL 8.0+, MariaDB 10.11+, or SQLite). The compiler emits readable, inspectable GPL-2.0-or-later PHP plugins — no proprietary server runtime, no Node process to operate, and no host lock-in.
  • Native WordPress pages by default, headless when you want it. Server-rendered TSX pages, layouts, progressive forms, and "use client" islands (compiled to the WordPress Interactivity API) run directly inside WordPress. Every build also emits OpenAPI 3.1 and a typed client (spacepress/client, spacepress/react) for external frontends and @spacepress/astro, or exports static HTML with spacepress export.
  • Both WordPress content and real SQL tables. Store editorial content as WordPress posts (collection(), extend("posts")) for Gutenberg, revisions, comments, and Markdown sync, right alongside custom relational SQL tables (table()) with compound indexes and forward-only migrations.
  • Compile-time safety. Schemas, queries, handlers, forms, and routes are type-checked against your data model before a line of PHP runs. Unsupported constructs fail at build time with file:line:col diagnostics instead of runtime surprises.

Quick Start

Requires Node.js 22+. Prebuilt native Rust compiler binaries install automatically via npm on macOS and Linux (arm64 / x64) — no Rust toolchain or Docker required (spacepress dev requires glibc on Linux for WordPress Studio).

npm create spacepress@0.3.2 my-app
cd my-app
npm run dev

npm run dev runs spacepress dev: it compiles your TypeScript, boots a local WordPress + SQLite site (PHP 8.4 via WordPress Studio CLI), activates the generated plugins, and rebuilds on save. Open the printed URL for your site and /wp-admin/new/ for SpacePress Admin.

  • Zero-config Markdown: A directory containing only .md files also builds with spacepress build — no spacepress.config.ts or package.json required.
  • Coding agents: create-spacepress runs spacepress init automatically to generate AGENTS.md, .mcp.json, and 10 agent skills. Run spacepress mcp for a stdio MCP server with version-matched docs and live compiler checks, or point an agent at spacepress.dev/start.md and spacepress.dev/rules.md.

What a SpacePress App Looks Like

1. Define schemas, access rules, hooks, and jobs

// spacepress.config.ts
import { defineConfig, extend, f, job, table } from "spacepress";

// Runs on WordPress Action Scheduler with retries and dedupe keys
export const notifyTask = job({ retries: 3 }, async ({ db }, { taskId }: { taskId: number }) => {
  await db.tasks.get(taskId);
});

// Extend native WordPress posts with typed fields, Markdown sync, and comments
export const posts = extend("posts", {
  fields: {
    subtitle: f.text().max(200).optional(),
  },
  sync: "content/posts/*.md",
  comments: { moderation: "first-time", threaded: 2 },
});

// Relational SQL table with forward-only migrations, declarative access, and hooks
export const tasks = table({
  title: f.text().min(1).max(120),
  done: f.boolean().default(false),
  postId: f.ref(posts).optional().onDelete("cascade"),
}, {
  access: {
    read: "anyone",
    create: "authenticated",
    update: "authenticated",
    delete: "editor",
  },
}).on({
  async afterCreate({ row }) {
    // Queued inside the write transaction; delivered after commit on Action Scheduler
    await notifyTask.enqueue({ taskId: row.id }, { key: `task-${row.id}` });
  },
});

export default defineConfig({
  name: "my-app",
  seed: true,
});

2. Write server mutations and queries

Every .ts file under sp/ (outside reserved folders) is compiled automatically. Mutation handlers are context-first: ({ db, user, mail, connectors, files }, input) (queries receive read-only { db, user, files }).

// sp/server.ts
import { mutation } from "spacepress";
import { HttpError } from "spacepress/server";

// Exposed as POST /wp-json/spacepress/v1/actions/createTask and as a WordPress Ability
export const createTask = mutation(
  { access: "authenticated" },
  async ({ db }, { title }: { title: string }) => {
    const trimmed = title.trim();
    if (!trimmed) throw new HttpError(422, "invalid_input", "Enter a task title", "/title");
    return await db.tasks.create({ title: trimmed });
  },
);

3. Render TSX pages and progressive forms

Pages in sp/app/ compile directly to PHP and receive a visitor-scoped db. Forms bound to a mutation work with zero JavaScript and enhance automatically when scripts load.

// sp/app/page.tsx
import { Link, useFormState, type PageProps } from "spacepress/app";
import { createTask } from "../server";

export const metadata = { title: "Home" };

export default async function Home({ db }: PageProps) {
  const latest = await db.posts.list({ orderBy: { publishedAt: "desc" }, limit: 10 });
  const form = useFormState(createTask);

  return (
    <main>
      <h1>Latest Posts</h1>
      <ul>
        {latest.map((post) => (
          <li key={post.id}>
            {/* Matched by a sibling sp/app/blog/[slug]/page.tsx route */}
            <Link href={`/blog/${post.slug}`}>{post.title}</Link>
          </li>
        ))}
      </ul>
      <form action={createTask}>
        <label htmlFor="task-title">Task</label>
        <input id="task-title" name="title" defaultValue={form.values.title ?? ""} required maxLength={120} />
        <button type="submit">Add task</button>
      </form>
      {form.error && <p role="alert">{form.error.fields.title ?? form.error.message}</p>}
      {form.result && <p role="status">Added: {form.result.title}</p>}
    </main>
  );
}

Add "use client" to any component in sp/components/ to compile it to a WordPress Interactivity API module using React hooks (useState), SpacePress hooks (useMutation, useLive, sharedState from "spacepress/react"), and generated API references from #sp/api.


Project Layout & Build Output

SpacePress keeps authored code, committed generated artifacts, and deployable build output clearly separated (the sp/ root is configurable via defineConfig({ dir })):

Authored                                 Emitted by `spacepress build`
───────────────────────────────────────  ─────────────────────────────────────────────────────
spacepress.config.ts   Config & schema   sp/_generated/                 (commit to Git)
sp/                                        migrations/<id>/
  schema.ts            Kinds & tables        ops.json                   Schema ops
  server.ts            Actions & jobs        migration.sql              Forward-only SQL
  app/                                     db.d.ts, routes.d.ts         Editor types
    layout.tsx         Root layout         types/                       Per-route $types
    page.tsx           TSX pages           api.js, api.d.ts             #sp/api bridge
    api/.../route.ts   HTTP routes         openapi.json                 OpenAPI 3.1
  components/          SSR & islands       client/                      Typed TS client
content/               Markdown sync       wp-plugins.lock.json         Pinned WP plugins
emails/                React Email         plugins.lock.json            Plugin grants
public/                Static root       sp/dist/wp-content/            (gitignored)
                                           spacepress-manifest.json
                                           spacepress-deployment.json
                                           plugins/
                                             spacepress-runtime/ (+ .zip)
                                             spacepress-identity/ (+ .zip)
                                             spacepress-admin/ (+ .zip)  (unless admin: false)
                                             spacepress-app-<name>/ (+ .zip)
                                             <pinned-wp-plugins>/
                                           mu-plugins/spacepress-commerce.php (if store())

Inside spacepress-app-<name>/sp/app/, the compiler writes schema.php, functions.php (checked with php -l when host PHP is present), openapi.json, migration folders, content-hashed CSS/image/OG assets, and Interactivity API island bundles.


Core Capabilities

  • Dual storage engine: Pair WordPress-native storage (collection(), extend("posts" | "pages" | "users"), taxonomy(), and global()) with custom relational SQL via table() (compound/unique indexes, soft deletes, revisions, forward-only ops.json + migration.sql folders, lossless .column() / .alias() renames).
  • Declarative access & identity: Visitor-scoped db.<kind> vs trusted db.system.<kind>, ordered role checks, row-level filter predicates compiled into SQL/PHP, field-level .access() masks, and spacepress-identity (passkeys, MFA/TOTP, OAuth 2.0 / OIDC, organizations, bearer tokens).
  • Server functions, hooks, jobs & routes: Validated query() and mutation() RPCs, transactional .on() lifecycle hooks, typed wp.action() / wp.filter() WordPress hooks, Action Scheduler job() and cron(), signed inbound/outbound webhooks, route.ts HTTP endpoints, compiled Node built-ins (node:crypto, node:buffer, node:path, node:zlib, etc.), files() private local/S3 buckets with signed URLs, typed connectors, and abilities.call().
  • TSX pages, islands & static export: File-based routing in sp/app/ with per-route ./$types, progressive zero-JS <form action={...}> + useFormState(), "use client" Interactivity API islands (useState, useLive, useMutation, sharedState), build-time Open Graph cards (opengraph-image.tsx or defineConfig({ meta, style })), and output: "static" + spacepress export (HTML, Markdown twins, llms.txt, sitemap.xml, _redirects, and --subset-fonts).
  • Two-way Markdown & Git sync: Bind collections, taxonomies, tables, or products to content/**/*.md or *.json with stable UIDs, validated YAML front matter, and 3-way merges via spacepress sync.
  • Native WooCommerce & React Email: Declare store(), product(), productCategory(), productTag(), and order() from "spacepress/commerce" (or scaffold with spacepress add shop) with optimistic cart hooks, plus emails/*.tsx templates rendered with mail.render() and sent with mail.send().
  • Admin, Gutenberg & locked plugins: Ships spacepress-admin at /wp-admin/new/ alongside declarative adminScreen(), adminWidget(), and adminDashboard() from "spacepress/admin"; author Gutenberg blocks in TSX with @spacepress/blocks; lock WordPress plugin dependencies in wp-plugins.lock.json (sealed: true) and capability-audited TypeScript plugins (definePlugin()) in plugins.lock.json.
  • MCP & WordPress Abilities: Publish schemas and actions as WordPress Abilities (served at runtime via /wp-json/mcp/spacepress-<app>), lock external site abilities with spacepress abilities pull, and run local spacepress mcp for coding agents.

CLI Reference

Build and local commands run directly in the spacepress binary; site commands forward to wp spacepress <command> against the local dev site by default, or against another target via --site <dir | workspace | @alias>.

Command Description
spacepress dev / dev stop / dev status [--json] Start, stop, or inspect the local WordPress + SQLite dev server with watch rebuilds
spacepress check [--json] [--frozen] [--fix] Type-check and validate schemas, handlers, pages, and locks without writing output
spacepress build [--out dir] [--frozen] Emit sp/_generated/ artifacts and sp/dist/wp-content/ WordPress plugins
spacepress export [--site url] [--subset-fonts] Render output: "static" apps to sp/dist/static/ (HTML, .md twins, llms.txt, assets)
spacepress add <db | api-reference | shop> Scaffold optional modules as source files you own
spacepress sync [status | resolve <uid>] Two-way 3-way-merge sync between local content/ files and WordPress
spacepress pull / styles pull / abilities pull Pull live runtime schema, Global Styles (sp/theme.json), or site abilities lock
spacepress init [--github] [--check] Generate/update AGENTS.md, .mcp.json, skills, and optional GitHub sync workflow
spacepress mcp [--allow-remote-read] [--allow-writes] Start the stdio MCP server with embedded version-matched docs and live checks
spacepress doctor [--site url [--links]] [--json] Verify local artifacts or a live WordPress site and optionally crawl links and anchors
spacepress plugin [--out file.zip] Package the upload-once spacepress.zip receiver plugin for wp-admin
spacepress login <url> / logout <url> / push Authenticate via WordPress Application Passwords and deploy to a live WordPress site
spacepress deploy <inspect | publish | init | status | backup | restore> Run the offline PHP deployment adapter against a local workspace
spacepress danger <plan | status | ...> Inspect or run explicit destructive schema/data cleanup (spacepress/danger)
spacepress wp <args> Forward any WP-CLI command to the dev site or --site
spacepress migrate / seed / jobs / staged / identity / schema / abilities / run / action Manage migrations, seeds, Action Scheduler jobs, staged versions, identity, and abilities
spacepress find / insert / update / delete / git-dispatch / publish-due Query or mutate records, configure GitHub dispatch, and publish due scheduled items

Run spacepress help or spacepress help <command> for full flags and usage.


Deploying to WordPress

  • Deploy to an existing WordPress 7.1+ / PHP 8.2+ site (Spacefast, Pressable / WordPress.com on WP Cloud, or self-hosted): run spacepress plugin to build spacepress.zip, upload and activate it once in wp-admin, then run spacepress login <site-url> and spacepress push.
  • Deploy built plugins directly: run spacepress build and deploy sp/dist/wp-content/plugins/ (and sp/dist/wp-content/mu-plugins/ before activating WooCommerce when the app declares a store()) following spacepress-manifest.json, or use spacepress deploy for offline staging.
  • Static export & desktop shells: set output: "static" and run spacepress export to ship static HTML or bundle screens into a desktop app (see examples/tauri-notes-with-signin).

Importing an Existing Project

This repository includes the standalone spacepress-migrate importer (migrate/):

cargo build --locked -p spacepress-migrate
./target/debug/spacepress-migrate --help

It imports Astro projects and static Astro dist/ builds, Zero 0.8 apps and WordPress data, and schemas from EmDash, Payload, Sanity, and Zero. See migrate/README.md for commands and options.


Packages & Examples

Package Path Description
spacepress packages/cli npm CLI launcher (installs per-platform native Rust compiler binary) + TypeScript types
create-spacepress packages/create-spacepress Project scaffolder (npm create spacepress@0.3.2 my-app)
@spacepress/client packages/client Typed fetch client and React hooks (spacepress/client, spacepress/react)
@spacepress/astro packages/astro Astro 7+ build-time and live content loaders, cache tags, and signed webhooks
@spacepress/blocks packages/blocks Author Gutenberg block content and block themes in TSX
@spacepress/docs packages/docs Documentation site module (hierarchical docs collection, 3-column layout, search)
@spacepress/frontend packages/frontend Vite 8 + Tailwind v4 route-level browser asset build; ships inside the compiler (browser in spacepress.config.ts), nothing to install
@spacepress/todo packages/todo Reusable GTD + PARA task and Kanban module for SpacePress apps
spacepress-site (spacepress.dev) www Official website, docs, and browser WASM playground, built as a SpacePress app

Browse examples/ for working apps, including examples/blog, examples/full-site, examples/kitchen-sink, examples/todo, examples/astro-garden, and examples/tauri-notes-with-signin.


Documentation

All documentation lives in www/content/docs/, is published at spacepress.dev/docs, and is embedded into spacepress mcp:


Building From Source

Requires Rust (rust-toolchain pins 1.100.1) and Node.js 22+ (.node-version pins 22.23.4). See CONTRIBUTING.md for PHP 8.2+ test suite prerequisites, compiler internals, and coding standards.

# Build the native CLI binary (embeds runtime/, skills/, and www/content/docs/ via build.rs)
cargo build --locked --release
./target/release/spacepress --help

# Build the browser WebAssembly compiler (src/wasm.rs)
cargo build --locked --lib --no-default-features --profile wasm --target wasm32-unknown-unknown

Licensing

SpacePress is licensed by component — anything that runs inside WordPress is GPL-2.0-or-later, and everything else is MIT (see LICENSING.md for the complete path-by-path map and third-party notices):

  • MIT (LICENSE): Rust compiler and CLI sources (src/, crates/), typed client (runtime/client/), type definitions (types/), npm packages (except bundled WordPress code in @spacepress/blocks), examples, documentation, and website.
  • GPL-2.0-or-later (licenses/GPL-2.0-or-later.txt): PHP runtime and WordPress plugins (runtime/SpacePress/, runtime/identity/, runtime/admin/, runtime/wp-plugin/, runtime/spacepress-plugin/), offline WordPress importer (migrate/zero/wp/), and every WordPress plugin emitted by spacepress build and spacepress plugin.
  • MIT AND GPL-2.0-or-later: packaged Rust crate and platform compiler binaries (which embed the GPL runtime) and @spacepress/blocks (which bundles WordPress block packages).

About

SpacePress is a toolkit for building sites to full-stack apps with ~TypeScript, fast.

Resources

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages