audit-plugin/src/index.ts

Classes

c
AuditService(
storage: IAuditStorage,
runtime: IRuntimeServices
)

Audit service backed by an IAuditStorage port.

c
DatabaseAuditStorage(options: { client: IAuditDbClient; table?: string; })

Database-backed audit storage. Requires an injected IAuditDbClient at construction time.

c
FileAuditStorage(options: { fs: IFileSystem; path?: string; })

File-backed audit storage. Writes JSONL to path via runtime.fs.

c
LogAuditStorage(options?: { logger?: ILogger; level?: LogLevel; })

Logs audit records through an ILogger. When constructed without a logger and used as a storage backend, queries return empty arrays.

c
MemoryAuditStorage

In-memory audit storage backed by an array. Stores already-frozen records; isReady() always returns true. Non-durable across restarts.

Functions

f
AuditPlugin(options?: AuditPluginOptions): IPlugin

AuditPlugin factory — registers an IAuditLogger under CAPABILITIES.AUDIT.

Interfaces

I
AuditEntry

One immutable audit trail entry.

I
AuditPluginOptions

Options accepted by the AuditPlugin factory.

I
AuditQuery

Query criteria for IAuditStorage.query. Every field is optional and combines as AND. An omitted field does not constrain.

I
AuditStorageOptions

Options passed to individual storage backends.

I
IAuditDbClient

Structural shape of an injected database client facade. The DB backend is inject-only — it never touches the database capability token.

I
IAuditLogger

Immutable audit trail writer.

I
StoredAuditEntry

A stored audit record extends AuditEntry with an internally assigned id (UUID v4) and timestamp (wall-clock epoch ms).

Type Aliases

T
AuditStorageType = "memory" | "log" | "database" | "file"

Storage backend identifier — closed union.

auth-plugin/src/index.ts

Examples

Example 1

import { AuthPlugin, authMiddleware, requireAuth, requireRole } from '@setu-ts/auth-plugin';

app.register(AuthPlugin({
  jwt: { secret: process.env.JWT_SECRET! },
  rbac: {
    roles: {
      admin: { permissions: ['*'], inherits: ['user'] },
      user: { permissions: ['users:read'] },
    },
  },
}));
// Priority 300 is the band ARCHITECTURE.md §10 reserves for authentication;
// a bare add() would take the kernel default of 500 and run after it.
app.middleware.add(authMiddleware(), { priority: 300 });
app.router.get('/protected', { middleware: [requireAuth()], handler });

Classes

c
MalformedPasswordHashError

Thrown by PasswordHasher.verify when the stored value is not a well-formed pbkdf2$<iterations>$<salt>$<hash> string.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
MemoryAccessTokenRevocationStore(runtime: IRuntimeServices)

Single-process access-token revocation store with bounded lazy expiry work.

c
MemoryRateLimitStore(runtime: IRuntimeServices)

In-memory implementation of RateLimitStore.

c
MemoryRefreshTokenStore(runtime: IRuntimeServices)

In-memory implementation of RefreshTokenStore.

c
PasswordHasher(runtime: IRuntimeServices)

Password hasher using PBKDF2-SHA256 via Web Crypto.

c
RedisRateLimitStore(options: { url?: string | undefined; client?: IRateLimitRedisClient | undefined; runtime: IRuntimeServices; keyPrefix?: string | undefined; })

Redis-backed rate limit store implementation.

c
RefreshTokenService(options: RefreshTokenOptions)

Refresh token service implementing token rotation and revocation.

Functions

f
authMiddleware(): MiddlewareFunction

Authentication middleware that runs passive strategies and populates ctx.request.user. Always calls next() - it authenticates only, does not authorize.

f
defaultRateLimitKey(ctx: IRequestContext): string

Default rate-limit key, in order of preference:

f
publicRoute(): MiddlewareFunction

Guard that allows public access (always continues). Useful for explicitly marking routes as public when auth middleware is global.

f
requireAllPermissions(permissions: readonly string[]): MiddlewareFunction

Guard that requires all of the specified permissions. Returns 401 if no principal, 403 if any missing.

f
requireAnyRole(roles: readonly string[]): MiddlewareFunction

Guard that requires any of the specified roles. Returns 401 if no principal, 403 if none match.

f
requireAuth(): MiddlewareFunction

Guard that requires authentication. Returns 401 if no principal.

f
requirePermission(permission: string): MiddlewareFunction

Guard that requires a specific permission. Returns 401 if no principal, 403 if insufficient permission.

f
requireRole(role: string): MiddlewareFunction

Guard that requires a specific role. Returns 401 if no principal, 403 if insufficient role.

Interfaces

I
ApiKeyOptions

API key configuration options.

I
AuthPluginOptions

Auth plugin configuration options.

  • apiKey: ApiKeyOptions

    API key configuration. Optional.

  • jwt: JwtOptions

    JWT configuration. Required.

  • local: LocalOptions

    Local credentials configuration. Optional.

  • rbac: RbacConfig

    RBAC configuration. When absent, AuthPlugin registers JWT authentication only and does not provide the authorization capability.

  • session: SessionAuthOptions

    Session authentication configuration. When present, the plugin appends an internal session strategy after the API-key strategy and requires the session capability (SessionPlugin) to be registered.

  • strategies: readonly IAuthStrategy[]

    Caller-supplied strategies, appended after every built-in in declaration order. A strategy whose name collides with any other strategy in the assembled chain makes register() throw.

I
IAccessTokenRevocationStore

Store for access-token identifiers revoked before their JWT expiry.

I
IAuthorizationService

Authorization service for RBAC with role hierarchy.

I
IAuthService

Authentication service that coordinates strategies and provides credential verification for login flows.

I
IAuthStrategy

Authentication strategy interface. Implementations extract credentials from a request and return a principal, or null if the strategy does not apply.

I
IJwtService

JWT sign/verify service.

I
IPrincipal

The authenticated identity attached to a request by authentication middleware.

I
JwtOptions

JWT configuration options.

I
JwtSignOptions

Options accepted when signing a JWT.

I
LocalOptions

Local (credentials) configuration options.

I
RateLimitOptions

Options for rate limiting middleware.

I
RateLimitResult

Result of incrementing a rate limit counter.

I
RateLimitStore

Store interface for rate limiting.

I
RbacConfig

RBAC configuration for role hierarchy and permissions.

I
RefreshTokenOptions

Options for constructing a RefreshTokenService.

I
RefreshTokenRecord

A refresh token record stored on the server.

I
RefreshTokenStore

Store interface for refresh tokens.

I
RoleDefinition

Role definition for RBAC configuration.

I
SessionAuthOptions

Session authentication configuration options.

I
TokenPair

A pair of access + refresh tokens issued together.

Type Aliases

Variables

v
DEFAULT_RATE_LIMIT_EXCLUDED_PATHS: readonly PathPattern[]

The operational paths RateLimitOptions.exclude exempts by default: the framework's health, metrics and OpenAPI routes plus the interactive docs. The same six tenantMiddleware exempts, deliberately — one list to remember rather than two.

v
DEFAULT_RATE_LIMIT_KEY_PREFIX: "setu:ratelimit:"

The namespace RedisRateLimitStore prepends to every key when no keyPrefix is supplied.

cache-plugin/src/index.ts

Classes

c
CacheService(
backend: CacheStore,
prefix: string,
defaultTtl?: number
)

Service layer that delegates to a backend CacheStore while applying:

c
MemoryStore(
_prefix: string,
options?: { maxSize?: number | undefined; clock?: ClockFn | undefined; }
)

In-memory cache implementation with LRU eviction and lazy TTL expiry.

c
NoopStore(_prefix?: string)

No-op implementation of CacheStore. Every method resolves without side effects: reads return null/false, writes resolve void, and lifecycle methods are no-ops.

c
RedisStore(
prefix: string,
options?: { url?: string | undefined; client?: IRedisClient | undefined; }
)

Redis-backed cache store implementation.

Functions

Interfaces

I
CachedResponsePayload

Serializable cached response payload stored in the cache backend. Body is base64-encoded when binary so that JSON-safe stores (Redis) can persist it without corruption.

I
CacheMiddlewareOptions

Options for the transparent response-caching middleware.

I
CachePluginOptions

Options for the CachePlugin factory.

I
CacheStoreOptions

Options for creating a cache store backend.

I
ICacheStore

Key/value cache with per-entry TTL.

I
IRedisClient

Structural shape of an ioredis-compatible client. Used for validation and injection so that the plugin does not hard-depend on ioredis.

Type Aliases

T
CacheStoreType = "memory" | "redis" | "noop"

Supported cache store backends.

cli/src/index.ts

Examples

Example 1

import { runCli } from '@setu-ts/cli';
import { createDenoRuntimeServices } from '@setu-ts/runtime';

const runtime = createDenoRuntimeServices();
const code = await runCli(['generate', 'service', 'billing'], {
  fs: runtime.fs!,
  cwd: Deno.cwd(),
  now: () => runtime.now(),
  log: console.log,
  error: console.error,
});

Functions

f
deriveNames(raw: string): DerivedNames

Derive all five naming forms from a raw input string.

f
detectPlugins(
fs: IFileSystem,
dir: string
): Promise<ReadonlySet<string>>

Detects the @setu-ts packages a project depends on.

f
runCli(
argv: readonly string[],
deps: CliDependencies
): Promise<number>

Parses argv, runs the requested command, and returns its exit code.

Interfaces

I
CliDependencies

Everything the CLI reaches the outside world through.

I
DerivedNames

The five naming forms derived from an input string.

  • camel: string

    camelCase: lowercase first letter, no separators (e.g., userProfile).

  • kebab: string

    kebab-case: lowercase with hyphens (e.g., user-profile).

  • pascal: string

    PascalCase: uppercase first letter, no separators (e.g., UserProfile).

  • raw: string

    The raw input as provided by the user.

  • screaming: string

    SCREAMING_SNAKE_CASE: uppercase with underscores (e.g., USER_PROFILE).

I
GeneratedFile

One file a schematic asks the command layer to create.

I
PromptChoice

One selectable answer to a scaffold question.

  • label: string

    One line describing what the choice does, shown above the question.

  • value: string

    The value written into the flag record when chosen.

I
Prompter

Asks the scaffold questions setu new accepts as flags.

I
SchematicOptions

Options handed to every schematic.

Type Aliases

T
AppLoader = ModuleLoader

Loads the project's config module by URL.

T
Schematic = (
names: DerivedNames,
options: SchematicOptions
) => readonly GeneratedFile[]

The contract every schematic satisfies — a pure function from a name to the files to create. Schematics perform no I/O; the command layer writes.

T
TemplateName = (TEMPLATES)[number]

A project template accepted by setu new --template.

Variables

v
PROGRAM_NAME: "setu"

The name of the CLI executable.

cli/src/main.ts

The setu executable entry point.

cloudflare-plugin/src/index.ts

Examples

Example 1

