@z0-app/sdk
v0.5.0
Published
Build immutable, traceable systems with three primitives: Entity, Fact, Config
Maintainers
Readme
z0 SDK
Build immutable, traceable systems with three primitives: Entity, Fact, Config
z0 is a minimalist SDK for building event-sourced, auditable systems on Cloudflare Workers. Instead of prescribing how your application should work, z0 gives you three powerful primitives and gets out of your way.
Quick Start
npm install @z0-app/sdkimport { EntityLedger, type Fact, type EntityLedgerEnv } from '@z0-app/sdk';
// 1. Define your domain ledger
export class AccountLedger extends EntityLedger<EntityLedgerEnv> {
protected async updateCachedState(fact: Fact): Promise<void> {
const balance = this.getCachedState<number>('balance') ?? 0;
if (fact.type === 'deposit') {
this.setCachedState('balance', balance + (fact.data.amount as number));
}
}
}
// 2. Use it via the Typed Client
import { LedgerClient } from '@z0-app/sdk';
export default {
async fetch(request: Request, env: EntityLedgerEnv) {
const client = new LedgerClient(env.ACCOUNT_LEDGER);
// Append a fact
await client.emit('user_123', 'deposit', { amount: 100 });
// Get the entity state
const entity = await client.get('user_123');
return Response.json(entity);
}
}The Three Primitives
Entity
Identity and state container. Like a row in a database, but immutable.
interface Entity<T = Record<string, unknown>> {
id: string;
type: string;
tenant_id?: string;
version: number;
data: T; // Generic JSON payload
created_at: number;
updated_at: number;
}Fact
Immutable event record. Once written, never changed.
interface Fact<T = Record<string, unknown>> {
id: string;
type: string;
subtype?: string;
timestamp: number;
tenant_id: string;
entity_id?: string;
data: T; // Generic JSON payload
}Config
Versioned configuration. Changes create new versions, never overwrite.
interface Config<T = Record<string, unknown>> {
id: string;
version: number;
settings: T; // Generic JSON payload
// ...
}Build Your First Domain in 5 Minutes
1. Define Your Domain Manifest
import { LedgerRegistry, type DomainManifest } from '@z0-app/sdk';
const manifest: DomainManifest = {
name: 'my-app',
version: '1.0.0',
entities: {
account: {
ledger: 'AccountLedger',
description: 'User account',
fields: {
// No more "slots"! Just define your fields.
// We automatically generate schema and indexes for you.
email: { type: 'string', required: true },
balance: { type: 'number' },
active: { type: 'boolean' },
},
facts: ['deposit', 'withdrawal'],
},
},
};
LedgerRegistry.register(manifest);2. Create Your Ledger Class
import { EntityLedger, type Fact } from '@z0-app/sdk';
export class AccountLedger extends EntityLedger {
protected async updateCachedState(fact: Fact): Promise<void> {
const balance = this.getCachedState<number>('balance') ?? 0;
switch (fact.type) {
case 'deposit':
this.setCachedState('balance', balance + (fact.data.amount as number));
break;
}
}
}3. Use Your Ledger with LedgerClient
import { LedgerClient } from '@z0-app/sdk';
// Create a client for the specific binding
const accounts = new LedgerClient(env.ACCOUNT_LEDGER);
// 1. Initialize (optional, upsert logic handles this)
await accounts.stub('user_123').upsertEntity({
type: 'account',
data: { email: '[email protected]', balance: 0 }
});
// 2. Append facts
await accounts.emit('user_123', 'deposit', { amount: 100.00 });
// 3. Query
const entity = await accounts.get<{ balance: number }>('user_123');
console.log(entity.data.balance); // 100.00Core Features
EntityLedger Base Class
The EntityLedger class provides:
- SQLite-backed storage with automatic schema initialization
- Fact append with hooks and replication
- Config management with versioning
- Cached state for denormalized views
- Snapshots for point-in-time recovery
- Idempotency for safe retries
- Tenant isolation built-in
LedgerRegistry Pattern
Register your domain manifest once and let z0 handle routing:
import { LedgerRegistry } from '@z0-app/sdk';
LedgerRegistry.register(manifest);
// Get entity definition
const def = LedgerRegistry.getDefinition('account');
// Check fact permissions
const allowed = LedgerRegistry.isFactAllowed('account', 'deposit');Utilities
ID Generation
import { generateId, PLATFORM_ID_PREFIXES } from '@z0-app/sdk';
const factId = generateId(PLATFORM_ID_PREFIXES.fact);
// => "fact_l3k5j8h9k2j3h4"Error Handling (RFC 7807)
import { ApiError, EntityLedgerErrors } from '@z0-app/sdk';
throw EntityLedgerErrors.notFound('Account', accountId);
// Returns RFC 7807 Problem Details responseAuthentication
import { authenticateRequest } from '@z0-app/sdk';
const auth = authenticateRequest(request);
if (!auth.success) {
return new Response('Unauthorized', { status: 401 });
}
console.log(auth.context.tenantId);Webhooks
import { buildWebhookPayload, signPayload } from '@z0-app/sdk';
const payload = buildWebhookPayload(fact, 'deposit.completed', deliveryId, 1);
const signature = await signPayload(JSON.stringify(payload), timestamp, secret);Runtime Invariants
import { assertInvariant, InvariantChecker } from '@z0-app/sdk';
// Simple assertion
assertInvariant(fact.timestamp > 0, 'Fact timestamp must be positive');
// Declarative invariant evaluation
InvariantChecker.evaluateInvariant(fact, {
code: 'POSITIVE_AMOUNT',
fact_type: 'payment',
rule: 'data.amount > 0',
severity: 'error',
message: 'Amount must be positive'
});
// Verify referential integrity
InvariantChecker.verifyFactInvariants(fact, { entity, sourceFact });Why z0?
Zero Overhead
z0 is primitives, not frameworks. No routing layer, no middleware stack, no magic. Just three types and some utilities.
Zero Lock-in
Built on standard Cloudflare Workers primitives. If you outgrow z0, you own your data and can migrate.
Zero Compromises
Immutability, auditability, and traceability are enforced at the type level. You can't accidentally break them.
Architecture
z0 is built on Cloudflare Durable Objects:
- One Durable Object per Entity - Perfect isolation, no cross-entity queries
- SQLite storage - Fast, local, transactional
- Automatic replication - Facts replicate to D1/R2 for analytics
- Event-driven hooks - React to facts with sync or async handlers
Examples
See docs.z0.app/examples for:
- Pay-per-call marketplace
- Multi-tenant SaaS billing
- Financial ledger with reconciliation
- Webhook delivery system
- Real-time dashboards
Documentation
- Primitives Guide: docs.z0.app/primitives
- Ledger Patterns: docs.z0.app/patterns
- API Reference: docs.z0.app/api
- Migration Guide: docs.z0.app/migration
Requirements
- Node.js >= 18
- Cloudflare Workers account
- Durable Objects enabled
License
MIT
Contributing
We welcome contributions! See CONTRIBUTING.md for guidelines.
Support
- Issues: github.com/z0-app/sdk/issues
- Docs: docs.z0.app
- Discord: discord.gg/z0
