API Reference
API Reference
Section titled “API Reference”This is the complete API reference for the z0 SDK. All exports are available from the main package:
import { EntityLedger, LedgerClient, generateId, ... } from '@z0/sdk';Table of Contents
Section titled “Table of Contents”- Core Primitives - Entity, Fact, Config types
- System Constants - Platform-level constants
- Base Classes - EntityLedger, SystemLedger
- Client Library - LedgerClient, LedgerStub
- Registry - LedgerRegistry
- Utilities - ID generation, errors, auth, webhooks, invariants
Core Primitives
Section titled “Core Primitives”Entity
Section titled “Entity”Identity and state container for domain objects.
interface Entity<T = Record<string, unknown>> { id: string; // Unique platform identifier type: string; // Domain-level category (e.g., 'account') tenant_id?: string; // Tenant ownership ID version: number; // Optimistic concurrency control metadata: Record<string, unknown>; data: T; // Main data payload created_at: number; // Unix timestamp (ms) updated_at: number; // Unix timestamp (ms)}Immutable event record linked to an Entity.
interface Fact<T = Record<string, unknown>> { id: string; // Unique fact identifier type: string; // Event category (e.g., 'invocation') subtype?: string; // Refined action (e.g., 'call_completed') timestamp: number; // Unix timestamp (ms) tenant_id: string; // Tenant ID for isolation source_id?: string; // Source service/tool ID entity_id?: string; // Parent Entity ID data: T; // Event payload}Config
Section titled “Config”Versioned configuration primitive.
interface Config<T = Record<string, unknown>> { id: string; tenant_id: string; type: string; // Category (e.g., 'routing', 'policy') category: string; // Logical grouping name: string; // Human-readable name applies_to: string; // Target entity type or ID scope: string; // 'tenant', 'platform', 'entity' version: number; // Auto-incrementing version effective_at: number; // When this version becomes active superseded_at?: number; // When superseded by newer version settings: T; // Configuration payload}InvariantSettings
Section titled “InvariantSettings”Configuration for declarative invariants.
interface InvariantSettings { code: string; // Unique code (e.g., 'PAYMENT_POSITIVE') fact_type: string; // Applies to this fact type ('*' for all) rule: string; // Expression (e.g., 'data.amount > 0') engine?: 'expression' | 'jsonschema' | 'sql'; severity: 'error' | 'warning'; message: string; // User-friendly error message priority?: number; // Override resolution (10=platform, 20=tenant, 30=entity)}System Constants
Section titled “System Constants”SYSTEM_TENANT_ID
Section titled “SYSTEM_TENANT_ID”Reserved tenant ID for platform-level operations.
const SYSTEM_TENANT_ID = 'platform';CONFIG_TYPES
Section titled “CONFIG_TYPES”Configuration types used internally by the SDK.
const CONFIG_TYPES = { HOOK: 'hook', // Hook configurations INVARIANT: 'invariant', // Invariant configurations} as const;SYSTEM_FACT_TYPES
Section titled “SYSTEM_FACT_TYPES”System fact types for platform operations.
const SYSTEM_FACT_TYPES = { SYSTEM: 'system', TENANT_CREATED: 'tenant_created', ENTITY_CREATED: 'entity_created', MANIFEST_INIT: 'manifest_init', HOOK_REGISTERED: 'hook_registered',} as const;SCOPE_PRIORITY
Section titled “SCOPE_PRIORITY”Hierarchical scope levels for configuration override resolution.
const SCOPE_PRIORITY = { PLATFORM: 10, TENANT: 20, ENTITY: 30,} as const;PLATFORM_ID_PREFIXES
Section titled “PLATFORM_ID_PREFIXES”Common ID prefixes for generated identifiers.
const PLATFORM_ID_PREFIXES = { entity: 'ent_', fact: 'fact_', config: 'cfg_', trace: 'tr_',} as const;Base Classes
Section titled “Base Classes”EntityLedger
Section titled “EntityLedger”Abstract base class for domain ledgers. Extend this to create your own ledger types.
abstract class EntityLedger<TEnv extends EntityLedgerEnv = EntityLedgerEnv> extends DurableObjectConstructor
Section titled “Constructor”constructor(ctx: DurableObjectState, env: TEnv)Protected Methods (Override in Subclass)
Section titled “Protected Methods (Override in Subclass)”| Method | Description |
|---|---|
updateCachedState(fact: Fact): Promise<void> | Required. Handle new facts to update materialized state |
initializeSubclassSchema(): Promise<void> | Optional. Add custom SQLite tables |
fetchUpstreamConfigs(): Promise<Config[]> | Optional. Fetch configs from parent ledgers |
Protected Methods (Available to Subclass)
Section titled “Protected Methods (Available to Subclass)”| Method | Returns | Description |
|---|---|---|
getEntity() | Entity | null | Get the current entity |
upsertEntity(entity) | Entity | Create or update entity |
appendFact(fact) | Fact | Append immutable fact |
getFacts(options?) | Fact[] | Query facts with filters |
getFactById(id) | Fact | null | Get single fact |
getCurrentConfig(id) | Config | null | Get active config |
createConfig(config) | Config | Create new config |
updateConfig(id, updates) | Config | Update config (creates new version) |
getCachedState<T>(key) | T | null | Read cached state |
setCachedState<T>(key, value) | void | Write cached state |
deleteCachedState(key) | void | Delete cached state |
createSnapshot(options?) | LedgerSnapshot | Create point-in-time snapshot |
saveSnapshot(snapshot) | void | Persist snapshot |
getSnapshots(options?) | LedgerSnapshot[] | List snapshots |
reconstructState() | Promise<void> | Replay all facts to rebuild state |
hydrate() | Promise<void> | Disaster recovery from R2 |
Environment Interface
Section titled “Environment Interface”interface EntityLedgerEnv { REPLICATION_QUEUE?: Queue; FACT_EVENTS_QUEUE?: Queue; SNAPSHOT_BUCKET?: R2Bucket; z0_STORAGE_CONTEXT?: R2Bucket; [key: string]: unknown;}SystemLedger
Section titled “SystemLedger”Root ledger for platform-level operations. Every z0 deployment should have exactly one.
class SystemLedger extends EntityLedger<EntityLedgerEnv>Public Methods
Section titled “Public Methods”| Method | Returns | Description |
|---|---|---|
initializeAsRoot() | Promise<void> | Initialize as platform root |
recordTenantCreated(tenantId, metadata?) | Promise<Fact> | Record tenant creation |
recordEntityCreated(tenantId, entityId, entityType) | Promise<Fact> | Record entity creation |
getTenants() | Array<{tenant_id, created_at}> | List all tenants |
getEntities() | Array<{tenant_id, entity_id, entity_type}> | List all entities |
getStats() | {tenant_count, entity_count} | Get platform statistics |
Client Library
Section titled “Client Library”LedgerClient
Section titled “LedgerClient”Typed wrapper for interacting with Ledger Durable Objects.
class LedgerClient { constructor(namespace: DurableObjectNamespace, tenantId?: string)}Methods
Section titled “Methods”| Method | Returns | Description |
|---|---|---|
stub(name) | LedgerStub | Get stub using logical name (uses idFromName) |
stubFromHexId(hexId) | LedgerStub | Get stub using DO hex ID |
create<T>(type, data, options?) | Promise<Entity<T>> | Create entity with random ID |
get<T>(id) | Promise<Entity<T>> | Get entity state |
emit<T>(id, event, data, options?) | Promise<Fact<T>> | Append fact to entity |
LedgerStub
Section titled “LedgerStub”Typed interface for a specific ledger entity instance.
class LedgerStub { readonly id: string;}Methods
Section titled “Methods”| Method | Returns | Description |
|---|---|---|
appendFact<T>(fact, options?) | Promise<Fact<T>> | Append fact |
getFact<T>(factId) | Promise<Fact<T>> | Get fact by ID |
getFacts<T>(options?) | Promise<Fact<T>[]> | Query facts |
upsertEntity<T>(entity, options?) | Promise<Entity<T>> | Create/update entity |
getEntity<T>() | Promise<Entity<T>> | Get current entity state |
createConfig<T>(config, options?) | Promise<Config<T>> | Create configuration |
getConfig<T>(configId) | Promise<Config<T>> | Get configuration |
updateConfig<T>(configId, updates, options?) | Promise<Config<T>> | Update configuration |
createSnapshot(options?) | Promise<LedgerSnapshot> | Create snapshot |
getSnapshots(limit?) | Promise<LedgerSnapshot[]> | List snapshots |
Options
Section titled “Options”interface ClientRequestOptions { idempotencyKey?: string; // For safe retries}Registry
Section titled “Registry”LedgerRegistry
Section titled “LedgerRegistry”Central registry for domain manifests and entity definitions.
class LedgerRegistry { // Static methods only}Methods
Section titled “Methods”| Method | Returns | Description |
|---|---|---|
register(manifest) | void | Register domain manifest |
getManifest() | DomainManifest | null | Get current manifest |
getDefinition(type) | EntityDefinition | undefined | Get entity definition |
getEntityTypes() | string[] | List registered entity types |
isFactAllowed(entityType, factType) | boolean | Check if fact type is allowed |
getNamespace(env, type) | DurableObjectNamespace | Get DO namespace for type |
registerHandler(name, handler) | void | Register async event handler |
getHandler(name) | FactEventHandler | undefined | Get registered handler |
getSubscriptions() | Subscription[] | Get manifest subscriptions |
clear() | void | Reset registry (for tests) |
interface DomainManifest { name: string; version: string; entities: Record<string, EntityDefinition>; subscriptions?: Subscription[];}
interface EntityDefinition { ledger: string | LedgerConstructor; subtype?: string; description?: string; fields?: Record<string, FieldDef>; facts?: string[]; hooks?: HookDef[];}Utilities
Section titled “Utilities”ID Generation
Section titled “ID Generation”function generateId(prefix: string): stringGenerates a unique ID with timestamp and random components.
import { generateId, PLATFORM_ID_PREFIXES } from '@z0/sdk';
const factId = generateId(PLATFORM_ID_PREFIXES.fact);// => "fact_mkp123abc456def"Error Handling
Section titled “Error Handling”RFC 7807 Problem Details implementation.
class ApiError extends Error { constructor( status: number, code: string, message: string, errors?: FieldError[], traceId?: string )
toProblemDetails(instance?: string): ProblemDetails toResponse(instance?: string): Response}Factory Methods
Section titled “Factory Methods”const EntityLedgerErrors = { notFound: (resource, id) => ApiError, badRequest: (message, errors?) => ApiError, unauthorized: (message?) => ApiError, forbidden: (message?) => ApiError, conflict: (message) => ApiError, internalError: (message?) => ApiError,};Authentication
Section titled “Authentication”function authenticateRequest(request: Request, prefix?: string): AuthResult
function parseApiKey(apiKey: string, prefix?: string): { mode: ApiKeyMode; tenantId: string } | nullKey format: <prefix>_<mode>_<tenant_id>_<random>
type ApiKeyMode = 'live' | 'test';
interface AuthResult = | { success: true; context: AuthContext } | { success: false; error: string; status: 401 }
interface AuthContext { tenantId: string; mode: ApiKeyMode; apiKey: string;}Validation Schemas
Section titled “Validation Schemas”Zod schemas for input validation.
import { CreateEntitySchema, CreateFactSchema, CreateConfigSchema } from '@z0/sdk';
const result = CreateFactSchema.safeParse(input);Webhooks
Section titled “Webhooks”Complete webhook delivery system.
// Signingasync function signPayload(payload: string, timestamp: number, secret: string): Promise<string>function constantTimeCompare(a: string, b: string): boolean
// Payload Buildingfunction buildWebhookPayload(fact: Fact, pattern: string, deliveryId: string, attempt: number): WebhookPayloadfunction buildWebhookHeaders(deliveryId: string, signature: string, timestamp: number): Record<string, string>
// ID Generationfunction generateDeliveryId(): stringfunction generateWebhookId(prefix?: string): string
// Matchingfunction matchWebhookTrigger(pattern: string, factType: string, factSubtype?: string): booleanfunction findMatchingWebhooks(webhooks: WebhookConfigSettings[], fact: Fact): WebhookConfigSettings[]
// Retry Logicfunction isRetryableError(status: number): booleanfunction calculateBackoff(attempt: number, config?: RetryConfig): numberfunction validateWebhookConfig(config: unknown): boolean
// Constantsconst DEFAULT_RETRY_CONFIG: RetryConfigInvariants
Section titled “Invariants”Runtime assertion system for enforcing platform invariants.
⚠️ Security Note: The expression engine uses
new Function()which is equivalent toeval(). Only use with admin-defined rules, never with untrusted user input.
// Simple assertionfunction assertInvariant( condition: boolean, message: string, invariant?: string, context?: Record<string, unknown>): asserts condition
// Error classclass InvariantViolation extends Error { readonly invariant: string; readonly context?: Record<string, unknown>;}InvariantChecker
Section titled “InvariantChecker”Static methods for checking various invariants.
| Method | Description |
|---|---|
evaluateInvariant(fact, settings) | Evaluate declarative invariant against fact |
verifyFactUniqueness(fact1, fact2) | Check facts with same ID are identical |
verifyFactImmutability(original, retrieved) | Check fact hasn’t changed |
verifyConfigUniqueness(configs) | Check at most one active config per type |
verifyConfigTemporalOrdering(config) | Check effective_at < superseded_at |
verifyFactEntityReference(fact, entity) | Check entity_id references exist |
verifyFactSourceReference(fact, source) | Check source_id references exist |
verifyConfigEntityReference(config, entity) | Check applies_to references exist |
verifyFactInvariants(fact, context) | Run all fact invariant checks |
verifyConfigInvariants(config, context) | Run all config invariant checks |
Router
Section titled “Router”Simple request routing utility.
class Router { get(pattern: string, handler: RouteHandler): this post(pattern: string, handler: RouteHandler): this put(pattern: string, handler: RouteHandler): this delete(pattern: string, handler: RouteHandler): this handle(request: Request): Promise<Response>}Ledger Types
Section titled “Ledger Types”interface FactSummary { total_count: number; total_amount: number; by_type: Record<string, { count: number; total_amount: number }>;}
interface LedgerSnapshot { id: string; entity_id: string; facts_through: string; timestamp: number; period_start?: number; period_end?: number; entity: Entity; fact_summary: FactSummary; cached_states: Record<string, unknown>; trigger: 'manual' | 'scheduled' | 'period_close' | 'archive' | 'reconstruct_backup';}
interface HookConfig { id: string; version: number; trigger: { type: string | '*'; subtype?: string | '*' }; mode: 'sync' | 'async'; action: HookAction;}
interface HookAction { type: 'queue' | 'webhook' | 'workflow' | 'method'; target: string; metadata?: Record<string, unknown>;}Version
Section titled “Version”export const VERSION = '0.2.0';