import { env, waitUntil } from 'cloudflare:workers';
import { createApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';
import { CloudflarePlugin } from '@setu-ts/cloudflare-plugin';

const app = createApplication({
  plugins: [
    RuntimePlugin({ env }),
    CloudflarePlugin({ env, waitUntil, cache: { binding: 'CACHE_KV', prefix: 'cache:' } }),
  ],
});

await app.start();
export default { fetch: app.fetch };

Classes

c
CloudflareBindingMissingError(message: string)

A binding the configuration names is absent from the Worker's env, or is present with the wrong shape.

c
CloudflareObjectNotFoundError(path: string)

An R2 object read found nothing.

c
CloudflareRemoteHandlerError(message: string)

A responder threw, and its failure was relayed to the caller.

c
CloudflareRequestTimeoutError(
topic: string,
timeoutMs: number
)

A brokered request received no reply within its budget.

c
CloudflareUnsupportedError(message: string)

The requested operation has no counterpart on the Cloudflare binding.

c
DurableObjectBackplane(
namespace: IDurableObjectNamespace,
options: DurableObjectBackplaneOptions
)

Carries RealtimeFrames between replicas over one WebSocket to a Durable Object.

c
R2Storage(
bucket: IR2Bucket,
options?: R2StorageOptions
)

Object storage backed by Cloudflare R2.

c
WorkersBroker(
producer: IQueueProducer,
runtime: BrokerRuntime,
options?: WorkersBrokerOptions
)

A message broker backed by Cloudflare Queues.

c
WorkersCron(options?: WorkersCronOptions)

A registry of Cron Trigger handlers, keyed by cron expression.

Functions

f
assessCacheability(input: CacheabilityInput): readonly CacheRefusal[]

Lists every reason the edge cache would refuse this response.

f
asUpgradeResponse(
response: unknown,
binding: string
): DurableObjectUpgradeResponse

Narrows a Durable Object stub's response to one carrying a socket.

f
f
createDefaultDurableObjectWebSocketHost(): DurableObjectWebSocketHost

Builds the default host from the real Workers global.

f
createMessagingHandler(
app: IApplication,
options?: MessagingHandlerOptions
): MessagingHandler

Builds the handler an application exports as queue to consume messages.

f
createScheduledHandler(cron: WorkersCron): ScheduledHandler

Builds the handler an application exports as scheduled.

f
isD1Database(value: unknown): value is ID1Database

Reports whether a binding is D1-shaped.

f
isDurableObjectNamespace(value: unknown): value is IDurableObjectNamespace

Reports whether a binding is Durable-Object-namespace-shaped.

f
isKvNamespace(value: unknown): value is IKvNamespace

Reports whether a binding is KV-shaped.

f
isQueueProducer(value: unknown): value is IQueueProducer

Reports whether a binding is Queues-producer-shaped.

f
isR2Bucket(value: unknown): value is IR2Bucket

Reports whether a binding is R2-shaped.

Interfaces

I
BrokerRuntime

The runtime capabilities this broker needs. IRuntimeServices satisfies it.

I
CacheabilityInput

What assessCacheability needs to decide.

I
CacheApiMiddlewareOptions

Options for cacheApiMiddleware.

  • bypass: (ctx: IRequestContext) => boolean

    Returning true skips the cache entirely for this request.

  • cache: ICacheApi

    The cache handle. Omitted resolves caches.default from the global scope; when that is also absent — every runtime other than Cloudflare Workers — the middleware passes through instead of throwing.

  • cacheableStatuses: readonly number[]

    Statuses worth caching. Defaults to [200]. Does not override the platform's unconditional refusal of 206.

  • key: (ctx: IRequestContext) => string

    Builds the cache key from the request. Omitted uses the full request URL, which is what the platform's own cache keys on.

  • ttlSeconds: number

    Adds Cache-Control: public, max-age=<n> to the stored copy when the response carries no Cache-Control of its own. The edge honors the stored response's own directive, so without one an entry has no freshness lifetime and is of little use. The client's response is left untouched.

I
CacheClock

The clock shape this store needs. IRuntimeServices satisfies it.

I
CloudflarePluginOptions

Options for CloudflarePlugin.

I
D1AdapterOptions

Options for D1Adapter.

I
D1EntityMapping

How one entity name maps onto a physical D1 table.

  • primaryKey: string | readonly string[]

    The primary-key column(s). A scalar name keeps today's single-column behaviour; an array enables a composite key whose columns are matched in declaration order. Defaults to ['id'].

  • table: string

    The table name. Defaults to the entity name itself, so getRepository('users') needs no mapping at all.

I
D1Result

A D1 statement result.

I
DistributedLockObjectCoreOptions

Options for DistributedLockObjectCore.

I
DurableObjectArm

Wires a Durable Object namespace up as the application's IRealtimeBackplane under CAPABILITIES.REALTIME_BACKPLANE, so WebSocket rooms and SSE channels reach clients on other replicas.

  • binding: string

    The Durable Object namespace binding name from wrangler.toml.

  • name: string

    Instance name. 'default' (the default) claims the bare realtime-backplane token; anything else derives realtime-backplane.<name>.

  • topic: string

    The object name every replica shares, passed to idFromName.

I
DurableObjectBackplaneOptions

Options for DurableObjectBackplane.

I
DurableObjectLockOptions

Options for DurableObjectLock.

I
DurableObjectMessageEvent

One message arriving on a Durable Object WebSocket.

I
DurableObjectUpgradeResponse

A Durable Object stub's response to a WebSocket upgrade.

I
DurableObjectWebSocketHost

Supplies the socket pair a Durable Object upgrade needs.

I
DurableObjectWebSocketPair

A created WebSocketPair.

I
ICloudflareBindings

Typed access to a Cloudflare Worker's platform bindings.

I
ID1Database

A D1 database binding.

I
ID1PreparedStatement

A prepared D1 statement.

I
IDurableObjectClientSocket

The client half of a WebSocketPair, or the socket a Worker gets back from a Durable Object upgrade.

I
IDurableObjectNamespace

A Durable Object namespace binding.

I
IDurableObjectState

The DurableObjectState (ctx) members this package calls.

I
IDurableObjectStorage

The subset of DurableObjectStorage the lock object uses.

I
IDurableObjectWebSocket

A WebSocket held by a Durable Object, as the hibernation API hands it back.

I
IKvNamespace

A Workers KV namespace binding.

I
IQueueMessage

One message delivered to a Queues consumer.

I
IQueueMessageBatch

A batch of messages delivered to a Queues consumer.

I
IQueueProducer

A Cloudflare Queues producer binding.

I
IR2Bucket
I
IR2Object

Metadata common to every R2 object.

I
IR2ObjectBody

An R2 object together with its body.

I
IScheduledController

The controller handed to a Cron Trigger's scheduled handler.

I
IServiceBinding

A service binding to another Worker — a fetch-shaped RPC channel.

I
JobIdSource

The id source this queue needs. IRuntimeServices satisfies it.

I
KvCacheOptions

Wires a KV namespace up as the application's ICacheStore under CAPABILITIES.CACHE.

  • binding: string

    The KV namespace binding name from wrangler.toml.

  • defaultTtlSeconds: number

    TTL in seconds applied when set omits one. Omitted means no expiry.

  • name: string

    Instance name. 'default' (the default) claims the bare cache token; anything else derives cache.<name>, matching CachePlugin's convention so several caches can coexist.

  • prefix: string

    Prefix applied to every cache key. Required to call clear(), and recommended whenever the namespace is shared.

I
KvCacheStoreOptions

Options for KvCacheStore.

  • defaultTtlSeconds: number

    TTL in seconds applied when set omits one. Omitted means no expiry.

  • prefix: string

    Prefix applied to every key. Required for KvCacheStore.clear, which otherwise has no way to tell this store's keys from anything else sharing the namespace.

I
KvListOptions

Options for IKvNamespace.list.

I
KvListResult

One page of IKvNamespace.list results.

I
KvPutOptions

Options for IKvNamespace.put.

  • expirationTtl: number

    Seconds until KV removes the entry. The platform minimum is 60; a smaller value is rejected, which is why physicalTtlSeconds floors it and a logical expiry is carried inside the value.

I
KvSessionStoreOptions

Options for KvSessionStore.

  • prefix: string

    Prefix applied to every session key. Defaults to 'session:', so sharing one namespace with a cache store is safe by default.

I
MessagingHandlerOptions

Options for createMessagingHandler.

  • name: string

    Which broker instance to dispatch into, matching CloudflarePluginOptions.messaging.name. Omitted resolves the bare CAPABILITIES.MESSAGING token.

I
QueueHandlerOptions

Options for createQueueHandler.

  • name: string

    Which queue instance to dispatch into, matching CloudflarePluginOptions.queue.name. Omitted resolves the bare CAPABILITIES.QUEUE token.

I
QueueSendOptions

Options for IQueueProducer.send.

I
R2PutOptions

The subset of R2's put options this package writes.

I
R2StorageArm

Wires an R2 bucket up as the application's IStorage under CAPABILITIES.STORAGE.

  • binding: string

    The R2 bucket binding name from wrangler.toml.

  • name: string

    Instance name. 'default' (the default) claims the bare storage token; anything else derives storage.<name>.

  • prefix: string

    Prefix applied to every object key.

I
R2StorageOptions

Options for R2Storage.

  • prefix: string

    Prefix applied to every object key, so one bucket can host several uses.

I
RealtimeBackplaneObjectCoreOptions

Options for RealtimeBackplaneObjectCore.

I
ReplyInboxBinding

The Durable Object namespace serving reply inboxes, plus its binding name.

I
ReplyInboxObjectCoreOptions

Options for ReplyInboxObjectCore.

I
WorkersBrokerOptions

Options for WorkersBroker.

I
WorkersCronOptions

Options for WorkersCron.

  • logger: ILogger

    Reports the two paths that would otherwise be silent: a trigger firing with no handler registered for its expression, and a handler that rejects. Omitted leaves both silent.

I
WorkersMessagingArm

Wires a Cloudflare Queues producer binding up as the application's IMessageBroker under CAPABILITIES.MESSAGING.

  • binding: string

    The Queues producer binding name from wrangler.toml.

  • name: string

    Instance name. 'default' (the default) claims the bare messaging token; anything else derives messaging.<name>, which MessagingHandlerOptions.name must then match.

  • rpc: WorkersMessagingRpcArm

    Enable request/respond. Omitted, both throw CloudflareUnsupportedError naming this arm.

I
WorkersMessagingRpcArm

Enables brokered request-reply on a WorkersMessagingArm.

I
WorkersQueueArm

Wires a Cloudflare Queues producer binding up as the application's IQueue under CAPABILITIES.QUEUE.

  • binding: string

    The Queues producer binding name from wrangler.toml.

  • maxDelaySeconds: number

    Largest accepted AddJobOptions.delayMs, in seconds. Defaults to 86400, the platform maximum; a larger delay throws rather than being silently truncated.

  • name: string

    Instance name. 'default' (the default) claims the bare queue token; anything else derives queue.<name>, which QueueHandlerOptions.name must then match.

I
WorkersQueueOptions

Options for WorkersQueue.

  • logger: LoggerSource

    Resolves the logger at the moment a dispatch path needs it, reporting on the four cases that would otherwise be silent: a message whose name has no processor, an unreadable body, a processor that threw, and a job that exhausted its attempts.

  • maxDelaySeconds: number

    Largest delayMs this queue will accept, in seconds. Defaults to 86400, the platform maximum. A larger delay throws rather than being silently truncated by the platform.

Type Aliases

T
CloudflareWorkerEnv = Readonly<Record<string, unknown>>

The Worker env record, as import { env } from 'cloudflare:workers' provides it: a mix of string variables and object bindings.

T
LoggerSource = () => ILogger | undefined

Resolves the logger at the moment a background task fails.

T
MessagingHandler = (batch: IQueueMessageBatch) => Promise<void>

The queue export's shape, as Cloudflare invokes it.

T
QueueHandler = (batch: IQueueMessageBatch) => Promise<void>

The queue export's shape, as Cloudflare invokes it.

T
ScheduledHandler = (controller: IScheduledController) => Promise<void>

The scheduled export's shape, as Cloudflare invokes it.

T
WaitUntilHost = (promise: Promise<unknown>) => void

A sink that keeps a Worker alive until the promise settles.

common/src/index.ts

Classes

c
MalformedRequestBodyError(cause: unknown)

Thrown when a request body cannot be parsed as JSON.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
UnsupportedFormEncodingError()

Raised when a request body is not a form encoding the framework can parse: a JSON body, a missing content-type, or a multipart/form-data type carrying no boundary=.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

Functions

f
assertRealPathContained(
fs: Pick<IFileSystem, "realPath" | "stat">,
root: string,
target: string
): Promise<boolean>

Asserts that a target path is contained within a root by comparing canonical paths.

f
brandErrorResponder(
middleware: object,
responder: IErrorResponder
): void

Brands a middleware function with the application's resolved error responder, so the kernel can reach it at the pre-pipeline sites.

f
causeMessage(cause: unknown): string

Extracts a caller-facing message from an unknown thrown value.

f
composeBehaviorChain<TWork, TResult>(
work: TWork,
behaviors: readonly BehaviorLike<TWork, TResult>[],
terminal: () => Promise<TResult>
): Promise<TResult>

Composes behaviours around a terminal handler — the ONE shared composer for the CQRS pipeline and all four non-HTTP ingress chains.

f
contentTypeFor(path: string): string

Returns the content type for a file based on its extension.

f
contextToTraceparent(context: TelemetryContext): string | null

Formats a context as a W3C traceparent value.

f
f
createCapabilityToken(name: string): CapabilityToken

Creates a custom capability token for third-party plugins.

f
createPathMatcher(patterns: readonly PathPattern[]): (path: string) => boolean

Builds a path-exclusion predicate from a list of literals and patterns.

f
decodeCursor(token: string): CursorPayload | null

Decode a cursor token to its CursorPayload, or null when the token is malformed.

f
decodeFrameData(payload: EncodedPayload): string | Uint8Array

Decodes a payload received from the wire back into its local form.

f
encodeCursor(payload: CursorPayload): string

Encode a CursorPayload as a base64url-encoded JSON token.

f
encodeFrameData(data: string | Uint8Array): EncodedPayload

Encodes a WebSocket payload for the wire.

f
err<E>(error: E): Err<E>

Creates a failed Result.

f
errorResponderOf(middleware: object): IErrorResponder | undefined

Reads the error responder branded onto a middleware function, if any.

f
extractContextFromHeaders(headers: Headers): TelemetryContext

Extracts W3C trace context from web-standard headers.

f
formEncodingOf(contentType: string | null): FormEncoding | undefined

Classifies a request content-type as one of the two form encodings.

f
fromNullable<T>(value: T | null | undefined): Option<T>

Converts a nullable value to an Option.

f
httpStatusHintOf(error: unknown): HttpStatusHint | undefined

Reads the status hint an error was branded with.

f
isErr<T, E>(result: Result<T, E>): result is Err<E>

Type guard: narrows a Result to Err.

f
isLexicallyContained(relativePath: string): boolean

Checks if a relative path is lexically contained within a root.

f
isNone<T>(option: Option<T>): option is None

Type guard: narrows an Option to None.

f
isOk<T, E>(result: Result<T, E>): result is Ok<T>

Type guard: narrows a Result to Ok.

f
isPromiseLike<T>(value: T | PromiseLike<T>): value is PromiseLike<T>

Reports whether a value is thenable, by the same duck-typed test the platform serve layers use rather than instanceof Promise.

f
isSome<T>(option: Option<T>): option is Some<T>

Type guard: narrows an Option to Some.

f
isWebSocketUpgradeRequest(headers: Headers): boolean

Reports whether a set of request headers describes an RFC 6455 WebSocket upgrade.

f
isWorkerReadySignal(message: unknown): message is WorkerReadySignal

Narrows an incoming message to a WorkerReadySignal.

f
isWorkerTaskReply(message: unknown): message is WorkerTaskReply

Narrows an incoming message to a WorkerTaskReply.

f
isWorkerTaskRequest(message: unknown): message is WorkerTaskRequest

Narrows an incoming message to a WorkerTaskRequest.

f
none(): None

Returns the None option.

f
ok<T>(value: T): Ok<T>

Creates a successful Result.

f
parseCookie(header: string | null | undefined): Record<string, string>

Parses a Cookie request header into a name→value record.

f
parseFormBody(
body: Uint8Array,
contentType: string | null
): FormBody

Parses one request body as a form — the ONE parse all three IRequest.formData?() implementations share, and the function every fallback path (a request without the optional accessor) calls directly.

f
parseJsonBody(text: string): unknown

Parses one request-body text as JSON, the ONE parse all three IRequest json() implementations share (X37-1, M90f).

f
replacePrincipal(
request: IRequest,
principal: IPrincipal
): void

Replaces request.user deliberately, bypassing the single-write guard.

f
replaceTenant(
request: IRequest,
tenant: ITenant
): void

Replaces request.tenant deliberately, bypassing the single-write guard.

f
resolveKeysetSort(
orderBy: Readonly<Record<string, OrderDirection>>,
keyColumns: ReadonlyArray<string>
): Record<string, OrderDirection>

The sort a keyset walk actually runs under: the caller's orderBy followed by every primary-key column it does not already carry, each ascending.

f
resolveProbeTiming(runtime: IRuntimeServices): ProbeTiming

Resolves a probe's monotonic clock and timer surface from an injected IRuntimeServices.

f
resolveRegistryEntry<T>(
entry: T | RegistryFactory<T>,
services: IServiceRegistry,
label: string
): T

Resolves one entry of a registration option that accepts either an instance or a RegistryFactory.

f
resolveResponseStatus(
status: number,
target: ErrorResponderTarget
): number

Returns a status the web Response constructor will accept, clamping an unserveable one to 500 and reporting it through the logger capability when one is reachable.

f
respondWithAuthorizationFailure(
target: ErrorResponderTarget,
failure: AuthorizationFailure
): void

Write the framework-standard response for an authorization refusal.

f
respondWithError(
target: ErrorResponderTarget,
init: ErrorResponseInit
): void

Responds to an error in the application's configured format.

f
sealRequestIdentity(request: IRequest): void

Installs the single-write guard over request.user and request.tenant.

f
securityMetadataOf(middleware: MiddlewareFunction): RouteSecurityMetadata | undefined

Reads the security metadata a middleware function was branded with.

f
serializeCookie(
name: string,
value: string,
attrs?: CookieAttributes
): string

Serializes a cookie into a Set-Cookie header value.

f
serializeError(value: unknown): SerializedError

Serializes any thrown value to a plain, serializable object.

f
setUpgradeIntent(
request: IRequest,
intent: WebSocketUpgradeIntent
): void

Brands a request with a WebSocket upgrade intent for the HTTP adapter to act on after the framework handler returns.

f
some<T>(value: T): Some<T>

Creates an Option holding a value.

f
sortFingerprint(orderBy: Readonly<Record<string, OrderDirection>>): string

Build the stable sort fingerprint embedded in every minted cursor.

f
f
unwrap<T, E>(result: Result<T, E>): T

Unwraps a Result, returning the value or throwing the error.

f
upgradeIntentOf(request: IRequest): WebSocketUpgradeIntent | undefined

Reads the WebSocket upgrade intent an adapter should act on, or undefined when the pipeline did not ask for an upgrade.

f
validatedStateKey(target: ValidationTarget): string

Builds the ctx.state key under which the validated value for a target is stored — the cross-package wire format between the writer (validation-plugin's middleware) and any reader (e.g. decorator-plugin's parameter resolvers). Both sides import this helper so the key can never drift between the package that writes it and the one that reads it back.

f
validationMetadataOf(middleware: MiddlewareFunction): RouteValidationMetadata | undefined

Reads the validation metadata a middleware function was branded with.

f
withHttpStatusHint<T extends Error>(
error: T,
hint: HttpStatusHint
): T

Brands an error with the status it should be answered with.

f
withSecurityMetadata<T extends MiddlewareFunction>(
middleware: T,
metadata: RouteSecurityMetadata
): T

Brands a middleware function with the security it enforces, so a documentation generator can read it without importing the plugin that produced it.

f
withValidationMetadata<T extends MiddlewareFunction>(
middleware: T,
metadata: RouteValidationMetadata
): T

Brands a middleware function with the request part and schema it validates, so a documentation generator can read it without importing the plugin that produced it.

Interfaces

I
AddJobOptions

Options accepted when enqueueing a job.

I
AuditEntry

One immutable audit trail entry.

I
BehaviorLike

The structural shape both behaviour contracts satisfy, and the element type of composeBehaviorChain's behaviors array.

I
BulkheadPolicy

Bulkhead policy consumed by the ResiliencePlugin's bulkhead pattern.

I
CachedProbeOptions

Options for createCachedProbe.

I
CircuitBreakerPolicy

Circuit breaker policy consumed by the ResiliencePlugin's breaker pattern.

  • resetTimeout: number

    Cooldown in milliseconds before an open breaker moves to half-open.

  • threshold: number

    Failures within the timeout window that trip the breaker open.

  • timeout: number

    Rolling failure window in milliseconds; failures older than this (measured by the monotonic clock) are dropped before the threshold check.

I
ClassProvider

Provides a service by constructing a class, injecting the listed tokens as constructor arguments.

I
CookieAttributes

Attributes controlling how a browser stores and returns a cookie.

I
CqrsCommand

A command: a request that mutates state and returns a result.

I
CqrsQuery

A query: a request that returns data without side effects.

I
CqrsRequest

A CQRS request identified by a string type and carrying typed data.

I
CursorPayload

The decoded contents of a cursor minted by encodeCursor: the values of every ordered field (in orderBy order) plus the primary-key column values (for tiebreaker lookups) plus a stable fingerprint of the sort specification. The fingerprint is what a fingerprint mismatch on decode detects.

  • keyValues: ReadonlyArray<CursorValue>

    The primary-key column values (in key-column order), from the row the cursor was minted against. Used by keysetPredicate as the tiebreaker fallback when a key column is absent from orderBy.

  • orderedValues: ReadonlyArray<CursorValue>

    The value of every ordered field (in orderBy declaration order), from the row the cursor was minted against. Index i is the value of the i-th entry of Object.entries(orderBy).

  • sortFingerprint: string

    A stable fingerprint of the resolved sort specification: each ordered field paired with its direction, in order. A cursor minted under one sort and presented under another has a different fingerprint, so the caller is refused by name rather than served a silently wrong page.

I
EncodedPayload

A payload as it travels the backplane.

I
EnvVarSpec

Specification of one environment variable for IEnvironmentApi.validate.

I
Err

A failed result carrying an error.

I
ErrorResponderTarget

The minimal context an error responder needs to write a response: the request-scoped state (where the responder itself is published), the response builder to write to, and the request (for the Problem Details instance).

I
ErrorResponseInit

The initialization of an error response produced through the responder seam.

I
FactoryProvider

Provides a service via a factory function.

I
FlagContext

Evaluation context for targeting rules.

I
FormBody

A parsed form body: the read-only view IRequest.formData?() resolves and parseFormBody returns.

  • entries(): IterableIterator<[string, FormValue]>

    Iterates every [name, value] pair in wire order — the enumeration primitive for reading a form whose field names the reader does not know ahead of time (the hand-rolled new URLSearchParams(body) iteration this accessor replaces).

  • get(name: string): FormValue | undefined

    Returns the FIRST value for a name, or undefined when the name is absent — the web standard's get, with undefined (narrowable) in place of null.

  • getAll(name: string): readonly FormValue[]

    Returns every value for a name in wire order — the web standard's getAll, so a repeated field (multi-select, multi-file) keeps the order the client sent.

I
FormFile

One file part of a form body: a field that declared a filename in its Content-Disposition.

I
GraphqlConnectionInfo

Information about a WebSocket connection used for subscription operations.

I
GraphqlExecutionOutcome

The outcome of a GraphQL execution, carrying an HTTP status code for the transport layer to use.

I
GraphqlExecutionResult

The execution result as specified by the GraphQL spec.

I
GraphqlFormattedError

Formatted GraphQL error as returned to the client.

I
GraphqlOperationContext

Context for a subscription operation, carrying either an HTTP request context or a WebSocket connection info.

I
GraphqlRequestParams

Parameters for a GraphQL execution request.

I
GrpcServiceDefinition

A gRPC service definition that satisfies the plugin's expectations. This is a structural constraint satisfied by generated descriptor objects from @bufbuild/protobuf. It contains only the fields the plugin needs to route requests and build reflection data.

I
HandlerResult

Opaque marker returned by IResponse terminal methods and expected back from route handlers. It exists purely so the type system can verify a handler produced a response; only the kernel creates values of this type.

I
HealthCheckResult

The outcome of one health check.

I
HealthReport

The aggregated health report returned by IHealthService.check().

I
HttpStatusHint

How an error should be answered, as decided by the code that threw it.

  • detail: string

    The caller-facing disclosure, served verbatim — required here, where ErrorResponseInit leaves it optional, because a hint that omitted it would fall back to the Error's own message.

  • status: number

    The HTTP status to answer with. Must be an integer in 400599; a hint outside that range is treated as ABSENT and the error takes the ordinary masked-500 path, because a hint says how an ERROR should be answered and a status the platform cannot serve would make the error handler itself throw.

I
IAdapterTransaction

A transaction handle that can also open entity data sources bound to itself.

I
IApplication

The application: registers plugins, owns the router and middleware pipeline, and manages the server lifecycle.

I
IAuditLogger

Immutable audit trail writer.

I
IAuthorizationService

Authorization service for RBAC with role hierarchy.

I
IAuthService

Authentication service that coordinates strategies and provides credential verification for login flows.

I
IAuthStrategy

Authentication strategy interface. Implementations extract credentials from a request and return a principal, or null if the strategy does not apply.

I
ICacheStore

Key/value cache with per-entry TTL.

I
ICircuitBreaker

Circuit breaker protecting calls to an unreliable dependency.

I
ICliApi

CLI command registration surface: a plugin publishes commands here, and the kernel registers each under CAPABILITIES.CLI_COMMAND as a multi-provider token that any consumer can read with getAll.

I
ICommandHandler

Handles one command type.

I
IConfig

Type-safe configuration access. Values originate from environment variables and .env files, validated at startup.

I
IContainer

Dependency injection container.

I
ICounter

Monotonically increasing counter. observe / inc add a non-negative value.

I
ICqrsFacade

Facade combining command and query buses.

I
IDatabaseAdapter

The full database backend port: lifecycle plus data access.

I
IDecoratorApi

Custom decorator registration surface (active only when the DecoratorPlugin is registered; inert otherwise).

I
IDnsResolver

DNS resolution, abstracted across runtimes.

I
IDomainEvent

A domain event.

I
IEnvironmentApi

Environment validation surface: plugins declare the environment variables they need, and the kernel validates them at startup, failing fast on violations.

I
IErrorResponder

A request-scoped error responder: writes an error response in the application's configured format.

I
IEventBus

In-memory publish/subscribe event bus for domain events.

I
IFeatureFlags

Feature flag evaluator. Evaluation is synchronous against the provider's cached state; providers refresh their state out of band.

I
IFileSystem

Runtime-agnostic file system operations. Absent on runtimes without file system access (edge platforms).

I
IGraphqlService

The GraphQL service contract.

I
IGrpcService

The service contract that applications use to register gRPC/Connect services. Provided by the grpc-plugin under the CAPABILITIES.GRPC token.

I
IHealthApi

Health check registration surface.

I
IHealthIndicator

A named health indicator contributing to /health, /live, and /ready.

I
IHealthService

Health service contract for registering and checking health indicators.

I
IHistogram

Histogram: bucketed observation distribution plus sum and count.

I
IHttpAdapter

HTTP server adapter provided by the runtime plugin. No other plugin may create HTTP servers (AI_GUIDELINES §4.3).

I
IIngressBehavior

Cross-cutting behaviour around one unit of non-HTTP ingress work.

I
IJob

A queued job delivered to a processor.

I
IJwtService

JWT sign/verify service.

I
ILifecycleApi

Lifecycle hook registration surface. Hooks run in registration order within each phase.

I
ILogger

Structured logger. All framework and application logging goes through this interface — never console (AI_GUIDELINES §11.6).

I
IMailer

Email sender.

I
IMessageBroker

Message broker for cross-service integration events.

I
IMetadataStore

Metadata captured by decorators, read by the DecoratorPlugin. Stored in plain maps — no reflection (ARCHITECTURE.md §12). The concrete metadata value shapes are owned by the decorator plugin.

I
IMetric

A registered metric.

I
IMetricsApi

Metric registration surface.

I
IMetricsService

Metrics service resolved via ctx.services.get<IMetricsService>('metrics').

I
IMiddleware

Object form of middleware, for implementations that carry state.

I
IMiddlewareApi

Middleware pipeline registration surface exposed to plugins.

I
IMultiTenancyService

Multi-tenancy service — exposes tenant context, repository creation, and cache-key helpers.

I
IngressContext

Transport-neutral envelope for ONE unit of non-HTTP work.

  • attempt: number

    1-based delivery attempt. Present for 'queue' (from IJob.attempts) and 'scheduler' (from ScheduledJob.attempts); ABSENT for 'messaging' and 'websocket'. Absent means "this ingress cannot tell you" — never "first try": brokers redeliver and none tracks a delivery count, so a fabricated 1 would lie on a fifth redelivery.

  • headers: Readonly<Record<string, string>>

    Transport headers, populated on the 'messaging' arm from MessageMetadata.headers and on the 'queue' arm from IJob.headers. {} means the channel carried none; absent means there was no channel.

  • kind: IngressKind

    Which ingress path produced this work item — the discriminator a behaviour branches on.

  • name: string

    The route the work is addressed by: the queue job name, the scheduler job name, the broker topic, or the WebSocket route path.

  • payload: TPayload

    The native work item: an IJob, a ScheduledJob, the message payload, or the frame data.

I
INotifier

Multi-channel notification dispatcher.

I
IOpenApiApi

OpenAPI contribution surface. Schema values are unknown here; the OpenAPI plugin narrows them (Zod schemas by default).

I
IOrmAdapter

ORM adapter port — what the DatabasePlugin requires from any ORM integration.

I
IPipelineBehavior

Wraps a handler with cross-cutting logic (logging, timing, validation, etc.).

I
IPlugin

The plugin contract. Every framework capability implements this interface (AI_GUIDELINES §3.2).

I
IPluginContext

The registration context handed to IPlugin.register — every extension point a plugin can touch.

I
IPrincipal

The authenticated identity attached to a request by authentication middleware.

I
IQueryHandler

Handles one query type.

I
IRealtimeBackplane

A publish/subscribe transport carrying RealtimeFrames between application instances.

I
IRequest

Runtime-agnostic view of an incoming HTTP request.

I
IRequestContext

Per-request context passed to middleware and route handlers. Each request gets a fresh context; request-scoped data lives here, never in globals.

I
IResilienceService

Resilience service registered under CAPABILITIES.RESILIENCE.

I
IResponse

Runtime-agnostic response builder. Configuration methods (status, header) chain; terminal methods (json, text, send, redirect) produce the HandlerResult a route handler returns.

I
IRouterApi

Router registration surface exposed to plugins and applications.

I
IRuntimeServices

Runtime services — every runtime-specific operation the framework needs, abstracted behind one interface. Registered under CAPABILITIES.RUNTIME by the RuntimePlugin, which is mandatory in every application.

I
ISecretManager

Secret manager backed by a provider (AWS KMS, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, or environment variables in development).

I
IServiceDiscovery

Resolves logical service names to reachable instances, balances across them, and learns from reported call outcomes.

I
IServiceRegistry

Maps capability tokens to service instances.

I
ISession

Per-request session handle.

I
ISessionService

Session service registered under CAPABILITIES.SESSION.

I
ISessionStore

Server-side session storage port.

I
ISpan

A span represents a single operation within a trace.

I
ISseConnection

A live SSE connection backed by a ReadableStream.

I
ISseService

Service contract for the SSE hub — registered by the SsePlugin under CAPABILITIES.SSE.

I
ISsrService

Service contract for server-side rendering (SSR).

I
IStorage

Object storage abstraction.

I
ISubscription

An active subscription.

I
ISummary

Summary: per-quantile observations plus sum and count.

I
ITelemetryService

Telemetry service — the primary API for creating spans.

I
ITenant

A resolved tenant.

I
ITenantRepository

Tenant-scoped repository — delegates CRUD to the data store the multi-tenancy plugin was configured with (ITenantDataStore, declared in that plugin), while threading the resolved tenant id.

I
ITenantResolver

Resolves the tenant for an incoming request (by subdomain, header, path, or JWT claim, depending on the implementation).

I
ITransaction

A database transaction handle.

I
ITransactionIsolationSupport

An adapter's explicit declaration of portable transaction isolation support.

I
IValidationService

Data validation service.

I
IViewEngine

View engine contract — renders a view component and its props to HTML.

I
IWebSocketConnection

A live WebSocket connection, as seen by application code.

I
IWebSocketService

Service contract for the WebSocket hub — registered by the WebSocketPlugin under CAPABILITIES.WEBSOCKET.

I
IWebSocketTransport

The runtime-native socket, normalized to the two operations the framework needs. Implemented by each HTTP adapter's upgrader over its platform socket (Deno.upgradeWebSocket's WebSocket, a ws socket on Node, Bun's ServerWebSocket, the server half of a Workers WebSocketPair).

I
IWorkerHandle

Handle to one spawned worker thread, normalized across web Worker (Deno/Bun) and node:worker_threads (Node).

I
IWorkerHost

Thread-spawning primitive provided by runtimes that support worker threads. Absent on runtimes without them (e.g. Cloudflare Workers) — consumers MUST degrade gracefully when it is not provided (see the WorkerPoolPlugin, which fails run() with a typed error when no host exists).

I
IWorkerPool

A pool of worker threads executing task modules off the event loop.

I
JwtSignOptions

Options accepted when signing a JWT.

I
MailMessage

An outgoing email message.

I
MessageMetadata

Transport metadata accompanying a delivered message.

I
MetricConfig

Configuration for registering a metric.

I
MetricOptions

Ergonomic options for the typed factory methods. type is injected by the method name; help defaults to the metric name.

I
MiddlewareOptions

Options accepted when adding middleware to the pipeline.

  • name: string

    Diagnostic name shown in pipeline introspection.

  • priority: number

    Execution priority — lower numbers run earlier. See ARCHITECTURE.md §10 for the conventional priority bands of first-party middleware.

I
None

An Option holding no value.

I
NormalizedQuery

A repository query with every option resolved to a concrete value — the shape a IDataSource evaluates.

I
NotificationMessage

A notification dispatched across one or more channels.

I
Ok

A successful result carrying a value.

I
PageResult

A single page of rows returned by IDataSource.findPage, plus the cursor that continues to the next page (or null when the page is the last).

I
PickOptions

Per-call overrides for IServiceDiscovery.pick.

I
ProbeTiming

The clock-and-timer surface createCachedProbe runs on, bound to a runtime.

I
ProcessOptions

Options accepted when registering a processor.

I
ProviderOptions

Options accepted when registering a provider.

I
PutObjectOptions

Object attributes accepted alongside the bytes when storing an object.

  • contentType: string

    MIME type recorded on the stored object (e.g. 'image/png'). Omitted leaves the backend's own default, which is application/octet-stream on every provider that supports the field.

  • metadata: Readonly<Record<string, string>>

    Arbitrary user metadata recorded alongside the object. Keys and values are passed through to the backend unmodified; backends impose their own limits on size and on which characters a key may contain.

I
RbacConfig

RBAC configuration for role hierarchy and permissions.

I
RealtimeFrame

One broadcast crossing the backplane.

I
RecurringOptions

Options accepted when scheduling a recurring job.

I
RegisterOptions

Options accepted when registering a service.

  • multi: boolean

    Allow multiple providers for the same token; consumers retrieve them with IServiceRegistry.getAll.

  • override: boolean

    Replace an existing registration. Without this flag, registering an already-registered token throws.

I
RequestOptions

Options accepted by IMessageBroker.request.

  • timeoutMs: number

    Reply wait budget in milliseconds. When no correlated reply arrives within this window, request rejects. Defaults to 5000 when omitted.

I
RetryOptions

Retry configuration for a scheduled job.

I
RetryPolicy

Retry policy consumed by the ResiliencePlugin's retry pattern.

I
RoleDefinition

Role definition for RBAC configuration.

I
RoomBroadcastOptions

Options for a room broadcast.

I
RouteDefinition

Full route definition, used when a route needs middleware or schemas in addition to its handler.

I
RouteInfo

Route information returned by IRouterApi.listRoutes.

I
RouteSchema

Validation/documentation schemas attached to a route. Schema values are intentionally unknown here — the validation plugin narrows them (Zod schemas by default) so common stays dependency-free.

I
RouteSecurityMetadata

What a middleware function enforces, for documentation generators.

  • authenticated: boolean

    true when the middleware requires an authenticated principal; false when it explicitly marks the route public.

I
RouteValidationMetadata

What a validating middleware checks, branded onto the middleware function so a documentation generator can describe the route without importing the plugin that produced it.

I
ScheduledJob

A scheduled job instance handed to the handler.

I
ScheduleOptions

Options passed when scheduling a job.

I
SerializedError

A plain, serializable representation of a thrown value.

I
ServiceInstance

One reachable instance of a service.

I
SignedUrlOptions

Options accepted when creating a signed URL.

I
Some

An Option holding a value.

I
SpanContext

The return type of ISpan.spanContext.

I
SpanOptions

Options for span creation.

I
SplitWorkerEnv

The two halves of a Workers env record.

I
SrvRecord

One DNS SRV record, normalized across runtimes.

I
SseChannel

A named broadcast channel within the SSE hub.

I
SseMessage

A single SSE event payload.

  • data: JsonValue

    Event data. A string is written literally (split on \n into multiple data: lines); any non-string is JSON.stringify-ed. undefined is forbidden — use {} or omit the message instead.

  • event: string

    Event type name — sent as event: field.

  • id: string

    Unique event identifier — sent as id: field; enables Last-Event-ID resume.

  • retry: number

    Reconnection time in milliseconds — sent as retry: field.

I
StartOptions

Options for starting the application server.

I
StatResult

File metadata returned by IFileSystem.stat.

I
SubscribeOptions

Options accepted when subscribing to a topic.

  • queue: string

    Consumer group / queue name for load-balanced delivery.

I
TaskPoolStats

A snapshot of one task-module pool's state, returned by IWorkerPool.stats.

I
TelemetryContext

Opaque handle representing the parent context for span creation.

I
TransactionOptions

Optional controls for opening a transaction.

I
ValidationIssue

A single validation failure.

I
ValueProvider

Provides a pre-built value.

I
WebSocketCloseEvent

Payload of a WebSocket close, normalized across runtimes.

  • code: number

    The RFC 6455 close code (e.g. 1000 normal, 1001 going away).

  • reason: string

    The close reason; an empty string when the peer supplied none.

I
WebSocketConnectionContext

Details of the upgrade request that opened a connection, handed to WebSocketHandlers.onOpen.

  • headers: Headers

    The upgrade request headers — read these to authenticate the peer.

  • path: string

    The URL path component (no query string).

  • protocol: string

    The negotiated subprotocol, when one was selected.

  • query: Readonly<Record<string, string>>

    Query string parameters.

  • url: string

    The full upgrade request URL.

  • user: IPrincipal

    The authenticated principal, when one authenticated the upgrade. Populated by threading ctx.request.user through IWebSocketService.routeUpgrade; omitted when the upgrade was not authenticated. Read this in onOpen to identify the peer rather than re-deriving it from the headers.

I
WebSocketEventSink

The callbacks an HTTP adapter drives once it has completed a handshake. The WebSocket plugin builds one sink per accepted upgrade and hands it to the adapter inside the accept decision; the adapter binds its native socket events to these methods.

I
WebSocketHandlers

The lifecycle callbacks an application supplies per WebSocket route.

I
WebSocketRoom

A named broadcast group of connections — the bidirectional analogue of the SSE plugin's channels.

I
WebSocketRouteOptions

Per-route configuration supplied alongside the handlers.

  • guards: readonly WebSocketUpgradeGuard[]

    Guards evaluated before this route's WebSocket handshake is accepted.

  • heartbeat: boolean

    Whether this route participates in the shared heartbeat sweep.

  • protocols: readonly string[]

    Subprotocols this route accepts. When non-empty, the first client-requested protocol appearing in this list is echoed back and any request whose Sec-WebSocket-Protocol matches none of them is rejected with 400. When omitted, no protocol is negotiated and none is echoed.

I
WebSocketUpgradeIntent

The WebSocket upgrade intent the kernel terminal handler brands onto an IRequest under UPGRADE_INTENT, for the HTTP adapter to act on once the middleware pipeline has run without short-circuiting.

I
WorkerErrorShape

Serialized shape of an error crossing the thread boundary in a WorkerTaskReply.

I
WorkerReadySignal

Posted once by the worker side (defineWorkerTask) after its message handler is wired; the pool dispatches tasks only to ready workers.

I
WorkerRunOptions

Options for one IWorkerPool.run call.

  • timeoutMs: number

    Per-call task timeout in milliseconds, overriding the pool's configured timeout. 0 disables the timeout for this call.

I
WorkerTaskReply

A task outcome posted by the worker back to the pool.

I
WorkerTaskRequest

A task dispatch posted by the pool to a worker.

I
WrapOptions

Options selecting which resilience patterns wrap a protected call.

Type Aliases

T
AuthorizationFailure =
"authentication-required"
| "not-configured"
| "insufficient-privileges"

The authorization condition that determines a standard refusal response.

T
BackoffStrategy = "fixed" | "exponential"

Backoff strategy applied to a RetryPolicy's base delay.

T
CapabilityToken = string

A capability token: a lowercase kebab-case string that identifies a capability, not a concrete type.

T
Component<P> = (props: P) => unknown

A view component: a pure function from a props bag to something the engine can render to a string — a JSX node (@hono/hono/jsx), an HtmlEscapedString (the html tagged template), or a plain string (a by-name template adapted per §3.6 of the M92 plan).

T
CursorValue = string | number | Date

A scalar value retained by a portable keyset cursor.

T
DecoratorHandler = (
metadata: Readonly<Record<string, unknown>>,
target: object,
propertyKey?: string
) => void

Handler invoked when a custom decorator is applied; receives the metadata the decorator captured.

T
EntityKey = string | number | Readonly<Record<string, string | number>>

A primary key value: a scalar string, a scalar number, or a composite key expressed as a readonly record of named columns to values.

T
FilterOperator = "eq" | "contains" | "gt" | "gte" | "lt" | "lte" | "in"

Operators supported by a portable repository filter comparison.

T
FormEncoding = "urlencoded" | "multipart"

The two request encodings a form body can carry.

T
FormValue = string | FormFile

One form value: a plain field string, or a FormFile.

T
GrpcServingStatus = "unknown" | "serving" | "not-serving" | "service-unknown"

The serving status returned by the health bridge. These values map onto the gRPC v1 Health response enum.

T
HardenedCall<T> = (signal?: AbortSignal) => Promise<T>

The hardened callable returned by IResilienceService.wrap.

T
HealthIndicatorFn = () => Promise<HealthCheckResult>

Function form of a health indicator.

T
HealthStatus = "up" | "down" | "degraded"

Health state reported by a health indicator.

T
IngressKind = "queue" | "scheduler" | "messaging" | "websocket"

The ingress path a unit of non-HTTP work arrived on.

T
LoadBalanceStrategy = "round-robin" | "random" | "weighted-random"

How IServiceDiscovery.pick chooses among healthy instances.

T
LogLevel = "fatal" | "error" | "warn" | "info" | "debug" | "trace"

Log severity levels, ordered from most to least severe.

T
LogMetadata = Readonly<Record<string, unknown>>

Structured metadata attached to a log entry.

T
MetricType = "counter" | "gauge" | "histogram" | "summary"

Metric instrument kinds supported by the metrics capability.

T
MiddlewareFunction = (
ctx: IRequestContext,
next: NextFunction
) => void | HandlerResult | Promise<void | HandlerResult>

A middleware function: pre-process, call next(), post-process. May short-circuit by returning a response without calling next().

T
NextFunction = () => Promise<void>

Continues the middleware pipeline. Not calling it short-circuits the pipeline (the caller must have produced a response).

T
Option<T> = Some<T> | None

An optional value: either Some or None. Narrow with the present discriminant or the isSome/isNone guards.

T
OrderDirection = "asc" | "desc"

Sort direction for a single field.

T
PathPattern = string | RegExp

One exclusion entry: an exact path, or a pattern tested against the path.

T
PluginPriority = (PLUGIN_PRIORITY)[keyof PLUGIN_PRIORITY]

Union of the well-known priority values in PLUGIN_PRIORITY.

T
Provider<T> = ClassProvider<T> | FactoryProvider<T> | ValueProvider<T>

Any provider form accepted by IContainer.register.

T
RealtimeFrameHandler = (frame: RealtimeFrame) => void

Receives frames published by other instances.

T
RealtimeFrameKind = "ws-room" | "sse-channel"

Which kind of broadcast group a RealtimeFrame addresses.

T
RegistryFactory<T> = (services: IServiceRegistry) => T

A factory that constructs a registry entry from the service registry.

T
RequestHandler<TReq = unknown, TRes = unknown> = (
message: TReq,
metadata: MessageMetadata
) => TRes | Promise<TRes>

Responder for a request topic. Its resolved value is sent back to the caller as the reply, correlated to the originating request.

T
ResilientCall<T> = (signal: AbortSignal) => Promise<T>

A call protected by the resilience patterns.

T
ResponseSnapshotInit = { readonly headers: HeadersInit; }

Native-response initialization data attached to a snapshot by the kernel when its headers have not needed a mutable Headers instance.

T
Result<T, E = Error> = Ok<T> | Err<E>

The result of an operation that can fail: either Ok or Err. Narrow with the success discriminant or the isOk/isErr guards.

T
RouteHandler = (ctx: IRequestContext) => HandlerResult | Promise<HandlerResult>

A route handler: receives the request context and returns a response via the context's response builder.

T
RpcFetchHandler = (request: Request) => Promise<Response | null>

A fetch handler that attempts to handle a gRPC/Connect request. Returns a Response if the request was handled as RPC, otherwise returns null so the adapter falls through to normal Hono handling.

T
RuntimePlatform = "node" | "deno" | "bun" | "cloudflare-workers"

JavaScript runtimes the framework can execute on.

T
RuntimeSignal = "SIGTERM" | "SIGINT"

A process-termination signal an application can shut down gracefully on.

T
SchedulerBackoff = "fixed" | "exponential"

Backoff strategy for retry delays.

T
SecurityRequirement = Readonly<Record<string, readonly string[]>>

A single OpenAPI security requirement: a map of security-scheme name to the scopes that scheme must grant. Scopes are meaningful only for OAuth2 and OpenID Connect schemes; every other scheme type takes an empty array.

T
ServerHandle = unknown

Opaque handle for a running HTTP server, created and consumed only by the runtime's HTTP adapter.

T
ServiceFactory<T> = () => T

A factory invoked lazily on the first lookup of a token registered with IServiceRegistry.registerFactory.

T
ServiceOutcome = "success" | "failure"

How a call to an instance went, as reported by the caller.

T
SessionData = Record<string, unknown>

Arbitrary serializable session payload.

T
SessionView = { readonly id: string; readonly data: Readonly<SessionData>; }

A read-only projection of a session: its identifier and payload, with no mutation surface.

T
SpanAttributeValue =
string
| number
| boolean
| ReadonlyArray<string | number | boolean>

Attribute value — a span attribute can be a primitive or an array of primitives.

T
SpanKind = "internal" | "server" | "client" | "producer" | "consumer"

The kind of span. Maps to OTel SpanKind at the implementation boundary.

T
SpanStatus = "ok" | "error" | "unset"

Span status — whether the span completed successfully or not.

T
StandardCapability = (CAPABILITIES)[keyof CAPABILITIES]

Union of all standard capability token values.

T
TimerHandle = unknown

Opaque handle returned by runtime timer methods. Its concrete shape is runtime-specific (a number on Deno, an object on Node); consumers only ever pass it back to clearTimeout/clearInterval.

T
Unsubscribe = () => void

Removes a subscription when called.

T
ValidationTarget = "body" | "query" | "params" | "headers" | "cookies"

The request part a validation middleware targets.

T
WebSocketGuardDecision = true | { readonly status: number; }

The result of a route-scoped WebSocket upgrade guard.

T
WebSocketReadyState = "connecting" | "open" | "closing" | "closed"

Lifecycle state of a WebSocket, normalized across runtimes to names rather than the numeric codes the web API uses.

T
WebSocketUpgradeRouter = (request: Request) => Promise<WebSocketUpgradeDecision | null>

Consulted by an HTTP adapter for every inbound WebSocket upgrade request.

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

v
CLIENT_IP_STATE_KEY: "http-security-plugin:client-ip"

The ctx.state key under which http-security-plugin's ipSecurityMiddleware publishes the resolved client IP, and from which auth-plugin's rateLimitMiddleware reads it back.

v
ERROR_RESPONDER_BRAND: unique symbol

The brand under which an errorHandler middleware function carries its resolved IErrorResponder.

v
ERROR_RESPONDER_STATE_KEY: "exceptions:error-responder"

The ctx.state key under which an application's resolved error responder is published.

v
HTTP_STATUS_HINT: unique symbol

Key under which an Error carries its HttpStatusHint.

v
PLUGIN_PRIORITY: { HIGHEST: number; HIGH: number; NORMAL: number; OPENAPI: number; LOW: number; LOWEST: number; }

Well-known plugin registration priorities. Lower numbers register first.

v
SECURITY_METADATA: unique symbol

Key under which a MiddlewareFunction carries its RouteSecurityMetadata.

v
TELEMETRY_CONTEXT_OPAQUE: unique symbol

Opaque marker symbol for TelemetryContext.

v
TRACEPARENT_HEADER: "traceparent"

The W3C header carrying a trace parent. @since 0.2.0

v
TRACESTATE_HEADER: "tracestate"

The W3C header carrying vendor trace state. @since 0.2.0

v
UPGRADE_INTENT: unique symbol

Key under which the kernel terminal handler brands an IRequest with a WebSocket upgrade intent.

v
VALIDATION_METADATA: unique symbol

Key under which a MiddlewareFunction carries its RouteValidationMetadata.

config-plugin/src/index.ts

Functions

f
loadConfig(
runtime: IRuntimeServices,
options?: ConfigPluginOptions
): Promise<IConfig>

Builds an immutable configuration snapshot from the environment.

Interfaces

I
ConfigPluginOptions

Options for ConfigPlugin and loadConfig.

  • envFileOptional: boolean

    When true, a path in ConfigPluginOptions.envFilePath that does not exist is skipped instead of throwing. Defaults to false, which is the behaviour released in 0.1.0.

  • envFilePath: string | readonly string[]

    Path or paths to .env files to load. Defaults to no file loading. When supplied, the runtime must provide fs (absent on edge platforms).

  • expandVariables: boolean

    When true (default), expand ${NAME} references in values. Set to false to disable variable expansion.

  • instance: IConfig

    An already-loaded configuration snapshot to use verbatim.

  • validationSchema: StructuralSchema<unknown>

    A structural schema (e.g., a Zod schema) for validating configuration at startup. When provided, the schema's parse() is called once after merging and expansion, and the parsed output is stored as the configuration snapshot. This preserves Zod coercions and defaults.

I
StructuralSchema

Minimal structural schema interface compatible with Zod's parse(unknown) API. Consumers supply a Zod schema without config-plugin depending on Zod.

cqrs-plugin/src/index.ts

Examples

Example 1

import { CqrsPlugin } from '@setu-ts/cqrs-plugin';

app.register(CqrsPlugin({ behaviors: [timingBehavior] }));

Classes

c
HandlerNotFoundError(requestType: string)

Thrown by CommandBus.execute and QueryBus.execute when no handler is registered for the request's type.

Functions

Interfaces

I
CommandHandlerRegistration

One command handler and the command type the bus routes to it.

I
CqrsCommand

A command: a request that mutates state and returns a result.

I
CqrsPluginOptions

Options for CqrsPlugin.

I
CqrsQuery

A query: a request that returns data without side effects.

I
CqrsRequest

A CQRS request identified by a string type and carrying typed data.

I
ICommandHandler

Handles one command type.

I
ICqrsFacade

Facade combining command and query buses.

I
IPipelineBehavior

Wraps a handler with cross-cutting logic (logging, timing, validation, etc.).

I
IQueryHandler

Handles one query type.

I
QueryHandlerRegistration

One query handler and the query type the bus routes to it.

database-plugin/src/index.ts

Classes

c
BaseRepository<Entity, Id extends EntityKey = string>(_dataSource: DataSource)

Shared repository implementation that normalizes options and delegates data operations to a DataSource.

c
BigtableAdapter(
options: BigtableAdapterOptions,
loader?: BigtableClientLoader
)

The Bigtable adapter.

c
BigtableTransactionScopeError(message: string)

Thrown when a Bigtable transaction is asked to write a second row.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
CosmosAdapter(options: CosmosAdapterOptions)

The Cosmos adapter — an Azure Cosmos DB NoSQL-API backend.

c
CosmosConcurrentModificationError(message: string)

Thrown when a Cosmos update loses an optimistic-concurrency race.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
CosmosTransactionScopeError(message: string)

Thrown when a Cosmos transaction is asked to do something a transactional batch cannot express.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
DatabaseUnavailableError(
message: string,
options?: { cause?: unknown; }
)

Thrown when the database, its connection pool, or its network is temporarily unreachable (X35-2, M90f). The operation did not happen and may be retried.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
DynamoAdapter(options: DynamoAdapterOptions)

The DynamoDB adapter — a key-value store backend served through the portable data-access contract.

c
MemoryAdapter

In-memory implementation of IDatabaseAdapter.

c
MongoAdapter(options: MongoAdapterOptions)

The Mongo adapter — a document-store backend over the native driver.

c
MongoTransactionUnavailableError(
message: string,
options?: ErrorOptions
)

Thrown by MongoAdapter.beginTransaction on a deployment without a replica set.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
SerializationConflictError(
message: string,
options?: { cause?: unknown; }
)

Thrown when the database rejected a write because a concurrent transaction changed the same data (X38-1, M90f). The operation did not happen and may be retried.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
UnitOfWork(
_transaction: ITransaction,
_repoFactory: (entity: string) => IRepository<unknown>,
_adapterType?: DatabaseAdapterType
)

Concrete Unit of Work that holds a transaction and delegates repository creation to the database service within the transaction boundary.

c
UnsupportedFilterOperatorError(
operator: string,
connector: string | undefined,
message: string
)

Thrown at translation time when a filter operator cannot be honoured by the active backend with the connector in use.

  • connector: string | undefined

    The connector the operator failed on, or undefined when the connector could not be determined. 'sqlite' names the concrete refusal; undefined means the adapter could not identify its connector and the provider option is the fix.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

  • operator: string

    The filter operator that could not be translated (e.g. 'contains').

c
UnsupportedIsolationLevelError(
adapter: string,
level: string
)

Thrown when a database adapter cannot honour a requested transaction isolation level.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
UnsupportedMigrationError(message: string)

Thrown by IDatabaseService.migrate because programmatic migrations are not implemented by the current adapters.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
UnsupportedQueryFeatureError(
feature: string,
adapter: string,
message: string,
options?: ErrorOptions
)

Thrown when an adapter refuses a query feature that is expressible in the portable IDataSource contract but not supported by the active backend.

  • adapter: string

    The adapter name (e.g. 'prisma', 'drizzle', 'memory').

  • feature: string

    The query feature that could not be honoured (e.g. 'composite-key').

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
UnsupportedRawQueryError(
adapter: string,
message: string
)

Thrown by MongoAdapter.rawQuery — MongoDB has no SQL, so a raw query is refused by name rather than emulated (the silent-divergence defect M70j closed). The error names the adapter and points at the injected client for native commands.

  • adapter: string

    The adapter name that refused the raw query (e.g. 'mongodb').

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

Functions

f
createInjectedDynamoLoader(client: IDynamoClient): DynamoClientLoader

Creates the no-import arm of the DynamoDB client seam.

f
decodeCursor(token: string): CursorPayload | null

Decode a cursor token to its CursorPayload, or null when the token is malformed.

f
encodeCursor(payload: CursorPayload): string

Encode a CursorPayload as a base64url-encoded JSON token.

f
withIsolationSupport<TDatabase extends object>(bridge: DrizzleTransactionBridge<TDatabase>): DrizzleTransactionBridge<TDatabase>

Declares that an application-owned Drizzle bridge forwards transaction options to its driver.

Interfaces

I
BigtableAdapterOptionsBase

The options both BigtableAdapterOptions arms share.

  • instance: string

    The Bigtable instance the tables live in. Required on both arms: a table is addressed as project/instance/table, and neither an injected client nor a project id encodes the instance.

  • maxPageFetches: number

    How many server round trips one findPage may take before it returns a bounded — but explicitly non-terminal — page. Defaults to 10.

  • tables: Readonly<Record<string, BigtableEntityMapping>>

    Per-entity table, row-key, column and value-encoding overrides, keyed by the entity name passed to getRepository().

I
BigtableCell

One stored cell: the raw value bytes, as text.

  • value: string

    The cell value, as the text the adapter's value codec wrote.

I
BigtableClientConfiguration

Client construction settings consumed by the lazy SDK arm.

I
BigtableClientLoader

The deferred client-resolution seam the adapter lifecycle drives.

I
BigtableDatabaseOptions

The 'bigtable' arm — a Google Cloud Bigtable wide-column backend.

I
BigtableEntityMapping

How one entity name maps onto a physical Bigtable table.

I
BigtableReadOptions

What a read asks the server for.

I
BigtableReadRow

One row as a read returns it.

I
BigtableRowBoundary

One end of a row-key range.

I
BigtableRowKeyMapping

How an entity's logical fields compose its single row key.

  • fields: readonly string[]

    The logical fields the row key is composed from, in order. The order is load-bearing: it is both the byte order the key sorts in and the order the portable cursor carries key values in.

  • prefix: string

    A constant prefix prepended to every row key of this entity.

  • separator: string

    The separator joining the fields. Defaults to '#'. Ignored for a single-field key, which is the field's own string form.

I
BigtableRowRange

A row-key range. An omitted end is unbounded in that direction.

I
BigtableValueRange

An exact byte range a cell value must fall in.

I
CosmosAccessCondition

One access condition — the optimistic-concurrency guard the replace path uses.

I
CosmosAdapterOptionsBase

The options both CosmosAdapterOptions arms share — everything that is required or optional regardless of how the client is supplied.

I
CosmosBatchDeleteOperation

A batch operation removing one document.

I
CosmosBatchInsertOperation

A batch operation inserting a whole document. The id is optional: the service mints one when the body carries none.

I
CosmosBatchPatchOperation

A batch operation carrying patch operations rather than a whole document.

I
CosmosBatchReplaceOperation

A batch operation overwriting a whole document, which therefore names the document it replaces.

I
CosmosBatchResponse

The response a transactional batch answers with.

I
CosmosContainerDefinition

The container definition the partition-key resolver reads.

I
CosmosDatabaseOptions

The arm selecting the Cosmos adapter over the @azure/cosmos SDK — Azure Cosmos DB's NoSQL (SQL) API.

I
CosmosEntityMapping

How one entity name maps onto a physical Cosmos container.

I
CosmosFeedResponse

A materialized query response.

I
CosmosItemResponse

The response envelope every single-item operation answers with.

I
CosmosPatchOperation

One JSON-patch-shaped operation. The adapter only emits set, and only for top-level fields, so the "cannot create a path whose parent is absent" limitation measured on the SDK is unreachable through it.

I
CosmosQueryParameter

One named query parameter. Values are always bound rather than interpolated, so a value can never be read as SQL.

I
CosmosQuerySpec

A parameterized Cosmos SQL query — the shape items.query accepts.

I
CosmosRequestOptions

Per-request options the adapter passes to a single-item operation.

I
CountOptions

Options for IRepository.count.

I
CursorPayload

The decoded contents of a cursor minted by encodeCursor: the values of every ordered field (in orderBy order) plus the primary-key column values (for tiebreaker lookups) plus a stable fingerprint of the sort specification. The fingerprint is what a fingerprint mismatch on decode detects.

  • keyValues: ReadonlyArray<CursorValue>

    The primary-key column values (in key-column order), from the row the cursor was minted against. Used by keysetPredicate as the tiebreaker fallback when a key column is absent from orderBy.

  • orderedValues: ReadonlyArray<CursorValue>

    The value of every ordered field (in orderBy declaration order), from the row the cursor was minted against. Index i is the value of the i-th entry of Object.entries(orderBy).

  • sortFingerprint: string

    A stable fingerprint of the resolved sort specification: each ordered field paired with its direction, in order. A cursor minted under one sort and presented under another has a different fingerprint, so the caller is refused by name rather than served a silently wrong page.

I
CustomDatabaseOptions

The arm supplying an externally-implemented backend.

  • adapter: IDatabaseAdapter

    The backend to use, already constructed. The plugin calls connect() on it during register() and disconnect() during shutdown; it never constructs or replaces it.

  • type: "custom"

    Selects the external-adapter arm.

I
DatabaseAdapterOptions

Adapter-specific configuration passed to the database adapter.

  • drizzleInstance: DrizzleDatabaseIdentity

    Inject the application's opaque configured Drizzle database, created by createDrizzleDatabase(database, transactionBridge). Required when type: 'drizzle' — see DrizzleAdapterOptions, which makes that a compile error rather than a startup throw. The explicit bridge positively guarantees Promise-aware native callback semantics instead of inferring them from a structural transaction method.

  • drizzleTables: Record<string, unknown>

    Registry mapping entity name → a real Drizzle table definition. Required when type: 'drizzle' — see DrizzleAdapterOptions, which makes that a compile error rather than a startup throw.

  • logQueries: boolean

    When true, log SQL queries to the registered logger.

  • prismaClient: unknown

    Inject an application-generated Prisma v7 client. This is required for the Prisma adapter because generated-client output belongs to the application rather than this package — see PrismaAdapterOptions, which makes that a compile error rather than a startup throw.

  • provider: PrismaSqlProvider

    The SQL connector the injected Prisma client is bound to.

  • transactionTimeout: number

    Timeout (ms) for Prisma interactive transactions. Defaults to 30_000. Prisma's default is ~5s which is too short for a full Unit of Work.

  • url: string

    Database connection URL (e.g., postgresql://localhost:5432/mydb).

I
DatabaseConnectionOptions

The options every DatabasePluginOptions arm shares.

I
DatabasePoolCapacity

A point-in-time reading of the database driver's connection-pool counters (M90b).

I
DrizzleAdapterOptions

DatabaseAdapterOptions narrowed for the Drizzle arm: the configured instance and the table registry are both required.

  • dialect: SqlJsonDialect

    The SQL dialect, used only to translate a nested JSON filter path (field: ['profile', 'city']). No two dialects spell JSON extraction alike: PostgreSQL uses #>>, MySQL JSON_UNQUOTE(JSON_EXTRACT(...)) and SQLite json_extract.

  • drizzleInstance: DrizzleDatabaseIdentity

    The opaque configuration returned by createDrizzleDatabase(database, transactionBridge). Required.

  • drizzleTables: Record<string, unknown>

    Entity name → real Drizzle table definition. Required, and must hold at least one entry.

  • entities: Readonly<Record<string, DrizzleCompositeKeyOptions>>

    Per-entity overrides keyed by the entity name passed to IRepository.getRepository.

  • poolStats: () => DatabasePoolCapacity

    Application-owned callback reporting the driver's connection-pool counters (M90b). The application reads its own driver's documented pool API — the configured Drizzle identity is opaque to this package — and the adapter publishes the returned DatabasePoolCapacity snapshot to the database health indicator through an internal seam.

I
DrizzleCompositeKeyOptions

Per-entity overrides for the Drizzle adapter.

I
DrizzleDatabase

Opaque configuration for one exact Drizzle database and async transaction bridge.

I
DrizzleDatabaseIdentity

Erased identity of a package-created Drizzle configuration.

I
DrizzleDatabaseOptions

The arm selecting the Drizzle adapter.

I
DynamoAdapterOptionsBase

The options both DynamoAdapterOptions arms share — everything that is optional regardless of how the client is supplied.

I
DynamoAttributeValue

A DynamoDB attribute value in the subset the adapter reads and writes.

I
DynamoClientConfiguration

AWS client construction settings consumed by the lazy SDK arm.

I
DynamoClientLoader

The deferred client-resolution seam used by the adapter lifecycle.

I
DynamoConditionExpression

A conditional expression used to prevent an unintended write.

I
DynamoDatabaseOptions

The arm selecting the DynamoDB adapter over the AWS SDK v3 client.

I
DynamoDeleteItemCommandInput

Input for DynamoDB DeleteItem.

I
DynamoDeleteItemCommandOutput

Output from DynamoDB DeleteItem.

I
DynamoEntityMapping

How one entity name maps onto a physical DynamoDB table.

I
DynamoExpressionAttributes

Expression aliases shared by all command shapes.

I
DynamoGetItemCommandInput

Input for DynamoDB GetItem.

I
DynamoGetItemCommandOutput

Output from DynamoDB GetItem.

I
DynamoIndexMapping

A configured global secondary index and its key schema.

I
DynamoPutItemCommandInput

Input for DynamoDB PutItem.

I
DynamoPutItemCommandOutput

Output from DynamoDB PutItem.

I
DynamoQueryCommandInput

Input for DynamoDB Query.

I
DynamoReadCommandInput

Shared fields for a DynamoDB query or scan.

I
DynamoReadCommandOutput

The common DynamoDB Query and Scan response shape.

I
DynamoSdkClient

The native DynamoDB SDK client operations driven by the facade.

I
DynamoSdkCommand

A native DynamoDB SDK command accepted by DynamoSdkClient.

I
DynamoTransactDelete

A transactional Delete operation.

I
DynamoTransactPut

A transactional Put operation.

I
DynamoTransactUpdate

A transactional Update operation.

I
DynamoTransactWriteItem

One transaction operation accepted by DynamoDB TransactWriteItems.

I
DynamoTransactWriteItemsCommandInput

Input for DynamoDB TransactWriteItems.

I
DynamoUpdateItemCommandInput

Input for DynamoDB UpdateItem.

I
DynamoUpdateItemCommandOutput

Output from DynamoDB UpdateItem.

I
FindOptions

Options for IRepository.findAll.

I
IAdapterTransaction

A transaction handle that can also open entity data sources bound to itself.

I
IBigtableClient

The Bigtable client the adapter drives.

I
IBigtableInstance

One Bigtable instance.

I
IBigtableTable

One table's data-plane surface.

I
ICosmosClient

A structural subset of the SDK CosmosClient — the members the adapter drives.

I
ICosmosContainer

A structural subset of the SDK Container — the members the adapter drives.

I
ICosmosDatabase

A structural subset of the SDK Database.

I
ICosmosItem

A structural subset of the SDK Item handle — one document addressed by its id and partition key.

I
ICosmosItems

A structural subset of the SDK Items collection — the members the data source drives.

I
ICosmosQueryIterator

A query iterator, narrowed to the one member the adapter uses.

I
IDatabaseAdapter

The full database backend port: lifecycle plus data access.

I
IDatabaseService

High-level database service combining repository access, unit of work, raw queries, and lifecycle management.

I
IMongoClient

A structural subset of the driver MongoClient — the members the adapter drives.

I
IMongoCollectionFindOneAndUpdateOptions

The native driver findOneAndUpdate options the adapter passes through.

I
IMongoCursor

A structural subset of the driver's cursor returned from find().

I
IMongoDatabase

A structural subset of the driver Database — what the collection resolver reads.

I
IMongoObjectId

A structural subset of the driver ObjectId — enough for the conversion rules the mapping owns.

I
IMongoObjectIdCtor

The driver ObjectId constructor shape.

I
IMongoSession

A structural subset of the driver ClientSession — the members the transaction path calls.

I
IRepository

Generic repository providing CRUD operations over an entity type.

I
IUnitOfWork

Unit of Work: transaction-scoped repository access.

I
MemoryDatabaseOptions

The arm selecting the zero-dependency in-memory adapter, which is also what an omitted type means.

I
MongoAdapterOptionsBase

The options both MongoAdapterOptions arms share — everything that is optional regardless of how the client is supplied.

I
MongoDatabaseOptions

The arm selecting the Mongo adapter over the native mongodb driver.

I
MongoEntityMapping

How one entity name maps onto a physical Mongo collection.

I
MongoOptions

Operation options the data source passes to every driver call — the session a transaction-scoped data source binds to.

I
NormalizedQuery

A repository query with every option resolved to a concrete value — the shape a IDataSource evaluates.

I
Page

A single page of entities returned by IRepository.findPage, plus the cursor that continues to the next page (or null when the page is the last).

I
PageResult

A single page of rows returned by IDataSource.findPage, plus the cursor that continues to the next page (or null when the page is the last).

I
PrismaAdapterOptions

DatabaseAdapterOptions narrowed for the Prisma arm: the injected client is required.

I
PrismaCompositeKeyOptions

Per-entity overrides for the Prisma adapter.

I
PrismaDatabaseOptions

The arm selecting the Prisma adapter.

I
TransactionOptions

Optional controls for opening a transaction.

Type Aliases

T
BigtableValueEncoding = "tagged" | "raw"

How a value round-trips through a cell.

T
CosmosPartitionKeyValue =
string
| number
| boolean
| null
| readonly (string | number | boolean | null)[]

A partition-key value as Cosmos accepts it: a JSON scalar, or an array of them for a hierarchical (MultiHash) partition key.

T
CursorValue = string | number | Date

A scalar value retained by a portable keyset cursor.

T
DynamoDateEncoding = "iso" | "epochMs"

The storage encoding a date-bearing attribute is declared to use.

T
DynamoTransactWriteItemsCommandOutput = Record<never, never>

Output from DynamoDB TransactWriteItems.

T
EntityKey = string | number | Readonly<Record<string, string | number>>

A primary key value: a scalar string, a scalar number, or a composite key expressed as a readonly record of named columns to values.

T
FilterOperator = "eq" | "contains" | "gt" | "gte" | "lt" | "lte" | "in"

Operators supported by a portable repository filter comparison.

T
MongoWriteOptions = MongoOptions

Write-path operation options the data source passes to the driver.

T
OrderDirection = "asc" | "desc"

Sort direction for a single field.

T
PageOptions = FindOptions

Options for IRepository.findPage — the parameter shape.

T
SqlJsonDialect = "postgresql" | "mysql" | "sqlite"

The SQL dialects whose JSON extraction syntax this module can emit.

T
DataSource = IDataSource

The data-access seam adapter-specific implementations provide, keeping BaseRepository decoupled from concrete ORM clients.

decorator-plugin/src/index.ts

Classes

c
MetadataStore

Concrete IMetadataStore. Decorators call the merge*/add* methods; the DecoratorPlugin and other consumers read the readonly controllers, services, and routes maps.

Functions

f
ApiOperation(config: ApiOperationConfig): SetuMethodDecorator

Describes the OpenAPI operation for a route handler.

f
ApiResponse(config: ApiResponseConfig): SetuMethodDecorator

Documents a response status for a route handler. May be applied multiple times to describe several responses.

f
ApiTags(...tags: string[]): SetuClassDecorator

Assigns OpenAPI tags to a controller. Tags are inherited by every route in the controller and merged with any method-level tags.

f
Body<T = unknown>(): ParamSource<T>

Binds the parsed JSON request body.

f
clearParameterResolvers(): void

Removes a registered custom parameter resolver (intended for tests).

f
Controller(path: string): SetuClassDecorator

Marks a class as a controller and assigns a base path prefix for all its routes.

f
createDecorator(
name: string,
metadata: Readonly<Record<string, unknown>>
): SetuClassOrMethodDecorator

Creates a custom class or method decorator that stores metadata readable by the DecoratorPlugin and custom decorator handlers.

f
Ctx(): ParamSource<IRequestContext>

Binds the active request context — for a handler that sets its own status code, adds a header, or returns a streaming response.

f
CurrentUser<T = unknown>(): ParamSource<T>

Binds the authenticated principal (ctx.request.user).

f
getParameterResolver(name: string): CustomParameterResolver | undefined

Returns the resolver registered for a custom parameter type, if any.

f
Inject(...tokens: readonly InjectToken[]): SetuClassDecorator

Declares the constructor injection tokens for a class, one per constructor argument in argument order. The DecoratorPlugin resolves each token (from the DI container or the service registry) and passes the results to the constructor.

f
Injectable(options?: InjectableOptions): SetuClassDecorator

Marks a class as injectable (eligible for DI container registration). When the DecoratorPlugin runs, injectable classes in its services list (or discovered) are registered with the DI container when present, or instantiated directly otherwise.

f
Module(options: ModuleOptions): SetuClassDecorator

Groups controllers and providers under one class.

f
Optional(token: string): OptionalToken

Marks a constructor dependency as optional: when the token has no provider, the argument receives undefined instead of failing construction.

f
parseCookies(headers: Headers): Record<string, string>

Parses cookies from a Cookie request header into a name→value record.

f
Permissions(...permissions: string[]): SetuClassOrMethodDecorator

Requires the authenticated principal to hold any of the given permissions. May be applied at the class or method level (method overrides class).

f
Public(): SetuMethodDecorator

Marks an unrestricted route as public in the OpenAPI document: its schema carries security: [], so a document-level security requirement does not apply to it.

f
registerParameterResolver(
name: string,
resolver: CustomParameterResolver
): void

Registers a resolver for a custom parameter type created with a Custom(name) source. current-user resolves directly; Ctx() uses an internal marker and also resolves directly. Application custom parameter types, including one named context, use this registry.

f
Render<P>(component: Component<P>): RenderDecorator<P>

A handler may also return a HandlerResult from ctx.response — a redirect, most usefully — instead of the props bag. That is what makes POST-redirect-GET expressible on a rendered route: a form handler returns the props to re-render itself with errors, or ctx.response.redirect(...) once the submission is accepted. HandlerResult is branded (__handlerResult: true), so widening the union costs nothing: a props bag of the wrong shape is still a compile error.

f
resolveParameter(
ctx: IRequestContext,
param: ParameterMetadata
): unknown | Promise<unknown>

Resolves a single parameter value from the request context. The result may be a promise (for body and custom resolvers); callers should await it.

f
resolveParameters(
ctx: IRequestContext,
params: readonly ParameterMetadata[]
): Promise<unknown[]>

Resolves an ordered argument array for a handler from its parameter metadata. Arguments are placed by parameter index, so undecorated parameters receive undefined.

f
Roles(...roles: string[]): SetuClassOrMethodDecorator

Requires the authenticated principal to hold any of the given roles. May be applied at the class level (default for all routes) or method level (overrides the class default).

f
UseFilters(...middlewares: MiddlewareLike[]): SetuClassOrMethodDecorator

Attaches error filters to a controller or route. Filters run last in the route middleware chain.

f
UseGuards(...middlewares: MiddlewareLike[]): SetuClassOrMethodDecorator

Attaches guards to a controller or route. Guards run before the handler and may short-circuit by responding without calling next().

f
UseInterceptors(...middlewares: MiddlewareLike[]): SetuClassOrMethodDecorator

Attaches interceptors to a controller or route. Interceptors wrap the handler invocation (pre- and post-processing via next()).

f
ValidateBody(schema: unknown): SetuMethodDecorator

Attaches a request body schema to the decorated route handler.

f
ValidateParams(schema: unknown): SetuMethodDecorator

Attaches a path parameter schema to the decorated route handler.

f
ValidateQuery(schema: unknown): SetuMethodDecorator

Attaches a query parameter schema to the decorated route handler.

f
Version(version: string): SetuClassDecorator

Assigns an API version prefix to a controller. Combined with @Controller, the effective path is version + basePath + routePath (e.g. '/v1/users').

Interfaces

I
ApiOperationConfig

Configuration for ApiOperation.

I
ApiResponseConfig

Configuration for ApiResponse.

I
DecoratorPluginOptions

Options for DecoratorPlugin.

  • autoDiscover: boolean

    When true, auto-scan controllersPath for decorated classes. Discovery failures are logged as warnings and never crash the application.

  • controllers: readonly Constructor[]

    Explicit list of controller classes to register.

  • controllersPath: string

    Glob path for controller discovery (used when autoDiscover is true).

  • enforceRoles: boolean

    When true (the default), a route decorated with @Roles / @Permissions gets enforcing authorization middleware appended to its chain — after the route's guards and filters, before any validation middleware. The middleware resolves CAPABILITIES.AUTHORIZATION per request: with a provider registered it answers 401/403 exactly like the equivalent @UseGuards(requireRole(...)) spelling; with none, the route FAILS CLOSED — it answers 501 and is never served unguarded — and register() warns once per affected route.

  • enforceSchemas: boolean

    When true (the default), a route decorated with @ValidateBody / @ValidateQuery / @ValidateParams gets the registered validation capability's enforcing middleware appended LAST in its chain (innermost, after guards and filters), so an invalid request is rejected with 400 before the handler runs — while guard 401/403 precedence is preserved.

  • modules: readonly Constructor[]

    Module classes to expand before registration. Imported modules are visited depth-first; each module's providers are collected before its controllers.

  • services: readonly Constructor[]

    Explicit list of service classes to register.

I
DiscoveryOptions

Discovery configuration.

I
DiscoveryResult

Result of a discovery scan.

I
InjectableOptions

Options for Injectable.

I
ModuleOptions

What a @Module declares.

I
OptionalToken

A token marked optional by Optional.

I
ParameterMetadata

Metadata captured by a parameter decorator, later resolved by the resolveParameters function.

I
ParamSource

A declaration of where one handler argument comes from.

Type Aliases

T
HttpMethodDecorator = (path?: string) => SetuMethodDecorator

A factory producing a method decorator that registers a route for a given HTTP verb.

T
InjectToken = string | OptionalToken

A constructor dependency: a capability token, or a token wrapped by Optional.

T
MiddlewareLike = MiddlewareFunction | (new () => IMiddleware)

A middleware value accepted by pipeline decorators: either a bare MiddlewareFunction or a class implementing IMiddleware.

T
ModuleImporter = (specifier: string) => Promise<unknown>

Loads a module from a specifier. Defaults to the global dynamic import; injectable for tests.

T
RenderDecorator<P> = (
value: (...args: never[]) => P | HandlerResult | Promise<P | HandlerResult>,
context: ClassMethodDecoratorContext
) => void

The decorator Render(Component) returns: assignable to a handler whose return is the component's props bag, sync or async, with any parameter list. A handler returning the WRONG shape fails compilation naming the mismatch — strictly stronger than NestJS's @Render('users/index'), a string checked against nothing.

T
SetuClassDecorator = (
value: unknown,
context: ClassDecoratorContext
) => void

A standard class decorator that records metadata and leaves the class as it is. Returning nothing means the class is never replaced, which is what keeps a decorated class identical to its undecorated self at runtime.

T
SetuClassOrMethodDecorator = (
value: unknown,
context: ClassDecoratorContext | ClassMethodDecoratorContext
) => void

A standard decorator valid in either the class or the method position, discriminating on context.kind.

T
SetuMethodDecorator = (
value: unknown,
context: ClassMethodDecoratorContext
) => void

A standard method decorator that records metadata and leaves the method as it is.

Variables

v
Delete: HttpMethodDecorator

Registers a DELETE route on the decorated method.

v
Get: HttpMethodDecorator

Registers a GET route on the decorated method.

v
Head: HttpMethodDecorator

Registers a HEAD route on the decorated method.

v
metadataStore: MetadataStore

The process-wide singleton decorators write to. The DecoratorPlugin registers this same instance under CAPABILITIES.METADATA_STORE so ctx.metadata resolves to it.

v
Options: HttpMethodDecorator

Registers an OPTIONS route on the decorated method.

v
Patch: HttpMethodDecorator

Registers a PATCH route on the decorated method.

v
Post: HttpMethodDecorator

Registers a POST route on the decorated method.

v
Put: HttpMethodDecorator

Registers a PUT route on the decorated method.

di-plugin/src/index.ts

Classes

c
CircularDetector

Detects circular dependencies during container resolution.

c
ContainerBuilder

Fluent builder for IContainer instances.

c
ProviderRegistry(parent?: ProviderRegistry)

Token-keyed store of provider entries with optional parent inheritance.

c
ScopeManager(
singletons?: Map<string, unknown>,
scoped?: Map<string, unknown>
)

Manages singleton and scoped instance caches for a container.

Functions

Interfaces

I
ContainerConfig

Configuration for constructing a DiContainer.

I
DiPluginOptions

Options for DiPlugin.

  • autoRegister: boolean

    When true, resolving a token not registered in the container automatically falls back to the kernel's ServiceRegistry. The first successful fallback is cached as a singleton so subsequent resolves are fast. Explicit DI registrations always take precedence. Defaults to false.

  • defaultScope: ServiceScope

    Default lifecycle scope for providers registered without an explicit scope. Defaults to 'singleton'.

I
ExternalResolver

External resolver used for auto-registration fallback. A subset of IServiceRegistry — when a token is not in the DI container and autoRegister is enabled, the container delegates here.

events-plugin/src/index.ts

Classes

c
DomainEvent<T = unknown>(
runtime: IRuntimeServices,
data: T,
opts?: { aggregateId?: string; version?: number; }
)

Abstract base class for domain events.

c
InMemoryEventBus(options: EventDispatchOptions)

In-memory publish/subscribe event bus.

Functions

Interfaces

I
EventHandlerRegistration

One event handler and the event type it subscribes to.

I
EventsPluginOptions

Options for the EventsPlugin.

I
IDomainEvent

A domain event.

I
IDomainEvents

Records domain facts raised by one aggregate during its current operation.

I
IEventBus

In-memory publish/subscribe event bus for domain events.

Type Aliases

exceptions/src/index.ts

Classes

c
HttpError(
statusCode: number,
message: string,
details?: Readonly<Record<string, unknown>>,
cause?: Error
)

The framework's HTTP error type.

Functions

f
conflict(message: string): HttpError

Creates a 409 Conflict error.

f
defaultFormatter(error: Error): DefaultErrorBody

Framework-standard error formatter.

f
errorHandler(options?: ErrorHandlerOptions): MiddlewareFunction

Creates a global error-handler middleware.

f
forbidden(message: string): HttpError

Creates a 403 Forbidden error.

f
internalServerError(
message: string,
cause?: Error
): HttpError

Creates a 500 Internal Server Error error.

f
notFound(message: string): HttpError

Creates a 404 Not Found error.

f
notImplemented(message: string): HttpError

Creates a 501 Not Implemented error.

f
f
selectFormatter(format?: ErrorFormat | ErrorHandlerFormatter): ErrorHandlerFormatter

Resolve the error format configuration to a concrete formatter function.

f
serviceUnavailable(message: string): HttpError

Creates a 503 Service Unavailable error.

f
statusTitle(statusCode: number): string

Resolves the human-readable title for a status code, falling back to a generic title for codes outside the well-known set.

f
unauthorized(message: string): HttpError

Creates a 401 Unauthorized error.

f
validationError(
errors: readonly ValidationError[],
message?: string
): HttpError

Creates a 422 Unprocessable Entity error wrapping a list of validation failures.

f

Interfaces

I
DefaultErrorBody

The framework-standard error body shape.

I
ErrorHandlerOptions

Options for the errorHandler middleware factory.

  • format: ErrorFormat | ErrorHandlerFormatter

    The error body format: 'default', 'rfc9457', the deprecated 'rfc7807', or a custom formatter function. Defaults to 'default'.

  • includeStackTrace: boolean

    When true, the error stack trace is included in the response body. Never enable this in production — pass a config-derived boolean (e.g. config.get('NODE_ENV') === 'development'), never read process.env directly (AI_GUIDELINES §4.1). Defaults to false.

  • logErrors: boolean

    When true (the default), caught errors are logged at error level via the ILogger resolved from ctx.services — but only if a logger is registered. When no logger is present, logging is silently skipped.

  • maskInternalErrors: boolean

    When true (the default), a caught value that was not an HttpError and resolves to a status >= 500 is masked in the response: its detail/message becomes the status title ('Internal Server Error') and the raw message — which for a failed query carries the SQL and its bound parameter values — is dropped from the body. The log is unaffected: logErrors still records the unmasked error and its cause chain, so an operator loses nothing unless logErrors is also false, the configuration that already logs nothing.

  • respond: (
    error: HttpError,
    ctx: IRequestContext
    ) =>
    HandlerResult
    | undefined
    | Promise<HandlerResult | undefined>

    Lets the application write its own response for a caught error. The hook receives the normalized error after status hints, internal-error masking, and status resolution, so error.statusCode is safe to serve. Return a HandlerResult produced by ctx.response to use that response; it may resolve that result asynchronously. Return or resolve to undefined to fall through to the configured formatter unchanged.

I
HttpErrorInit

Options accepted by the HttpError constructor.

I
ProblemDetails

A Problem Details object as defined by RFC 9457.

I
ValidationError

A single validation failure carried by a 422 error.

Type Aliases

T
ErrorFormat = "default" | "rfc9457" | "rfc7807"

The built-in error format identifiers for @setu-ts/exceptions.

T
ErrorHandlerFormatter = (
error: Error,
ctx?: IRequestContext
) => Record<string, unknown>

A function that formats a thrown error into a serializable error body.

Variables

v
ERROR_TYPE_BASE: "https://setu-ts.dev/errors"

The canonical base URI for framework-produced problem type identifiers.

v
STATUS_TITLES: Readonly<Record<number, string>>

A human-readable title for a given HTTP status code. This is the single source of truth used by both the factory functions and the Problem Details formatters so the title field never drifts from the produced statusCode.

feature-flags-plugin/src/index.ts

Classes

c
ConfigProvider(flags: Readonly<Record<string, FlagDefinition>>)

Immutable config-backed flag provider.

c
DatabaseProvider(
options: { readonly store: IFlagStore; readonly refreshIntervalMs?: number; },
runtime: IRuntimeServices,
logger?: ILogger
)

Database-backed flag provider that polls an injected IFlagStore.

c
FeatureFlagService(provider: FlagProvider)

Feature flag service that delegates to a single FlagProvider.

c
LaunchDarklyModuleError(message: string)

Thrown when a supplied module does not look like the LaunchDarkly SDK.

c
LaunchDarklyProvider(
config: LaunchDarklyProviderConfig,
logger?: ILogger
)

A FlagProvider backed by LaunchDarkly.

c
MemoryProvider(initialFlags?: Readonly<Record<string, FlagDefinition>>)

Mutable in-memory flag provider.

Functions

f
adaptLaunchDarklyModule(module: unknown): ILaunchDarklyModule

Narrows an arbitrary module object to ILaunchDarklyModule.

f
createFlagGuard(
flag: string,
options?: FlagGuardOptions
): MiddlewareFunction

Creates a middleware function that guards a route based on a feature flag.

f
loadLaunchDarklyModule(): Promise<ILaunchDarklyModule>

Lazily imports the LaunchDarkly Node server SDK.

f
toLaunchDarklyContext(context?: FlagContext): LaunchDarklyContext

Builds the LaunchDarkly evaluation context for a framework FlagContext.

Interfaces

I
ConfigProviderOptions

Options for the 'config' provider arm.

I
CustomProviderOptions

Options for the 'custom' provider arm.

I
DatabaseProviderOptions

Options for the 'database' provider arm.

I
FlagContext

Evaluation context for targeting rules.

I
FlagDefinition

Definition of a single feature flag.

  • enabled: boolean

    Whether the flag is enabled by default.

  • percentage: number

    Optional percentage rollout (0-100).

  • tenants: readonly string[]

    Optional tenant restriction. When present and non-empty, the flag is false for any context whose tenantId is not in this list — including a context with no tenant — and this restriction is evaluated ahead of every other rule (it is not an allowlist: it cannot be overridden by users). When absent, evaluation is unchanged.

  • users: readonly string[]

    Optional user allowlist — overrides enabled: false.

I
FlagGuardOptions

Options for the createFlagGuard factory.

I
FlagProvider

Port that all flag providers implement.

I
FlagProviderStatus

Status reported by a flag provider.

I
IFeatureFlags

Feature flag evaluator. Evaluation is synchronous against the provider's cached state; providers refresh their state out of band.

I
IFlagStore

Structural facade injected into DatabaseProvider.

I
ILaunchDarklyClient

The subset of LaunchDarkly's LDClient this provider uses.

I
ILaunchDarklyFlagsState

The subset of LaunchDarkly's LDFlagsState this provider reads.

I
ILaunchDarklyModule

The subset of the SDK module surface this provider uses.

I
LaunchDarklyContext

The LaunchDarkly evaluation context.

I
LaunchDarklyProviderConfig

Configuration for the 'launchdarkly' provider arm.

  • client: ILaunchDarklyClient

    A prebuilt client. When present the SDK module is never loaded and sdkKey is not read.

  • fallbackValue: boolean

    Value returned by the synchronous isEnabled for a context whose snapshot has not loaded yet, and used as the SDK default in isEnabledAsync. Defaults to false.

  • initTimeoutSeconds: number

    Seconds to wait for the client's initial connection. Defaults to 5. A timeout is logged and tolerated, leaving the provider degraded rather than failing application startup.

  • ldOptions: Readonly<Record<string, unknown>>

    Options forwarded verbatim as the SDK init() second argument.

  • module: unknown

    The SDK module, adapted rather than imported. Lets a test drive the whole construction path without the real package installed.

  • sdkKey: string

    The LaunchDarkly SDK key. Required unless client is injected; a missing key with no client throws during register().

I
LaunchDarklyProviderOptions

Options for the 'launchdarkly' provider arm.

I
MemoryProviderOptions

Options for the 'memory' provider arm.

Type Aliases

T
FlagProviderType = "config" | "memory" | "database" | "launchdarkly" | "custom"

Provider identity reported by FlagProvider.type, and surfaced as data.provider by the plugin's feature-flags health indicator.

graphql-plugin/src/index.ts

Classes

c
GraphqlRuntimeLoadError(
specifier: string,
cause: unknown
)

Error thrown when the graphql runtime cannot be loaded.

c
GraphqlSchemaError(
message: string,
cause?: unknown
)

Error thrown when schema construction or resolver attachment fails.

Functions

f
adaptGraphqlModule(module: GraphqlModuleLike): GraphqlRuntime

Adapt a graphql module to the internal runtime interface.

f
encodeSseComment(): Uint8Array

Encode a keep-alive comment.

f
encodeSseComplete(): Uint8Array

Encode a complete SSE event with the mandatory empty data: field.

f
encodeSseEvent(data: unknown): Uint8Array

Encode a next SSE event carrying a GraphQL execution result.

f
f
loadGraphqlModule(importer?): Promise<GraphqlRuntime>

Load the graphql runtime, either from an injected module or lazily.

f
persistedQueryHash(
query: string,
subtle: SubtleCrypto
): Promise<string>

Compute a SHA-256 hash of the query string and return lowercase hex.

Interfaces

I
AnySubscriptionResolver

The entry type for a SUBSCRIPTION resolver stored in a TypeResolverMap.

I
DefaultGraphqlContext

Default context shape that resolvers receive.

I
GraphqlApqOptions

APQ (Automatic Persisted Queries) options.

I
GraphqlCodeFirstOptions

Code-first arm options.

I
GraphqlConnectionInfo

Information about a WebSocket connection used for subscription operations.

I
GraphqlContextInput

Context input for custom context building.

I
GraphqlExecutionResult

The execution result as specified by the GraphQL spec.

I
GraphqlFormattedError

Formatted GraphQL error as returned to the client.

I
GraphqlModuleLike

The structural shape of a graphql@16 module — the external boundary (M70i X6-3).

I
GraphqlOperationContext

Context for a subscription operation, carrying either an HTTP request context or a WebSocket connection info.

I
GraphqlRequestParams

Parameters for a GraphQL execution request.

I
GraphqlScalarResolver

Custom scalar resolver methods.

I
GraphqlSchemaFirstOptions

Schema-first arm options.

I
GraphqlSseTransportOptions

SSE transport options for GraphQL subscriptions.

I
GraphqlSubscriptionsOptions

Subscription transport configuration.

I
GraphqlWsTransportOptions

WebSocket transport options for GraphQL subscriptions.

I
IGraphqlService

The GraphQL service contract.

I
SubscriptionResolver

A subscription field's resolver pair.

Type Aliases

Variables

grpc-plugin/src/index.ts

Examples

Example 1

import { createApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';
import { GrpcPlugin } from '@setu-ts/grpc-plugin';
import { CAPABILITIES, type IGrpcService } from '@setu-ts/common';

const app = createApplication({
  plugins: [RuntimePlugin(), GrpcPlugin()],
});

await app.start({ port: 3000 });

// The plugin registers CAPABILITIES.GRPC during start(), so resolve it
// only AFTER start() resolves — before that, the capability does not exist.
const grpc = app.services.get<IGrpcService>(CAPABILITIES.GRPC);

Classes

c
GrpcDescriptorError(
detail: string,
options?: ErrorOptions
)

Thrown when an embedded descriptor set cannot be decoded, or when a service the plugin expects to find inside one is absent — i.e. the committed base64 constant is truncated, swapped, or regenerated against an incompatible proto.

c
GrpcRuntimeLoadError(
specifier: string,
installCommand: string,
options?: ErrorOptions
)

Thrown when any of the Connect runtime modules cannot be imported. Carries the exact specifier that failed and the suggested install command.

c
GrpcService(init: GrpcServiceOptions)

The gRPC service applications use to register Connect/gRPC services.

c
GrpcUnavailableError()

Thrown when the adapter does not support the RPC interceptor seam (i.e., IHttpAdapter.setRpcHandler? is not available) and an attempt is made to handle a request directly through GrpcService.handleRequest.

Functions

f
adaptConnectModule(modules: ConnectModuleLike): ConnectRuntime

Adapts already-imported Connect and Protobuf-ES modules into the internal ConnectRuntime port. Pure — it performs no I/O, so unit tests drive it with a fake module bundle.

Interfaces

I
GrpcPluginOptions

Options for the gRPC plugin.

  • basePath: string

    Base path under which gRPC/Connect services are served. Defaults to the root ('/', M70i). A gRPC-family client derives its path from the fully-qualified method name alone and has no prefix option, so a prefixed default puts every procedure at an address no such client asks for. At the root, unknown paths fall through to Hono and only registered procedure paths are claimed. This makes Connect and gRPC-Web reachable at their natural addresses; native application/grpc reaches the server too but is deliberately refused with a Trailers-Only UNIMPLEMENTED. Pass '/grpc' to restore the pre-M70i prefix.

  • connectModule: ConnectRuntime

    Injected Connect runtime module(s). When provided, avoids the lazy import. Used by tests to avoid network dependencies.

  • health: boolean

    Whether to enable the gRPC Health v1 service (bridged to M20 health plugin). Defaults to true.

  • interceptors: readonly unknown[]

    Application-supplied Connect interceptors, threaded into createConnectRouter({ interceptors }) (M70f §3.7). The plugin's built-in handler-error logging wraps each application service's implementation (innermost), so a handler throw is logged before an application interceptor observes it. Absent: no application interceptors are installed.

  • reflection: boolean

    Whether to enable server reflection (v1). Defaults to true.

  • services: Array<{ definition: unknown; implementation?: unknown; }>

    Initial services to register. Each entry contains a service definition and an optional implementation object.

I
GrpcServiceDefinition

A gRPC service definition that satisfies the plugin's expectations. This is a structural constraint satisfied by generated descriptor objects from @bufbuild/protobuf. It contains only the fields the plugin needs to route requests and build reflection data.

I
IGrpcService

The service contract that applications use to register gRPC/Connect services. Provided by the grpc-plugin under the CAPABILITIES.GRPC token.

Type Aliases

T
GrpcServingStatus = "unknown" | "serving" | "not-serving" | "service-unknown"

The serving status returned by the health bridge. These values map onto the gRPC v1 Health response enum.

T
RpcFetchHandler = (request: Request) => Promise<Response | null>

A fetch handler that attempts to handle a gRPC/Connect request. Returns a Response if the request was handled as RPC, otherwise returns null so the adapter falls through to normal Hono handling.

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

health-plugin/src/index.ts

Examples

Example 1

import { HealthPlugin, createHttpIndicator } from '@setu-ts/health-plugin';

app.register(HealthPlugin({
  endpoints: {
    health: '/health',
    live: '/live',
    ready: '/ready',
  },
  indicators: [
    createHttpIndicator('external-api', { url: 'https://api.example.com/health' }),
  ],
}));

Classes

c
HealthService(
runtime: IRuntimeServices,
options?: { indicatorTimeoutMs?: number; }
)

Default implementation of IHealthService.

Functions

Interfaces

I
HealthCheckResult

The outcome of one health check.

I
HealthPluginOptions

Options for configuring the health plugin.

I
HealthReport

The aggregated health report returned by IHealthService.check().

I
HttpIndicatorOptions

Options for creating an HTTP probe indicator.

I
IHealthIndicator

A named health indicator contributing to /health, /live, and /ready.

I
IHealthService

Health service contract for registering and checking health indicators.

Type Aliases

T
HealthIndicatorEntry = IHealthIndicator | RegistryFactory<IHealthIndicator>

One entry of HealthPluginOptions.indicators: either a ready indicator instance or a factory that builds one from the service registry.

T
HealthIndicatorFn = () => Promise<HealthCheckResult>

Function form of a health indicator.

T
HealthStatus = "up" | "down" | "degraded"

Health state reported by a health indicator.

http-security-plugin/src/index.ts

Examples

Example 1

import { HttpSecurityPlugin, corsMiddleware } from '@setu-ts/http-security-plugin';

app.register(HttpSecurityPlugin({
  cors: { origin: 'https://example.com', credentials: true },
  csrf: { trustedOrigins: ['https://example.com'] },
}));

// Per-route use of standalone factories:
app.router.get('/api', {
  middleware: [corsMiddleware({ origin: 'https://other.com' })],
  handler: (ctx) => ctx.response.json({ ok: true }),
});

Functions

Interfaces

I
ContentSecurityPolicyOptions

Options for Content-Security-Policy header.

I
CorsOptions

Options for CORS middleware.

I
CsrfOptions

Options for CSRF middleware.

  • customHeader: string

    When set, unsafe methods must carry this custom header or the request is rejected with 403. Simple form submits cannot set custom headers without a preflight, making this a CSRF defense.

  • enabled: boolean

    Enable/disable CSRF protection. Defaults to true when present.

  • trustedOrigins: readonly string[]

    Additional trusted origins (scheme+host) beyond the request's own origin. The request's own origin (derived from request.url) is always implicitly trusted. Default: [].

I
HttpSecurityPluginOptions

Options for HttpSecurityPlugin.

I
IpSecurityOptions

Options for IP security middleware.

  • enabled: boolean

    Enable/disable IP resolution. Defaults to true when present.

  • ipHeader: string

    The header name to read when trustProxy is true. Default: X-Forwarded-For.

  • proxyHops: number

    The number of proxies in front of this application, when they cannot be addressed by IP (a managed load balancer on a rotating address). The nth entry FROM THE RIGHT is the client: 1 skips the immediate peer's contribution, 2 skips two, and so on.

  • trustProxy: boolean

    When true, read the client IP from the proxy header instead of request.ip. Requires a trusted reverse proxy. Default: false.

  • trustedProxies: readonly string[]

    Addresses of the proxies in front of this application, as literal addresses or CIDR blocks. When supplied, the header is walked RIGHT to LEFT and the first entry that is not one of these is the client.

I
RequestSizeOptions

Options for request-size middleware.

I
SecurityHeadersOptions

Options for security headers middleware.

I
StrictTransportSecurityOptions

Options for Strict-Transport-Security header.

Type Aliases

kernel/src/index.ts

Functions

Interfaces

I
ApplicationOptions

Options for createApplication.

I
IKernelApplication

Kernel application extends IApplication with inject() capability.

I
InjectRequest

Inject request shape for IKernelApplication.inject.

I
InjectResponse

Inject response shape returned by IKernelApplication.inject.

logger-plugin/src/index.ts

Classes

Functions

Interfaces

I
ConsoleLoggerOptions

Options for constructing a ConsoleLogger.

I
LoggerPluginOptions

Options for LoggerPlugin.

I
NoopLoggerOptions

Options for constructing a NoopLogger. Currently unused but kept for a stable, forward-compatible constructor signature that mirrors the other logger implementations.

I
PinoLoggerOptions

Options for constructing a PinoLogger.

I
RequestLoggerOptions

Options for createRequestLoggerMiddleware.

Type Aliases

T
LoggerTransport = "console" | "pino" | "noop"

Selects the underlying logger implementation.

T
PinoFactory = (options: { level: LogLevel; redact?: readonly string[]; base?: Record<string, unknown>; }) => PinoLoggerLike

Factory signature for creating a Pino logger instance. Matches the shape of the pino default export and allows tests to inject a stub.

mail-plugin/src/index.ts

Classes

c
LogProvider(options?: LogProviderOptions)

Records outgoing mail instead of sending it.

c
MailService(
provider: MailProvider,
templates: TemplateEngine,
options?: MailServiceOptions
)

Mailer backed by a pluggable provider and a template engine.

c
SendGridProvider(options?: SendGridProviderOptions)

SendGrid provider over fetch.

c
SesProvider(options?: SesProviderOptions)

AWS SESv2 provider.

c
SmtpProvider(options?: SmtpProviderOptions)

SMTP provider over nodemailer.

c
TemplateEngine(templates?: Readonly<Record<string, MailTemplate>>)

A registry of named body templates with {{ variable }} interpolation.

Functions

f
adaptNodemailerModule(
mod: NodemailerModule,
options: SmtpProviderOptions
): ISmtpTransport

Adapts the nodemailer module to a transport facade. Pure — unit-tested with a fake module; the real module is supplied on the lazy path by loadNodemailerModule.

f
adaptSesModule(
mod: SesSdkModule,
options: SesProviderOptions
): ISesClient

Adapts the AWS SESv2 SDK module to the facade. Pure — unit-tested with a fake module; the real module is supplied on the lazy path by loadSesModule.

f
escapeHtml(value: string): string

Escapes the five HTML-significant characters so interpolated user data cannot inject markup into an HTML body.

f
loadNodemailerModule(): Promise<NodemailerModule>

Lazily imports nodemailer. Only exercised on the lazy path.

f
loadSesModule(): Promise<SesSdkModule>

Lazily imports the AWS SESv2 SDK. Only exercised on the lazy path.

f
toSendGridBody(message: OutgoingMail): Record<string, unknown>

Maps an OutgoingMail to a SendGrid v3 request body.

f
toSesInput(message: OutgoingMail): Record<string, unknown>

Maps an OutgoingMail to a SendEmailCommand input.

f
validateSesClient(client: unknown): client is ISesClient

Validates that an injected object matches ISesClient.

f
validateSmtpTransport(transport: unknown): transport is ISmtpTransport

Validates that an injected object matches ISmtpTransport.

Interfaces

I
IMailer

Email sender.

I
ISesClient

Structural shape of an AWS SESv2 client facade (injected or SDK-adapted). The plugin never hard-depends on @aws-sdk/client-sesv2.

I
ISmtpTransport

Structural shape of a nodemailer transport. The plugin never hard-depends on nodemailer; inject this shape, or SmtpProvider lazily loads the package and adapts it to this facade.

I
LogProviderOptions

Options for LogProvider.

I
MailMessage

An outgoing email message.

I
MailPluginOptions

Options for the MailPlugin factory.

I
MailProviderOptions

Provider-specific options. Fields are consumed only by the matching provider; unrelated fields are ignored (mirrors SecretsProviderOptions).

I
MailServiceOptions

Options for MailService.

I
MailTemplate

A named body template. At least one of html/text must be present.

  • html: string

    HTML body template with {{ variable }} placeholders (values escaped).

  • text: string

    Plain-text body template with {{ variable }} placeholders (raw).

I
RenderedTemplate

A rendered template body. Only present bodies are returned.

I
SendGridProviderOptions

Options for SendGridProvider.

I
SesProviderOptions

Options for SesProvider.

I
SmtpProviderOptions

Options for SmtpProvider.

Type Aliases

T
IMailHttp = (
url: string,
init?: RequestInit
) => Promise<Response>

A fetch-shaped function used by SendGridProvider so it stays runtime-agnostic and testable.

T
OutgoingMail = MailMessage & { readonly from: string; }

An outgoing email whose sender has already been resolved by MailService (from the message or the configured default). This is the shape every MailProvider receives — from is never absent.

messaging-plugin/src/index.ts

Examples

Example 1

import { MessagingPlugin } from '@setu-ts/messaging-plugin';
import { CAPABILITIES } from '@setu-ts/common';

// GCP Pub/Sub
app.register(MessagingPlugin({
  broker: 'pubsub',
  projectId: 'my-project',
}));

// Azure Service Bus
app.register(MessagingPlugin({
  broker: 'service-bus',
  connectionString: 'Endpoint=sb://...',
}));

// Custom broker
app.register(MessagingPlugin({
  broker: 'custom',
  instance: myBroker,
}));

Classes

c
ChainGateTimeoutError(timeoutMs: number)

Thrown when a delivery held on the ingress behaviour-chain gate (PipelinedBroker) waits longer than the configured chainReadyTimeoutMs (default 10 000 ms; 0 waits forever) for the behaviour chain to open.

c
CloudBrokerUnavailableError(
backend: string,
specifier: string
)

Thrown by a cloud broker's IMessageBroker.connect when the runtime platform is Cloudflare Workers and the SDK cannot function (gRPC, AMQP, or long-poll — not fetch). The throw fails app.start() at the earliest possible point.

c
GcpPubSubBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: PubSubOptions
)

GCP Pub/Sub message broker.

c
InMemoryBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: InMemoryBrokerOptions
)

In-memory message broker implementation.

c
IntegrationEventRejectedError(details: { reason: IntegrationEventRejectionReason; topic: string; expectedType: string; expectedVersion: number; detail: string; cause?: unknown; })

Thrown by onIntegrationEvent's wrapper when a delivered message is refused before the application handler runs. One class rather than four keeps the consumer's instanceof branch a single import, while reason discriminates.

c
JetStreamStreamError(
stream: string,
cause?: unknown
)

Thrown by NatsBroker.connect when the JetStream stream could not be ensured: the stream is absent and NatsOptions.streamSubjects was not supplied, or the platform refused the stream read/create. The platform's own error is carried as cause when there is one.

c
JetStreamUnavailableError(cause: unknown)

Thrown by NatsBroker.connect when the NATS server rejects the JetStream manager probe — the server does not have JetStream enabled, which the nats broker requires. The platform's own error (typically the raw 503 / NO_RESPONDERS reply for the $JS.API subjects) is carried as cause.

c
JsonSerializer

JSON serializer implementation for message payloads.

c
KafkaBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: KafkaOptions
)

