@avelon/core
@avelon/core defines the framework-neutral contracts shared by Avelon applications, adapters, and drivers. It gives you a serializable query IR, a portable request dispatcher boundary, capability-narrowed driver facades, normalized errors, and event/listener primitives. Reach for this package when you implement a driver or adapter, or when application code needs a contract without importing an implementation.
Installation
bun add @avelon/core
Basic Usage
Build a query once and pass it to a database facade whose available operations come from literal driver capabilities.
import type { Database, DatabaseDriver, QueryIR } from '@avelon/core'
type AppDatabaseDriver = DatabaseDriver<{
transactions: true
rowSecurity: true
maxRelationDepth: 4
fullTextSearch: true
upsert: true
returning: true
windowFunctions: true
jsonOperators: true
}>
export async function latestPublishedPosts(db: Database<AppDatabaseDriver>) {
const query = {
table: 'posts',
mode: 'select',
select: ['id', 'title', 'published_at'],
where: [{ kind: 'null', column: 'published_at', negated: true }],
relations: [],
order: [{ column: 'published_at', direction: 'desc' }],
limit: 20,
} satisfies QueryIR & { mode: 'select'; conflict?: never }
return db.execute<{ id: string; title: string; published_at: string }>(query)
}
Query IR
QueryIR is serializable and has one meaning across database compilers. Top-level where entries compose with AND, and the ward compiler injects ward as another AND predicate; application code never supplies it. Empty AND is true, empty OR is false, an empty IN list is false unless negated, and a false ward short-circuits without a database round trip. Upserts require an explicit conflict target and update list before execution. Count mode returns the number of rows matching where and ward as QueryResult.count.
import type { QueryIR } from '@avelon/core'
export const updatePost: QueryIR = {
table: 'posts',
mode: 'update',
select: '*',
where: [{ kind: 'compare', column: 'id', op: '=', value: 'post-7' }],
relations: [],
order: [],
values: { title: 'Frozen contracts' },
returning: ['id', 'title'],
}
Adapters And Kernel Dispatch
Adapters translate native requests and responses at three seams: mount, request conversion, and response conversion. Every mounted route delegates middleware, binding, validation mapping, controller dispatch, and exception mapping to Kernel. HttpRequest.rawBody() preserves signature-verification bytes, and streaming adapters accept StreamResult. A POST route exists whether the adapter uses a server action or an ordinary HTTP POST, and the adapter alone interprets an opaque view reference.
import type { Adapter, Kernel, RouteManifest } from '@avelon/core'
export async function mountApplication(
adapter: Adapter<string, string>,
kernel: Kernel<string, string>,
) {
const manifest: RouteManifest<string> = {
version: '2026-08-02',
routes: [
{
name: 'posts.store',
method: 'POST',
path: '/posts',
controller: 'PostController',
action: 'store',
middleware: ['auth'],
bindings: {},
api: false,
},
],
}
return adapter.mount(manifest, { kernel })
}
Capability-Narrowed Drivers
Every driver declares literal capabilities and a named instance. Boolean capabilities add or remove method surfaces; spectra retain exact providers, MFA factors, transforms, channels, algorithms, modes, and relation depth. raw() returns the driver's generic client type without exposing an implementation in core.
import type { Storage, StorageDriver } from '@avelon/core'
type ImageDiskDriver = StorageDriver<{
signedUrls: true
transforms: readonly ['resize', 'format']
}>
export async function avatarUrl(storage: Storage<ImageDiskDriver>, path: string) {
await storage.put(path, new Uint8Array([137, 80, 78, 71]), {
contentType: 'image/png',
})
return storage.transform(path, 'resize', { width: 256, height: 256 })
}
Use supports() only when configuration is resolved dynamically. Static configuration should rely on the narrowed facade so unsupported methods never enter application code.
Normalized Errors
Drivers map failures into the fixed taxonomy. Each error has a stable code, framework-owned metadata, and the original failure on the standard cause property.
import { Conflict } from '@avelon/core'
export function normalizeDuplicateSlug(cause: unknown) {
return new Conflict('A post already uses this slug.', {
metadata: { resource: 'Post', key: 'slug' },
cause,
})
}
Events And Listeners
Synchronous listeners run by ascending priority and may stop propagation by returning false or calling stopPropagation(). after listeners run post-response without retry. queued listeners declare a queue, attempts, and backoff, and receive no implicit request or actor; authorization-sensitive events must carry an actor explicitly.
import { Event, defineListener } from '@avelon/core'
class PostPublished extends Event {
constructor(
readonly postId: string,
readonly actorId: string,
) {
super()
}
}
export const IndexPublishedPost = defineListener<PostPublished, void, 'queued'>({
delivery: 'queued',
queue: 'search',
priority: 20,
tries: 3,
backoff: [10, 60, 300],
async handle(event, context) {
console.info('indexing post', event.postId, context.attempt)
},
})
Runtime Facades
Wave B implements the frozen contracts as process-local facades. You wire drivers with defineConfig, dispatch events through Events, authorize with Gate, validate with defineRequest, inject wards with injectWard, and run background work through Errands. Named mailers, disks, and connections never fall back to the default when the name is unknown.
import {
DB,
Event,
Events,
defineConfig,
defineListener,
definePolicy,
defineWard,
injectWard,
mailers,
type DatabaseDriver,
type MailDriver,
} from '@avelon/core'
class Post {
static readonly name = 'Post'
static readonly table = 'posts'
}
class PostPublished extends Event {
constructor(readonly postId: string) {
super()
}
}
export function boot(
databaseDriver: DatabaseDriver,
transactionalMail: MailDriver,
marketingMail: MailDriver,
) {
defineConfig({
name: 'app',
drivers: {
database: databaseDriver,
mail: {
default: 'transactional',
mailers: { transactional: transactionalMail, marketing: marketingMail },
},
},
})
Events.listen(
PostPublished,
defineListener({
handle: (event) => {
console.info('published', event.postId)
},
}),
)
definePolicy(Post, {
update: (actor, post) => actor?.id === (post as { user_id: string }).user_id,
})
defineWard(Post, {
read: (actor) =>
actor ? { or: [{ published: true }, { user_id: actor.id }] } : { published: true },
insert: (actor) => (actor ? { user_id: actor.id } : false),
update: (actor) => (actor ? { user_id: actor.id } : false),
delete: (actor) => (actor ? { user_id: actor.id } : false),
})
}
export async function publishedPosts() {
return DB.execute(
injectWard(
{
table: 'posts',
mode: 'select',
select: '*',
where: [],
relations: [],
order: [],
},
{ published: true },
),
)
}
export async function notifyMarketing() {
return mailers.mailer('marketing').send({
to: 'reader@example.test',
subject: 'Published',
text: 'A post is live.',
})
}
The Event class stays the frozen primitive. Events is the dispatcher so application code does not add static methods to that class. mailers.mailer, disks.disk, and queues.connection exist because Mail, Storage, and Queue are frozen type aliases.
Method Reference
The table lists every public export. Capability surface interfaces describe methods that appear only when the corresponding literal capability enables them.
| Export | Signature | Description | |
|---|---|---|---|
AI | type AI<TDriver> | AI facade narrowed to completion, embedding, and streaming capabilities. | |
ActionResult | interface ActionResult<TData> | Transport-neutral controller action state. | |
Adapter | interface Adapter<TController, TViewRef, TNativeRequest, TNativeResponse> | Web framework boundary with capability-aware stream conversion. | |
AfterListenerContext | interface AfterListenerContext | Context for best-effort post-response listeners. | |
AiCapabilities | interface AiCapabilities<TMode> | Literal AI mode and streaming declaration. | |
AiDriver | interface AiDriver<TCapabilities, TRaw> | Base AI driver identity extended by mode surfaces. | |
AiMessage | interface AiMessage | Role-tagged completion message. | |
AiMode | type AiMode | Portable AI operation modes. | |
Auth | type Auth<TDriver> | Application-facing alias for Identity<TDriver>. | |
AuthCapabilities | type AuthCapabilities<TFactor> | Application-facing alias for factor-aware identity capabilities. | |
AuthDriver | type AuthDriver<TCapabilities, TRaw, TActor, TSession> | Application-facing alias for the identity driver contract. | |
AvelonError | class AvelonError<TMetadata> | Base normalized error with code, metadata, and cause. | |
AvelonErrorOptions | interface AvelonErrorOptions<TMetadata> | Typed metadata and cause supplied to framework errors. | |
BroadcastRealtimeSurface | interface BroadcastRealtimeSurface | Broadcast methods for capable realtime drivers. | |
Cache | type Cache<TDriver> | Cache facade narrowed to tags and locks. | |
CacheCapabilities | interface CacheCapabilities | Literal tag and lock declaration. | |
CacheDriver | interface CacheDriver<TCapabilities, TRaw> | Base cache key-value contract. | |
CacheStore | interface CacheStore | Shared get, put, forget, and flush methods. | |
CapabilityMembers | type CapabilityMembers<TValues> | Members retained by a literal capability spectrum. | |
CapabilitySurface | type CapabilitySurface<TCapability, TSurface> | Surface present only when a capability is literal true. | |
CheckoutPaymentSurface | interface CheckoutPaymentSurface | Hosted checkout methods for capable payment drivers. | |
CheckoutSession | interface CheckoutSession | Normalized hosted checkout session. | |
CompareOp | type CompareOp | Portable comparison operator union. | |
CompletionAiSurface | interface CompletionAiSurface | Complete-response generation method. | |
CompletionChunk | interface CompletionChunk | One incremental streaming completion chunk. | |
CompletionRequest | interface CompletionRequest | Portable text completion request. | |
CompletionResult | interface CompletionResult | Generated text and optional token counts. | |
CookieOptions | interface CookieOptions | Transport-neutral cookie write options. | |
Conflict | class Conflict | Normalized state conflict error. | |
ConflictMetadata | interface ConflictMetadata | Resource and framework-owned conflict key. | |
Database | type Database<TDriver> | Database facade narrowed to literal capabilities. | |
DatabaseCapabilities | interface DatabaseCapabilities | Exact database capability declaration. | |
DatabaseDriver | interface DatabaseDriver<TCapabilities, TRaw> | Query, routine, migration, and raw client contract. | |
DatabaseFullTextSurface | interface DatabaseFullTextSurface | Native full-text search method. | |
DatabaseSurface | interface DatabaseSurface<TDriver> | Always-available database facade methods. | |
DatabaseTransaction | interface DatabaseTransaction | Query and routine methods inside a transaction. | |
DeadLetterQueueSurface | interface DeadLetterQueueSurface | Failed-job inspection, replay, and deletion methods. | |
DelayedQueueSurface | interface DelayedQueueSurface | Scheduled enqueue method. | |
DeliveryMode | type DeliveryMode | Sync, after-response, or queued listener delivery. | |
DriverCapabilitiesOf | type DriverCapabilitiesOf<TDriver> | Extracts a driver's exact capability shape. | |
DriverContract | interface DriverContract<TCapabilities, TRaw> | Shared name, instance, capabilities, and raw client contract. | |
DriverFault | class DriverFault | Normalized unmapped driver error. | |
DriverFaultMetadata | interface DriverFaultMetadata | Driver contract and operation identifiers. | |
EmbeddingAiSurface | interface EmbeddingAiSurface | Text embedding method. | |
EmbeddingResult | interface EmbeddingResult | Ordered embedding vectors and token count. | |
ErrorCode | type ErrorCode | Fixed machine-readable error code union. | |
Event | class Event | Event primitive with explicit propagation state. | |
EventConstructor | interface EventConstructor<TEvent> | Constructable event class used by registrations. | |
EventDispatchOptions | interface EventDispatchOptions | Dispatch options including afterCommit. | |
EventDispatcher | interface EventDispatcher | Dispatch, post-response, and until event boundary. | |
EventSerializer | interface EventSerializer<TEvent> | Queue serialization and rehydration boundary. | |
EventSubscriber | interface EventSubscriber | Multi-event listener registration contract. | |
FailedQueueJob | interface FailedQueueJob | Terminal queue failure retained for replay. | |
FlagCapabilities | interface FlagCapabilities | Literal targeting capability declaration. | |
FlagContext | interface FlagContext | Explicit actor, organization, and targeting attributes. | |
FlagDriver | interface FlagDriver<TCapabilities, TRaw> | Feature flag evaluation contract. | |
FlagSurface | interface FlagSurface<TDriver> | Context-restricted feature flag methods. | |
Flags | type Flags<TDriver> | Feature flag facade narrowed to targeting support. | |
Forbidden | class Forbidden | Normalized authorization denial. | |
ForbiddenMetadata | interface ForbiddenMetadata | Denied ability and resource identifiers. | |
HttpMethod | type HttpMethod | Methods accepted by route manifests. | |
HttpRequest | interface HttpRequest<TBody> | Framework-neutral decoded request with access to raw bytes. | |
Identity | type Identity<TDriver> | Identity facade narrowed to five auth capabilities. | |
IdentityCapabilities | interface IdentityCapabilities<TFactor> | Password, magic-link, OAuth, organization, and MFA factor declaration. | |
IdentityDriver | interface IdentityDriver<TCapabilities, TRaw, TActor, TSession> | Current actor, session, and sign-out contract. | |
IdentityOrganization | interface IdentityOrganization | Normalized organization summary. | |
Invalid | class Invalid | Normalized invalid-input error. | |
InvalidMetadata | interface InvalidMetadata | Field-keyed validation messages. | |
IssuedToken | interface IssuedToken | Token metadata plus one-time plaintext value. | |
Kernel | interface Kernel<TController, TViewRef> | Core request pipeline dispatcher. | |
KernelResult | type KernelResult<TViewRef> | Action, redirect, opaque view, or byte-stream result. | |
ListenerContext | type ListenerContext<TDelivery> | Delivery-specific context with no implicit actor. | |
ListenerDefinition | type ListenerDefinition<TEvent, TResult, TDelivery> | Listener handler, priority, delivery, retry, and backoff contract. | |
ListenerRegistration | interface ListenerRegistration<TEvent> | Event class and listener pair. | |
ListenerResult | type ListenerResult<TResult> | Listener value, null, void, or propagation-stopping false. | |
LockCacheSurface | interface LockCacheSurface | Named cache lock method. | |
LogCapabilities | interface LogCapabilities | Literal tracing capability declaration. | |
LogDriver | interface LogDriver<TCapabilities, TRaw> | Structured log write contract. | |
LogLevel | type LogLevel | Portable structured log severity. | |
LogRecord | interface LogRecord | Structured application log event. | |
Logs | type Logs<TDriver> | Logging facade narrowed to tracing support. | |
MagicLinkIdentitySurface | interface MagicLinkIdentitySurface | Passwordless sign-in link method. | |
Mail | type Mail<TDriver> | Mail facade narrowed to hosted templates. | |
MailAttachment | interface MailAttachment | Portable attachment filename, bytes, and media type. | |
MailCapabilities | interface MailCapabilities | Literal hosted-template capability declaration. | |
MailDriver | interface MailDriver<TCapabilities, TRaw> | Transactional mail send contract. | |
MailMessage | interface MailMessage | Transport-neutral email message with optional reply recipients. | |
MailReceipt | interface MailReceipt | Accepted message identifier and recipients. | |
MfaChallenge | interface MfaChallenge<TFactor> | Normalized challenge retaining its declared factor. | |
MfaIdentitySurface | interface MfaIdentitySurface<TFactor> | Factor-restricted challenge and verification methods. | |
MigrationPlan | interface MigrationPlan | Driver-owned pending migration plan. | |
MigrationStatus | interface MigrationStatus | Applied state for one migration. | |
MountOptions | interface MountOptions<TController, TViewRef> | Kernel, base path, and development mount settings. | |
MountResult | interface MountResult | Mounted routes and generated files. | |
NotFound | class NotFound | Normalized missing-resource error. | |
NotFoundMetadata | interface NotFoundMetadata | Missing resource and optional identifier. | |
NotificationCapabilities | interface NotificationCapabilities<TChannel> | Literal notification channel spectrum. | |
NotificationChannel | type NotificationChannel | Push, SMS, and in-app channels. | |
NotificationDriver | interface NotificationDriver<TCapabilities, TRaw> | Notification delivery contract. | |
NotificationMessage | interface NotificationMessage<TData> | Portable recipient, body, and application data. | |
NotificationReceipt | interface NotificationReceipt | Accepted notification identifier and channel. | |
NotificationSurface | interface NotificationSurface<TDriver> | Send method restricted to configured channels. | |
Notifications | type Notifications<TDriver> | Notification facade narrowed to channel literals. | |
OAuthIdentitySurface | interface OAuthIdentitySurface | Social identity linking method. | |
OrderTerm | interface OrderTerm | Column, direction, and null ordering. | |
OrganizationIdentitySurface | interface OrganizationIdentitySurface | Organization listing and selection methods. | |
PasswordIdentitySurface | interface PasswordIdentitySurface<TActor> | Registration, sign-in, token reset, and authenticated update methods. | |
PaymentCapabilities | interface PaymentCapabilities | Subscription, checkout, and webhook declaration. | |
PaymentCustomer | interface PaymentCustomer | Normalized payment customer. | |
PaymentDriver | interface PaymentDriver<TCapabilities, TRaw> | Base payment customer contract. | |
PaymentSubscription | interface PaymentSubscription | Normalized recurring subscription. | |
PaymentWebhook | interface PaymentWebhook<TData> | Verified normalized payment event. | |
Payments | type Payments<TDriver> | Payments facade narrowed to optional commerce methods. | |
Predicate | type Predicate | Serializable portable predicate tree. | |
PresenceRealtimeSurface | interface PresenceRealtimeSurface | Presence join, leave, and member methods. | |
QueryIR | interface QueryIR | Serializable select, count, and write query representation. | |
QueryResult | interface QueryResult<TRow> | Returned rows, affected rows, and count-mode total. | |
Queue | type Queue<TDriver> | Queue facade narrowed to delay, retry, and dead letter. | |
QueueCapabilities | interface QueueCapabilities | Literal queue capability declaration. | |
QueueDriver | interface QueueDriver<TCapabilities, TRaw> | Base enqueue and drain contract. | |
QueueJob | interface QueueJob<TPayload> | Named serializable queue job. | |
QueueReceipt | interface QueueReceipt<TPayload> | Job delivery identifier and attempt. | |
QueuedEventEnvelope | interface QueuedEventEnvelope | Durable event/listener queue boundary without actor context. | |
QueuedListenerContext | interface QueuedListenerContext | Queue, attempt, and maximum tries for a worker. | |
RateLimit | type RateLimit<TDriver> | Rate-limit facade narrowed to algorithm literals. | |
RateLimitAlgorithm | type RateLimitAlgorithm | Token-bucket and sliding-window algorithms. | |
RateLimitCapabilities | interface RateLimitCapabilities<TAlgorithm> | Literal algorithm spectrum. | |
RateLimitDecision | interface RateLimitDecision | Allowance, remaining capacity, and reset time. | |
RateLimitDriver | interface RateLimitDriver<TCapabilities, TRaw> | Rate consumption and reset contract. | |
RateLimitPolicy | interface RateLimitPolicy<TAlgorithm> | Algorithm, limit, and interval settings. | |
RateLimitSurface | interface RateLimitSurface<TDriver> | Consume method restricted to configured algorithms. | |
RateLimited | class RateLimited | Normalized rate-limit error. | |
RateLimitedMetadata | interface RateLimitedMetadata | Key, retry delay, and applied limit. | |
Realtime | type Realtime<TDriver> | Realtime facade narrowed to presence and broadcast. | |
RealtimeCapabilities | interface RealtimeCapabilities | Literal presence and broadcast declaration. | |
RealtimeDriver | interface RealtimeDriver<TCapabilities, TRaw> | Base channel subscription contract. | |
RealtimeMessage | interface RealtimeMessage<TPayload> | Channel event and payload. | |
RealtimeSubscription | interface RealtimeSubscription | Active subscription with asynchronous unsubscribe. | |
RedirectResult | interface RedirectResult | Transport-neutral redirect result. | |
RelationLoad | interface RelationLoad | Fully resolved eager relation plan. | |
RequestCookies | interface RequestCookies | Request-scoped cookie read, write, and delete boundary. | |
RetryQueueSurface | interface RetryQueueSurface | Failed-attempt retry method. | |
RouteDefinition | interface RouteDefinition<TController> | Concrete transport-neutral route entry. | |
RouteManifest | interface RouteManifest<TController> | Versioned ordered route collection. | |
RowSecuritySurface | interface RowSecuritySurface | Ward synchronization method. | |
Search | type Search<TDriver> | Search facade narrowed to facet support. | |
SearchCapabilities | interface SearchCapabilities | Literal facet capability declaration. | |
SearchDocument | interface SearchDocument | Stable document identifier and fields. | |
SearchDriver | interface SearchDriver<TCapabilities, TRaw> | Index, removal, and query contract. | |
SearchHit | interface SearchHit<TDocument> | Matching document and normalized score. | |
SearchOptions | interface SearchOptions | Pagination, filters, and optional facets. | |
SearchResult | interface SearchResult<TDocument> | Hits, total, and optional facet counts. | |
SearchSurface | interface SearchSurface<TDriver> | Query method restricted by facet capability. | |
SerializedEvent | interface SerializedEvent | Queue-safe event payload and references. | |
SerializedReference | interface SerializedReference<TId> | Explicit reference rehydrated in a worker. | |
SignedUrlStorageSurface | interface SignedUrlStorageSurface | Temporary signed read URL method. | |
Social | type Social<TDriver> | Social facade narrowed to provider literals. | |
SocialCapabilities | interface SocialCapabilities<TProvider> | Literal social provider spectrum. | |
SocialDriver | interface SocialDriver<TCapabilities, TRaw, TProfile> | OAuth redirect and state-verifying callback exchange contract. | |
SocialIdentity | interface SocialIdentity<TProfile> | Normalized social subject and profile. | |
SocialSurface | interface SocialSurface<TDriver> | OAuth callback methods restricted to configured providers. | |
Storage | type Storage<TDriver> | Storage facade narrowed to signed URLs and transforms. | |
StorageCapabilities | interface StorageCapabilities<TTransform> | Literal signed URL and transform declaration. | |
StorageDriver | interface StorageDriver<TCapabilities, TRaw> | Base put, get, delete, and exists contract. | |
StorageObject | interface StorageObject | Normalized stored object metadata. | |
StorageTransform | type StorageTransform | Resize, crop, and format operations. | |
StorageTransformOptions | interface StorageTransformOptions | Portable dimensions and output format. | |
StreamResult | interface StreamResult | Async response-byte stream for streaming adapters. | |
StreamingAiSurface | interface StreamingAiSurface | Incremental completion stream method. | |
SubscriptionPaymentSurface | interface SubscriptionPaymentSurface | Subscription create, read, and cancel methods. | |
SyncListenerContext | interface SyncListenerContext | Context for inline listeners. | |
TaggedCacheSurface | interface TaggedCacheSurface | Tagged cache namespace method. | |
TemplateMailSurface | interface TemplateMailSurface | Hosted-template mail method. | |
TokenCapabilities | interface TokenCapabilities | Literal ability and expiration declaration. | |
TokenDriver | interface TokenDriver<TCapabilities, TRaw> | Token authentication, issuance, listing, and revocation contract. | |
TokenIssueOptions | interface TokenIssueOptions | Optional token abilities and expiration. | |
TokenRecord | interface TokenRecord | Subject-owned token metadata without its secret. | |
TokenSurface | interface TokenSurface<TDriver> | Verification plus capability-restricted token issuance. | |
Tokens | type Tokens<TDriver> | API-token facade narrowed to issuance features. | |
TraceLogSurface | interface TraceLogSurface | Trace span creation method. | |
TraceSpan | interface TraceSpan | Active trace span with attributes, errors, and end. | |
TransactionSurface | interface TransactionSurface | Atomic database callback method. | |
TransformStorageSurface | interface TransformStorageSurface<TTransform> | Transform method restricted to literal operations. | |
Unauthenticated | class Unauthenticated | Normalized missing-authentication error. | |
UnauthenticatedMetadata | interface UnauthenticatedMetadata | Authentication guard identifier. | |
Unavailable | class Unavailable | Normalized temporary service outage. | |
UnavailableMetadata | interface UnavailableMetadata | Service name and retry delay. | |
ViewRef | type ViewRef<TReference> | Opaque adapter-owned view reference. | |
ViewResult | interface ViewResult<TViewRef, TProps> | Opaque view reference and serializable properties. | |
WebhookPaymentSurface | interface WebhookPaymentSurface | Signed webhook verification and normalization method. | |
defineListener | defineListener(definition) | Preserves literal delivery, priority, retry, and backoff types. | |
supports | supports(driver, capability) | Runtime capability guard with typed keys. | |
AvelonConfig | interface AvelonConfig | Application configuration accepted by defineConfig. | |
AvelonDrivers | interface AvelonDrivers | Optional driver wiring for database, identity, mail, storage, and queue. | |
CompiledSql | interface CompiledSql | Parameterized SQL boolean expression produced by the ward compiler. | |
ControllerClass | type ControllerClass | Constructable controller accepted by createKernel. | |
ControllerMethod | type ControllerMethod | Controller action signature. | |
CreateKernelOptions | interface CreateKernelOptions | Binding, actor, middleware, and exception-mapping hooks. | |
DB | const DB | Database facade with named connection() resolution. | |
ErrandDefinition | interface ErrandDefinition<TPayload> | Background job contract with three delivery modes. | |
Errands | const Errands | Dispatch, drain, failed table, retry, and flush. | |
Events | const Events | Process-wide EventDispatcher plus after/queued flush helpers. | |
Events.bindQueue | (queue?: QueueDriver) => void | Wires a queue driver for queued listeners; omit to use the memory board. | |
FormRequest | interface FormRequest<TOutput> | Request validator with validate(). | |
FormRequestDefinition | interface FormRequestDefinition<TOutput> | Zod schema plus optional authorize hook. | |
Gate | const Gate | Policy can and authorize helpers. | |
GateActor | type GateActor | Authenticated actor or null. | |
InProcessEventDispatcher | class InProcessEventDispatcher | Default EventDispatcher implementation. | |
KernelMiddleware | type KernelMiddleware | Named middleware callback. | |
MaybeNamed | type MaybeNamed<TDriver> | Single driver or named registry. | |
MemoryJobBoard | class MemoryJobBoard | Process-local queue and failed table. | |
NamedDrivers | interface NamedDrivers<TDriver> | { default, instances/mailers/disks/connections } registry. | |
PolicyAbilities | type PolicyAbilities | Ability name to handler map. | |
PolicyHandler | type PolicyHandler | Policy callback receiving actor and resource. | |
RequestSchema | interface RequestSchema<TOutput> | Zod-compatible parse surface. | |
WardAbilities | interface WardAbilities | read/insert/update/delete ward factories. | |
WardAction | type WardAction | One of the four ward abilities. | |
WardDrift | interface WardDrift | Fixture evaluation mismatch. | |
WardFixture | interface WardFixture | Row plus expected visibility. | |
WardInput | type WardInput | Predicate, boolean, or object shorthand. | |
WardShorthand | interface WardShorthand | { or, and, not } or column-equals object. | |
auth | (cookies) => IdentityDriver | Request-scoped identity factory. | |
backoffSeconds | (backoff, attempt) => number | Delay for a one-based attempt. | |
capabilityMatrix | (config?) => Record<string, Record<string, unknown>> | Literal capabilities for every configured instance. | |
compilePredicateToSql | (predicate) => CompiledSql | Parameterized SQL boolean expression. | |
compileWardPolicy | (resource, action, actor, role?) => { statement, params } | Postgres RLS CREATE POLICY statement. | |
compileWardShorthand | (input) => Predicate | Shorthand or boolean to portable predicate. | |
createEventDispatcher | (options?) => InProcessEventDispatcher | Isolated event bus. | |
createKernel | (options?) => Kernel | Request pipeline with middleware, binding, and exception mapping. | |
defineAbility | (ability, handler) => void | Registers a global can:* middleware ability. | |
defineConfig | (config, environment?) => config | Wires drivers; overlay merges on top. | |
defineErrand | (definition) => ErrandDefinition | Preserves errand delivery and retry metadata. | |
definePolicy | (resource, abilities) => void | Registers policy abilities for a resource. | |
defineRequest | (definition) => FormRequest | Zod validation with optional authorize hook. | |
defineWard | (resource, abilities) => void | Registers a ward for IR injection and SQL policy compile. | |
detectPolicyDrift | (currentSql, recordedSql) => boolean | True when a compiled policy statement changed. | |
detectWardDrift | (predicate, fixtures) => WardDrift[] | Client-side evaluation mismatches. | |
disks | const disks | Storage facade with named disk() resolution. | |
eventDispatcher | () => InProcessEventDispatcher | Process-wide dispatcher instance. | |
evaluatePredicate | `(predicate, row) => boolean \ | null` | SQL three-valued client evaluation. |
finishResponse | () => Promise<void> | Flushes after listeners and errands. | |
flushAfterErrands | () => Promise<void> | Runs errands scheduled with delivery: 'after'. | |
getConfig | () => AvelonConfig | Active configuration, or Unavailable. | |
holdUntilCommit | (task) => void | Holds a task until runInTransaction commits. | |
injectWard | (query, ward) => QueryIR | Copies a query and sets ward. | |
isInTransaction | () => boolean | Whether an afterCommit boundary is open. | |
jobBoard | () => MemoryJobBoard | Process-local job board used by events and errands. | |
mailers | const mailers | Mail facade with named mailer() resolution. | |
mapKernelException | `(error) => KernelResult \ | undefined` | Maps taxonomy errors to HTTP-shaped results. |
queues | const queues | Queue facade with named connection() resolution. | |
redirect | (location, status?) => RedirectResult | Builds a redirect kernel result. | |
refusedWardShapes | readonly string[] | Predicate shapes the ward compiler will not approximate. | |
registerErrand | (definition) => void | Registers an errand by name. | |
resetConfig | () => void | Clears configuration. Test helper. | |
resetErrands | () => void | Clears registered errands. Test helper. | |
resetPolicies | () => void | Clears registered policies. Test helper. | |
resetTransaction | () => void | Clears commit-boundary state. Test helper. | |
resetWards | () => void | Clears registered wards. Test helper. | |
resolveNamedDriver | (value, name, kind) => TDriver | Resolves a named instance or throws Invalid. | |
resolveWard | (resource, action, actor) => Predicate | Compiles a registered ward ability. | |
rowAllowedByWard | (predicate, row) => boolean | True only when evaluation is true. | |
runInTransaction | (callback) => Promise<T> | Commit boundary for afterCommit dispatch. | |
validateRequest | (request, schema) => TOutput | Parses a body or throws Invalid. | |
view | (viewRef, props, status?) => ViewResult | Builds an opaque view kernel result. | |
withWard | typeof injectWard | Alias for injectWard. |
Testing
Driver packages provide certified fakes. When you test a package that only consumes the contract, a small structural fake keeps the exact same method surface.
import { expect, test } from 'bun:test'
import type { MailDriver } from '@avelon/core'
const sent: string[] = []
const mail = {
name: 'memory',
instance: 'default',
capabilities: { templates: false } as const,
async send(message) {
const recipients = typeof message.to === 'string' ? [message.to] : message.to
sent.push(...recipients)
return { id: `message-${sent.length}`, accepted: recipients }
},
raw() {
return null
},
} satisfies MailDriver<{ templates: false }, null>
test('sends the welcome message', async () => {
await mail.send({
to: 'reader@example.com',
subject: 'Welcome',
text: 'Your account is ready.',
})
expect(sent).toEqual(['reader@example.com'])
})
Run the package's runtime and type-level contract tests together:
bun test
bun run typecheck