Audit service backed by an IAuditStorage port.
-
log(entry: AuditEntry): Promise<void>
Appends an entry to the audit trail. Entries are immutable once written.
Database-backed audit storage. Requires an injected IAuditDbClient
at construction time.
-
append(entry: StoredAuditEntry): Promise<void>
Appends one row via
client.insert. -
close(): Promise<void>
The injected client owns the connection lifecycle; nothing to drain here.
-
isHealthy(): Promise<boolean>
Probes the injected client with a
selectthat matches nothing. -
isReady(): boolean
Database storage is always ready once constructed.
-
query(criteria?: AuditQuery): Promise<StoredAuditEntry[]>
Selects rows via
client.select, filters, maps to frozen entries.
File-backed audit storage. Writes JSONL to path via runtime.fs.
-
append(entry: StoredAuditEntry): Promise<void>
Read-modify-write with serialized in-process appends via
_lock. Cross-process file contention is inherent to the OS file and not solved here. -
close(): Promise<void>
Awaits the serialized write chain so no in-flight append is lost on close.
-
isHealthy(): Promise<boolean>
Reports whether the audit file's sink is reachable.
-
isReady(): boolean
File storage is always ready once constructed (we don't probe the FS).
-
query(criteria?: AuditQuery): Promise<StoredAuditEntry[]>
Reads and filters lines via
matchAuditQuery.
Logs audit records through an ILogger. When constructed without a logger
and used as a storage backend, queries return empty arrays.
-
append(entry: StoredAuditEntry): Promise<void>
Routes the frozen record to
logger[level]('audit', record). -
close(): Promise<void>
The logger owns its own flush lifecycle; nothing to drain here.
-
isHealthy(): Promise<boolean>
Lifecycle truth: the sink is the resolved
ILogger, which is in-process, so reachability IS readiness. Where that logger's own transport goes is the logger's health to report, not this backend's. -
isReady(): boolean
Ready as long as a logger is configured.
-
query(_criteria?: AuditQuery): Promise<StoredAuditEntry[]>
The log sink is the durable trail; read-back happens through the logging backend, not this object. Returns
[]. -
setContextLogger(logger: ILogger): void
Initializes the logger from context when not injected.
-
setLogLevel(level: LogLevel): void
Sets the log level for emitting audit records.
In-memory audit storage backed by an array. Stores already-frozen records;
isReady() always returns true. Non-durable across restarts.
-
append(entry: StoredAuditEntry): Promise<void>
Appends a (already frozen) entry.
-
close(): Promise<void>
No buffered state — appends complete synchronously.
-
isHealthy(): Promise<boolean>
Lifecycle truth: an in-process array has no separate sink to reach, so reachability IS readiness — the process either holds the entries or it does not.
-
isReady(): boolean
Whether the storage is ready to accept writes.
-
query(criteria?: AuditQuery): Promise<StoredAuditEntry[]>
Filters entries via
matchAuditQuery, then orders ascending by timestamp and applieslimit(newest) viaorderAndLimit.
AuditPlugin factory — registers an IAuditLogger under CAPABILITIES.AUDIT.
One immutable audit trail entry.
-
action: string
The action performed (e.g.
"user.delete"). -
after: Readonly<Record<string, unknown>>
Resource state after the action.
-
before: Readonly<Record<string, unknown>>
Resource state before the action.
-
metadata: Readonly<Record<string, unknown>>
Additional context (IP, request ID, …).
-
resource: string
The resource kind acted on (e.g.
"user"). -
resourceId: string
The specific resource instance, when applicable.
-
result: "success" | "failure"
Whether the action succeeded.
-
userId: string
The acting principal's ID.
Options accepted by the AuditPlugin factory.
-
options: AuditStorageOptions
Backend-specific options.
-
storage: AuditStorageType
Storage backend selector; default
'memory'.
Query criteria for IAuditStorage.query. Every field is optional
and combines as AND. An omitted field does not constrain.
-
action: string
Matches entries whose
actionequals this value exactly. -
from: number
Lower time bound, inclusive (epoch ms).
-
limit: number
Cap on returned count, applied after filtering and ordering.
-
resource: string
Matches entries whose
resourceequals this value exactly. -
resourceId: string
Matches entries whose
resourceIdequals this value exactly. -
result: "success" | "failure"
Matches entries whose outcome equals this value.
-
to: number
Upper time bound, inclusive (epoch ms).
-
userId: string
Matches entries whose
userIdequals this value exactly.
Options passed to individual storage backends.
-
client: IAuditDbClient
Injected database client for
DatabaseAuditStorage. -
level: "info" | "warn" | "error"
Logger method to emit at (
'info'/'warn'/'error'); default'info'. -
logger: ILogger
Injected
ILoggerforLogAuditStorage; overridesctx.logger. -
path: string
JSONL file path for
FileAuditStorage; defaults to'./audit.log'. -
table: string
Table name for
DatabaseAuditStorage; defaults to'audit_logs'.
Structural shape of an injected database client facade. The DB backend is
inject-only — it never touches the database capability token.
Immutable audit trail writer.
-
log(entry: AuditEntry): Promise<void>
Appends an entry to the audit trail. Entries are immutable once written.
A stored audit record extends AuditEntry with an internally
assigned id (UUID v4) and timestamp (wall-clock epoch ms).
-
action: string
The audited action (e.g.
'user.login'). -
after: Readonly<Record<string, unknown>> | undefined
Resource state after the operation, when captured.
-
before: Readonly<Record<string, unknown>> | undefined
Resource state before the operation, when captured.
-
id: string
Internally assigned unique identifier (UUID v4).
-
metadata: Readonly<Record<string, unknown>> | undefined
Free-form structured context attached by the caller.
-
resource: string
The audited resource type (e.g.
'session'). -
resourceId: string | undefined
The affected resource instance identifier, when known.
-
result: "success" | "failure"
Whether the audited operation succeeded or failed.
-
timestamp: number
Wall-clock epoch milliseconds, assigned by the storage at append.
-
userId: string | undefined
The acting principal's identifier, when authenticated.
Storage backend identifier — closed union.
Example 1
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 });
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
instanceofacross realms.
Single-process access-token revocation store with bounded lazy expiry work.
-
isRevoked(jti: string): Promise<boolean>
Return whether an access-token identifier is currently revoked.
-
revoke(): Promise<void>jti: string,expiresAt: number
Record an access-token identifier as revoked until its expiry timestamp.
In-memory implementation of RateLimitStore.
-
increment(): Promise<RateLimitResult>key: string,windowMs: number
Increment the counter for the given key within its window. Creates the window if it does not exist.
-
reset(key: string): Promise<void>
Reset the counter for the given key.
In-memory implementation of RefreshTokenStore.
-
get(jti: string): Promise<RefreshTokenRecord | null>
Retrieve a record by jti; returns null if missing or expired. A revoked record is still returned so the caller can distinguish replay of a rotated token from an unknown token.
-
revoke(jti: string): Promise<void>
Revoke a token by jti.
-
revokeFamily(jti: string): Promise<readonly RefreshTokenRecord[]>
Revoke every refresh token in the requested token's family.
-
rotate(): Promise<IRefreshTokenRotation>jti: string,successor: RefreshTokenRecord
Atomically consume a live refresh token and persist its successor.
-
save(record: RefreshTokenRecord): Promise<void>
Store or update a refresh token record.
Password hasher using PBKDF2-SHA256 via Web Crypto.
-
hash(secret: string): Promise<string>
Hash a secret (password) with a random salt.
-
verify(): Promise<boolean>stored: string,secret: string
Verify a secret against a stored hash.
Redis-backed rate limit store implementation.
-
disconnect(): Promise<void>
Close the Redis connection (calls QUIT).
-
increment(): Promise<RateLimitResult>key: string,windowMs: number
Increment the counter for the given key within its window. Creates the window if it does not exist.
-
reset(key: string): Promise<void>
Reset the counter for the given key.
Refresh token service implementing token rotation and revocation.
-
issue(principal: IPrincipal): Promise<TokenPair>
Issue a new access + refresh token pair for the given principal.
-
refresh(refreshToken: string): Promise<TokenPair | null>
Refresh a token pair: verify the refresh token, revoke its jti, and issue a new pair (rotation). Returns null if the token is invalid, expired, tampered with, not a refresh token, or already revoked (replay).
-
revoke(refreshToken: string): Promise<boolean>
Revoke a refresh token (logout). Returns true if a live record was found and revoked; false when the token does not verify or no live record exists (missing, expired, or already revoked).
Authentication middleware that runs passive strategies and populates ctx.request.user. Always calls next() - it authenticates only, does not authorize.
AuthPlugin factory.
Default rate-limit key, in order of preference:
Guard that allows public access (always continues). Useful for explicitly marking routes as public when auth middleware is global.
Rate limiting middleware factory.
Guard that requires all of the specified permissions. Returns 401 if no principal, 403 if any missing.
Guard that requires any of the specified roles. Returns 401 if no principal, 403 if none match.
Guard that requires authentication. Returns 401 if no principal.
Guard that requires a specific permission. Returns 401 if no principal, 403 if insufficient permission.
Guard that requires a specific role. Returns 401 if no principal, 403 if insufficient role.
API key configuration options.
-
header: string
Header name for API key (default: 'X-API-Key').
-
validate: (key: string) => Promise<IPrincipal | null>
Callback to validate the API key and return a principal. Return
nullif the key is invalid.
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
sessioncapability (SessionPlugin) to be registered. -
strategies: readonly IAuthStrategy[]
Caller-supplied strategies, appended after every built-in in declaration order. A strategy whose
namecollides with any other strategy in the assembled chain makesregister()throw.
Store for access-token identifiers revoked before their JWT expiry.
-
isRevoked(jti: string): Promise<boolean>
Return whether an access-token identifier is currently revoked.
-
revoke(): Promise<void>jti: string,expiresAt: number
Record an access-token identifier as revoked until its expiry timestamp.
Authentication service that coordinates strategies and provides credential verification for login flows.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Run configured passive strategies to authenticate a request.
-
verifyCredentials(credentials: { readonly identifier: string; readonly secret: string; }): Promise<IPrincipal | null>
Verify credentials for a login flow (e.g., username/password).
Authentication strategy interface. Implementations extract credentials
from a request and return a principal, or null if the strategy
does not apply.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Attempt to authenticate the request.
-
name: string
Strategy name for identification.
JWT sign/verify service.
-
decode<T = Readonly<Record<string, unknown>>>(token: string): T | null
Decodes a token without verifying it. Never trust the result for authorization decisions.
-
sign(): Promise<string>payload: Readonly<Record<string, unknown>>,options?: JwtSignOptions
Signs a payload into a JWT.
-
verify<T = Readonly<Record<string, unknown>>>(token: string): Promise<T>
Verifies a token's signature and validity window.
The authenticated identity attached to a request by authentication middleware.
-
claims: Readonly<Record<string, unknown>>
Additional claims from the credential.
-
id: string
Stable subject identifier.
-
permissions: readonly string[]
Permission names held by the principal.
-
roles: readonly string[]
Role names held by the principal.
JWT configuration options.
-
accessTokenRevocationStore: IAccessTokenRevocationStore
Optional shared store that rejects revoked typed access credentials. Supply the same instance to
RefreshTokenServicefor logout invalidation. -
algorithm: "HS256" | "RS256"
Algorithm to use. Inferred from key material if omitted.
-
audience: string
Expected audience for verification.
-
header: string
Header name for token extraction (default: 'authorization').
-
issuer: string
Expected issuer for verification.
-
privateKey: string
Private key for RS256 signing (PEM format). Required if HS256 secret not provided.
-
publicKey: string
Public key for RS256 verification (PEM format). Required for RS256 verification.
-
scheme: string
Token scheme prefix (default: 'bearer').
-
secret: string | Uint8Array
Secret key for HS256 algorithm. Required if RS256 keys not provided.
Options accepted when signing a JWT.
-
audience: string
Token audience.
-
expiresIn: string
Token lifetime (e.g.
"1h","7d"). -
issuer: string
Token issuer.
Local (credentials) configuration options.
-
verify: () => Promise<IPrincipal | null>identifier: string,secret: string
Callback to verify credentials (e.g., username/password). Return
nullif credentials are invalid.
Options for rate limiting middleware.
-
exclude: readonly PathPattern[]
Paths exempted from the limiter, matched against
IRequest.path. A string is an EXACT match; aRegExpis tested against the path. -
keyGenerator: (ctx: IRequestContext) => string
Key generator function. Defaults to
defaultRateLimitKey, which prefers the authenticated principal, then the client IP published byipSecurityMiddleware, thenIRequest.ip, and only then'anonymous'. -
max: number
Max requests per window per key.
-
message: string
Message returned in the 429 body.
-
standardHeaders: boolean
Emit standard RateLimit-* headers (default: true).
-
store: RateLimitStore
Custom store implementation. If omitted, a MemoryRateLimitStore is built lazily.
-
windowMs: number
Time window in milliseconds.
Result of incrementing a rate limit counter.
-
count: number
Request count in the current window.
-
resetTime: number
Absolute timestamp (ms since epoch) when the window resets.
Store interface for rate limiting.
-
increment(): Promise<RateLimitResult>key: string,windowMs: number
Increment the counter for the given key within its window. Creates the window if it does not exist.
-
reset(key: string): Promise<void>
Reset the counter for the given key.
RBAC configuration for role hierarchy and permissions.
-
roles: Readonly<Record<string, RoleDefinition>>
Role definitions keyed by role name.
Options for constructing a RefreshTokenService.
-
accessToken: { readonly expiresIn?: string; readonly audience?: string; readonly issuer?: string; }
Optional access token options (passed through to jwt.sign).
-
accessTokenRevocationStore: IAccessTokenRevocationStore
Optional shared store for invalidating paired access tokens at logout or refresh-token replay. Requires
accessToken.expiresInso entries remain bounded. -
jwt: IJwtService
The JWT service used to sign/verify tokens.
-
refreshTokenExpiresIn: string
Refresh token lifetime (default: '7d').
-
runtime: IRuntimeServices
Runtime services for random bytes and clock.
-
store: RefreshTokenStore
The store backing refresh tokens.
A refresh token record stored on the server.
-
accessTokenExpiresAt: number
Absolute expiry timestamp for the paired access token.
-
accessTokenJti: string
Identifier of the paired access token, when issued by the current service.
-
expiresAt: number
Absolute expiry timestamp (ms since epoch).
-
familyId: string
Family identifier shared by a rotated refresh-token lineage.
-
jti: string
Unique token identifier (from JWT jti claim).
-
principal: IPrincipal
Snapshot of the principal at issue time.
-
principalId: string
Principal ID the token belongs to.
-
revoked: boolean
Whether the token has been revoked.
Store interface for refresh tokens.
-
get(jti: string): Promise<RefreshTokenRecord | null>
Retrieve a record by jti; returns null if missing or expired. A revoked record is still returned so the caller can distinguish replay of a rotated token from an unknown token.
-
revoke(jti: string): Promise<void>
Revoke a token by jti.
-
revokeFamily(jti: string): Promise<readonly RefreshTokenRecord[]>
Revoke every refresh token in the requested token's family.
-
rotate(): Promise<IRefreshTokenRotation>jti: string,successor: RefreshTokenRecord
Atomically consume a live refresh token and persist its successor.
-
save(record: RefreshTokenRecord): Promise<void>
Store or update a refresh token record.
Role definition for RBAC configuration.
-
inherits: readonly string[]
Role names this role inherits from (transitive).
-
permissions: readonly string[]
Permissions granted by this role.
Session authentication configuration options.
-
toPrincipal: (view: SessionView) => IPrincipal | null
Maps an opened session to the principal it carries. Return
nullwhen the session holds no identity — the strategy chain then continues.
A pair of access + refresh tokens issued together.
-
accessToken: string
Short-lived access token.
-
refreshToken: string
Refresh token (signed JWT with type:'refresh' and jti).
| { readonly record: RefreshTokenRecord | null; readonly rotated: false; }
Result of atomically rotating one refresh token into its successor.
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.
The namespace RedisRateLimitStore prepends to every key when no
keyPrefix is supplied.
Service layer that delegates to a backend CacheStore while applying:
-
clear(): Promise<void>
Delegates to the backend's
clear(), which uses the construction-time prefix to scope the deletion. CacheService does not prepend a key here sinceclear()takes no key argument. -
delete(key: string): Promise<boolean>
Removes a cached value.
-
get<T>(key: string): Promise<T | null>
Reads a cached value.
-
getOrSet<T>(): Promise<T>key: string,factory: () => Promise<T>,ttlSeconds?: number
Reads a cached value or produces and stores it once for all concurrent callers of this service and key.
-
has(key: string): Promise<boolean>
Reports whether a live entry exists.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Stores a value.
In-memory cache implementation with LRU eviction and lazy TTL expiry.
-
clear(): Promise<void>
Remove all entries scoped to this backend's prefix.
-
connect(): Promise<void>
Establish the backend connection (if applicable).
-
delete(key: string): Promise<boolean>
Delete a value. The key is already-prefixed by CacheService.
-
disconnect(): Promise<void>
Gracefully disconnect.
-
get<T>(key: string): Promise<T | null>
Read a value. The key is already-prefixed by CacheService.
-
has(key: string): Promise<boolean>
Check existence. The key is already-prefixed by CacheService.
-
isHealthy(): Promise<boolean>
Lifecycle truth (M90b): an in-process Map has no separate backend to reach, so reachability IS readiness — the process either holds the map or it does not.
-
isReady(): boolean
Reports whether the backend is ready for operations.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Write a value. The key is already-prefixed by CacheService.
No-op implementation of CacheStore. Every method resolves without side
effects: reads return null/false, writes resolve void, and lifecycle
methods are no-ops.
-
clear(): Promise<void>
Remove all entries scoped to this backend's prefix.
-
connect(): Promise<void>
Establish the backend connection (if applicable).
-
delete(_key: string): Promise<boolean>
Delete a value. The key is already-prefixed by CacheService.
-
disconnect(): Promise<void>
Gracefully disconnect.
-
get<T>(_key: string): Promise<T | null>
Read a value. The key is already-prefixed by CacheService.
-
has(_key: string): Promise<boolean>
Check existence. The key is already-prefixed by CacheService.
-
isHealthy(): Promise<boolean>
Lifecycle truth (M90b): the no-op backend stores nothing, so the only honest reachability answer is whether the store is connected.
-
isReady(): boolean
Reports whether the backend is ready for operations.
-
set<T>(): Promise<void>_key: string,_value: T,_ttlSeconds?: number
Write a value. The key is already-prefixed by CacheService.
Redis-backed cache store implementation.
-
clear(): Promise<void>
Remove all entries scoped to this backend's prefix.
-
connect(): Promise<void>
Establish the backend connection (if applicable).
-
delete(key: string): Promise<boolean>
Delete a value. The key is already-prefixed by CacheService.
-
disconnect(): Promise<void>
Gracefully disconnect.
-
get<T>(key: string): Promise<T | null>
Read a value. The key is already-prefixed by CacheService.
-
has(key: string): Promise<boolean>
Check existence. The key is already-prefixed by CacheService.
-
isHealthy(): Promise<boolean>
Probes Redis with a typed
ping()(M90b).falseafter disconnect — a store with no client cannot answer — and otherwisetrueonly when the server answers, a rejection being unreachability. -
isReady(): boolean
Reports whether the backend is ready for operations.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Write a value. The key is already-prefixed by CacheService.
Create a caching middleware function.
Creates the CachePlugin.
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.
-
body: string | null
Body content (decoded string or base64-encoded bytes).
-
bodyEncoding: "base64"
Present when the body was base64-encoded during storage. The replay helper decodes it back to
Uint8Array. -
headers: Array<[string, string]>
Headers as
[name, value]pairs. -
status: number
HTTP status code.
Options for the transparent response-caching middleware.
-
bypass: (ctx: IRequestContext) => boolean
Bypass function — when
true, skip caching entirely for this request and pass through to the handler. -
cacheableStatuses: number[]
HTTP status codes eligible for caching. Defaults to
[200]. -
key: (ctx: IRequestContext) => string
Custom cache key generator. Defaults to
${request.method}:${request.url}. -
store: string
Capability token for the cache store to use. Defaults to
CAPABILITIES.CACHE. -
ttlSeconds: number
Per-route TTL override in seconds.
-
vary: (ctx: IRequestContext) => readonly string[]
Per-request discriminator values appended to the cache key after the tenant segment. Each returned string is length-prefixed and joined in order, so two requests differing in any value never share an entry. Omitted leaves the key unchanged.
Options for the CachePlugin factory.
-
name: string
Plugin instance name for multi-cache setups. Derives the capability token as
cache.<name>when not'default'. -
options: CacheStoreOptions
Store-specific options.
-
store: CacheStoreType
Store backend type. Defaults to
'memory'.
Options for creating a cache store backend.
-
client: IRedisClient
Injected ioredis-compatible client (bypasses lazy import).
-
defaultTtl: number
Default TTL in seconds when
setomits ttlSeconds. -
maxSize: number
Maximum entry count for MemoryStore LRU eviction.
-
prefix: string
Key prefix applied to all cache keys.
-
url: string
Redis connection URL (used when store is
'redis').
Key/value cache with per-entry TTL.
-
clear(): Promise<void>
Removes every entry (respecting the store's key prefix, if configured).
-
delete(key: string): Promise<boolean>
Removes a cached value.
-
get<T>(key: string): Promise<T | null>
Reads a cached value.
-
has(key: string): Promise<boolean>
Reports whether a live entry exists.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Stores a value.
Structural shape of an ioredis-compatible client. Used for validation and injection so that the plugin does not hard-depend on ioredis.
-
connect(): Promise<void>
Establish the connection.
-
del(...keys: string[]): Promise<number>
Delete one or more keys. Returns the count of removed keys.
-
exists(key: string): Promise<number>
Check if a key exists. Returns
1or0. -
get(key: string): Promise<string | null>
Get a string value by key. Returns
nullwhen missing. -
ping(): Promise<string>
Pings the server (M90b). The Redis store's reachability probe invokes it; a
PONGresponse proves the backend is reachable, and a rejection does not. The real ioredis client implements it. -
quit(): Promise<void>
Gracefully close the connection.
-
scan(): Promise<[string, string[]]>cursor: string,matcher: string,matchValue?: string
Cursor-based scan. Returns
[cursor, keys[]]. Use'0'to start and continue until cursor returns'0'. -
set(): Promise<string | null>key: string,value: string,ttlMode?: "EX",ttlSeconds?: number
Set a key with optional TTL.
Supported cache store backends.
Example 1
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, });
Derive all five naming forms from a raw input string.
Detects the @setu-ts packages a project depends on.
Parses argv, runs the requested command, and returns its exit code.
Everything the CLI reaches the outside world through.
-
ask: Prompter
Asks the questions
setu newalready accepts as flags. -
cwd: string
The working directory commands resolve relative paths against (absolute).
-
error: (message: string) => void
Writes a line of error output.
-
fs: IFileSystem
The filesystem all reads and writes go through.
-
load: ModuleLoader
Loads a custom schematic module; defaults to a real dynamic
import(). -
loadApp: AppLoader
Loads the target project's
setu.config.ts; defaults to a real dynamicimport(). Only the plugin-command paths use it. -
log: (message: string) => void
Writes a line of normal output.
-
now: () => number
Wall-clock milliseconds, for timestamped output.
-
portAvailable: PortProbe
Checks whether a workspace port can bind before the CLI assigns it.
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).
One file a schematic asks the command layer to create.
-
contents: string
The file contents.
-
managed: boolean
Marks a file the CLI owns outright and regenerates, exempting it from the overwrite refusal in
findExisting. -
path: string
Path to write, relative to the command's target directory.
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.
Asks the scaffold questions setu new accepts as flags.
-
select(): Promise<string | undefined>question: string,choices: readonly PromptChoice[]
Asks one question and reports the chosen value.
Options handed to every schematic.
-
artifacts: Readonly<Record<string, readonly string[]>>
The generated artifacts already present in the project, keyed by the schematic name that emits them (
{ 'health-indicator': ['external-api'] }). -
legacyModules: readonly string[]
Pre-module-declaration directories that retain the old controller/service barrel exports until their application converts to
MODULES. -
migrations: readonly string[]
The migrations already present, oldest first.
-
modules: readonly string[]
The domain modules already present under
src/modules/, sorted. -
now: () => number
Wall-clock milliseconds, injected so timestamped output (the migration schematic) is deterministic under test.
-
plugins: ReadonlySet<string>
The
@setu-tspackages detected in the target project. -
runtime: TargetRuntime
The project's runtime target, so a schematic can shape platform-specific output.
Loads the project's config module by URL.
Loads an ES module by absolute URL.
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.
A project template accepted by setu new --template.
The name of the CLI executable.
The setu executable entry point.
Example 1
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 };
A binding the configuration names is absent from the Worker's env, or is
present with the wrong shape.
-
absent(): CloudflareBindingMissingErrorbinding: string,available: readonly string[]
Builds the error for a binding that is absent entirely.
-
name: string
Discriminating name for
instanceof-free checks. -
wrongShape(): CloudflareBindingMissingErrorbinding: string,expected: string
Builds the error for a binding that is present with the wrong shape.
An R2 object read found nothing.
-
name: string
Discriminating name for
instanceof-free checks.
A responder threw, and its failure was relayed to the caller.
-
name: string
Discriminating name for
instanceof-free checks.
A brokered request received no reply within its budget.
-
name: string
Discriminating name for
instanceof-free checks.
The requested operation has no counterpart on the Cloudflare binding.
-
name: string
Discriminating name for
instanceof-free checks.
A database backend over a Cloudflare D1 binding.
- beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
- connect(): Promise<void>
- createDataSource(entity: string): IDataSource
- disconnect(): Promise<void>
- isReady(): boolean
-
rawQuery<T>(): Promise<T[]>sql: string,params?: unknown[]
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
D1's deferred batch transaction has no isolation-level surface.
Serializes lock acquisition for one key.
-
fetch(request: Request): Promise<Response>
Routes one lock operation.
Carries RealtimeFrames between replicas over one WebSocket to a
Durable Object.
-
close(): Promise<void>
Closes the socket and drops every handler.
-
connect(): Promise<void>
Opens the socket to the Durable Object. Idempotent and concurrency-safe.
-
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed replica.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other replicas.
A distributed lock backed by one Durable Object per key.
-
acquire(): Promise<string | null>key: string,ttlMs: number
Attempts to acquire the lock.
-
release(): Promise<void>key: string,token: string
Releases a previously acquired lock.
A cache store backed by Workers KV.
-
clear(): Promise<void>
Removes every key this store owns.
-
delete(key: string): Promise<boolean>
Removes a cached value.
-
get<T>(key: string): Promise<T | null>
Reads a cached value.
-
has(key: string): Promise<boolean>
Reports whether a live entry exists.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Stores a value.
A session store backed by Workers KV.
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
Object storage backed by Cloudflare R2.
-
delete(path: string): Promise<boolean>
Deletes an object.
-
exists(path: string): Promise<boolean>
Reports whether an object exists.
-
get(path: string): Promise<Uint8Array>
Retrieves an object.
-
getSignedUrl(): Promise<string>path: string,_options: SignedUrlOptions
Always throws — R2 bindings cannot presign.
-
getStream(path: string): Promise<ReadableStream<Uint8Array>>
Streams an object without buffering it.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Writes an object, translating
PutObjectOptionsinto R2's own spelling: the content type lives underhttpMetadata, user metadata undercustomMetadata. Without this every object was served asapplication/octet-stream(X8-6).
Fans one replica's broadcast out to every other connected replica.
-
fetch(request: Request): Promise<Response>
Answers a replica's WebSocket upgrade.
-
webSocketClose(): voidsocket: IDurableObjectWebSocket,code: number,reason: string
Handles a replica disconnecting.
-
webSocketError(socket: IDurableObjectWebSocket): void
Handles a socket error.
-
webSocketMessage(): voidsender: IDurableObjectWebSocket,message: string | ArrayBuffer
Re-broadcasts one replica's message to every other connected replica.
Delivers RPC replies to the caller waiting on them.
-
fetch(request: Request): Promise<Response>
Serves both halves of the inbox.
-
webSocketClose(): voidsocket: IDurableObjectWebSocket,code: number,reason: string
Handles the caller disconnecting.
-
webSocketError(socket: IDurableObjectWebSocket): void
Handles a socket error.
A message broker backed by Cloudflare Queues.
-
connect(): Promise<void>
No-op: a producer binding is ready as soon as the Worker has its
env, and there is no connection to open. -
disconnect(): Promise<void>
Closes the reply inbox, rejects every in-flight request, and drops every subscription.
-
dispatch(batch: IQueueMessageBatch): Promise<void>
Dispatches one delivered batch into the registered subscribers and responders.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request and awaits its single correlated reply.
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
A registry of Cron Trigger handlers, keyed by cron expression.
-
dispatch(controller: IScheduledController): Promise<void>
Runs every handler registered for the firing trigger's expression.
-
expressions(): readonly string[]
Every expression that has at least one handler.
-
on(): thisexpression: string,handler: CronHandler
Registers a handler for a cron expression.
A background job queue backed by Cloudflare Queues.
-
add<T>(): Promise<string>name: string,data: T,options?: AddJobOptions
Enqueues a job.
-
addRecurring<T>(): Promise<void>name: string,_data: T,options: RecurringOptions
Not supported on Cloudflare Queues.
-
dispatch(batch: IQueueMessageBatch): Promise<void>
Dispatches one delivered batch into the registered processors.
-
process<T>(): voidname: string,processor: JobProcessor<T>,options?: ProcessOptions
Registers a processor for a job name.
Lists every reason the edge cache would refuse this response.
Narrows a Durable Object stub's response to one carrying a socket.
Caches responses in the Cloudflare edge cache.
Creates the Cloudflare Workers plugin.
Builds the default host from the real Workers global.
Builds the handler an application exports as queue to consume messages.
Builds the handler an application exports as queue.
Builds the handler an application exports as scheduled.
Reports whether a binding is D1-shaped.
Reports whether a binding is Durable-Object-namespace-shaped.
Reports whether a binding is KV-shaped.
Reports whether a binding is Queues-producer-shaped.
Reports whether a binding is R2-shaped.
The runtime capabilities this broker needs. IRuntimeServices
satisfies it.
-
clearTimeout(handle: TimerHandle): void
Cancels a reply timeout.
-
now(): number
Wall-clock milliseconds, for
MessageMetadata.timestamp. -
setTimeout(): TimerHandlefn: () => void,ms: number
Schedules a reply timeout.
-
uuid(): string
A fresh unique id, for message ids, correlation ids, and inbox addresses.
What assessCacheability needs to decide.
-
cacheableStatuses: readonly number[]
Statuses the caller considers cacheable.
-
headers: Headers
The response headers.
-
method: string
The request method.
-
status: number
The response status.
Options for cacheApiMiddleware.
-
bypass: (ctx: IRequestContext) => boolean
Returning
trueskips the cache entirely for this request. -
cache: ICacheApi
The cache handle. Omitted resolves
caches.defaultfrom 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 noCache-Controlof 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.
The clock shape this store needs. IRuntimeServices satisfies it.
-
now(): number
Current wall-clock time.
Options for CloudflarePlugin.
-
cache: KvCacheOptions
Serve
CAPABILITIES.CACHEfrom a KV namespace. Omitted registers nothing. -
durableObject: DurableObjectArm
Serve
CAPABILITIES.REALTIME_BACKPLANEfrom a Durable Object namespace. Omitted registers nothing. -
env: CloudflareWorkerEnv
The Worker's
env, fromimport { env } from 'cloudflare:workers'. -
messaging: WorkersMessagingArm
Serve
CAPABILITIES.MESSAGINGfrom a Queues producer binding. Omitted registers nothing. -
queue: WorkersQueueArm
Serve
CAPABILITIES.QUEUEfrom a Queues producer binding. Omitted registers nothing. -
requireBindings: readonly string[]
Bindings that must be present.
register()throws naming every absent one, so a missingwrangler.tomlstanza fails at startup instead of on the first request that needs it. -
storage: R2StorageArm
Serve
CAPABILITIES.STORAGEfrom an R2 bucket. Omitted registers nothing. -
waitUntil: WaitUntilHost
The platform's background-work sink, from
import { waitUntil } from 'cloudflare:workers'(available from compatibility date 2025-08-08).
Options for D1Adapter.
-
tables: Readonly<Record<string, D1EntityMapping>>
Per-entity table and primary-key overrides, keyed by the entity name passed to
getRepository().
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.
A D1 statement result.
-
results: readonly T[]
The returned rows; empty for a write.
-
success: boolean
Whether the statement succeeded.
Options for DistributedLockObjectCore.
-
now: () => number
Wall-clock source, in epoch milliseconds. Defaults to
Date.now.
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 barerealtime-backplanetoken; anything else derivesrealtime-backplane.<name>. -
topic: string
The object name every replica shares, passed to
idFromName.
Options for DurableObjectBackplane.
-
binding: string
The Durable Object binding name, used only in error messages.
-
logger: () => ILogger | undefined
Logger accessor for reporting a transport failure.
-
origin: string
This instance's identity, stamped on every published frame.
-
topic: string
The object name every replica shares, from
idFromName.
Options for DurableObjectLock.
-
binding: string
The Durable Object binding name, used only in error messages.
-
keyPrefix: string
Prefix applied to every lock key before deriving the object name.
-
runtime: IRuntimeServices
Runtime services, for minting the lock token.
One message arriving on a Durable Object WebSocket.
-
data: string | ArrayBuffer
The payload, as the runtime delivered it.
A Durable Object stub's response to a WebSocket upgrade.
-
status: number
Always
101 Switching Protocolson a successful upgrade. -
webSocket: IDurableObjectClientSocket
The client half of the connection.
Supplies the socket pair a Durable Object upgrade needs.
-
createPair(): DurableObjectWebSocketPair
Creates a linked client/server socket pair.
A created WebSocketPair.
-
client: IDurableObjectClientSocket
Handed back to the connecting replica in the 101 response.
-
server: IDurableObjectWebSocket
Retained by the Durable Object and accepted for hibernation.
The subset of the platform's Cache this package calls.
-
delete(request: Request | string): Promise<boolean>
Removes a cached response.
-
match(request: Request | string): Promise<Response | undefined>
Looks up a cached response.
-
put(): Promise<void>request: Request | string,response: Response
Stores a response.
Typed access to a Cloudflare Worker's platform bindings.
-
d1(name: string): ID1Database
A D1 database binding.
-
durableObject(name: string): IDurableObjectNamespace
A Durable Object namespace binding.
-
get<T>(name: string): T
A binding of a type this package has no facade for — Hyperdrive, Vectorize, Workers AI, Analytics Engine, and anything Cloudflare ships next.
-
has(name: string): boolean
Reports whether a binding of that name is present.
-
kv(name: string): IKvNamespace
A KV namespace binding.
-
names(): readonly string[]
Every binding name the Worker carries, sorted.
-
queue(name: string): IQueueProducer
A Queues producer binding.
-
r2(name: string): IR2Bucket
An R2 bucket binding.
-
service(name: string): IServiceBinding
A service binding to another Worker.
-
vars(): Readonly<Record<string, string>>
The Worker's string variables and secrets.
-
waitUntil(promise: Promise<unknown>): void
Keeps the invocation alive until the promise settles, so work can outlive the response.
A D1 database binding.
-
batch<T = Record<string, unknown>>(statements: readonly ID1PreparedStatement[]): Promise<readonly D1Result<T>[]>
Runs several statements as one atomic transaction. D1 exposes no imperative
BEGIN/COMMIT, so this is its unit of atomicity. -
prepare(query: string): ID1PreparedStatement
Prepares a statement.
A prepared D1 statement.
-
all<T = Record<string, unknown>>(): Promise<D1Result<T>>
Runs the statement and returns every row.
-
bind(...values: readonly unknown[]): ID1PreparedStatement
Binds ordered parameters. D1 supports
?and?NNN, not named parameters. -
first<T = Record<string, unknown>>(): Promise<T | null>
Runs the statement and returns the first row.
-
run<T = Record<string, unknown>>(): Promise<D1Result<T>>
Runs the statement for its effect.
The client half of a WebSocketPair, or the socket a Worker gets back from a
Durable Object upgrade.
-
accept(): void
Begins handling the socket in this isolate.
-
addEventListener(): voidtype: "message" | "close" | "error",listener: (event: DurableObjectMessageEvent) => void
Subscribes to a socket event.
-
close(): voidcode?: number,reason?: string
Closes the connection.
-
send(message: string | ArrayBuffer): void
Sends one frame to the peer.
A Durable Object namespace binding.
-
get(id: unknown): IServiceBinding
Returns a stub for the object with this id.
-
idFromName(name: string): unknown
Derives a stable object id from a name.
The DurableObjectState (ctx) members this package calls.
-
acceptWebSocket(ws: IDurableObjectWebSocket): void
Accepts a socket as hibernatable.
-
getWebSockets(): IDurableObjectWebSocket[]
Returns every currently connected socket.
-
storage: IDurableObjectStorage
Durable, transactional key/value storage scoped to this object.
The subset of DurableObjectStorage the lock object uses.
-
delete(key: string): Promise<boolean>
Removes one value.
-
get<T>(key: string): Promise<T | undefined>
Reads one persisted value.
-
put<T>(): Promise<void>key: string,value: T
Writes one value.
A WebSocket held by a Durable Object, as the hibernation API hands it back.
-
close(): voidcode?: number,reason?: string
Closes the connection.
-
send(message: string | ArrayBuffer): void
Sends one frame to the peer.
A Workers KV namespace binding.
-
delete(key: string): Promise<void>
Removes a value. Succeeds whether or not the key existed.
-
get(key: string): Promise<string | null>
Reads a value as text.
-
list(options?: KvListOptions): Promise<KvListResult>
Lists keys, one page at a time.
-
put(): Promise<void>key: string,value: string,options?: KvPutOptions
Writes a value.
One message delivered to a Queues consumer.
-
ack(): void
Marks the message processed. It is not redelivered.
-
attempts: number
Delivery attempt, 1 on first delivery — the same base as
IJob. -
body: unknown
The message body, as the producer sent it.
-
id: string
The platform-assigned message id.
-
retry(options?: { readonly delaySeconds?: number; }): void
Returns the message for redelivery, subject to the queue's configured
max_retriesand dead-letter queue.
A batch of messages delivered to a Queues consumer.
-
messages: readonly IQueueMessage[]
The messages in the batch.
-
queue: string
The name of the queue this batch came from.
A Cloudflare Queues producer binding.
-
send(): Promise<void>body: unknown,options?: QueueSendOptions
Enqueues one message, at most 128 KB.
-
sendBatch(messages: readonly { readonly body: unknown; readonly contentType?: string; }[]): Promise<void>
Enqueues up to 100 messages, at most 256 KB in total.
-
delete(key: string): Promise<void>
Removes an object. Succeeds whether or not it existed, and reports nothing about what was removed — which is why
R2Storage.deleteheads first to honor its committedPromise<boolean>. -
get(key: string): Promise<IR2ObjectBody | null>
Reads an object.
-
head(key: string): Promise<IR2Object | null>
Reads object metadata without transferring the body.
-
put(): Promise<IR2Object | null>key: string,value: ArrayBuffer | ArrayBufferView,options?: R2PutOptions
Writes an object.
Metadata common to every R2 object.
-
etag: string
The object's entity tag.
-
key: string
The object key.
-
size: number
Object size in bytes.
An R2 object together with its body.
-
arrayBuffer(): Promise<ArrayBuffer>
Reads the whole body into memory.
-
body: ReadableStream<Uint8Array>
The object body as a stream — the zero-copy download path.
The controller handed to a Cron Trigger's scheduled handler.
-
cron: string
The cron expression that fired, exactly as written in
wrangler.toml. -
scheduledTime: number
When the trigger was scheduled to fire, in epoch milliseconds.
A service binding to another Worker — a fetch-shaped RPC channel.
-
fetch(): Promise<Response>input: Request | string,init?: RequestInit
Invokes the bound Worker.
The id source this queue needs. IRuntimeServices satisfies it.
-
uuid(): string
A fresh unique id.
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
setomits one. Omitted means no expiry. -
name: string
Instance name.
'default'(the default) claims the barecachetoken; anything else derivescache.<name>, matchingCachePlugin'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.
Options for KvCacheStore.
-
defaultTtlSeconds: number
TTL in seconds applied when
setomits 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.
Options for IKvNamespace.list.
-
cursor: string
Continuation cursor from a previous page.
-
limit: number
Page size. The platform default and maximum are both 1000.
-
prefix: string
Return only keys starting with this prefix.
One page of IKvNamespace.list results.
-
cursor: string
Cursor for the next page; absent on the last page.
-
keys: readonly { readonly name: string; }[]
The keys in this page.
-
list_complete: boolean
truewhen this page is the last one.
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
physicalTtlSecondsfloors it and a logical expiry is carried inside the value.
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.
Options for createMessagingHandler.
-
name: string
Which broker instance to dispatch into, matching
CloudflarePluginOptions.messaging.name. Omitted resolves the bareCAPABILITIES.MESSAGINGtoken.
Options for createQueueHandler.
-
name: string
Which queue instance to dispatch into, matching
CloudflarePluginOptions.queue.name. Omitted resolves the bareCAPABILITIES.QUEUEtoken.
Options for IQueueProducer.send.
-
contentType: "json" | "text" | "bytes" | "v8"
How the body is serialized. Defaults to
'json'. -
delaySeconds: number
Delivery delay in seconds, from 0 to 86400.
The subset of R2's put options this package writes.
-
customMetadata: Readonly<Record<string, string>>
Arbitrary user metadata stored alongside the object.
-
httpMetadata: { readonly contentType?: string; }
HTTP metadata stored on the object; R2 serves
contentTypeback on GET.
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 barestoragetoken; anything else derivesstorage.<name>. -
prefix: string
Prefix applied to every object key.
Options for R2Storage.
-
prefix: string
Prefix applied to every object key, so one bucket can host several uses.
Options for RealtimeBackplaneObjectCore.
-
createPair: DurableObjectWebSocketHost
Supplies the
WebSocketPairan upgrade needs.
The Durable Object namespace serving reply inboxes, plus its binding name.
-
binding: string
The binding name, for error messages.
-
defaultTimeoutMs: number
Reply budget when
RequestOptions.timeoutMsis omitted. -
namespace: IDurableObjectNamespace
The Durable Object namespace binding.
Options for ReplyInboxObjectCore.
-
createPair: DurableObjectWebSocketHost
Supplies the
WebSocketPairan upgrade needs.
Options for WorkersBroker.
-
logger: LoggerSource
Resolves the logger at the moment a dispatch path needs it.
-
replyInbox: ReplyInboxBinding
Enables
request/respond. Omitted, both throwCloudflareUnsupportedErrornaming the arm to add.
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.
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 baremessagingtoken; anything else derivesmessaging.<name>, whichMessagingHandlerOptions.namemust then match. -
rpc: WorkersMessagingRpcArm
Enable
request/respond. Omitted, both throwCloudflareUnsupportedErrornaming this arm.
Enables brokered request-reply on a WorkersMessagingArm.
-
binding: string
The Durable Object namespace binding name from
wrangler.toml. -
defaultTimeoutMs: number
Reply budget applied when
RequestOptions.timeoutMsis omitted.
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 barequeuetoken; anything else derivesqueue.<name>, whichQueueHandlerOptions.namemust then match.
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
delayMsthis queue will accept, in seconds. Defaults to 86400, the platform maximum. A larger delay throws rather than being silently truncated by the platform.
| "status"
| "partial-content"
| "vary-star"
| "set-cookie"
Why the edge cache would refuse a response.
The Worker env record, as import { env } from 'cloudflare:workers'
provides it: a mix of string variables and object bindings.
Invoked when a Cron Trigger fires.
Resolves the logger at the moment a background task fails.
The queue export's shape, as Cloudflare invokes it.
The queue export's shape, as Cloudflare invokes it.
The scheduled export's shape, as Cloudflare invokes it.
A sink that keeps a Worker alive until the promise settles.
Thrown when a request body cannot be parsed as JSON.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
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
instanceofacross realms.
Asserts that a target path is contained within a root by comparing canonical paths.
Brands a middleware function with the application's resolved error responder, so the kernel can reach it at the pre-pipeline sites.
Extracts a caller-facing message from an unknown thrown value.
Composes behaviours around a terminal handler — the ONE shared composer for the CQRS pipeline and all four non-HTTP ingress chains.
Returns the content type for a file based on its extension.
Formats a context as a W3C traceparent value.
Builds a cached, coalesced, time-bounded reachability probe.
Creates a custom capability token for third-party plugins.
Builds a path-exclusion predicate from a list of literals and patterns.
Decode a cursor token to its CursorPayload, or null when the
token is malformed.
Decodes a payload received from the wire back into its local form.
Encode a CursorPayload as a base64url-encoded JSON token.
Encodes a WebSocket payload for the wire.
Creates a failed Result.
Reads the error responder branded onto a middleware function, if any.
Extracts W3C trace context from web-standard headers.
Classifies a request content-type as one of the two form encodings.
Converts a nullable value to an Option.
Reads the status hint an error was branded with.
Type guard: narrows a Result to Err.
Checks if a relative path is lexically contained within a root.
Type guard: narrows an Option to None.
Type guard: narrows a Result to Ok.
Reports whether a value is thenable, by the same duck-typed test the
platform serve layers use rather than instanceof Promise.
Type guard: narrows an Option to Some.
Reports whether a set of request headers describes an RFC 6455 WebSocket upgrade.
Narrows an incoming message to a WorkerReadySignal.
Narrows an incoming message to a WorkerTaskReply.
Narrows an incoming message to a WorkerTaskRequest.
Build the "row after this one" keyset comparison as a portable
FilterExpression.
Mint the next-page cursor from the last row of a non-terminal page.
Returns the None option.
Creates a successful Result.
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.
Parses one request-body text as JSON, the ONE parse all three IRequest
json() implementations share (X37-1, M90f).
Parses a W3C traceparent value.
Replaces request.user deliberately, bypassing the single-write guard.
Replaces request.tenant deliberately, bypassing the single-write guard.
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.
Resolves a probe's monotonic clock and timer surface from an injected
IRuntimeServices.
Resolves one entry of a registration option that accepts either an instance
or a RegistryFactory.
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.
Responds to an error in the application's configured format.
Installs the single-write guard over request.user and request.tenant.
Reads the security metadata a middleware function was branded with.
Serializes any thrown value to a plain, serializable object.
Brands a request with a WebSocket upgrade intent for the HTTP adapter to act on after the framework handler returns.
Creates an Option holding a value.
Build the stable sort fingerprint embedded in every minted cursor.
Partitions a Workers env record by value type.
Unwraps a Result, returning the value or throwing the error.
Reads the WebSocket upgrade intent an adapter should act on, or undefined
when the pipeline did not ask for an upgrade.
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.
Reads the validation metadata a middleware function was branded with.
Brands an error with the status it should be answered with.
Brands a middleware function with the security it enforces, so a documentation generator can read it without importing the plugin that produced it.
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.
Options accepted when enqueueing a job.
-
delayMs: number
Delay before the job becomes available, in milliseconds.
-
headers: Readonly<Record<string, string>>
Transport headers to carry with the job, delivered to the processor as
IJob.headers. -
maxAttempts: number
Maximum attempts before the job is dead-lettered.
One immutable audit trail entry.
-
action: string
The action performed (e.g.
"user.delete"). -
after: Readonly<Record<string, unknown>>
Resource state after the action.
-
before: Readonly<Record<string, unknown>>
Resource state before the action.
-
metadata: Readonly<Record<string, unknown>>
Additional context (IP, request ID, …).
-
resource: string
The resource kind acted on (e.g.
"user"). -
resourceId: string
The specific resource instance, when applicable.
-
result: "success" | "failure"
Whether the action succeeded.
-
userId: string
The acting principal's ID.
The structural shape both behaviour contracts satisfy, and the element type
of composeBehaviorChain's behaviors array.
-
handle(): TResult | Promise<TResult>work: TWork,next: () => Promise<TResult>
Wraps the rest of the chain.
Bulkhead policy consumed by the ResiliencePlugin's bulkhead pattern.
-
maxConcurrent: number
Maximum concurrent in-flight executions.
-
maxQueue: number
Maximum queued executions once concurrency is saturated. Defaults to 0.
Options for createCachedProbe.
-
clearTimer: (handle: TimerHandle) => void
Cancels a timer created by
CachedProbeOptions.setTimer(e.g.IRuntimeServices.clearTimeout). -
fallback: T
Outcome recorded when the probe times out or rejects.
-
hrtime: () => number
Monotonic clock in milliseconds (e.g.
IRuntimeServices.hrtime()). Injected so the TTL is an interval, not a wall-clock reading. -
probe: () => Promise<T>
The reachability probe. Resolving
truemeans the backend is reachable; resolvingfalseor rejecting means it is not. -
setTimer: () => TimerHandlefn: () => void,ms: number
Timer used to bound each probe (e.g.
IRuntimeServices.setTimeout). -
timeoutMs: number
Per-probe timeout, in milliseconds. A probe that does not settle within this window resolves
CachedProbeOptions.fallback, which isfalse— unreachable — unless the caller widened it. -
ttlMs: number
How long to cache the last outcome, in milliseconds.
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
timeoutwindow 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.
Provides a service by constructing a class, injecting the listed tokens as constructor arguments.
-
inject: readonly string[]
Tokens resolved and passed as constructor arguments, in order.
-
useClass: Constructor<T>
The class to instantiate.
A command: a request that mutates state and returns a result.
A query: a request that returns data without side effects.
A CQRS request identified by a string type and carrying typed data.
-
data: TData
The request payload.
-
type: string
Request type name (e.g.
"CreateUser"). Used for routing.
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
keysetPredicateas the tiebreaker fallback when a key column is absent fromorderBy. -
orderedValues: ReadonlyArray<CursorValue>
The value of every ordered field (in
orderBydeclaration order), from the row the cursor was minted against. Indexiis the value of the i-th entry ofObject.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.
A payload as it travels the backplane.
-
binary: boolean
True when
EncodedPayload.datais base64-encoded binary. -
data: string
The payload as a string.
Specification of one environment variable for
IEnvironmentApi.validate.
-
default: string | number | boolean
Default applied when the variable is absent.
-
required: boolean
Whether the variable must be present.
-
type: "string" | "number" | "boolean"
Expected primitive type (defaults to
'string').
A failed result carrying an error.
-
error: E
The error value.
-
success: false
Discriminant:
falsefor failure.
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).
-
request: { readonly path: string; }
The request, when one exists (supplies the Problem Details
instance). -
response: IResponse
The response builder to write the error response to.
-
state: Map<string, unknown>
Request-scoped state; the responder is published under
ERROR_RESPONDER_STATE_KEY.
The initialization of an error response produced through the responder seam.
-
detail: string
An optional disclosure, kept verbatim by every format.
-
details: Readonly<Record<string, unknown>>
Optional structured details (e.g. a validation
errorsarray). -
status: number
The HTTP status code to answer with.
-
title: string
The framework-default
errormember. In a formatted response this is the Problem Detailsdetailwhen nodetailis supplied.
Provides a service via a factory function.
-
useFactory: () => T
Factory invoked to produce the instance.
Evaluation context for targeting rules.
-
attributes: Readonly<Record<string, string | number | boolean>>
Additional targeting attributes.
-
tenantId: string
The tenant the flag is evaluated for, when the request resolves one.
-
userId: string
The user the flag is evaluated for.
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-rollednew URLSearchParams(body)iteration this accessor replaces). -
get(name: string): FormValue | undefined
Returns the FIRST value for a name, or
undefinedwhen the name is absent — the web standard'sget, withundefined(narrowable) in place ofnull. -
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.
One file part of a form body: a field that declared a filename in its
Content-Disposition.
-
data: Uint8Array
The file bytes, synchronously.
-
filename: string
The client-provided file name (
Content-Dispositionfilename="…"). -
mimeType: string
MIME type reported by the part's
Content-Type, or its default.
Information about a WebSocket connection used for subscription operations.
-
connectionParams: Record<string, unknown>
The payload sent with
connection_init, if any. -
data: Map<string, unknown>
Per-connection application state.
-
headers: Headers
The upgrade request headers.
-
id: string
Unique connection identifier.
-
protocol: string
The negotiated subprotocol, when one was selected.
-
query: Readonly<Record<string, string>>
Query string parameters from the upgrade request.
The outcome of a GraphQL execution, carrying an HTTP status code for the transport layer to use.
-
result: GraphqlExecutionResult
The execution result (may contain errors).
-
status: number
The HTTP status code to return under
application/graphql-response+jsonnegotiation.
The execution result as specified by the GraphQL spec.
-
data: Record<string, unknown> | null
The data returned by the execution, or null if an error occurred.
-
errors: GraphqlFormattedError[]
Errors encountered during execution, or undefined if none.
Formatted GraphQL error as returned to the client.
-
extensions: Record<string, unknown>
Optional extensions for application-specific error codes.
-
locations: Array<{ line: number; column: number; }>
Optional locations in the query document.
-
message: string
Human-readable error message.
-
path: Array<string | number>
Optional path to the field where the error occurred.
Context for a subscription operation, carrying either an HTTP request context or a WebSocket connection info.
-
connection: GraphqlConnectionInfo
The WebSocket connection info (supplied by the WS path).
-
requestContext: IRequestContext
The HTTP request context (supplied by the SSE path).
Parameters for a GraphQL execution request.
-
extensions: Record<string, unknown>
Optional extensions carried with the request.
-
operationName: string
Operation name for documents with multiple operations.
-
query: string
The GraphQL query string.
-
variables: Record<string, unknown>
Variables as a record of unknown values (passed through verbatim).
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.
-
method: Readonly<Record<string, TMethod>>
Methods keyed by their camelCase local name.
-
typeName: string
The fully qualified name of the service, e.g.
"package.ServiceName".
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.
-
__handlerResult: true
Brand preventing accidental structural matches.
The outcome of one health check.
-
data: Readonly<Record<string, unknown>>
Optional diagnostic details (response times, versions, …).
-
status: HealthStatus
The reported health state.
The aggregated health report returned by IHealthService.check().
-
checks: Readonly<Record<string, Readonly<HealthCheckResult & { readonly latencyMs?: number; }>>>
Per-indicator results with optional latency measurements.
-
status: HealthStatus
Overall health status (worst of all participating indicators).
-
timestamp: string
ISO 8601 timestamp of when the check was performed.
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
ErrorResponseInitleaves it optional, because a hint that omitted it would fall back to theError's own message. -
status: number
The HTTP status to answer with. Must be an integer in
400–599; a hint outside that range is treated as ABSENT and the error takes the ordinary masked-500path, because a hint says how an ERROR should be answered and a status the platform cannot serve would make the error handler itself throw.
A transaction handle that can also open entity data sources bound to itself.
-
createDataSource(entity: string): IDataSource
Open a data source for
entitybound to THIS transaction.
The application: registers plugins, owns the router and middleware pipeline, and manages the server lifecycle.
-
fetch(request: Request): Promise<Response>
Delegates a web-standard
Requestto the registeredIHttpAdapter.fetch. This works regardless of whetherstart()was called (Cloudflare Workers path:setHandlerruns atstart()time,fetchworks withoutlisten). -
middleware: IMiddlewareApi
The global middleware pipeline.
-
register(plugin: IPlugin): IApplication
Registers a plugin. Plugins register when the application starts, in dependency order.
-
router: IRouterApi
The application router.
-
services: IServiceRegistry
The application-scoped service registry.
-
start(options?: StartOptions): Promise<void>
Resolves plugins, builds the pipeline and router, and starts the server.
-
stop(): Promise<void>
Stops the server and runs shutdown hooks.
Immutable audit trail writer.
-
log(entry: AuditEntry): Promise<void>
Appends an entry to the audit trail. Entries are immutable once written.
Authentication service that coordinates strategies and provides credential verification for login flows.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Run configured passive strategies to authenticate a request.
-
verifyCredentials(credentials: { readonly identifier: string; readonly secret: string; }): Promise<IPrincipal | null>
Verify credentials for a login flow (e.g., username/password).
Authentication strategy interface. Implementations extract credentials
from a request and return a principal, or null if the strategy
does not apply.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Attempt to authenticate the request.
-
name: string
Strategy name for identification.
Key/value cache with per-entry TTL.
-
clear(): Promise<void>
Removes every entry (respecting the store's key prefix, if configured).
-
delete(key: string): Promise<boolean>
Removes a cached value.
-
get<T>(key: string): Promise<T | null>
Reads a cached value.
-
has(key: string): Promise<boolean>
Reports whether a live entry exists.
-
set<T>(): Promise<void>key: string,value: T,ttlSeconds?: number
Stores a value.
Circuit breaker protecting calls to an unreliable dependency.
-
execute<T>(fn: ResilientCall<T>): Promise<T>
Executes a call through the breaker.
-
state: CircuitState
The current circuit state.
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.
-
register(): voidname: string,handler: CliCommandHandler
Registers a CLI command.
Registers and executes commands.
-
execute<TResult = unknown>(command: CqrsCommand): Promise<TResult>
Executes a command.
-
register<TCommand extends CqrsCommand, TResult>(): voidtype: string,handler: ICommandHandler<TCommand, TResult>
Registers a handler for a command type.
Handles one command type.
-
handle(command: TCommand): TResult | Promise<TResult>
Executes the command.
Type-safe configuration access. Values originate from environment
variables and .env files, validated at startup.
-
get<T>(key: string): T | undefined
Reads a configuration value.
-
getOrThrow<T>(key: string): T
Reads a required configuration value.
-
has(key: string): boolean
Reports whether a key is present.
Dependency injection container.
-
createScope(): IContainer
Creates a child scope. Scoped services resolve to one instance per scope; singletons are shared with the parent.
-
has(token: string): boolean
Reports whether a token is registered.
-
register<T>(): voidtoken: string,provider: Provider<T>,options?: ProviderOptions
Registers a provider under a token.
-
resolve<T>(token: string): T
Resolves an instance, constructing it (and its dependencies) as needed.
Monotonically increasing counter. observe / inc add a non-negative value.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the counter.
Facade combining command and query buses.
-
commandBus: ICommandBus
The command bus.
-
queryBus: IQueryBus
The query bus.
The full database backend port: lifecycle plus data access.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Begin a transaction, returning a handle that can open transaction-scoped data sources as well as commit and roll back.
-
createDataSource(entity: string): IDataSource
Open a non-transactional data source for the named entity.
-
rawQuery<T>(): Promise<T[]>sql: string,params?: unknown[]
Execute a raw query in the backend's own dialect.
The data-access seam a backend provides per entity.
-
count(): Promise<number>where: Record<string, unknown>,filter?: FilterExpression
Count entities matching a filter.
-
create(data: Partial<Record<string, unknown>>): Promise<Record<string, unknown>>
Insert a new entity.
-
delete(id: EntityKey): Promise<boolean>
Delete an entity by primary key.
-
findAll(query: NormalizedQuery): Promise<Record<string, unknown>[]>
Find every entity matching the normalized query.
-
findById(id: EntityKey): Promise<Record<string, unknown> | null>
Find a single entity by its primary key value.
-
findPage(query: NormalizedQuery): Promise<PageResult>
Find a page of entities by cursor pagination.
-
update(): Promise<Record<string, unknown>>id: EntityKey,data: Partial<Record<string, unknown>>
Update an existing entity by primary key.
Custom decorator registration surface (active only when the DecoratorPlugin is registered; inert otherwise).
-
register(): voidname: string,handler: DecoratorHandler
Registers a handler for a custom decorator.
DNS resolution, abstracted across runtimes.
-
resolveHost(hostname: string): Promise<readonly string[]>
Resolves a hostname to IP address literals.
-
resolveSrv(hostname: string): Promise<readonly SrvRecord[]>
Resolves
SRVrecords for a hostname.
A domain event.
-
aggregateId: string
ID of the aggregate that produced the event, when applicable.
-
data: T
The event payload.
-
id: string
Unique event ID.
-
occurredOn: Date
When the event occurred.
-
type: string
Event type name (e.g.
"UserCreated"). -
version: number
Aggregate version, for event-sourced aggregates.
Environment validation surface: plugins declare the environment variables they need, and the kernel validates them at startup, failing fast on violations.
-
validate(spec: Readonly<Record<string, EnvVarSpec>>): void
Declares and validates environment variables.
A request-scoped error responder: writes an error response in the application's configured format.
-
respond(): voidtarget: ErrorResponderTarget,init: ErrorResponseInit
Writes an error response in the configured format.
In-memory publish/subscribe event bus for domain events.
-
publish<T>(event: IDomainEvent<T>): Promise<void>
Publishes an event to every subscriber of its type.
-
publishBatch(events: IDomainEvent[]): Promise<void>
Publishes multiple events, each to its own subscribers.
-
subscribe<T>(): Unsubscribetype: string,handler: EventHandler<T>
Subscribes to an event type.
Feature flag evaluator. Evaluation is synchronous against the provider's cached state; providers refresh their state out of band.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates a flag.
-
isEnabledAsync(): Promise<boolean>flag: string,context?: FlagContext
Evaluates a flag, awaiting the backing provider when it can produce a more accurate answer asynchronously.
Runtime-agnostic file system operations. Absent on runtimes without file system access (edge platforms).
-
mkdir(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Creates a directory.
-
readFile(path: string): Promise<Uint8Array>
Reads a file.
-
readStream(): Promise<ReadableStream<Uint8Array>>path: string,options?: { readonly start?: number; readonly end?: number; }
Reads a file as a stream, optionally with byte range.
-
readdir(path: string): Promise<readonly string[]>
Lists directory entries.
-
realPath(path: string): Promise<string>
Resolves a path to its canonical absolute form, following symlinks.
-
rm(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Removes a file or directory.
-
stat(path: string): Promise<StatResult>
Returns file metadata.
-
writeFile(): Promise<void>path: string,data: Uint8Array
Writes a file, creating it if absent.
Gauge: arbitrary set / inc / dec. observe sets the value.
-
dec(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Decrements the gauge.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the gauge.
-
set(): voidvalue: number,labels?: Readonly<Record<string, string>>
Sets the gauge to a specific value.
The GraphQL service contract.
-
cachedDocumentCount: number
Report the number of cached documents.
-
endpoint: string
The endpoint path where GraphQL is served.
-
execute(): Promise<GraphqlExecutionOutcome>params: GraphqlRequestParams,requestContext?: IRequestContext,method?: "GET" | "POST"
Execute a GraphQL request.
-
subscribe(): Promise<GraphqlSubscriptionOutcome>params: GraphqlRequestParams,context?: GraphqlOperationContext
Subscribe to a GraphQL operation (query, mutation, or subscription).
The service contract that applications use to register gRPC/Connect services.
Provided by the grpc-plugin under the CAPABILITIES.GRPC token.
-
addService<TDef extends GrpcServiceDefinition>(): voiddefinition: TDef,implementation?: unknown
Registers a gRPC service definition with an optional implementation.
-
available: boolean
Whether gRPC dispatch is available.
-
claims(request: Request): boolean
Whether this service claims a request — that is, whether the request path lies inside the configured
basePath. -
handleRequest(request: Request): Promise<Response>
Handles an incoming RPC request directly.
-
refuses(request: Request): Response | null
Whether this service refuses the request outright, decided from its HEADERS alone.
Health check registration surface.
-
register(): voidname: string,indicator: HealthIndicatorFn
Registers a health indicator.
A named health indicator contributing to /health, /live, and
/ready.
-
check(): Promise<HealthCheckResult>
Performs the health check.
-
name: string
Indicator name, unique per application.
Health service contract for registering and checking health indicators.
-
check(): Promise<HealthReport>
Runs all registered indicators and returns the aggregated report.
-
checkLive(): Promise<HealthReport>
Runs only the liveness indicator (the built-in "self" indicator).
-
checkReady(): Promise<HealthReport>
Runs all contributed indicators for readiness.
-
registerIndicator(): voidname: string,indicator: HealthIndicatorFn
Registers a health indicator.
Histogram: bucketed observation distribution plus sum and count.
-
buckets: readonly number[]
Upper bounds of the histogram buckets.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation (sample).
HTTP server adapter provided by the runtime plugin. No other plugin may create HTTP servers (AI_GUIDELINES §4.3).
-
close(handle: ServerHandle): Promise<void>
Stops the server gracefully.
-
fetch(request: Request): Response | Promise<Response>
The universal web-standard entry point. Accepts a web
Requestand returns a webResponse. May be called withoutlisten(e.g. Cloudflare Workers whereexport default { fetch: app.fetch }is the deploy path). -
listen(): Promise<ServerHandle>port: number,hostname?: string
Binds the adapter's
fetchto a real TCP socket. -
setHandler(handler: (request: IRequest) => IResponse | Promise<IResponse>): void
Installs the framework request handler. Called once at
start()time, after the middleware pipeline compiles and before anyfetchorlisten. -
setRpcHandler(handler: RpcFetchHandler): void
Installs a gRPC/Connect fetch handler.
-
setUpgradeRouter(router: WebSocketUpgradeRouter): void
Installs a WebSocket upgrade router. The adapter stores the router but does not consult it: since M70a the kernel's terminal handler resolves
IWebSocketServiceand callsrouteUpgradeitself, after the middleware pipeline has run without short-circuiting and before route matching — so an application catch-all cannot shadow an upgrade. What the adapter needs from this setter is the bare fact that a router was installed: Node attaches its rawupgradelistener only then.
Cross-cutting behaviour around one unit of non-HTTP ingress work.
-
handle(): void | Promise<void>ctx: IngressContext,next: () => Promise<void>
Wraps the rest of the chain around one work item.
A queued job delivered to a processor.
-
attempts: number
How many times this job has been attempted (1 on first delivery).
-
data: T
The job payload.
-
headers: Readonly<Record<string, string>>
Transport headers carried with the job, mirroring
MessageMetadata.headersso the two ingresses cannot drift on meaning:{}means the channel was read and carried nothing; absent means there was no channel. -
id: string
Queue-assigned job ID.
-
name: string
The job name it was enqueued under.
JWT sign/verify service.
-
decode<T = Readonly<Record<string, unknown>>>(token: string): T | null
Decodes a token without verifying it. Never trust the result for authorization decisions.
-
sign(): Promise<string>payload: Readonly<Record<string, unknown>>,options?: JwtSignOptions
Signs a payload into a JWT.
-
verify<T = Readonly<Record<string, unknown>>>(token: string): Promise<T>
Verifies a token's signature and validity window.
Lifecycle hook registration surface. Hooks run in registration order within each phase.
-
onBootstrap(fn: () => void | Promise<void>): void
Runs immediately before the server starts listening.
-
onClose(fn: () => void | Promise<void>): void
Runs after shutdown completes.
-
onError(fn: () => void | Promise<void>): voiderror: Error,ctx: IRequestContext
Runs when an error escapes middleware or a handler.
-
onInit(fn: () => void | Promise<void>): void
Runs after all plugins have registered.
-
onRegister(fn: () => void | Promise<void>): void
Runs during the owning plugin's registration.
-
onRequest(fn: (ctx: IRequestContext) => void | Promise<void>): void
Runs at the start of every request.
-
onResponse(fn: (ctx: IRequestContext) => void | Promise<void>): void
Runs after every response is produced.
-
onShutdown(fn: () => void | Promise<void>): void
Runs when shutdown begins — close connections, flush buffers here.
-
onStopping(fn: () => void | Promise<void>): void
Runs at the very start of
stop(), before the application begins refusing new requests.
Structured logger. All framework and application logging goes through
this interface — never console (AI_GUIDELINES §11.6).
-
child(bindings: LogMetadata): ILogger
Creates a child logger whose entries always include the bindings.
-
debug(): voidmessage: string,metadata?: LogMetadata
Logs at
debugseverity. -
error(): voidmessage: string,metadata?: LogMetadata
Logs at
errorseverity. -
fatal(): voidmessage: string,metadata?: LogMetadata
Logs at
fatalseverity. -
info(): voidmessage: string,metadata?: LogMetadata
Logs at
infoseverity. -
level: LogLevel
The minimum level this logger emits.
-
trace(): voidmessage: string,metadata?: LogMetadata
Logs at
traceseverity. -
warn(): voidmessage: string,metadata?: LogMetadata
Logs at
warnseverity.
Email sender.
-
isHealthy(): Promise<boolean | undefined>
Reports whether the mail transport is REACHABLE right now, distinct from whether the mailer was constructed. Optional: a mailer whose transport exposes no side-effect-free probe omits it, and so does an implementation that does not answer the question at all.
-
send(message: MailMessage): Promise<void>
Sends an email.
-
sendTemplate(): Promise<void>template: string,message: Omit<MailMessage, "html" | "text">,data: Readonly<Record<string, unknown>>
Renders a named template and sends the result.
Message broker for cross-service integration events.
-
connect(): Promise<void>
Opens the broker connection.
-
disconnect(): Promise<void>
Closes the broker connection.
-
isHealthy(): Promise<boolean>
Reports whether the broker's backend is reachable right now, for the plugin's health indicator.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request to a topic and awaits a single correlated reply, providing brokered request-reply (RPC) over the message broker.
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic. The handler's resolved value is sent back to the requesting caller, correlated to the originating request.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
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.
-
controllers: Map<Constructor, Readonly<Record<string, unknown>>>
Controller metadata keyed by class.
-
routes: Map<>Constructor,ReadonlyArray<Readonly<Record<string, unknown>>>
Route metadata lists keyed by controller class.
-
services: Map<Constructor, Readonly<Record<string, unknown>>>
Service metadata keyed by class.
A registered metric.
-
help: string
Human-readable description.
-
name: string
Metric name (Prometheus naming conventions).
-
observe(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Records an observation.
-
type: MetricType
The metric instrument kind.
Metric registration surface.
-
register(): voidname: string,config: MetricConfig
Registers a metric.
Metrics service resolved via ctx.services.get<IMetricsService>('metrics').
-
counter(): ICountername: string,options?: MetricOptions
Gets or creates a counter.
-
gauge(): IGaugename: string,options?: MetricOptions
Gets or creates a gauge.
-
get(name: string): IMetric | undefined
Gets a metric by name.
-
histogram(): IHistogramname: string,options?: MetricOptions
Gets or creates a histogram.
-
summary(): ISummaryname: string,options?: MetricOptions
Gets or creates a summary.
Object form of middleware, for implementations that carry state.
Middleware pipeline registration surface exposed to plugins.
-
add(): voidmiddleware: MiddlewareFunction,options?: MiddlewareOptions
Adds middleware to the global pipeline.
Multi-tenancy service — exposes tenant context, repository creation, and cache-key helpers.
-
getCurrentTenant(ctx: IRequestContext): ITenant | undefined
Return the tenant resolved for this request context, or
undefined. -
getRepository<Entity, Id = string>(): ITenantRepository<Entity, Id>ctx: IRequestContext,entity: string
Create a tenant-scoped repository for the given entity type. Throws
TenantNotResolvedErrorif no tenant is resolved. -
getRepositoryFor<Entity, Id = string>(): ITenantRepository<Entity, Id>tenantId: string,entity: string
Create a tenant-scoped repository for the given entity type, scoped to the tenant id GIVEN — no
IRequestContextrequired. This is the entry point for non-HTTP work (an ingress behaviour, a queue processor, a scheduled job), where no request exists to resolve a tenant from; the caller reads the tenant id from the work item's own payload. Modelled onprefixCacheKey— this interface's other ctx-free, id-taking member. -
prefixCacheKey(): stringtenantId: string,key: string
Build a cache key that includes the tenant id, joined by the separator the plugin was configured with (
cache.separator, default':'). The separator is deliberately NOT a per-call argument: this method is the single home for separator resolution, so the middleware'sctx.stateprefix and a caller's key can never disagree.
Transport-neutral envelope for ONE unit of non-HTTP work.
-
attempt: number
1-based delivery attempt. Present for
'queue'(fromIJob.attempts) and'scheduler'(fromScheduledJob.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 fabricated1would lie on a fifth redelivery. -
headers: Readonly<Record<string, string>>
Transport headers, populated on the
'messaging'arm fromMessageMetadata.headersand on the'queue'arm fromIJob.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, aScheduledJob, the message payload, or the frame data.
Multi-channel notification dispatcher.
-
send(notification: NotificationMessage): Promise<void>
Dispatches a notification on every requested channel.
-
sendSettled(notification: NotificationMessage): Promise<readonly ChannelSendResult[]>
Dispatches a notification on every requested channel and reports the settled outcome of each, without throwing.
OpenAPI contribution surface. Schema values are unknown here; the
OpenAPI plugin narrows them (Zod schemas by default).
-
addSchema(): voidname: string,schema: unknown
Contributes a named schema to the generated OpenAPI document.
ORM adapter port — what the DatabasePlugin requires from any ORM integration.
-
beginTransaction(): Promise<ITransaction>
Begins a transaction.
-
connect(): Promise<void>
Opens the underlying connection (pool).
-
disconnect(): Promise<void>
Closes the underlying connection (pool).
-
isReady(): boolean
Reports whether the adapter is connected and usable.
Wraps a handler with cross-cutting logic (logging, timing, validation, etc.).
-
handle(): TResult | Promise<TResult>request: TRequest,next: () => Promise<TResult>
Wraps the next handler in the pipeline.
The plugin contract. Every framework capability implements this interface (AI_GUIDELINES §3.2).
-
consumes: readonly CapabilityToken[]
Capability tokens this plugin resolves lazily at runtime via
ctx.services.get. UnlikeIPlugin.dependencies, these are not required before this plugin registers and impose no ordering; but if no registered plugin provides one, the kernel emits a softwarn-level startup diagnostic (through the logger capability when one is registered), because the deferred lookups would otherwise fail only later, at request time. -
dependencies: readonly CapabilityToken[]
Capability tokens that must be provided before this plugin registers.
-
name: string
Unique plugin name, lowercase kebab-case.
-
optionalDependencies: readonly CapabilityToken[]
Capability tokens used when present, tolerated when absent.
-
priority: number
Registration priority within the same dependency level; lower first.
-
provides: readonly CapabilityToken[]
Capability tokens this plugin registers.
-
register(ctx: IPluginContext): void | Promise<void>
Registers the plugin's services, middleware, routes, and hooks.
-
version: string
Plugin semver, matching its
deno.jsonversion.
The registration context handed to IPlugin.register — every
extension point a plugin can touch.
-
app: IApplication
The owning application.
-
cli: ICliApi
CLI command registration.
-
config: IConfig
Configuration access (from the ConfigPlugin, when registered).
-
container: IContainer
DI container (from the DiPlugin, when registered).
-
decorators: IDecoratorApi
Custom decorator registration.
-
environment: IEnvironmentApi
Environment variable validation.
-
health: IHealthApi
Health check registration.
-
lifecycle: ILifecycleApi
Lifecycle hooks.
-
logger: ILogger
Logger (from the LoggerPlugin, when registered).
-
metadata: IMetadataStore
Decorator metadata store (from the DecoratorPlugin, when registered).
-
metrics: IMetricsApi
Metric registration.
-
middleware: IMiddlewareApi
Middleware pipeline.
-
openapi: IOpenApiApi
OpenAPI contributions.
-
options: Readonly<Record<string, unknown>>
Options the application passed to this plugin's factory.
-
router: IRouterApi
Route registration.
-
runtime: IRuntimeServices
Runtime services. Non-optional by contract: a runtime provider is mandatory and the kernel registers it first, so every other plugin can rely on it during registration (see ARCHITECTURE.md §7).
-
services: IServiceRegistry
Service registration and resolution.
The authenticated identity attached to a request by authentication middleware.
-
claims: Readonly<Record<string, unknown>>
Additional claims from the credential.
-
id: string
Stable subject identifier.
-
permissions: readonly string[]
Permission names held by the principal.
-
roles: readonly string[]
Role names held by the principal.
Registers and executes queries.
-
execute<TResult = unknown>(query: CqrsQuery): Promise<TResult>
Executes a query.
-
register<TQuery extends CqrsQuery, TResult>(): voidtype: string,handler: IQueryHandler<TQuery, TResult>
Registers a handler for a query type.
Handles one query type.
-
handle(query: TQuery): TResult | Promise<TResult>
Executes the query.
Background job queue.
-
add<T>(): Promise<string>name: string,data: T,options?: AddJobOptions
Enqueues a job.
-
addRecurring<T>(): Promise<void>name: string,data: T,options: RecurringOptions
Schedules a recurring job.
-
process<T>(): voidname: string,processor: JobProcessor<T>,options?: ProcessOptions
Registers a processor for a job name.
A publish/subscribe transport carrying RealtimeFrames between
application instances.
-
close(): Promise<void>
Closes the underlying transport and drops every handler.
-
connect(): Promise<void>
Opens the underlying transport. Idempotent.
-
isHealthy(): Promise<boolean>
Reports whether the transport's backend is reachable right now, for the plugin's health indicator.
-
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed instance.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other instances.
Runtime-agnostic view of an incoming HTTP request.
-
bytes(): Promise<Uint8Array>
Reads the body as raw bytes.
-
formData(): Promise<FormBody>
Reads the body as a form, for both
application/x-www-form-urlencodedandmultipart/form-datarequests. -
headers: Headers
Request headers (web-standard
Headers). -
ip: string
Client IP address, when derivable.
-
json<T = unknown>(): Promise<T>
Reads and parses the body as JSON.
-
method: HttpMethod
The HTTP method.
-
path: string
The URL path component (no query string).
-
raw: Request
The undisturbed web-standard
Request, preserved for WebSocket upgrade and gRPC dispatch after the middleware pipeline. -
signal: AbortSignal
An abort signal that fires when the underlying HTTP connection is severed (client disconnect, timeout). Populated by the HTTP adapter from the native
Request.signal; optional because injected / test requests may not carry one. -
tenant: ITenant
The resolved tenant, populated by the multi-tenancy middleware. Absent when no tenant could be resolved or multi-tenancy is not enabled.
-
text(): Promise<string>
Reads the body as text.
-
url: string
The full request URL.
-
user: IPrincipal
The authenticated principal, populated by authentication middleware. Absent when the request is unauthenticated.
Per-request context passed to middleware and route handlers. Each request gets a fresh context; request-scoped data lives here, never in globals.
-
id: string
Unique request ID (generated or propagated by middleware).
-
params: Readonly<Record<string, string>>
Path parameters extracted by the router (e.g.
:id). -
query: Readonly<Record<string, string>>
Query string parameters.
-
raw: Request
The undisturbed web-standard
Request, preserved for WebSocket upgrade and gRPC dispatch after the middleware pipeline. -
request: IRequest
The incoming request.
-
response: IResponse
The response builder.
-
services: IServiceRegistry
Service resolution (application-scoped plus request-scoped services).
-
signal: AbortSignal
An abort signal that fires when the underlying HTTP connection is severed (client disconnect, timeout). Populated by the kernel's request-context factory from the native
Request.signal; falls back to a non-aborting sentinel so handlers always have a live signal to listen on. -
startTime: number
High-resolution timestamp captured when the context was created.
-
state: Map<string, unknown>
Request-scoped state for passing data between middleware and handlers.
Resilience service registered under CAPABILITIES.RESILIENCE.
-
wrap<T>(): HardenedCall<T>fn: ResilientCall<T>,options?: WrapOptions
Wraps
fnwith the selected patterns and returns a hardened callable that reuses one shared pattern chain across invocations, so circuit-breaker and bulkhead state persist across calls.
Runtime-agnostic response builder. Configuration methods (status,
header) chain; terminal methods (json, text, send, redirect)
produce the HandlerResult a route handler returns.
-
appendHeader(): IResponsename: string,value: string
Appends a response header, preserving any existing values for the same name rather than replacing them (unlike
IResponse.header, which overwrites). This is the correct way to emit multiple headers of the same name — most notably severalSet-Cookieheaders (e.g. an access cookie plus a refresh cookie, or deleting several cookies at once). -
header(): IResponsename: string,value: string
Sets a response header.
-
html(body: string): HandlerResult
Sends an HTML response.
-
json<T>(body: T): HandlerResult
Sends a JSON response.
-
redirect(): HandlerResulturl: string,status?: number
Sends a redirect response.
-
send(body?: Uint8Array): HandlerResult
Sends a raw byte response.
-
snapshot(): ResponseSnapshot
Returns a snapshot of the current response state (status, headers, body). Enables middleware to inspect the response after
next()returns — required for transparent response caching. -
status(code: number): IResponse
Sets the response status code.
-
stream(body: ReadableStream<Uint8Array>): HandlerResult
Sends a streaming response body.
-
text(body: string): HandlerResult
Sends a plain-text response.
Router registration surface exposed to plugins and applications.
-
delete(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a DELETE route.
-
get(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a GET route.
-
group(): voidprefix: string,configure: (router: IRouterApi) => void
Creates a route group: routes registered inside the callback share the prefix and any group middleware.
-
head(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a HEAD route.
-
listRoutes(): readonly RouteInfo[]
Returns all registered routes for introspection.
-
options(): voidpath: string,route: RouteHandler | RouteDefinition
Registers an OPTIONS route.
-
patch(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a PATCH route.
-
post(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a POST route.
-
put(): voidpath: string,route: RouteHandler | RouteDefinition
Registers a PUT route.
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.
-
clearInterval(handle: TimerHandle): void
Cancels a
setInterval. -
clearTimeout(handle: TimerHandle): void
Cancels a
setTimeout. -
dns: IDnsResolver
DNS resolution; absent on runtimes with no resolver API (edge platforms).
-
env: Readonly<Record<string, string | undefined>>
Environment variables. Always read env through this, never
process.env. -
exit(code?: number): never
Terminates the process.
-
fs: IFileSystem
File system access; absent on runtimes without one (edge platforms).
-
hostname(): string
Returns the host name, when the runtime exposes one.
-
hrtime(): number
Returns a high-resolution monotonic timestamp in milliseconds, suitable for measuring durations.
-
now(): number
Returns the current wall-clock time in milliseconds since the epoch.
-
onSignal(): voidsignal: RuntimeSignal,handler: () => void
Registers a handler for a process-termination signal, so an application can run
app.stop()before the process dies. -
platform(): RuntimePlatform
Identifies the current runtime.
-
randomBytes(length: number): Uint8Array
Generates cryptographically secure random bytes.
-
setInterval(): TimerHandlefn: () => void,ms: number
Schedules a repeating callback.
-
setTimeout(): TimerHandlefn: () => void,ms: number
Schedules a one-shot callback.
-
subtle: SubtleCrypto
Web Crypto
SubtleCryptofor cryptographic operations. -
uuid(): string
Generates a UUID v4.
-
version(): string
Returns the runtime version string.
-
workers: IWorkerHost
Worker-thread spawning; absent on runtimes without threads (edge platforms).
In-process job scheduler.
-
cron<T = unknown>(): Promise<void>name: string,expression: string,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a recurring job using a 5-field cron expression (UTC).
-
delay<T = unknown>(): Promise<void>name: string,delayMs: number,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a one-shot delayed job.
-
every<T = unknown>(): Promise<void>name: string,intervalMs: number,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a recurring job that fires every
intervalMsmilliseconds. -
getNextRun(name: string): Promise<number>
Return the next scheduled fire time as epoch milliseconds.
-
pause(name: string): Promise<void>
Pause a scheduled job without dropping its configuration.
-
remove(name: string): Promise<void>
Remove a scheduled job entirely.
-
resume(name: string): Promise<void>
Resume a paused job.
Secret manager backed by a provider (AWS KMS, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, or environment variables in development).
-
get(name: string): Promise<string>
Retrieves a secret.
-
has(name: string): Promise<boolean>
Reports whether a secret exists.
-
rotate(): Promise<void>name: string,value: string
Rotates a secret to a new value.
Resolves logical service names to reachable instances, balances across them, and learns from reported call outcomes.
-
pick(): Promise<ServiceInstance | null>serviceName: string,options?: PickOptions
Chooses one instance, skipping ejected ones.
-
report(): voidinstance: ServiceInstance,outcome: ServiceOutcome
Reports how a call to an instance went.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Lists every instance discovery knows for a service.
-
resolveUrl(): Promise<string | null>serviceName: string,path?: string,options?: PickOptions
Formats
IServiceDiscovery.pick's choice as an absolute URL. -
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Subscribes to instance-list changes for a service.
Maps capability tokens to service instances.
-
get<T extends object>(token: CapabilityToken): T
Resolves a service by capability token.
-
getAll<T extends object>(token: CapabilityToken): readonly T[]
Resolves every provider registered for a multi-provider token.
-
has(token: CapabilityToken): boolean
Reports whether a capability is available.
-
register<T extends object>(): voidtoken: CapabilityToken,service: T,options?: RegisterOptions
Registers a service instance under a capability token.
-
registerFactory<T extends object>(): voidtoken: CapabilityToken,factory: ServiceFactory<T>,options?: RegisterOptions
Registers a lazy factory: the service is instantiated on first
getand cached for subsequent lookups. -
unregister(token: CapabilityToken): boolean
Removes a registration. On a multi-provider token this removes EVERY provider registered under it, not just the first.
Per-request session handle.
-
clear(): void
Removes every key, keeping the session and its id.
-
delete(key: string): boolean
Removes a key and marks the session for commit.
-
destroy(): void
Ends the session: clears the data, deletes any stored entry, and instructs the client to drop the cookie.
-
get<T = unknown>(key: string): T | undefined
Reads a value.
-
has(key: string): boolean
Reports whether a key is present.
-
id: string
The session identifier. Stable for the session's lifetime until
ISession.regenerateis called. -
isNew: boolean
Whether this session was created for this request rather than restored from a cookie.
truefor a first visit, and for a request whose cookie was missing, expired, or failed authentication. -
regenerate(): void
Issues a new session id while keeping the current data.
-
set<T>(): voidkey: string,value: T
Writes a value and marks the session for commit.
-
toJSON(): SessionData
Returns a plain snapshot of the current data.
Session service registered under CAPABILITIES.SESSION.
-
from(ctx: IRequestContext): ISession
Returns the session the middleware loaded for this request.
-
fromHeaders(headers: Headers): Promise<SessionView | null>
Opens a session from a
Headersobject alone — the headers-only read for non-HTTP entry points that have no request context to commit onto (a WebSocketonOpenhandler, an auth strategy reading a cookie).
Server-side session storage port.
-
close(): Promise<void>
Releases resources held by the store (timers, connections).
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
isHealthy(): Promise<boolean>
Reports the store's reachability, for the plugin's health indicator.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
A span represents a single operation within a trace.
-
end(): void
Ends the span. Must be called exactly once.
-
recordException(error: Error): void
Records an exception on this span.
-
setAttribute(): thiskey: string,value: SpanAttributeValue
Sets a single attribute on the span.
-
setAttributes(attributes: Readonly<Record<string, SpanAttributeValue>>): this
Sets multiple attributes on the span.
-
setStatus(status: SpanStatus): void
Sets the status of the span.
-
spanContext(): SpanContext
Returns the span's context (traceId, spanId, traceFlags).
A live SSE connection backed by a ReadableStream.
-
close(): void
Closes the connection: clears the heartbeat, closes the stream controller, and marks the connection as closed. Idempotent.
-
comment(text: string): void
Enqueues a plain-text comment frame (
: <text>\n\n) — commonly used as a keep-alive heartbeat. -
id: string
Unique connection ID.
-
isOpen: boolean
Whether this connection is still open.
-
lastEventId: string | null
The client's
Last-Event-IDheader value, if present. -
result: HandlerResult
The
HandlerResultobtained fromctx.response.stream(). The handler returns this value so the kernel maps it to the correct web response. -
send(msg: SseMessage): void
Enqueues an encoded SSE frame for the connected client.
Service contract for the SSE hub — registered by the SsePlugin under
CAPABILITIES.SSE.
-
channel(name: string): SseChannel
Returns or creates a named channel.
-
channelCount: number
Number of channels the registry currently holds.
-
connectionCount: number
Current number of open connections.
-
open(ctx: IRequestContext): ISseConnection
Opens a new SSE connection for the given request context.
-
peek(name: string): SseChannel | undefined
Returns the named channel if one already exists, without creating it.
Service contract for server-side rendering (SSR).
-
render(ctx: IRequestContext): Promise<HandlerResult>
Renders an SSR document for the given request context.
Object storage abstraction.
-
delete(path: string): Promise<boolean>
Deletes an object.
-
exists(path: string): Promise<boolean>
Reports whether an object exists.
-
get(path: string): Promise<Uint8Array>
Retrieves an object.
-
getSignedUrl(): Promise<string>path: string,options: SignedUrlOptions
Creates a time-limited URL granting direct access to an object.
-
getStream(path: string): Promise<ReadableStream<Uint8Array>>
Retrieves an object as a streaming body for zero-copy downloads.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object.
Summary: per-quantile observations plus sum and count.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation (sample).
-
quantiles: readonly number[]
Configured quantiles.
Telemetry service — the primary API for creating spans.
-
activeSpanContext(): SpanContext | undefined
Reports the identifiers of the span that is active RIGHT NOW, so a signal emitted outside any span-creating call — a log record, most of all — can name the trace it belongs to.
-
withSpan<T>(): Promise<T>name: string,fn: (span: ISpan) => Promise<T>,options?: SpanOptions
Creates a span, runs the callback, and ends the span.
A resolved tenant.
-
id: string
Stable tenant identifier.
-
metadata: Readonly<Record<string, unknown>>
Tenant-specific configuration.
-
name: string
Display name.
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.
-
create(data: Readonly<Record<string, unknown>>): Promise<Entity>
Create a new record.
-
delete(id: Id): Promise<boolean>
Delete a record by its identifier. Returns
trueif a record was deleted. -
find(filter: Readonly<Record<string, unknown>>): Promise<readonly Entity[]>
Find records matching a filter.
-
findAll(): Promise<readonly Entity[]>
Retrieve all records.
-
findById(id: Id): Promise<Entity | null>
Find a single record by its identifier.
-
update(): Promise<Entity | null>id: Id,data: Readonly<Record<string, unknown>>
Update an existing record by its identifier.
Resolves the tenant for an incoming request (by subdomain, header, path, or JWT claim, depending on the implementation).
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolves the request's tenant.
A database transaction handle.
-
commit(): Promise<void>
Commits the transaction.
-
rollback(): Promise<void>
Rolls the transaction back.
An adapter's explicit declaration of portable transaction isolation support.
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
The portable isolation levels this adapter honours.
Data validation service.
-
middleware(): MiddlewareFunctionschema: unknown,target: ValidationTarget
Creates middleware that validates one part of the request and stores the parsed value in request state.
-
validate<T>(): Result<T, readonly ValidationIssue[]>schema: unknown,data: unknown
Validates data against a schema.
View engine contract — renders a view component and its props to HTML.
-
render<P>(): string | Promise<string>component: Component<P>,props: P
Renders a view component with the given props to an HTML string.
A live WebSocket connection, as seen by application code.
-
close(): voidcode?: number,reason?: string
Closes the connection. Idempotent.
-
data: Map<string, unknown>
Per-connection application state, the socket-lifetime analogue of
IRequestContext.state. Use it to attach an authenticated user id, a tenant, or any value later handlers and broadcasts need. -
id: string
Unique connection ID (from
runtime.uuid()). -
isOpen: boolean
Whether the connection is still writable.
-
path: string
The path this connection was opened on.
-
readyState: WebSocketReadyState
Current lifecycle state.
-
send(data: string | Uint8Array): void
Sends a frame to this peer.
-
sendJson<T>(payload: T): void
Serializes a value to JSON and sends it as a text frame.
Service contract for the WebSocket hub — registered by the WebSocketPlugin
under CAPABILITIES.WEBSOCKET.
-
available: boolean
Whether the underlying HTTP adapter can perform WebSocket upgrades.
-
connectionCount: number
Current number of open connections across all routes.
-
peek(name: string): WebSocketRoom | undefined
Returns the named room if one already exists, without creating it.
-
room(name: string): WebSocketRoom
Returns the named room, creating it on first use.
-
roomCount: number
Current number of live rooms.
-
route(): voidpath: string,handlers: WebSocketHandlers,options?: WebSocketRouteOptions
Registers a WebSocket route. Paths match exactly; the query string is ignored for matching and exposed to
onOpeninstead. -
routeUpgrade(): Promise<WebSocketUpgradeDecision | null>request: Request,principal?: IPrincipal
Consults the internal upgrade router for an inbound request. Used by the kernel terminal handler to decide whether to upgrade after the middleware pipeline runs.
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).
-
close(): voidcode?: number,reason?: string
Closes the socket.
-
readyState: WebSocketReadyState
Current lifecycle state of the underlying socket.
-
send(data: string | Uint8Array): void
Sends a frame to the peer. A
stringis sent as a text frame, aUint8Arrayas a binary frame.
Handle to one spawned worker thread, normalized across web Worker
(Deno/Bun) and node:worker_threads (Node).
-
onError(listener: (error: Error) => void): void
Registers a listener for worker-level errors (module evaluation failure, uncaught error in the worker).
-
onExit(listener: (code: number | null) => void): void
Registers a listener for the worker's THREAD ENDING, however it ended — a clean self-termination included. This is distinct from
onError, which reports a failure the worker survived long enough to report; a worker that simply stops raises no error at all. -
onMessage(listener: (message: unknown) => void): void
Registers a listener for messages from the worker.
-
postMessage(message: unknown): void
Posts a structured-clonable message to the worker.
-
terminate(): Promise<void>
Terminates the worker immediately.
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).
-
availableParallelism(): number
Number of threads the host can usefully run in parallel.
-
reportsExit(): boolean
Reports whether handles from
spawnwill implementIWorkerHandle.onExit. -
spawn(specifier: string): IWorkerHandle
Spawns a module worker.
A pool of worker threads executing task modules off the event loop.
-
run<TInput, TOutput>(): Promise<TOutput>taskModule: string,input: TInput,options?: WorkerRunOptions
Runs a task on a pool worker for the given task module, creating the pool lazily on first use.
-
shutdown(): Promise<void>
Terminates every worker in every pool and rejects pending tasks. Called by the plugin's
onClosehook; safe to call more than once. -
stats(): readonly TaskPoolStats[]
Returns a snapshot of every pool created so far.
Options accepted when signing a JWT.
-
audience: string
Token audience.
-
expiresIn: string
Token lifetime (e.g.
"1h","7d"). -
issuer: string
Token issuer.
An outgoing email message.
-
bcc: readonly string[]
Blind-carbon-copy recipients.
-
cc: readonly string[]
Carbon-copy recipients.
-
from: string
Sender address; omitted to use the provider default.
-
html: string
HTML body.
-
subject: string
Subject line.
-
text: string
Plain-text body.
-
to: string | readonly string[]
Recipient address(es).
Transport metadata accompanying a delivered message.
-
headers: Readonly<Record<string, string>>
Transport headers read from the delivered message. First-party brokers populate this with
{}when their transport carried no headers. -
messageId: string
Broker-assigned message ID, when available.
-
timestamp: Date
Delivery timestamp, when available.
-
topic: string
The topic the message arrived on.
Configuration for registering a metric.
-
buckets: readonly number[]
Histogram bucket boundaries (histogram metrics only).
-
help: string
Human-readable description (Prometheus
HELP). -
labels: readonly string[]
Label names attachable to observations.
-
type: MetricType
The metric instrument kind.
Ergonomic options for the typed factory methods. type is injected by the
method name; help defaults to the metric name.
-
buckets: readonly number[]
Histogram bucket boundaries (histogram metrics only).
-
help: string
Human-readable description (Prometheus
HELP). Defaults to the metric name. -
labels: readonly string[]
Label names attachable to observations.
-
maxSamples: number
Summary only: bounded sample-window size.
-
quantiles: readonly number[]
Summary quantiles (summary metrics only).
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.
A repository query with every option resolved to a concrete value — the
shape a IDataSource evaluates.
-
cursor: string
A keyset cursor position, or
undefinedwhen the query starts at the first page. Carried alongsideoffsetrather than replacing it: an offset says "skip this many from the start" and a cursor says "after this row", and the two are contradictory — a query carrying both is refused by name (§3.10). -
filter: FilterExpression
Optional portable expression conjoined with
where. -
limit: number
Maximum results, or
-1for unlimited. -
offset: number
Number of leading rows to skip.
-
orderBy: Record<string, OrderDirection>
Field-to-direction sort specification. Empty means no ordering.
-
select: readonly string[]
Field projection. Empty means all fields.
-
where: Record<string, unknown>
Filter conditions, matched by equality. Empty means no filter.
A notification dispatched across one or more channels.
-
body: string
Notification body.
-
channels: readonly string[]
Channel names to dispatch on (e.g.
['email', 'sms']). -
metadata: Readonly<Record<string, unknown>>
Channel-specific extras.
-
subject: string
Subject/title, for channels that support one.
-
to: Readonly<Record<string, string>>
Recipient addresses keyed by channel (e.g.
{ email: '…', phone: '…' }).
A successful result carrying a value.
-
success: true
Discriminant:
truefor success. -
value: T
The success value.
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).
-
nextCursor: string | null
A cursor to fetch the next page, or
nullwhen the page is the last. -
rows: Record<string, unknown>[]
The rows in this page, already filtered, sorted, paginated and projected.
Per-call overrides for IServiceDiscovery.pick.
-
strategy: LoadBalanceStrategy
Overrides the plugin-configured strategy for this call only.
The clock-and-timer surface createCachedProbe runs on, bound to
a runtime.
-
clearTimer: (handle: TimerHandle) => void
Cancels a timer created by
ProbeTiming.setTimer— the runtime'sclearTimeout. -
hrtime: () => number
Monotonic clock in milliseconds — the runtime's
hrtime. Measures the cache TTL as an interval, never a wall-clock reading. -
setTimer: () => TimerHandlefn: () => void,ms: number
Timer used to bound each probe — the runtime's
setTimeout.
Options accepted when registering a processor.
-
concurrency: number
Jobs processed concurrently by this worker (default 1).
-
onFailed: () => void | Promise<void>job: IJob,error: unknown
Invoked once when a job has exhausted its attempts, immediately before it is dead-lettered — the only programmatic notice that work was permanently abandoned. It does NOT fire on an attempt that will be retried.
Options accepted when registering a provider.
-
scope: ServiceScope
Lifecycle scope (defaults to the container's default scope).
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 isapplication/octet-streamon 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.
RBAC configuration for role hierarchy and permissions.
-
roles: Readonly<Record<string, RoleDefinition>>
Role definitions keyed by role name.
One broadcast crossing the backplane.
-
binary: boolean
True when
RealtimeFrame.datais base64-encoded binary. -
data: string
The payload, always a string.
-
exceptId: string
The connection excluded from this broadcast, by ID.
-
kind: RealtimeFrameKind
Which consumer the frame belongs to.
-
name: string
The room or channel name the frame addresses.
-
origin: string
The publishing instance's identity.
Options accepted when scheduling a recurring job.
-
cron: string
Cron expression controlling the schedule.
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.
Options accepted by IMessageBroker.request.
-
timeoutMs: number
Reply wait budget in milliseconds. When no correlated reply arrives within this window,
requestrejects. Defaults to5000when omitted.
Retry configuration for a scheduled job.
-
backoff: SchedulerBackoff
Backoff strategy. Defaults to
'fixed'. -
delay: number
Base delay in milliseconds for the first retry.
-
limit: number
Maximum number of attempts before giving up (1-based minimum).
Retry policy consumed by the ResiliencePlugin's retry pattern.
-
backoff: BackoffStrategy
Backoff strategy applied to
delay. -
delay: number
Base backoff delay in milliseconds.
-
limit: number
Maximum total attempts (
1= a single attempt, no retry).
Role definition for RBAC configuration.
-
inherits: readonly string[]
Role names this role inherits from (transitive).
-
permissions: readonly string[]
Permissions granted by this role.
Options for a room broadcast.
-
except: IWebSocketConnection
A member to skip — typically the sender, so it does not echo to itself.
Full route definition, used when a route needs middleware or schemas in addition to its handler.
-
handler: RouteHandler
The route handler.
-
middleware: readonly MiddlewareFunction[]
Route-level middleware, executed before the handler.
-
schema: RouteSchema
Validation and OpenAPI schemas.
Route information returned by IRouterApi.listRoutes.
-
definition: RouteDefinition
The route definition including handler, middleware, and schema.
-
method: HttpMethod
HTTP method of the route.
-
owner: string
Name of the plugin that registered this route.
-
path: string
Route path pattern (router-style with
:paramsegments).
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.
-
body: unknown
Request body schema.
-
headers: unknown
Header schema.
-
params: unknown
Path parameter schema.
-
query: unknown
Query parameter schema.
-
response: Readonly<Record<number, unknown>>
Response schemas keyed by status code.
-
security: readonly SecurityRequirement[]
OpenAPI security requirements for this operation, overriding any document-level default. Each entry names a scheme declared in the document's
components.securitySchemesand lists the scopes it needs (empty for non-OAuth2 schemes such as HTTP bearer or API key). -
summary: string
OpenAPI operation summary.
-
tags: readonly string[]
OpenAPI tags.
What a middleware function enforces, for documentation generators.
-
authenticated: boolean
truewhen the middleware requires an authenticated principal;falsewhen it explicitly marks the route public.
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.
-
schema: unknown
The schema it validates against, exactly as the caller supplied it.
-
target: ValidationTarget
Which part of the request the middleware validates.
A scheduled job instance handed to the handler.
-
attempts: number
Current attempt number (1-based).
-
data: T
Payload data supplied by the caller.
-
id: string
Unique job identifier.
-
name: string
Human-readable job name.
Options passed when scheduling a job.
-
data: T
Payload data handed to the handler.
-
retry: RetryOptions
Retry configuration. When absent the job runs once.
A plain, serializable representation of a thrown value.
-
cause: SerializedError
The serialized
cause, when the error carries one. -
classifiers: Readonly<Record<string, string | number | boolean>>
Safe scalar driver fields useful for error classification.
-
errors: readonly SerializedError[]
Serialized members of an
AggregateError, when present. -
message: string
The error's
message, or the stringified value for a non-Errorvalue. -
name: string
The error's
name(e.g.'Error','HttpError'), or'Error'for a non-Errorvalue. -
omittedErrorCount: number
Number of direct aggregate members omitted by the serialization budget.
-
stack: string
The error's
stack, when present.
One reachable instance of a service.
-
host: string
Hostname or IP literal. IPv6 literals arrive unbracketed.
-
id: string
Instance identity, unique within the service.
-
metadata: Readonly<Record<string, string>>
Free-form key/value metadata the backend carries.
-
port: number
TCP port.
-
secure: boolean
Whether the instance speaks TLS, deciding the
httpsscheme. -
serviceName: string
The logical service this instance belongs to.
-
tags: readonly string[]
Free-form labels the backend carries (Consul tags, for example).
-
weight: number
Relative selection weight for the
'weighted-random'strategy.
Options accepted when creating a signed URL.
-
expiresIn: number
URL validity in seconds.
An Option holding a value.
-
present: true
Discriminant:
truewhen a value is present. -
value: T
The contained value.
The return type of ISpan.spanContext.
-
spanId: string
16-character lowercase hex span ID.
-
traceFlags: string
2-character lowercase hex trace flags.
-
traceId: string
32-character lowercase hex trace ID.
Options for span creation.
-
attributes: Readonly<Record<string, SpanAttributeValue>>
Initial attributes to set on the span.
-
kind: SpanKind
The span kind (defaults to
'internal'). -
parentContext: TelemetryContext
Optional parent context for span parenting.
The two halves of a Workers env record.
-
bindings: Readonly<Record<string, object>>
Entries whose value is a non-null object — the platform bindings.
-
vars: Readonly<Record<string, string>>
Entries whose value is a string — safe for
IRuntimeServices.env.
One DNS SRV record, normalized across runtimes.
-
host: string
Target hostname. Trailing dots are left as the resolver returned them.
-
port: number
TCP port the service listens on.
-
priority: number
RFC 2782 priority — clients use the lowest-numbered tier first.
-
weight: number
RFC 2782 weight — relative share within one priority tier.
A named broadcast channel within the SSE hub.
-
add(conn: ISseConnection): void
Adds a connection to this channel's membership.
-
publish(msg: SseMessage): void
Publishes a message to every open member of this channel, skipping any connection whose
ISseConnection.isOpenisfalse. -
remove(conn: ISseConnection): void
Removes a connection from this channel's membership.
-
size: number
Number of currently open connections in this channel.
A single SSE event payload.
-
data: JsonValue
Event data. A
stringis written literally (split on\ninto multipledata:lines); any non-string isJSON.stringify-ed.undefinedis 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; enablesLast-Event-IDresume. -
retry: number
Reconnection time in milliseconds — sent as
retry:field.
Options for starting the application server.
-
hostname: string
Bind address (defaults to all interfaces).
-
port: number
TCP port to listen on.
File metadata returned by IFileSystem.stat.
-
isDirectory: boolean
Whether the path is a directory.
-
isFile: boolean
Whether the path is a regular file.
-
mtime: Date
Last modification time, when the runtime provides it.
-
size: number
Size in bytes.
Options accepted when subscribing to a topic.
-
queue: string
Consumer group / queue name for load-balanced delivery.
A snapshot of one task-module pool's state, returned by
IWorkerPool.stats.
-
busy: number
Workers currently executing a task.
-
completed: number
Tasks completed successfully since the pool was created.
-
failed: number
Tasks failed (error, crash, or timeout) since the pool was created.
-
queued: number
Tasks waiting in the pool's queue.
-
taskModule: string
The task-module specifier this pool executes.
-
workers: number
Workers currently alive in the pool.
Opaque handle representing the parent context for span creation.
-
_opaque: TELEMETRY_CONTEXT_OPAQUE
Internal marker — consumers must not inspect this type.
-
spanId: string
16-character lowercase hex parent span ID (W3C format).
-
traceFlags: string
2-character lowercase hex trace flags (W3C format).
-
traceId: string
32-character lowercase hex trace ID (W3C format).
-
tracestate: string
Raw
tracestateheader value, if present.
Optional controls for opening a transaction.
-
isolation: TransactionIsolationLevel
Requested isolation level; omitted preserves the adapter default.
A single validation failure.
-
code: string
Machine-readable failure code, when the validator provides one.
-
message: string
Human-readable description of the failure.
-
path: string
Dot-path of the offending field (e.g.
"address.zip").
Payload of a WebSocket close, normalized across runtimes.
-
code: number
The RFC 6455 close code (e.g.
1000normal,1001going away). -
reason: string
The close reason; an empty string when the peer supplied none.
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.userthroughIWebSocketService.routeUpgrade; omitted when the upgrade was not authenticated. Read this inonOpento identify the peer rather than re-deriving it from the headers.
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.
-
onClose(event: WebSocketCloseEvent): void
Called once, when the socket closes for any reason.
-
onError(error: Error): void
Called when the socket reports a transport-level error. A socket that errors is also expected to close, so implementations must tolerate
WebSocketEventSink.onClosearriving afterwards. -
onMessage(data: string | Uint8Array): void
Called for every inbound frame.
-
onOpen(transport: IWebSocketTransport): void
Called once, when the socket is live and writable.
The lifecycle callbacks an application supplies per WebSocket route.
-
onClose(): void | Promise<void>conn: IWebSocketConnection,event: WebSocketCloseEvent
Called once, when the connection closes for any reason.
-
onError(): void | Promise<void>conn: IWebSocketConnection,error: Error
Called on a transport error, and on a rejected promise from any other callback.
-
onMessage(): void | Promise<void>conn: IWebSocketConnection,data: string | Uint8Array
Called for every inbound frame.
-
onOpen(): void | Promise<void>conn: IWebSocketConnection,context: WebSocketConnectionContext
Called once per connection, after the handshake completes.
A named broadcast group of connections — the bidirectional analogue of the SSE plugin's channels.
-
add(conn: IWebSocketConnection): void
Adds a connection to this room.
-
broadcast(): voiddata: string | Uint8Array,options?: RoomBroadcastOptions
Sends a frame to every open member, skipping any closed member and any member named by
options.except. -
broadcastJson<T>(): voidpayload: T,options?: RoomBroadcastOptions
Serializes a value to JSON once and broadcasts it as a text frame.
-
name: string
The room name.
-
remove(conn: IWebSocketConnection): void
Removes a connection from this room.
-
size: number
Number of currently open members.
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-Protocolmatches none of them is rejected with 400. When omitted, no protocol is negotiated and none is echoed.
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.
-
protocol: string | undefined
The negotiated subprotocol to echo back, when one was selected.
-
sink: import("./services/websocket.ts").WebSocketEventSink
The sink the adapter binds its native socket events into.
Serialized shape of an error crossing the thread boundary in a
WorkerTaskReply.
-
message: string
The remote error's
message. -
name: string
The remote error's
name. -
stack: string
The remote error's
stack, when available.
Posted once by the worker side (defineWorkerTask) after its message
handler is wired; the pool dispatches tasks only to ready workers.
-
__hewp: 1
Protocol marker.
-
kind: "ready"
Discriminant.
Options for one IWorkerPool.run call.
-
timeoutMs: number
Per-call task timeout in milliseconds, overriding the pool's configured timeout.
0disables the timeout for this call.
A task outcome posted by the worker back to the pool.
-
__hewp: 1
Protocol marker.
-
error: WorkerErrorShape
The serialized error when
okisfalse. -
id: number
Correlation id echoed from the request.
-
kind: "reply"
Discriminant.
-
ok: boolean
Whether the task handler returned normally.
-
result: unknown
The handler's return value when
okistrue.
A task dispatch posted by the pool to a worker.
-
__hewp: 1
Protocol marker.
-
id: number
Correlation id, unique per pool.
-
input: unknown
Structured-clonable task input.
-
kind: "task"
Discriminant.
Options selecting which resilience patterns wrap a protected call.
-
bulkhead: boolean | BulkheadPolicy
Bulkhead layer:
trueuses the default, a policy overrides. -
circuitBreaker: boolean | CircuitBreakerPolicy
Circuit breaker layer:
trueuses the default, a policy overrides. -
retry: boolean | RetryPolicy
Retry layer:
trueuses the default, a policy overrides. -
timeout: number
Per-attempt timeout in milliseconds; absent disables the timeout layer.
Backoff strategy applied to a RetryPolicy's base delay.
A capability token: a lowercase kebab-case string that identifies a capability, not a concrete type.
| { readonly channel: string; readonly ok: false; readonly error: SerializedError; }
The settled outcome of dispatching a notification on a single channel.
Circuit breaker states.
A CLI command implementation.
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).
A constructable class reference.
A scalar value retained by a portable keyset cursor.
Handler invoked when a custom decorator is applied; receives the metadata the decorator captured.
A primary key value: a scalar string, a scalar number, or a composite
key expressed as a readonly record of named columns to values.
Handles one event type.
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "contains"; readonly value: string; }
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "gt" | "gte" | "lt" | "lte"; readonly value: string | number | Date; }
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "in"; readonly value: readonly unknown[]; }
A comparison of one entity field against a scalar value or value list.
| { readonly type: "and" | "or"; readonly filters: readonly FilterExpression[]; }
A portable filter tree evaluated by every repository backend.
Operators supported by a portable repository filter comparison.
The two request encodings a form body can carry.
One form value: a plain field string, or a FormFile.
| { kind: "single"; status: number; result: GraphqlExecutionResult; }
| { kind: "stream"; status: number; stream: AsyncIterable<GraphqlExecutionResult>; }
Discriminated outcome of a subscription operation.
The serving status returned by the health bridge. These values map onto the gRPC v1 Health response enum.
The hardened callable returned by IResilienceService.wrap.
Function form of a health indicator.
Health state reported by a health indicator.
| "HEAD"
| "POST"
| "PUT"
| "PATCH"
| "DELETE"
| "OPTIONS"
HTTP request methods supported by the router.
The ingress path a unit of non-HTTP work arrived on.
Processes jobs of one name.
| number
| boolean
| null
| readonly JsonValue[]
| { readonly [key: string]: JsonValue | undefined; }
A value JSON.stringify can serialize.
| "init"
| "bootstrap"
| "active"
| "shutdown"
| "close"
Application lifecycle phases, in execution order.
How IServiceDiscovery.pick chooses among healthy instances.
Log severity levels, ordered from most to least severe.
Structured metadata attached to a log entry.
Handles messages delivered on a subscription.
Metric instrument kinds supported by the metrics capability.
A middleware function: pre-process, call next(), post-process. May
short-circuit by returning a response without calling next().
Continues the middleware pipeline. Not calling it short-circuits the pipeline (the caller must have produced a response).
An optional value: either Some or None. Narrow
with the present discriminant or the isSome/isNone
guards.
Sort direction for a single field.
One exclusion entry: an exact path, or a pattern tested against the path.
Union of the well-known priority values in PLUGIN_PRIORITY.
Any provider form accepted by IContainer.register.
Receives frames published by other instances.
Which kind of broadcast group a RealtimeFrame addresses.
A factory that constructs a registry entry from the service registry.
Responder for a request topic. Its resolved value is sent back to the caller as the reply, correlated to the originating request.
A call protected by the resilience patterns.
| { readonly streaming: true; readonly status: number; readonly headers: Headers; readonly body: ReadableStream<Uint8Array>; readonly responseInit?: ResponseSnapshotInit | undefined; }
Discriminated union representing the possible shapes of an IResponse snapshot.
When streaming is false, body is a buffered Uint8Array | string | null.
When streaming is true, body is a live ReadableStream<Uint8Array>.
Native-response initialization data attached to a snapshot by the kernel
when its headers have not needed a mutable Headers instance.
-
headers: HeadersInit
Header input accepted directly by the web-standard
Responseconstructor.
The result of an operation that can fail: either Ok or
Err. Narrow with the success discriminant or the
isOk/isErr guards.
A route handler: receives the request context and returns a response via the context's response builder.
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.
JavaScript runtimes the framework can execute on.
A process-termination signal an application can shut down gracefully on.
Backoff strategy for retry delays.
Handler invoked when a scheduled job fires.
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.
Opaque handle for a running HTTP server, created and consumed only by the runtime's HTTP adapter.
A factory invoked lazily on the first lookup of a token registered with
IServiceRegistry.registerFactory.
How a call to an instance went, as reported by the caller.
Service lifecycle scopes.
Arbitrary serializable session payload.
A read-only projection of a session: its identifier and payload, with no mutation surface.
-
data: Readonly<SessionData>
The session payload, exactly as stored.
-
id: string
The session identifier.
| number
| boolean
| ReadonlyArray<string | number | boolean>
Attribute value — a span attribute can be a primitive or an array of primitives.
The kind of span. Maps to OTel SpanKind at the implementation boundary.
Span status — whether the span completed successfully or not.
Union of all standard capability token values.
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.
| "read-committed"
| "repeatable-read"
| "serializable"
Portable transaction isolation levels.
Removes a subscription when called.
The request part a validation middleware targets.
The result of a route-scoped WebSocket upgrade guard.
Lifecycle state of a WebSocket, normalized across runtimes to names rather than the numeric codes the web API uses.
| { readonly accept: false; readonly status: number; }
What an HTTP adapter should do with an inbound upgrade request, as decided
by the WebSocketUpgradeRouter.
A route-scoped predicate evaluated before a WebSocket handshake is accepted.
Consulted by an HTTP adapter for every inbound WebSocket upgrade request.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
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.
The brand under which an errorHandler middleware function carries its
resolved IErrorResponder.
The ctx.state key under which an application's resolved error responder is
published.
Key under which an Error carries its HttpStatusHint.
Well-known plugin registration priorities. Lower numbers register first.
-
HIGH: number
Logging, configuration — capabilities most plugins consume.
-
HIGHEST: number
Runtime and other must-run-first infrastructure.
-
LOW: number
Plugins that want most capabilities available before they register.
-
LOWEST: number
Observers that must register after everything else.
-
NORMAL: number
Default band for ordinary capability plugins.
-
OPENAPI: number
OpenAPI plugin — generates spec after routes are registered.
Key under which a MiddlewareFunction carries its
RouteSecurityMetadata.
Opaque marker symbol for TelemetryContext.
The W3C header carrying a trace parent. @since 0.2.0
The W3C header carrying vendor trace state. @since 0.2.0
Key under which the kernel terminal handler brands an IRequest
with a WebSocket upgrade intent.
Key under which a MiddlewareFunction carries its
RouteValidationMetadata.
Creates the ConfigPlugin.
Builds an immutable configuration snapshot from the environment.
Options for ConfigPlugin and loadConfig.
-
envFileOptional: boolean
When
true, a path inConfigPluginOptions.envFilePaththat does not exist is skipped instead of throwing. Defaults tofalse, which is the behaviour released in 0.1.0. -
envFilePath: string | readonly string[]
Path or paths to
.envfiles to load. Defaults to no file loading. When supplied, the runtime must providefs(absent on edge platforms). -
expandVariables: boolean
When
true(default), expand${NAME}references in values. Set tofalseto 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.
Minimal structural schema interface compatible with Zod's parse(unknown)
API. Consumers supply a Zod schema without config-plugin depending on Zod.
-
parse(input: unknown): T
Parses and validates the input, applying coercions and defaults.
Concrete command bus implementing ICommandBus.
-
clear(): void
Clears all registered command handlers.
-
execute<TResult = unknown>(command: CqrsCommand): Promise<TResult>
Executes a command.
-
handlerCount(): number
The number of registered command handlers.
-
register<TCommand extends CqrsCommand, TResult>(): voidtype: string,handler: ICommandHandler<TCommand, TResult>
Registers a command handler.
-
setBehaviors(behaviors: readonly IPipelineBehavior[]): void
Replaces the behavior list.
Thrown by CommandBus.execute and QueryBus.execute
when no handler is registered for the request's type.
-
requestType: string
The request type that had no handler.
Concrete query bus implementing IQueryBus.
-
clear(): void
Clears all registered query handlers.
-
execute<TResult = unknown>(query: CqrsQuery): Promise<TResult>
Executes a query.
-
handlerCount(): number
The number of registered query handlers.
-
register<TQuery extends CqrsQuery, TResult>(): voidtype: string,handler: IQueryHandler<TQuery, TResult>
Registers a query handler.
-
setBehaviors(behaviors: readonly IPipelineBehavior[]): void
Replaces the behavior list.
Creates the CQRS plugin.
One command handler and the command type the bus routes to it.
-
handler: ICommandHandler | RegistryFactory<ICommandHandler>
The handler to register for that type, or a factory that builds one from the service registry.
-
type: string
Command type name, matching
command.type.
A command: a request that mutates state and returns a result.
Options for CqrsPlugin.
-
behaviors: readonly (IPipelineBehavior | RegistryFactory<IPipelineBehavior>)[]
Pipeline behaviors applied to every command and query execution.
-
commandHandlers: readonly CommandHandlerRegistration[]
Command handlers registered on the command bus at
register()time. -
queryHandlers: readonly QueryHandlerRegistration[]
Query handlers registered on the query bus at
register()time.
A query: a request that returns data without side effects.
A CQRS request identified by a string type and carrying typed data.
-
data: TData
The request payload.
-
type: string
Request type name (e.g.
"CreateUser"). Used for routing.
Registers and executes commands.
-
execute<TResult = unknown>(command: CqrsCommand): Promise<TResult>
Executes a command.
-
register<TCommand extends CqrsCommand, TResult>(): voidtype: string,handler: ICommandHandler<TCommand, TResult>
Registers a handler for a command type.
Handles one command type.
-
handle(command: TCommand): TResult | Promise<TResult>
Executes the command.
Facade combining command and query buses.
-
commandBus: ICommandBus
The command bus.
-
queryBus: IQueryBus
The query bus.
Wraps a handler with cross-cutting logic (logging, timing, validation, etc.).
-
handle(): TResult | Promise<TResult>request: TRequest,next: () => Promise<TResult>
Wraps the next handler in the pipeline.
Registers and executes queries.
-
execute<TResult = unknown>(query: CqrsQuery): Promise<TResult>
Executes a query.
-
register<TQuery extends CqrsQuery, TResult>(): voidtype: string,handler: IQueryHandler<TQuery, TResult>
Registers a handler for a query type.
Handles one query type.
-
handle(query: TQuery): TResult | Promise<TResult>
Executes the query.
One query handler and the query type the bus routes to it.
-
handler: IQueryHandler | RegistryFactory<IQueryHandler>
The handler to register for that type, or a factory that builds one from the service registry.
-
type: string
Query type name, matching
query.type.
Shared repository implementation that normalizes options and delegates
data operations to a DataSource.
-
coerceId(id: Id): EntityKey
Cast the entity id to the type the adapter expects.
-
count(options?: CountOptions): Promise<number>
Count entities with optional filtering.
-
create(data: Partial<Entity>): Promise<Entity>
Insert a new entity.
-
delete(id: Id): Promise<boolean>
Delete an entity by primary key.
-
exists(id: Id): Promise<boolean>
Check whether an entity with the given primary key exists.
-
findAll(options?: FindOptions): Promise<Entity[]>
Fetch entities with optional filtering, sorting, and pagination.
-
findById(id: Id): Promise<Entity | null>
Fetch a single entity by its primary key.
-
findOne(options?: FindOptions): Promise<Entity | null>
Find the first entity that matches the supplied query options.
-
findPage(options: PageOptions): Promise<Page<Entity>>
Find a page of entities by cursor pagination.
-
toEntity(row: Partial<Record<string, unknown>>): Entity
Cast a raw row to the typed Entity.
-
update(): Promise<Entity>id: Id,data: Partial<Entity>
Update an existing entity by primary key.
The Bigtable adapter.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Opens a single-row deferred-write transaction.
-
connect(): Promise<void>
Resolves the client and the instance handle.
-
createDataSource(entity: string): IDataSource
Returns a data source for the named entity's table. @inheritdoc
-
disconnect(): Promise<void>
Releases the client.
-
isReady(): boolean
Reports whether the adapter is connected. @inheritdoc
-
rawQuery<T>(): Promise<T[]>_sql: string,_params?: unknown[]
Refuses the raw query by name.
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
Bigtable exposes no portable transaction-isolation selector.
Thrown when a Bigtable transaction is asked to write a second row.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
The Cosmos adapter — an Azure Cosmos DB NoSQL-API backend.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Opens a deferred-write transaction whose buffer is flushed as one transactional batch at commit.
-
connect(): Promise<void>
Establishes the connection: resolves the client and proves the database is reachable with these credentials.
-
createDataSource(entity: string): IDataSource
Returns a data source for the named entity's container. @inheritdoc
-
disconnect(): Promise<void>
Releases the client and the per-container caches.
-
isReady(): boolean
Reports whether the adapter is connected. @inheritdoc
-
rawQuery<T>(): Promise<T[]>_sql: string,_params?: unknown[]
Refuses the raw query by name.
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
Cosmos DB exposes no portable transaction-isolation selector.
Thrown when a Cosmos update loses an optimistic-concurrency race.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Thrown when a Cosmos transaction is asked to do something a transactional batch cannot express.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Database service implementation wrapping an ORM adapter.
- close(): Promise<void>
-
getRepository<Entity, Id extends EntityKey = string>(entity: string): IRepository<Entity, Id>
Returns a repository bound to the named entity on the outer database scope.
-
isClosed(): boolean
Reports whether
closehas run — a LIFECYCLE-only read that reaches no adapter and performs no I/O (M90b). - isHealthy(): Promise<boolean>
- migrate(): Promise<void>
-
query<T>(): Promise<T[]>sql: string,params?: unknown[]
-
transaction<T>(): Promise<T>work: (uow: IUnitOfWork) => Promise<T>,options?: TransactionOptions
Drizzle adapter wrapping a Drizzle database instance.
- beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
- connect(): Promise<void>
- createDataSource(entity: string): DataSource
-
createDataSourceForEntity(entity: string): DataSource
Create a DataSource for the named entity using the main instance.
- disconnect(): Promise<void>
- isReady(): boolean
-
rawQuery<T>(): Promise<T[]>sql: string,params?: unknown[]
-
transactionIsolationLevels(): readonly TransactionIsolationLevel[]
The branded transaction bridge either accepts every portable level or no isolation request at all; it is the application's explicit guarantee.
Repository backed by the Drizzle adapter.
The DynamoDB adapter — a key-value store backend served through the portable data-access contract.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Opens a deferred transaction: an empty buffer shared by every data source created from the returned handle. Commit flushes the buffer as one
TransactWriteItemscall; rollback discards it and sends nothing. -
connect(): Promise<void>
Establishes the adapter's client, resolving the injected or lazy loader.
-
createDataSource(entity: string): IDataSource
Returns a data source for the named entity's table. @inheritdoc
-
disconnect(): Promise<void>
Destroys the client the adapter constructed and releases it. An injected client is released without
destroy(): it belongs to the application, which may reuse it. -
isReady(): boolean
Reports whether the adapter resolved a client. @inheritdoc
-
rawQuery<T>(): Promise<T[]>_sql: string,_params?: unknown[]
Refuses the raw SQL query by name — DynamoDB has no SQL — rather than emulating it (the silent-divergence defect M70j closed). The error names the adapter and points at the client for native commands.
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
DynamoDB exposes no portable transaction-isolation selector.
In-memory implementation of IDatabaseAdapter.
- beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
- connect(): Promise<void>
-
countEntities(): Promise<number>entity: string,where: Record<string, unknown>,filter?: FilterExpression
Count entities matching a filter.
-
createDataSource(): DataSourceentity: string,primaryKey?: string | readonly string[]
-
deleteEntity(): Promise<boolean>entity: string,id: EntityKey
Delete an entity by primary key.
- disconnect(): Promise<void>
-
findEntityById(): Promise<Record<string, unknown> | null>entity: string,id: EntityKey
Find a single entity by its primary key value.
-
findPageInternal(): Promise<PageResult>entity: string,query: NormalizedQuery,getRecords: () => Record<string, unknown>[]
Core
findPageimplementation shared between the non-transactional data source and the transaction overlay. ThegetRecordsthunk lets the two callers — the committed store and the per-tx overlay — each supply their visible row set without duplicating the cursor-handling logic. -
getStore(): EntityStoreentity: string,primaryKey?: string | readonly string[]
Returns the internal store for an entity, creating it lazily.
-
insertEntity(): Promise<Record<string, unknown>>entity: string,data: Partial<Record<string, unknown>>
Insert a new entity. Generates key values if absent.
- isReady(): boolean
-
queryEntities(): Promise<Record<string, unknown>[]>entity: string,query: NormalizedQuery
Query entities with full filtering, sorting, and pagination.
-
rawQuery<T>(): Promise<T[]>_sql: string,_params?: unknown[]
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
Portable isolation levels this adapter can honestly provide.
-
updateEntity(): Promise<Record<string, unknown>>entity: string,id: EntityKey,data: Partial<Record<string, unknown>>
Update an existing entity by primary key, merging fields.
The Mongo adapter — a document-store backend over the native driver.
-
assertConnected(): void
Asserts the adapter is connected before a data operation.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Opens a driver session and calls
startTransaction(). A deployment without a replica set fails here, with the driver's own error wrapped inMongoTransactionUnavailableError— never atconnect(). -
connect(): Promise<void>
Establishes the database connection, resolving the client and database name.
-
createDataSource(entity: string): import("@setu-ts/common").IDataSource
Returns a data source for the named entity's collection. @inheritdoc
-
disconnect(): Promise<void>
Closes the connection and releases the client. @inheritdoc
-
isReady(): boolean
Reports whether the adapter is connected. @inheritdoc
-
rawQuery<T>(): Promise<T[]>_sql: string,_params?: unknown[]
Refuses the raw SQL query by name — MongoDB has no SQL — rather than emulating it (the silent-divergence defect M70j closed). The error names the adapter and points at the injected client for native commands.
-
transactionIsolationLevels: readonly TransactionIsolationLevel[]
MongoDB snapshot isolation is not the portable serializable guarantee.
Prisma adapter wrapping the official Prisma client.
- beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
- connect(): Promise<void>
- createDataSource(entity: string): DataSource
-
createDataSourceForEntity(entity: string): DataSource
Create a DataSource for the named entity using the main client.
- disconnect(): Promise<void>
- isReady(): boolean
-
rawQuery<T>(): Promise<T[]>sql: string,params?: unknown[]
-
transactionIsolationLevels(): readonly TransactionIsolationLevel[]
Portable levels available from the resolved Prisma connector.
Repository backed by the Prisma adapter.
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
instanceofacross realms.
Concrete Unit of Work that holds a transaction and delegates repository creation to the database service within the transaction boundary.
-
commit(): Promise<void>
Commit the transaction. Must be called after all operations complete.
- getRepository<Entity, Id extends EntityKey = string>(entity: string): IRepository<Entity, Id>
-
rollback(): Promise<void>
Roll back the transaction. Called automatically by
DatabaseServiceon errors, but can also be called explicitly.
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
undefinedwhen the connector could not be determined.'sqlite'names the concrete refusal;undefinedmeans the adapter could not identify its connector and theprovideroption is the fix. -
name: string
Discriminant for consumers that cannot use
instanceofacross realms. -
operator: string
The filter operator that could not be translated (e.g.
'contains').
Thrown when a database adapter cannot honour a requested transaction isolation level.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Thrown by IDatabaseService.migrate because programmatic
migrations are not implemented by the current adapters.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
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
instanceofacross realms.
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
instanceofacross realms.
Creates the opaque configuration required by the Drizzle adapter and query accessors.
Creates a DataSource backed by a Drizzle instance for the given
entity name.
Creates the no-import arm of the client seam.
Creates the no-import arm of the DynamoDB client seam.
Creates the lazy SDK loader.
Creates the lazy DynamoDB SDK loader.
Creates a DataSource backed by a Prisma client for the given
entity name.
Creates the DatabasePlugin.
Decode a cursor token to its CursorPayload, or null when the
token is malformed.
Encode a CursorPayload as a base64url-encoded JSON token.
Returns the exact configured outer Drizzle database for a database service.
Returns Drizzle's callback-scoped transaction object for a Unit of Work.
Build the "row after this one" keyset comparison as a portable
FilterExpression.
Declares that an application-owned Drizzle bridge forwards transaction options to its driver.
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
findPagemay take before it returns a bounded — but explicitly non-terminal — page. Defaults to10. -
tables: Readonly<Record<string, BigtableEntityMapping>>
Per-entity table, row-key, column and value-encoding overrides, keyed by the entity name passed to
getRepository().
One stored cell: the raw value bytes, as text.
-
value: string
The cell value, as the text the adapter's value codec wrote.
Client construction settings consumed by the lazy SDK arm.
-
apiEndpoint: string
An explicit API endpoint, such as
127.0.0.1:8086forcbtemulator. -
projectId: string
The GCP project the instance lives in.
The deferred client-resolution seam the adapter lifecycle drives.
-
load(): Promise<IBigtableClient>
Resolves a client without forcing the injected arm through an SDK import.
-
owned: boolean
Whether the loader constructed the client itself.
The 'bigtable' arm — a Google Cloud Bigtable wide-column backend.
-
options: BigtableAdapterOptions
Bigtable adapter configuration;
instanceand one client form are required. -
type: "bigtable"
Selects the Bigtable arm.
How one entity name maps onto a physical Bigtable table.
-
columnFamily: string
The column family unmapped fields are written to. Defaults to
'cf'. -
columns: Readonly<Record<string, string>>
Per-field column addresses. A value of
'family'keeps the field name as the qualifier;'family:qualifier'names both. -
rowKey: BigtableRowKeyMapping
How the row key is composed. Defaults to
{ fields: ['id'] }. -
table: string
The table id. Defaults to the entity name itself.
-
valueEncoding: BigtableValueEncoding
How values round-trip through a cell. Defaults to
'tagged'.
What a read asks the server for.
-
filter: BigtableFilter
A server-side filter applied to every candidate row.
-
keys: readonly string[]
An explicit key list. A key with no row contributes no result.
-
limit: number
A server-side row cap. Omitted means unbounded.
-
ranges: readonly BigtableRowRange[]
Row-key ranges, unioned.
One row as a read returns it.
-
data: BigtableRowData
The row's cells.
-
key: string
The row key.
One end of a row-key range.
-
inclusive: boolean
Whether the boundary row itself is included.
-
value: string
The boundary row key.
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.
A row-key range. An omitted end is unbounded in that direction.
-
end: BigtableRowBoundary
The upper bound, or unbounded when omitted.
-
start: BigtableRowBoundary
The lower bound, or unbounded when omitted.
An exact byte range a cell value must fall in.
-
end: string
The inclusive upper bound.
-
start: string
The inclusive lower bound.
One access condition — the optimistic-concurrency guard the replace path uses.
-
condition: string
The
_etagthe write is conditional on. -
type: "IfMatch"
The condition kind; the adapter only ever sends
IfMatch.
The options both CosmosAdapterOptions arms share — everything
that is required or optional regardless of how the client is supplied.
-
containers: Readonly<Record<string, CosmosEntityMapping>>
Per-entity container, primary-key and partition-key overrides, keyed by the entity name passed to
getRepository(). -
database: string
The database the containers live in. Required on both arms: a Cosmos endpoint encodes no database name, so unlike a MongoDB URI there is nothing to fall back to.
A batch operation removing one document.
-
id: string
The document id.
-
operationType: "Delete"
The operation kind.
A batch operation inserting a whole document. The id is optional: the service mints one when the body carries none.
-
id: string
The document id, when the caller chose one.
-
operationType: "Create" | "Upsert"
The operation kind.
-
resourceBody: Record<string, unknown>
The document to write.
A batch operation carrying patch operations rather than a whole document.
-
id: string
The document id.
-
operationType: "Patch"
The operation kind.
-
resourceBody: { readonly operations: readonly CosmosPatchOperation[]; }
The patch operations, in the envelope the SDK expects.
A batch operation overwriting a whole document, which therefore names the document it replaces.
-
id: string
The document id.
-
operationType: "Replace"
The operation kind.
-
resourceBody: Record<string, unknown>
The document to write in its place.
The response a transactional batch answers with.
-
code: number
The overall status code;
200when every operation succeeded. -
result: readonly { readonly statusCode: number; }[]
The per-operation results, in the order the operations were sent.
The container definition the partition-key resolver reads.
-
partitionKey: { readonly paths?: readonly string[]; readonly kind?: string; }
The partition-key definition, present on every container.
The arm selecting the Cosmos adapter over the @azure/cosmos SDK — Azure
Cosmos DB's NoSQL (SQL) API.
-
options: CosmosAdapterOptions
Cosmos adapter configuration;
databaseand one credential form are required. -
type: "cosmos"
Selects the Cosmos arm.
How one entity name maps onto a physical Cosmos container.
-
container: string
The container name. Defaults to the entity name itself, so
getRepository('orders')needs no mapping at all. -
partitionKey: string | readonly string[] | readonly (readonly string[])[]
The document field path(s) carrying the partition key.
-
primaryKey: string
The repository-visible primary-key field name. Defaults to
'id'.
The response envelope every single-item operation answers with.
-
resource: T
The resource, or
undefinedwhen none was returned. -
statusCode: number
The HTTP status code.
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.
-
op: "set"
The operation kind.
-
path: string
The document path, always a single leading-slash segment.
-
value: unknown
The value to set.
One named query parameter. Values are always bound rather than interpolated, so a value can never be read as SQL.
-
name: string
The parameter name, including its leading
@. -
value: unknown
The bound value.
A parameterized Cosmos SQL query — the shape items.query accepts.
-
parameters: readonly CosmosQueryParameter[]
The bound parameters.
-
query: string
The SQL text, with
@nameplaceholders for every value.
Per-request options the adapter passes to a single-item operation.
-
accessCondition: CosmosAccessCondition
The optimistic-concurrency guard, when the write is conditional.
Options for IRepository.count.
-
filter: FilterExpression
Portable filter expression conjoined with
where. -
where: Record<string, unknown>
Filter conditions applied to the count query.
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
keysetPredicateas the tiebreaker fallback when a key column is absent fromorderBy. -
orderedValues: ReadonlyArray<CursorValue>
The value of every ordered field (in
orderBydeclaration order), from the row the cursor was minted against. Indexiis the value of the i-th entry ofObject.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.
The arm supplying an externally-implemented backend.
-
adapter: IDatabaseAdapter
The backend to use, already constructed. The plugin calls
connect()on it duringregister()anddisconnect()during shutdown; it never constructs or replaces it. -
type: "custom"
Selects the external-adapter arm.
Adapter-specific configuration passed to the database adapter.
-
drizzleInstance: DrizzleDatabaseIdentity
Inject the application's opaque configured Drizzle database, created by
createDrizzleDatabase(database, transactionBridge). Required whentype: 'drizzle'— seeDrizzleAdapterOptions, 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'— seeDrizzleAdapterOptions, 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).
The options every DatabasePluginOptions arm shares.
-
name: string
Named connection for multi-database support. Defaults to
'default'. -
options: DatabaseAdapterOptions
Adapter-specific options.
A point-in-time reading of the database driver's connection-pool counters (M90b).
-
idle: number
Connections currently idle in the pool.
-
total: number
Total connections the pool holds (idle + in use).
-
waiting: number
Callers currently waiting for a connection.
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#>>, MySQLJSON_UNQUOTE(JSON_EXTRACT(...))and SQLitejson_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
DatabasePoolCapacitysnapshot to thedatabasehealth indicator through an internal seam.
Per-entity overrides for the Drizzle adapter.
-
primaryKey: string | readonly string[]
Primary-key column(s) for this entity.
Opaque configuration for one exact Drizzle database and async transaction bridge.
Erased identity of a package-created Drizzle configuration.
The arm selecting the Drizzle adapter.
-
options: DrizzleAdapterOptions
Drizzle adapter configuration; the instance and table registry are required.
-
type: "drizzle"
Selects the Drizzle arm.
The options both DynamoAdapterOptions arms share — everything
that is optional regardless of how the client is supplied.
-
entities: Readonly<Record<string, DynamoEntityMapping>>
Per-entity table and key mappings, keyed by the entity name passed to
getRepository(). -
maxPageFetches: number
The maximum number of server pages one
findPagecall fetches while filling the page, defaulting to 10.
A DynamoDB attribute value in the subset the adapter reads and writes.
-
B: Uint8Array
A binary value.
-
BOOL: boolean
A boolean value.
-
BS: readonly Uint8Array[]
A set of binary values.
-
L: readonly DynamoAttributeValue[]
An ordered list of attribute values.
-
M: DynamoAttributeMap
A nested map value.
-
N: string
A base-10 number encoded as text.
-
NS: readonly string[]
A set of base-10 numbers encoded as text.
-
NULL: boolean
A DynamoDB null marker.
-
S: string
A UTF-8 string value.
-
SS: readonly string[]
A set of string values.
AWS client construction settings consumed by the lazy SDK arm.
-
credentials: unknown
AWS credentials or an SDK-supported credential provider.
-
endpoint: string
An optional custom endpoint, such as DynamoDB Local.
-
region: string
The AWS region supplied to
DynamoDBClient.
The deferred client-resolution seam used by the adapter lifecycle.
-
load(): Promise<IDynamoClient>
Resolves a client without forcing the injected arm through an SDK import.
A conditional expression used to prevent an unintended write.
-
ConditionExpression: string
A DynamoDB condition expression, including attribute-existence guards.
The arm selecting the DynamoDB adapter over the AWS SDK v3 client.
-
options: DynamoAdapterOptions
DynamoDB adapter configuration;
region(orclient) is required. -
type: "dynamodb"
Selects the DynamoDB arm.
Input for DynamoDB DeleteItem.
-
Key: DynamoAttributeMap
The complete primary key.
-
ReturnValues: "ALL_OLD"
Requests the prior row so deletion can report whether it existed.
-
TableName: string
The physical table to write.
Output from DynamoDB DeleteItem.
-
Attributes: DynamoAttributeMap
The deleted row when one existed and
ALL_OLDwas requested.
How one entity name maps onto a physical DynamoDB table.
-
dateAttributes: Readonly<Record<string, DynamoDateEncoding>>
The encoding each date-bearing attribute is stored under.
-
indexes: Readonly<Record<string, DynamoIndexMapping>>
The table's configured global secondary indexes, keyed by index name.
-
partitionKey: string
The table's partition-key attribute.
-
sortKey: string
The table's sort-key attribute, when the table is keyed by partition AND sort.
-
table: string
The table name. Defaults to the entity name itself, so
getRepository('users')needs no mapping at all.
Expression aliases shared by all command shapes.
-
ExpressionAttributeNames: Readonly<Record<string, string>>
Generated
#namealiases mapped to physical attribute names. -
ExpressionAttributeValues: DynamoAttributeMap
Generated
:valuealiases mapped to DynamoDB values.
Input for DynamoDB GetItem.
-
Key: DynamoAttributeMap
The complete primary key.
-
ProjectionExpression: string
A projection expression for selected attributes.
-
TableName: string
The physical table to read.
Output from DynamoDB GetItem.
-
Item: DynamoAttributeMap
The item, omitted when no item matches the key.
A configured global secondary index and its key schema.
-
partitionKey: string
The index's partition-key attribute.
-
sortKey: string
The index's sort-key attribute, when the index carries one.
Input for DynamoDB PutItem.
-
Item: DynamoAttributeMap
The complete item to persist.
-
TableName: string
The physical table to write.
Output from DynamoDB PutItem.
-
Attributes: DynamoAttributeMap
Returned attributes when the command asks for them.
Input for DynamoDB Query.
-
IndexName: string
An optional configured global secondary index.
-
KeyConditionExpression: string
The required partition-key condition, optionally with a sort condition.
-
ScanIndexForward: boolean
truefor ascending sort-key order andfalsefor descending.
Shared fields for a DynamoDB query or scan.
-
ExclusiveStartKey: DynamoAttributeMap
The server continuation key from the preceding response.
-
FilterExpression: string
A post-read filter expression.
-
Limit: number
The maximum number of evaluated items.
-
ProjectionExpression: string
A projection expression for selected attributes.
-
Select: "ALL_ATTRIBUTES"
| "ALL_PROJECTED_ATTRIBUTES"
| "COUNT"
| "SPECIFIC_ATTRIBUTES"The response shape requested from DynamoDB.
-
TableName: string
The physical table to read.
The common DynamoDB Query and Scan response shape.
-
Count: number
Number of returned or counted items in this response.
-
Items: readonly DynamoAttributeMap[]
Returned items, omitted by
Select: 'COUNT'. -
LastEvaluatedKey: DynamoAttributeMap
The authoritative server continuation key, when further results exist.
-
ScannedCount: number
Number of items DynamoDB evaluated before filtering.
The native DynamoDB SDK client operations driven by the facade.
-
destroy(): void
Releases resources owned by the AWS SDK client.
-
send<TInput, TOutput>(command: DynamoSdkCommand<TInput, TOutput>): Promise<TOutput>
Sends one DynamoDB command to the configured AWS endpoint.
A native DynamoDB SDK command accepted by DynamoSdkClient.
-
input: TInput
The command request supplied to the AWS SDK.
-
output: TOutput
The typed AWS SDK response, when a command carries one.
The native @aws-sdk/client-dynamodb module shape adapted by the lazy arm.
-
DeleteItemCommand: DynamoCommandConstructor<>DynamoDeleteItemCommandInput,DynamoDeleteItemCommandOutput
The AWS
DeleteItemCommandconstructor. -
DynamoDBClient: new (configuration: DynamoClientConfiguration) => DynamoSdkClient
The AWS DynamoDB client constructor.
-
GetItemCommand: DynamoCommandConstructor<DynamoGetItemCommandInput, DynamoGetItemCommandOutput>
The AWS
GetItemCommandconstructor. -
PutItemCommand: DynamoCommandConstructor<DynamoPutItemCommandInput, DynamoPutItemCommandOutput>
The AWS
PutItemCommandconstructor. -
QueryCommand: DynamoCommandConstructor<DynamoQueryCommandInput, DynamoReadCommandOutput>
The AWS
QueryCommandconstructor. -
ScanCommand: DynamoCommandConstructor<DynamoScanCommandInput, DynamoReadCommandOutput>
The AWS
ScanCommandconstructor. -
TransactWriteItemsCommand: DynamoCommandConstructor<>DynamoTransactWriteItemsCommandInput,DynamoTransactWriteItemsCommandOutput
The AWS
TransactWriteItemsCommandconstructor. -
UpdateItemCommand: DynamoCommandConstructor<>DynamoUpdateItemCommandInput,DynamoUpdateItemCommandOutput
The AWS
UpdateItemCommandconstructor.
A transactional Delete operation.
-
Key: DynamoAttributeMap
The complete primary key.
-
TableName: string
The physical table to write.
A transactional Put operation.
-
Item: DynamoAttributeMap
The complete item to persist.
-
TableName: string
The physical table to write.
A transactional Update operation.
-
Key: DynamoAttributeMap
The complete primary key.
-
TableName: string
The physical table to write.
-
UpdateExpression: string
The update expression to apply.
One transaction operation accepted by DynamoDB TransactWriteItems.
-
Delete: DynamoTransactDelete
A conditional delete operation.
-
Put: DynamoTransactPut
A conditional create operation.
-
Update: DynamoTransactUpdate
A conditional update operation.
Input for DynamoDB TransactWriteItems.
-
TransactItems: readonly DynamoTransactWriteItem[]
The ordered writes that DynamoDB commits atomically.
Input for DynamoDB UpdateItem.
-
Key: DynamoAttributeMap
The complete primary key.
-
ReturnValues: "ALL_NEW"
Requests the persisted row after a successful update.
-
TableName: string
The physical table to write.
-
UpdateExpression: string
The update expression to apply.
Output from DynamoDB UpdateItem.
-
Attributes: DynamoAttributeMap
The persisted row when
ReturnValuesisALL_NEW.
Options for IRepository.findAll.
-
cursor: string
A keyset cursor position, or
undefinedwhen the query starts at the first page. Carried alongsideoffsetrather than replacing it: an offset says "skip this many from the start" and a cursor says "after this row", and the two are contradictory — a query carrying both is refused by name (UnsupportedQueryFeatureError). -
filter: FilterExpression
Portable filter expression conjoined with
where. -
limit: number
Maximum number of results to return.
-
offset: number
Number of results to skip.
-
orderBy: Record<string, OrderDirection>
Field-to-direction sort specification.
-
select: readonly string[]
Select only specific fields (projection).
-
where: Record<string, unknown>
Filter conditions keyed by field name.
A transaction handle that can also open entity data sources bound to itself.
-
createDataSource(entity: string): IDataSource
Open a data source for
entitybound to THIS transaction.
The Bigtable client the adapter drives.
-
close(): Promise<void>
Releases the client's gRPC channels.
-
instance(id: string): IBigtableInstance
Returns a handle for one instance. No RPC is issued.
One Bigtable instance.
-
table(id: string): IBigtableTable
Returns a handle for one table. No RPC is issued.
The row-scoped write surface: one atomic check-and-mutate.
-
conditionalMutate(): Promise<boolean>test: readonly BigtableFilter[],branches: { readonly onMatch?: readonly BigtableMutation[]; readonly onNoMatch?: readonly BigtableMutation[]; }
Applies one branch of a CheckAndMutateRow atomically.
One table's data-plane surface.
-
readRows(options: BigtableReadOptions): Promise<BigtableReadRow[]>
Reads rows matching the supplied key set, range set and filter.
-
row(key: string): IBigtableRow
Returns the row-scoped write surface for one key.
A structural subset of the SDK CosmosClient — the members the adapter
drives.
-
database(id: string): ICosmosDatabase
Addresses a database by id. The database is not created.
A structural subset of the SDK Container — the members the adapter drives.
-
item(): ICosmosItemid: string,partitionKey?: CosmosPartitionKeyValue
Addresses one document by id and partition key.
-
items: ICosmosItems
The document collection.
-
read(): Promise<CosmosItemResponse<CosmosContainerDefinition>>
Reads the container definition, which is also what proves the container exists.
A structural subset of the SDK Database.
-
container(id: string): ICosmosContainer
Addresses a container by id. The container is not created.
-
read(): Promise<CosmosItemResponse<Record<string, unknown>>>
Reads the database, proving the credentials and the database name.
A structural subset of the SDK Item handle — one document addressed by its
id and partition key.
-
delete(): Promise<CosmosItemResponse<Record<string, unknown>>>
Deletes the document, throwing a 404 when it does not exist.
-
patch(operations: readonly CosmosPatchOperation[]): Promise<CosmosItemResponse<Record<string, unknown>>>
Applies a patch to the document server-side.
-
read(): Promise<CosmosItemResponse<Record<string, unknown>>>
Reads the document.
-
replace(): Promise<CosmosItemResponse<Record<string, unknown>>>body: Record<string, unknown>,options?: CosmosRequestOptions
Replaces the document wholesale.
A structural subset of the SDK Items collection — the members the data
source drives.
-
batch(): Promise<CosmosBatchResponse>operations: readonly CosmosBatchOperation[],partitionKey: CosmosPartitionKeyValue
Runs a transactional batch, atomic within one partition-key value.
-
create(body: Record<string, unknown>): Promise<CosmosItemResponse<Record<string, unknown>>>
Inserts one document, refusing a duplicate id within the partition.
-
query(spec: CosmosQuerySpec): ICosmosQueryIterator<Record<string, unknown>>
Runs a parameterized SQL query across the container.
A query iterator, narrowed to the one member the adapter uses.
-
fetchAll(): Promise<CosmosFeedResponse<T>>
Materializes every matching row.
The full database backend port: lifecycle plus data access.
-
beginTransaction(options?: TransactionOptions): Promise<IAdapterTransaction>
Begin a transaction, returning a handle that can open transaction-scoped data sources as well as commit and roll back.
-
createDataSource(entity: string): IDataSource
Open a non-transactional data source for the named entity.
-
rawQuery<T>(): Promise<T[]>sql: string,params?: unknown[]
Execute a raw query in the backend's own dialect.
High-level database service combining repository access, unit of work, raw queries, and lifecycle management.
-
close(): Promise<void>
Gracefully close all database connections.
-
getRepository<Entity, Id extends EntityKey = string>(entity: string): IRepository<Entity, Id>
Get a repository for the named entity type.
-
isHealthy(): Promise<boolean>
Health-check probe: verifies the database connection is alive.
-
migrate(): Promise<void>
Programmatic migrations are unsupported by the current adapters. Each ORM owns schema migration through its own CLI, so this rejects with
UnsupportedMigrationError. -
query<T>(): Promise<T[]>sql: string,params?: unknown[]
Execute a raw SQL query and return results.
-
transaction<T>(): Promise<T>work: (uow: IUnitOfWork) => Promise<T>,options?: TransactionOptions
Execute the
workcallback within a database transaction.
The data-access seam a backend provides per entity.
-
count(): Promise<number>where: Record<string, unknown>,filter?: FilterExpression
Count entities matching a filter.
-
create(data: Partial<Record<string, unknown>>): Promise<Record<string, unknown>>
Insert a new entity.
-
delete(id: EntityKey): Promise<boolean>
Delete an entity by primary key.
-
findAll(query: NormalizedQuery): Promise<Record<string, unknown>[]>
Find every entity matching the normalized query.
-
findById(id: EntityKey): Promise<Record<string, unknown> | null>
Find a single entity by its primary key value.
-
findPage(query: NormalizedQuery): Promise<PageResult>
Find a page of entities by cursor pagination.
-
update(): Promise<Record<string, unknown>>id: EntityKey,data: Partial<Record<string, unknown>>
Update an existing entity by primary key.
The structural DynamoDB facade the adapter drives.
-
deleteItem(input: DynamoDeleteItemCommandInput): Promise<DynamoDeleteItemCommandOutput>
Deletes one item.
-
destroy(): void
Releases resources held by a client constructed through the lazy path.
-
getItem(input: DynamoGetItemCommandInput): Promise<DynamoGetItemCommandOutput>
Reads a single item by its complete key.
-
putItem(input: DynamoPutItemCommandInput): Promise<DynamoPutItemCommandOutput>
Creates one item.
-
query(input: DynamoQueryCommandInput): Promise<DynamoReadCommandOutput>
Sends a key-constrained query.
-
scan(input: DynamoScanCommandInput): Promise<DynamoReadCommandOutput>
Scans a table or index when no key-constrained query is possible.
-
transactWriteItems(input: DynamoTransactWriteItemsCommandInput): Promise<DynamoTransactWriteItemsCommandOutput>
Commits a bounded set of writes atomically.
-
updateItem(input: DynamoUpdateItemCommandInput): Promise<DynamoUpdateItemCommandOutput>
Updates one existing item.
A structural subset of the driver MongoClient — the members the adapter
drives.
-
close(): Promise<void>
Closes the connection.
-
connect(): Promise<void>
Opens the connection.
-
db(name: string): IMongoDatabase
Returns the database named
name. -
startSession(): IMongoSession
Starts a new session.
A structural subset of the driver Collection — the methods the data source
calls to serve the six IDataSource methods.
-
countDocuments(): Promise<number>filter: Record<string, unknown>,options?: MongoWriteOptions
Counts matching documents.
-
deleteOne(): Promise<{ deletedCount: number; }>filter: Record<string, unknown>,options?: MongoWriteOptions
Deletes matching documents.
-
find(): IMongoCursorfilter: Record<string, unknown>,options?:MongoOptions
& { sort?: Record<string, unknown>; skip?: number; limit?: number; projection?: Record<string, 0 | 1>; }Finds matching documents.
-
findOne(): Promise<Record<string, unknown> | null>filter: Record<string, unknown>,options?:MongoOptions
& { projection?: Record<string, 0 | 1>; sort?: Record<string, unknown>; }Finds a single document.
-
findOneAndUpdate(): Promise<Record<string, unknown> | null>filter: Record<string, unknown>,update: Record<string, unknown>,options: IMongoCollectionFindOneAndUpdateOptions
Finds one document and applies an update, returning the updated document.
-
insertOne(): Promise<document: Record<string, unknown>,options?: MongoWriteOptions>{ acknowledged: boolean; insertedId: IMongoObjectId | string | number; }
Inserts one document.
The native driver findOneAndUpdate options the adapter passes through.
-
returnDocument: "before" | "after"
Returns the updated document (rather than the original).
-
session: IMongoSession
The session a transaction-scoped operation runs under.
A structural subset of the driver's cursor returned from find().
-
toArray(): Promise<Record<string, unknown>[]>
Materializes the cursor's matching documents.
A structural subset of the driver Database — what the collection resolver
reads.
-
collection(name: string): IMongoCollection
Returns the collection named
name.
A structural subset of the driver ObjectId — enough for the conversion
rules the mapping owns.
-
toString(): string
Serializes the id to its 24-hex string, the value callers address.
The driver ObjectId constructor shape.
-
isValid(value: unknown): boolean
Tests whether a value is a valid
ObjectId— exactly a 24-hex string, so a 12-char value is rejected.
A structural subset of the driver ClientSession — the members the
transaction path calls.
-
abortTransaction(): Promise<void>
Rolls the active transaction back.
-
commitTransaction(): Promise<void>
Commits the active transaction.
-
endSession(): Promise<void>
Ends the session, releasing its server resources.
-
startTransaction(options?: Record<string, unknown>): Promise<void>
Starts the transaction on this session.
Generic repository providing CRUD operations over an entity type.
-
count(options?: CountOptions): Promise<number>
Count entities with optional filtering.
-
create(data: Partial<Entity>): Promise<Entity>
Insert a new entity.
-
delete(id: Id): Promise<boolean>
Delete an entity by primary key.
-
exists(id: Id): Promise<boolean>
Check whether an entity with the given primary key exists.
-
findAll(options?: FindOptions): Promise<Entity[]>
Fetch entities with optional filtering, sorting, and pagination.
-
findById(id: Id): Promise<Entity | null>
Fetch a single entity by its primary key.
-
findOne(options?: FindOptions): Promise<Entity | null>
Fetch the first entity matching the optional filter.
-
findPage(options: PageOptions): Promise<Page<Entity>>
Find a page of entities by cursor pagination.
-
update(): Promise<Entity>id: Id,data: Partial<Entity>
Update an existing entity by primary key.
Unit of Work: transaction-scoped repository access.
-
getRepository<Entity, Id extends EntityKey = string>(entity: string): IRepository<Entity, Id>
Get a transaction-scoped repository for the named entity.
The arm selecting the zero-dependency in-memory adapter, which is also what
an omitted type means.
-
type: "memory"
ORM adapter type. Defaults to
'memory'.
The options both MongoAdapterOptions arms share — everything
that is optional regardless of how the client is supplied.
-
collections: Readonly<Record<string, MongoEntityMapping>>
Per-entity collection and primary-key overrides, keyed by the entity name passed to
getRepository(). -
database: string
The database the collections live in.
-
objectIdCtor: IMongoObjectIdCtor
The driver's
ObjectIdconstructor whenMongoAdapterOptions.clientis injected.
The arm selecting the Mongo adapter over the native mongodb driver.
-
options: MongoAdapterOptions
Mongo adapter configuration;
url(orclient) is required. -
type: "mongodb"
Selects the Mongo arm.
How one entity name maps onto a physical Mongo collection.
-
collection: string
The collection name. Defaults to the entity name itself, so
getRepository('users')needs no mapping at all. -
idType: "objectId" | "raw" | "compound"
How the collection stores its
_idvalues. -
primaryKey: string | readonly string[]
The primary-key field name(s). Defaults to
'id'.
Operation options the data source passes to every driver call — the session a transaction-scoped data source binds to.
-
session: IMongoSession
The session a transaction-scoped operation runs under.
A repository query with every option resolved to a concrete value — the
shape a IDataSource evaluates.
-
cursor: string
A keyset cursor position, or
undefinedwhen the query starts at the first page. Carried alongsideoffsetrather than replacing it: an offset says "skip this many from the start" and a cursor says "after this row", and the two are contradictory — a query carrying both is refused by name (§3.10). -
filter: FilterExpression
Optional portable expression conjoined with
where. -
limit: number
Maximum results, or
-1for unlimited. -
offset: number
Number of leading rows to skip.
-
orderBy: Record<string, OrderDirection>
Field-to-direction sort specification. Empty means no ordering.
-
select: readonly string[]
Field projection. Empty means all fields.
-
where: Record<string, unknown>
Filter conditions, matched by equality. Empty means no filter.
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).
-
nextCursor: string | null
A cursor to fetch the next page, or
nullwhen no further page exists. -
rows: Entity[]
The rows in this page, already filtered, sorted, paginated and projected.
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).
-
nextCursor: string | null
A cursor to fetch the next page, or
nullwhen the page is the last. -
rows: Record<string, unknown>[]
The rows in this page, already filtered, sorted, paginated and projected.
DatabaseAdapterOptions narrowed for the Prisma arm: the injected
client is required.
-
entities: Readonly<Record<string, PrismaCompositeKeyOptions>>
Per-entity overrides for key resolution and other model-specific tuning.
-
prismaClient: unknown
The application-generated Prisma v7 client. Required — a framework package cannot locate an application-selected generated-client output path, and
PrismaAdapter.connect()rejects without it.
Per-entity overrides for the Prisma adapter.
-
compositeKeyName: string
Override for the derived compound-key field name.
-
keyColumns: readonly string[]
The primary-key columns for this entity, in Prisma schema declaration order.
The arm selecting the Prisma adapter.
-
options: PrismaAdapterOptions
Prisma adapter configuration;
prismaClientis required. -
type: "prisma"
Selects the Prisma arm.
Optional controls for opening a transaction.
-
isolation: TransactionIsolationLevel
Requested isolation level; omitted preserves the adapter default.
& { readonly projectId: string; readonly apiEndpoint?: string; readonly client?: IBigtableClient; }
| (
& { readonly client: IBigtableClient; readonly projectId?: string; readonly apiEndpoint?: string; }
Options for the BigtableAdapter — the 'bigtable' arm.
| { readonly method: "insert"; readonly data: Readonly<Record<string, Readonly<Record<string, string>>>>; }
One mutation in a CheckAndMutateRow branch or a batch entry.
A row's cells, addressed family → qualifier → versions.
How a value round-trips through a cell.
| PrismaDatabaseOptions
| DrizzleDatabaseOptions
| MongoDatabaseOptions
| DynamoDatabaseOptions
| CosmosDatabaseOptions
| BigtableDatabaseOptions
The arm selecting one of the adapters this package ships.
& { readonly endpoint: string; readonly key: string; readonly client?: ICosmosClient; }
| (
& { readonly client: ICosmosClient; readonly endpoint?: string; readonly key?: string; }
Options for the CosmosAdapter — the 'cosmos' arm.
| CosmosBatchReplaceOperation
| CosmosBatchPatchOperation
| CosmosBatchDeleteOperation
One operation in a transactional batch.
| 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.
A scalar value retained by a portable keyset cursor.
Options for the DatabasePlugin factory.
The native transaction object supplied by a configured Drizzle database.
Promise-aware transaction bridge owned by the application at configuration.
& { readonly region: string; readonly endpoint?: string; readonly credentials?: unknown; readonly client?: IDynamoClient; }
| (
& { readonly client: IDynamoClient; readonly region?: string; readonly endpoint?: string; readonly credentials?: unknown; }
Options for the DynamoAdapter — the 'dynamodb' arm.
A DynamoDB item or key map.
A native DynamoDB SDK command constructor.
The storage encoding a date-bearing attribute is declared to use.
Input for DynamoDB Scan.
Output from DynamoDB TransactWriteItems.
A primary key value: a scalar string, a scalar number, or a composite
key expressed as a readonly record of named columns to values.
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "contains"; readonly value: string; }
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "gt" | "gte" | "lt" | "lte"; readonly value: string | number | Date; }
| { readonly type: "comparison"; readonly field: string | readonly string[]; readonly operator: "in"; readonly value: readonly unknown[]; }
A comparison of one entity field against a scalar value or value list.
| { readonly type: "and" | "or"; readonly filters: readonly FilterExpression[]; }
A portable filter tree evaluated by every repository backend.
Operators supported by a portable repository filter comparison.
& { readonly url: string; readonly client?: IMongoClient; }
| (
& { readonly client: IMongoClient; readonly url?: string; }
Options for the MongoAdapter — the 'mongodb' arm.
Write-path operation options the data source passes to the driver.
Sort direction for a single field.
Options for IRepository.findPage — the parameter shape.
| "postgres"
| "mysql"
| "sqlserver"
| "cockroachdb"
| "mongodb"
| "sqlite"
The SQL connector a Prisma client is bound to.
The SQL dialects whose JSON extraction syntax this module can emit.
| "read-committed"
| "repeatable-read"
| "serializable"
Portable transaction isolation levels.
The data-access seam adapter-specific implementations provide, keeping
BaseRepository decoupled from concrete ORM clients.
Concrete IMetadataStore. Decorators call the merge*/add*
methods; the DecoratorPlugin and other consumers read the readonly
controllers, services, and routes maps.
-
addCustomDecorator(record: CustomDecoratorRecord): void
Records a custom decorator for replay at registration time.
-
addRouteBinding(): voidtarget: Constructor,handler: string,method: HttpMethod,path: string
Adds an HTTP verb + path binding to a method (
@Get,@Post, …). -
clear(): void
Removes all stored metadata. Intended for test isolation — decorators applied at module-evaluation time are NOT re-run, so callers that rely on decorated fixtures should not clear between tests using those fixtures.
-
controllers(): Map<Constructor, Readonly<Record<string, unknown>>>
Controllers keyed by class.
-
ctorOptional(target: Constructor): ReadonlySet<number>
Returns the constructor-argument indices a class marked
@Optional. -
getController(target: Constructor): ControllerMetadata | undefined
Returns a class's controller metadata, or
undefined. -
getCustomDecorators(): readonly CustomDecoratorRecord[]
Returns all recorded custom decorators.
-
getMethods(target: Constructor): ReadonlyMap<string, MethodMeta>
Returns the method accumulators for a controller.
-
getModule(target: Constructor): ModuleMetadata | undefined
Returns a class's module declaration, if it has one.
-
getOrCreateMethod(): MethodMetatarget: Constructor,handler: string
Returns the (mutable) method accumulator for a controller method, creating it if absent.
-
getRoutesFor(target: Constructor): RouteMetadata[]
Returns the materialized
RouteMetadataentries for a controller — one per (method, HTTP verb). Unlike theIMetadataStore.routesgetter (loosely typed for external consumers), this returns the concrete shape the plugin composes routes from. -
getService(target: Constructor): ServiceMetadata | undefined
Returns a class's service metadata, or
undefined. -
hasController(target: Constructor): boolean
Reports whether a class has controller metadata.
-
hasService(target: Constructor): boolean
Reports whether a class has service metadata.
-
mergeController(): voidtarget: Constructor,partial: Partial<ControllerMetadata>
Merges a partial into a class's controller metadata, creating it if absent. Arrays append; scalar fields replace.
-
mergeCtorOptional(): voidtarget: Constructor,index: number
Marks one constructor parameter as optional, keyed by its argument index.
-
mergeModule(): voidtarget: Constructor,partial: Partial<ModuleMetadata>
Merges a partial module declaration into a class's metadata.
-
mergeService(): voidtarget: Constructor,partial: Partial<ServiceMetadata>
Merges a partial into a class's service metadata, creating it if absent.
-
mutateMethod(): voidtarget: Constructor,handler: string,mutate: (meta: MethodMeta) => void
Merges a partial into a method's accumulator. Arrays append; scalar fields replace. Parameter decorators append to
params. -
routes(): Map<>Constructor,ReadonlyArray<Readonly<Record<string, unknown>>>
Materialized route metadata, one entry per (controller, HTTP verb). Derived from the internal per-method accumulators so the result is independent of decorator application order.
-
services(): Map<Constructor, Readonly<Record<string, unknown>>>
Services keyed by class.
-
setCtorOptional(): voidtarget: Constructor,indices: Iterable<number>
Replaces a class's optional-argument set outright.
-
storeParam(): voidtarget: Constructor,handler: string,param: ParameterMetadata
Appends a parameter to a method's accumulator.
Describes the OpenAPI operation for a route handler.
Documents a response status for a route handler. May be applied multiple times to describe several responses.
Binds the parsed JSON request body.
Removes a registered custom parameter resolver (intended for tests).
Marks a class as a controller and assigns a base path prefix for all its routes.
Creates a custom class or method decorator that stores metadata readable by the DecoratorPlugin and custom decorator handlers.
Binds the active request context — for a handler that sets its own status code, adds a header, or returns a streaming response.
Binds the authenticated principal (ctx.request.user).
Binds a value produced by an application-registered resolver.
Creates the DecoratorPlugin.
Discovers decorated classes by scanning a directory and importing files.
Returns the resolver registered for a custom parameter type, if any.
Binds a request header value.
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.
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.
Groups controllers and providers under one class.
Marks a constructor dependency as optional: when the token has no provider,
the argument receives undefined instead of failing construction.
Binds a path parameter.
Binds handler arguments to request sources, positionally.
Requires the authenticated principal to hold any of the given permissions. May be applied at the class or method level (method overrides class).
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.
Binds the whole query record.
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.
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.
Resolves a single parameter value from the request context. The result may
be a promise (for body and custom resolvers); callers should await it.
Resolves an ordered argument array for a handler from its parameter
metadata. Arguments are placed by parameter index, so undecorated
parameters receive undefined.
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).
Attaches error filters to a controller or route. Filters run last in the route middleware chain.
Attaches guards to a controller or route. Guards run before the handler and
may short-circuit by responding without calling next().
Attaches interceptors to a controller or route. Interceptors wrap the
handler invocation (pre- and post-processing via next()).
Attaches a request body schema to the decorated route handler.
Attaches a path parameter schema to the decorated route handler.
Attaches a query parameter schema to the decorated route handler.
Assigns an API version prefix to a controller. Combined with @Controller,
the effective path is version + basePath + routePath
(e.g. '/v1/users').
Configuration for ApiOperation.
-
description: string
Longer description.
-
operationId: string
Operation id.
-
summary: string
Short summary.
Configuration for ApiResponse.
-
description: string
Response description.
-
schema: unknown
Response body schema.
-
status: number
HTTP status code.
Options for DecoratorPlugin.
-
autoDiscover: boolean
When
true, auto-scancontrollersPathfor 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
autoDiscoveristrue). -
enforceRoles: boolean
When
true(the default), a route decorated with@Roles/@Permissionsgets enforcing authorization middleware appended to its chain — after the route's guards and filters, before any validation middleware. The middleware resolvesCAPABILITIES.AUTHORIZATIONper request: with a provider registered it answers401/403exactly like the equivalent@UseGuards(requireRole(...))spelling; with none, the route FAILS CLOSED — it answers501and is never served unguarded — andregister()warns once per affected route. -
enforceSchemas: boolean
When
true(the default), a route decorated with@ValidateBody/@ValidateQuery/@ValidateParamsgets the registered validation capability's enforcing middleware appended LAST in its chain (innermost, after guards and filters), so an invalid request is rejected with400before the handler runs — while guard401/403precedence 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.
Discovery configuration.
-
exclude: readonly string[]
Glob patterns to exclude (default: test/spec files).
-
extensions: readonly string[]
File extensions to include (default:
['.ts', '.mts', '.js', '.mjs']). -
path: string
Directory path to scan (relative or absolute).
Result of a discovery scan.
-
controllers: readonly Constructor[]
Discovered controller classes.
-
errors: ReadonlyArray<{ readonly file: string; readonly error: string; }>
Files that failed to import, with error messages.
-
services: readonly Constructor[]
Discovered service classes.
Options for Injectable.
-
scope: ServiceScope
Lifecycle scope.
-
token: string
Capability token to register the service under.
What a @Module declares.
-
controllers: readonly Constructor[]
Controller classes this module contributes.
-
imports: readonly Constructor[]
Other modules that this module includes.
-
providers: readonly Constructor[]
Provider classes this module contributes.
A token marked optional by Optional.
-
optional: true
Discriminator marking this dependency as optional.
-
token: string
The capability token to resolve.
Metadata captured by a parameter decorator, later resolved by the
resolveParameters function.
-
customType: string
Custom parameter type name (from a
Custom(name)source). -
index: number
Positional index of the parameter in the handler signature.
-
metadata: Readonly<Record<string, unknown>>
Extra payload captured by a custom parameter decorator.
-
name: string
Name for named sources (
@Query('page'),@Param('id'), …). -
type: ParameterType
Source of the parameter value.
A declaration of where one handler argument comes from.
-
__value: T
Phantom carrier for the resolved value type. Never present at runtime.
-
descriptor: Omit<ParameterMetadata, "index">
The metadata this source contributes, less its positional index.
Resolves a custom parameter value (from
a Custom(name) source) at request time.
A factory producing a method decorator that registers a route for a given HTTP verb.
A constructor dependency: a capability token, or a token wrapped by
Optional.
A middleware value accepted by pipeline decorators: either a bare
MiddlewareFunction or a class implementing
IMiddleware.
Loads a module from a specifier. Defaults to the global dynamic import;
injectable for tests.
Where a request parameter is sourced from.
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.
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.
A standard decorator valid in either the class or the method position,
discriminating on context.kind.
A standard method decorator that records metadata and leaves the method as it is.
Maps a tuple of sources onto the handler parameter tuple they bind.
Registers a DELETE route on the decorated method.
Registers a GET route on the decorated method.
Registers a HEAD route on the decorated method.
The process-wide singleton decorators write to. The DecoratorPlugin
registers this same instance under CAPABILITIES.METADATA_STORE so
ctx.metadata resolves to it.
Registers an OPTIONS route on the decorated method.
Registers a PATCH route on the decorated method.
Registers a POST route on the decorated method.
Registers a PUT route on the decorated method.
Detects circular dependencies during container resolution.
-
enter(token: string): void
Marks a token as currently being resolved.
-
isActive(): boolean
Reports whether any tokens are currently being resolved.
-
leave(): void
Removes the most recently entered token from the resolution chain.
Fluent builder for IContainer instances.
-
build(): IContainer
Creates the container with all queued registrations applied.
-
register<T>(): thistoken: string,provider: Provider<T>,options?: ProviderOptions
Queues a provider registration to be applied at
buildtime. -
setAutoRegister(enabled: boolean): this
Enables or disables auto-registration fallback to the external resolver.
-
setDefaultScope(scope: ServiceScope): this
Sets the default lifecycle scope for providers registered without an explicit scope.
-
setExternalResolver(resolver: ExternalResolver): this
Sets the external resolver used when auto-registration is enabled.
Dependency injection container implementing IContainer.
Token-keyed store of provider entries with optional parent inheritance.
-
createChild(): ProviderRegistry
Creates a child registry that inherits lookups from this one.
-
get(token: string): ProviderEntry | undefined
Looks up a provider entry, walking the parent chain.
-
has(token: string): boolean
Reports whether a token is registered anywhere in this chain.
-
register(): voidtoken: string,entry: ProviderEntry
Registers a provider entry under a token.
Manages singleton and scoped instance caches for a container.
-
createChild(): ScopeManager
Creates a child scope that shares singletons but has its own scoped map.
-
getScoped(token: string): unknown
Retrieves a cached scoped instance.
-
getSingleton(token: string): unknown
Retrieves a cached singleton instance.
-
hasScoped(token: string): boolean
Reports whether a scoped instance is cached.
-
hasSingleton(token: string): boolean
Reports whether a singleton is cached.
-
setScoped(): voidtoken: string,instance: unknown
Stores a scoped instance (local to this scope).
-
setSingleton(): voidtoken: string,instance: unknown
Stores a singleton instance (shared across all scopes).
Convenience factory for creating a standalone DI container.
Creates the DiPlugin.
Configuration for constructing a DiContainer.
-
autoRegister: boolean
When
true, resolving an unregistered token falls back to the external resolver and caches the result as a singleton. -
defaultScope: ServiceScope
Default lifecycle scope for providers without an explicit scope.
-
externalResolver: ExternalResolver
Optional external resolver for auto-registration fallback.
-
parentRegistry: ProviderRegistry
Parent registry for hierarchical lookups (internal).
-
parentScopes: ScopeManager
Parent scope manager sharing singletons (internal).
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 tofalse. -
defaultScope: ServiceScope
Default lifecycle scope for providers registered without an explicit scope. Defaults to
'singleton'.
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.
-
has(token: string): boolean
Reports whether the external source can resolve the token.
-
resolve(token: string): unknown
Resolves a token from the external source.
Abstract base class for domain events.
-
data: T
The event payload.
-
id: string
Unique event ID.
-
occurredOn: Date
When the event occurred.
-
type: string
Event type name (e.g.
"UserCreated").
In-memory publish/subscribe event bus.
-
clear(): void
Removes all subscriptions.
-
publish<T>(event: IDomainEvent<T>): Promise<void>
Publishes an event to every subscriber of its type.
-
publishBatch(events: IDomainEvent[]): Promise<void>
Publishes multiple events, each to its own subscribers.
-
subscribe<T>(): () => voidtype: string,handler: EventHandler<T>
Subscribes to an event type.
-
subscriptionCount(): number
Returns the count of subscribed event types (for health reporting).
-
whenIdle(): Promise<void>
Resolves once all in-flight fire-and-forget handlers settle.
Abstract base class for integration (cross-service) events.
Creates an aggregate-local domain event recorder.
Runtime-bound abstract bases for ergonomic construction.
Creates the EventsPlugin.
Adapts a class-based handler to the EventHandler function signature and
subscribes it to the bus. Returns the Unsubscribe function.
One event handler and the event type it subscribes to.
-
handler: IEventHandler<unknown>
| RegistryFactory<IEventHandler<unknown>>The handler to subscribe for that type, or a factory that builds one from the service registry.
-
type: string
Event type name, matching
event.type.
Options for the EventsPlugin.
-
async: boolean
Dispatch policy for event handlers.
-
errorHandler: () => voiderror: unknown,event: IDomainEvent
Handler for errors thrown/rejected by event handlers.
-
handlers: readonly EventHandlerRegistration[]
Handlers subscribed to the bus at
register()time.
A domain event.
-
aggregateId: string
ID of the aggregate that produced the event, when applicable.
-
data: T
The event payload.
-
id: string
Unique event ID.
-
occurredOn: Date
When the event occurred.
-
type: string
Event type name (e.g.
"UserCreated"). -
version: number
Aggregate version, for event-sourced aggregates.
Records domain facts raised by one aggregate during its current operation.
-
clear(): void
Removes all pending facts.
-
pending(): readonly IDomainEvent[]
Returns an ordered, read-only snapshot of pending facts.
-
record<T>(event: IDomainEvent<T>): void
Appends an event reference to the pending facts in insertion order.
-
remove(event: IDomainEvent): boolean
Removes the first pending reference that is strictly equal to
event.
In-memory publish/subscribe event bus for domain events.
-
publish<T>(event: IDomainEvent<T>): Promise<void>
Publishes an event to every subscriber of its type.
-
publishBatch(events: IDomainEvent[]): Promise<void>
Publishes multiple events, each to its own subscribers.
-
subscribe<T>(): Unsubscribetype: string,handler: EventHandler<T>
Subscribes to an event type.
Class-based event handler interface.
Handles one event type.
Removes a subscription when called.
The framework's HTTP error type.
-
details: Readonly<Record<string, unknown>>
Structured details appended to the error body. Omitted entirely when not supplied (never
undefined) so serialization stays clean. -
from(init: HttpErrorInit): HttpError
Creates an
HttpErrorfrom anHttpErrorInitobject. -
statusCode: number
The HTTP status code this error maps to.
Creates a 400 Bad Request error.
Creates a 409 Conflict error.
Framework-standard error formatter.
Creates a global error-handler middleware.
Creates a 403 Forbidden error.
Creates a 500 Internal Server Error error.
Creates a 404 Not Found error.
Creates a 501 Not Implemented error.
Format an error as RFC 9457 Problem Details.
Resolve the error format configuration to a concrete formatter function.
Resolves the human-readable title for a status code, falling back to a generic title for codes outside the well-known set.
Creates a 429 Too Many Requests error.
Creates a 422 Unprocessable Entity error wrapping a list of validation
failures.
Format an error as RFC 7807 Problem Details.
The framework-standard error body shape.
-
details: Readonly<Record<string, unknown>>
Optional structured details (present when the error carries any).
-
message: string
Human-readable error message.
-
stack: string
Optional stack trace (present only when
includeStackTraceis on). -
statusCode: number
The HTTP status code.
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 errorstacktrace is included in the response body. Never enable this in production — pass a config-derived boolean (e.g.config.get('NODE_ENV') === 'development'), never readprocess.envdirectly (AI_GUIDELINES §4.1). Defaults tofalse. -
logErrors: boolean
When
true(the default), caught errors are logged aterrorlevel via theILoggerresolved fromctx.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 anHttpErrorand resolves to a status>= 500is masked in the response: itsdetail/messagebecomes 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:logErrorsstill records the unmasked error and its cause chain, so an operator loses nothing unlesslogErrorsis alsofalse, the configuration that already logs nothing. -
respond: () =>error: HttpError,ctx: IRequestContextHandlerResult
| 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.statusCodeis safe to serve. Return aHandlerResultproduced byctx.responseto use that response; it may resolve that result asynchronously. Return or resolve toundefinedto fall through to the configured formatter unchanged.
Options accepted by the HttpError constructor.
-
cause: Error
Optional underlying cause (forwarded to the ES2022
Errorcause chain). -
details: Readonly<Record<string, unknown>>
Optional structured details attached to the error body.
-
message: string
Human-readable error message.
-
statusCode: number
HTTP status code (e.g.
404).
A Problem Details object as defined by RFC 9457.
-
detail: string
A human-readable explanation specific to this occurrence.
-
errors: ReadonlyArray<{ field: string; message: string; code?: string; }>
Optional validation failures extension (present for
422errors). -
instance: string
A URI reference identifying the specific occurrence (request path).
-
stack: string
Optional stack trace (present only when
includeStackTraceis on). -
status: number
The HTTP status code generated for this occurrence.
-
title: string
A short, human-readable summary of the problem type.
-
type: string
A URI reference identifying the problem type.
A single validation failure carried by a 422 error.
-
code: string
Optional machine-readable failure code.
-
field: string
Dot-path of the offending field (e.g.
"address.zip"). -
message: string
Human-readable description of the failure.
The built-in error format identifiers for @setu-ts/exceptions.
A function that formats a thrown error into a serializable error body.
The canonical base URI for framework-produced problem type identifiers.
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.
Immutable config-backed flag provider.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates the flag against the immutable flag map.
-
start(): Promise<void>
No-op — flags are immutable.
-
stop(): Promise<void>
No-op — flags are immutable.
-
type: "config"
Provider type identifier.
Database-backed flag provider that polls an injected IFlagStore.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates the flag against the current snapshot.
-
start(): Promise<void>
Loads initial state ONCE and arms the poll interval ONCE.
-
status(): FlagProviderStatus
Returns status: healthy when the last poll succeeded; degraded when it failed.
-
stop(): Promise<void>
Stops the poll timer. Guards against stop()-before-arm (no-op if start was never called or the timer is already cleared).
-
type: "database"
Provider type identifier.
Feature flag service that delegates to a single FlagProvider.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates whether a flag is enabled.
-
isEnabledAsync(): Promise<boolean>flag: string,context?: FlagContext
Evaluates a flag, awaiting the provider when it can answer asynchronously.
-
start(): Promise<void>
Starts the underlying provider (pulls initial state).
-
status(): FlagProviderStatus | undefined
Forwards the provider's optional health status.
-
stop(): Promise<void>
Stops the underlying provider (releases timers / connections).
Thrown when a supplied module does not look like the LaunchDarkly SDK.
A FlagProvider backed by LaunchDarkly.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates a flag against the cached snapshot for this context.
-
isEnabledAsync(): Promise<boolean>flag: string,context?: FlagContext
Evaluates a flag by awaiting LaunchDarkly directly.
-
start(): Promise<void>
Builds the client (unless one was injected), waits for its initial connection, subscribes to flag updates, and prewarms the anonymous snapshot.
-
status(): FlagProviderStatus
Reports whether the client is connected.
-
stop(): Promise<void>
Closes the client and drops every cached snapshot.
-
type: "launchdarkly"
Provider type identifier.
Mutable in-memory flag provider.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates the flag against the current flag map.
-
removeFlag(name: string): void
Removes a flag by name.
-
replaceFlags(flags: Readonly<Record<string, FlagDefinition>>): void
Replaces all flags with a new set.
-
setFlag(): voidname: string,def: FlagDefinition
Sets or updates a flag definition.
-
start(): Promise<void>
No-op — in-memory store needs no startup.
-
stop(): Promise<void>
No-op — in-memory store needs no shutdown.
-
type: "memory"
Provider type identifier.
Narrows an arbitrary module object to ILaunchDarklyModule.
Creates a middleware function that guards a route based on a feature flag.
Creates a flag provider from plugin options.
FeatureFlagsPlugin factory.
Lazily imports the LaunchDarkly Node server SDK.
Builds the LaunchDarkly evaluation context for a framework
FlagContext.
Options for the 'config' provider arm.
-
options: { readonly flags: Readonly<Record<string, FlagDefinition>>; }
Static flag map.
-
provider: "config"
Provider type discriminant.
Options for the 'custom' provider arm.
-
options: { readonly instance: FlagProvider; }
A pre-built
FlagProviderinstance. -
provider: "custom"
Provider type discriminant.
Options for the 'database' provider arm.
-
options: { readonly store: IFlagStore; readonly refreshIntervalMs?: number; }
Injected flag store.
-
provider: "database"
Provider type discriminant.
Evaluation context for targeting rules.
-
attributes: Readonly<Record<string, string | number | boolean>>
Additional targeting attributes.
-
tenantId: string
The tenant the flag is evaluated for, when the request resolves one.
-
userId: string
The user the flag is evaluated for.
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
falsefor any context whosetenantIdis 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 byusers). When absent, evaluation is unchanged. -
users: readonly string[]
Optional user allowlist — overrides
enabled: false.
Options for the createFlagGuard factory.
-
context: FlagContext
Static context override for the flag evaluation.
-
fallback: string
Fallback URL for a 302 redirect when the flag is off.
-
statusCode: number
HTTP status code when no fallback is provided (default 404).
Port that all flag providers implement.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluate whether a flag is enabled.
-
isEnabledAsync(): Promise<boolean>flag: string,context?: FlagContext
Optionally evaluate a flag asynchronously, when the backing source can produce a more accurate answer than the cached snapshot.
-
start(): Promise<void>
Pull initial state into the cache.
-
status(): FlagProviderStatus
Optional status — absent when the provider has no health signal.
-
stop(): Promise<void>
Release timers / connections.
-
type: FlagProviderType
Provider type identifier.
Status reported by a flag provider.
-
detail: string
Optional human-readable detail.
-
healthy: boolean
Whether the provider is healthy.
Feature flag evaluator. Evaluation is synchronous against the provider's cached state; providers refresh their state out of band.
-
isEnabled(): booleanflag: string,context?: FlagContext
Evaluates a flag.
-
isEnabledAsync(): Promise<boolean>flag: string,context?: FlagContext
Evaluates a flag, awaiting the backing provider when it can produce a more accurate answer asynchronously.
Structural facade injected into DatabaseProvider.
-
loadFlags(): Promise<Readonly<Record<string, FlagDefinition>>>
Load the current flag definitions from the backing store.
The subset of LaunchDarkly's LDClient this provider uses.
-
allFlagsState(context: LaunchDarklyContext): Promise<ILaunchDarklyFlagsState>
Fetches a synchronously-queryable snapshot of every flag for a context.
-
boolVariation(): Promise<boolean>key: string,context: LaunchDarklyContext,defaultValue: boolean
Evaluates a boolean flag for a context.
-
close(): void
Shuts the client down and flushes pending events. Synchronous.
-
initialized(): boolean
Whether the client has completed initialization. Synchronous.
-
on(): voidevent: string,listener: () => void
Registers an event listener. The provider listens for
'update', which fires whenever any flag's configuration changes. -
waitForInitialization(options?: { readonly timeoutSeconds?: number; }): Promise<unknown>
Resolves once the client has connected, or rejects on permanent failure.
The subset of LaunchDarkly's LDFlagsState this provider reads.
-
getFlagValue(key: string): unknown
Reads one flag's value from the recorded snapshot.
-
valid: boolean
False when the snapshot could not be computed (client offline, no context).
The subset of the SDK module surface this provider uses.
-
init(): ILaunchDarklyClientsdkKey: string,options?: Readonly<Record<string, unknown>>
Creates a client. Synchronous — it returns immediately and connects in the background, which is why
ILaunchDarklyClient.waitForInitializationexists.
The LaunchDarkly evaluation context.
-
anonymous: boolean
True when no
userIdwas supplied. -
key: string
The context key; the anonymous key when no
userIdwas supplied. -
kind: "user"
Context kind — always
'user'for the contexts this provider builds.
Configuration for the 'launchdarkly' provider arm.
-
client: ILaunchDarklyClient
A prebuilt client. When present the SDK module is never loaded and
sdkKeyis not read. -
fallbackValue: boolean
Value returned by the synchronous
isEnabledfor a context whose snapshot has not loaded yet, and used as the SDK default inisEnabledAsync. Defaults tofalse. -
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
clientis injected; a missing key with no client throws duringregister().
Options for the 'launchdarkly' provider arm.
-
options: LaunchDarklyProviderConfig
LaunchDarkly configuration.
-
provider: "launchdarkly"
Provider type discriminant.
Options for the 'memory' provider arm.
-
options: { readonly flags?: Readonly<Record<string, FlagDefinition>>; }
Optional initial flag map — defaults to empty.
-
provider: "memory"
Provider type discriminant.
| MemoryProviderOptions
| DatabaseProviderOptions
| LaunchDarklyProviderOptions
| CustomProviderOptions
Discriminated union of all plugin option shapes.
Provider identity reported by FlagProvider.type, and surfaced as
data.provider by the plugin's feature-flags health indicator.
APQ resolver that verifies hashes before caching.
-
resolve(params: { query?: string; extensions?: Record<string, unknown>; }): Promise<ApqResolveResult>
Resolve APQ for a request.
Error thrown when the graphql runtime cannot be loaded.
- name: string
-
specifier: string
The specifier that failed to load.
Error thrown when schema construction or resolver attachment fails.
GraphQL service implementation.
-
cachedDocumentCount(): number
Report the number of cached documents.
-
clearCache(): void
Clear the document cache.
-
endpoint(): string
The endpoint path where GraphQL is served.
-
execute(): Promise<GraphqlExecutionOutcome>params: GraphqlRequestParams,requestContext?: IRequestContext,method?: "GET" | "POST"
Execute a GraphQL request.
-
subscribe(): Promise<GraphqlSubscriptionOutcome>params: GraphqlRequestParams,context?: GraphqlOperationContext
Subscribe to a GraphQL operation (query, mutation, or subscription).
Adapt a graphql module to the internal runtime interface.
Create a validation rule that limits query depth.
Encode a keep-alive comment.
Encode a complete SSE event with the mandatory empty data: field.
Encode a next SSE event carrying a GraphQL execution result.
Extract persisted query info from request extensions.
Generate a GraphiQL HTML page.
Create a GraphQL plugin.
Load the graphql runtime, either from an injected module or lazily.
Compute a SHA-256 hash of the query string and return lowercase hex.
The entry type for a SUBSCRIPTION resolver stored in a
TypeResolverMap.
-
resolve: AnyFieldResolver
Maps each emitted payload to the field value. Optional.
-
subscribe(): AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>source: unknown,args: Record<string, unknown>,context: unknown,info: unknown
Produces the event source for this subscription field.
Default context shape that resolvers receive.
-
connection: GraphqlConnectionInfo
The WebSocket connection info. Present only over the WS transport.
-
requestContext: IRequestContext
The HTTP request context. Absent over the WebSocket transport.
-
services: IServiceRegistry
The live service registry (request-scoped over HTTP, plugin-level over WS).
-
tenant: ITenant
The resolved tenant, when tenancy resolved one.
-
user: IPrincipal
The authenticated principal, when the auth middleware published one.
APQ (Automatic Persisted Queries) options.
-
maxEntries: number
Maximum entries in the in-memory LRU fallback. Default
1000. -
ttlSeconds: number
TTL in seconds for cache-store entries. Default
300.
Code-first arm options.
- resolvers: never
-
schema: GraphqlSchemaLike
Pre-built schema from the application.
-
typeDefs: never
Disallow schema-first options.
Information about a WebSocket connection used for subscription operations.
-
connectionParams: Record<string, unknown>
The payload sent with
connection_init, if any. -
data: Map<string, unknown>
Per-connection application state.
-
headers: Headers
The upgrade request headers.
-
id: string
Unique connection identifier.
-
protocol: string
The negotiated subprotocol, when one was selected.
-
query: Readonly<Record<string, string>>
Query string parameters from the upgrade request.
Context input for custom context building.
-
connection: GraphqlConnectionInfo
Present when the operation arrives over a WebSocket subscription.
- request: unknown
- services: unknown
The execution result as specified by the GraphQL spec.
-
data: Record<string, unknown> | null
The data returned by the execution, or null if an error occurred.
-
errors: GraphqlFormattedError[]
Errors encountered during execution, or undefined if none.
Formatted GraphQL error as returned to the client.
-
extensions: Record<string, unknown>
Optional extensions for application-specific error codes.
-
locations: Array<{ line: number; column: number; }>
Optional locations in the query document.
-
message: string
Human-readable error message.
-
path: Array<string | number>
Optional path to the field where the error occurred.
The structural shape of a graphql@16 module — the external boundary (M70i X6-3).
-
GraphQLError: new () => unknownmessage: string,options?: undefined
The graphql
GraphQLErrorconstructor.optionsisundefined(not a modeled object) so the realtypeof GraphQLError— whose constructor isnew (message: string, options?: GraphQLErrorOptions)— stays assignable: contravariance requires the facade'soptionsto be assignable toGraphQLErrorOptions | undefined, andundefinedis. -
NoSchemaIntrospectionCustomRule: unknown
The no-schema-introspection validation rule.
-
buildSchema(source: unknown): GraphqlSchemaLike
Build a schema from SDL source.
-
execute(args: { schema: GraphqlSchemaLike; document: unknown; rootValue?: unknown; contextValue?: unknown; variableValues?: unknown; operationName?: string | null | undefined; }): unknown
Execute a document; the result carries
dataand/orerrors. -
getOperationAST(): unknowndocument: unknown,operationName?: string | null | undefined
Extract the operation definition for
operationNamefrom a document. -
parse(source: unknown): unknown
Parse a query/mutation/subscription document.
-
specifiedRules: readonly unknown[]
The specified (built-in) validation rules.
-
subscribe(args: { schema: GraphqlSchemaLike; document: unknown; rootValue?: unknown; contextValue?: unknown; variableValues?: unknown; operationName?: string | null | undefined; }): unknown
Subscribe to a document; the result is an async iterable or a single error result.
-
validate(): unknownschema: GraphqlSchemaLike,document: unknown,rules?: readonly unknown[]
Validate a document against a schema; returns validation errors.
-
validateSchema(schema: GraphqlSchemaLike): unknown
Validate a schema; returns schema errors.
Context for a subscription operation, carrying either an HTTP request context or a WebSocket connection info.
-
connection: GraphqlConnectionInfo
The WebSocket connection info (supplied by the WS path).
-
requestContext: IRequestContext
The HTTP request context (supplied by the SSE path).
Parameters for a GraphQL execution request.
-
extensions: Record<string, unknown>
Optional extensions carried with the request.
-
operationName: string
Operation name for documents with multiple operations.
-
query: string
The GraphQL query string.
-
variables: Record<string, unknown>
Variables as a record of unknown values (passed through verbatim).
Custom scalar resolver methods.
-
parseLiteral(): unknownnode: unknown,variables?: Record<string, unknown> | null
Parse a literal AST value (inline argument).
-
parseValue(value: unknown): unknown
Parse a client input value (variable).
-
serialize(value: unknown): unknown
Serialize an internal value to JSON-safe output.
Structural facade for a graphql@16 scalar type, exposing the three settable resolver properties.
Schema-first arm options.
-
resolvers: ResolverMap
Resolver map to attach to the schema.
-
schema: never
Disallow code-first option.
-
typeDefs: string
SDL string defining the schema.
Structural facade for a graphql@16 schema.
- getDirective(name: string): GraphqlDirectiveLike | null | undefined
- getDirectives(): readonly GraphqlDirectiveLike[]
- getMutationType(): GraphqlObjectTypeLike | null | undefined
- getPossibleTypes(abstractType: GraphqlAbstractTypeLike): readonly GraphqlObjectTypeLike[]
- getQueryType(): GraphqlObjectTypeLike | null | undefined
- getSubscriptionType(): GraphqlObjectTypeLike | null | undefined
- getType(name: string): GraphqlNamedTypeLike | null | undefined
- toAST(): unknown
SSE transport options for GraphQL subscriptions.
-
heartbeatMs: number
Milliseconds between
:keep-alivecomment frames.0disables. Default0. -
path: string
The SSE endpoint path; defaults to
`${path}/stream`.
Subscription transport configuration.
-
sse: GraphqlSseTransportOptions | false
SSE transport options.
falsedisables SSE subscriptions;{}enables with defaults. Present by default. -
websocket: GraphqlWsTransportOptions | false
WebSocket transport options.
falsedisables WS subscriptions;{}enables with defaults. Absent defaults to enabled whenCAPABILITIES.WEBSOCKETis available.
WebSocket transport options for GraphQL subscriptions.
-
connectionInitWaitMs: number
Milliseconds to wait for
connection_initbefore closing with code 4408. Default3000. -
heartbeatMs: number
Milliseconds between protocol
pingframes.0disables. Default0. -
onConnect: (info: GraphqlConnectionInfo) => false | void | Promise<false | void>
Called on
connection_initBEFORE the ack. Returningfalsecloses the socket with4403: Forbidden. May write toconn.datato establish identity for the default resolver context. -
path: string
The WebSocket endpoint path; defaults to
`${path}/ws`.
The surface the transports consume.
The GraphQL service contract.
-
cachedDocumentCount: number
Report the number of cached documents.
-
endpoint: string
The endpoint path where GraphQL is served.
-
execute(): Promise<GraphqlExecutionOutcome>params: GraphqlRequestParams,requestContext?: IRequestContext,method?: "GET" | "POST"
Execute a GraphQL request.
-
subscribe(): Promise<GraphqlSubscriptionOutcome>params: GraphqlRequestParams,context?: GraphqlOperationContext
Subscribe to a GraphQL operation (query, mutation, or subscription).
A subscription field's resolver pair.
-
resolve: FieldResolver<TSource, TContext, TArgs>
Maps each emitted payload to the field value. Optional.
-
subscribe: () => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>source: TSource,args: TArgs,context: TContext,info: unknown
Produces the event source for this subscription field.
The entry type for a field resolver stored in a TypeResolverMap.
| { ok: false; message: string; code: string; status: number; }
The result of resolving APQ for a request.
& { path?: string; graphiql?: boolean; introspection?: boolean; maxDepth?: number; maxNodes?: number; validationRules?: unknown[]; maskInternalErrors?: boolean; formatError?: (error: unknown) => unknown; documentCacheSize?: number; buildContext?: (input: GraphqlContextInput) => unknown | Promise<unknown>; rootValue?: unknown; graphqlModule?: GraphqlModuleLike; subscriptions?: GraphqlSubscriptionsOptions; apq?: GraphqlApqOptions; maxBatchSize?: number; }
Union of schema construction options — mutually exclusive arms.
| { kind: "single"; status: number; result: GraphqlExecutionResult; }
| { kind: "stream"; status: number; stream: AsyncIterable<GraphqlExecutionResult>; }
Discriminated outcome of a subscription operation.
Resolver map for schema-first construction.
The resolver entries for one object or interface type.
The protocol identifier.
Example 1
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);
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.
Thrown when any of the Connect runtime modules cannot be imported. Carries the exact specifier that failed and the suggested install command.
-
specifier: string
The specifier that failed to import.
The gRPC service applications use to register Connect/gRPC services.
-
addService<TDef extends GrpcServiceDefinition>(): voiddefinition: TDef,implementation?: unknown
Registers a gRPC service definition with an optional implementation.
-
available: boolean
Whether gRPC dispatch is available. Always
truesince the kernel now resolvesIGrpcServicefrom the service registry and dispatches after the middleware pipeline (M70a). The previous adapter-based seam is retired. -
claims(request: Request): boolean
Whether this service claims the request's path — that is, whether the path lies inside the configured
basePath. -
close(): void
Releases the built router and its handlers. Afterwards the plugin's own procedures answer
503instead of rebuilding a router for an application that is shutting down, while every other path falls through untouched. -
createFetchHandler(): RpcFetchHandler
The handler that used to be installed into
IHttpAdapter.setRpcHandler. Returnsnullfor any request outsidebasePath. -
handleRequest(request: Request): Promise<Response>
Handles an RPC request directly.
-
refuses(request: Request): Response | null
Refuses a native
application/grpcrequest from its HEADERS alone. -
serviceCount(): number
Number of application services registered. Read by the health indicator.
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.
Creates the gRPC plugin.
The four modules the runtime is adapted from.
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; nativeapplication/grpcreaches the server too but is deliberately refused with a Trailers-OnlyUNIMPLEMENTED. 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.
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.
-
method: Readonly<Record<string, TMethod>>
Methods keyed by their camelCase local name.
-
typeName: string
The fully qualified name of the service, e.g.
"package.ServiceName".
The service contract that applications use to register gRPC/Connect services.
Provided by the grpc-plugin under the CAPABILITIES.GRPC token.
-
addService<TDef extends GrpcServiceDefinition>(): voiddefinition: TDef,implementation?: unknown
Registers a gRPC service definition with an optional implementation.
-
available: boolean
Whether gRPC dispatch is available.
-
claims(request: Request): boolean
Whether this service claims a request — that is, whether the request path lies inside the configured
basePath. -
handleRequest(request: Request): Promise<Response>
Handles an incoming RPC request directly.
-
refuses(request: Request): Response | null
Whether this service refuses the request outright, decided from its HEADERS alone.
The serving status returned by the health bridge. These values map onto the gRPC v1 Health response enum.
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.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
Default implementation of IHealthService.
-
check(): Promise<HealthReport>
{@inheritDoc IHealthService.check}
-
checkLive(): Promise<HealthReport>
{@inheritDoc IHealthService.checkLive}
-
checkReady(): Promise<HealthReport>
{@inheritDoc IHealthService.checkReady}
-
registerIndicator(): voidname: string,indicator: HealthIndicatorFn
{@inheritDoc IHealthService.registerIndicator}
Creates an HTTP probe indicator.
Creates a health plugin.
The outcome of one health check.
-
data: Readonly<Record<string, unknown>>
Optional diagnostic details (response times, versions, …).
-
status: HealthStatus
The reported health state.
Options for configuring the health plugin.
-
endpoints: EndpointsOptions
Endpoint path configuration.
-
indicatorTimeoutMs: number
Deadline applied independently to every selected indicator, in milliseconds (M90b). Must be a positive finite number; anything else — zero, negative,
NaN,Infinity— throws at plugin construction. The identical check runs in the barrel-exportedHealthServiceconstructor, so constructing the service directly cannot bypass it. -
indicators: readonly HealthIndicatorEntry[]
Additional indicators to register.
The aggregated health report returned by IHealthService.check().
-
checks: Readonly<Record<string, Readonly<HealthCheckResult & { readonly latencyMs?: number; }>>>
Per-indicator results with optional latency measurements.
-
status: HealthStatus
Overall health status (worst of all participating indicators).
-
timestamp: string
ISO 8601 timestamp of when the check was performed.
Options for creating an HTTP probe indicator.
-
fetcher: fetch
Injectable fetcher for testing.
-
timeoutMs: number
Timeout in milliseconds for the request.
-
url: string
The URL to probe.
A named health indicator contributing to /health, /live, and
/ready.
-
check(): Promise<HealthCheckResult>
Performs the health check.
-
name: string
Indicator name, unique per application.
Health service contract for registering and checking health indicators.
-
check(): Promise<HealthReport>
Runs all registered indicators and returns the aggregated report.
-
checkLive(): Promise<HealthReport>
Runs only the liveness indicator (the built-in "self" indicator).
-
checkReady(): Promise<HealthReport>
Runs all contributed indicators for readiness.
-
registerIndicator(): voidname: string,indicator: HealthIndicatorFn
Registers a health indicator.
One entry of HealthPluginOptions.indicators: either a ready
indicator instance or a factory that builds one from the service registry.
Function form of a health indicator.
Health state reported by a health indicator.
Example 1
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 }), });
CORS middleware factory.
CSRF middleware factory.
HttpSecurityPlugin factory.
IP security middleware factory.
Request size middleware factory.
Security headers middleware factory.
Options for Content-Security-Policy header.
-
connectSrc: string
Connect source directive.
-
defaultSrc: string
Default source directive.
-
fontSrc: string
Font source directive.
-
frameSrc: string
Frame source directive.
-
imgSrc: string
Image source directive.
-
mediaSrc: string
Media source directive.
-
objectSrc: string
Object source directive.
-
reportUri: string
Report URI for CSP violations.
-
scriptSrc: string
Script source directive.
-
styleSrc: string
Style source directive.
Options for CORS middleware.
-
allowedHeaders: readonly string[]
Allowed request headers for the preflight
Access-Control-Allow-Headersresponse. -
credentials: boolean
When
true, emitAccess-Control-Allow-Credentials: true. -
enabled: boolean
Enable/disable CORS. Defaults to
truewhen present. -
exposedHeaders: readonly string[]
Exposed response headers for
Access-Control-Expose-Headers. -
maxAge: number
Max age (seconds) for preflight cache.
-
methods: readonly string[]
Allowed methods for preflight
Allow-Methodsheader. -
origin: boolean | string | readonly string[] | CorsOriginMatcher
Origin configuration:
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
truewhen 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:[].
Options for HttpSecurityPlugin.
-
cors: CorsOptions
CORS configuration. Presence enables CORS; absent means inactive.
-
csrf: CsrfOptions
CSRF configuration. Presence enables CSRF; absent means inactive.
-
headers: SecurityHeadersOptions
Security headers configuration. Omitted → default secure header set.
{ enabled: false }→ off. Sub-fields override individual headers. -
ipSecurity: IpSecurityOptions
IP security configuration. Presence enables IP resolution; absent means inactive.
-
requestSize: RequestSizeOptions
Request-size configuration. Presence enables size limiting; absent means inactive.
Options for IP security middleware.
-
enabled: boolean
Enable/disable IP resolution. Defaults to
truewhen present. -
ipHeader: string
The header name to read when
trustProxyistrue. 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:
1skips the immediate peer's contribution,2skips two, and so on. -
trustProxy: boolean
When
true, read the client IP from the proxy header instead ofrequest.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.
Options for request-size middleware.
-
enabled: boolean
Enable/disable request size limiting. Defaults to
truewhen present. -
maxBodySize: number
Maximum body size in bytes. Default: 1_048_576 (1 MiB).
Options for security headers middleware.
-
contentSecurityPolicy: ContentSecurityPolicyOptions | false
Content-Security-Policy configuration. Set to
falseto omit entirely.undefinedkeeps the default (no CSP by default since it breaks apps). -
enabled: boolean
Enable/disable all security headers. Defaults to
true. -
permissionsPolicy: string | false
Permissions-Policy value. Set to
falseto omit.undefineduses default (none by default). -
referrerPolicy: string | false
Referrer-Policy value. Set to
falseto omit.undefineduses default (no-referrer). -
strictTransportSecurity: StrictTransportSecurityOptions | false
Strict-Transport-Security configuration. Set to
falseto omit.undefineduses defaults. -
xContentTypeOptions: string | false
X-Content-Type-Options value. Set to
falseto omit.undefineduses default (nosniff). -
xFrameOptions: string | false
X-Frame-Options value. Set to
falseto omit.undefineduses default (DENY).
Options for Strict-Transport-Security header.
-
includeSubDomains: boolean
Include subdomains. Default: true.
-
maxAge: number
Max age in seconds. Default: 31536000 (1 year).
-
preload: boolean
Preload directive.
Origin matcher function for dynamic CORS decisions.
Creates a new kernel application instance.
Options for createApplication.
-
plugins: IPlugin[]
Plugins to pre-register before
IApplication.start.
Kernel application extends IApplication with inject() capability.
-
hasPlugin(name: string): boolean
Reports whether a plugin carrying this name is pending.
-
inject(request: InjectRequest): Promise<InjectResponse>
Synthesizes an incoming request and runs it through the full pipeline without requiring a listening server.
-
unregister(name: string): boolean
Removes a pending plugin by name before the application starts.
Inject request shape for IKernelApplication.inject.
-
body: unknown
Request body (will be stringified if not a string).
-
headers: Record<string, string> | Headers
Request headers.
-
method: string
HTTP method.
-
url: string
Full request URL.
Inject response shape returned by IKernelApplication.inject.
-
body: string | null
Raw response body as text. A byte body (from
response.send(bytes)) is UTF-8 decoded;nullonly when the response genuinely has no body. -
headers: Headers
Response headers.
-
json<T>(): T
Parses the response body as JSON.
-
statusCode: number
Response status code.
Structured logger that writes JSON lines (or pretty text) to console.
-
child(bindings: LogMetadata): ILogger
Returns a new logger whose entries always include
bindingsmerged on top of this logger's existing bindings. -
debug(): voidmessage: string,metadata?: LogMetadata
-
error(): voidmessage: string,metadata?: LogMetadata
-
fatal(): voidmessage: string,metadata?: LogMetadata
-
info(): voidmessage: string,metadata?: LogMetadata
-
level: LogLevel
The minimum level this logger emits.
-
trace(): voidmessage: string,metadata?: LogMetadata
-
warn(): voidmessage: string,metadata?: LogMetadata
Logger that does nothing. Every method is a no-op and child() returns
the same instance, so it is cheap to share widely.
-
child(_bindings: LogMetadata): ILogger
Returns this same instance — a no-op logger has no state to fork.
-
debug(): void_message: string,_metadata?: LogMetadata
-
error(): void_message: string,_metadata?: LogMetadata
-
fatal(): void_message: string,_metadata?: LogMetadata
-
info(): void_message: string,_metadata?: LogMetadata
-
level: LogLevel
The configured level; defaults to
trace. No output is ever produced. -
trace(): void_message: string,_metadata?: LogMetadata
-
warn(): void_message: string,_metadata?: LogMetadata
Structured logger backed by Pino.
-
child(bindings: LogMetadata): ILogger
Returns a child logger backed by Pino's native
child(). -
create(options?: PinoLoggerOptions): Promise<PinoLogger>
Asynchronously creates a
PinoLogger. -
debug(): voidmessage: string,metadata?: LogMetadata
-
error(): voidmessage: string,metadata?: LogMetadata
-
fatal(): voidmessage: string,metadata?: LogMetadata
-
info(): voidmessage: string,metadata?: LogMetadata
-
level: LogLevel
The minimum level this logger emits.
-
trace(): voidmessage: string,metadata?: LogMetadata
-
warn(): voidmessage: string,metadata?: LogMetadata
Creates middleware that logs each request and its response.
Creates the LoggerPlugin.
Options for constructing a ConsoleLogger.
-
bindings: LogMetadata
Bindings merged into every entry produced by this logger.
-
level: LogLevel
Minimum level to emit. Defaults to
'info'. -
pretty: boolean
When
true, pretty-print entries instead of emitting JSON lines. -
redact: readonly string[]
Dot-paths to redact from metadata (e.g.
['password', 'auth.token']).
Options for LoggerPlugin.
-
excludePaths: readonly string[]
Exact paths excluded from request logging.
-
level: LogLevel
Minimum level to emit. Defaults to
'info'. -
pinoFactory: PinoFactory
Inject a pre-loaded Pino factory for the pino transport, bypassing the
import('npm:pino')path. Useful for tests. -
pretty: boolean
When
true(andtransport: 'console'), pretty-print entries. -
redact: readonly string[]
Dot-paths to redact from metadata (e.g.
['password', 'token']). -
requestLogging: boolean
When
true, register automatic request/response logging middleware. -
slowRequestThreshold: number
Requests slower than this (ms) trigger a
warnentry. Defaults to5000. -
transport: LoggerTransport
Underlying logger implementation. Defaults to
'console'.
Options for constructing a NoopLogger. Currently unused but
kept for a stable, forward-compatible constructor signature that mirrors
the other logger implementations.
-
bindings: LogMetadata
Accepted for API symmetry; ignored.
-
level: LogLevel
Accepted for API symmetry; ignored.
Options for constructing a PinoLogger.
-
bindings: LogMetadata
Bindings merged into every entry produced by this logger.
-
level: LogLevel
Minimum level to emit. Defaults to
'info'. -
pinoFactory: PinoFactory
Inject a pre-loaded Pino factory, bypassing the
import('npm:pino@10.x')path. Useful for tests and environments where the module is already available in-memory. -
redact: readonly string[]
Dot-paths to redact from metadata, delegated to Pino's built-in redaction.
Options for createRequestLoggerMiddleware.
-
excludePaths: readonly PathPattern[]
Paths to skip logging (e.g.
['/health']). A string is an EXACT match; aRegExpis tested against the path. -
slowRequestThreshold: number
Requests slower than this (ms) trigger a
warnentry. Defaults to5000.
Selects the underlying logger implementation.
Factory signature for creating a Pino logger instance. Matches the shape
of the pino default export and allows tests to inject a stub.
Records outgoing mail instead of sending it.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
isHealthy(): Promise<boolean>
M70c: a log provider never touches a network, so it is always reachable (M47).
-
isReady(): boolean
Reports whether the provider is ready to send.
-
messages(): readonly OutgoingMail[]
Every message recorded by this provider, in send order.
-
send(message: OutgoingMail): Promise<void>
Records and logs a message.
Mailer backed by a pluggable provider and a template engine.
-
isHealthy(): Promise<boolean | undefined>
Reports whether the backing provider's transport is reachable right now.
-
send(message: MailMessage): Promise<void>
Sends an email, resolving
fromfrom the message or the configured default. -
sendTemplate(): Promise<void>template: string,message: Omit<MailMessage, "html" | "text">,data: Readonly<Record<string, unknown>>
Renders a named template and sends the result. The
subjectis taken verbatim frommessage; the template supplies thehtml/textbodies.
SendGrid provider over fetch.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
isHealthy(): Promise<boolean>
M70c: a
GET /v3/scopesthrough the existingIMailHttpseam. 2xx means the key is valid; 401 means the API reached us (so the backend is reachable even though the key is wrong); any other status or a network failure means unreachable. -
isReady(): boolean
Reports whether the provider is ready to send.
-
send(message: OutgoingMail): Promise<void>
Sends a message via the SendGrid v3 API.
AWS SESv2 provider.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
isHealthy: () => Promise<boolean>
M70c: present only when the client exposes
isHealthy?()(the real adapter issuesGetAccount); its absence is unknown reachability, notfalse. -
isReady(): boolean
Reports whether the provider is ready to send.
-
send(message: OutgoingMail): Promise<void>
Sends a message via SES.
SMTP provider over nodemailer.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
isHealthy: () => Promise<boolean>
M70c: present only when the transport exposes
verify(); its absence is unknown reachability, notfalse(a minimal injected fake has not told us the server is dead). -
isReady(): boolean
Reports whether the provider is ready to send.
-
send(message: OutgoingMail): Promise<void>
Sends a message over SMTP.
A registry of named body templates with {{ variable }} interpolation.
-
has(name: string): boolean
Reports whether a template is registered.
-
render(): RenderedTemplatename: string,data: Readonly<Record<string, unknown>>
Renders a template's bodies with
data.
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.
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.
Builds the provider adapter for the configured backend.
Escapes the five HTML-significant characters so interpolated user data cannot inject markup into an HTML body.
Lazily imports nodemailer. Only exercised on the lazy path.
Lazily imports the AWS SESv2 SDK. Only exercised on the lazy path.
Creates the MailPlugin.
Maps an OutgoingMail to nodemailer's message fields.
Maps an OutgoingMail to a SendGrid v3 request body.
Maps an OutgoingMail to a SendEmailCommand input.
Validates that an injected object matches ISesClient.
Validates that an injected object matches ISmtpTransport.
Email sender.
-
isHealthy(): Promise<boolean | undefined>
Reports whether the mail transport is REACHABLE right now, distinct from whether the mailer was constructed. Optional: a mailer whose transport exposes no side-effect-free probe omits it, and so does an implementation that does not answer the question at all.
-
send(message: MailMessage): Promise<void>
Sends an email.
-
sendTemplate(): Promise<void>template: string,message: Omit<MailMessage, "html" | "text">,data: Readonly<Record<string, unknown>>
Renders a named template and sends the result.
Structural shape of an AWS SESv2 client facade (injected or SDK-adapted). The
plugin never hard-depends on @aws-sdk/client-sesv2.
-
isHealthy(): Promise<boolean>
M70c: reports whether the SES account is reachable — the real adapter issues
GetAccount. Optional so a minimal injected fake still type-checks; a client that omits it is unknown, notfalse. -
sendEmail(message: OutgoingMail): Promise<void>
Sends one message via SES.
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.
-
sendMail(mail: { from: string; to: string; subject: string; text?: string; html?: string; cc?: string; bcc?: string; }): Promise<unknown>
Sends one message.
-
verify(): Promise<unknown>
M70c: verifies the SMTP connection. nodemailer's real transport exposes this; a minimal injected fake may omit it, in which case the provider reports unknown reachability rather than
false.
Options for LogProvider.
-
logger: ILogger
Logger to write each send to (typically
ctx.logger). -
sink: (message: OutgoingMail) => void
Called with each sent message — a read-back seam for tests/hooks.
An outgoing email message.
-
bcc: readonly string[]
Blind-carbon-copy recipients.
-
cc: readonly string[]
Carbon-copy recipients.
-
from: string
Sender address; omitted to use the provider default.
-
html: string
HTML body.
-
subject: string
Subject line.
-
text: string
Plain-text body.
-
to: string | readonly string[]
Recipient address(es).
Options for the MailPlugin factory.
-
defaults: { from?: string; }
Message defaults applied when a message omits the field.
-
options: MailProviderOptions
Provider-specific options.
-
provider: MailProviderType
Provider backend. Defaults to
'log'. -
templates: Record<string, MailTemplate>
Named body templates available to
sendTemplate.
Provider-specific options. Fields are consumed only by the matching provider;
unrelated fields are ignored (mirrors SecretsProviderOptions).
-
accessKeyId: string
(
ses) AWS access key id for the lazily-loaded client. -
apiKey: string
(
sendgrid) SendGrid API key sent as a Bearer token. -
auth: { user: string; pass: string; }
(
smtp) SMTP auth credentials. -
client: ISesClient
(
ses) Injected client facade; bypasses the lazy SDK import. -
endpoint: string
(
sendgrid) API endpoint. Defaulthttps://api.sendgrid.com/v3/mail/send. -
host: string
(
smtp) SMTP server host. -
http: IMailHttp
(
sendgrid) Injectedfetch-shaped function; defaults to globalfetch. -
port: number
(
smtp) SMTP server port. Default587. -
region: string
(
ses) AWS region for the lazily-loaded client. -
secretAccessKey: string
(
ses) AWS secret access key for the lazily-loaded client. -
secure: boolean
(
smtp) Use an implicit TLS connection. Defaultfalse. -
sink: (message: OutgoingMail) => void
(
log) Called with each sent message — a read-back seam for tests/hooks. -
transport: ISmtpTransport
(
smtp) Injected transport facade; bypasses the lazynodemailerimport.
Options for MailService.
-
defaultFrom: string
Default sender used when a message omits
from. -
probeTiming: ProbeTiming
Monotonic clock and timers used to cache and bound
MailService.isHealthy.
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).
The subset of nodemailer the adapter uses.
A rendered template body. Only present bodies are returned.
Options for SendGridProvider.
-
apiKey: string | undefined
SendGrid API key sent as a Bearer token.
-
endpoint: string | undefined
API endpoint. Default
https://api.sendgrid.com/v3/mail/send. -
http: IMailHttp | undefined
Injected
fetch-shaped function; defaults to globalfetch.
Options for SesProvider.
-
accessKeyId: string | undefined
AWS access key id for the lazily-loaded client.
-
client: ISesClient | undefined
Injected client facade; bypasses the lazy SDK import.
-
region: string | undefined
AWS region for the lazily-loaded client.
-
secretAccessKey: string | undefined
AWS secret access key for the lazily-loaded client.
The subset of the AWS SESv2 SDK the adapter uses.
Options for SmtpProvider.
-
auth: { user: string; pass: string; } | undefined
SMTP auth credentials.
-
host: string | undefined
SMTP server host.
-
port: number | undefined
SMTP server port. Default
587. -
secure: boolean | undefined
Use an implicit TLS connection. Default
false. -
transport: ISmtpTransport | undefined
Injected transport facade; bypasses the lazy
nodemailerimport.
A fetch-shaped function used by SendGridProvider so it stays
runtime-agnostic and testable.
Supported mail provider backends.
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.
Example 1
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, }));
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.
-
timeoutMs: number
The bound that fired, in milliseconds.
GCP Pub/Sub message broker.
-
connect(): Promise<void>
Opens the broker connection.
-
disconnect(): Promise<void>
Closes the broker connection.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c):
falseonly when positively unreachable. -
isReady(): boolean
Checks if the broker is connected and ready (lifecycle).
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. @internal
-
reachability(): Promise<boolean | undefined>
Tri-state backend reachability (M70c).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request to a topic and awaits a single correlated reply, providing brokered request-reply (RPC) over the message broker.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic. The handler's resolved value is sent back to the requesting caller, correlated to the originating request.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
In-memory message broker implementation.
-
connect(): Promise<void>
Connects the broker (idempotent no-op for in-memory).
-
disconnect(): Promise<void>
Disconnects the broker and clears all subscriptions.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c).
-
isReady(): boolean
Checks if the broker is connected.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. Resolves on dispatch hand-off (see
publish); each invoked handler's promise is RETAINED and its rejection routed to the failure path below — never dropped, never unhandled. @internal -
reachability(): Promise<boolean>
Tri-state backend reachability (M70c).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request and awaits a single correlated reply.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder whose result is returned to the requesting caller.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
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.
-
expectedType: string
The
typethe consuming definition expects. -
expectedVersion: number
The
versionthe consuming definition expects. -
reason: IntegrationEventRejectionReason
Why the delivery was refused.
-
topic: string
The topic the message was consumed from.
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.
-
stream: string
The stream name the broker tried to ensure.
JSON serializer implementation for message payloads.
-
deserialize<T = unknown>(payload: string): T
Deserializes a JSON string to a value.
-
serialize<T>(value: T): string
Serializes a value to a JSON string.
Kafka message broker implementation.
-
connect(): Promise<void>
Connects to Kafka and creates producer.
-
disconnect(): Promise<void>
Disconnects from Kafka.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c):
falseonly when positively unreachable. -
isReady(): boolean
Checks if the broker is connected.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. @internal
-
reachability(): Promise<boolean | undefined>
Tri-state backend reachability (M70c).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request and awaits its single correlated reply.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic. The handler's resolved value is sent back to the caller, correlated to the originating request.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic using a consumer group.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
NATS JetStream message broker implementation.
-
connect(): Promise<void>
Connects to NATS and ensures the JetStream stream exists.
-
disconnect(): Promise<void>
Disconnects from NATS.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c):
falseonly when positively unreachable. -
isReady(): boolean
Checks if the broker is connected.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a subject (topic).
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. @internal
-
reachability(): Promise<boolean | undefined>
Tri-state backend reachability (M70c).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request and awaits a single correlated reply.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder whose result is returned to the requesting caller.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic using JetStream durable consumers.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
RabbitMQ message broker implementation using AMQP 0-9-1 topic exchange.
-
connect(): Promise<void>
Connects to RabbitMQ.
-
disconnect(): Promise<void>
Disconnects from RabbitMQ.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c):
falseonly when positively unreachable. -
isReady(): boolean
Checks if the broker is connected (lifecycle — M70c).
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. @internal
-
reachability(): Promise<boolean>
Tri-state backend reachability (M70c).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request and awaits a single correlated reply.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder whose result is returned to the requesting caller.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
Redis Streams message broker implementation.
-
connect(): Promise<void>
Connects the broker to Redis.
-
disconnect(): Promise<void>
Disconnects the broker and clears all subscriptions.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c):
falseonly when positively unreachable. -
isReady(): boolean
Checks if the broker is connected.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic (Redis stream).
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. @internal
-
reachability(): Promise<boolean | undefined>
Tri-state backend reachability (M70c).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request and awaits a single correlated reply.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder whose result is returned to the requesting caller.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic using Redis Streams consumer groups.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
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.
-
remoteMessage: string
The error message reported by the remote responder.
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.
Azure Service Bus message broker.
-
connect(): Promise<void>
Opens the broker connection.
-
disconnect(): Promise<void>
Closes the broker connection.
-
isHealthy(): Promise<boolean>
Boolean port member (M70c):
falseonly when positively unreachable. -
isReady(): boolean
Checks if the broker is connected and ready (lifecycle).
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
publishWithHeaders<T>(): Promise<void>topic: string,message: T,headers: Readonly<Record<string, string>>
Publishes a message with framework-owned transport headers. @internal
-
reachability(): Promise<boolean | undefined>
Tri-state backend reachability (M70c, bounded in M90b).
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request to a topic and awaits a single correlated reply, providing brokered request-reply (RPC) over the message broker.
-
requestWithHeaders<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,headers: Readonly<Record<string, string>>,options?: RequestOptions
Sends request-reply traffic with framework-owned headers. @internal
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic. The handler's resolved value is sent back to the requesting caller, correlated to the originating request.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
-
subscribeWithHeaders<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes through the header-aware internal path. @internal
Signals that a broker's transport cannot support brokered request-reply.
Adapts the real GCP Pub/Sub SDK module to the domain port.
Adapts the real Azure Service Bus SDK module to the domain port.
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.
Defines a versioned integration-event contract and validates it eagerly.
EventsMessagingBridge factory.
Lazily load the GCP Pub/Sub SDK.
Lazily load the Azure Service Bus SDK.
MessagingPlugin factory.
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().
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.
Custom (inject-any-broker) arm.
Options for the EventsMessagingBridge factory.
-
errorHandler: () => voiderror: unknown,eventType: string
Custom error handler for publish failures.
-
eventTypes: readonly string[]
The event types to forward to the messaging broker.
-
token: string
The capability token for the messaging broker to use.
-
topicMapping: (eventType: string) => string
Function to map event types to broker topics.
Message broker for cross-service integration events.
-
connect(): Promise<void>
Opens the broker connection.
-
disconnect(): Promise<void>
Closes the broker connection.
-
isHealthy(): Promise<boolean>
Reports whether the broker's backend is reachable right now, for the plugin's health indicator.
-
publish<T>(): Promise<void>topic: string,message: T
Publishes a message to a topic.
-
request<TReq, TRes>(): Promise<TRes>topic: string,message: TReq,options?: RequestOptions
Sends a request to a topic and awaits a single correlated reply, providing brokered request-reply (RPC) over the message broker.
-
respond<TReq, TRes>(): Promise<ISubscription>topic: string,handler: RequestHandler<TReq, TRes>,options?: SubscribeOptions
Registers a responder for a request topic. The handler's resolved value is sent back to the requesting caller, correlated to the originating request.
-
subscribe<T>(): Promise<ISubscription>topic: string,handler: MessageHandler<T>,options?: SubscribeOptions
Subscribes to a topic.
Public members used from NATS MsgHdrs.
-
get(key: string): string | undefined
Reads one header value.
-
keys(): Iterable<string>
Lists the header names.
-
set(): voidkey: string,value: string
Stores one header value.
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: () => void | Promise<void>error: unknown,metadata: MessageMetadata
Called once per REJECTED subscription handler, with the error and the message metadata of the failed dispatch.
publishresolves 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 rejectpublishnor abort the sibling fan-out nor surface as an unhandled rejection.MessagingPluginalways supplies one backed by the application's logger, so the absent case is reachable only by constructing the broker directly.
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
typefield. -
version: number
The contract version. A bump is a breaking payload change.
The wire shape of a published integration event.
-
aggregateId: string
ID of the aggregate the event concerns, when supplied.
-
aggregateVersion: number
Version of the aggregate the event concerns, when supplied.
-
causationId: string
ID of the event that directly caused this one, when propagated.
-
correlationId: string
ID of the chain root this event descends from, when propagated.
-
data: T
The event payload, as the producer published it.
-
id: string
Producer-assigned event identity (
runtime.uuid()). -
occurredAt: string
Publish time as an ISO-8601 string (
new Date(runtime.now()).toISOString()). -
type: string
The definition's semantic event name.
-
version: number
The definition's contract version.
Optional causal metadata for publishIntegrationEvent.
-
aggregateId: string
ID of the aggregate the event concerns.
-
aggregateVersion: number
Version of the aggregate the event concerns.
-
causationId: string
ID of the event that directly caused this one.
-
correlationId: string
ID of the causal chain root this event descends from.
Handle for an open Pub/Sub subscription.
-
close(): Promise<void>
Close the subscription.
Domain port for GCP Pub/Sub operations. The broker depends on this, not the SDK directly.
-
close(): Promise<void>
Close the client and all subscriptions.
-
createSubscription(): Promise<void>topic: string,subscription: string
Explicitly create a subscription (for RPC inbox).
-
deleteSubscription(subscription: string): Promise<void>
Delete a subscription (for RPC inbox teardown).
-
isHealthy(): Promise<boolean>
Reports whether the Pub/Sub backend is reachable (optional, M70c).
-
open(): Promise<IPubSubSubscription>topic: string,subscription: string,onMessage: (msg: { payload: string; ack: () => void; nack: () => void; attributes?: Readonly<Record<string, string>>; messageId?: string; timestamp?: Date; }) => void
Open a subscription on a topic. Creates the subscription when absent.
-
publish(): Promise<void>topic: string,bytes: Uint8Array,attributes?: Readonly<Record<string, string>>
Publish bytes to a topic.
Serializer contract for converting messages to/from string payloads.
-
deserialize<T = unknown>(payload: string): T
Deserializes a string payload to a value.
-
serialize<T>(value: T): string
Serializes a value to a string payload.
Structural type matching the real SDK's ProcessErrorArgs callback argument (npm:@azure/service-bus@^7).
-
entityPath: string
The entity path for the current receiver.
-
error: Error
The underlying error.
-
errorSource: "abandon"
| "complete"
| "processMessageCallback"
| "receive"
| "renewLock"The operation where the error originated.
-
fullyQualifiedNamespace: string
The fully qualified namespace for the Service Bus.
-
identifier: string
The identifier of the client that raised this event.
Structural receiver type carrying the real SDK settlement methods. Settlement belongs to the receiver — NOT the received message.
-
abandonMessage(): Promise<void>message: unknown,propertiesToModify?: Record<string, unknown>
- close(): Promise<void>
- completeMessage(message: unknown): Promise<void>
-
subscribe(): { close(): Promise<void>; }handlers: { processMessage: (message: unknown) => Promise<void>; processError: (args: IServiceBusProcessErrorArgs) => Promise<void>; },options?: IServiceBusSubscribeOptions
Structural receive-options matching the real SDK's SubscribeOptions (npm:@azure/service-bus@^7). The property is autoCompleteMessages, not autoComplete.
Handle for an open Service Bus subscription receiver.
-
close(): Promise<void>
Close the receiver.
Domain port for Azure Service Bus operations.
-
close(): Promise<void>
Close the client and all senders/receivers.
-
createSubscription(): Promise<void>topic: string,subscription: string
Create a subscription (for RPC inbox).
-
deleteSubscription(): Promise<void>topic: string,subscription: string
Delete a subscription (for RPC inbox teardown).
-
isHealthy(): Promise<boolean | undefined>
Reports whether the Service Bus namespace is reachable (optional, M70c).
-
open(): Promise<IServiceBusSubscription>topic: string,subscription: string,onMessage: (msg: { payload: string; ack: () => void; nack: () => void; applicationProperties?: Readonly<Record<string, string>>; messageId?: string; timestamp?: Date; }) => void | Promise<void>
Open a receiver on a topic subscription.
-
send(): Promise<void>topic: string,body: string,applicationProperties?: Readonly<Record<string, string>>
Send a body to a topic.
Kafka-specific options (internal use).
-
brokers: readonly string[]
Kafka bootstrap brokers.
-
client: IKafkaFactory
Injected Kafka factory.
-
clientId: string
Kafka client ID (default: 'messaging-client').
-
defaultQueue: string
Default consumer group name.
-
logger: { error: (msg: string) => void; }
Optional logger for error reporting.
-
replyTopic: string
Topic every request-reply response is published to and read back from.
Default (memory) arm. The discriminant is optional so that MessagingPlugin()
and MessagingPlugin({}) remain valid.
Transport metadata accompanying a delivered message.
-
headers: Readonly<Record<string, string>>
Transport headers read from the delivered message. First-party brokers populate this with
{}when their transport carried no headers. -
messageId: string
Broker-assigned message ID, when available.
-
timestamp: Date
Delivery timestamp, when available.
-
topic: string
The topic the message arrived on.
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 (
IIngressBehaviorin@setu-ts/common). -
chainReadyTimeoutMs: number
Bounds a dispatch held on the behaviour-chain gate, which exists only when a
RegistryFactorybehaviour is declared. A held dispatch that waits longer than this rejects withChainGateTimeoutError, whose message names the likely cause (a plugin publishing during its ownregister()); 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 afterstart(). Each entry — instance orRegistryFactory— produces onesubscribe()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.
NATS arm.
- broker: "nats"
- client: INatsConnection
- defaultQueue: string
-
headersFactory: () => INatsHeaders
Factory building the NATS
MsgHdrsused to carry transport headers. - streamName: string
-
streamSubjects: readonly string[]
Subjects the broker may create streamName with when the stream is absent on the server.
- url: string
NATS-specific options (internal use).
-
client: INatsConnection
Injected NATS connection.
-
defaultQueue: string
Default consumer group name.
-
headersFactory: () => INatsHeaders
Factory for NATS headers when an application injects the connection.
-
logger: { error: (msg: string) => void; }
Optional logger for error reporting.
-
streamName: string
JetStream stream name (default: 'MESSAGING').
-
streamSubjects: readonly string[]
Subjects the broker may create the stream with when it is absent (X28-2). No default: with the stream absent and this unset,
connect()throwsJetStreamStreamErrornaming both remedies. SeeNatsMessagingOptions.streamSubjectsfor the full behavior. -
url: string
NATS connection URL(s).
Options for GCP Pub/Sub broker.
-
client: IPubSubTransport
Injected transport (bypasses lazy SDK load).
-
credentials: unknown
Service-account credentials (object or key path). SDK ADC is used when omitted.
-
defaultQueue: string
Default consumer-group subscription name.
-
logger: { error: (msg: string) => void; }
Optional logger.
-
projectId: string
GCP project ID. Required unless client is injected.
-
replyTopic: string
Shared reply topic for request-reply (must pre-exist).
Declares the constructors used from the real GCP Pub/Sub SDK so the adapter can build a domain port. This is NOT an SDK-shaped structural facade — it names only what the adapter actually uses.
RabbitMQ-specific options (internal use).
-
client: IAmqpConnection
Injected AMQP connection.
-
defaultQueue: string
Default consumer group/queue name.
-
exchangeName: string
Exchange name (default: 'messaging').
-
logger: { error: (msg: string) => void; }
Optional logger for error reporting.
-
url: string
RabbitMQ connection URL.
Redis-specific options (internal use).
-
blockSizeMs: number
Block timeout in milliseconds.
-
client: IRedisStreamsClient
Injected Redis client.
-
defaultQueue: string
Default consumer group name.
-
logger: { error: (msg: string) => void; }
Optional logger for error reporting.
-
pollIntervalMs: number
Poll interval in milliseconds.
-
url: string
Redis connection URL.
Options accepted by IMessageBroker.request.
-
timeoutMs: number
Reply wait budget in milliseconds. When no correlated reply arrives within this window,
requestrejects. Defaults to5000when omitted.
Options for Azure Service Bus broker.
-
adminConnectionString: string
Connection string for the administration client (reply-subscription creation). Defaults to connectionString.
-
client: IServiceBusTransport
Injected transport (bypasses lazy SDK load).
-
connectionString: string
Connection string for the Service Bus namespace. Required unless client is injected.
-
defaultQueue: string
Default subscription name.
-
logger: { error: (msg: string) => void; }
Optional logger.
-
replyTopic: string
Shared reply topic for request-reply (must pre-exist).
-
retryOptions: ServiceBusRetryOptions
SDK retry budget for the data client (M90b / X28-6). Forwarded to
ServiceBusClientonly — the administration client is never given it.
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;0disables 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
RetryModebeforeServiceBusClientis 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.
Declares the constructors used from the real Azure Service Bus SDK.
-
RetryMode: { readonly Exponential: number; readonly Fixed: number; }
The SDK's numeric
RetryModeenum (re-exported by@azure/service-bus). The publicServiceBusRetryOptions.modestring is translated through this before reaching the SDK —@azure/core-amqpcompares the value with===against its enum, so an untranslated string silently behaves as the SDK default (Fixed). -
ServiceBusAdministrationClient: new (connectionString: string) => { createSubscription(): Promise<unknown>; deleteSubscription(topicName: string,subscriptionName: string): Promise<unknown>; getNamespaceProperties?(): Promise<unknown>; }topicName: string,subscriptionName: string
-
ServiceBusClient: new () => { createSender(queueOrTopicName: string): { sendMessages(messages: { body: unknown; }): Promise<void>; close(): Promise<void>; }; createReceiver(connectionString: string,options?: { retryOptions?: Omit<ServiceBusRetryOptions, "mode"> & { mode?: number; }; }): IServiceBusReceiver; createReceiver(queueName: string,options?: unknown): IServiceBusReceiver; close(): Promise<void>; }topicName: string,subscriptionName: string,options?: unknown
Options accepted when subscribing to a topic.
-
queue: string
Consumer group / queue name for load-balanced delivery.
The declarative form of one IMessageBroker.subscribe() call — the entry
an application writes instead of calling subscribe() imperatively after
start().
-
handler: MessageHandler
Invoked per delivered message, exactly as the imperative
subscribe()accepts. -
options: SubscribeOptions
Consumer-group configuration, exactly as the imperative
subscribe()accepts. -
topic: string
The topic to subscribe to (the
subscribe()topic argument).
Handles one delivered integration event.
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.
Handles messages delivered on a subscription.
| PubSubMessagingOptionsProduction
GCP Pub/Sub options — exclusive union of injected and production arms.
Responder for a request topic. Its resolved value is sent back to the caller as the reply, correlated to the originating request.
| ServiceBusMessagingOptionsProduction
Azure Service Bus options — exclusive union of injected and production arms.
| RegistryFactory<SubscriptionDefinition>
One entry of MessagingCommonOptions.subscriptions: a
subscription definition, or a RegistryFactory producing one
when the handler needs a resolved capability.
Example 1
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);
-
getValue(labels?: Readonly<Record<string, string>>): number
Gets the current value for a label set.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the counter.
-
observe(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Records an observation — equivalent to
inc()for counters. -
valueEntries(): ReadonlyMap<string, CounterValue>
Gets all value entries with labels.
-
values(): ReadonlyMap<string, number>
Gets all values.
-
dec(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Decrements the gauge.
-
getValue(labels?: Readonly<Record<string, string>>): number
Gets the current value for a label set.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the gauge.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation — equivalent to
set()for gauges. -
set(): voidvalue: number,labels?: Readonly<Record<string, string>>
Sets the gauge to a specific value.
-
valueEntries(): ReadonlyMap<string, GaugeValue>
Gets all value entries with labels.
-
values(): ReadonlyMap<string, number>
Gets all values.
-
buckets(): readonly number[]
The bucket boundaries.
-
getAllBucketCounts(): ReadonlyMap<>string,{ buckets: ReadonlyMap<number, number>; sum: number; count: number; labels?: Readonly<Record<string, string>>; }
Gets all bucket counts for all observed label sets.
-
getBucketCounts(labels?: Readonly<Record<string, string>>): ReadonlyMap<number, number>
Gets the bucket counts for a label set.
-
getCount(labels?: Readonly<Record<string, string>>): number
Gets the count for a label set.
-
getSum(labels?: Readonly<Record<string, string>>): number
Gets the sum for a label set.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation.
The metrics service — provides factory methods for creating metrics and rendering them in Prometheus format.
-
counter(): ICountername: string,options?: MetricOptions
Gets or creates a counter.
-
gauge(): IGaugename: string,options?: MetricOptions
Gets or creates a gauge.
-
get(name: string): IMetric | undefined
Gets a metric by name.
-
histogram(): IHistogramname: string,options?: MetricOptions
Gets or creates a histogram.
-
names(): readonly string[]
Gets all registered metric names.
-
register(): IMetricname: string,config: MetricConfig
Registers a metric directly (for declarative registration).
-
render(): string
Renders all metrics in Prometheus text format.
-
snapshot(): readonly MetricSnapshot[]
Takes a snapshot of all metrics for rendering.
-
summary(): ISummaryname: string,options?: MetricOptions
Gets or creates a summary.
-
getAllQuantiles(): ReadonlyMap<>string,{ quantiles: ReadonlyMap<number, number>; sum: number; count: number; labels?: Readonly<Record<string, string>>; }
Gets all quantile data for all observed label sets.
-
getCount(labels?: Readonly<Record<string, string>>): number
Gets the count for a label set.
-
getQuantiles(labels?: Readonly<Record<string, string>>): ReadonlyMap<number, number>
Gets the quantile values for a label set.
-
getSampleCount(labels?: Readonly<Record<string, string>>): number
Gets the current sample window size.
-
getSum(labels?: Readonly<Record<string, string>>): number
Gets the sum for a label set.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation.
-
quantiles(): readonly number[]
The quantiles.
Creates a metrics plugin.
Monotonically increasing counter. observe / inc add a non-negative value.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the counter.
Gauge: arbitrary set / inc / dec. observe sets the value.
-
dec(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Decrements the gauge.
-
inc(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Increments the gauge.
-
set(): voidvalue: number,labels?: Readonly<Record<string, string>>
Sets the gauge to a specific value.
Histogram: bucketed observation distribution plus sum and count.
-
buckets: readonly number[]
Upper bounds of the histogram buckets.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation (sample).
A registered metric.
-
help: string
Human-readable description.
-
name: string
Metric name (Prometheus naming conventions).
-
observe(): voidvalue?: number,labels?: Readonly<Record<string, string>>
Records an observation.
-
type: MetricType
The metric instrument kind.
Metrics service resolved via ctx.services.get<IMetricsService>('metrics').
-
counter(): ICountername: string,options?: MetricOptions
Gets or creates a counter.
-
gauge(): IGaugename: string,options?: MetricOptions
Gets or creates a gauge.
-
get(name: string): IMetric | undefined
Gets a metric by name.
-
histogram(): IHistogramname: string,options?: MetricOptions
Gets or creates a histogram.
-
summary(): ISummaryname: string,options?: MetricOptions
Gets or creates a summary.
Summary: per-quantile observations plus sum and count.
-
observe(): voidvalue: number,labels?: Readonly<Record<string, string>>
Records an observation (sample).
-
quantiles: readonly number[]
Configured quantiles.
Configuration for registering a metric.
-
buckets: readonly number[]
Histogram bucket boundaries (histogram metrics only).
-
help: string
Human-readable description (Prometheus
HELP). -
labels: readonly string[]
Label names attachable to observations.
-
type: MetricType
The metric instrument kind.
Ergonomic options for the typed factory methods. type is injected by the
method name; help defaults to the metric name.
-
buckets: readonly number[]
Histogram bucket boundaries (histogram metrics only).
-
help: string
Human-readable description (Prometheus
HELP). Defaults to the metric name. -
labels: readonly string[]
Label names attachable to observations.
-
maxSamples: number
Summary only: bounded sample-window size.
-
quantiles: readonly number[]
Summary quantiles (summary metrics only).
Plugin options for MetricsPlugin.
-
customMetrics: readonly NamedMetricConfig[]
Declarative metric definitions to pre-register.
-
defaultBuckets: readonly number[]
Default histogram bucket boundaries.
-
defaultMetrics: boolean
Enable built-in HTTP metrics.
-
defaultQuantiles: readonly number[]
Default summary quantiles.
-
endpoint: string
The scrape endpoint path.
-
excludePaths: readonly PathPattern[]
Request paths the HTTP metrics middleware skips entirely — no counter, histogram, or gauge is touched for them.
-
httpMetrics: boolean
Enable the metrics middleware for HTTP request tracking.
Isolates tenants by stamping a tenant column on every row.
-
getTenantColumn(): string
Return the column name used to stamp tenant ids on rows.
- kind: "column"
Isolates tenants by assigning each a separate database.
- kind: "database"
-
resolveDatabase(tenantId: string): string
Derive the database name for a tenant id.
Resolves the tenant id from an HTTP header.
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolve the tenant id from the configured request header.
& { decode: (token: string) => Record<string, unknown> | null; }
Resolves the tenant id from a claim in an unverified JWT payload.
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolve the tenant id from the configured JWT claim.
A zero-dependency in-memory ITenantDataStore that partitions rows by
strategy-derived scope ('column' → tenantId, 'schema' → resolved schema,
'database' → resolved database).
-
close(): Promise<void>
Gracefully close any connections.
-
create<E>(): Promise<E>tenantId: string,entity: string,data: Readonly<Record<string, unknown>>
Create a new record; returns the stored entity including its id.
-
delete<Id>(): Promise<boolean>tenantId: string,entity: string,id: Id
Delete a record. Returns
trueif a record was deleted. -
find<E>(): Promise<readonly E[]>tenantId: string,entity: string,filter: Readonly<Record<string, unknown>>
Find records matching a filter.
-
findAll<E>(): Promise<readonly E[]>tenantId: string,entity: string
Retrieve all records of an entity for a tenant.
-
findById<E, Id>(): Promise<E | null>tenantId: string,entity: string,id: Id
Find a single record by its identifier.
-
update<E, Id>(): Promise<E | null>tenantId: string,entity: string,id: Id,data: Readonly<Record<string, unknown>>
Update an existing record; returns
nullwhen the id is unknown. -
useIsolation(strategy: ITenantIsolationStrategy): void
Receive the isolation strategy from the plugin's
register().
Resolves the tenant id from a segment of request.path.
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolve the tenant id from a segment of
request.path.
Isolates tenants by assigning each a separate database schema.
- kind: "schema"
-
resolveSchema(tenantId: string): string
Derive the schema name for a tenant id.
Resolves the tenant id from the first subdomain label of request.url.
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolve the tenant id from the request's subdomain.
Thrown by IMultiTenancyService.getRepository when no tenant
is resolved in the request context.
Exported accessor that reads the cache-prefix stamped into ctx.state by
the middleware. Consumers never hardcode the state key string.
Multi-tenancy plugin factory.
Factory that creates a middleware function resolving the tenant and attaching
it to ctx.request.tenant.
Options for HeaderResolver.
-
name: string
HTTP header name to read (default
'x-tenant-id').
Multi-tenancy service — exposes tenant context, repository creation, and cache-key helpers.
-
getCurrentTenant(ctx: IRequestContext): ITenant | undefined
Return the tenant resolved for this request context, or
undefined. -
getRepository<Entity, Id = string>(): ITenantRepository<Entity, Id>ctx: IRequestContext,entity: string
Create a tenant-scoped repository for the given entity type. Throws
TenantNotResolvedErrorif no tenant is resolved. -
getRepositoryFor<Entity, Id = string>(): ITenantRepository<Entity, Id>tenantId: string,entity: string
Create a tenant-scoped repository for the given entity type, scoped to the tenant id GIVEN — no
IRequestContextrequired. This is the entry point for non-HTTP work (an ingress behaviour, a queue processor, a scheduled job), where no request exists to resolve a tenant from; the caller reads the tenant id from the work item's own payload. Modelled onprefixCacheKey— this interface's other ctx-free, id-taking member. -
prefixCacheKey(): stringtenantId: string,key: string
Build a cache key that includes the tenant id, joined by the separator the plugin was configured with (
cache.separator, default':'). The separator is deliberately NOT a per-call argument: this method is the single home for separator resolution, so the middleware'sctx.stateprefix and a caller's key can never disagree.
A resolved tenant.
-
id: string
Stable tenant identifier.
-
metadata: Readonly<Record<string, unknown>>
Tenant-specific configuration.
-
name: string
Display name.
Tenant-scoped data-store port.
-
close(): Promise<void>
Gracefully close any connections.
-
create<E>(): Promise<E>tenantId: string,entity: string,data: Readonly<Record<string, unknown>>
Create a new record; returns the stored entity including its id.
-
delete<Id>(): Promise<boolean>tenantId: string,entity: string,id: Id
Delete a record. Returns
trueif a record was deleted. -
find<E>(): Promise<readonly E[]>tenantId: string,entity: string,filter: Readonly<Record<string, unknown>>
Find records matching a filter.
-
findAll<E>(): Promise<readonly E[]>tenantId: string,entity: string
Retrieve all records of an entity for a tenant.
-
findById<E, Id>(): Promise<E | null>tenantId: string,entity: string,id: Id
Find a single record by its identifier.
-
update<E, Id>(): Promise<E | null>tenantId: string,entity: string,id: Id,data: Readonly<Record<string, unknown>>
Update an existing record; returns
nullwhen the id is unknown. -
useIsolation(strategy: ITenantIsolationStrategy): void
Receives the resolved isolation strategy once, during
register(). Optional so a store may ignore isolation metadata entirely.
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.
-
create(data: Readonly<Record<string, unknown>>): Promise<Entity>
Create a new record.
-
delete(id: Id): Promise<boolean>
Delete a record by its identifier. Returns
trueif a record was deleted. -
find(filter: Readonly<Record<string, unknown>>): Promise<readonly Entity[]>
Find records matching a filter.
-
findAll(): Promise<readonly Entity[]>
Retrieve all records.
-
findById(id: Id): Promise<Entity | null>
Find a single record by its identifier.
-
update(): Promise<Entity | null>id: Id,data: Readonly<Record<string, unknown>>
Update an existing record by its identifier.
Resolves the tenant for an incoming request (by subdomain, header, path, or JWT claim, depending on the implementation).
-
resolve(request: IRequest): Promise<Option<ITenant>>
Resolves the request's tenant.
Options for JwtResolver.
-
claim: string
JWT claim name that holds the tenant id (default
'tenant_id'). -
decode: (token: string) => Record<string, unknown> | null
Custom JWT-decode function. When absent the plugin resolves
IJwtService.decodefrom the capability token inregister(). -
headerName: string
Authorization header name (default
'authorization').
Options passed to the MemoryTenantDataStore constructor.
-
generateId: () => string
Generate a unique identifier for new records when
data.idis not astringornumber. Defaults to a monotonic counter ('1','2', …).
Top-level options for MultiTenancyPlugin.
-
cache: TenantCacheOptions
Cache-prefix behaviour.
-
dataStore: ITenantDataStore
An application-provided data store. When absent the plugin ships a zero-dependency
MemoryTenantDataStore. -
database: DatabaseStrategyKind | ITenantIsolationStrategy
Database-isolation strategy: a discriminant string, or a custom
ITenantIsolationStrategyinstance. Default:'column-per-tenant'. -
exclude: readonly PathPattern[]
Paths that skip tenant resolution entirely — no resolver runs, no tenant is stamped, and a
requireddeployment does not reject them. Matched againstctx.request.pathby exact string equality orRegExp.test. -
header: HeaderResolverOptions
Options forwarded to
HeaderResolver. -
jwt: JwtResolverOptions
Options forwarded to
JwtResolver. -
middlewarePriority: number
Priority passed to
ctx.middleware.add(default40). -
path: PathResolverOptions
Options forwarded to
PathResolver. -
rejectionStatus: number
HTTP status code returned when short-circuiting (default
400). -
required: boolean
When
trueand no resolver returns a tenant, short-circuit with an error response. Default:false. -
resolver: ResolverConfig
Which resolver(s) to use for tenant resolution (required).
-
subdomain: SubdomainResolverOptions
Options forwarded to
SubdomainResolver.
Options for PathResolver.
-
segment: number
Segment index in
request.path(default0).
Options for SubdomainResolver.
-
baseDomain: string
When set, strip this suffix from the host before taking the first label.
Options for cache-prefix stamping.
-
prefix: boolean
When
true, write the resolved prefix intoctx.state. -
separator: string
Separator between tenant id and key (default
':').
| "schema-per-tenant"
| "database-per-tenant"
A string discriminant that maps to an isolation-strategy class.
| "header"
| "path"
| "jwt"
| ITenantResolver
| readonly ITenantResolver[]
Resolver configuration — one string name, a custom instance, or a chain.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
State key for the cache prefix — consumers should use getTenantCachePrefix
instead of reading this directly.
EmailChannel dispatches notifications through the resolved IMailer.
-
isHealthy(): Promise<boolean | undefined>
Reports the mail transport's reachability by asking the injected
IMailer, which is the only channel in this package whose transport offers a side-effect-free probe. -
name: string
Channel dispatch name (e.g.
'email','sms'). -
send(notification: NotificationMessage): Promise<void>
Builds a
MailMessageand sends it viaIMailer.
FcmProvider implements PushTransport via the FCM HTTP v1 API.
-
send(message: PushMessage): Promise<void>
Sends a push notification via the FCM HTTP v1 endpoint.
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).
-
send(notification: NotificationMessage): Promise<void>
Dispatches a notification on every requested channel.
-
sendSettled(notification: NotificationMessage): Promise<readonly ChannelSendResult[]>
Dispatches a notification on every requested channel and reports the settled outcome of each, without throwing.
PushChannel dispatches notifications through a PushTransport (e.g. FcmProvider).
-
name: string
Channel dispatch name (e.g.
'email','sms'). -
send(notification: NotificationMessage): Promise<void>
Extracts
to.tokenand optionallysubjectas title, then sends viaPushTransport.
SlackChannel dispatches notifications through a SlackTransport (e.g. SlackProvider).
-
name: string
Channel dispatch name (e.g.
'email','sms'). -
send(notification: NotificationMessage): Promise<void>
Sends the body as text, optionally including
to.channel.
SlackProvider implements SlackTransport via a Slack incoming webhook URL.
-
send(message: SlackMessage): Promise<void>
Posts a message to the Slack webhook.
SmsChannel dispatches notifications through an SmsTransport (e.g. TwilioProvider).
-
name: string
Channel dispatch name (e.g.
'email','sms'). -
send(notification: NotificationMessage): Promise<void>
Extracts
to.phoneand sends viaSmsTransport.
TwilioProvider implements SmsTransport via the Twilio Accounts SID / Messages endpoint.
-
send(message: SmsMessage): Promise<void>
Sends an SMS via the Twilio REST API.
Creates a NotificationChannel for the given channel entry.
Creates the default fetch-backed INotificationHttp.
Creates the transport for a channel configuration.
Creates the plugin factory.
Push channel configuration — options are FcmProviderOptions.
Options for FcmProvider.
-
clientEmail: string
Service-account email that signs the OAuth2 assertion. Required unless
tokenSourceis supplied. - http: INotificationHttp
-
privateKey: string
PEM PKCS#8 private key for the service account. Required unless
tokenSourceis supplied. -
projectId: string
Firebase project id; addressed by the v1
messages:sendURL. -
runtime: IRuntimeServices
Runtime services providing Web Crypto and the wall clock, used to sign the assertion and expire cached tokens. Required unless
tokenSourceis 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.
Supplies OAuth2 access tokens for FCM HTTP v1.
-
getAccessToken(): Promise<string>
Returns a valid access token, minting or refreshing one as needed.
Injectable HTTP seam for notification providers.
-
post(): Promise<NotificationHttpResponse>url: string,body: string,headers: Record<string, string>
Issues a POST request and returns a mapped response.
Multi-channel notification dispatcher.
-
send(notification: NotificationMessage): Promise<void>
Dispatches a notification on every requested channel.
-
sendSettled(notification: NotificationMessage): Promise<readonly ChannelSendResult[]>
Dispatches a notification on every requested channel and reports the settled outcome of each, without throwing.
Response shape returned by INotificationHttp.post.
A notification dispatched across one or more channels.
-
body: string
Notification body.
-
channels: readonly string[]
Channel names to dispatch on (e.g.
['email', 'sms']). -
metadata: Readonly<Record<string, unknown>>
Channel-specific extras.
-
subject: string
Subject/title, for channels that support one.
-
to: Readonly<Record<string, string>>
Recipient addresses keyed by channel (e.g.
{ email: '…', phone: '…' }).
Options for NotificationPlugin.
-
channels: ChannelsMap
Channel definitions keyed by dispatch name.
An outgoing push-notification message shaped by PushTransport.
Push-notification transport port implemented by FcmProvider.
-
send(message: PushMessage): Promise<void>
Sends a push notification.
Slack channel configuration — options are SlackProviderOptions.
Slack transport port implemented by SlackProvider.
-
send(message: SlackMessage): Promise<void>
Posts a Slack message.
SMS transport port implemented by TwilioProvider.
-
send(message: SmsMessage): Promise<void>
Sends an SMS message.
SMS channel configuration — options are TwilioProviderOptions.
Options for TwilioProvider.
| TwilioChannelConfig
| FcmChannelConfig
| SlackChannelConfig
Per-channel configuration, discriminated on provider.
Plugin-level channels map.
Union of every transport a channel can be built on, as returned by
createProvider.
Provider type selector — the ChannelConfig discriminant.
Generates OpenAPI 3.1 documents from route information.
-
addSchema(): voidname: string,schema: unknown
Registers a named schema for deduplication.
-
generate(routes: readonly RouteInfo[]): OpenApiDocument
Generates an OpenAPI document from routes.
Service for generating and caching OpenAPI specifications.
-
addSchema(): voidname: string,schema: unknown
Registers a named schema for deduplication.
-
getSpec(): Readonly<Record<string, unknown>>
Returns the generated OpenAPI specification.
Converts a Zod schema to an OpenAPI 3.1 schema object.
-
transform(): OpenApiSchemaObjectschema: unknown,io?: SchemaIo
Transforms a Zod schema into an OpenAPI schema object.
Creates an OpenAPI plugin that auto-generates OpenAPI 3.1 documentation from registered routes and serves it (with optional Swagger UI).
Generates the Swagger UI HTML page.
Convenience function for one-off Zod to OpenAPI conversion.
Service for generating and retrieving OpenAPI 3.1 specifications.
-
addSchema(): voidname: string,schema: unknown
Registers a named schema for deduplication.
-
getSpec(): Readonly<Record<string, unknown>>
Returns the generated OpenAPI 3.1 document.
OpenAPI 3.1 document structure.
-
components: { readonly schemas?: Record<string, OpenApiSchemaObject>; readonly securitySchemes?: Record<string, unknown>; }
Reusable components.
-
info: { readonly title: string; readonly version: string; readonly description?: string; }
API metadata.
-
openapi: string
OpenAPI version.
-
paths: Record<>string,{ readonly get?: OpenApiOperation; readonly post?: OpenApiOperation; readonly put?: OpenApiOperation; readonly patch?: OpenApiOperation; readonly delete?: OpenApiOperation; readonly head?: OpenApiOperation; readonly options?: OpenApiOperation; }
API paths.
-
security: readonly SecurityRequirement[]
Document-level security requirements, applied to every operation that does not declare its own. An operation opts out with
security: []. -
servers: readonly { readonly url: string; readonly description?: string; }[]
Server URLs.
Options for OpenAPI document generation.
-
deriveRequestSchemas: boolean
Fills each operation's
requestBodyandparametersfrom the validation middleware actually guarding its route, so a route that already carriesvalidateBody(schema)does not have to repeat that schema inschema.body. -
deriveSecurity: { readonly scheme: string; }
Derives each operation's security requirement from the guards actually protecting its route, instead of requiring every route to declare one.
-
description: string
API description.
-
exclude: readonly string[]
Router paths to leave out of the generated document.
-
excludeOwners: readonly string[]
Plugin names whose routes are left out of the generated document, matched against
RouteInfo.owner. -
security: readonly SecurityRequirement[]
Document-level security requirements, inherited by every operation whose route does not declare
schema.security. Names must match keys ofOpenApiGeneratorOptions.securitySchemes. -
securitySchemes: Record<string, unknown>
Security schemes.
-
servers: readonly { readonly url: string; readonly description?: string; }[]
Server URLs.
-
title: string
API title (required, defaults to 'API').
-
version: string
API version (required, defaults to '1.0.0').
OpenAPI operation definition.
-
operationId: string
Unique operation identifier.
-
parameters: readonly OpenApiParameter[]
Path/query parameters.
-
requestBody: OpenApiRequestBody
Request body.
-
responses: Record<string, OpenApiResponse>
Response codes.
-
security: readonly SecurityRequirement[]
Security requirements for this operation — declared on the route's
schema.security, or derived from its branded guards whenOpenApiGeneratorOptions.deriveSecurityis configured (declared wins). Absent when neither applies, which leaves the operation inheriting the document-level requirement; an empty array marks it public, overriding that default. -
summary: string
Operation summary.
-
tags: readonly string[]
Operation tags.
-
x-setu-unrepresentable: readonly { readonly at: string; readonly reason: string; }[]
Machine-readable vendor extension naming the schema nodes on THIS operation the transformer could not represent (a zod
z.date()field, for example). Each entry names the operation (at) and why (reason). The node itself still degrades to an empty schema — never a throw — so a single unrepresentable field cannot take down/openapi.json. Absent when empty.
OpenAPI parameter definition.
-
description: string
Parameter description.
-
in: "path" | "query" | "header" | "cookie"
Parameter location.
-
name: string
Parameter name.
-
required: boolean
Whether parameter is required.
-
schema: OpenApiSchemaObject
Parameter schema.
Options for the OpenAPI plugin.
-
endpoint: string
Path for the Swagger UI HTML page.
-
specEndpoint: string
Path for the JSON spec endpoint.
-
swagger: boolean
Whether to serve the Swagger UI HTML page.
OpenAPI request body definition.
-
content: { readonly application/json: { readonly schema: OpenApiSchemaObject; }; }
Content types.
-
required: boolean
Whether body is required.
OpenAPI response definition.
-
content: { readonly application/json?: { readonly schema: OpenApiSchemaObject; }; }
Response content.
-
description: string
Response description.
OpenAPI 3.1 schema object.
-
$ref: string
Reference to a component schema.
-
additionalProperties: boolean | OpenApiSchemaObject
For objects: additional properties schema.
-
allOf: readonly OpenApiSchemaObject[]
AllOf for intersections.
-
anyOf: readonly OpenApiSchemaObject[]
AnyOf for unions.
-
const: string | number | boolean
Const value.
-
default: unknown
Default value.
-
enum: readonly (string | number | boolean)[]
Enum values.
-
exclusiveMaximum: number
For numbers: exclusive maximum.
-
exclusiveMinimum: number
For numbers: exclusive minimum.
-
format: string
Format (e.g., 'email', 'uri', 'uuid', 'date-time').
-
items: OpenApiSchemaObject
For arrays: schema of items.
-
maxItems: number
For arrays: maximum items.
-
maxLength: number
For strings: maximum length.
-
maximum: number
For numbers: maximum value.
-
minItems: number
For arrays: minimum items.
-
minLength: number
For strings: minimum length.
-
minimum: number
For numbers: minimum value.
-
properties: Record<string, OpenApiSchemaObject>
For objects: properties map.
-
required: readonly string[]
For objects: required property names.
-
type: "string"
| "number"
| "integer"
| "boolean"
| "array"
| "object"
| "null"Type of the value (string, number, integer, boolean, array, object, null).
Options for the OpenAPI service.
-
app: IApplication
The application context for accessing routes.
-
schemas: readonly { readonly name: string; readonly schema: unknown; }[]
Pre-registered schemas from other plugins.
Options for Swagger UI HTML generation.
-
specUrl: string
The URL of the OpenAPI spec JSON.
-
title: string
The title of the page.
Which side of a schema a document site is describing.
Consulted for every schema ZodToOpenApi.transform is about to
convert — the top-level one AND every sub-schema it recurses into.
In-memory queue adapter implementation.
-
ack(): Promise<void>name: string,id: string,_claimToken?: string
Acknowledges a job as successfully processed.
-
advanceRecurring(): Promise<void>id: string,nextRunAtMs: number
Advances a recurring job's next run time.
-
connect(): Promise<void>
Connects the adapter to its backend.
-
deadLetter(): Promise<void>name: string,id: string,_nowMs: number,_claimToken?: string
Moves a job to the dead letter queue.
-
depths(name: string): Promise<QueueDepths>
M70k (X8-4): counts this name's three states. Free for an in-process store, so there is no reason to omit it.
-
disconnect(): Promise<void>
Disconnects the adapter.
-
enqueue<T>(job: StoredJob<T>): Promise<void>
Enqueues a job.
-
fetchRecurringDue(nowMs: number): Promise<readonly StoredRecurring[]>
Fetches recurring jobs that are due.
-
getDeadLetters<T>(name: string): readonly StoredJob<T>[]
Returns the jobs dead-lettered under a queue name, in the order they were dead-lettered. A job lands here once it fails on its final attempt; the queue never delivers it again.
-
isHealthy(): Promise<boolean>
M70c: an in-memory queue has no backend to be unreachable, so it is always reachable (M47).
-
isReady(): boolean
Checks if the adapter is ready/connected.
-
requeue<T>(): Promise<void>name: string,id: string,availableAtMs: number,attempts: number,_claimToken?: string
Requeues a job with a new available timestamp.
-
reserve<T>(): Promise<readonly StoredJob<T>[]>name: string,limit: number,nowMs: number
Reserves up to
limitjobs that are due (availableAtMs <= nowMs). -
storeRecurring(rec: StoredRecurring): Promise<void>
Stores a recurring job.
RabbitMQ queue adapter implementation.
-
ack(): Promise<void>name: string,id: string,_claimToken?: string
Acknowledges a job as successfully processed.
-
advanceRecurring(): Promise<void>id: string,nextRunAtMs: number
Advances a recurring job's next run time.
-
connect(): Promise<void>
Connects the adapter to its backend.
-
deadLetter(): Promise<void>name: string,id: string,nowMs: number,_claimToken?: string
Moves a job to the dead letter queue.
-
disconnect(): Promise<void>
Disconnects the adapter.
-
enqueue<T>(job: StoredJob<T>): Promise<void>
Enqueues a job.
-
fetchRecurringDue(nowMs: number): Promise<readonly StoredRecurring[]>
Fetches recurring jobs that are due.
-
isHealthy: () => Promise<boolean>
M70c: present only when the connection exposes
on?; its absence is unknown reachability, notfalse. -
isReady(): boolean
Checks if the adapter is ready/connected.
-
requeue<T>(): Promise<void>name: string,id: string,availableAtMs: number,attempts: number,_claimToken?: string
Requeues a job with a new available timestamp.
-
reserve<T>(): Promise<readonly StoredJob<T>[]>name: string,limit: number,_nowMs: number
Reserves up to
limitjobs that are due (availableAtMs <= nowMs). -
storeRecurring(rec: StoredRecurring): Promise<void>
Stores a recurring job.
Redis queue adapter implementation.
-
ack(): Promise<void>name: string,id: string,_claimToken?: string
Acknowledges a job as successfully processed.
-
advanceRecurring(): Promise<void>id: string,nextRunAtMs: number
Advances a recurring job's next run time.
-
connect(): Promise<void>
Connects the adapter to its backend.
-
deadLetter(): Promise<void>name: string,id: string,nowMs: number,_claimToken?: string
Moves a job to the dead letter queue.
-
depths: (name: string) => Promise<QueueDepths>
M70k (X8-4): counts this name's three states with one
ZCARDeach. -
disconnect(): Promise<void>
Disconnects the adapter.
-
enqueue<T>(job: StoredJob<T>): Promise<void>
Enqueues a job.
-
fetchRecurringDue(nowMs: number): Promise<readonly StoredRecurring[]>
Fetches recurring jobs that are due.
-
isHealthy: () => Promise<boolean>
M70c: present only when the client exposes
ping(); its absence is unknown reachability, notfalse(a minimal injected fake has not told us the server is dead). -
isReady(): boolean
Checks if the adapter is ready/connected.
-
requeue<T>(): Promise<void>name: string,id: string,availableAtMs: number,attempts: number,_claimToken?: string
Requeues a job with a new available timestamp.
-
reserve<T>(): Promise<readonly StoredJob<T>[]>name: string,limit: number,nowMs: number
Reserves up to
limitjobs that are due (availableAtMs <= nowMs). -
storeRecurring(rec: StoredRecurring): Promise<void>
Stores a recurring job.
SNS publisher for fan-out messaging.
- connect(): Promise<void>
- disconnect(): Promise<void>
- isReady(): boolean
-
publish(message: unknown): Promise<string | undefined>
Publish a message to the configured SNS topic.
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.
SQS queue adapter.
-
ack(): Promise<void>name: string,id: string,claimToken: string
Acknowledges a job as successfully processed.
-
advanceRecurring(): Promise<void>id: string,nextRunAtMs: number
Advances a recurring job's next run time.
-
connect(): Promise<void>
Connects the adapter to its backend.
-
deadLetter(): Promise<void>name: string,id: string,_nowMs: number,claimToken: string
Moves a job to the dead letter queue.
-
disconnect(): Promise<void>
Disconnects the adapter.
-
enqueue<T>(job: StoredJob<T>): Promise<void>
Enqueues a job.
-
fetchRecurringDue(nowMs: number): Promise<readonly StoredRecurring[]>
Fetches recurring jobs that are due.
-
isHealthy: () => Promise<boolean>
M70c: present only when the transport exposes
isHealthy?()(the real adapter issuesGetQueueAttributes); its absence is unknown reachability, notfalse. -
isReady(): boolean
Checks if the adapter is ready/connected.
-
requeue(): Promise<void>name: string,id: string,availableAtMs: number,_attempts: number,claimToken: string
Requeues a job with a new available timestamp.
-
reserve<T>(): Promise<readonly StoredJob<T>[]>name: string,limit: number,nowMs: number
Reserves up to
limitjobs that are due (availableAtMs <= nowMs). -
storeRecurring(rec: StoredRecurring): Promise<void>
Stores a recurring job.
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.
Adapts the real AWS SNS SDK v3 module to the domain port.
Adapts the real AWS SQS SDK v3 module to the domain port.
Lazy-load the AWS SNS SDK v3.
Lazy-load the AWS SQS SDK v3.
Creates a queue plugin.
Options accepted when enqueueing a job.
-
delayMs: number
Delay before the job becomes available, in milliseconds.
-
headers: Readonly<Record<string, string>>
Transport headers to carry with the job, delivered to the processor as
IJob.headers. -
maxAttempts: number
Maximum attempts before the job is dead-lettered.
A queued job delivered to a processor.
-
attempts: number
How many times this job has been attempted (1 on first delivery).
-
data: T
The job payload.
-
headers: Readonly<Record<string, string>>
Transport headers carried with the job, mirroring
MessageMetadata.headersso the two ingresses cannot drift on meaning:{}means the channel was read and carried nothing; absent means there was no channel. -
id: string
Queue-assigned job ID.
-
name: string
The job name it was enqueued under.
Background job queue.
-
add<T>(): Promise<string>name: string,data: T,options?: AddJobOptions
Enqueues a job.
-
addRecurring<T>(): Promise<void>name: string,data: T,options: RecurringOptions
Schedules a recurring job.
-
process<T>(): voidname: string,processor: JobProcessor<T>,options?: ProcessOptions
Registers a processor for a job name.
Domain port for SNS operations.
-
close(): Promise<void>
Close the client.
-
publish(): Promise<string | undefined>topicArn: string,body: string
Publish a message to a topic. Returns the message ID or undefined.
Domain port for SQS operations. The adapter depends on this, not the SDK.
-
changeVisibility(): Promise<void>queueUrl: string,receiptHandle: string,seconds: number
Change visibility timeout (requeue).
-
close(): Promise<void>
Close the client.
-
delete(): Promise<void>queueUrl: string,receiptHandle: string
Delete a message (ack).
-
isHealthy(): Promise<boolean>
M70c: reports whether the queue is reachable — the real adapter issues
GetQueueAttributes. Optional so a minimal injected fake still type-checks; a transport that omits it is unknown, notfalse. -
receive(): Promise<readonly SqsReceivedMessage[]>queueUrl: string,max: number,visibilitySeconds: number
Receive messages from a queue.
-
send(): Promise<void>queueUrl: string,body: string,delaySeconds?: number
Send a message to a queue.
Options accepted when registering a processor.
-
concurrency: number
Jobs processed concurrently by this worker (default 1).
-
onFailed: () => void | Promise<void>job: IJob,error: unknown
Invoked once when a job has exhausted its attempts, immediately before it is dead-lettered — the only programmatic notice that work was permanently abandoned. It does NOT fire on an attempt that will be retried.
How many jobs are in each of one name's states.
-
dead: number
Jobs that exhausted their attempts and were dead-lettered.
-
processing: number
Jobs reserved and being processed.
-
ready: number
Jobs available to be reserved now or later.
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.
-
error(): voidmessage: string,metadata?: Record<string, unknown>
Logs at
errorseverity.
Options for configuring the queue plugin.
-
adapter: QueueAdapterType
The adapter type to use (default 'memory').
-
behaviors: readonly (IIngressBehavior | RegistryFactory<IIngressBehavior>)[]
Ingress behaviours wrapped around every processor — the queue arm of the transport-neutral behaviour chain shared with the websocket, scheduler, and messaging plugins (
IIngressBehaviorin@setu-ts/common). -
client: IRedisQueueClient | IAmqpQueueConnection
Injected client (bypasses lazy import).
-
deadLetterTtlMs: number
How long a dead-lettered job's payload is retained, in milliseconds.
-
defaultMaxAttempts: number
Default max attempts for jobs (default 3).
-
name: string
Instance name for multi-instance support.
-
pollIntervalMs: number
Poll interval for worker loop (default 1000ms).
-
prefix: string
Queue name prefix for RabbitMQ adapter (default 'he.queue').
-
processors: readonly QueueProcessorEntry[]
Processors registered declaratively, as an alternative to calling
queue.process(name, processor, options)imperatively afterstart(). Each entry — instance orRegistryFactory— produces oneprocess()call, so a processor can be declared where the plugin is composed instead of after the application has started. -
sqs: import("../adapters/sqs-queue.ts").SqsQueueOptions
SQS-specific options (required when adapter is 'sqs').
-
url: string
Connection URL (used when adapter is 'redis' or 'rabbitmq').
The declarative form of one IQueue.process() call — the entry an
application writes instead of calling process() imperatively after
start().
-
name: string
The job name this processor handles (the
process()name argument). -
options: ProcessOptions
Per-name configuration, exactly as the imperative
process()accepts. -
processor: JobProcessor
Invoked per delivered job, exactly as the imperative
process()accepts.
Options for configuring RabbitMqQueue.
-
client: IAmqpQueueConnection
Injected AMQP connection (bypasses lazy import).
-
prefix: string
Queue name prefix (default 'he.queue').
-
url: string
RabbitMQ connection URL (default 'amqp://localhost:5672').
Options accepted when scheduling a recurring job.
-
cron: string
Cron expression controlling the schedule.
Options for configuring RedisQueue.
-
client: IRedisQueueClient
Injected Redis client (bypasses lazy import).
-
deadLetterTtlMs: number
How long a dead-lettered job's payload is retained, in milliseconds; see QueuePluginOptions.deadLetterTtlMs.
-
url: string
Redis connection URL (default 'redis://localhost:6379').
Options for SNS publisher.
-
client: ISnsTransport
Injected transport (bypasses lazy SDK load).
-
credentials: unknown
AWS credentials (for lazy SDK load).
-
endpoint: string
Custom endpoint URL (for local testing).
-
region: string
AWS region (for lazy SDK load).
-
topicArn: string
Target SNS topic ARN.
Declares the constructors used from the real AWS SNS SDK v3.
Options for SQS queue adapter.
-
client: ISqsTransport
Injected transport (bypasses lazy SDK load).
-
credentials: unknown
AWS credentials (for lazy SDK load).
-
deadLetterQueues: Record<string, string>
Job name → dead-letter queue URL mapping (optional).
-
endpoint: string
Custom endpoint URL (for ElasticMQ / local testing).
-
queues: Record<string, string>
Job name → queue URL mapping.
-
region: string
AWS region (for lazy SDK load).
-
visibilityTimeoutSeconds: number
Visibility timeout in seconds for claims (default 30).
A message received from SQS with its receipt handle.
-
approximateReceiveCount: string | undefined
Approximate receive count (system attribute). May be undefined if the attribute is not requested.
-
body: string
The message body (JSON string).
-
receiptHandle: string
Receipt handle for settle operations.
Declares the constructors used from the real AWS SQS SDK v3.
- ChangeMessageVisibilityCommand: new (input: Record<string, unknown>) => unknown
- DeleteMessageCommand: new (input: Record<string, unknown>) => unknown
- ReceiveMessageCommand: new (input: Record<string, unknown>) => unknown
- SQSClient: new (config: { region?: string | undefined; credentials?: unknown; endpoint?: string | undefined; }) => { send(command: unknown): Promise<unknown>; destroy(): Promise<void>; }
- SendMessageCommand: new (input: Record<string, unknown>) => unknown
Processes jobs of one name.
Queue adapter type for plugin configuration.
| RegistryFactory<QueueProcessorDefinition>
One entry of QueuePluginOptions.processors: a processor
definition, or a RegistryFactory producing one when the
processor needs a resolved capability.
Example 1
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 });
Implements ISsrService.
-
render(ctx: IRequestContext): Promise<HandlerResult>
Renders an SSR document for the given request context.
Pure function that assembles an RR request handler from a pre-loaded build
and the createRequestHandler factory.
Validates that an injected loadRequestHandler resolved to a usable
SsrRuntime, and narrows it.
Bridges a kernel IRequestContext into a web Request, invokes the RR
handler, and maps the resulting web Response back onto ctx.response.
Returns the context key for a name, creating it on first use.
Builds the per-request context factory from React Router's
RouterContextProvider class.
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.
Creates a static-asset RouteHandler that serves files from a directory
using the injected IFileSystem.
Default implementation of loadRequestHandler.
Creates the ReactRouterPlugin.
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.
-
__handlerResult: true
Brand preventing accidental structural matches.
Runtime-agnostic file system operations. Absent on runtimes without file system access (edge platforms).
-
mkdir(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Creates a directory.
-
readFile(path: string): Promise<Uint8Array>
Reads a file.
-
readStream(): Promise<ReadableStream<Uint8Array>>path: string,options?: { readonly start?: number; readonly end?: number; }
Reads a file as a stream, optionally with byte range.
-
readdir(path: string): Promise<readonly string[]>
Lists directory entries.
-
realPath(path: string): Promise<string>
Resolves a path to its canonical absolute form, following symlinks.
-
rm(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Removes a file or directory.
-
stat(path: string): Promise<StatResult>
Returns file metadata.
-
writeFile(): Promise<void>path: string,data: Uint8Array
Writes a file, creating it if absent.
Per-request context passed to middleware and route handlers. Each request gets a fresh context; request-scoped data lives here, never in globals.
-
id: string
Unique request ID (generated or propagated by middleware).
-
params: Readonly<Record<string, string>>
Path parameters extracted by the router (e.g.
:id). -
query: Readonly<Record<string, string>>
Query string parameters.
-
raw: Request
The undisturbed web-standard
Request, preserved for WebSocket upgrade and gRPC dispatch after the middleware pipeline. -
request: IRequest
The incoming request.
-
response: IResponse
The response builder.
-
services: IServiceRegistry
Service resolution (application-scoped plus request-scoped services).
-
signal: AbortSignal
An abort signal that fires when the underlying HTTP connection is severed (client disconnect, timeout). Populated by the kernel's request-context factory from the native
Request.signal; falls back to a non-aborting sentinel so handlers always have a live signal to listen on. -
startTime: number
High-resolution timestamp captured when the context was created.
-
state: Map<string, unknown>
Request-scoped state for passing data between middleware and handlers.
Service contract for server-side rendering (SSR).
-
render(ctx: IRequestContext): Promise<HandlerResult>
Renders an SSR document for the given request context.
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'sreact-router.config.tsbasenamefor flat/nested routes to resolve. -
loadRequestHandler: () => Promise<SsrRuntime>serverBuildPath: string,mode: string
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
servicesContextanduserContextkeys the plugin always sets. -
publicFiles: boolean
Also serves files from the client-build ROOT — where Vite copies
public/(robots.txt,favicon.ico, …) — in addition toReactRouterPluginOptions.assetUrlPrefix, withCache-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).
A React Router context key, used by identity as the argument to
RouterLoadContext.get / RouterLoadContext.set.
-
defaultValue: T
Value returned by
get()when the key has not been set.
The per-request context object React Router passes to loaders, actions, and
middleware as context.
-
get<T>(key: RouterContextKey<T>): T
Reads a key, falling back to the key's
defaultValue. -
set<T>(): voidkey: RouterContextKey<T>,value: T
Writes a key, overwriting any previous value.
Everything the plugin needs from a loaded React Router module: the request
handler, plus a factory for the RouterContextProvider that handler will
accept.
-
createLoadContext: () => RouterLoadContext
Constructs a fresh, empty per-request context provider.
-
handler: SsrRequestHandler
The callable returned by
createRequestHandler(build, mode).
Hook for adding application values to the per-request React Router context.
A route handler: receives the request context and returns a response via the context's response builder.
React Router request handler — the callable returned by
createRequestHandler(build, mode).
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
Key holding the kernel IServiceRegistry for the current request.
Key holding the authenticated principal, or null on an anonymous request.
Example 1
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(), ], });
A real single-process backplane.
-
close(): Promise<void>
Closes the underlying transport and drops every handler.
-
connect(): Promise<void>
Opens the underlying transport. Idempotent.
-
handlerErrors(): readonly Error[]
Errors thrown by subscribers during delivery, oldest first.
-
isHealthy(): Promise<boolean>
M70c: a real single-process bus has no backend to be unreachable, so it is always reachable. There is no external dependency whose outage could make this transport
down(M47). -
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed instance.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other instances.
Carries frames over whatever broker is registered under
CAPABILITIES.MESSAGING.
-
close(): Promise<void>
Closes the underlying transport and drops every handler.
-
connect(): Promise<void>
Opens the underlying transport. Idempotent.
-
handlerErrors(): readonly Error[]
Errors thrown by subscribers during delivery, oldest first.
-
isHealthy: () => Promise<boolean>
M70c: delegates to the resolved broker's
isHealthy?()— the only way the backplane can report the broker's reachability without importing the messaging plugin (§3.1). Assigned only when the broker provides the member: a broker that omits it is unknown, and the indicator reads absence ofisHealthy(notfalse) as that. -
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed instance.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other instances.
Carries frames over Redis pub/sub.
-
close(): Promise<void>
Closes the underlying transport and drops every handler.
-
connect(): Promise<void>
Builds the client pair when needed, then subscribes.
-
handlerErrors(): readonly Error[]
Errors thrown by subscribers during delivery, oldest first.
-
isHealthy: () => Promise<boolean>
M70c: present only when both connections expose
statusandping; the indicator reads absence as unknown (a minimal fake that lacks the surface has not told us the backend is dead). A subscriber-mode connection refuses every command but (un)subscribe, so the pair is probed separately (M47's two-connection requirement). -
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed instance.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other instances.
Thrown when ioredis cannot be loaded or does not look like itself.
Narrows an ioredis module to the constructor facade this package uses.
Creates the transport named by options.transport.
Decodes a payload received from the wire back into its local form.
Encodes a WebSocket payload for the wire.
Narrows an arriving broker payload to a RealtimeFrame.
Lazily imports ioredis.
Creates the RealtimeBackplanePlugin.
Options shared by every transport arm.
-
localNotice: boolean
M70n X3-4: when the resolved transport is
'memory', the plugin logs a process-local notice atregister()— frames fan out only within this process, which looks like partial delivery behind more than one replica. Defaulttrue;falsesuppresses the notice, matching the existingscalingNoticeopt-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.
Options for the 'custom' arm — a caller-supplied transport.
-
instance: IRealtimeBackplane
The transport to register, used as-is.
-
transport: "custom"
Transport discriminant.
A payload as it travels the backplane.
-
binary: boolean
True when
EncodedPayload.datais base64-encoded binary. -
data: string
The payload as a string.
A publish/subscribe transport carrying RealtimeFrames between
application instances.
-
close(): Promise<void>
Closes the underlying transport and drops every handler.
-
connect(): Promise<void>
Opens the underlying transport. Idempotent.
-
isHealthy(): Promise<boolean>
Reports whether the transport's backend is reachable right now, for the plugin's health indicator.
-
origin: string
This instance's identity, stamped onto every frame it publishes.
-
publish(frame: RealtimeFrame): Promise<void>
Publishes a frame to every other subscribed instance.
-
subscribe(handler: RealtimeFrameHandler): Promise<() => void>
Registers a handler for frames arriving from other instances.
The ioredis-shaped client surface the Redis transport uses.
-
off(): voidevent: string,listener: () => voidchannel: string,message: string
Removes a previously registered listener.
-
on(): voidevent: string,listener: () => voidchannel: string,message: string
Registers an event listener. The transport listens for
'message'. -
ping(): Promise<unknown>
M70c: resolves when this connection is alive. Optional so a minimal injected fake still type-checks; the real
ioredisclient exposes it. -
publish(): Promise<number>channel: string,message: string
Publishes a message to a channel.
-
quit(): Promise<unknown>
Closes the connection.
-
status: string
M70c: the
ioredisconnection state ('ready'when usable). Optional for the same reason asping. -
subscribe(channel: string): Promise<unknown>
Subscribes to a channel.
-
unsubscribe(channel: string): Promise<unknown>
Unsubscribes from a channel.
A module exposing an ioredis-compatible constructor.
-
create(url: string): IRedisBackplaneClient
Constructs a client.
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.
Options for the 'messaging' arm, which carries frames over whatever broker
is registered under CAPABILITIES.MESSAGING.
-
transport: "messaging"
Transport discriminant.
One broadcast crossing the backplane.
-
binary: boolean
True when
RealtimeFrame.datais base64-encoded binary. -
data: string
The payload, always a string.
-
exceptId: string
The connection excluded from this broadcast, by ID.
-
kind: RealtimeFrameKind
Which consumer the frame belongs to.
-
name: string
The room or channel name the frame addresses.
-
origin: string
The publishing instance's identity.
Options for the 'redis' arm — Redis pub/sub.
-
client: IRedisBackplaneClient
The publishing client. Must be supplied together with
RedisBackplaneOptions.subscriber: a Redis connection in subscriber mode refuses every other command, so one connection cannot do both jobs. -
module: IRedisModule
A module exposing an
ioredis-compatible constructor, for testing. -
subscriber: IRedisBackplaneClient
The dedicated subscriber client.
-
transport: "redis"
Transport discriminant.
-
url: string
Connection URL used to build both clients on the lazy
npm:ioredispath. Read only when no clients are injected.
| MessagingBackplaneOptions
| RedisBackplaneOptions
| CustomBackplaneOptions
Options for RealtimeBackplanePlugin, discriminated on
transport.
Receives frames published by other instances.
Which kind of broadcast group a RealtimeFrame addresses.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
The default topic when none is configured.
Example 1
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 });
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.
Thrown when a circuit breaker is open and fails fast without invoking the protected call.
Thrown when a protected call exceeds its per-attempt timeout deadline.
Creates a resilience plugin.
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.
-
defaultBulkhead: BulkheadPolicy
Default bulkhead policy used when a
wrapsetsbulkhead: true. -
defaultCircuitBreaker: CircuitBreakerPolicy
Default circuit-breaker policy used when a
wrapsetscircuitBreaker: true. -
defaultRetry: RetryPolicy
Default retry policy used when a
wrapsetsretry: true.
Bun HTTP adapter implementation.
-
close(handle: ServerHandle): Promise<void>
Stops the server gracefully.
-
fetch(request: Request): Response | Promise<Response>
The universal web-standard entry point. Accepts a web
Requestand returns a webResponse. May be called withoutlisten(e.g. Cloudflare Workers whereexport default { fetch: app.fetch }is the deploy path). -
listen(): Promise<ServerHandle>port: number,hostname?: string
Binds the adapter's
fetchto a real TCP socket. -
setHandler(handler: (request: IRequest) => IResponse | Promise<IResponse>): void
Installs the framework request handler. Called once at
start()time, after the middleware pipeline compiles and before anyfetchorlisten. -
setRpcHandler(handler: RpcFetchHandler): void
Installs a gRPC/Connect fetch handler.
-
setUpgradeRouter(router: WebSocketUpgradeRouter): void
Installs a WebSocket upgrade router. The adapter stores the router but does not consult it: since M70a the kernel's terminal handler resolves
IWebSocketServiceand callsrouteUpgradeitself, after the middleware pipeline has run without short-circuiting and before route matching — so an application catch-all cannot shadow an upgrade. What the adapter needs from this setter is the bare fact that a router was installed: Node attaches its rawupgradelistener only then.
Cloudflare Workers HTTP adapter implementation.
-
close(_handle: ServerHandle): Promise<void>
Stops the server gracefully.
-
fetch(request: Request): Response | Promise<Response>
The universal web-standard entry point. Accepts a web
Requestand returns a webResponse. May be called withoutlisten(e.g. Cloudflare Workers whereexport default { fetch: app.fetch }is the deploy path). -
listen(): Promise<ServerHandle>_port: number,_hostname?: string
Binds the adapter's
fetchto a real TCP socket. -
setHandler(handler: (request: IRequest) => IResponse | Promise<IResponse>): void
Installs the framework request handler. Called once at
start()time, after the middleware pipeline compiles and before anyfetchorlisten. -
setRpcHandler(handler: RpcFetchHandler): void
Installs a gRPC/Connect fetch handler.
-
setUpgradeRouter(router: WebSocketUpgradeRouter): void
Installs a WebSocket upgrade router. The adapter stores the router but does not consult it: since M70a the kernel's terminal handler resolves
IWebSocketServiceand callsrouteUpgradeitself, after the middleware pipeline has run without short-circuiting and before route matching — so an application catch-all cannot shadow an upgrade. What the adapter needs from this setter is the bare fact that a router was installed: Node attaches its rawupgradelistener only then.
Deno HTTP adapter implementation.
-
close(handle: ServerHandle): Promise<void>
Stops the server gracefully.
-
fetch(request: Request): Response | Promise<Response>
The universal web-standard entry point. Accepts a web
Requestand returns a webResponse. May be called withoutlisten(e.g. Cloudflare Workers whereexport default { fetch: app.fetch }is the deploy path). -
listen(): Promise<ServerHandle>port: number,hostname?: string
Binds the adapter's
fetchto a real TCP socket. -
setHandler(handler: (request: IRequest) => IResponse | Promise<IResponse>): void
Installs the framework request handler. Called once at
start()time, after the middleware pipeline compiles and before anyfetchorlisten. -
setRpcHandler(handler: RpcFetchHandler): void
Installs a gRPC/Connect fetch handler.
-
setUpgradeRouter(router: WebSocketUpgradeRouter): void
Installs a WebSocket upgrade router. The adapter stores the router but does not consult it: since M70a the kernel's terminal handler resolves
IWebSocketServiceand callsrouteUpgradeitself, after the middleware pipeline has run without short-circuiting and before route matching — so an application catch-all cannot shadow an upgrade. What the adapter needs from this setter is the bare fact that a router was installed: Node attaches its rawupgradelistener only then.
Node HTTP adapter implementation.
-
close(handle: ServerHandle): Promise<void>
Stops the server gracefully.
-
fetch(request: Request): Response | Promise<Response>
The universal web-standard entry point. Accepts a web
Requestand returns a webResponse. May be called withoutlisten(e.g. Cloudflare Workers whereexport default { fetch: app.fetch }is the deploy path). -
listen(): Promise<ServerHandle>port: number,hostname?: string
Binds the adapter's
fetchto a real TCP socket. -
setHandler(handler: (request: IRequest) => IResponse | Promise<IResponse>): void
Installs the framework request handler. Called once at
start()time, after the middleware pipeline compiles and before anyfetchorlisten. -
setRpcHandler(handler: RpcFetchHandler): void
Installs a gRPC/Connect fetch handler.
-
setUpgradeRouter(router: WebSocketUpgradeRouter): void
Installs a WebSocket upgrade router. The adapter stores the router but does not consult it: since M70a the kernel's terminal handler resolves
IWebSocketServiceand callsrouteUpgradeitself, after the middleware pipeline has run without short-circuiting and before route matching — so an application catch-all cannot shadow an upgrade. What the adapter needs from this setter is the bare fact that a router was installed: Node attaches its rawupgradelistener only then.
Owns the ws server for one Node HTTP adapter and performs the handshake.
-
close(): void
Shuts down the
wsserver, when one was ever created. -
handshake(): Promise<void>incoming: NodeIncomingMessage,socket: unknown,head: unknown,sink: WebSocketEventSink,protocol?: string
Completes the RFC 6455 handshake over an already-accepted TCP connection and binds the resulting socket to the decision's sink.
-
hasServer(): boolean
Whether a
wsserver has been created yet.
Raised when a request body exceeds the configured
RuntimeOptions.maxBodyBytes cap.
-
maxBodyBytes: number
The configured cap, in bytes.
Stores an adapter's RPC interceptor and consults it safely.
-
consult(request: Request): Promise<Response | null>
Calls the installed handler. Returns the handler's response if it returns a
Response, otherwise returnsnull. -
set(handler: RpcFetchHandler): void
Installs the handler. A later call replaces the previous one.
Narrows an already-imported module to WsModuleLike.
Probes a server handle for the raw upgrade event.
Binds a Workers server socket's events to a sink.
Binds a Deno socket's event handlers to a sink.
Binds a ws socket's events to a sink.
Builds the default BunHost from node: built-ins, which Bun
implements.
Builds the default NodeHost from node: built-ins, which Deno
and Bun also implement.
Creates IRuntimeServices backed by Bun APIs.
Builds the serve-time handler object that routes every Bun socket event to
the sink stored on that socket's data.
Creates IRuntimeServices for Cloudflare Workers.
Builds the default host from the real Workers globals.
Creates an IDnsResolver backed by Deno.resolveDns.
Creates IRuntimeServices backed by Deno APIs.
Creates an IDnsResolver backed by node:dns/promises.
Creates IRuntimeServices backed by Node.js APIs.
Creates an IWorkerHost backed by node:worker_threads.
Creates runtime services for the current platform.
Reconstructs a web-standard Request from Node's upgrade event arguments,
so the upgrade router sees the same shape on every runtime.
Wraps a web-API socket as an IWebSocketTransport.
Creates an IWorkerHost backed by the web-standard Worker API
(Deno and Bun).
Wraps a ws socket as an IWebSocketTransport.
Detects the current runtime platform.
Reports whether a set of request headers describes an RFC 6455 WebSocket upgrade.
Lazily imports ws and narrows it.
Normalizes an inbound frame payload to the framework's string | Uint8Array.
Refuses an upgrade on the raw socket, since there is no Response object to
return on Node's upgrade path.
Creates the RuntimePlugin that provides runtime-agnostic services and HTTP adapter.
Maps the web WebSocket API's numeric readyState to the framework's named
WebSocketReadyState.
Coerces an error-event payload into a real Error.
Maps a ws numeric ready state to the framework's named state.
File info returned by BunHost.stat().
Minimal interface covering the Bun-specific operations used by this adapter. Inject this interface to test the adapter without real Bun.
-
createReadStream: () => NodeJS.ReadableStream | nullpath: string,options?: { start?: number; end?: number; }
Create a read stream for a file. Returns null if the file cannot be opened.
-
env: { [key: string]: string | undefined; }
Environment variable map.
-
exit: (code?: number) => never
Exit the process.
-
hostname: string
Returns the host name.
-
mkdir: () => booleanpath: string,options?: { recursive?: boolean; }
Create a directory.
-
onSignal: () => voidsignal: RuntimeSignal,handler: () => void
Registers a process-termination signal listener.
-
readFile: (path: string) => Uint8Array | null
Read file as bytes.
-
readdir: (path: string) => readonly string[] | null
List directory entries.
-
realPath: (path: string) => string | null
Resolve a path to its canonical absolute form (null when it cannot be resolved).
-
rm: () => booleanpath: string,options?: { recursive?: boolean; }
Remove a file or directory.
-
stat: (path: string) => BunFileInfo | null
Get file/directory info.
-
version: string
Bun version string.
-
writeFile: () => voidpath: string,data: Uint8Array
Write bytes to a file.
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.
-
bunGlobal: { version?: string; } | undefined
The
Bunglobal when running on Bun,undefinedelsewhere — read only for its version string. Required (rather than optional) so callers and tests state it explicitly and every version-resolution arm stays reachable. -
fs: { createReadStream?: () => NodeJS.ReadableStream | null; readFileSync(path: string): Uint8Array; realpathSync(path: string): string; writeFileSync(path: string,options?: { start?: number; end?: number; }): void; statSync(path: string): { size: number; mtime: Date; isFile(): boolean; isDirectory(): boolean; }; readdirSync(path: string): string[]; mkdirSync(path: string,data: Uint8Array): string | undefined; rmSync(path: string,options?: { recursive?: boolean; }): void; }path: string,options?: { recursive?: boolean; }
Synchronous file-system operations (compatible with
node:fs). -
hostname: () => string
Hostname function (from
node:os). -
proc: { version: string; versions: Record<string, string | undefined>; env: Record<string, string | undefined>; exit: (code?: number) => never; on: () => void; }event: RuntimeSignal,listener: () => void
Process object (version, env, exit, signal listening).
Minimal interface covering the Bun-specific HTTP operations used by this adapter. Inject this interface to test the adapter without real Bun.
Bun server handle (from Bun.serve).
-
stop(): void
Stops the server gracefully.
-
upgrade(): booleanrequest: Request,options: { data: BunSocketData; headers?: Headers; }
Upgrades an inbound request to a WebSocket.
A Bun ServerWebSocket, narrowed to what this adapter drives.
-
data: BunSocketData
The data bag supplied to
server.upgrade().
The per-socket data Bun carries from server.upgrade() through to every
socket handler.
-
sink: WebSocketEventSink
The sink this socket's events are routed to.
The serve-time socket handler object Bun expects under Bun.serve's
websocket option.
-
close(): voidws: BunServerWebSocket,code: number,reason: string
Called once on close.
-
error(): voidws: BunServerWebSocket,error: unknown
Called on transport error.
-
message(): voidws: BunServerWebSocket,message: string | Uint8Array
Called per inbound frame.
-
open(ws: BunServerWebSocket): void
Called once the socket is live.
Injectable environment seam for Cloudflare Workers bindings. Defaults to an empty record so the adapter is testable without Workers globals.
Options for createCloudflareRuntimeServices.
-
env: CloudflareEnv
Injectable env source for reading Workers bindings. Defaults to an empty record.
The server half of a Workers WebSocketPair. Workers sockets are driven with
addEventListener after an explicit accept(), not with on* properties.
-
accept(): void
Puts the server socket into the accepted state so it can send and receive.
-
addEventListener(): voidtype: string,listener: (event: never) => void
Subscribes to a socket event.
Injectable seam covering the two Workers-only globals this upgrader needs.
-
createPair(): CloudflareWebSocketPair
Creates a linked client/server socket pair.
-
createUpgradeResponse(): Responseclient: unknown,protocol?: string
Builds the 101 response that hands the client half back to the peer.
A created WebSocketPair: the client half travels back in the 101 response,
the server half stays here.
-
client: unknown
The half handed to the client in the response.
-
server: CloudflareServerSocket
The half the server keeps.
Options for createRuntimeServices.
-
adapters: RuntimeAdapterFactories
Replace the built-in platform → factory map.
-
env: Readonly<Record<string, unknown>>
The Cloudflare Workers
envrecord, which is the only way bindings and variables reach a Worker — there is no ambientprocess.envon the edge. -
platform: RuntimePlatform
Build services for this platform instead of auto-detecting.
The Deno.resolveDns surface this resolver needs.
-
resolveDns(): Promise<DenoSrvRecord[]>query: string,recordType: "SRV"
Resolves SRV records.
File info returned by DenoHost.stat().
Minimal interface covering the Deno-specific operations used by this adapter. Inject this interface to test the adapter without real Deno.
-
addSignalListener(): voidsignal: RuntimeSignal,handler: () => void
Registers a signal listener.
-
build: { os: string; }
Build metadata. Read for
osalone, to decide whether signal listening is available — seecreateDenoRuntimeServices. -
env: { toObject(): Record<string, string>; }
Environment variable map.
-
exit(code?: number): never
Exit the process.
-
hostname(): string
Returns the host name.
-
mkdir(): Promise<void>path: string,options?: { recursive?: boolean; }
Create a directory.
-
open(path: string): Promise<Deno.FsFile>
Open a file for reading.
-
readDir(path: string): AsyncIterable<DenoDirEntry>
Lists directory entries. Named and shaped after the real API this host defaults to:
Deno.readDir(capitalD) returns an async iterable, so it must be consumed withfor await. -
readFile(path: string): Promise<Uint8Array>
Read file as bytes.
-
realPath(path: string): Promise<string>
Resolve a path to its canonical absolute form, following symlinks.
-
remove(): Promise<void>path: string,options?: { recursive?: boolean; }
Remove a file or directory.
-
resolveDns(): Promise<DenoSrvRecord[]>query: string,recordType: "SRV"
Resolves SRV records.
-
stat(path: string): Promise<DenoFileInfo>
Get file/directory info.
-
version: { deno: string; }
Current runtime version string.
-
writeFile(): Promise<void>path: string,data: Uint8Array
Write bytes to a file.
Minimal interface covering the Deno operations this adapter needs. Inject this interface to test the adapter without real Deno.
-
serve(options: { port: number; hostname?: string; fetch: (request: Request) => Response | Promise<Response>; }): DenoServer
Starts an HTTP server.
-
upgradeWebSocket(): DenoWebSocketUpgraderequest: Request,options?: { protocol?: string; }
Performs an RFC 6455 handshake on an inbound request.
Deno HTTP server handle (from Deno.serve).
-
shutdown(): Promise<void>
Shuts down the server.
One SRV record as Deno.resolveDns returns it.
-
port: number
TCP port.
-
priority: number
RFC 2782 priority.
-
target: string
Target hostname.
-
weight: number
RFC 2782 weight.
A web-API socket that exposes the on* handler properties, as Deno's
upgradeWebSocket socket does.
-
onclose: ((event: { code: number; reason: string; }) => void) | null
Fires once on close.
-
onerror: ((event: unknown) => void) | null
Fires on transport error.
-
onmessage: ((event: { data: unknown; }) => void) | null
Fires per inbound frame.
-
onopen: ((event: unknown) => void) | null
Fires once the socket is writable.
The result shape of Deno.upgradeWebSocket.
-
response: Response
The 101 response that must be returned from the fetch handler.
-
socket: DenoWebSocketLike
The server-side socket.
Minimal global scope shape needed for detection.
Allows injecting a fake global for testing without as casts in test code.
Map of platform → HTTP adapter factory. Used internally for dependency injection.
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.
The node:dns/promises surface this resolver needs, injectable so every
branch is unit-testable without real DNS or network permission.
-
resolve4(hostname: string): Promise<string[]>
Resolves IPv4 addresses.
-
resolve6(hostname: string): Promise<string[]>
Resolves IPv6 addresses.
-
resolveSrv(hostname: string): Promise<>{ name: string; port: number; priority: number; weight: number; }[]
Resolves SRV records.
File info returned by NodeHost.stat().
Minimal interface covering the Node-specific operations used by this adapter. Inject this interface to test the adapter without real Node.js.
-
createReadStream: () => NodeJS.ReadableStream | nullpath: string,options?: { start?: number; end?: number; }
Create a read stream for a file. Returns null if the file cannot be opened.
-
env: Record<string, string | undefined>
Environment variable map.
-
exit: (code?: number) => never
Exit the process.
-
hostname: string
Host name string.
-
mkdir: () => Promise<void>path: string,options?: { recursive?: boolean; }
Create a directory.
-
nodeVersion: string
Node.js version string (e.g. "v18.19.0").
-
onSignal: () => voidsignal: RuntimeSignal,handler: () => void
Registers a process-termination signal listener.
-
readFile: (path: string) => Promise<Uint8Array>
Read file as bytes.
-
readdir: (path: string) => Promise<readonly string[]>
List directory entries.
-
realPath: (path: string) => Promise<string>
Resolve a path to its canonical absolute form, following symlinks.
-
rm: () => Promise<void>path: string,options?: { recursive?: boolean; }
Remove a file or directory.
-
stat: (path: string) => Promise<NodeFsInfo>
Get file/directory info.
-
writeFile: () => Promise<void>path: string,data: Uint8Array
Write bytes to a file.
A Node IncomingMessage, narrowed to what building an upgrade Request
needs.
-
headers: Record<string, string | string[] | undefined>
Raw headers, as Node's lowercase-keyed object.
-
method: string | undefined
The HTTP method.
-
url: string | undefined
The request target (path plus query), as Node reports it.
-
fs: NodeFsOperations
File-system operations (compatible with
node:fs/promises). -
hostname: () => string
Hostname function (from
node:os). -
proc: { version: string; env: Record<string, string | undefined>; exit: (code?: number) => never; on: () => void; }event: RuntimeSignal,listener: () => void
Process object (version, env, exit, signal listening).
Minimal interface covering the @hono/node-server serve() operation.
Inject this interface to test the adapter without a real Node server.
Node.js HTTP server handle (returned by @hono/node-server serve()).
-
close(): void
Stops the server gracefully.
Minimal shape of a node:worker_threads Worker as used by this host.
-
on(): unknownevent: "message" | "error" | "exit",listener: (arg: unknown) => void
Registers an event listener (
'message'payloads arrive unwrapped;'exit'receives the numeric exit code). -
postMessage(value: unknown): void
Posts a structured-clonable message to the worker.
-
terminate(): Promise<number>
Terminates the worker; resolves with the exit code.
The Node built-ins this host needs. Inject fakes to test without real threads.
-
Worker: new (specifier: string | URL) => NodeWorkerLike
The
worker_threads.Workerconstructor. -
availableParallelism: () => number
os.availableParallelism.
The raw socket handed to a Node upgrade listener, narrowed to what a
refusal needs.
-
destroy(): void
Closes the socket.
-
write(data: string): void
Writes bytes to the socket.
Map of platform → runtime adapter factory.
-
bun: () => IRuntimeServices
Factory for Bun.
-
cloudflare-workers: () => IRuntimeServices
Factory for Cloudflare Workers.
-
deno: () => IRuntimeServices
Factory for Deno.
-
node: () => IRuntimeServices
Factory for Node.js.
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
envrecord. There is no ambient environment on the edge, so without thisruntime.envis empty on Workers andConfigPluginreads 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.
An event emitter that can report raw HTTP upgrades — the one capability this
adapter needs from the node:http server that serve() returns.
-
on(): unknownevent: "upgrade",listener: (...args: never[]) => void
Subscribes to the raw
upgradeevent.
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.
-
close(): voidcode?: number,reason?: string
Closes the socket.
-
readyState: number
Numeric ready state, per the web WebSocket API.
-
send(data: string | Uint8Array): void
Sends a text or binary frame.
The web globals this host needs. Inject fakes to test without spawning real workers.
-
Worker: new () => WebWorkerLikespecifier: string,options: { type: "module"; }
The
Workerconstructor; absent on runtimes without web workers. -
hardwareConcurrency: number
Reported hardware concurrency (
navigator.hardwareConcurrency).
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 omitonExitentirely.
Minimal shape of a web Worker instance as used by this host.
-
addEventListener(): voidtype: string,listener: (event: unknown) => void
Registers an event listener. Only used for the runtime-specific worker-ended event named by
WebWorkerHostOptions.exitEventName, which is not part of the webWorkerstandard and therefore has no handler slot. -
onerror: ((event: unknown) => void) | null
Error handler slot; events carry a
messagewhen available. -
onmessage: ((event: { data: unknown; }) => void) | null
Message handler slot; events carry the payload in
data. -
postMessage(message: unknown): void
Posts a structured-clonable message to the worker.
-
terminate(): void
Terminates the worker.
The shape of the ws module this adapter uses.
A ws WebSocketServer in noServer mode, narrowed to what this adapter
drives.
-
close(): void
Shuts the server down.
-
handleUpgrade(): voidrequest: unknown,socket: unknown,head: unknown,callback: (ws: WsSocketLike) => void
Completes the handshake over an already-accepted TCP connection.
A ws socket, narrowed to what this adapter drives. Declared structurally so
the package never takes a type dependency on @types/ws.
-
close(): voidcode?: number,reason?: string
Closes the socket.
-
on(): voidevent: string,listener: (...args: never[]) => void
Subscribes to a socket event.
-
readyState: number
Numeric ready state, matching the web WebSocket API's values.
-
send(data: string | Uint8Array): void
Sends a text or binary frame.
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.
Registers this module's task handler. Call once, at module top level, in a module that the WorkerPoolPlugin executes:
Creates a scheduler plugin.
Options for distributed locking.
-
client: IRedisLockClient
Injected ioredis-compatible client (preferred over lazy load).
-
enabled: boolean
Enable distributed locking. Default
false. -
lock: IDistributedLock
Custom lock implementation. Takes priority over
storagewhen present. -
storage: "redis"
Lock backend. Only
'redis'is supported whenenabled: true. -
ttlMs: number
Lock TTL in milliseconds. Must exceed the job's worst-case runtime.
-
url: string
Redis connection URL. Default
'redis://localhost:6379'.
Distributed lock interface.
-
acquire(): Promise<string | null>key: string,ttlMs: number
Attempt to acquire the lock.
-
release(): Promise<void>key: string,token: string
Release a previously acquired lock.
Minimal ioredis client shape required by RedisLock.
-
eval(): Promise<number | string | null>script: string,numkeys: number,...keysAndArgs: string[]
EVAL script numkeys keys... argv...
-
quit(): Promise<void>
Quit the connection
-
set(): Promise<string | null>key: string,value: string,option: string,px: "PX",ttl: number
SET key value [NX] [PX ttl] - PX is the milliseconds flag
In-process job scheduler.
-
cron<T = unknown>(): Promise<void>name: string,expression: string,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a recurring job using a 5-field cron expression (UTC).
-
delay<T = unknown>(): Promise<void>name: string,delayMs: number,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a one-shot delayed job.
-
every<T = unknown>(): Promise<void>name: string,intervalMs: number,handler: SchedulerJobHandler<T>,options?: ScheduleOptions<T>
Schedule a recurring job that fires every
intervalMsmilliseconds. -
getNextRun(name: string): Promise<number>
Return the next scheduled fire time as epoch milliseconds.
-
pause(name: string): Promise<void>
Pause a scheduled job without dropping its configuration.
-
remove(name: string): Promise<void>
Remove a scheduled job entirely.
-
resume(name: string): Promise<void>
Resume a paused job.
Retry configuration for a scheduled job.
-
backoff: SchedulerBackoff
Backoff strategy. Defaults to
'fixed'. -
delay: number
Base delay in milliseconds for the first retry.
-
limit: number
Maximum number of attempts before giving up (1-based minimum).
A scheduled job instance handed to the handler.
-
attempts: number
Current attempt number (1-based).
-
data: T
Payload data supplied by the caller.
-
id: string
Unique job identifier.
-
name: string
Human-readable job name.
Options passed when scheduling a job.
-
data: T
Payload data handed to the handler.
-
retry: RetryOptions
Retry configuration. When absent the job runs once.
Plugin options passed to SchedulerPlugin().
-
behaviors: readonly (IIngressBehavior | RegistryFactory<IIngressBehavior>)[]
Ingress behaviours wrapped around every job handler — the scheduler arm of the transport-neutral behaviour chain shared with the websocket, queue, and messaging plugins (
IIngressBehaviorin@setu-ts/common). -
distributedLock: DistributedLockOptions
Distributed lock configuration.
-
jobs: readonly SchedulerJobEntry[]
Jobs registered declaratively, as an alternative to calling
scheduler.cron()/every()/delay()imperatively afterstart(). Each entry — instance orRegistryFactory— produces one registration call, dispatched on itstrigger, so a job can be declared where the plugin is composed instead of after the application has started. -
timezone: string
Timezone for cron evaluation. Only
'UTC'is supported in this release.
Backoff strategy for retry delays.
| { readonly trigger: "every"; readonly name: string; readonly intervalMs: number; readonly handler: SchedulerJobHandler; readonly data?: unknown; readonly retry?: RetryOptions; }
| { readonly trigger: "delay"; readonly name: string; readonly delayMs: number; readonly handler: SchedulerJobHandler; readonly data?: unknown; readonly retry?: RetryOptions; }
The declarative form of one scheduler job registration — the entry an
application writes instead of calling cron()/every()/delay()
imperatively after start().
| RegistryFactory<SchedulerJobDefinition>
One entry of SchedulerPluginOptions.jobs: a job definition, or
a RegistryFactory producing one when the definition needs a
resolved capability.
Handler invoked when a scheduled job fires.
Thrown when the circuit breaker for the target origin is open.
Thrown by IHttpClient.request() when the server returns a non-2xx status.
Thrown by generateOpenApiClient() with path/method diagnostics when the
OpenAPI document is malformed or contains unsupported constructs.
Create a request interceptor that sets an API-key header.
Create a request interceptor that sets Authorization: Bearer <token>.
Create a configured HTTP client.
Factory returning the default IClientTiming backed by
performance.now() and setTimeout.
Creates and immediately connects a portable WebSocket realtime client.
Creates and starts a portable SSE client.
Generate TypeScript client source from an OpenAPI 3.1 document. Pure function with zero I/O and deterministic output.
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
timeoutwindow 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.
Options passed to createClient().
-
baseUrl: string
Required base URL for all requests.
-
circuitBreaker: CircuitBreakerPolicy
Circuit breaker policy.
threshold < 1throws at construction. -
fetch: () => Promise<Response>input: RequestInfo,init?: RequestInit
Injectable fetch seam. Defaults to global
fetch. -
headers: HeadersInit
Default headers cloned into each request.
-
rateLimit: ClientRateLimitPolicy
Rate-limit policy. Non-positive
maxRequestsorwindowMsthrows. -
requestInterceptors: ClientRequestInterceptor[]
Request interceptors executed once before resilient execution.
-
responseInterceptors: ClientResponseInterceptor<unknown>[]
Response interceptors executed after successful parsing.
-
retry: RetryPolicy
Retry policy.
limit < 1throws at construction. -
timing: IClientTiming
Timing abstraction. Defaults to
createDefaultClientTiming().
Per-origin sliding-window rate-limit configuration.
-
maxRequests: number
Maximum requests allowed within the window.
-
windowMs: number
Window size in milliseconds.
An outbound JSON request described by application or generated code.
-
headers: HeadersInit
Additional headers merged on top of the client defaults.
-
json: TBody
JSON body. When present,
Content-Type: application/jsonis set automatically. -
method: string
HTTP method.
-
path: string
Relative path resolved against the client
baseUrl. Must be relative. -
query: Record<>string,string
| number
| boolean
| (string | number | boolean)[]
| null
| undefinedQuery values. Primitives are encoded once; arrays repeat the key. Nullish values are omitted.
-
signal: AbortSignal
Abort signal that cancels fetches and queued waits.
Mutable context passed to a ClientRequestInterceptor so it can
inspect and modify the resolved URL and headers before the request executes.
-
headers: Headers
The mutable header map for the outbound request.
-
url: URL
The fully-resolved request URL.
A successful parsed response returned by IHttpClient.request.
-
data: T | undefined
Parsed JSON body.
undefinedfor 204 or empty responses. -
headers: Headers
Response headers.
-
status: number
HTTP status code (always 2xx).
Monotonic-time and sleep abstraction used by retry, breaker, and rate-limiter.
-
now(): number
Monotonic timestamp in milliseconds (like
performance.now()). -
sleep(): Promise<void>ms: number,signal?: AbortSignal
Sleep for approximately
msmilliseconds, abortable viasignal.
The public HTTP client contract returned by createClient().
-
request<TResponse, TBody = unknown>(request: ClientRequest<TBody>): Promise<ClientResponse<TResponse>>
Execute an outbound JSON request.
A running realtime WebSocket client.
-
close(): voidcode?: number,reason?: string
Stops future reconnect attempts and closes the active socket.
-
send(message: TOutgoing): void
Serializes non-string values as JSON and sends a text frame.
-
state: RealtimeClientState
Current lifecycle state.
A running SSE client returned by createSseClient.
-
close(): void
Stops the active stream and disables every future reconnect attempt.
-
state: SseClientState
Current lifecycle state.
Minimal structural WebSocket surface used by the client.
-
close(): voidcode?: number,reason?: string
Closes the connection.
-
onclose: ((event: CloseEvent) => void) | null
Close callback installed by the client.
-
onerror: ((event: Event) => void) | null
Error callback installed by the client.
-
onmessage: ((event: MessageEvent) => void) | null
Message callback installed by the client.
-
onopen: ((event: Event) => void) | null
Open callback installed by the client.
-
readyState: number
Browser-compatible ready-state number (
0connecting,1open). -
send(data: string): void
Sends one text frame.
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'.
The source frame given to a custom SSE payload parser.
-
data: string
Joined raw
data:lines. -
event: string
Server-provided event name, or
'message'when omitted. -
id: string
Server event ID, when supplied.
Configuration for createRealtimeClient.
-
heartbeatPayload: string
Application heartbeat text to suppress and send back. Defaults to
'ping'. -
onError: (error: unknown) => void
Receives socket or payload parse errors.
-
onMessage: (message: RealtimeMessage<TIncoming>) => void
Receives parsed application messages in arrival order.
-
onStateChange: (state: RealtimeClientState) => void
Receives lifecycle transitions.
-
parse: (data: string) => TIncoming
Parses a non-heartbeat text frame. Defaults to
JSON.parse. -
reconnect: RealtimeReconnectOptions
Reconnect policy following an unrequested close.
-
room: string
Room name re-applied to the URL on every connection.
-
roomParameter: string
Query-string key for
RealtimeClientOptions.room. Defaults to'room'. -
signal: AbortSignal
Optional external signal that permanently closes the client.
-
timing: IClientTiming
Injectable clock and sleep seam. Defaults to
createDefaultClientTiming(). -
url: string
Absolute WebSocket endpoint URL.
-
webSocket: WebSocketFactory
Injectable constructor seam. Defaults to global WebSocket.
One parsed application message received from the server.
-
data: TData
Parsed text-frame payload.
Bounded reconnect policy for a realtime connection.
-
delayMs: number
Initial reconnect delay in milliseconds. Defaults to 1,000.
-
maxAttempts: number
Maximum reconnect attempts after close. Omit for unlimited attempts.
-
maxDelayMs: number
Maximum exponential reconnect delay in milliseconds. Defaults to 30,000.
Retry policy consumed by the ResiliencePlugin's retry pattern.
-
backoff: BackoffStrategy
Backoff strategy applied to
delay. -
delay: number
Base backoff delay in milliseconds.
-
limit: number
Maximum total attempts (
1= a single attempt, no retry).
Top-level OpenAPI 3.1 document consumed by {@code generateOpenApiClient}.
-
components: { readonly schemas?: Record<string, SdkOpenApiSchema>; }
Optional component definitions (schemas, parameters, etc.).
-
openapi: string
OpenAPI spec version string (expected {@code '3.1.0'}).
-
paths: Record<string, SdkOpenApiPathItem>
API paths keyed by path template.
An HTTP operation (method handler) on a path.
A single operation parameter.
A single path item containing HTTP operation entries.
Operation request body.
A single response description keyed by status code or range.
OpenAPI schema supporting the M21 emitted vocabulary:
- $ref: string
- additionalProperties: boolean | SdkOpenApiSchema
- allOf: SdkOpenApiSchema[]
- anyOf: SdkOpenApiSchema[]
- const: unknown
- description: string
- enum: unknown[]
- format: string
- items: SdkOpenApiSchema
- oneOf: SdkOpenApiSchema[]
- properties: Record<string, SdkOpenApiSchema>
- required: string[]
- type: string | string[]
Configuration for createSseClient.
-
fetch: () => Promise<Response>input: RequestInfo,init?: RequestInit
Injectable streaming transport. Defaults to global
fetch. -
headers: HeadersInit
Headers cloned into every initial and reconnect request.
-
onError: (error: unknown) => void
Receives recoverable transport or parse errors before a reconnect attempt.
-
onEvent: (event: SseEvent<keyof TEvents & string, TEvents[keyof TEvents]>) => void | Promise<void>
Receives every parsed data-bearing event in stream order.
-
onStateChange: (state: SseClientState) => void
Receives each state transition.
-
parse: (event: RawSseEvent) => TEvents[keyof TEvents]
Parses one raw SSE event. Defaults to
JSON.parseand is typed against the event map so applications can refine payloads by event name. -
reconnect: SseReconnectOptions
Reconnect behavior after an ended or failed stream.
-
signal: AbortSignal
External signal that closes the stream and prevents reconnects.
-
timing: IClientTiming
Injectable clock and sleep seam. Defaults to
createDefaultClientTiming(). -
url: string
Absolute SSE endpoint URL.
One parsed SSE event delivered to an application.
-
data: TData
Parsed event payload.
-
event: TName
Server-provided event name, or
'message'when omitted on the wire. -
id: string
Server event ID, when supplied.
Reconnection policy for an SSE stream.
-
delayMs: number
Default reconnect delay in milliseconds. Defaults to 1,000.
-
maxAttempts: number
Maximum reconnect attempts after a stream failure. Omit for unlimited attempts.
-
maxDelayMs: number
Upper bound for exponential reconnect delay. Defaults to 30,000.
Backoff strategy applied to a RetryPolicy's base delay.
A request interceptor called once (before any retry attempt) in registration
order. Receives a mutable ClientRequestContext.
A response interceptor called after a successful JSON parse, in registration order. Skipped entirely when the request throws.
Lifecycle states a realtime client reports.
The lifecycle state of an SSE client.
A map from SSE event names to their parsed payload types.
Injectable constructor seam for the global WebSocket.
AWS Secrets Manager provider.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
get(name: string): Promise<string | null>
Reads a secret from AWS Secrets Manager.
-
isHealthy: () => Promise<boolean>
Reachability probe, present only when the resolved client supplies one (M90b). The AWS SDK facade has no non-mutating probe of its own, so the adapted (lazy) path stays
undefinedand the indicator reportsreachable: 'unknown'; an injected facade that exposesisHealthypublishes real reachability. -
isReady(): boolean
Reports whether the provider is ready to serve reads.
-
set(): Promise<void>name: string,value: string
Writes a new value for a secret.
Azure Key Vault provider.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
get(name: string): Promise<string | null>
Reads a secret from Azure Key Vault.
-
isHealthy: () => Promise<boolean>
Reachability probe, present only when the resolved client supplies one (M90b). The Azure SDK facade has no non-mutating probe of its own, so the adapted (lazy) path stays
undefinedand the indicator reportsreachable: 'unknown'; an injected facade that exposesisHealthypublishes real reachability. -
isReady(): boolean
Reports whether the provider is ready to serve reads.
-
set(): Promise<void>name: string,value: string
Sets a secret's value.
Environment-variable secret provider.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
get(name: string): Promise<string | null>
Reads the environment variable for a secret name.
-
isHealthy(): Promise<boolean>
Lifecycle truth (M90b): environment variables are process state, so the only honest reachability answer is readiness.
-
isReady(): boolean
Reports whether the provider is ready to serve reads.
-
set(): Promise<void>_name: string,_value: string
Always rejects — environment variables are immutable at runtime.
GCP Secret Manager provider.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
get(name: string): Promise<string | null>
Reads a secret from GCP Secret Manager.
-
isHealthy: () => Promise<boolean>
Reachability probe, present only when the resolved client supplies one (M90b). The GCP SDK facade has no non-mutating probe of its own, so the adapted (lazy) path stays
undefinedand the indicator reportsreachable: 'unknown'; an injected facade that exposesisHealthypublishes real reachability. -
isReady(): boolean
Reports whether the provider is ready to serve reads.
-
set(): Promise<void>name: string,value: string
Adds a new secret version.
HashiCorp Vault (KV v2) provider.
-
connect(): Promise<void>
Establishes any backing connection/client. No-op for stateless providers.
-
disconnect(): Promise<void>
Releases any backing connection/client. No-op for stateless providers.
-
get(name: string): Promise<string | null>
Reads a secret from Vault's KV v2 engine.
-
isHealthy(): Promise<boolean>
Probes Vault's unauthenticated
/v1/sys/health(M90b). Any HTTP response proves the server answered — Vault reports its standby and sealing states through STATUS CODES on this endpoint, all of which mean "reachable" — and a network failure does not. No secret is read and the auth token is not sent: the health endpoint is unauthenticated by design, and a read is not a probe. -
isReady(): boolean
Reports whether the provider is ready to serve reads.
-
set(): Promise<void>name: string,value: string
Writes a new secret version to Vault's KV v2 engine.
Thrown when a secret is written through a provider that cannot store.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms. -
provider: string
The provider that refused the write (e.g.
'EnvProvider').
Secret manager backed by a pluggable provider with a read-through cache.
-
get(name: string): Promise<string>
Retrieves a secret, serving a fresh cache entry when present.
-
has(name: string): Promise<boolean>
Reports whether a secret exists and is accessible.
-
rotate(): Promise<void>name: string,value: string
Rotates a secret to a new value and refreshes the cache entry.
Creates the SecretsPlugin.
Options for AwsKmsProvider.
-
accessKeyId: string | undefined
AWS access key id for the lazily-loaded client.
-
client: IAwsSecretsClient | undefined
Injected client facade; bypasses the lazy SDK import.
-
region: string | undefined
AWS region for the lazily-loaded client.
-
secretAccessKey: string | undefined
AWS secret access key for the lazily-loaded client.
Options for AzureKeyVaultProvider.
-
client: IAzureSecretsClient | undefined
Injected client facade; bypasses the lazy SDK import.
-
vaultUrl: string | undefined
Key Vault URL for the lazily-loaded client.
Options for GcpSecretManagerProvider.
-
client: IGcpSecretsClient | undefined
Injected client facade; bypasses the lazy SDK import.
-
projectId: string | undefined
GCP project id used to build secret resource paths.
Options for HashiCorpVaultProvider.
-
address: string | undefined
Vault server address, e.g.
https://vault.example.com. -
http: IVaultHttp | undefined
Injected
fetch-shaped function; defaults to globalfetch. -
mount: string | undefined
KV v2 mount path. Default
secret. -
token: string | undefined
Vault auth token sent as
X-Vault-Token.
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.
-
getSecretValue(secretId: string): Promise<string | null>
Retrieves a secret string by id.
-
isHealthy(): Promise<boolean>
Optional non-mutating reachability probe (M90b). When the injected facade exposes it, the provider's health indicator reports real reachability; when omitted, the indicator reports
reachable: 'unknown'rather than reading a secret as a probe — a read is not a health check and would alter the plugin's cache and billing profile. -
putSecretValue(): Promise<void>secretId: string,value: string
Stores a new value for a secret.
Structural shape of an Azure Key Vault facade (injected or SDK-adapted).
-
getSecret(name: string): Promise<string | null>
Gets a secret's current value.
-
isHealthy(): Promise<boolean>
Optional non-mutating reachability probe (M90b). See
IAwsSecretsClient.isHealthyfor the contract. -
setSecret(): Promise<void>name: string,value: string
Sets a secret's value.
Structural shape of a GCP Secret Manager facade (injected or SDK-adapted).
-
accessSecretVersion(name: string): Promise<string | null>
Accesses the latest enabled version of a secret.
-
addSecretVersion(): Promise<void>name: string,value: string
Adds a new version to a secret.
-
isHealthy(): Promise<boolean>
Optional non-mutating reachability probe (M90b). See
IAwsSecretsClient.isHealthyfor the contract.
Secret manager backed by a provider (AWS KMS, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, or environment variables in development).
-
get(name: string): Promise<string>
Retrieves a secret.
-
has(name: string): Promise<boolean>
Reports whether a secret exists.
-
rotate(): Promise<void>name: string,value: string
Rotates a secret to a new value.
Options for the SecretsPlugin factory.
-
options: SecretsProviderOptions
Provider-specific options.
-
provider: SecretsProviderType
Provider backend. Defaults to
'env'.
Provider-specific options. Fields are consumed only by the matching provider; unrelated fields are ignored.
-
accessKeyId: string
(
aws-kms) AWS access key id for the lazily-loaded client. -
address: string
(
vault) Vault server address, e.g.https://vault.example.com. -
cacheTtl: number
Read-cache TTL in seconds.
0disables caching. Default300. -
client: IAwsSecretsClient | IGcpSecretsClient | IAzureSecretsClient
(
aws-kms|gcp|azure) Injected client facade; bypasses the lazy SDK import. Typed as the union of the three facades — each provider validates the shape it needs. -
http: IVaultHttp
(
vault) Injectedfetch-shaped function; defaults to globalfetch. -
mount: string
(
vault) KV v2 mount path. Defaultsecret. -
prefix: string
(
env) Prefix prepended to the derived environment key. -
projectId: string
(
gcp) GCP project id used to build secret resource paths. -
region: string
(
aws-kms) AWS region for the lazily-loaded client. -
secretAccessKey: string
(
aws-kms) AWS secret access key for the lazily-loaded client. -
token: string
(
vault) Vault auth token sent asX-Vault-Token. -
vaultUrl: string
(
azure) Key Vault URL for the lazily-loaded client.
Options for SecretsService.
-
cacheTtlSeconds: number
Read-cache TTL in seconds.
0disables caching. Default300. -
clock: () => number
Monotonic clock in milliseconds (e.g.
runtime.hrtime). Defaults to a monotonicperformance.now-free stub returning0, which — combined with a non-zero TTL — still caches within a request but never mixes wall-clock.
A fetch-shaped function used by SecretsProviderOptions.http so
the HashiCorp Vault provider stays runtime-agnostic and testable.
Supported secret provider backends.
Example 1
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');
Reads and registers against a Consul agent.
-
deregisterSelf(registration: SelfRegistration): Promise<void>
Removes this instance from the agent.
-
headers(): Record<string, string>
Headers every request carries; the ACL header is omitted when unset.
-
healthUrl(): stringserviceName: string,index?: number
Builds the health-read URL.
-
isHealthy(): Promise<boolean>
M70c: probes the agent's leader endpoint —
GET /v1/status/leader— through the existingIDiscoveryHttpseam. 2xx means the agent is reachable; any other status or a transport failure means it is not. -
kind: string
Backend id.
-
mapEntries(): readonly ServiceInstance[]body: unknown,serviceName: string
Maps a health response body onto instances.
-
registerSelf(registration: SelfRegistration): Promise<void>
Advertises this instance to the agent.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Reads the current instance list for a service.
-
selfId(registration: SelfRegistration): string
The instance id used for both register and deregister.
-
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Subscribes to instance-list changes.
Resolves services through DNS.
-
domainFor(serviceName: string): string
Substitutes the service name into the configured template.
-
kind: string
Backend id.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Reads the current instance list for a service.
-
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Polls at
watchIntervalMs, firing only when the instance list changed.
Reads EndpointSlices for a service.
-
authHeader(): Promise<string>
Resolves the bearer token, reading the projected file when no explicit token was configured.
-
isHealthy(): Promise<boolean>
M70c: probes the API server with a
limit=1EndpointSlice LIST through the existing seam. This is the probe that makes X10-3 visible: anUnknownIssuerTLS rejection surfaces here asdown. 2xx means the API is reachable. -
kind: string
Backend id.
-
listUrl(): stringserviceName: string,extra?: Readonly<Record<string, string>>
Builds the EndpointSlice list URL for a service.
-
mapSlices(): readonly ServiceInstance[]body: unknown,serviceName: string
Maps an EndpointSlice list onto instances.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Reads the current instance list for a service.
-
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Subscribes to instance-list changes.
selfRegistration was configured against a provider that cannot register.
-
name: string
Discriminating name for
instanceof-free checks.
Serves a configured instance list.
-
isHealthy(): Promise<boolean>
M70c: a static map is in memory and cannot be unreachable, so it is always reachable (M47).
-
kind: string
Backend id.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Reads the current instance list for a service.
-
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Fires once with the configured list and never again.
Creates the default HTTP seam.
Creates the service discovery plugin.
The 'dns' arm in address mode — A/AAAA records carry no port.
-
mode: "a"
Query
A/AAAArecords. -
port: number
Port every resolved address is reached on.
The 'consul' arm.
-
address: string
Base URL of the Consul agent, e.g.
http://127.0.0.1:8500. -
datacenter: string
Datacenter, sent as
?dc=. -
http: IDiscoveryHttp
Overrides the default
fetch-backed HTTP seam. -
provider: "consul"
Discriminant.
-
secure: boolean
Whether resolved instances speak TLS — Consul carries no scheme.
-
token: string
ACL token, sent as
X-Consul-Token. -
waitSeconds: number
Blocking-query
wait, in seconds. Default30, clamped to Consul's documented maximum of 600.
Constructor options.
-
address: string
Base URL of the Consul agent.
-
datacenter: string
Datacenter, sent as
?dc=. -
secure: boolean
Whether resolved instances speak TLS.
-
token: string
ACL token, sent as
X-Consul-Token. -
waitSeconds: number
Blocking-query wait, in seconds.
The 'custom' arm — the application's own backend.
-
discovery: DiscoveryProvider
The provider, used as supplied.
-
provider: "custom"
Discriminant.
A buffered HTTP response, as IDiscoveryHttp.request returns it.
-
headers: Headers
Response headers.
-
ok: boolean
Whether the status is 2xx.
-
status: number
HTTP status code.
-
text: string
Response body, read to completion as text.
A streaming HTTP response, as IDiscoveryHttp.stream returns it.
-
body: ReadableStream<Uint8Array> | null
The response body, or
nullwhen the response carries none. -
headers: Headers
Response headers.
-
ok: boolean
Whether the status is 2xx.
-
status: number
HTTP status code.
A discovery backend.
-
deregisterSelf(registration: SelfRegistration): Promise<void>
Removes this application instance from the backend.
-
isHealthy(): Promise<boolean>
M70c: reports whether the discovery backend is reachable right now, for the plugin's health indicator.
-
kind: string
Backend id, surfaced by the health indicator.
-
registerSelf(registration: SelfRegistration): Promise<void>
Registers this application instance with the backend.
-
resolve(serviceName: string): Promise<readonly ServiceInstance[]>
Reads the current instance list for a service.
-
watch(): Promise<Unsubscribe>serviceName: string,listener: (instances: readonly ServiceInstance[]) => void
Subscribes to instance-list changes.
Outlier-ejection tuning.
-
durationMs: number
How long an ejection lasts, in milliseconds.
-
failureThreshold: number
Failures inside the window that eject an instance.
-
maxEjectionPercent: number
Ceiling on the percentage of a service's instances ejected at once.
-
windowMs: number
Rolling window, in milliseconds, that failures are counted over.
The HTTP surface the Consul and Kubernetes providers need.
-
request(): Promise<DiscoveryHttpResponse>url: string,init?: RequestInit
Performs a request and reads the whole body.
-
stream(): Promise<DiscoveryHttpStream>url: string,init?: RequestInit
Performs a request and leaves the body unread.
The 'kubernetes' arm — EndpointSlices read from the API server.
-
apiServer: string
API server base URL. Defaults to the in-cluster
https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT. -
http: IDiscoveryHttp
Overrides the default
fetch-backed HTTP seam. -
namespace: string
Namespace the services live in.
-
portName: string
Selects the
ports[]entry by name when a service exposes several. -
provider: "kubernetes"
Discriminant.
-
secure: boolean
Whether resolved instances speak TLS.
-
token: string
Bearer token, used verbatim.
Constructor options.
-
apiServer: string
API server base URL, already resolved from options or the environment.
-
namespace: string
Namespace the services live in.
-
portName: string
Selects the
ports[]entry by name. -
secure: boolean
Whether resolved instances speak TLS.
-
token: string
Bearer token used verbatim; absent means read the projected token file.
What this application advertises about itself.
-
address: string
Address other applications should reach this instance on.
-
check: SelfRegistrationCheck
The mandatory health check (defaults applied by
resolveOptions). -
drainDelayMs: number
Milliseconds to keep serving after deregistering, before draining begins.
-
id: string
Instance id, unique within the service. Defaults to
<name>-<uuid>. -
metadata: Readonly<Record<string, string>>
Key/value metadata to attach to the registration.
-
port: number
Port other applications should reach this instance on.
-
serviceName: string
Logical service name other applications resolve.
-
tags: readonly string[]
Labels to attach to the registration.
The health check the backend runs against this instance after registration.
-
deregisterAfterSeconds: number
Seconds a critical service survives before the backend removes it.
-
httpPath: string
HTTP path the backend polls, appended to this instance's origin.
-
intervalSeconds: number
Seconds between checks.
The 'dns' arm in SRV mode — records carry their own ports.
-
mode: "srv"
Query
SRVrecords and honor RFC 2782 priority tiers.
The 'static' arm — a literal instance list, with no backend at all.
-
provider: "static"
Discriminant.
-
services: Readonly<Record<string, readonly StaticServiceDefinition[]>>
Service name to its instances. An unknown name resolves to
[]. -
watchIntervalMs: number
Milliseconds between
watch()polls.
One entry of a 'static' service list.
-
host: string
Hostname or IP literal.
-
id: string
Instance id. Synthesized as
<host>:<port>when omitted. -
metadata: Readonly<Record<string, string>>
Key/value metadata.
-
port: number
TCP port.
-
secure: boolean
Whether the instance speaks TLS.
-
tags: readonly string[]
Labels.
-
weight: number
Relative selection weight for
'weighted-random'.
| ConsulDiscoveryOptions
| KubernetesDiscoveryOptions
| DnsDiscoveryOptions
| CustomDiscoveryOptions
Options accepted by ServiceDiscoveryPlugin.
Example 1
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 }); });
ISessionStore over any ICacheStore.
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
isHealthy(): Promise<boolean>
Reports the store's reachability, for the plugin's health indicator.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
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
instanceofacross realms.
Map-backed ISessionStore.
-
close(): Promise<void>
Releases resources held by the store (timers, connections).
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
isHealthy(): Promise<boolean>
Reports the store's reachability, for the plugin's health indicator.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
size(): number
How many entries are currently held, expired ones included.
-
sweep(): void
Drops every expired entry. Exposed so the sweep is directly testable.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
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
instanceofacross realms.
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
instanceofacross realms.
Loads, exposes, and commits the per-request session.
-
close(): Promise<void>
Releases store resources; called from the plugin's
onClose. -
commit(): Promise<void>ctx: IRequestContext,session: Session
Writes the session back, when it needs writing.
-
from(ctx: IRequestContext): ISession
Returns the session the middleware loaded for this request.
-
fromHeaders(headers: Headers): Promise<SessionView | null>
Opens a session from a
Headersobject alone — the headers-only read for non-HTTP entry points that have no request context to commit onto (a WebSocketonOpenhandler, an auth strategy reading a cookie). -
keyCount(): number
How many keys can open a cookie, for the health indicator.
-
load(ctx: IRequestContext): Promise<Session>
Loads the session for a request, falling back to a fresh one whenever the cookie is absent, malformed, tampered with, expired, idle, or (on the store strategy) no longer present server-side.
-
mode(): string
How the cookie is protected, for the health indicator.
-
storeHealth(): Promise<boolean | undefined>
Reports store reachability for the health indicator.
-
strategy(): "cookie" | "store"
Which strategy is in effect, for the health indicator.
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
instanceofacross realms.
Builds the form-CSRF middleware.
Renders this session's CSRF token as a hidden HTML form field.
Returns this session's CSRF token, minting and storing one on first call.
Returns the session the middleware loaded for this request.
Builds the session middleware.
Registers cookie-backed sessions under CAPABILITIES.SESSION, with optional
session-backed form CSRF.
Verifies the request's CSRF token against the session's, throwing on any mismatch.
Options for CacheSessionStore.
-
keyPrefix: string
Key namespace inside the cache. Default
'session:'.
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 formultipart/form-databodies 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'].
Runtime capabilities the store needs.
-
clearInterval: (handle: TimerHandle) => void
Interval canceller, from
IRuntimeServices.clearInterval. -
now: () => number
Wall-clock milliseconds, from
IRuntimeServices.now. -
setInterval: () => TimerHandlefn: () => void,ms: number
Interval scheduler, from
IRuntimeServices.setInterval. -
sweepIntervalMs: number
Milliseconds between expiry sweeps. Default
60000.
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 customISessionStoreto 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 with403before the handler runs. When either the session or the request carries no tenant, nothing is compared, so an application without tenancy is inert.falserestores the previous behaviour (no seal, no compare).
Runtime capabilities the service needs, injected for testability.
-
now: () => number
Wall-clock milliseconds, from
IRuntimeServices.now. -
randomBytes: (length: number) => Uint8Array
Random bytes, from
IRuntimeServices.randomBytes. -
subtle: SubtleCrypto
Web Crypto, from
IRuntimeServices.subtle. -
uuid: () => string
Identifier source, from
IRuntimeServices.uuid.
How a session cookie is protected.
Reserved session key holding the CSRF token.
Example 1
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; });
Implements IConn.
-
close(): void
Close the connection (idempotent).
-
comment(text: string): void
Enqueue a plain-text comment frame.
-
id: string
Unique connection ID.
-
isOpen(): boolean
Whether this connection is still open.
-
lastEventId: string | null
The client's
Last-Event-IDheader value, if present. -
result: HandlerResult
The
HandlerResultobtained fromctx.response.stream()— set in constructor. -
send(msg: SseMessage): void
Enqueue an encoded SSE message.
Implements IService.
-
channel(name: string): SseChannel
Return or create a named channel.
-
channelCount(): number
Number of channels the registry currently holds.
-
closeAll(): void
Close all live connections (used during shutdown).
-
connectionCount(): number
Current number of open connections.
-
deliverRemoteFrame(frame: RealtimeFrame): void
Delivers a message that arrived from another replica to this replica's local channel members.
-
open(ctx: IRequestContext): ISseConnection
Open a new SSE connection for the given request context.
-
peek(name: string): SseChannel | undefined
Return the named channel if it already exists, without creating it.
Creates the SsePlugin.
A live SSE connection backed by a ReadableStream.
-
close(): void
Closes the connection: clears the heartbeat, closes the stream controller, and marks the connection as closed. Idempotent.
-
comment(text: string): void
Enqueues a plain-text comment frame (
: <text>\n\n) — commonly used as a keep-alive heartbeat. -
id: string
Unique connection ID.
-
isOpen: boolean
Whether this connection is still open.
-
lastEventId: string | null
The client's
Last-Event-IDheader value, if present. -
result: HandlerResult
The
HandlerResultobtained fromctx.response.stream(). The handler returns this value so the kernel maps it to the correct web response. -
send(msg: SseMessage): void
Enqueues an encoded SSE frame for the connected client.
Service contract for the SSE hub — registered by the SsePlugin under
CAPABILITIES.SSE.
-
channel(name: string): SseChannel
Returns or creates a named channel.
-
channelCount: number
Number of channels the registry currently holds.
-
connectionCount: number
Current number of open connections.
-
open(ctx: IRequestContext): ISseConnection
Opens a new SSE connection for the given request context.
-
peek(name: string): SseChannel | undefined
Returns the named channel if one already exists, without creating it.
A named broadcast channel within the SSE hub.
-
add(conn: ISseConnection): void
Adds a connection to this channel's membership.
-
publish(msg: SseMessage): void
Publishes a message to every open member of this channel, skipping any connection whose
ISseConnection.isOpenisfalse. -
remove(conn: ISseConnection): void
Removes a connection from this channel's membership.
-
size: number
Number of currently open connections in this channel.
A single SSE event payload.
-
data: JsonValue
Event data. A
stringis written literally (split on\ninto multipledata:lines); any non-string isJSON.stringify-ed.undefinedis 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; enablesLast-Event-IDresume. -
retry: number
Reconnection time in milliseconds — sent as
retry:field.
Options for the SsePlugin.
-
heartbeatMs: number
Heartbeat interval in milliseconds. When set, the plugin schedules a repeating
: heartbeat\n\ncomment 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 noretry:field. -
scalingNotice: boolean
Whether to log one
infoline at registration when no realtime backplane is registered, stating that channels broadcast in-process only. Defaults totrue.
Forwards a local publish to peers on other replicas.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
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.
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.
Creates a full-stack application whose options are derived from configuration.
Options for createFullStackAppFromConfig.
-
config: ConfigPluginOptions
Loading options —
.envpaths, variable expansion, validation schema. -
env: Readonly<Record<string, unknown>> | undefined
The environment to read configuration from, instead of the platform's.
Options for createFullStackApp. Extends MicroserviceStarterOptions
with full-stack arms (always-on + gated). Omitted plugins use their defaults.
-
audit: AuditPluginOptions
Always-on arm:
AuditPlugin. Omitted → memory storage default. -
cache: CachePluginOptions
Always-on arm:
CachePlugin. Omitted → memory store default. -
cqrs: CqrsPluginOptions
Always-on arm:
CqrsPlugin. Omitted → no built-in behaviors. -
events: EventsPluginOptions
Always-on arm:
EventsPlugin. Omitted → in-memory bus default. -
featureFlags: FeatureFlagsPluginOptions
Optional arm:
FeatureFlagsPlugin. Gated — requires a provider to be useful. -
mail: MailPluginOptions
Always-on arm:
MailPlugin. Omitted → log provider default. -
multiTenancy: MultiTenancyPluginOptions
Optional arm:
MultiTenancyPlugin. Gated — requires resolvers to be useful. -
notifications: NotificationPluginOptions
Optional arm:
NotificationPlugin. Gated — requires channels to be useful. -
reactRouter: ReactRouterPluginOptions
Optional arm:
ReactRouterPlugin. Gated — requiresserverBuildPathfor SSR. -
scheduler: SchedulerPluginOptions
Always-on arm:
SchedulerPlugin. Omitted → defaults. -
secrets: SecretsPluginOptions
Always-on arm:
SecretsPlugin. Omitted → env provider default. -
static: StaticPluginOptions
Optional arm:
StaticPlugin. Gated — requiresrootto serve from; absent registers nothing, leaving the composition byte-identical. -
storage: StoragePluginOptions
Always-on arm:
StoragePlugin. Omitted → memory provider default.
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.
-
backplane: RealtimeBackplanePluginOptions
Options for
RealtimeBackplanePlugin, which fans WebSocket rooms and SSE channels out across replicas. Present → the plugin is registered atPLUGIN_PRIORITY.HIGH, so it precedes both consumers. -
sse: SsePluginOptions
Options for
SsePlugin. Present → the plugin is registered. -
websocket: WebSocketPluginOptions
Options for
WebSocketPlugin. Present → the plugin is registered.
Options for configuring the StaticPlugin.
-
cacheControl: string | ((relativePath: string) => string)
Cache-Control header configuration (default: function returning immutable for hashed assets, must-revalidate for others).
-
compressed: boolean
Enable precompressed sidecar negotiation (default: true).
-
etag: boolean
Enable ETag generation (default: true).
-
fallback: string
Fallback file to serve for missing paths when Accept includes text/html (default: undefined). Used for SPA fallback.
-
fs: IFileSystem
The filesystem to use for file operations.
-
index: string
Index file to serve when a directory is requested (default: 'index.html'). Set to empty string '' to disable index resolution.
-
maxBufferBytes: number
Maximum file size to read fully into memory (default: 1MB). Files larger than this will use streaming when available.
-
ranges: boolean
Enable Range request handling (default: true).
-
root: string
Required. The filesystem directory to serve files from.
-
urlPrefix: string
URL prefix for static routes (default: '/').
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.
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.
Options for createMicroserviceApp. Extends RestStarterOptions
with microservice-specific arms. Omitted plugins use their defaults.
-
messaging: MessagingPluginOptions
Configuration for
MessagingPlugin, which this tier ALWAYS registers — unlike the gated arms inherited fromRestStarterOptions, omitting this does not skip the plugin. Omitted → the memory broker default. -
queue: QueuePluginOptions
Configuration for
QueuePlugin, always registered. Omitted → the memory adapter default. -
resilience: ResiliencePluginOptions
Configuration for
ResiliencePlugin, always registered. Omitted → plugin defaults. -
telemetry: TelemetryPluginOptions
Configuration for
TelemetryPlugin, always registered. Omitted → aNoopTelemetryService, since no exporter is configured.
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.
-
backplane: RealtimeBackplanePluginOptions
Options for
RealtimeBackplanePlugin, which fans WebSocket rooms and SSE channels out across replicas. Present → the plugin is registered atPLUGIN_PRIORITY.HIGH, so it precedes both consumers. -
sse: SsePluginOptions
Options for
SsePlugin. Present → the plugin is registered. -
websocket: WebSocketPluginOptions
Options for
WebSocketPlugin. Present → the plugin is registered.
Builds the canonical REST plugin set. The list is exported so the microservice starter can compose from it without duplication.
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.
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.
-
backplane: RealtimeBackplanePluginOptions
Options for
RealtimeBackplanePlugin, which fans WebSocket rooms and SSE channels out across replicas. Present → the plugin is registered atPLUGIN_PRIORITY.HIGH, so it precedes both consumers. -
sse: SsePluginOptions
Options for
SsePlugin. Present → the plugin is registered. -
websocket: WebSocketPluginOptions
Options for
WebSocketPlugin. Present → the plugin is registered.
Options for createRestApp. Per-plugin optional arms are threaded
straight through to each plugin factory. Omitted plugins use their default
configuration (no arguments required).
-
auth: AuthPluginOptions
Optional arm:
AuthPlugin. Provided only when the caller supplies auth configuration; omitted → auth not registered.rbacis itself optional — supplyjwtalone for a JWT-only application, which registers no authorization capability. -
config: ConfigPluginOptions
Options for
ConfigPlugin. Omitted → defaults. -
database: DatabasePluginOptions
Optional arm:
DatabasePlugin. Provided only when the caller supplies database credentials; omitted → database not registered. -
decorators: DecoratorPluginOptions
Options for
DecoratorPlugin. Omitted → defaults. -
di: DiPluginOptions
Optional arm:
DiPlugin. Omitted → decorated services are constructed directly and registered in the kernel'sServiceRegistry, which is the default and needs no container. -
graphql: GraphqlPluginOptions
Optional arm:
GraphqlPlugin. Gated because the plugin cannot boot without an application-supplied schema — the rule that madesessiongated. -
health: HealthPluginOptions
Options for
HealthPlugin. Omitted → defaults. -
httpSecurity: HttpSecurityPluginOptions
Options for
HttpSecurityPlugin. Omitted → defaults. -
logger: LoggerPluginOptions
Options for
LoggerPlugin. Omitted → defaults. -
metrics: MetricsPluginOptions
Options for
MetricsPlugin. Omitted → defaults. -
openapi: OpenApiPluginOptions
Options for
OpenApiPlugin. Omitted → defaults. -
realtime: RealtimeArm
Optional arm: the real-time plugins, one per sub-arm. Omitted → none of the three is registered.
-
serviceDiscovery: ServiceDiscoveryPluginOptions
Optional arm: ServiceDiscoveryPlugin. Provided → service discovery is registered; omitted → no discovery capability is added.
-
session: SessionPluginOptions
Optional arm:
SessionPlugin. Omitted → the application has no cookie session and no session-backed form CSRF. -
validation: ValidationPluginOptions
Options for
ValidationPlugin. Omitted → defaults.
Static files service that serves files from a configured root directory.
-
serve(ctx: IRequestContext): Promise<HandlerResult>
Serves the static file addressed by the request context.
Creates a static file RouteHandler.
Creates a StaticPlugin that serves static files from a configured root directory.
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.
Options for configuring the StaticPlugin.
-
cacheControl: string | ((relativePath: string) => string)
Cache-Control header configuration (default: function returning immutable for hashed assets, must-revalidate for others).
-
compressed: boolean
Enable precompressed sidecar negotiation (default: true).
-
etag: boolean
Enable ETag generation (default: true).
-
fallback: string
Fallback file to serve for missing paths when Accept includes text/html (default: undefined). Used for SPA fallback.
-
fs: IFileSystem
The filesystem to use for file operations.
-
index: string
Index file to serve when a directory is requested (default: 'index.html'). Set to empty string '' to disable index resolution.
-
maxBufferBytes: number
Maximum file size to read fully into memory (default: 1MB). Files larger than this will use streaming when available.
-
ranges: boolean
Enable Range request handling (default: true).
-
root: string
Required. The filesystem directory to serve files from.
-
urlPrefix: string
URL prefix for static routes (default: '/').
Azure Blob storage provider.
-
connect(): Promise<void>
Establishes the Azure client — injects the SDK lazily or uses injected client.
-
delete(path: string): Promise<boolean>
Deletes an object from Azure Blob Storage.
-
disconnect(): Promise<void>
Disconnect is a no-op for Azure (connectionless HTTP client).
-
exists(path: string): Promise<boolean>
Reports whether an object exists in Azure Blob Storage.
-
get(path: string): Promise<Uint8Array | null>
Retrieves an object from Azure Blob Storage;
nullwhen absent. -
getSignedUrl(): Promise<string>path: string,options: { expiresIn: number; }
Creates a SAS URL for an Azure Blob.
-
getStream(path: string): Promise<ReadableStream<Uint8Array> | null>
Native stream download — adapts Azure
readableStreamBody(Node Readable) into a webReadableStreamvia async iteration. -
isHealthy: () => Promise<boolean>
M70c: delegates to the injected client's optional
isHealthy?()(the real adapter calls the container client'sexists()). Assigned inconnect()only when the client provides the member; a client that omits it is unknown, and the indicator reads absence (notfalse) as that. -
isReady(): boolean
Reports readiness.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object in Azure Blob Storage, recording any content type and user metadata on the blob so a SAS URL serves it under the right type.
Google Cloud Storage provider.
-
connect(): Promise<void>
Establishes the GCS client — injects the SDK lazily or uses injected client.
-
delete(path: string): Promise<boolean>
Deletes an object from GCS.
-
disconnect(): Promise<void>
Disconnect is a no-op for GCS (connectionless HTTP client).
-
exists(path: string): Promise<boolean>
Reports whether an object exists in GCS.
-
get(path: string): Promise<Uint8Array | null>
Retrieves an object from GCS;
nullwhen absent. -
getSignedUrl(): Promise<string>path: string,options: { expiresIn: number; }
Creates a signed GET URL for a GCS object.
-
getStream(path: string): Promise<ReadableStream<Uint8Array> | null>
Native stream download — adapts GCS
createReadStream()(Node Readable) into a webReadableStreamvia async iteration (nonode:import needed). -
isHealthy: () => Promise<boolean>
M70c: delegates to the injected client's optional
isHealthy?()(the real adapter callsbucket.exists()). Assigned inconnect()only when the client provides the member; a client that omits it is unknown, and the indicator reads absence (notfalse) as that. -
isReady(): boolean
Reports readiness.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object in GCS, recording any content type and user metadata on the object itself so a signed URL serves it under the right type.
Local file-system storage provider.
-
connect(): Promise<void>
Connects, and PROVES the root is writable rather than assuming it.
-
delete(path: string): Promise<boolean>
Deletes an object from disk.
-
disconnect(): Promise<void>
Disconnect is a no-op for local storage.
-
exists(path: string): Promise<boolean>
Reports whether an object exists on disk.
-
get(path: string): Promise<Uint8Array | null>
Retrieves an object from disk;
nullwhen absent. -
getSignedUrl(): Promise<string>_path: string,_options: { expiresIn: number; }
Throws — local storage cannot produce signed URLs.
-
isHealthy(): Promise<boolean>
M70c:
runtime.fs.stat(root)succeeds — a disk that vanished or a permission change is a real, common failure. -
isReady(): boolean
Reports readiness (true when fs is present and connected).
-
put(): Promise<void>path: string,data: Uint8Array,_options?: PutObjectOptions
Stores an object on disk.
In-memory storage provider backed by Map<string, Uint8Array>.
-
connect(): Promise<void>
Connect is a no-op for the memory provider.
-
delete(path: string): Promise<boolean>
Deletes an object from memory.
-
disconnect(): Promise<void>
Disconnect is a no-op for the memory provider.
-
exists(path: string): Promise<boolean>
Reports whether an object exists in memory.
-
get(path: string): Promise<Uint8Array | null>
Retrieves an object from memory;
nullwhen absent. -
getSignedUrl(): Promise<string>path: string,options: { expiresIn: number; }
Returns a synthetic memory:// URL with expiry query parameter.
-
isHealthy(): Promise<boolean>
M70c: an in-memory store has no backend to be unreachable, so it is always reachable (M47).
-
isReady(): boolean
Reports readiness (memory is always ready once connected).
-
put(): Promise<void>path: string,data: Uint8Array,_options?: PutObjectOptions
Stores an object in memory.
AWS S3 storage provider.
-
connect(): Promise<void>
Establishes the S3 client — injects the SDK lazily or uses injected client.
-
delete(path: string): Promise<boolean>
Deletes an object from S3.
-
disconnect(): Promise<void>
Disconnect is a no-op for S3 (connectionless HTTP client).
-
exists(path: string): Promise<boolean>
Reports whether an object exists in S3.
-
get(path: string): Promise<Uint8Array | null>
Retrieves an object from S3;
nullwhen absent. -
getSignedUrl(): Promise<string>path: string,options: { expiresIn: number; }
Creates a presigned GET URL for an S3 object.
-
getStream(path: string): Promise<ReadableStream<Uint8Array> | null>
Native stream download — zero-copy from S3.
-
isHealthy(): Promise<boolean>
M70c: a
client.head('')-shaped bucket probe using the existingheadmember. Resolvestruewhen the bucket answers,falsewhen it does not (or the provider is not connected). -
isReady(): boolean
Reports readiness.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object in S3, recording any content type and user metadata on the object itself — which is what makes a presigned URL render in a browser instead of downloading as
application/octet-stream.
Storage service backed by a pluggable provider.
-
delete(path: string): Promise<boolean>
Deletes an object.
-
exists(path: string): Promise<boolean>
Reports whether an object exists.
-
get(path: string): Promise<Uint8Array>
Retrieves an object.
-
getSignedUrl(): Promise<string>path: string,options: SignedUrlOptions
Creates a time-limited URL granting direct access to an object.
-
getStream(path: string): Promise<ReadableStream<Uint8Array>>
Retrieves an object as a streaming body for zero-copy downloads.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object.
Reports whether key-based SAS signing is possible for these options.
Creates an upload middleware factory.
Retrieves uploaded files for a given field name from ctx.state.
Creates the StoragePlugin.
Options for AzureBlobProvider.
-
accountKey: string
Azure storage account key (required for SAS signing).
-
accountName: string
Azure storage account name.
-
client: IAzureBlobClient
Injected structural client (bypasses lazy import).
-
connectionString: string
Azure connection string (alternative to accountName + accountKey).
-
containerName: string
Container name.
The Azure Blob Storage arm.
-
options: AzureBlobProviderOptions
Container and credentials;
containerNameis required. -
provider: "azure"
Selects the Azure Blob backend.
Options for GcsProvider.
-
bucket: string
Bucket name.
-
client: IGcsClient
Injected structural client (bypasses lazy import).
-
projectId: string
GCP project ID.
The Google Cloud Storage arm.
-
options: GcsProviderOptions
Bucket and project;
bucketis required. -
provider: "gcs"
Selects the GCS backend.
Minimal Azure Blob client shape for structural injection.
- getContainerClient(_name: string): unknown
-
getSignedUrl(): Promise<string>_path: string,_expiresIn: number
Creates a SAS-signed URL. Added by adaptAzureModule internally.
-
isHealthy(): Promise<boolean>
M70c: resolves when the container is reachable — the real adapter calls the container client's
exists(). Optional so a minimal injected fake still type-checks.
Minimal GCS client shape for structural injection.
- bucket(_name?: string): unknown
-
isHealthy(): Promise<boolean>
M70c: resolves when the bucket is reachable — the real adapter calls
bucket.exists(). Optional so a minimal injected fake still type-checks.
The S3 BACKEND surface this package drives — not an @aws-sdk/client-s3
client.
- delete(path: string): Promise<boolean>
- get(path: string): Promise<Uint8Array | null>
-
getSignedUrl(): Promise<string>path: string,expiresIn: number
- getStream(path: string): Promise<ReadableStream<Uint8Array> | null>
- head(path: string): Promise<boolean>
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
The S3 BACKEND surface this package drives — not an @aws-sdk/client-s3
client.
- delete(path: string): Promise<boolean>
- get(path: string): Promise<Uint8Array | null>
-
getSignedUrl(): Promise<string>path: string,expiresIn: number
- getStream(path: string): Promise<ReadableStream<Uint8Array> | null>
- head(path: string): Promise<boolean>
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Object storage abstraction.
-
delete(path: string): Promise<boolean>
Deletes an object.
-
exists(path: string): Promise<boolean>
Reports whether an object exists.
-
get(path: string): Promise<Uint8Array>
Retrieves an object.
-
getSignedUrl(): Promise<string>path: string,options: SignedUrlOptions
Creates a time-limited URL granting direct access to an object.
-
getStream(path: string): Promise<ReadableStream<Uint8Array>>
Retrieves an object as a streaming body for zero-copy downloads.
-
put(): Promise<void>path: string,data: Uint8Array,options?: PutObjectOptions
Stores an object.
The local-filesystem arm.
-
options: LocalStorageProviderOptions
Root directory configuration.
-
provider: "local"
Selects the local-filesystem backend.
Options for LocalStorageProvider.
-
rootDir: string
Root directory for stored objects.
The default arm: in-memory storage, which takes no configuration.
-
provider: "memory"
Selects the memory backend. Optional — an omitted provider means memory.
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 isapplication/octet-streamon 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.
Options for S3Provider (and 'b2' preset).
-
accessKeyId: string
AWS access key ID.
-
bucket: string
Bucket name.
-
client: IS3Backend
An implementation of the S3 backend, bypassing the lazy SDK import.
-
endpoint: string
Custom S3-compatible endpoint (R2, MinIO, B2).
-
region: string
AWS region.
-
secretAccessKey: string
AWS secret access key.
The S3 arm, shared by 's3' and the 'b2' (Backblaze) preset, which reaches
the same provider over B2's S3-compatible endpoint.
-
options: S3ProviderOptions
Bucket and credentials;
bucketis required. -
provider: "s3" | "b2"
Selects the S3 backend, or the Backblaze B2 preset over it.
Options accepted when creating a signed URL.
-
expiresIn: number
URL validity in seconds.
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 NOfilenameunder the field name is a plain form value, not an upload (an emptyfilename=""— 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.
Options for the upload middleware factory.
-
allowedMimeTypes: readonly string[]
Allowed MIME-type allow-list (optional).
-
fieldname: string
Form field name to extract (default
'file'). -
maxBodyBytes: number
Hard ceiling, in bytes, on the request body this middleware will PARSE (default 50 MB). The effective bound is
min(maxSize * 2 + framing allowance, maxBodyBytes), so raisingmaxSizeraises the bound only up to this ceiling. -
maxFiles: number
Maximum number of files (default unlimited).
-
maxSize: number
Maximum per-file size in bytes (default 10 MB).
| 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.
| S3ProviderOptions
| GcsProviderOptions
| AzureBlobProviderOptions
Union of per-provider option shapes.
Supported storage back-ends.
A telemetry service that does nothing — used when no exporter is configured.
-
withSpan<T>(): Promise<T>_name: string,fn: (span: ISpan) => Promise<T>,_options?: SpanOptions
Creates a span, runs the callback, and ends the span.
Creates the request-span middleware.
Creates a telemetry plugin.
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
configargument (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
Instrumentationinstance — the INJECT half of the inject-or-lazy seam. When set, the registry skips the lazynpm:import and uses this instance directly.
Configuration for auto-instrumentations.
-
amqplib: true | InstrumentationConfig
amqplib via @opentelemetry/instrumentation-amqplib. Node-only; no-op elsewhere.
-
fetch: true | InstrumentationConfig
Node undici/fetch via @opentelemetry/instrumentation-undici. Node-only; no-op elsewhere.
-
http: true | InstrumentationConfig
node:http/https via @opentelemetry/instrumentation-http. Node-only; no-op elsewhere.
-
ioredis: true | InstrumentationConfig
ioredis via @opentelemetry/instrumentation-ioredis. Node-only; no-op elsewhere.
-
kafkajs: true | InstrumentationConfig
kafkajs via @opentelemetry/instrumentation-kafkajs. Node-only; no-op elsewhere.
A span represents a single operation within a trace.
-
end(): void
Ends the span. Must be called exactly once.
-
recordException(error: Error): void
Records an exception on this span.
-
setAttribute(): thiskey: string,value: SpanAttributeValue
Sets a single attribute on the span.
-
setAttributes(attributes: Readonly<Record<string, SpanAttributeValue>>): this
Sets multiple attributes on the span.
-
setStatus(status: SpanStatus): void
Sets the status of the span.
-
spanContext(): SpanContext
Returns the span's context (traceId, spanId, traceFlags).
Telemetry service — the primary API for creating spans.
-
activeSpanContext(): SpanContext | undefined
Reports the identifiers of the span that is active RIGHT NOW, so a signal emitted outside any span-creating call — a log record, most of all — can name the trace it belongs to.
-
withSpan<T>(): Promise<T>name: string,fn: (span: ISpan) => Promise<T>,options?: SpanOptions
Creates a span, runs the callback, and ends the span.
Sampling configuration.
-
ratio: number
Sampling ratio between 0.0 and 1.0 (default: 1.0).
-
type: "traceidratio"
Currently only
'traceidratio'is supported.
Options for span creation.
-
attributes: Readonly<Record<string, SpanAttributeValue>>
Initial attributes to set on the span.
-
kind: SpanKind
The span kind (defaults to
'internal'). -
parentContext: TelemetryContext
Optional parent context for span parenting.
Opaque handle representing the parent context for span creation.
-
_opaque: TELEMETRY_CONTEXT_OPAQUE
Internal marker — consumers must not inspect this type.
-
spanId: string
16-character lowercase hex parent span ID (W3C format).
-
traceFlags: string
2-character lowercase hex trace flags (W3C format).
-
traceId: string
32-character lowercase hex trace ID (W3C format).
-
tracestate: string
Raw
tracestateheader value, if present.
Options for the TelemetryPlugin.
-
contextManagerFactory: () => Promise<{ enable(): unknown; disable(): unknown; }>
Injectable loader for the OTel context manager.
-
contextPropagation: boolean
Whether real OTel spans become active for nested work (default:
true). -
endpoint: string
OTLP endpoint URL (required when
exporter: 'otlp'). -
exporter: SpanExporterKind
Which exporter to use. Absent = noop mode.
-
headers: Record<string, string>
Optional headers sent with OTLP requests.
-
instrumentations: InstrumentationsConfig
Auto-instrumentation configuration.
-
middleware: boolean
Whether to register the request-span middleware (default:
true). -
sampling: SamplingConfig
Sampling configuration.
-
serviceName: string
Service name reported to the exporter (required when exporter is configured).
-
serviceVersion: string
Service version (default:
'1.0.0'). -
spanProcessor: SpanProcessorKind
Span processor to use (
'simple'by default,'batch'as an option). -
tracerProviderFactory: () => Promise<TracerHost>
Injectable factory that returns a pre-built TracerHost (test seam).
The host seam returned by loadOtelTracerProvider.
-
activate<T>(): Promise<T>span: unknown,fn: () => Promise<T>
Runs work with the supplied span as the active OTel span, when supported.
-
activeSpanContext(): SpanContext | undefined
Reports the identifiers of the span the OTel context currently holds active, or
undefinedwhen nothing is active. -
extractContext(headers: Headers): TelemetryContext
Extracts a context from incoming headers (for traceparent propagation).
-
forceFlush(): Promise<void>
Forces flush of pending spans.
-
injectContext(context: TelemetryContext): Record<string, string>
Injects a context into outgoing headers.
-
otelProvider: unknown
The underlying OTel TracerProvider; undefined for noop/custom hosts (instrumentations then no-op).
-
shutdown(): Promise<void>
Shuts down the provider and flushes pending spans.
-
startSpan(): unknownname: string,options?: { kind?: number; attributes?: Record<string, unknown>; parentContext?: TelemetryContext; }
Starts a new span.
The kind of instrumentation to enable.
| number
| boolean
| ReadonlyArray<string | number | boolean>
Attribute value — a span attribute can be a primitive or an array of primitives.
Which span exporter to use.
The kind of span. Maps to OTel SpanKind at the implementation boundary.
Which span processor to use.
Span status — whether the span completed successfully or not.
The key used to store the active span on ctx.state.
Collects mock plugin definitions and real plugins, produces the
IPlugin[] for createTestApp, and resets between tests.
-
mock(): thisname: string,service: object,options?: { provides?: string; priority?: number; }
Registers a mock service under a capability token.
-
plugin(plugin: IPlugin): this
Stores a real plugin.
-
plugins(): IPlugin[]
Returns all plugins in true insertion order.
-
reset(): void
Clears the store. Call in
afterEachto reset between tests.
In-memory IResponse double with snapshot() and ended getter.
-
appendHeader(): IResponsename: string,value: string
Appends a response header, preserving any existing values for the same name rather than replacing them (unlike
IResponse.header, which overwrites). This is the correct way to emit multiple headers of the same name — most notably severalSet-Cookieheaders (e.g. an access cookie plus a refresh cookie, or deleting several cookies at once). - ended(): boolean
-
header(): IResponsename: string,value: string
Sets a response header.
-
html(_body: string): HandlerResult
Terminal HTML response — mirrors the kernel builder's
html(), so a test asserting on the double cannot pass where the real builder would fail. -
json<T>(_body: T): HandlerResult
Sends a JSON response.
-
redirect(): HandlerResulturl: string,_status?: number
Sends a redirect response.
-
send(_body?: Uint8Array): HandlerResult
Sends a raw byte response.
-
snapshot(): ResponseSnapshot
Returns a snapshot of the current response state (status, headers, body). Enables middleware to inspect the response after
next()returns — required for transparent response caching. -
status(code: number): IResponse
Sets the response status code.
-
stream(body: ReadableStream<Uint8Array>): HandlerResult
Sends a streaming response body.
-
text(_body: string): HandlerResult
Sends a plain-text response.
In-memory IServiceRegistry with registration recording.
-
get<T extends object>(token: CapabilityToken): T
Resolves a service by capability token.
-
getAll<T extends object>(token: CapabilityToken): readonly T[]
Resolves every provider registered for a multi-provider token.
-
has(token: CapabilityToken): boolean
Reports whether a capability is available.
-
register<T extends object>(): voidtoken: CapabilityToken,service: T,options?: RegisterOptions
Registers a service instance under a capability token.
-
registerFactory<T extends object>(): voidtoken: CapabilityToken,factory: ServiceFactory<T>,options?: RegisterOptions
Registers a lazy factory: the service is instantiated on first
getand cached for subsequent lookups. -
registrations(): ReadonlyArray<{ token: string; multi: boolean; }>
Records every
register/registerFactorycall, in order. -
unregister(token: CapabilityToken): boolean
Removes a registration. On a multi-provider token this removes EVERY provider registered under it, not just the first.
Collects a web Response body incrementally via a ReadableStream reader.
Creates an IPlugin that registers a mock service under a capability token.
Creates a started test application that can be exercised via inject()
and fetch() without binding a socket.
Builds a contract-faithful IRequestContext for unit-testing middleware
and handlers in isolation (no started app needed).
Free-function HTTP request injector with string, InjectRequest, and
web-standard Request shorthand.
Creates a plugin that REPLACES an already-provided capability with a test double, leaving the rest of the application's composition intact.
Kernel application extends IApplication with inject() capability.
-
hasPlugin(name: string): boolean
Reports whether a plugin carrying this name is pending.
-
inject(request: InjectRequest): Promise<InjectResponse>
Synthesizes an incoming request and runs it through the full pipeline without requiring a listening server.
-
unregister(name: string): boolean
Removes a pending plugin by name before the application starts.
Inject request shape for IKernelApplication.inject.
-
body: unknown
Request body (will be stringified if not a string).
-
headers: Record<string, string> | Headers
Request headers.
-
method: string
HTTP method.
-
url: string
Full request URL.
Inject response shape returned by IKernelApplication.inject.
-
body: string | null
Raw response body as text. A byte body (from
response.send(bytes)) is UTF-8 decoded;nullonly when the response genuinely has no body. -
headers: Headers
Response headers.
-
json<T>(): T
Parses the response body as JSON.
-
statusCode: number
Response status code.
Options for createMockPlugin.
-
name: string
Plugin name (also used as the capability token when
providesis absent). -
priority: number
Registration priority; passed through to the kernel resolver. Omitted when not needed (the returned plugin omits
prioritytoo). -
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.
Parsed body returned by collectStream.
-
chunks: Uint8Array[]
Individual chunks as they arrived from the stream.
-
text: string
The concatenated body decoded as UTF-8 text.
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 fromsetu.config.ts, or a starter factory's return value. -
autoStart: boolean
Whether to auto-start the application.
-
overrides: readonly IPlugin[]
Plugins to append after
withoutis applied — usuallyoverrideCapabilityresults, though anyIPluginis accepted. -
plugins: never
Not available on this arm — supply
pluginsorapp, never both. -
without: readonly string[]
Plugin names to drop before
start(), so theirregister()never runs and any eager side effect inside it never happens.
Hand-assembled arm of TestAppOptions: the test names the plugins
it wants and gets nothing else.
-
app: never
Not available on this arm — supply
pluginsorapp, never both. -
autoStart: boolean
Whether to auto-start the application.
-
overrides: never
Not available on this arm — supply
pluginsorapp, never both. -
plugins: IPlugin[]
Plugins to pre-register before
start(). Must include a runtime capability provider (RuntimePlugin()or a mock providingCAPABILITIES.RUNTIME) whenautoStartistrue— the kernel throws otherwise. -
without: never
Not available on this arm — supply
pluginsorapp, never both.
Options for createTestContext.
-
body: unknown
Body backing
json()/text()/bytes()on the mock request. -
params: Record<string, string>
Path parameters — defaults to
{}. -
query: Record<string, string>
Query string parameters — defaults to parse from the request URL's search params.
-
request: Partial<IRequest>
Partial
IRequestoverrides (method, url, headers, etc.). -
response: IResponse
Response builder — defaults to
new MockResponse(). -
runtime: IRuntimeServices
Runtime services — when absent, the internal default is used.
-
services: IServiceRegistry
Service registry — defaults to
new MockServiceRegistry(). -
signal: AbortSignal
Abort signal for
ctx.signal. Precedence isoptions.request.signal>options.signal> a live, never-abortingAbortController().signal—request.signalwins because that is the kernel's own rule (request.signal ?? NEVER_ABORT_CONTROLLER.signal). -
startTime: number
Direct
startTimeoverride — highest precedence:options.startTime ?? options.runtime?.hrtime() ?? 0. Must be a monotonic reading, neverDate.now(). -
state: Map<string, unknown>
Request-scoped state — defaults to
new Map().
Options for createTestApp.
Example 1
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 }, });
Default validation service.
-
middleware(): MiddlewareFunctionschema: unknown,target: ValidationTarget
Creates validation middleware for the given request target.
-
validate<T>(): Result<T, readonly ValidationIssue[]>schema: unknown,data: unknown
Validate
dataagainst the given schema.
Create a sanitization function that applies the given rules to each call.
Create a validation middleware function.
Framework-standard validation error formatter.
NestJS-compatible validation error formatter.
Resolve the error format configuration to a concrete formatter function.
Format validation issues as RFC 9457 Problem Details.
Sanitize a single string value with the given rules.
Validate the request body against a schema.
Validate request headers against a schema.
Validate path parameters against a schema.
Validate query parameters against a schema.
Creates the ValidationPlugin.
A single formatted error entry.
-
code: string
Optional machine-readable error code.
-
field: string
Dot-separated field path.
-
message: string
Human-readable message.
The shaped error body produced by a validation error formatter.
-
errors: readonly FormattedError[]
Array of formatted error entries.
-
message: string | string[]
Human-readable summary message (optional; present on default/nestjs, omitted on rfc7807).
Configuration for sanitizing a string value.
-
allowedTags: string[]
Keep only the listed tag names (implies
stripTagsfor non-listed tags). -
htmlEncode: boolean
Encode HTML entities (
<,>,&,",'). -
maxLength: number
Truncate the string to this many characters (applied after other transforms).
-
pattern: RegExp
Replace the entire string with an empty string if it does not match.
-
stripTags: boolean
Remove all HTML tags.
-
toLowerCase: boolean
Convert the string to lowercase.
-
toUpperCase: boolean
Convert the string to uppercase.
-
trim: boolean
Trim leading and trailing whitespace.
Options for ValidationPlugin.
-
errorFormat: ErrorFormat | ValidationErrorFormatter
Error response format. Defaults to
'default'. -
forbidNonWhitelisted: boolean
When true, reject payloads carrying properties the schema does not declare.
-
whitelist: boolean
When true, strip properties the schema does not declare.
The built-in error format identifiers for @setu-ts/validation-plugin.
A function that formats validation issues into a structured error body.
Format validation issues as RFC 7807 Problem Details.
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.
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.
Renders a view component with the given props and writes the result as the request's HTML response.
Creates the ViewPlugin.
| { readonly engine: "hono-html"; }
| { readonly engine: "custom"; readonly view: IViewEngine; }
Selects the view engine the plugin registers under CAPABILITIES.VIEW.
Example 1
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 });
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.
A named group of connections that can be addressed as one.
-
add(conn: IWebSocketConnection): void
Adds a connection to this room.
-
broadcast(): voiddata: string | Uint8Array,options?: RoomBroadcastOptions
Sends a frame to every open member, skipping any closed member and any member named by
options.except. -
broadcastJson<T>(): voidpayload: T,options?: RoomBroadcastOptions
Serializes a value to JSON once and broadcasts it as a text frame.
-
broadcastLocal(): voiddata: string | Uint8Array,options?: LocalBroadcastOptions
Sends a frame to this replica's own members only, without forwarding it to the backplane.
-
name(): string
The room name.
-
rawSize(): number
Total membership including connections that have since closed.
-
remove(conn: IWebSocketConnection): void
Removes a connection from this room.
-
size(): number
Number of currently open members.
Owns the set of live rooms, creating them on demand and dropping them once empty.
-
clear(): void
Discards every room.
-
deliverRemote(): voidname: string,data: string | Uint8Array,exceptId?: string
Delivers a frame that arrived from another replica to this replica's local members.
-
evict(conn: IWebSocketConnection): void
Removes a connection from every room it belongs to, then discards any room left empty.
-
get(name: string): Room
Returns the named room, creating it on first use.
-
peek(name: string): Room | undefined
Returns the named room if one already exists, without creating it.
-
size(): number
Number of live rooms.
A live WebSocket connection.
-
close(): voidcode?: number,reason?: string
Closes the connection. Idempotent.
-
data(): Map<string, unknown>
Per-connection application state, the socket-lifetime analogue of
IRequestContext.state. Use it to attach an authenticated user id, a tenant, or any value later handlers and broadcasts need. -
id(): string
Unique connection ID (from
runtime.uuid()). -
isOpen(): boolean
Whether the connection is still writable.
-
lastSeenAt(): number
The monotonic timestamp of the most recent inbound frame. Compared against another
runtime.hrtime()reading — never against a wall clock. -
markClosed(): void
Marks the connection closed without touching the transport — used when the peer closed first, so the socket is already gone.
-
participatesInHeartbeat(): boolean
Whether the shared heartbeat sweeper should include this connection. When
false, the sweeper skips both the payload send and idle eviction. -
path(): string
The path this connection was opened on.
-
readyState(): WebSocketReadyState
Current lifecycle state.
-
send(data: string | Uint8Array): void
Sends a frame to this peer.
-
sendJson<T>(payload: T): void
Serializes a value to JSON and sends it as a text frame.
-
touch(now: number): void
Records that a frame arrived, resetting the idle countdown.
The WebSocket hub.
-
available(): boolean
Whether the underlying HTTP adapter can perform WebSocket upgrades.
-
closeAll(): void
Closes every connection and stops the heartbeat. Called from the plugin's shutdown hook (AI_GUIDELINES §14.5).
-
connectionCount(): number
Current number of open connections across all routes.
-
createUpgradeRouter(): (request: Request) => Promise<WebSocketUpgradeDecision | null>
The router handed to the HTTP adapter. Matches the request against the route table, applies admission control, and builds the sink the adapter binds its native socket into.
-
deliverRemoteFrame(frame: RealtimeFrame): void
Delivers a frame that arrived from another replica to this replica's local room members.
-
peek(name: string): WebSocketRoom | undefined
Returns the named room if one already exists, without creating it.
-
replaceIngressBehaviors(behaviors: readonly IIngressBehavior[]): void
Replaces the plugin-level ingress chain around
onMessagewith the resolved declared sequence. -
room(name: string): WebSocketRoom
Returns the named room, creating it on first use.
-
roomCount(): number
Current number of live rooms.
-
route(): voidpath: string,handlers: WebSocketHandlers,options?: WebSocketRouteOptions
Registers a WebSocket route. Paths match exactly; the query string is ignored for matching and exposed to
onOpeninstead. -
routeCount(): number
Number of registered routes — reported by the health indicator.
-
routeUpgrade(): Promise<WebSocketUpgradeDecision | null>request: Request,principal?: IPrincipal
The upgrade router the kernel terminal handler consults after the middleware pipeline has run without short-circuiting.
The registered WebSocket routes.
-
add(): voidpath: string,handlers: WebSocketHandlers,options?: WebSocketRouteOptions
Registers a route.
-
match(request: Request): WsRouteMatch | null
Matches an upgrade request.
-
size(): number
Number of registered routes.
Builds the context handed to onOpen from the upgrade request.
Measures an inbound frame in bytes.
Parses a Sec-WebSocket-Protocol header into its comma-separated tokens.
Applies defaults and rejects a configuration that cannot work.
Selects the subprotocol to echo for a route.
Creates the WebSocketPlugin.
Configuration for the sweeper.
-
heartbeatMs: number
Tick interval in milliseconds;
0disables the sweeper entirely. -
heartbeatPayload: string
The text frame sent on each tick.
-
idleTimeoutMs: number
Inbound silence in milliseconds after which a connection is closed;
0disables.
A live WebSocket connection, as seen by application code.
-
close(): voidcode?: number,reason?: string
Closes the connection. Idempotent.
-
data: Map<string, unknown>
Per-connection application state, the socket-lifetime analogue of
IRequestContext.state. Use it to attach an authenticated user id, a tenant, or any value later handlers and broadcasts need. -
id: string
Unique connection ID (from
runtime.uuid()). -
isOpen: boolean
Whether the connection is still writable.
-
path: string
The path this connection was opened on.
-
readyState: WebSocketReadyState
Current lifecycle state.
-
send(data: string | Uint8Array): void
Sends a frame to this peer.
-
sendJson<T>(payload: T): void
Serializes a value to JSON and sends it as a text frame.
Service contract for the WebSocket hub — registered by the WebSocketPlugin
under CAPABILITIES.WEBSOCKET.
-
available: boolean
Whether the underlying HTTP adapter can perform WebSocket upgrades.
-
connectionCount: number
Current number of open connections across all routes.
-
peek(name: string): WebSocketRoom | undefined
Returns the named room if one already exists, without creating it.
-
room(name: string): WebSocketRoom
Returns the named room, creating it on first use.
-
roomCount: number
Current number of live rooms.
-
route(): voidpath: string,handlers: WebSocketHandlers,options?: WebSocketRouteOptions
Registers a WebSocket route. Paths match exactly; the query string is ignored for matching and exposed to
onOpeninstead. -
routeUpgrade(): Promise<WebSocketUpgradeDecision | null>request: Request,principal?: IPrincipal
Consults the internal upgrade router for an inbound request. Used by the kernel terminal handler to decide whether to upgrade after the middleware pipeline runs.
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).
-
close(): voidcode?: number,reason?: string
Closes the socket.
-
readyState: WebSocketReadyState
Current lifecycle state of the underlying socket.
-
send(data: string | Uint8Array): void
Sends a frame to the peer. A
stringis sent as a text frame, aUint8Arrayas a binary frame.
Options for Room.broadcastLocal.
-
exceptId: string
Skip the member with this connection ID.
Options for a room broadcast.
-
except: IWebSocketConnection
A member to skip — typically the sender, so it does not echo to itself.
Notified whenever a connection joins or leaves a Room.
-
onJoin(conn: IWebSocketConnection): void
Called when a connection is added to a room it was not already in.
-
onLeave(conn: IWebSocketConnection): void
Called when a connection is removed from a room it was in — whether by an explicit
Room.removeor by being dropped mid-broadcast.
Payload of a WebSocket close, normalized across runtimes.
-
code: number
The RFC 6455 close code (e.g.
1000normal,1001going away). -
reason: string
The close reason; an empty string when the peer supplied none.
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.userthroughIWebSocketService.routeUpgrade; omitted when the upgrade was not authenticated. Read this inonOpento identify the peer rather than re-deriving it from the headers.
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.
-
onClose(event: WebSocketCloseEvent): void
Called once, when the socket closes for any reason.
-
onError(error: Error): void
Called when the socket reports a transport-level error. A socket that errors is also expected to close, so implementations must tolerate
WebSocketEventSink.onClosearriving afterwards. -
onMessage(data: string | Uint8Array): void
Called for every inbound frame.
-
onOpen(transport: IWebSocketTransport): void
Called once, when the socket is live and writable.
The lifecycle callbacks an application supplies per WebSocket route.
-
onClose(): void | Promise<void>conn: IWebSocketConnection,event: WebSocketCloseEvent
Called once, when the connection closes for any reason.
-
onError(): void | Promise<void>conn: IWebSocketConnection,error: Error
Called on a transport error, and on a rejected promise from any other callback.
-
onMessage(): void | Promise<void>conn: IWebSocketConnection,data: string | Uint8Array
Called for every inbound frame.
-
onOpen(): void | Promise<void>conn: IWebSocketConnection,context: WebSocketConnectionContext
Called once per connection, after the handshake completes.
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 (IIngressBehaviorin@setu-ts/common). -
heartbeatMs: number
Interval in milliseconds at which
WebSocketPluginOptions.heartbeatPayloadis 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 whenWebSocketPluginOptions.heartbeatMsis above0. -
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 code1009(message too big) and is never delivered toonMessage. -
routes: readonly WebSocketRouteEntry[]
Routes registered declaratively, as an alternative to calling
service.route(...)imperatively afterstart(). Each entry — instance orRegistryFactory— produces oneroute()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
infoline at registration when no realtime backplane is registered, stating that rooms broadcast in-process only. Defaults totrue.
A named broadcast group of connections — the bidirectional analogue of the SSE plugin's channels.
-
add(conn: IWebSocketConnection): void
Adds a connection to this room.
-
broadcast(): voiddata: string | Uint8Array,options?: RoomBroadcastOptions
Sends a frame to every open member, skipping any closed member and any member named by
options.except. -
broadcastJson<T>(): voidpayload: T,options?: RoomBroadcastOptions
Serializes a value to JSON once and broadcasts it as a text frame.
-
name: string
The room name.
-
remove(conn: IWebSocketConnection): void
Removes a connection from this room.
-
size: number
Number of currently open members.
The declarative form of one IWebSocketService.route() call — the entry
an application writes instead of calling route() imperatively after
start().
-
handlers: WebSocketHandlers
The lifecycle callbacks, exactly as the imperative
route()accepts. -
options: WebSocketRouteOptions
Per-route configuration, including the route's upgrade guards.
-
path: string
The exact URL path to accept upgrades on (e.g.
/ws/chat).
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-Protocolmatches none of them is rejected with 400. When omitted, no protocol is negotiated and none is echoed.
One registered WebSocket route.
-
handlers: WebSocketHandlers
The application's lifecycle callbacks.
-
heartbeat: boolean
Whether this route participates in the shared heartbeat sweep. Defaults to
trueso existing routes are unaffected. -
path: string
The exact path this route serves.
-
protocols: readonly string[]
Subprotocols this route accepts, empty when none are configured.
Forwards a local broadcast to peers on other replicas.
Lifecycle state of a WebSocket, normalized across runtimes to names rather than the numeric codes the web API uses.
| RegistryFactory<WebSocketRouteDefinition>
One entry of WebSocketPluginOptions.routes: a route definition,
or a RegistryFactory producing one when the handlers need a
resolved capability.
| { readonly accept: false; readonly status: number; }
What an HTTP adapter should do with an inbound upgrade request, as decided
by the WebSocketUpgradeRouter.
Consulted by an HTTP adapter for every inbound WebSocket upgrade request.
| { readonly matched: false; readonly status: number; }
The outcome of matching an upgrade request against the table.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
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.
-
code: number | null
The exit code the runtime reported, or
nullwhen it reported none. -
taskModule: string
The task-module specifier the abandoned task belonged to.
The worker pool service registered under CAPABILITIES.WORKER_POOL.
-
run<TInput, TOutput>(): Promise<TOutput>taskModule: string,input: TInput,options?: WorkerRunOptions
Runs a task on the pool for
taskModule, creating it lazily. -
shutdown(): Promise<void>
Shuts down every pool (terminating workers, rejecting pending tasks). Safe to call more than once.
-
stats(): readonly TaskPoolStats[]
Returns a snapshot of every pool created so far.
Thrown by run() when the pool's pending queue is at its bound, shedding
the task instead of growing memory without limit.
-
limit: number
The configured queue bound.
-
taskModule: string
The task-module specifier whose pool queue is full.
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.
-
remoteName: string
The remote error's
name. -
remoteStack: string
The remote error's
stack, when the worker provided one. -
taskModule: string
The task-module specifier the failing task belonged to.
Thrown by run() when a task exceeds its timeout. The worker running the
task is terminated and replaced — in-flight JavaScript cannot be cancelled.
-
taskModule: string
The task-module specifier the timed-out task belonged to.
-
timeoutMs: number
The timeout that elapsed, in milliseconds.
Creates the WorkerPoolPlugin.
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.0disables the timeout.
Options for WorkerPoolPlugin.
-
defaultPoolSize: number
Default workers per pool. Defaults to the host's
availableParallelism(). -
host: IWorkerHost
Injected worker host, taking precedence over the runtime's
IRuntimeServices.workers. Intended for tests and custom transports. -
maxQueue: number
Default pending-queue bound per pool. Defaults to 1024.
-
pools: Readonly<Record<string, TaskPoolOptions>>
Per-task-module overrides, keyed by the specifier passed to
run(). -
taskTimeoutMs: number
Default task timeout in milliseconds. Defaults to 30 000;
0disables. A worker whose task times out is terminated and replaced.