Kafka message broker implementation.

c
NatsBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: NatsOptions
)

NATS JetStream message broker implementation.

c
RabbitMqBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: RabbitMqOptions
)

RabbitMQ message broker implementation using AMQP 0-9-1 topic exchange.

c
RedisStreamsBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: RedisStreamsOptions
)

Redis Streams message broker implementation.

c
RemoteHandlerError(remoteMessage: string)

Thrown by IMessageBroker.request when the remote responder threw while handling the request. The responder's error message is propagated back to the caller in remoteMessage.

c
ReplyInboxUnavailableError(topic: string)

Thrown by GcpPubSubBroker and ServiceBusBroker when the per-instance RPC reply subscription cannot be created (missing Manage right or the reply topic does not exist).

c
RequestTimeoutError(message?: string)

Thrown by IMessageBroker.request when no correlated reply arrives within the configured timeoutMs window. The pending request is abandoned and its correlation entry cleaned up; a reply that arrives afterwards is dropped.

c
ServiceBusBroker(
runtime: IRuntimeServices,
serializer: ISerializer,
options?: ServiceBusOptions
)

Azure Service Bus message broker.

c
MessagingNotSupportedError(message?: string)

Signals that a broker's transport cannot support brokered request-reply.

Functions

f
causedBy(envelope: IntegrationEventEnvelope): { correlationId: string; causationId: string; }

Derives the causal metadata a consumed envelope contributes to the event its handling publishes next — the whole of the chain-root rule, extracted so no handler copies it by hand.

f
loadPubSubModule(): Promise<PubSubSdkModule>

Lazily load the GCP Pub/Sub SDK.

f
loadServiceBusModule(): Promise<ServiceBusSdkModule>

Lazily load the Azure Service Bus SDK.

f
onIntegrationEvent<T>(
definition: IntegrationEventDefinition<T>,
handler: IntegrationEventHandler<T>,
options?: SubscribeOptions
): SubscriptionDefinition

Produces a SubscriptionDefinition for an integration-event contract — the declarative form, plugging straight into MessagingPlugin({ subscriptions }), or spread by hand into an imperative broker.subscribe after start().

f
publishIntegrationEvent<T>(
runtime: IRuntimeServices,
broker: IMessageBroker,
definition: IntegrationEventDefinition<T>,
payload: T,
metadata?: IntegrationEventMetadata
): Promise<void>

Publishes one integration event: builds the envelope from the caller's already-typed payload and hands it to broker.publish on the definition's topic.

Interfaces

I
EventsMessagingBridgeOptions

Options for the EventsMessagingBridge factory.

I
IMessageBroker

Message broker for cross-service integration events.

I
INatsHeaders

Public members used from NATS MsgHdrs.

I
InMemoryBrokerOptions

Options for the in-memory broker — the adapter behind the memory arm of MessagingPluginOptions, constructed by it and by applications that build InMemoryBroker directly.

  • onDispatchError: (
    error: unknown,
    metadata: MessageMetadata
    ) => void | Promise<void>

    Called once per REJECTED subscription handler, with the error and the message metadata of the failed dispatch. publish resolves on dispatch hand-off — never on handler completion — so this reporter is the terminus of the broker's failure path: the in-memory broker has no ack model and no redelivery to fall back on (unlike RabbitMQ, where a rejection reaching the broker's failure path can nack and redeliver). Absent, the rejection is still observed and settled — never an unhandled rejection — then dropped. A reporter that itself throws or rejects is swallowed by the broker: it is the last-resort sink, so its own failure can neither reject publish nor abort the sibling fan-out nor surface as an unhandled rejection. MessagingPlugin always supplies one backed by the application's logger, so the absent case is reachable only by constructing the broker directly.

I
IntegrationEventDefinition

A named, versioned cross-service event contract.

  • parse: (value: unknown) => T

    Narrows the delivered payload for the application handler. Runs on the consumer side only — never on publish.

  • topic: string

    The transport topic the event is published to and consumed from.

  • type: string

    The event's semantic name, carried in the envelope's type field.

  • version: number

    The contract version. A bump is a breaking payload change.

I
IntegrationEventEnvelope

The wire shape of a published integration event.

I
IntegrationEventMetadata

Optional causal metadata for publishIntegrationEvent.

I
IPubSubSubscription

Handle for an open Pub/Sub subscription.

I
IPubSubTransport

Domain port for GCP Pub/Sub operations. The broker depends on this, not the SDK directly.

I
ISerializer

Serializer contract for converting messages to/from string payloads.

I
IServiceBusProcessErrorArgs

Structural type matching the real SDK's ProcessErrorArgs callback argument (npm:@azure/service-bus@^7).

I
IServiceBusSubscribeOptions

Structural receive-options matching the real SDK's SubscribeOptions (npm:@azure/service-bus@^7). The property is autoCompleteMessages, not autoComplete.

I
IServiceBusSubscription

Handle for an open Service Bus subscription receiver.

I
ISubscription

An active subscription.

I
KafkaOptions

Kafka-specific options (internal use).

I
MemoryMessagingOptions

Default (memory) arm. The discriminant is optional so that MessagingPlugin() and MessagingPlugin({}) remain valid.

I
MessageMetadata

Transport metadata accompanying a delivered message.

I
MessagingCommonOptions

Shared options present on every MessagingPluginOptions arm.

  • behaviors: readonly (IIngressBehavior | RegistryFactory<IIngressBehavior>)[]

    Ingress behaviours wrapped around every subscription handler — the messaging arm of the transport-neutral behaviour chain shared with the websocket, queue, and scheduler plugins (IIngressBehavior in @setu-ts/common).

  • chainReadyTimeoutMs: number

    Bounds a dispatch held on the behaviour-chain gate, which exists only when a RegistryFactory behaviour is declared. A held dispatch that waits longer than this rejects with ChainGateTimeoutError, whose message names the likely cause (a plugin publishing during its own register()); the gate itself is left in place, so later dispatches refuse the same way rather than delivering through a partial chain.

  • name: string

    Instance name for multi-instance support.

  • serializer: ISerializer

    Serializer for message payloads.

  • subscriptions: readonly SubscriptionEntry[]

    Subscriptions registered declaratively, as an alternative to calling broker.subscribe(topic, handler, options) imperatively after start(). Each entry — instance or RegistryFactory — produces one subscribe() call, so a subscription can be declared where the plugin is composed instead of after the application has started.

  • tracing: boolean

    Whether to create producer and consumer spans when telemetry is available.

I
NatsMessagingOptions

NATS arm.

I
NatsOptions

NATS-specific options (internal use).

I
PubSubOptions

Options for GCP Pub/Sub broker.

I
RabbitMqOptions

RabbitMQ-specific options (internal use).

I
RedisStreamsOptions

Redis-specific options (internal use).

I
RequestOptions

Options accepted by IMessageBroker.request.

  • timeoutMs: number

    Reply wait budget in milliseconds. When no correlated reply arrives within this window, request rejects. Defaults to 5000 when omitted.

I
ServiceBusOptions

Options for Azure Service Bus broker.

I
ServiceBusRetryOptions

Azure Service Bus SDK retry budget for the data client (M90b / X28-6).

  • maxRetries: number

    Maximum number of retry attempts before an operation fails. The SDK default is 3; 0 disables retries entirely.

  • maxRetryDelayInMs: number

    Ceiling the exponential backoff grows to, in milliseconds. The SDK default is 90000.

  • mode: "fixed" | "exponential"

    Backoff curve. Translated to the SDK's numeric RetryMode before ServiceBusClient is constructed (the SDK compares the value with === against its enum). The SDK default when omitted is 'fixed'.

  • retryDelayInMs: number

    Delay before the first retry, in milliseconds. The SDK default is 30000.

  • timeoutInMs: number

    Whole-operation timeout, in milliseconds. The SDK default is 60000.

I
SubscribeOptions

Options accepted when subscribing to a topic.

  • queue: string

    Consumer group / queue name for load-balanced delivery.

I
SubscriptionDefinition

The declarative form of one IMessageBroker.subscribe() call — the entry an application writes instead of calling subscribe() imperatively after start().

Type Aliases

T
IntegrationEventRejectionReason = "malformed" | "type-mismatch" | "version-mismatch" | "parse"

Why an integration-event delivery was refused before the application handler ran. The four values are the four distinct producer-side faults an operator triaging a dead-letter needs to tell apart.

T
PubSubMessagingOptions =
PubSubMessagingOptionsInjected
| PubSubMessagingOptionsProduction

GCP Pub/Sub options — exclusive union of injected and production arms.

T
RequestHandler<TReq = unknown, TRes = unknown> = (
message: TReq,
metadata: MessageMetadata
) => TRes | Promise<TRes>

Responder for a request topic. Its resolved value is sent back to the caller as the reply, correlated to the originating request.

T
ServiceBusMessagingOptions =
ServiceBusMessagingOptionsInjected
| ServiceBusMessagingOptionsProduction

Azure Service Bus options — exclusive union of injected and production arms.

T
SubscriptionEntry =
SubscriptionDefinition
| RegistryFactory<SubscriptionDefinition>

One entry of MessagingCommonOptions.subscriptions: a subscription definition, or a RegistryFactory producing one when the handler needs a resolved capability.

metrics-plugin/src/index.ts

Examples

Example 1

import { MetricsPlugin } from '@setu-ts/metrics-plugin';

app.register(MetricsPlugin({
  endpoint: '/metrics',
  httpMetrics: true,
}));

// Record metrics
const metrics = ctx.services.get<IMetricsService>('metrics');
const counter = metrics.counter('my_counter', { help: 'My counter' });
counter.inc(1);

Classes

c
MetricsService(options?: MetricsServiceOptions)

The metrics service — provides factory methods for creating metrics and rendering them in Prometheus format.

Functions

Interfaces

I
ICounter

Monotonically increasing counter. observe / inc add a non-negative value.

I
IHistogram

Histogram: bucketed observation distribution plus sum and count.

I
IMetric

A registered metric.

I
IMetricsService

Metrics service resolved via ctx.services.get<IMetricsService>('metrics').

I
ISummary

Summary: per-quantile observations plus sum and count.

I
MetricConfig

Configuration for registering a metric.

I
MetricOptions

Ergonomic options for the typed factory methods. type is injected by the method name; help defaults to the metric name.

I
MetricsPluginOptions

Plugin options for MetricsPlugin.

I
NamedMetricConfig

Named metric config for declarative registration.

multi-tenancy-plugin/src/index.ts

Classes

c
ColumnPerTenant(columnName?: string)

Isolates tenants by stamping a tenant column on every row.

c
DatabasePerTenant(prefix?: string)

Isolates tenants by assigning each a separate database.

c
HeaderResolver(options?: HeaderResolverOptions)

Resolves the tenant id from an HTTP header.

c
JwtResolver(options:
JwtResolverOptions
& { decode: (token: string) => Record<string, unknown> | null; }
)

Resolves the tenant id from a claim in an unverified JWT payload.

c
MemoryTenantDataStore(options?: MemoryTenantDataStoreOptions)

A zero-dependency in-memory ITenantDataStore that partitions rows by strategy-derived scope ('column' → tenantId, 'schema' → resolved schema, 'database' → resolved database).

c
PathResolver(options?: PathResolverOptions)

Resolves the tenant id from a segment of request.path.

c
SchemaPerTenant(prefix?: string)

Isolates tenants by assigning each a separate database schema.

c
SubdomainResolver(options?: SubdomainResolverOptions)

Resolves the tenant id from the first subdomain label of request.url.

c
TenantNotResolvedError(message?: string)

Thrown by IMultiTenancyService.getRepository when no tenant is resolved in the request context.

Functions

f
getTenantCachePrefix(ctx: { state: Map<string, unknown>; }): string | undefined

Exported accessor that reads the cache-prefix stamped into ctx.state by the middleware. Consumers never hardcode the state key string.

f
tenantMiddleware(arg_0: TenantMiddlewareOptions): MiddlewareFunction

Factory that creates a middleware function resolving the tenant and attaching it to ctx.request.tenant.

Interfaces

I
HeaderResolverOptions

Options for HeaderResolver.

I
IMultiTenancyService

Multi-tenancy service — exposes tenant context, repository creation, and cache-key helpers.

I
ITenant

A resolved tenant.

I
ITenantDataStore

Tenant-scoped data-store port.

I
ITenantRepository

Tenant-scoped repository — delegates CRUD to the data store the multi-tenancy plugin was configured with (ITenantDataStore, declared in that plugin), while threading the resolved tenant id.

I
ITenantResolver

Resolves the tenant for an incoming request (by subdomain, header, path, or JWT claim, depending on the implementation).

I
JwtResolverOptions

Options for JwtResolver.

I
MemoryTenantDataStoreOptions

Options passed to the MemoryTenantDataStore constructor.

  • generateId: () => string

    Generate a unique identifier for new records when data.id is not a string or number. Defaults to a monotonic counter ('1', '2', …).

I
MultiTenancyPluginOptions

Top-level options for MultiTenancyPlugin.

I
PathResolverOptions

Options for PathResolver.

I
SubdomainResolverOptions

Options for SubdomainResolver.

I
TenantCacheOptions

Options for cache-prefix stamping.

Type Aliases

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

v
TENANT_CACHE_PREFIX_STATE_KEY: "multi-tenancy-plugin:cache-prefix"

State key for the cache prefix — consumers should use getTenantCachePrefix instead of reading this directly.

notification-plugin/src/index.ts

Classes

c
EmailChannel(
name: string,
mailer: IMailer
)

EmailChannel dispatches notifications through the resolved IMailer.

c
FcmProvider(options: FcmProviderOptions)

FcmProvider implements PushTransport via the FCM HTTP v1 API.

c
NotificationService(channels: Map<string, NotificationChannel>)

NotificationService implements INotifier, fanning out a single NotificationMessage across all requested channels in parallel via Promise.allSettled. If any channel fails, it throws an AggregateError whose members each name their channel (X8-12).

c
PushChannel(
name: string,
transport: PushTransport
)

PushChannel dispatches notifications through a PushTransport (e.g. FcmProvider).

c
SlackChannel(
name: string,
transport: SlackTransport
)

SlackChannel dispatches notifications through a SlackTransport (e.g. SlackProvider).

c
SlackProvider(options: SlackProviderOptions)

SlackProvider implements SlackTransport via a Slack incoming webhook URL.

c
SmsChannel(
name: string,
transport: SmsTransport
)

SmsChannel dispatches notifications through an SmsTransport (e.g. TwilioProvider).

c
TwilioProvider(options: TwilioProviderOptions)

TwilioProvider implements SmsTransport via the Twilio Accounts SID / Messages endpoint.

Functions

Interfaces

I
FcmChannelConfig

Push channel configuration — options are FcmProviderOptions.

I
FcmProviderOptions

Options for FcmProvider.

  • clientEmail: string

    Service-account email that signs the OAuth2 assertion. Required unless tokenSource is supplied.

  • http: INotificationHttp
  • privateKey: string

    PEM PKCS#8 private key for the service account. Required unless tokenSource is supplied.

  • projectId: string

    Firebase project id; addressed by the v1 messages:send URL.

  • runtime: IRuntimeServices

    Runtime services providing Web Crypto and the wall clock, used to sign the assertion and expire cached tokens. Required unless tokenSource is supplied; the plugin passes this automatically.

  • tokenSource: FcmTokenSource

    Overrides how access tokens are acquired — e.g. from a GCP metadata server instead of a locally held key. When set, the three credential fields above are unused.

I
FcmTokenSource

Supplies OAuth2 access tokens for FCM HTTP v1.

I
INotificationHttp

Injectable HTTP seam for notification providers.

I
INotifier

Multi-channel notification dispatcher.

I
MailChannelConfig

Email channel configuration.

I
NotificationHttpResponse

Response shape returned by INotificationHttp.post.

I
NotificationMessage

A notification dispatched across one or more channels.

I
NotificationPluginOptions

Options for NotificationPlugin.

I
PushMessage

An outgoing push-notification message shaped by PushTransport.

I
PushTransport

Push-notification transport port implemented by FcmProvider.

I
SlackChannelConfig

Slack channel configuration — options are SlackProviderOptions.

I
SlackMessage

An outgoing Slack message shaped by SlackTransport.

I
SlackTransport

Slack transport port implemented by SlackProvider.

I
SmsMessage

An outgoing SMS message shaped by SmsTransport.

I
SmsTransport

SMS transport port implemented by TwilioProvider.

I
TwilioChannelConfig

SMS channel configuration — options are TwilioProviderOptions.

Type Aliases

T
NotificationTransport = IMailer | SmsTransport | PushTransport | SlackTransport

Union of every transport a channel can be built on, as returned by createProvider.

T
ProviderType = ChannelConfig["provider"]

Provider type selector — the ChannelConfig discriminant.

openapi-plugin/src/index.ts

Classes

Functions

f
OpenApiPlugin(options?: OpenApiPluginOptions): IPlugin

Creates an OpenAPI plugin that auto-generates OpenAPI 3.1 documentation from registered routes and serves it (with optional Swagger UI).

f
zodToOpenApi(schema: unknown): OpenApiSchemaObject

Convenience function for one-off Zod to OpenAPI conversion.

Interfaces

I
IOpenApiService

Service for generating and retrieving OpenAPI 3.1 specifications.

I
OpenApiGeneratorOptions

Options for OpenAPI document generation.

I
OpenApiOperation

OpenAPI operation definition.

I
OpenApiParameter

OpenAPI parameter definition.

I
OpenApiPluginOptions

Options for the OpenAPI plugin.

I
OpenApiSchemaObject

OpenAPI 3.1 schema object.

I
OpenApiServiceOptions

Options for the OpenAPI service.

I
SwaggerUiOptions

Options for Swagger UI HTML generation.

Type Aliases

T
SchemaIo = "input" | "output"

Which side of a schema a document site is describing.

T
SchemaNodeHook = (schema: unknown) => OpenApiSchemaObject | undefined

Consulted for every schema ZodToOpenApi.transform is about to convert — the top-level one AND every sub-schema it recurses into.

queue-plugin/src/index.ts

Classes

c
MemoryQueue()

In-memory queue adapter implementation.

c
QueueBackendUnavailableError(
backend: string,
specifier: string
)

Thrown by a queue backend's connect() when the runtime platform is Cloudflare Workers and the SDK cannot function. The throw fails app.start() at the earliest possible point.

c
RabbitMqQueue(
runtime: IRuntimeServices,
options?: RabbitMqQueueOptions
)

RabbitMQ queue adapter implementation.

c
RedisQueue(options?: RedisQueueOptions)

Redis queue adapter implementation.

c
SqsDelayTooLongError(delayMs: number)

Thrown by SqsQueue when a job delay exceeds SQS's 900 s DelaySeconds ceiling. The delay is NOT clamped (a clamp runs the job early); the caller must adjust the value.

c
SqsQueue(
runtime: IRuntimeServices,
options: SqsQueueOptions,
logger?: { error: (msg: string) => void; }
)

SQS queue adapter.

c
SqsQueueNotConfiguredError(
jobName: string,
configuredNames: readonly string[]
)

Thrown by SqsQueue when a job name is not mapped in the queues configuration. The error message names the job name and the configured names.

Functions

Interfaces

I
AddJobOptions

Options accepted when enqueueing a job.

I
IJob

A queued job delivered to a processor.

I
ISnsTransport

Domain port for SNS operations.

I
ISqsTransport

Domain port for SQS operations. The adapter depends on this, not the SDK.

I
ProcessOptions

Options accepted when registering a processor.

I
QueueDepths

How many jobs are in each of one name's states.

I
QueueLogger

Minimal logger surface the service reports through — structurally compatible with ILogger so the plugin can pass the resolved logger capability without this package depending on the logger plugin.

I
QueuePluginOptions

Options for configuring the queue plugin.

I
QueueProcessorDefinition

The declarative form of one IQueue.process() call — the entry an application writes instead of calling process() imperatively after start().

I
RabbitMqQueueOptions

Options for configuring RabbitMqQueue.

I
RecurringOptions

Options accepted when scheduling a recurring job.

I
RedisQueueOptions

Options for configuring RedisQueue.

I
SnsPublisherOptions

Options for SNS publisher.

I
SqsQueueOptions

Options for SQS queue adapter.

I
SqsReceivedMessage

A message received from SQS with its receipt handle.

Type Aliases

T
QueueAdapterType = "memory" | "redis" | "rabbitmq" | "sqs"

Queue adapter type for plugin configuration.

T
QueueProcessorEntry =
QueueProcessorDefinition
| RegistryFactory<QueueProcessorDefinition>

One entry of QueuePluginOptions.processors: a processor definition, or a RegistryFactory producing one when the processor needs a resolved capability.

react-router-plugin/src/index.ts

Examples

Example 1

import { ReactRouterPlugin } from '@setu-ts/react-router-plugin';
import { CAPABILITIES, ISsrService } from '@setu-ts/common';

const app = createApplication();
app.register(ReactRouterPlugin({
  serverBuildPath: './build/server/index.js',
  assetsDir: './build/client/assets',
}));
await app.start({ port: 3000 });

Classes

Functions

f
assembleHandler(
build: unknown,
createRequestHandler: (
build: unknown,
mode: string
) => unknown
,
mode: string
): SsrRequestHandler

Pure function that assembles an RR request handler from a pre-loaded build and the createRequestHandler factory.

f
assertSsrRuntime(value: unknown): SsrRuntime

Validates that an injected loadRequestHandler resolved to a usable SsrRuntime, and narrows it.

f
bridgeRequestToRR(
ctx: IRequestContext,
handler: SsrRequestHandler,
createLoadContext: () => RouterLoadContext,
populateLoadContext?: PopulateLoadContext
): Promise<HandlerResult>

Bridges a kernel IRequestContext into a web Request, invokes the RR handler, and maps the resulting web Response back onto ctx.response.

f
contextKeyFor<T>(
name: string,
defaultValue: T
): RouterContextKey<T>

Returns the context key for a name, creating it on first use.

f
createLoadContextFactory(rr: Record<string, unknown>): () => RouterLoadContext

Builds the per-request context factory from React Router's RouterContextProvider class.

f
createPublicFileHandler(options: { fs: IFileSystem; assetsDir: string; }): (ctx: IRequestContext) => Promise<HandlerResult | undefined>

Creates a handler that ATTEMPTS to serve a file from a directory, resolving the request path relative to createPublicFileHandler.options.assetsDir. The plugin passes the CLIENT-BUILD ROOT here (the parent of the assets dir, where Vite copies public/) — probing the assets subdir itself missed every public file.

f
createStaticAssetHandler(options: { fs: IFileSystem; assetsDir: string; assetUrlPrefix: string; }): RouteHandler

Creates a static-asset RouteHandler that serves files from a directory using the injected IFileSystem.

Interfaces

I
HandlerResult

Opaque marker returned by IResponse terminal methods and expected back from route handlers. It exists purely so the type system can verify a handler produced a response; only the kernel creates values of this type.

I
IFileSystem

Runtime-agnostic file system operations. Absent on runtimes without file system access (edge platforms).

I
IRequestContext

Per-request context passed to middleware and route handlers. Each request gets a fresh context; request-scoped data lives here, never in globals.

I
ISsrService

Service contract for server-side rendering (SSR).

I
ReactRouterPluginOptions

Options for the React Router plugin.

  • assetUrlPrefix: string

    URL prefix for the static-asset route. Default /assets/.

  • assetsDir: string

    Filesystem root of the built client bundle. Omit to disable static-asset serving (no asset route registered).

  • basename: string

    Mount prefix for the SSR catch-all route. Default /. MUST match the app's react-router.config.ts basename for flat/nested routes to resolve.

  • loadRequestHandler: (
    serverBuildPath: string,
    mode: string
    ) => Promise<SsrRuntime>

    Injectable seam for lazy loading the RR runtime. When omitted, the default performs await import(serverBuildPath) + await import('npm:react-router@8').

  • mode: "production" | "development"

    Mode passed to createRequestHandler(build, mode).

  • populateLoadContext: PopulateLoadContext

    Adds application values to the per-request React Router context, on top of the servicesContext and userContext keys the plugin always sets.

  • publicFiles: boolean

    Also serves files from the client-build ROOT — where Vite copies public/ (robots.txt, favicon.ico, …) — in addition to ReactRouterPluginOptions.assetUrlPrefix, with Cache-Control: public, max-age=0, must-revalidate: root files are not content-hashed, so they must be revalidated rather than cached immutably. A request matching neither the root nor the prefix still falls through to the SSR catch-all.

  • serverBuildPath: string

    Path to the React Router Vite server build (default export = ServerBuild).

I
RouterContextKey

A React Router context key, used by identity as the argument to RouterLoadContext.get / RouterLoadContext.set.

I
RouterLoadContext

The per-request context object React Router passes to loaders, actions, and middleware as context.

I
SsrRuntime

Everything the plugin needs from a loaded React Router module: the request handler, plus a factory for the RouterContextProvider that handler will accept.

Type Aliases

T
PopulateLoadContext = (
ctx: IRequestContext,
context: RouterLoadContext
) => void

Hook for adding application values to the per-request React Router context.

T
RouteHandler = (ctx: IRequestContext) => HandlerResult | Promise<HandlerResult>

A route handler: receives the request context and returns a response via the context's response builder.

T
SsrRequestHandler = (
request: Request,
loadContext: unknown
) => Promise<Response>

React Router request handler — the callable returned by createRequestHandler(build, mode).

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

v
servicesContext: RouterContextKey<IServiceRegistry | null>

Key holding the kernel IServiceRegistry for the current request.

v
userContext: RouterContextKey<IPrincipal | null>

Key holding the authenticated principal, or null on an anonymous request.

realtime-backplane-plugin/src/index.ts

Examples

Example 1

import { createApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';
import { RealtimeBackplanePlugin } from '@setu-ts/realtime-backplane-plugin';
import { WebSocketPlugin } from '@setu-ts/websocket-plugin';

const app = createApplication({
  plugins: [
    RuntimePlugin(),
    RealtimeBackplanePlugin({ transport: 'redis', url: 'redis://localhost:6379' }),
    WebSocketPlugin(),
  ],
});

Classes

c
MemoryBackplane(
origin: string,
bus?: string
)

A real single-process backplane.

c
MessagingBackplane(
broker: IMessageBroker,
origin: string,
topic: string
)

Carries frames over whatever broker is registered under CAPABILITIES.MESSAGING.

c
RedisBackplane(
options: RedisBackplaneOptions,
origin: string,
topic: string
)

Carries frames over Redis pub/sub.

c
RedisModuleError(message: string)

Thrown when ioredis cannot be loaded or does not look like itself.

Functions

f
adaptRedisModule(module: unknown): IRedisModule

Narrows an ioredis module to the constructor facade this package uses.

f
decodeFrameData(payload: EncodedPayload): string | Uint8Array

Decodes a payload received from the wire back into its local form.

f
encodeFrameData(data: string | Uint8Array): EncodedPayload

Encodes a WebSocket payload for the wire.

f
isRealtimeFrame(value: unknown): value is RealtimeFrame

Narrows an arriving broker payload to a RealtimeFrame.

Interfaces

I
BackplaneCommonOptions

Options shared by every transport arm.

  • localNotice: boolean

    M70n X3-4: when the resolved transport is 'memory', the plugin logs a process-local notice at register() — frames fan out only within this process, which looks like partial delivery behind more than one replica. Default true; false suppresses the notice, matching the existing scalingNotice opt-out shape on the SSE and WebSocket plugins.

  • origin: string

    This instance's identity, stamped on published frames so a subscriber can drop its own echoes. Defaults to a fresh runtime.uuid(), which is correct for every deployment; override only to make a test deterministic.

  • topic: string

    The broker topic / Redis channel every instance publishes and subscribes on. Defaults to 'setu-ts.realtime'. Instances must agree on it to see each other.

I
CustomBackplaneOptions

Options for the 'custom' arm — a caller-supplied transport.

I
EncodedPayload

A payload as it travels the backplane.

I
IRealtimeBackplane

A publish/subscribe transport carrying RealtimeFrames between application instances.

I
IRedisBackplaneClient

The ioredis-shaped client surface the Redis transport uses.

I
IRedisModule

A module exposing an ioredis-compatible constructor.

I
MemoryBackplaneOptions

Options for the 'memory' arm — a real single-process transport, not a no-op. Instances sharing one process see each other; separate processes do not.

  • bus: string

    The name of the process-wide bus this instance joins. Two backplanes built with the same name exchange frames; different names are isolated, which is what keeps concurrent tests from bleeding into each other. Defaults to 'default'.

  • transport: "memory"

    Transport discriminant.

I
MessagingBackplaneOptions

Options for the 'messaging' arm, which carries frames over whatever broker is registered under CAPABILITIES.MESSAGING.

I
RealtimeFrame

One broadcast crossing the backplane.

I
RedisBackplaneOptions

Options for the 'redis' arm — Redis pub/sub.

Type Aliases

T
RealtimeFrameHandler = (frame: RealtimeFrame) => void

Receives frames published by other instances.

T
RealtimeFrameKind = "ws-room" | "sse-channel"

Which kind of broadcast group a RealtimeFrame addresses.

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

v
DEFAULT_TOPIC: "setu-ts.realtime"

The default topic when none is configured.

resilience-plugin/src/index.ts

Examples

Example 1

import { ResiliencePlugin } from '@setu-ts/resilience-plugin';
import type { IResilienceService } from '@setu-ts/common';

app.register(ResiliencePlugin({
  defaultRetry: { limit: 3, delay: 100, backoff: 'exponential' },
}));

const resilience = ctx.services.get<IResilienceService>('resilience');
const guarded = resilience.wrap(() => externalApi.call(), { retry: true, timeout: 2000 });

Classes

c
BulkheadFullError(message?: string)

Thrown when a bulkhead is at maximum concurrency and its queue is full, so the call is shed (fail-fast load shedding) rather than executed or queued.

c
CircuitOpenError(message?: string)

Thrown when a circuit breaker is open and fails fast without invoking the protected call.

c
TimeoutError(message?: string)

Thrown when a protected call exceeds its per-attempt timeout deadline.

Functions

Interfaces

I
ResiliencePluginOptions

Options passed to ResiliencePlugin(). Each default* policy is consumed when a wrap sets the matching field to true; a wrap requesting true with no matching default configured throws.

runtime/src/index.ts

Classes

c
BunHttpAdapter(
host?: BunServeHost,
options?: HttpAdapterOptions
)

Bun HTTP adapter implementation.

c
CloudflareWorkersHttpAdapter(
wsHost?: CloudflareWebSocketHost,
options?: HttpAdapterOptions
)

Cloudflare Workers HTTP adapter implementation.

c
DenoHttpAdapter(
host?: DenoServeHost,
options?: HttpAdapterOptions
)

Deno HTTP adapter implementation.

c
NodeHttpAdapter(
host?: NodeServeHost,
wsModule?: WsModuleLike,
options?: HttpAdapterOptions
)

Node HTTP adapter implementation.

c
NodeUpgradeCoordinator(module?: WsModuleLike)

Owns the ws server for one Node HTTP adapter and performs the handshake.

c
RequestBodyTooLargeError(maxBodyBytes: number)

Raised when a request body exceeds the configured RuntimeOptions.maxBodyBytes cap.

c
RpcInterceptorStore

Stores an adapter's RPC interceptor and consults it safely.

Functions

f
adaptWsModule(module: unknown): WsModuleLike

Narrows an already-imported module to WsModuleLike.

f
asUpgradeEmitter(server: unknown): UpgradeEmitter | null

Probes a server handle for the raw upgrade event.

f
buildBunHost(mods?: BunModules): BunHost

Builds the default BunHost from node: built-ins, which Bun implements.

f
buildNodeHost(mods?: NodeModules): NodeHost

Builds the default NodeHost from node: built-ins, which Deno and Bun also implement.

f
createBunWebSocketHandlers(): BunWebSocketHandlers

Builds the serve-time handler object that routes every Bun socket event to the sink stored on that socket's data.

f
createDefaultCloudflareWebSocketHost(): CloudflareWebSocketHost

Builds the default host from the real Workers globals.

f
createDenoDnsResolver(host: DenoDnsHost): IDnsResolver

Creates an IDnsResolver backed by Deno.resolveDns.

f
createNodeDnsResolver(dns?: NodeDnsModule): IDnsResolver

Creates an IDnsResolver backed by node:dns/promises.

f
createNodeWorkerHost(mods?: NodeWorkerModules): IWorkerHost

Creates an IWorkerHost backed by node:worker_threads.

f
createUpgradeRequest(incoming: NodeIncomingMessage): Request

Reconstructs a web-standard Request from Node's upgrade event arguments, so the upgrade router sees the same shape on every runtime.

f
createWebSocketTransport(socket: WebSocketLike): IWebSocketTransport

Wraps a web-API socket as an IWebSocketTransport.

f
createWebWorkerHost(
globals?: WebWorkerGlobals,
options?: WebWorkerHostOptions
): IWorkerHost

Creates an IWorkerHost backed by the web-standard Worker API (Deno and Bun).

f
createWsTransport(socket: WsSocketLike): IWebSocketTransport

Wraps a ws socket as an IWebSocketTransport.

f
detectRuntime(globals?: GlobalScope): RuntimePlatform

Detects the current runtime platform.

f
isWebSocketUpgradeRequest(headers: Headers): boolean

Reports whether a set of request headers describes an RFC 6455 WebSocket upgrade.

f
loadWsModule(): Promise<WsModuleLike>

Lazily imports ws and narrows it.

f
normalizeFrame(data: unknown): string | Uint8Array

Normalizes an inbound frame payload to the framework's string | Uint8Array.

f
rejectRawUpgrade(
socket: RawUpgradeSocket,
status: number
): void

Refuses an upgrade on the raw socket, since there is no Response object to return on Node's upgrade path.

f
RuntimePlugin(options?: RuntimeOptions): IPlugin

Creates the RuntimePlugin that provides runtime-agnostic services and HTTP adapter.

f
toReadyState(state: number): WebSocketReadyState

Maps the web WebSocket API's numeric readyState to the framework's named WebSocketReadyState.

f
toTransportError(value: unknown): Error

Coerces an error-event payload into a real Error.

f
toWsReadyState(state: number): WebSocketReadyState

Maps a ws numeric ready state to the framework's named state.

Interfaces

I
BunHost

Minimal interface covering the Bun-specific operations used by this adapter. Inject this interface to test the adapter without real Bun.

I
BunModules

The built-ins buildBunHost needs, injectable so every wrapper is unit-testable without real file-system access. Shapes match node:fs (sync), node:os, and node:process, all of which Bun implements.

I
BunServeHost

Minimal interface covering the Bun-specific HTTP operations used by this adapter. Inject this interface to test the adapter without real Bun.

I
BunServer

Bun server handle (from Bun.serve).

I
BunServerWebSocket

A Bun ServerWebSocket, narrowed to what this adapter drives.

I
BunSocketData

The per-socket data Bun carries from server.upgrade() through to every socket handler.

I
BunWebSocketHandlers

The serve-time socket handler object Bun expects under Bun.serve's websocket option.

I
CloudflareEnv

Injectable environment seam for Cloudflare Workers bindings. Defaults to an empty record so the adapter is testable without Workers globals.

I
CloudflareRuntimeOptions

Options for createCloudflareRuntimeServices.

  • env: CloudflareEnv

    Injectable env source for reading Workers bindings. Defaults to an empty record.

I
CloudflareServerSocket

The server half of a Workers WebSocketPair. Workers sockets are driven with addEventListener after an explicit accept(), not with on* properties.

I
CloudflareWebSocketHost

Injectable seam covering the two Workers-only globals this upgrader needs.

I
CloudflareWebSocketPair

A created WebSocketPair: the client half travels back in the 101 response, the server half stays here.

I
CreateRuntimeServicesOptions

Options for createRuntimeServices.

I
DenoDirEntry

Directory entry returned by DenoHost.readdir().

I
DenoDnsHost

The Deno.resolveDns surface this resolver needs.

I
DenoHost

Minimal interface covering the Deno-specific operations used by this adapter. Inject this interface to test the adapter without real Deno.

I
DenoServeHost

Minimal interface covering the Deno operations this adapter needs. Inject this interface to test the adapter without real Deno.

I
DenoServer

Deno HTTP server handle (from Deno.serve).

I
DenoSrvRecord

One SRV record as Deno.resolveDns returns it.

I
DenoWebSocketLike

A web-API socket that exposes the on* handler properties, as Deno's upgradeWebSocket socket does.

I
DenoWebSocketUpgrade

The result shape of Deno.upgradeWebSocket.

I
GlobalScope

Minimal global scope shape needed for detection. Allows injecting a fake global for testing without as casts in test code.

I
HttpAdapterOptions

Options every IHttpAdapter implementation in this package accepts, supplied by RuntimePlugin when it constructs one.

  • maxBodyBytes: number

    Maximum request-body size, in bytes, enforced where the body is actually read. Omitted, the read is unbounded — the released behaviour.

I
NodeDnsModule

The node:dns/promises surface this resolver needs, injectable so every branch is unit-testable without real DNS or network permission.

I
NodeHost

Minimal interface covering the Node-specific operations used by this adapter. Inject this interface to test the adapter without real Node.js.

I
NodeIncomingMessage

A Node IncomingMessage, narrowed to what building an upgrade Request needs.

I
NodeModules
I
NodeServeHost

Minimal interface covering the @hono/node-server serve() operation. Inject this interface to test the adapter without a real Node server.

I
NodeServer

Node.js HTTP server handle (returned by @hono/node-server serve()).

I
NodeWorkerLike

Minimal shape of a node:worker_threads Worker as used by this host.

I
NodeWorkerModules

The Node built-ins this host needs. Inject fakes to test without real threads.

I
RawUpgradeSocket

The raw socket handed to a Node upgrade listener, narrowed to what a refusal needs.

I
RuntimeAdapterFactories

Map of platform → runtime adapter factory.

I
RuntimeOptions

Options for RuntimePlugin.

  • adapters: RuntimeAdapterFactories

    Override runtime adapter factories for testing. When provided, the plugin uses these instead of the real adapter factories, allowing unit tests to run without OS permissions or real runtime globals.

  • env: Readonly<Record<string, unknown>>

    The Cloudflare Workers env record. There is no ambient environment on the edge, so without this runtime.env is empty on Workers and ConfigPlugin reads nothing.

  • httpAdapters: HttpAdapterFactories

    Override HTTP adapter factories for testing. When provided, the plugin uses these instead of the default HTTP adapters, allowing unit tests to inject fake HTTP adapters.

  • maxBodyBytes: number

    Maximum request-body size, in bytes, enforced where the body is read. Omitted, the read is unbounded — the released behaviour, byte for byte.

  • platform: RuntimePlatform

    Force a specific platform instead of auto-detecting. Useful for testing or when running in an environment where detection might be ambiguous.

I
UpgradeEmitter

An event emitter that can report raw HTTP upgrades — the one capability this adapter needs from the node:http server that serve() returns.

I
WebSocketLike

The subset of the web WebSocket API the runtime adapters drive. Declared structurally so no module depends on a platform's global types and a fake can stand in during unit tests.

I
WebWorkerGlobals

The web globals this host needs. Inject fakes to test without spawning real workers.

I
WebWorkerHostOptions

Host-construction options that vary between the runtimes sharing this implementation.

  • exitEventName: string

    Name of the non-standard event this runtime emits when a worker's thread ends. Bun emits 'close'; Deno emits nothing at all, so it passes nothing and the handles this host produces omit onExit entirely.

I
WebWorkerLike

Minimal shape of a web Worker instance as used by this host.

I
WsServerLike

A ws WebSocketServer in noServer mode, narrowed to what this adapter drives.

I
WsSocketLike

A ws socket, narrowed to what this adapter drives. Declared structurally so the package never takes a type dependency on @types/ws.

runtime/src/worker/define-worker-task.ts

Worker-side task helper — the ONLY framework code that runs inside a worker thread, published as the @setu-ts/runtime/worker subpath so task modules can import it without pulling in the runtime plugin barrel.

Functions

f
defineWorkerTask<TInput, TOutput>(fn: (input: TInput) => TOutput | Promise<TOutput>): void

Registers this module's task handler. Call once, at module top level, in a module that the WorkerPoolPlugin executes:

scheduler-plugin/src/index.ts

Classes

c
SchedulerUnavailableError(platform: string)

Thrown when SchedulerPlugin is registered on a runtime whose platform cannot run its timers.

Functions

Interfaces

I
DistributedLockOptions

Options for distributed locking.

I
IDistributedLock

Distributed lock interface.

I
IRedisLockClient

Minimal ioredis client shape required by RedisLock.

I
RetryOptions

Retry configuration for a scheduled job.

I
ScheduledJob

A scheduled job instance handed to the handler.

I
ScheduleOptions

Options passed when scheduling a job.

I
SchedulerPluginOptions

Plugin options passed to SchedulerPlugin().

Type Aliases

sdk/src/index.ts

Classes

c
ClientCircuitOpenError(message: string)

Thrown when the circuit breaker for the target origin is open.

c
OpenApiCodegenError(
message: string,
path?: string,
method?: string
)

Thrown by generateOpenApiClient() with path/method diagnostics when the OpenAPI document is malformed or contains unsupported constructs.

Functions

f
createBearerAuthInterceptor(token: string | (() => Promise<string>)): ClientRequestInterceptor

Create a request interceptor that sets Authorization: Bearer <token>.

f
f
createDefaultClientTiming(): IClientTiming

Factory returning the default IClientTiming backed by performance.now() and setTimeout.

f
generateOpenApiClient(
document: SdkOpenApiDocument,
options?: OpenApiCodegenOptions
): string

Generate TypeScript client source from an OpenAPI 3.1 document. Pure function with zero I/O and deterministic output.

Interfaces

I
CircuitBreakerPolicy

Circuit breaker policy consumed by the ResiliencePlugin's breaker pattern.

  • resetTimeout: number

    Cooldown in milliseconds before an open breaker moves to half-open.

  • threshold: number

    Failures within the timeout window that trip the breaker open.

  • timeout: number

    Rolling failure window in milliseconds; failures older than this (measured by the monotonic clock) are dropped before the threshold check.

I
ClientOptions

Options passed to createClient().

I
ClientRateLimitPolicy

Per-origin sliding-window rate-limit configuration.

I
ClientRequest

An outbound JSON request described by application or generated code.

I
ClientRequestContext

Mutable context passed to a ClientRequestInterceptor so it can inspect and modify the resolved URL and headers before the request executes.

I
ClientResponse

A successful parsed response returned by IHttpClient.request.

I
IClientTiming

Monotonic-time and sleep abstraction used by retry, breaker, and rate-limiter.

I
IHttpClient

The public HTTP client contract returned by createClient().

I
IRealtimeClient

A running realtime WebSocket client.

I
ISseClient

A running SSE client returned by createSseClient.

I
IWebSocketTransport

Minimal structural WebSocket surface used by the client.

I
OpenApiCodegenOptions

Options for generateOpenApiClient.

  • apiTypeName: string

    Name of the exported interface describing the generated client, and the factory's return type. Defaults to 'Api'.

  • factoryName: string

    Name of the exported factory function. Defaults to 'createApi'.

  • sdkImport: string

    Import specifier for SDK types. Defaults to '@setu-ts/sdk'.

I
RawSseEvent

The source frame given to a custom SSE payload parser.

I
RealtimeClientOptions

Configuration for createRealtimeClient.

I
RealtimeMessage

One parsed application message received from the server.

I
RealtimeReconnectOptions

Bounded reconnect policy for a realtime connection.

I
RetryPolicy

Retry policy consumed by the ResiliencePlugin's retry pattern.

I
SdkOpenApiDocument

Top-level OpenAPI 3.1 document consumed by {@code generateOpenApiClient}.

I
SdkOpenApiResponse

A single response description keyed by status code or range.

I
SseClientOptions

Configuration for createSseClient.

I
SseEvent

One parsed SSE event delivered to an application.

I
SseReconnectOptions

Reconnection policy for an SSE stream.

Type Aliases

T
BackoffStrategy = "fixed" | "exponential"

Backoff strategy applied to a RetryPolicy's base delay.

T
ClientRequestInterceptor = (ctx: ClientRequestContext) => void | Promise<void>

A request interceptor called once (before any retry attempt) in registration order. Receives a mutable ClientRequestContext.

T
ClientResponseInterceptor<T> = (
response: ClientResponse<T>,
request: ClientRequestContext
) => ClientResponse<T> | Promise<ClientResponse<T>>

A response interceptor called after a successful JSON parse, in registration order. Skipped entirely when the request throws.

T
RealtimeClientState = "connecting" | "open" | "closed"

Lifecycle states a realtime client reports.

T
SseClientState = "connecting" | "open" | "closed"

The lifecycle state of an SSE client.

T
SseEventMap = Record<string, unknown>

A map from SSE event names to their parsed payload types.

T
WebSocketFactory = (url: string) => IWebSocketTransport

Injectable constructor seam for the global WebSocket.

secrets-plugin/src/index.ts

Classes

c
AwsKmsProvider(options?: AwsKmsProviderOptions)

AWS Secrets Manager provider.

c
AzureKeyVaultProvider(options?: AzureKeyVaultProviderOptions)

Azure Key Vault provider.

c
EnvProvider(
env: Readonly<Record<string, string | undefined>>,
options?: { prefix?: string | undefined; }
)

Environment-variable secret provider.

c
GcpSecretManagerProvider(options?: GcpSecretManagerProviderOptions)

GCP Secret Manager provider.

c
HashiCorpVaultProvider(options?: HashiCorpVaultProviderOptions)

HashiCorp Vault (KV v2) provider.

c
ReadOnlySecretProviderError(provider: string)

Thrown when a secret is written through a provider that cannot store.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

  • provider: string

    The provider that refused the write (e.g. 'EnvProvider').

c
SecretsService(
provider: SecretProvider,
options?: SecretsServiceOptions
)

Secret manager backed by a pluggable provider with a read-through cache.

Functions

Interfaces

I
AwsKmsProviderOptions

Options for AwsKmsProvider.

I
AzureKeyVaultProviderOptions

Options for AzureKeyVaultProvider.

I
GcpSecretManagerProviderOptions

Options for GcpSecretManagerProvider.

I
HashiCorpVaultProviderOptions

Options for HashiCorpVaultProvider.

I
IAwsSecretsClient

Structural shape of an AWS Secrets Manager facade. The plugin never hard-depends on @aws-sdk/client-secrets-manager; inject this shape, or the provider lazily loads the SDK and adapts it to this facade.

I
IAzureSecretsClient

Structural shape of an Azure Key Vault facade (injected or SDK-adapted).

I
IGcpSecretsClient

Structural shape of a GCP Secret Manager facade (injected or SDK-adapted).

I
ISecretManager

Secret manager backed by a provider (AWS KMS, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, or environment variables in development).

I
SecretsPluginOptions

Options for the SecretsPlugin factory.

I
SecretsProviderOptions

Provider-specific options. Fields are consumed only by the matching provider; unrelated fields are ignored.

I
SecretsServiceOptions

Options for SecretsService.

  • cacheTtlSeconds: number

    Read-cache TTL in seconds. 0 disables caching. Default 300.

  • clock: () => number

    Monotonic clock in milliseconds (e.g. runtime.hrtime). Defaults to a monotonic performance.now-free stub returning 0, which — combined with a non-zero TTL — still caches within a request but never mixes wall-clock.

Type Aliases

T
IVaultHttp = (
url: string,
init?: RequestInit
) => Promise<Response>

A fetch-shaped function used by SecretsProviderOptions.http so the HashiCorp Vault provider stays runtime-agnostic and testable.

service-discovery-plugin/src/index.ts

Examples

Example 1

import { createApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';
import { ServiceDiscoveryPlugin } from '@setu-ts/service-discovery-plugin';
import { CAPABILITIES, type IServiceDiscovery } from '@setu-ts/common';

const app = createApplication({
  plugins: [
    RuntimePlugin(),
    ServiceDiscoveryPlugin({
      provider: 'consul',
      address: 'http://127.0.0.1:8500',
    }),
  ],
});

await app.start({ port: 3000 });

const discovery = app.services.get<IServiceDiscovery>(
  CAPABILITIES.SERVICE_DISCOVERY,
);
const url = await discovery.resolveUrl('billing', '/invoices');

Classes

c
ConsulProvider(
options: ConsulProviderOptions,
http: IDiscoveryHttp,
runtime: IRuntimeServices
)

Reads and registers against a Consul agent.

c
DiscoveryUnavailableError(
message: string,
options?: ErrorOptions
)

Discovery could not answer.

c
DnsProvider(
resolver: IDnsResolver,
runtime: IRuntimeServices,
options: DnsProviderOptions
)

Resolves services through DNS.

c
KubernetesProvider(
options: KubernetesProviderOptions,
http: IDiscoveryHttp,
runtime: IRuntimeServices
)

Reads EndpointSlices for a service.

c
SelfRegistrationNotSupportedError(provider: string)

selfRegistration was configured against a provider that cannot register.

c
StaticProvider(
services: Readonly<Record<string, readonly StaticServiceDefinition[]>>,
runtime: IRuntimeServices
)

Serves a configured instance list.

Functions

Interfaces

I
ADnsDiscoveryOptions

The 'dns' arm in address mode — A/AAAA records carry no port.

I
ConsulDiscoveryOptions

The 'consul' arm.

I
ConsulProviderOptions

Constructor options.

I
CustomDiscoveryOptions

The 'custom' arm — the application's own backend.

I
DiscoveryHttpResponse

A buffered HTTP response, as IDiscoveryHttp.request returns it.

I
DiscoveryHttpStream

A streaming HTTP response, as IDiscoveryHttp.stream returns it.

I
DiscoveryProvider

A discovery backend.

I
EjectionOptions

Outlier-ejection tuning.

I
IDiscoveryHttp

The HTTP surface the Consul and Kubernetes providers need.

I
KubernetesDiscoveryOptions

The 'kubernetes' arm — EndpointSlices read from the API server.

I
KubernetesProviderOptions

Constructor options.

I
SelfRegistration

What this application advertises about itself.

I
SelfRegistrationCheck

The health check the backend runs against this instance after registration.

I
SrvDnsDiscoveryOptions

The 'dns' arm in SRV mode — records carry their own ports.

  • mode: "srv"

    Query SRV records and honor RFC 2782 priority tiers.

I
StaticDiscoveryOptions

The 'static' arm — a literal instance list, with no backend at all.

I
StaticServiceDefinition

One entry of a 'static' service list.

Type Aliases

session-plugin/src/index.ts

Examples

Example 1

import { createApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';
import { getSession, SessionPlugin } from '@setu-ts/session-plugin';

const app = createApplication({
  plugins: [RuntimePlugin(), SessionPlugin({ secret: mySecret, csrf: {} })],
});

app.router.get('/me', (ctx) => {
  const session = getSession(ctx);
  return ctx.response.json({ userId: session.get<string>('userId') ?? null });
});

Classes

c
CacheSessionStore(
cache: ICacheStore,
options?: CacheSessionStoreOptions
)

ISessionStore over any ICacheStore.

c
CsrfTokenMismatchError(reason: string)

Thrown by the form-CSRF verifier when the submitted token is absent or does not match the session's token.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
MemorySessionStore(deps: MemorySessionStoreDeps)

Map-backed ISessionStore.

c
SessionMiddlewareMissingError()

Thrown by getSession(ctx) / SessionService.from(ctx) when the session middleware did not run for the request.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
SessionSecretMissingError(message: string)

Thrown during register() when no usable session secret could be resolved, or when the resolved secret is too short.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

c
SessionService(
config: ResolvedSessionConfig,
ring: KeyRing,
deps: SessionServiceDeps,
store?: ISessionStore
)

Loads, exposes, and commits the per-request session.

c
SessionTooLargeError(
actual: number,
limit: number
)

Thrown when a committed session cookie would exceed the configured byte budget, which browsers enforce at roughly 4 KB per cookie.

  • name: string

    Discriminant for consumers that cannot use instanceof across realms.

Functions

f
csrfTokenField(
ctx: IRequestContext,
options?: Pick<CsrfFormOptions, "fieldName">
): string

Renders this session's CSRF token as a hidden HTML form field.

f
getCsrfToken(ctx: IRequestContext): string

Returns this session's CSRF token, minting and storing one on first call.

f
getSession(ctx: IRequestContext): ISession

Returns the session the middleware loaded for this request.

f
SessionPlugin(options?: SessionPluginOptions): IPlugin

Registers cookie-backed sessions under CAPABILITIES.SESSION, with optional session-backed form CSRF.

f
verifyCsrfToken(
ctx: IRequestContext,
options?: CsrfFormOptions
): Promise<void>

Verifies the request's CSRF token against the session's, throwing on any mismatch.

Interfaces

I
CacheSessionStoreOptions

Options for CacheSessionStore.

I
CsrfFormOptions

Form-CSRF options.

  • exclude: readonly (string | RegExp)[]

    Request paths exempt from form-CSRF verification, matched by exact string equality or RegExp.test. Omitted means no path is exempt.

  • fieldName: string

    Form field carrying the token. Default '_csrf'.

  • headerName: string

    Header that may carry the token instead of a form field, for fetch-based posts and for multipart/form-data bodies this package does not parse. Default 'x-csrf-token'; header reading cannot be disabled — a synchroniser token that cannot be presented is not a security control.

  • ignoreMethods: readonly string[]

    Methods that skip verification. Default ['GET', 'HEAD', 'OPTIONS'].

I
MemorySessionStoreDeps

Runtime capabilities the store needs.

I
SessionCookieOptions

Cookie attributes for the session cookie.

I
SessionPluginOptions

Options for SessionPlugin.

  • cookie: SessionCookieOptions

    Cookie attributes.

  • csrf: CsrfFormOptions

    Enable session-backed form CSRF. Omitted means no CSRF middleware is registered; an empty object enables it with defaults.

  • idleTimeoutMs: number

    Expire a session that has received no requests for this long, independently of maxAge. Omitted by default (no idle check).

  • maxAge: number

    Absolute session lifetime in seconds. Default 7200 (2 hours).

  • maxCookieBytes: number

    Byte budget for the serialized cookie. Default 4096. Exceeding it throws rather than emitting a cookie the browser would silently drop.

  • mode: SessionMode

    How the cookie is protected. 'encrypt' (default) hides the payload with AES-256-GCM; 'sign' leaves it readable base64url JSON under an HMAC-SHA256 signature, which suits the store strategy where the cookie holds only an opaque id.

  • rolling: boolean

    Re-issue the cookie on every response, extending the expiry so an active user is not logged out mid-session. Default false, which commits only when the session actually changed.

  • secret: string | readonly string[]

    The session secret, or an ordered list of secrets for rotation: index 0 signs/encrypts new cookies while every entry can still open existing ones, so rotating a secret does not log everybody out.

  • secretName: string

    Name looked up in the secret manager and the environment. Default 'SESSION_SECRET'.

  • store: "memory" | "cache" | ISessionStore

    Where the payload lives. Omitted (default) keeps it in the cookie itself, which needs no infrastructure. Set to 'memory', 'cache', or a custom ISessionStore to keep only an opaque id in the cookie and the payload server-side, which makes immediate revocation possible.

  • tenantBinding: boolean

    Bind a session to the tenant it was minted under. Default true: when a tenant is resolved for the request, the tenant id is sealed into the session on commit, and a later request presenting that session under a different tenant is refused with 403 before the handler runs. When either the session or the request carries no tenant, nothing is compared, so an application without tenancy is inert. false restores the previous behaviour (no seal, no compare).

I
SessionServiceDeps

Runtime capabilities the service needs, injected for testability.

Type Aliases

T
SessionMode = "encrypt" | "sign"

How a session cookie is protected.

Variables

v
CSRF_SESSION_KEY: "__csrf"

Reserved session key holding the CSRF token.

sse-plugin/src/index.ts

Examples

Example 1

import { SsePlugin } from '@setu-ts/sse-plugin';
import { CAPABILITIES, ISseService } from '@setu-ts/common';

const app = createApplication();
app.register(SsePlugin({ heartbeatMs: 15000, retryMs: 3000 }));
await app.start({ port: 3000 });

app.router.get('/events', async (ctx) => {
  const sse = ctx.services.get<ISseService>(CAPABILITIES.SSE);
  const conn = sse.open(ctx);
  conn.send({ id: '1', data: 'hello world' });
  return conn.result;
});

Classes

c
SseConnection(
ctx: IRequestContext,
runtime: IRuntimeServices,
heartbeatMs: number | undefined,
retryMs: number | undefined,
onClosed: () => void
)

Implements IConn.

c
SseService(
options: SsePluginOptions | undefined,
runtime: IRuntimeServices,
backplane?: IRealtimeBackplane,
logger?: ILogger
)

Implements IService.

Functions

Interfaces

I
ISseConnection

A live SSE connection backed by a ReadableStream.

I
ISseService

Service contract for the SSE hub — registered by the SsePlugin under CAPABILITIES.SSE.

I
SseChannel

A named broadcast channel within the SSE hub.

I
SseMessage

A single SSE event payload.

  • data: JsonValue

    Event data. A string is written literally (split on \n into multiple data: lines); any non-string is JSON.stringify-ed. undefined is forbidden — use {} or omit the message instead.

  • event: string

    Event type name — sent as event: field.

  • id: string

    Unique event identifier — sent as id: field; enables Last-Event-ID resume.

  • retry: number

    Reconnection time in milliseconds — sent as retry: field.

I
SsePluginOptions

Options for the SsePlugin.

  • heartbeatMs: number

    Heartbeat interval in milliseconds. When set, the plugin schedules a repeating : heartbeat\n\n comment frame. Omit to disable (no timer created).

  • retryMs: number

    Reconnection time in milliseconds. When set, the first bytes on every new stream are retry: <ms> advertising the reconnect delay. Omit to send no retry: field.

  • scalingNotice: boolean

    Whether to log one info line at registration when no realtime backplane is registered, stating that channels broadcast in-process only. Defaults to true.

Type Aliases

T
ChannelPublisher = (
name: string,
msg: SseMessage
) => void

Forwards a local publish to peers on other replicas.

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

starters/full-stack-starter/src/index.ts

Functions

f
buildFullStackPlugins(options?: FullStackStarterOptions): IPlugin[]

Builds the canonical full-stack plugin set. Composes from buildMicroservicePlugins and appends the full-stack plugins (cache, events, cqrs, scheduler, audit, secrets, storage, mail). The list is exported for advanced custom composition.

f
createFullStackApp(options?: FullStackStarterOptions): IKernelApplication

Creates a fully wired full-stack application. The factory registers the curated full-stack plugin set (microservice + cache, events, cqrs, scheduler, audit, secrets, storage, mail), adds the error-handler middleware at priority 0 (outermost per exceptions contract), and returns the un-started application.

Interfaces

I
FromConfigOptions

Options for createFullStackAppFromConfig.

I
FullStackStarterOptions

Options for createFullStackApp. Extends MicroserviceStarterOptions with full-stack arms (always-on + gated). Omitted plugins use their defaults.

I
RealtimeArm

The real-time arm: one option grouping the three plugins that together make a connection-oriented application work, each added only when its sub-arm is present.

Type Aliases

T
StaticPluginOptions = { root: string; fs?: IFileSystem; urlPrefix?: string; index?: string; fallback?: string; cacheControl?: string | ((relativePath: string) => string); etag?: boolean; ranges?: boolean; compressed?: boolean; maxBufferBytes?: number; }

Options for configuring the StaticPlugin.

starters/microservice-starter/src/index.ts

Functions

f
buildMicroservicePlugins(options?: MicroserviceStarterOptions): IPlugin[]

Builds the canonical microservice plugin set. Composes from buildRestPlugins and appends the four microservice-specific plugins (messaging, queue, resilience, telemetry). The list is exported so full-stack can compose from it.

f
createMicroserviceApp(options?: MicroserviceStarterOptions): IKernelApplication

Creates a fully wired microservice application. The factory registers the curated microservice plugin set (REST + messaging, queue, resilience, telemetry), adds the error-handler middleware at priority 0 (outermost per exceptions contract), and returns the un-started application.

Interfaces

I
MicroserviceStarterOptions

Options for createMicroserviceApp. Extends RestStarterOptions with microservice-specific arms. Omitted plugins use their defaults.

I
RealtimeArm

The real-time arm: one option grouping the three plugins that together make a connection-oriented application work, each added only when its sub-arm is present.

starters/rest-starter/src/index.ts

Functions

f
buildRestPlugins(options?: RestStarterOptions): IPlugin[]

Builds the canonical REST plugin set. The list is exported so the microservice starter can compose from it without duplication.

f
createRestApp(options?: RestStarterOptions): IKernelApplication

Creates a fully wired REST application. The factory registers the curated REST plugin set, adds the error-handler middleware at priority 0 (outermost per the exceptions contract), and returns the un-started application.

Interfaces

I
RealtimeArm

The real-time arm: one option grouping the three plugins that together make a connection-oriented application work, each added only when its sub-arm is present.

I
RestStarterOptions

Options for createRestApp. Per-plugin optional arms are threaded straight through to each plugin factory. Omitted plugins use their default configuration (no arguments required).

static-plugin/src/index.ts

Examples

Example 1

import { StaticPlugin } from '@setu-ts/static-plugin';

app.register(StaticPlugin({
  root: './public',
  urlPrefix: '/assets',
}));

Classes

c
StaticFilesService(options: StaticPluginOptions)

Static files service that serves files from a configured root directory.

Functions

f
StaticPlugin(options: StaticPluginOptions): IPlugin

Creates a StaticPlugin that serves static files from a configured root directory.

Interfaces

I
IStaticFiles

Static files service interface.

  • serve(ctx: IRequestContext): Promise<HandlerResult>

    Serves the static file addressed by the request context, applying the same conditional-request, Range, and encoding negotiation the mounted routes use — this and the route handler are one implementation, so both honour the plugin's configuration identically.

Type Aliases

T
StaticPluginOptions = { root: string; fs?: IFileSystem; urlPrefix?: string; index?: string; fallback?: string; cacheControl?: string | ((relativePath: string) => string); etag?: boolean; ranges?: boolean; compressed?: boolean; maxBufferBytes?: number; }

Options for configuring the StaticPlugin.

storage-plugin/src/index.ts

Classes

c
AzureBlobProvider(
options?: AzureBlobProviderOptions,
now?: () => number
)

Azure Blob storage provider.

c
GcsProvider(
options?: GcsProviderOptions,
now?: () => number
)

Google Cloud Storage provider.

c
LocalStorageProvider(
runtimeFs: IFileSystem | undefined,
options?: { rootDir?: string; },
platform?: () => string
)

Local file-system storage provider.

c
MemoryProvider(now?: () => number)

In-memory storage provider backed by Map<string, Uint8Array>.

c
S3Provider(options?: S3ProviderOptions)

AWS S3 storage provider.

c
StorageService(provider: StorageProvider)

Storage service backed by a pluggable provider.

Functions

f
canSign(options: AzureBlobProviderOptions): boolean

Reports whether key-based SAS signing is possible for these options.

Interfaces

I
AzureBlobProviderOptions

Options for AzureBlobProvider.

I
AzureStorageOptions

The Azure Blob Storage arm.

I
GcsProviderOptions

Options for GcsProvider.

I
GcsStorageOptions

The Google Cloud Storage arm.

I
IAzureBlobClient

Minimal Azure Blob client shape for structural injection.

I
IGcsClient

Minimal GCS client shape for structural injection.

I
IStorage

Object storage abstraction.

I
LocalStorageOptions

The local-filesystem arm.

I
LocalStorageProviderOptions

Options for LocalStorageProvider.

I
MemoryStorageOptions

The default arm: in-memory storage, which takes no configuration.

I
PutObjectOptions

Object attributes accepted alongside the bytes when storing an object.

  • contentType: string

    MIME type recorded on the stored object (e.g. 'image/png'). Omitted leaves the backend's own default, which is application/octet-stream on every provider that supports the field.

  • metadata: Readonly<Record<string, string>>

    Arbitrary user metadata recorded alongside the object. Keys and values are passed through to the backend unmodified; backends impose their own limits on size and on which characters a key may contain.

I
S3ProviderOptions

Options for S3Provider (and 'b2' preset).

I
S3StorageOptions

The S3 arm, shared by 's3' and the 'b2' (Backblaze) preset, which reaches the same provider over B2's S3-compatible endpoint.

I
SignedUrlOptions

Options accepted when creating a signed URL.

I
UploadedFile

A single parsed file from a multipart upload.

  • data: Uint8Array

    File bytes.

  • filename: string

    The client-provided original file name (Content-Disposition filename="…"). Always present: since M94b a part carrying NO filename under the field name is a plain form value, not an upload (an empty filename="" — an empty file input — still is one).

  • mimeType: string

    MIME type reported by the client.

  • name: string

    The form field name the file was uploaded under (Content-Disposition name="…").

  • size: number

    File size in bytes.

I
UploadMiddlewareOptions

Options for the upload middleware factory.

Type Aliases

T
StoragePluginOptions =
MemoryStorageOptions
| LocalStorageOptions
| S3StorageOptions
| GcsStorageOptions
| AzureStorageOptions

Top-level options passed to StoragePlugin: a union discriminated on provider, so each backend's options are checked against that backend's own shape.

telemetry-plugin/src/index.ts

Classes

c
NoopTelemetryService

A telemetry service that does nothing — used when no exporter is configured.

Functions

Interfaces

I
InstrumentationConfig

Per-instrumentation entry. Presence of the parent key enables; this configures or injects.

  • config: Readonly<Record<string, unknown>>

    Opaque config object forwarded VERBATIM to the OTel instrumentation constructor's config argument (the LAZY half). Framework-owned and untyped on purpose: OTel instrumentation config surfaces evolve independently and re-typing them here would fabricate field names and drift.

  • instrumentation: unknown

    An already-constructed OTel Instrumentation instance — the INJECT half of the inject-or-lazy seam. When set, the registry skips the lazy npm: import and uses this instance directly.

I
InstrumentationsConfig

Configuration for auto-instrumentations.

I
ISpan

A span represents a single operation within a trace.

I
ITelemetryService

Telemetry service — the primary API for creating spans.

I
SamplingConfig

Sampling configuration.

I
SpanOptions

Options for span creation.

I
TelemetryContext

Opaque handle representing the parent context for span creation.

I
TelemetryPluginOptions

Options for the TelemetryPlugin.

I
TracerHost

The host seam returned by loadOtelTracerProvider.

Type Aliases

T
SpanAttributeValue =
string
| number
| boolean
| ReadonlyArray<string | number | boolean>

Attribute value — a span attribute can be a primitive or an array of primitives.

T
SpanExporterKind = "otlp" | "console"

Which span exporter to use.

T
SpanKind = "internal" | "server" | "client" | "producer" | "consumer"

The kind of span. Maps to OTel SpanKind at the implementation boundary.

T
SpanProcessorKind = "simple" | "batch"

Which span processor to use.

T
SpanStatus = "ok" | "error" | "unset"

Span status — whether the span completed successfully or not.

Variables

v
TELEMETRY_SPAN_KEY: "telemetry-plugin:span"

The key used to store the active span on ctx.state.

testing/src/index.ts

Classes

c
FixtureManager

Collects mock plugin definitions and real plugins, produces the IPlugin[] for createTestApp, and resets between tests.

c
MockResponse

In-memory IResponse double with snapshot() and ended getter.

c
MockServiceRegistry

In-memory IServiceRegistry with registration recording.

Functions

f
collectStream(response: Response): Promise<StreamingBody>

Collects a web Response body incrementally via a ReadableStream reader.

f
createMockPlugin(options: MockPluginOptions): IPlugin

Creates an IPlugin that registers a mock service under a capability token.

f
createTestApp(options?: TestAppOptions): Promise<IKernelApplication>

Creates a started test application that can be exercised via inject() and fetch() without binding a socket.

f
createTestContext(options?: TestContextOptions): IRequestContext

Builds a contract-faithful IRequestContext for unit-testing middleware and handlers in isolation (no started app needed).

f
inject(
app: IKernelApplication,
request: string | InjectRequest | Request
): Promise<InjectResponse>

Free-function HTTP request injector with string, InjectRequest, and web-standard Request shorthand.

f
overrideCapability(
token: CapabilityToken,
service: object
): IPlugin

Creates a plugin that REPLACES an already-provided capability with a test double, leaving the rest of the application's composition intact.

Interfaces

I
IKernelApplication

Kernel application extends IApplication with inject() capability.

I
InjectRequest

Inject request shape for IKernelApplication.inject.

I
InjectResponse

Inject response shape returned by IKernelApplication.inject.

I
MockPluginOptions

Options for createMockPlugin.

  • name: string

    Plugin name (also used as the capability token when provides is absent).

  • priority: number

    Registration priority; passed through to the kernel resolver. Omitted when not needed (the returned plugin omits priority too).

  • provides: string

    Capability token this plugin provides. Defaults to name. Override when the plugin name differs from the capability token.

  • register: (ctx: IPluginContext) => void | Promise<void>

    Additional registration callback invoked during register(ctx). Useful for registering middleware, routes, or lifecycle hooks alongside the mock service.

  • service: object

    The mock service object to register.

I
StreamingBody

Parsed body returned by collectStream.

I
TestAppFromApp

Composition-root arm of TestAppOptions: the test starts from the application the project actually ships and subtracts from it.

  • app: IKernelApplication

    An already-constructed, not yet started application — typically the createApp() a scaffolded project exports from setu.config.ts, or a starter factory's return value.

  • autoStart: boolean

    Whether to auto-start the application.

  • overrides: readonly IPlugin[]

    Plugins to append after without is applied — usually overrideCapability results, though any IPlugin is accepted.

  • plugins: never

    Not available on this arm — supply plugins or app, never both.

  • without: readonly string[]

    Plugin names to drop before start(), so their register() never runs and any eager side effect inside it never happens.

I
TestAppFromPlugins

Hand-assembled arm of TestAppOptions: the test names the plugins it wants and gets nothing else.

  • app: never

    Not available on this arm — supply plugins or app, never both.

  • autoStart: boolean

    Whether to auto-start the application.

  • overrides: never

    Not available on this arm — supply plugins or app, never both.

  • plugins: IPlugin[]

    Plugins to pre-register before start(). Must include a runtime capability provider (RuntimePlugin() or a mock providing CAPABILITIES.RUNTIME) when autoStart is true — the kernel throws otherwise.

  • without: never

    Not available on this arm — supply plugins or app, never both.

I
TestContextOptions

Options for createTestContext.

Type Aliases

validation-plugin/src/index.ts

Examples

Example 1

import { validatedStateKey } from '@setu-ts/common';
import { ValidationPlugin, validateBody, validateQuery } from '@setu-ts/validation-plugin';

app.register(ValidationPlugin({ errorFormat: 'rfc9457' }));

app.router.post('/users', {
  middleware: [validateBody(CreateUserSchema)],
  handler: async (ctx) => {
    const body = ctx.state.get(validatedStateKey('body'));
    // body is validated
  },
});

Classes

Functions

f
createSanitizer(rules: SanitizationRules): (input: string) => string

Create a sanitization function that applies the given rules to each call.

f
resolveFormatter(format?: ErrorFormat | ValidationErrorFormatter): ValidationErrorFormatter

Resolve the error format configuration to a concrete formatter function.

f
sanitize(
input: string,
rules: SanitizationRules
): string

Sanitize a single string value with the given rules.

f
validateBody(schema: unknown): MiddlewareFunction

Validate the request body against a schema.

f
f
validateHeaders(schema: unknown): MiddlewareFunction

Validate request headers against a schema.

f
validateParams(schema: unknown): MiddlewareFunction

Validate path parameters against a schema.

f
validateQuery(schema: unknown): MiddlewareFunction

Validate query parameters against a schema.

Interfaces

I
FormattedError

A single formatted error entry.

I
FormatValidationErrors

The shaped error body produced by a validation error formatter.

I
SanitizationRules

Configuration for sanitizing a string value.

I
ValidationPluginOptions

Options for ValidationPlugin.

Type Aliases

T
ErrorFormat = "default" | "rfc9457" | "rfc7807" | "nestjs"

The built-in error format identifiers for @setu-ts/validation-plugin.

Variables

v
rfc7807Formatter: ValidationErrorFormatter

Format validation issues as RFC 7807 Problem Details.

view-plugin/src/index.ts

Classes

c
UnresolvedSuspenseError(component: Component<never>)

A rendered tree holds a pending <Suspense> boundary. Buffered rendering serves only the fallback — with a 200 and no error — so it is refused by name instead of silently shipping a loading placeholder forever. Streaming resolution is deferred to a follow-up milestone; the remedy today is to move the <Suspense> boundary out of the rendered tree.

c
ViewRenderError(
component: Component<never>,
reason: string,
options?: ErrorOptions
)

A view component threw while rendering, or returned undefined — almost always a missing return, since null and false are the deliberate render-nothing values and yield an empty string. A failure raised from a throwing component carries the original as cause, so the underlying fault is never swallowed.

Functions

Type Aliases

websocket-plugin/src/index.ts

Examples

Example 1

import { createApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';
import { WebSocketPlugin } from '@setu-ts/websocket-plugin';
import { CAPABILITIES, type IWebSocketService } from '@setu-ts/common';

const app = createApplication({
  plugins: [RuntimePlugin(), WebSocketPlugin({ heartbeatMs: 30_000 })],
});

const ws = app.services.get<IWebSocketService>(CAPABILITIES.WEBSOCKET);
ws.route('/ws/chat', {
  onOpen: (conn, { query }) => {
    conn.data.set('room', query.room ?? 'lobby');
    ws.room(query.room ?? 'lobby').add(conn);
  },
  onMessage: (conn, data) => {
    ws.room(conn.data.get('room') as string).broadcast(data, { except: conn });
  },
});

await app.start({ port: 3000 });

Classes

c
HeartbeatSweeper(
runtime: IRuntimeServices,
options: HeartbeatOptions,
connections: () => Iterable<WebSocketConnection>
)

Sends heartbeats and closes idle connections on one shared interval.

  • isRunning(): boolean

    Whether the interval is currently running.

  • start(): void

    Starts the interval. A no-op when heartbeats are disabled, so a plugin left at its defaults never creates a timer.

  • stop(): void

    Stops the interval. Idempotent.

  • tick(): void

    Runs one sweep: closes connections that have been silent too long, then sends the heartbeat payload to the rest.

c
Room(
name: string,
listener?: RoomMembershipListener,
publish?: RoomPublisher
)

A named group of connections that can be addressed as one.

c
RoomRegistry(
publish?: RoomPublisher,
onMemberJoined?: () => void
)

Owns the set of live rooms, creating them on demand and dropping them once empty.

c
WebSocketConnection(
id: string,
path: string,
transport: IWebSocketTransport,
now: number,
heartbeat?: boolean
)

A live WebSocket connection.

c
WebSocketService(
runtime: IRuntimeServices,
options: ResolvedOptions,
available: boolean,
logger?: ILogger,
backplane?: IRealtimeBackplane,
behaviors?: readonly IIngressBehavior[]
)

The WebSocket hub.

c
WebSocketUnavailableError(message?: string)

Thrown when a WebSocket route is registered but the application's HTTP adapter provides no upgrade seam, so no handshake could ever succeed.

c
WsRouteTable

The registered WebSocket routes.

Functions

f
frameByteLength(data: string | Uint8Array): number

Measures an inbound frame in bytes.

f
parseRequestedProtocols(header: string | null): readonly string[]

Parses a Sec-WebSocket-Protocol header into its comma-separated tokens.

f
resolveOptions(options?: WebSocketPluginOptions): ResolvedOptions

Applies defaults and rejects a configuration that cannot work.

Interfaces

I
HeartbeatOptions

Configuration for the sweeper.

I
IWebSocketConnection

A live WebSocket connection, as seen by application code.

I
IWebSocketService

Service contract for the WebSocket hub — registered by the WebSocketPlugin under CAPABILITIES.WEBSOCKET.

I
IWebSocketTransport

The runtime-native socket, normalized to the two operations the framework needs. Implemented by each HTTP adapter's upgrader over its platform socket (Deno.upgradeWebSocket's WebSocket, a ws socket on Node, Bun's ServerWebSocket, the server half of a Workers WebSocketPair).

I
LocalBroadcastOptions

Options for Room.broadcastLocal.

I
RoomBroadcastOptions

Options for a room broadcast.

I
RoomMembershipListener

Notified whenever a connection joins or leaves a Room.

I
WebSocketCloseEvent

Payload of a WebSocket close, normalized across runtimes.

  • code: number

    The RFC 6455 close code (e.g. 1000 normal, 1001 going away).

  • reason: string

    The close reason; an empty string when the peer supplied none.

I
WebSocketConnectionContext

Details of the upgrade request that opened a connection, handed to WebSocketHandlers.onOpen.

  • headers: Headers

    The upgrade request headers — read these to authenticate the peer.

  • path: string

    The URL path component (no query string).

  • protocol: string

    The negotiated subprotocol, when one was selected.

  • query: Readonly<Record<string, string>>

    Query string parameters.

  • url: string

    The full upgrade request URL.

  • user: IPrincipal

    The authenticated principal, when one authenticated the upgrade. Populated by threading ctx.request.user through IWebSocketService.routeUpgrade; omitted when the upgrade was not authenticated. Read this in onOpen to identify the peer rather than re-deriving it from the headers.

I
WebSocketEventSink

The callbacks an HTTP adapter drives once it has completed a handshake. The WebSocket plugin builds one sink per accepted upgrade and hands it to the adapter inside the accept decision; the adapter binds its native socket events to these methods.

I
WebSocketHandlers

The lifecycle callbacks an application supplies per WebSocket route.

I
WebSocketPluginOptions

Configuration for WebSocketPlugin.

  • behaviors: readonly (IIngressBehavior | RegistryFactory<IIngressBehavior>)[]

    Plugin-level ingress behaviours wrapped around every route's onMessage — the WebSocket arm of the transport-neutral behaviour chain shared with the queue, scheduler, and messaging plugins (IIngressBehavior in @setu-ts/common).

  • heartbeatMs: number

    Interval in milliseconds at which WebSocketPluginOptions.heartbeatPayload is sent to every open connection. 0 (the default) disables the heartbeat entirely and creates no timer.

  • heartbeatPayload: string

    The text frame sent on each heartbeat tick. Defaults to 'ping'. Read only when WebSocketPluginOptions.heartbeatMs is above 0.

  • idleTimeoutMs: number

    Milliseconds of inbound silence after which a connection is closed with code 1001. 0 (the default) disables idle closing.

  • maxConnections: number

    Maximum number of simultaneously open connections across all routes. 0 (the default) means unlimited. At the limit, further upgrade requests are refused with HTTP 503 before any socket is created.

  • maxMessageBytes: number

    Maximum size in bytes of a single inbound frame. 0 (the default) means unlimited. A larger frame closes the connection with code 1009 (message too big) and is never delivered to onMessage.

  • routes: readonly WebSocketRouteEntry[]

    Routes registered declaratively, as an alternative to calling service.route(...) imperatively after start(). Each entry — instance or RegistryFactory — produces one route() call, so a route can be declared where the plugin is composed instead of after the application has started.

  • scalingNotice: boolean

    Whether to log one info line at registration when no realtime backplane is registered, stating that rooms broadcast in-process only. Defaults to true.

I
WebSocketRoom

A named broadcast group of connections — the bidirectional analogue of the SSE plugin's channels.

I
WebSocketRouteDefinition

The declarative form of one IWebSocketService.route() call — the entry an application writes instead of calling route() imperatively after start().

I
WebSocketRouteOptions

Per-route configuration supplied alongside the handlers.

  • guards: readonly WebSocketUpgradeGuard[]

    Guards evaluated before this route's WebSocket handshake is accepted.

  • heartbeat: boolean

    Whether this route participates in the shared heartbeat sweep.

  • protocols: readonly string[]

    Subprotocols this route accepts. When non-empty, the first client-requested protocol appearing in this list is echoed back and any request whose Sec-WebSocket-Protocol matches none of them is rejected with 400. When omitted, no protocol is negotiated and none is echoed.

I
WsRoute

One registered WebSocket route.

Type Aliases

T
T
WebSocketReadyState = "connecting" | "open" | "closing" | "closed"

Lifecycle state of a WebSocket, normalized across runtimes to names rather than the numeric codes the web API uses.

T
WebSocketRouteEntry =
WebSocketRouteDefinition
| RegistryFactory<WebSocketRouteDefinition>

One entry of WebSocketPluginOptions.routes: a route definition, or a RegistryFactory producing one when the handlers need a resolved capability.

T
WebSocketUpgradeRouter = (request: Request) => Promise<WebSocketUpgradeDecision | null>

Consulted by an HTTP adapter for every inbound WebSocket upgrade request.

Variables

v
CAPABILITIES: { RUNTIME: string; LOGGER: string; CONFIG: string; VALIDATION: string; DATABASE: string; CACHE: string; EVENTS: string; MESSAGING: string; AUTH: string; AUTHORIZATION: string; JWT: string; SCHEDULER: string; METRICS: string; HEALTH: string; OPENAPI: string; TELEMETRY: string; SECRETS: string; AUDIT: string; RESILIENCE: string; STORAGE: string; MAIL: string; NOTIFICATION: string; FEATURE_FLAGS: string; QUEUE: string; CQRS: string; COMMAND_BUS: string; QUERY_BUS: string; MULTI_TENANCY: string; WORKER_POOL: string; DI_CONTAINER: string; HTTP_ADAPTER: string; SSE: string; WEBSOCKET: string; REALTIME_BACKPLANE: string; SSR: string; SESSION: string; SERVICE_DISCOVERY: string; HEALTH_INDICATOR: string; METRIC_REGISTRATION: string; OPENAPI_SCHEMA: string; CLI_COMMAND: string; DECORATOR_HANDLER: string; METADATA_STORE: string; GRPC: string; CLOUDFLARE: string; GRAPHQL: string; STATIC_FILES: string; VIEW: string; }

Standard capability tokens provided by the first-party plugins.

worker-pool-plugin/src/index.ts

Classes

c
WorkerExitError(
taskModule: string,
code: number | null
)

Thrown into a task's promise when its worker's THREAD ENDED while the task was in flight — a clean self-termination (process.exit() inside the worker, or self.close() on runtimes that report it) as much as an abrupt one.

c
WorkerPoolService(
options: WorkerPoolPluginOptions | undefined,
runtime: IRuntimeServices,
collector?: WorkerPoolCollector
)

The worker pool service registered under CAPABILITIES.WORKER_POOL.

c
WorkerPoolUnavailableError(message?: string)

Thrown by run() when the runtime provides no worker support (no IRuntimeServices.workers and no injected host) — e.g. Cloudflare Workers.

c
WorkerQueueFullError(
taskModule: string,
limit: number
)

Thrown by run() when the pool's pending queue is at its bound, shedding the task instead of growing memory without limit.

c
WorkerTaskError(
taskModule: string,
remote: WorkerErrorShape
)

Thrown by run() when the task handler threw on the worker, or when the worker crashed while the task was in flight. Carries the remote error's serialized shape.

c
WorkerTaskTimeoutError(
taskModule: string,
timeoutMs: number
)

Thrown by run() when a task exceeds its timeout. The worker running the task is terminated and replaced — in-flight JavaScript cannot be cancelled.

Functions

Interfaces

I
TaskPoolOptions

Per-task-module pool overrides, keyed by task-module specifier in WorkerPoolPluginOptions.pools.

  • maxQueue: number

    Pending-queue bound for this pool; overrides the plugin maxQueue.

  • size: number

    Workers in this pool; overrides defaultPoolSize.

  • taskTimeoutMs: number

    Task timeout in milliseconds for this pool; overrides the plugin taskTimeoutMs. 0 disables the timeout.

I
WorkerPoolPluginOptions

Options for WorkerPoolPlugin.