@amqp-contract/contract
@amqp-contract/contract
Type Aliases
AnySchema
type AnySchema = StandardSchemaV1;Defined in: types.ts:14
Any schema that conforms to Standard Schema v1.
This library supports any validation library that implements the Standard Schema v1 specification, including Zod, Valibot, and ArkType. This allows you to use your preferred validation library while maintaining type safety.
See
https://github.com/standard-schema/standard-schema
BaseExchangeDefinition
type BaseExchangeDefinition<TName> = object;Defined in: types.ts:410
Base definition of an AMQP exchange.
An exchange receives messages from publishers and routes them to queues based on the exchange type and routing rules. This type contains properties common to all exchange types.
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
arguments? | Record<string, unknown> | Additional AMQP arguments for advanced configuration. Common arguments include alternate-exchange for handling unroutable messages. | types.ts:437 |
autoDelete? | boolean | If true, the exchange is deleted when all queues have finished using it. | types.ts:425 |
durable? | boolean | If true, the exchange survives broker restarts. Durable exchanges are persisted to disk. Default true | types.ts:420 |
internal? | boolean | If true, the exchange cannot be directly published to by clients. It can only receive messages from other exchanges via exchange-to-exchange bindings. | types.ts:431 |
name | TName | The name of the exchange. Must be unique within the RabbitMQ virtual host. | types.ts:414 |
BindingDefinition
type BindingDefinition =
| QueueBindingDefinition
| ExchangeBindingDefinition;Defined in: types.ts:885
Union type of all binding definitions.
A binding can be either:
- Queue-to-exchange binding: Routes messages from an exchange to a queue
- Exchange-to-exchange binding: Forwards messages from one exchange to another
BindingPattern
type BindingPattern<S> = S extends "" ? never : S;Defined in: builder/routing-types.ts:52
Type-safe binding pattern that validates basic format and wildcards.
Validates that a binding pattern follows basic AMQP binding pattern rules:
- Can contain wildcards (* for one word, # for zero or more words)
- Must not be empty
- Should contain alphanumeric characters, dots, hyphens, underscores, and wildcards
Note: Full character-by-character validation is not performed to avoid TypeScript recursion depth limits. Runtime validation is still recommended.
Type Parameters
| Type Parameter | Description |
|---|---|
S extends string | The binding pattern string to validate |
Example
type ValidPattern = BindingPattern<"order.*">; // "order.*"
type ValidHash = BindingPattern<"order.#">; // "order.#"
type ValidConcrete = BindingPattern<"order.created">; // "order.created"
type Invalid = BindingPattern<"">; // never (empty string)BridgedPublisherConfig
type BridgedPublisherConfig<TMessage, TBridgeExchange, TTargetExchange> = object;Defined in: builder/command.ts:62
Configuration for a bridged command publisher.
A bridged publisher publishes to a bridge exchange (local domain), which forwards messages to the target exchange (remote domain) via an exchange-to-exchange binding.
Type Parameters
| Type Parameter | Description |
|---|---|
TMessage extends MessageDefinition | The message definition |
TBridgeExchange extends ExchangeDefinition | The bridge (local domain) exchange definition |
TTargetExchange extends ExchangeDefinition | The target (remote domain) exchange definition |
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
[brand] | readonly | "BridgedPublisherConfig" | Discriminator to identify this as a bridged publisher config | builder/command.ts:68 |
bridgeExchange | public | TBridgeExchange | The bridge (local domain) exchange | builder/command.ts:74 |
exchangeBinding | public | ExchangeBindingDefinition | The exchange-to-exchange binding (bridge → target) | builder/command.ts:72 |
publisher | public | PublisherDefinition<TMessage> | The publisher definition (publishes to bridge exchange) | builder/command.ts:70 |
targetExchange | public | TTargetExchange | The target (remote domain) exchange | builder/command.ts:76 |
BridgedPublisherConfigBase
type BridgedPublisherConfigBase = object;Defined in: types.ts:1031
Base type for bridged publisher configuration.
A bridged publisher publishes to a bridge exchange, which forwards messages to the target exchange via an exchange-to-exchange binding.
See
defineCommandPublisher with bridgeExchange option
Properties
| Property | Modifier | Type | Defined in |
|---|---|---|---|
[brand] | readonly | "BridgedPublisherConfig" | types.ts:1032 |
bridgeExchange | public | ExchangeDefinition | types.ts:1035 |
exchangeBinding | public | ExchangeBindingDefinition | types.ts:1034 |
publisher | public | PublisherDefinition | types.ts:1033 |
targetExchange | public | ExchangeDefinition | types.ts:1036 |
ClassicQueueDefinition
type ClassicQueueDefinition<TName> = BaseQueueDefinition<TName> & object;Defined in: types.ts:651
Definition of a classic queue.
Classic queues are the traditional RabbitMQ queue type. Use them when you need specific features not supported by quorum queues (e.g., exclusive queues, auto-deleting queues, priority queues).
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
autoDelete? | boolean | If true, the queue is deleted when the last consumer unsubscribes. | types.ts:671 |
durable | boolean | If true, the queue survives broker restarts. Durable queues are persisted to disk. | types.ts:660 |
exclusive? | boolean | If true, the queue can only be used by the declaring connection and is deleted when that connection closes. Exclusive queues are private to the connection. | types.ts:666 |
maxPriority? | number | Maximum priority level for priority queue (1-255, recommended: 1-10). Sets x-max-priority argument. | types.ts:677 |
type | "classic" | Queue type discriminator: classic queue. | types.ts:655 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
ClassicQueueOptions
type ClassicQueueOptions = BaseQueueOptions & object;Defined in: types.ts:358
Options for creating a classic queue.
Classic queues support all traditional RabbitMQ features including:
exclusive- For connection-scoped queuesautoDelete- For auto-deleting queues when consumers disconnectmaxPriority- For priority queuesdurable: false- For non-durable queues
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
autoDelete? | boolean | If true, the queue is deleted when the last consumer unsubscribes. | types.ts:379 |
durable? | boolean | If true, the queue survives broker restarts. Durable queues are persisted to disk. Default true | types.ts:368 |
exclusive? | boolean | If true, the queue can only be used by the declaring connection and is deleted when that connection closes. Exclusive queues are private to the connection. | types.ts:374 |
maxPriority? | number | Maximum priority level for priority queue (1-255, recommended: 1-10). Sets x-max-priority argument. | types.ts:385 |
type | "classic" | Queue type: classic (for special cases) | types.ts:362 |
Example
const priorityQueue = defineQueue('tasks', {
type: 'classic',
maxPriority: 10,
});CommandConsumerConfig
type CommandConsumerConfig<TMessage, TExchange, TRoutingKey, TQueue> = object;Defined in: builder/command.ts:30
Configuration for a command consumer.
Commands are sent by one or more publishers to a single consumer (task queue pattern). The consumer "owns" the queue, and publishers send commands to it.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TMessage extends MessageDefinition | - | The message definition |
TExchange extends ExchangeDefinition | - | The exchange definition |
TRoutingKey extends string | undefined | undefined | The routing key type (undefined for fanout and headers exchanges) |
TQueue extends QueueDefinition | QueueDefinition | - |
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
[brand] | readonly | "CommandConsumerConfig" | Discriminator to identify this as a command consumer config | builder/command.ts:37 |
binding | public | QueueBindingDefinition | The binding connecting the queue to the exchange | builder/command.ts:41 |
consumer | public | ConsumerDefinition<TMessage> | The consumer definition for processing commands | builder/command.ts:39 |
exchange | public | TExchange | The exchange that receives commands | builder/command.ts:43 |
message | public | TMessage | The message definition | builder/command.ts:47 |
queue | public | TQueue | The queue this consumer reads from | builder/command.ts:45 |
routingKey | public | TRoutingKey | The routing key pattern for the binding | builder/command.ts:49 |
CommandConsumerConfigBase
type CommandConsumerConfigBase = object;Defined in: types.ts:995
Base type for command consumer configuration.
This is a simplified type used in ContractDefinition. The full generic type is defined in the builder module.
See
defineCommandConsumer for creating command consumers
Properties
| Property | Modifier | Type | Defined in |
|---|---|---|---|
[brand] | readonly | "CommandConsumerConfig" | types.ts:996 |
binding | public | QueueBindingDefinition | types.ts:998 |
consumer | public | ConsumerDefinition | types.ts:997 |
exchange | public | ExchangeDefinition | types.ts:999 |
message | public | MessageDefinition | types.ts:1001 |
queue | public | QueueDefinition | types.ts:1000 |
routingKey | public | string | undefined | types.ts:1002 |
CompressionAlgorithm
type CompressionAlgorithm = "gzip" | "deflate";Defined in: types.ts:201
Supported compression algorithms for message payloads.
gzip: GZIP compression (standard, widely supported, good compression ratio)deflate: DEFLATE compression (faster than gzip, slightly less compression)
Compression is configured at runtime via PublishOptions when calling AmqpClient.publish, not at publisher definition time.
When compression is enabled, the message payload is compressed before publishing and automatically decompressed when consuming. The content-encoding AMQP message property is set to indicate the compression algorithm used.
To disable compression, simply omit the compression option (it's optional).
Example
// Define a publisher without compression configuration
const orderCreatedPublisher = definePublisher(exchange, message, {
routingKey: "order.created",
});
// Later, choose whether to compress at publish time
await client.publish("orderCreated", payload, {
compression: "gzip",
});ConsumerDefinition
type ConsumerDefinition<TMessage> = object;Defined in: types.ts:956
Definition of a message consumer.
A consumer receives and processes messages from a queue with automatic schema validation. The message payload is validated against the schema before being passed to your handler. If the message is compressed (indicated by the content-encoding header), it will be automatically decompressed before validation.
Example
const consumer: ConsumerDefinition = {
queue: orderProcessingQueue,
message: orderMessage
};Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TMessage extends MessageDefinition | MessageDefinition | The message definition with payload schema |
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
message | TMessage | The message definition including the payload schema | types.ts:961 |
queue | QueueDefinition | The queue to consume messages from | types.ts:958 |
ConsumerEntry
type ConsumerEntry =
| ConsumerDefinition
| EventConsumerResultBase
| CommandConsumerConfigBase;Defined in: types.ts:1201
Consumer entry that can be passed to defineContract's consumers section.
Can be either:
- A plain ConsumerDefinition from defineConsumer
- An EventConsumerResult from defineEventConsumer (binding auto-extracted)
- A CommandConsumerConfig from defineCommandConsumer (binding auto-extracted)
ContractDefinition
type ContractDefinition = object;Defined in: types.ts:1131
Complete AMQP contract definition (output type).
A contract brings together all AMQP resources into a single, type-safe definition. It defines the complete messaging topology including exchanges, queues, bindings, publishers, and consumers.
The contract is used by:
- Clients (TypedAmqpClient) for type-safe message publishing
- Workers (TypedAmqpWorker) for type-safe message consumption
- AsyncAPI generator for documentation
Example
const contract: ContractDefinition = {
exchanges: {
orders: ordersExchange,
},
queues: {
orderProcessing: orderProcessingQueue,
},
bindings: {
orderBinding: orderQueueBinding,
},
publishers: {
orderCreated: orderCreatedPublisher,
},
consumers: {
processOrder: processOrderConsumer,
},
};Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
bindings? | Record<string, BindingDefinition> | Named binding definitions. Bindings can be queue-to-exchange or exchange-to-exchange. | types.ts:1152 |
consumers? | Record<string, ConsumerDefinition> | Named consumer definitions. Each key requires a corresponding handler in the TypedAmqpWorker. The handler will be fully typed based on the message schema. | types.ts:1166 |
exchanges? | Record<string, ExchangeDefinition> | Named exchange definitions. Each key becomes available as a named resource in the contract. | types.ts:1136 |
publishers? | Record<string, PublisherDefinition> | Named publisher definitions. Each key becomes a method on the TypedAmqpClient for publishing messages. The method will be fully typed based on the message schema. | types.ts:1159 |
queues? | Record<string, QueueDefinition> | Named queue definitions. Each key becomes available as a named resource in the contract. Queues with TTL-backoff retry configured are plain QueueDefinitions; their wait queues are derived and declared at topology-setup time, not stored in the contract. | types.ts:1146 |
rpcs? | Record<string, RpcDefinition> | Named RPC definitions. Each key gets: - A handler in the TypedAmqpWorker that returns the typed response. - A client.call(name, request, options) method on the TypedAmqpClient. RPC entries do not appear in publishers or consumers because each end of an RPC plays both roles (publisher of one direction, consumer of the other). | types.ts:1177 |
ContractDefinitionInput
type ContractDefinitionInput = object;Defined in: types.ts:1230
Contract definition input type with automatic extraction of event/command patterns.
Users only define publishers and consumers. Exchanges, queues, and bindings are automatically extracted from these definitions.
Example
const contract = defineContract({
publishers: {
// EventPublisherConfig → auto-extracted to publisher
orderCreated: defineEventPublisher(ordersExchange, orderMessage, { routingKey: "order.created" }),
},
consumers: {
// CommandConsumerConfig → auto-extracted to consumer + binding
processOrder: defineCommandConsumer(orderQueue, ordersExchange, orderMessage, { routingKey: "order.process" }),
// EventConsumerResult → auto-extracted to consumer + binding
notify: defineEventConsumer(orderCreatedEvent, notificationQueue),
},
});See
defineContract - Processes this input and returns a ContractDefinition
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
bindings? | Record<string, BindingDefinition> | Standalone bindings — e.g. binding a declared DLQ to the dead-letter exchange. Keys are used verbatim as the binding labels in the output. | types.ts:1278 |
consumers? | Record<string, ConsumerEntry> | Named consumer definitions. Can accept: - ConsumerDefinition from defineConsumer - EventConsumerResult from defineEventConsumer (binding auto-extracted) - CommandConsumerConfig from defineCommandConsumer (binding auto-extracted) | types.ts:1248 |
exchanges? | Record<string, ExchangeDefinition> | Standalone exchanges — topology this service asserts without publishing to it (e.g. an exchange owned by another domain that bindings reference). Keys are authoring labels; the contract output keys exchanges by name. | types.ts:1262 |
publishers? | Record<string, PublisherEntry> | Named publisher definitions. Can accept: - PublisherDefinition from definePublisher - EventPublisherConfig from defineEventPublisher (auto-extracted to publisher) | types.ts:1238 |
queues? | Record<string, QueueDefinition> | Standalone queues — queues with no consumer in this service, asserted by setupAmqpTopology all the same. The classic cases: a DLQ bound to the auto-extracted dead-letter exchange, or an audit queue that another process drains. Dead-letter exchanges are auto-extracted exactly as for consumer queues. Keys are authoring labels; the contract output keys queues by name. | types.ts:1272 |
rpcs? | Record<string, RpcDefinition> | Named RPC definitions from defineRpc. Each entry contributes its queue (and DLX if any) to the contract topology and exposes a typed client.call(name, ...) / worker handler pair. | types.ts:1255 |
ContractOutput
type ContractOutput<TContract> = object;Defined in: types.ts:1601
Contract output type with all resources extracted and properly typed.
This type represents the fully expanded contract with:
- exchanges: Extracted from publishers and consumer bindings, plus standalone declarations
- queues: Extracted from consumers and RPCs, plus standalone declarations
- bindings: Extracted from event/command consumers, plus standalone declarations
- publishers: Normalized publisher definitions
- consumers: Normalized consumer definitions
Type Parameters
| Type Parameter |
|---|
TContract extends ContractDefinitionInput |
Properties
| Property | Type | Defined in |
|---|---|---|
bindings | TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractBindingsFromConsumers<TContract["consumers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractExchangeBindingsFromConsumers<TContract["consumers"]> : object & TContract["publishers"] extends Record<string, PublisherEntry> ? ExtractExchangeBindingsFromPublishers<TContract["publishers"]> : object & TContract["bindings"] extends Record<string, BindingDefinition> ? TContract["bindings"] : object | types.ts:1635 |
consumers | TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractConsumerDefinitions<TContract["consumers"]> : object | types.ts:1648 |
exchanges | TContract["publishers"] extends Record<string, PublisherEntry> ? ExtractExchangesFromPublishers<TContract["publishers"]> : object & TContract["exchanges"] extends Record<string, ExchangeDefinition> ? ExtractStandaloneExchanges<TContract["exchanges"]> : object & TContract["queues"] extends Record<string, QueueDefinition> ? ExtractDeadLetterExchangesFromStandaloneQueues<TContract["queues"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractExchangesFromConsumers<TContract["consumers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractDeadLetterExchangesFromConsumers<TContract["consumers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractBridgeExchangesFromConsumers<TContract["consumers"]> : object & TContract["publishers"] extends Record<string, PublisherEntry> ? ExtractTargetExchangesFromPublishers<TContract["publishers"]> : object & TContract["rpcs"] extends Record<string, RpcDefinition> ? ExtractDeadLetterExchangesFromRpcs<TContract["rpcs"]> : object | types.ts:1602 |
publishers | TContract["publishers"] extends Record<string, PublisherEntry> ? ExtractPublisherDefinitions<TContract["publishers"]> : object | types.ts:1645 |
queues | TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractQueuesFromConsumers<TContract["consumers"]> : object & TContract["rpcs"] extends Record<string, RpcDefinition> ? ExtractQueuesFromRpcs<TContract["rpcs"]> : object & TContract["queues"] extends Record<string, QueueDefinition> ? ExtractStandaloneQueues<TContract["queues"]> : object | types.ts:1626 |
rpcs | TContract["rpcs"] extends Record<string, RpcDefinition> ? TContract["rpcs"] : object | types.ts:1651 |
DeadLetterConfig
type DeadLetterConfig = object;Defined in: types.ts:534
Configuration for dead letter exchange (DLX) on a queue.
When a message in a queue is rejected, expires, or exceeds the queue length limit, it can be automatically forwarded to a dead letter exchange for further processing or storage.
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
exchange | ExchangeDefinition | The exchange to send dead-lettered messages to. This exchange must be declared in the contract. | types.ts:539 |
externalConsumers? | boolean | Declares that the queue bound to this dead-letter exchange lives outside this contract — another service, or infrastructure-as-code, owns it. defineContract otherwise requires a declared binding from the exchange, because a dead-letter exchange with nothing bound to it discards every message routed to it, exactly as silently as an unroutable publish. Named to match PublisherDefinition.externalConsumers: the concept is identical — the consuming side is not this contract's to declare. | types.ts:558 |
routingKey? | string | Optional routing key to use when forwarding messages to the dead letter exchange. If not specified, the original message routing key is used. | types.ts:545 |
DefineQueueOptions
type DefineQueueOptions =
| QuorumQueueOptions
| ClassicQueueOptions;Defined in: types.ts:395
Options for defining a queue. Uses a discriminated union based on the type property to enforce quorum queue constraints at compile time.
- Quorum queues (default): Do not support
exclusive,autoDelete, ormaxPriority - Classic queues: Support all options including
exclusive,autoDelete, andmaxPriority
DefineQueueOptionsWithDeadLetterExchange
type DefineQueueOptionsWithDeadLetterExchange<TDlx> = DefineQueueOptions & object;Defined in: types.ts:400
Options for defining a queue with a dead letter exchange.
Type Declaration
| Name | Type | Defined in |
|---|---|---|
deadLetter | object | types.ts:402 |
deadLetter.exchange | TDlx | types.ts:402 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TDlx extends ExchangeDefinition | ExchangeDefinition |
DirectExchangeDefinition
type DirectExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;Defined in: types.ts:475
A direct exchange definition.
Direct exchanges route messages to queues based on exact routing key matches. This is ideal for point-to-point messaging where each message should go to specific queues.
Type Declaration
| Name | Type | Defined in |
|---|---|---|
type | "direct" | types.ts:477 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
Example
const tasksExchange: DirectExchangeDefinition = defineExchange('tasks', {
type: 'direct',
});EventConsumerResult
type EventConsumerResult<TMessage, TExchange, TQueue, TExchangeBinding, TBridgeExchange> = object;Defined in: builder/event.ts:72
Result from defineEventConsumer.
Contains the consumer definition and binding needed to subscribe to an event. Can be used directly in defineContract's consumers section - the binding will be automatically extracted.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TMessage extends MessageDefinition | - | The message definition |
TExchange extends ExchangeDefinition | ExchangeDefinition | - |
TQueue extends QueueDefinition | QueueDefinition | - |
TExchangeBinding extends ExchangeBindingDefinition | undefined | ExchangeBindingDefinition | undefined | - |
TBridgeExchange extends ExchangeDefinition | undefined | ExchangeDefinition | undefined | - |
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
[brand] | readonly | "EventConsumerResult" | Discriminator to identify this as an event consumer result | builder/event.ts:82 |
binding | public | QueueBindingDefinition | The binding connecting the queue to the exchange | builder/event.ts:86 |
bridgeExchange | public | TBridgeExchange | The bridge (local domain) exchange when bridging, if configured | builder/event.ts:94 |
consumer | public | ConsumerDefinition<TMessage> | The consumer definition for processing messages | builder/event.ts:84 |
exchange | public | TExchange | The source exchange this consumer subscribes to | builder/event.ts:88 |
exchangeBinding | public | TExchangeBinding | The exchange-to-exchange binding when bridging, if configured | builder/event.ts:92 |
queue | public | TQueue | The queue this consumer reads from | builder/event.ts:90 |
EventConsumerResultBase
type EventConsumerResultBase = object;Defined in: types.ts:1013
Base type for event consumer result.
This is a simplified type used in ContractDefinitionInput. The full generic type is defined in the builder module.
See
defineEventConsumer for creating event consumers
Properties
| Property | Modifier | Type | Defined in |
|---|---|---|---|
[brand] | readonly | "EventConsumerResult" | types.ts:1014 |
binding | public | QueueBindingDefinition | types.ts:1016 |
bridgeExchange | public | ExchangeDefinition | undefined | types.ts:1020 |
consumer | public | ConsumerDefinition | types.ts:1015 |
exchange | public | ExchangeDefinition | types.ts:1017 |
exchangeBinding | public | ExchangeBindingDefinition | undefined | types.ts:1019 |
queue | public | QueueDefinition | types.ts:1018 |
EventPublisherConfig
type EventPublisherConfig<TMessage, TExchange, TRoutingKey> = object;Defined in: builder/event.ts:30
Configuration for an event publisher.
Events are published without knowing who consumes them. Multiple consumers can subscribe to the same event. This follows the pub/sub pattern where publishers broadcast events and consumers subscribe to receive them.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TMessage extends MessageDefinition | - | The message definition |
TExchange extends ExchangeDefinition | - | The exchange definition |
TRoutingKey extends string | undefined | undefined | The routing key type (undefined for fanout and headers exchanges) |
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
[brand] | readonly | "EventPublisherConfig" | Discriminator to identify this as an event publisher config | builder/event.ts:36 |
bindingArguments? | public | Record<string, unknown> | Default AMQP binding arguments for consumers of this event. These are NOT publish arguments — they are applied to the queue binding of every defineEventConsumer of this event that does not pass its own arguments option. | builder/event.ts:50 |
exchange | public | TExchange | The exchange to publish to | builder/event.ts:38 |
externalConsumers? | public | boolean | Declares that this event's consumers live outside this contract — a separate service or deployment owns the binding. Carried onto the publisher definition that defineContract extracts, so it opts the event out of the define-time routability check. See PublisherDefinition.externalConsumers | builder/event.ts:60 |
message | public | TMessage | The message definition | builder/event.ts:40 |
routingKey | public | TRoutingKey | The routing key for direct/topic exchanges | builder/event.ts:42 |
EventPublisherConfigBase
type EventPublisherConfigBase = object;Defined in: types.ts:976
Base type for event publisher configuration.
This is a simplified type used in ContractDefinition. The full generic type is defined in the builder module.
See
defineEventPublisher for creating event publishers
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
[brand] | readonly | "EventPublisherConfig" | - | types.ts:977 |
bindingArguments? | public | Record<string, unknown> | Default binding arguments for this event's consumers (not publish arguments). | types.ts:982 |
exchange | public | ExchangeDefinition | - | types.ts:978 |
externalConsumers? | public | boolean | Opt out of the define-time routability check — see PublisherDefinition.externalConsumers. | types.ts:984 |
message | public | MessageDefinition | - | types.ts:979 |
routingKey | public | string | undefined | - | types.ts:980 |
ExchangeBindingDefinition
type ExchangeBindingDefinition = object &
| {
routingKey: string;
source: | DirectExchangeDefinition
| TopicExchangeDefinition;
}
| {
routingKey?: never;
source: | FanoutExchangeDefinition
| HeadersExchangeDefinition;
};Defined in: types.ts:849
Binding between two exchanges (exchange-to-exchange routing).
Defines how messages should be forwarded from a source exchange to a destination exchange. This allows for more complex routing topologies.
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
arguments? | Record<string, unknown> | Additional AMQP arguments for the binding. | types.ts:859 |
destination | ExchangeDefinition | The destination exchange that will receive forwarded messages | types.ts:854 |
type | "exchange" | Discriminator indicating this is an exchange-to-exchange binding | types.ts:851 |
Example
// Forward high-priority orders to a special processing exchange
const binding: ExchangeBindingDefinition = {
type: 'exchange',
source: ordersExchange,
destination: highPriorityExchange,
routingKey: 'order.high-priority.*'
};ExchangeDefinition
type ExchangeDefinition<TName> =
| TopicExchangeDefinition<TName>
| DirectExchangeDefinition<TName>
| FanoutExchangeDefinition<TName>
| HeadersExchangeDefinition<TName>;Defined in: types.ts:521
Union type of all exchange definitions.
Represents any type of AMQP exchange: topic, direct, fanout, headers.
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
FanoutExchangeDefinition
type FanoutExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;Defined in: types.ts:493
A fanout exchange definition.
Fanout exchanges broadcast all messages to all bound queues, ignoring routing keys. This is the simplest exchange type for pub/sub messaging patterns.
Type Declaration
| Name | Type | Defined in |
|---|---|---|
type | "fanout" | types.ts:495 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
Example
const logsExchange: FanoutExchangeDefinition = defineExchange('logs', {
type: 'fanout',
});HeadersExchangeDefinition
type HeadersExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;Defined in: types.ts:511
A headers exchange definition.
Headers exchanges route messages based on header values rather than routing keys. This is useful for more complex routing scenarios where metadata is important.
Type Declaration
| Name | Type | Defined in |
|---|---|---|
type | "headers" | types.ts:513 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
Example
const routesExchange: HeadersExchangeDefinition = defineExchange('routes', {
type: 'headers',
});ImmediateRequeueRetryOptions
type ImmediateRequeueRetryOptions = object;Defined in: types.ts:97
Immediate-Requeue retry options.
Failed messages are requeued immediately. For quorum queues, messages are requeued with nack(requeue=true), and the worker tracks delivery count via the native RabbitMQ x-delivery-count header. For classic queues, messages are re-published on the same queue, and the worker tracks delivery count via a custom x-retry-count header. When the count exceeds maxRetries, the message is automatically dead-lettered (if DLX is configured) or dropped.
Benefits: Simpler architecture, no wait queues needed, no head-of-queue blocking. Limitation: Immediate retries only (no exponential backoff).
See
https://www.rabbitmq.com/docs/quorum-queues#poison-message-handling
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
maxRetries? | number | Maximum retry attempts before sending to DLQ. Minimum 1 - Must be a positive integer (1 or greater) Default 3 | types.ts:107 |
mode | "immediate-requeue" | Immediate-Requeue mode. | types.ts:101 |
InferConsumerNames
type InferConsumerNames<TContract> = TContract["consumers"] extends Record<string, unknown> ? keyof TContract["consumers"] : never;Defined in: types.ts:1687
Extract consumer names from a contract.
This utility type extracts the keys of all consumers defined in a contract. It's used internally for type inference in the TypedAmqpWorker.
Type Parameters
| Type Parameter | Description |
|---|---|
TContract extends ContractDefinition | The contract definition |
Returns
Union of consumer names, or never if no consumers defined
Example
type ConsumerNames = InferConsumerNames<typeof myContract>;
// Result: 'processOrder' | 'sendNotification' | 'updateInventory'InferPublisherNames
type InferPublisherNames<TContract> = TContract["publishers"] extends Record<string, unknown> ? keyof TContract["publishers"] : never;Defined in: types.ts:1669
Extract publisher names from a contract.
This utility type extracts the keys of all publishers defined in a contract. It's used internally for type inference in the TypedAmqpClient.
Type Parameters
| Type Parameter | Description |
|---|---|
TContract extends ContractDefinition | The contract definition |
Returns
Union of publisher names, or never if no publishers defined
Example
type PublisherNames = InferPublisherNames<typeof myContract>;
// Result: 'orderCreated' | 'orderUpdated' | 'orderCancelled'InferRpcNames
type InferRpcNames<TContract> = TContract["rpcs"] extends Record<string, RpcDefinition> ? keyof TContract["rpcs"] : never;Defined in: types.ts:1699
Extract RPC names from a contract.
Each name in this union has a typed worker handler and a client.call(name, ...) method. RPC names are disjoint from InferConsumerNames and InferPublisherNames.
Type Parameters
| Type Parameter | Description |
|---|---|
TContract extends ContractDefinition | The contract definition |
Returns
Union of RPC names, or never if no RPCs defined
InferSchemaInput
type InferSchemaInput<TSchema> = TSchema extends StandardSchemaV1<infer TInput> ? TInput : never;Defined in: types.ts:24
Infer a Standard Schema's INPUT type — what callers hand to validation (publish payloads, RPC requests) before defaults and transforms run.
Canonical home of the helper the client and worker packages alias, so a contract-only package can derive payload types without depending on either: type OrderCreated = InferSchemaInput<typeof contract.publishers.orderCreated.message.payload>.
Type Parameters
| Type Parameter |
|---|
TSchema extends StandardSchemaV1 |
InferSchemaOutput
type InferSchemaOutput<TSchema> = TSchema extends StandardSchemaV1<infer _TInput, infer TOutput> ? TOutput : never;Defined in: types.ts:31
Infer a Standard Schema's OUTPUT type — what validation produces (defaults applied, transforms run); the shape handlers and RPC callers receive.
Type Parameters
| Type Parameter |
|---|
TSchema extends StandardSchemaV1 |
MatchingBindingPattern
type MatchingBindingPattern<Pattern, PublisherKey> = IsStringLiteral<Pattern> extends false ? BindingPattern<Pattern> : IsStringLiteral<PublisherKey> extends false ? BindingPattern<Pattern> : [BindingPattern<Pattern>] extends [never] ? never : MatchesPattern<PublisherKey, Pattern> extends true ? Pattern : `Error: binding pattern '${Pattern}' can never match the publisher routing key '${PublisherKey}'`;Defined in: builder/routing-types.ts:213
Binding pattern for a topic consumer, validated against the publisher's concrete routing key.
defineEventConsumer uses this on its topic overloads: a routing-key override must be a pattern that can actually match the event publisher's routing key, otherwise the binding compiles but silently receives nothing at runtime. On a mismatch this resolves to a human-readable error-message string type — so the compile error names both sides instead of collapsing to a bare never:
Type '"user.*"' is not assignable to type
"Error: binding pattern 'user.*' can never match the publisher routing key 'order.created'"The check runs only when both sides are fully known at compile time. Plain string, a template-literal type with a ${…} hole (`${string}.created`), and any union containing either are skipped: the match cannot be decided, and guessing would reject a pattern that matches at runtime. The define-time routability check in defineContract does not cover the gap this leaves: it fails a contract whose publisher reaches no queue, but it does not detect a consumer binding like this one that receives nothing while a sibling binding keeps the publisher routable. There is no compile-time or define-time backstop for that case.
Type Parameters
| Type Parameter | Description |
|---|---|
Pattern extends string | The consumer's binding pattern (can contain * and # wildcards) |
PublisherKey extends string | The publisher's concrete routing key |
MatchingRoutingKey
type MatchingRoutingKey<Pattern, Key> = RoutingKey<Key> extends never ? never : BindingPattern<Pattern> extends never ? never : IsStringLiteral<Pattern> extends false ? Key : IsStringLiteral<Key> extends false ? Key : MatchesPattern<Key, Pattern> extends true ? Key : never;Defined in: builder/routing-types.ts:171
Validate that a routing key matches a binding pattern.
This is a utility type for users who want compile-time validation that a routing key matches a specific pattern. The library enforces the same matching on defineEventConsumer's topic routing-key overrides via MatchingBindingPattern (which surfaces a readable error-message string type instead of never).
Returns the routing key when both the pattern and the key are valid (see RoutingKey and BindingPattern) and the key matches the pattern; never when either is invalid or the key does not match — so MatchingRoutingKey<"order.*", "order.*"> is never: the key matches the pattern textually, but a routing key may not itself contain a wildcard.
Each side's validity (RoutingKey for Key, BindingPattern for Pattern) is always enforced, even when the other side is not fully known — validity is decidable from one side alone. Only the match between the two is skipped when either side is not a fully known compile-time literal: plain string, a template-literal type, or a union containing either resolves to Key unchecked once both sides pass their own validity check — the match cannot be decided, and guessing would reject a key that routes at runtime.
Type Parameters
| Type Parameter | Description |
|---|---|
Pattern extends string | The binding pattern (can contain * and # wildcards) |
Key extends string | The routing key to validate |
Example
type ValidKey = MatchingRoutingKey<"order.*", "order.created">; // "order.created"
type InvalidKey = MatchingRoutingKey<"order.*", "user.created">; // neverMessageDefinition
type MessageDefinition<TPayload, THeaders> = object;Defined in: types.ts:763
Definition of a message with typed payload and optional headers.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TPayload extends AnySchema | AnySchema | The Standard Schema v1 compatible schema for the message payload |
THeaders extends | StandardSchemaV1<Record<string, unknown>> | undefined | | StandardSchemaV1<Record<string, unknown>> | undefined | The Standard Schema v1 compatible schema for the message headers (optional) |
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
description? | string | Detailed description of the message for documentation purposes. Used in AsyncAPI specification generation. | types.ts:791 |
headers? | THeaders | Optional headers schema for validating message metadata. Must be a Standard Schema v1 compatible schema. | types.ts:779 |
payload | TPayload | The payload schema for validating message content. Must be a Standard Schema v1 compatible schema (Zod, Valibot, ArkType, etc.). | types.ts:773 |
summary? | string | Brief description of the message for documentation purposes. Used in AsyncAPI specification generation. | types.ts:785 |
NoneRetryOptions
type NoneRetryOptions = object;Defined in: types.ts:114
No retry mode. Failed messages are not retried and are sent directly to DLQ (if configured) or rejected.
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
mode | "none" | None mode disables retry attempts entirely. | types.ts:118 |
PublisherDefinition
type PublisherDefinition<TMessage> = object &
| {
exchange: | DirectExchangeDefinition
| TopicExchangeDefinition;
routingKey: string;
}
| {
exchange: | FanoutExchangeDefinition
| HeadersExchangeDefinition;
routingKey?: never;
};Defined in: types.ts:907
Definition of a message publisher.
A publisher sends messages to an exchange with automatic schema validation. The message payload is validated against the schema before being sent to RabbitMQ.
Compression can be optionally applied at publish time by specifying a compression algorithm when calling the publish method.
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
externalConsumers? | boolean | Declares that this publisher's consumers live outside this contract — a separate service or deployment owns the binding. Routability cannot be verified for such a publisher, so the define-time check is skipped. This is deliberately explicit: a heuristic ("no bindings at all means external") would silently miss the mistyped-key case the check exists to catch. | types.ts:919 |
message | TMessage | The message definition including the payload schema | types.ts:909 |
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TMessage extends MessageDefinition | MessageDefinition | The message definition with payload schema |
Example
const publisher: PublisherDefinition = {
exchange: ordersExchange,
message: orderMessage,
routingKey: 'order.created'
};PublisherEntry
type PublisherEntry =
| PublisherDefinition
| EventPublisherConfigBase
| BridgedPublisherConfigBase;Defined in: types.ts:1188
Publisher entry that can be passed to defineContract's publishers section.
Can be either:
- A plain PublisherDefinition from definePublisher
- An EventPublisherConfig from defineEventPublisher (auto-extracted to publisher)
- An BridgedPublisherConfig from defineCommandPublisher (auto-extracted to publisher)
QueueBindingDefinition
type QueueBindingDefinition = object &
| {
exchange: | DirectExchangeDefinition
| TopicExchangeDefinition;
routingKey: string;
}
| {
exchange: | FanoutExchangeDefinition
| HeadersExchangeDefinition;
routingKey?: never;
};Defined in: types.ts:801
Binding between a queue and an exchange.
Defines how messages from an exchange should be routed to a queue. For direct and topic exchanges, a routing key is required. For fanout and headers exchanges, no routing key is needed.
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
arguments? | Record<string, unknown> | Additional AMQP arguments for the binding. Can be used for advanced routing scenarios with the headers exchange type. | types.ts:812 |
queue | QueueDefinition | The queue that will receive messages | types.ts:806 |
type | "queue" | Discriminator indicating this is a queue-to-exchange binding | types.ts:803 |
QueueDefinition
type QueueDefinition<TName> =
| QuorumQueueDefinition<TName>
| ClassicQueueDefinition<TName>;Defined in: types.ts:689
Definition of an AMQP queue.
A discriminated union based on queue type:
QuorumQueueDefinition: For quorum queues (type: "quorum")ClassicQueueDefinition: For classic queues (type: "classic")
Use queue.type as the discriminator to narrow the type.
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
QueueDefinitionWithDeadLetterExchange
type QueueDefinitionWithDeadLetterExchange<TName, TDlx> = QueueDefinition<TName> & object;Defined in: types.ts:750
A queue definition with a dead letter exchange.
Type Declaration
| Name | Type | Defined in |
|---|---|---|
deadLetter | object | types.ts:754 |
deadLetter.exchange | TDlx | types.ts:754 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
TDlx extends ExchangeDefinition | ExchangeDefinition |
QueueType
type QueueType = "quorum" | "classic";Defined in: types.ts:229
Supported queue types in RabbitMQ.
quorum: Quorum queues (default, recommended) - Provide better durability and high-availability using the Raft consensus algorithm. Best for most production use cases.classic: Classic queues - The traditional RabbitMQ queue type. Use only when you need specific features not supported by quorum queues (e.g., non-durable queues, priority queues).
Note: Quorum queues only support durable queues, and do not support exclusive, auto-deleting, or priority queues.
See
https://www.rabbitmq.com/docs/quorum-queues
Example
// Create a quorum queue (default, recommended)
const orderQueue = defineQueue('order-processing', {
type: 'quorum', // This is the default
});
// Create a classic queue (for special cases)
const tempQueue = defineQueue('temp-queue', {
type: 'classic',
durable: false, // Only supported with classic queues
});QuorumQueueDefinition
type QuorumQueueDefinition<TName> = BaseQueueDefinition<TName> & object;Defined in: types.ts:615
Definition of a quorum queue.
Quorum queues provide better durability and high-availability using the Raft consensus algorithm.
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
autoDelete? | never | Quorum queues do not support auto-delete mode. Use type: 'classic' if you need auto-deleting queues. | types.ts:636 |
durable | true | Quorum queues only support durable queues. | types.ts:624 |
exclusive? | never | Quorum queues do not support exclusive mode. Use type: 'classic' if you need exclusive queues. | types.ts:630 |
maxPriority? | never | Quorum queues do not support priority queues. Use type: 'classic' if you need priority queues. | types.ts:642 |
type | "quorum" | Queue type discriminator: quorum queue. | types.ts:619 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
QuorumQueueOptions
type QuorumQueueOptions = BaseQueueOptions & object;Defined in: types.ts:311
Options for creating a quorum queue.
Quorum queues do not support:
exclusive- Use classic queues for connection-scoped queuesautoDelete- Use classic queues for auto-deleting queues when consumers disconnectmaxPriority- Use classic queues for priority queuesdurable: false- Use classic queues for non-durable queues
Quorum queues provide native retry support for immediate-requeue retry mode:
- RabbitMQ tracks delivery count automatically via
x-delivery-countheader - When the limit is exceeded, messages are dead-lettered (if DLX is configured) or dropped
- This is simpler than TTL-based retry and avoids head-of-queue blocking issues
Type Declaration
| Name | Type | Description | Defined in |
|---|---|---|---|
autoDelete? | never | Quorum queues do not support auto-delete mode. Use type: 'classic' if you need auto-deleting queues. | types.ts:332 |
durable? | true | Quorum queues only support durable queues. | types.ts:320 |
exclusive? | never | Quorum queues do not support exclusive mode. Use type: 'classic' if you need exclusive queues. | types.ts:326 |
maxPriority? | never | Quorum queues do not support priority queues. Use type: 'classic' if you need priority queues. | types.ts:338 |
type? | "quorum" | Queue type: quorum (default, recommended) | types.ts:315 |
Example
const orderQueue = defineQueue('orders', {
type: 'quorum',
deadLetter: { exchange: dlx },
retry: { mode: 'immediate-requeue', maxRetries: 3 } // Message dead-lettered after 3 retry attempts
});ResolvedImmediateRequeueRetryOptions
type ResolvedImmediateRequeueRetryOptions = object;Defined in: types.ts:152
Resolved Immediate-Requeue retry options with all defaults applied.
This is what queue definitions carry after defineQueue has applied default values. All fields are required.
Properties
| Property | Type | Defined in |
|---|---|---|
maxRetries | number | types.ts:154 |
mode | "immediate-requeue" | types.ts:153 |
ResolvedRetryOptions
type ResolvedRetryOptions =
| NoneRetryOptions
| ResolvedImmediateRequeueRetryOptions
| ResolvedTtlBackoffRetryOptions;Defined in: types.ts:168
Resolved retry configuration stored in queue definitions.
This is a discriminated union based on the mode field:
none: No retry attempts are made; failed messages are handled by DLQ/rejectimmediate-requeue: Has all immediate-requeue retry options with default appliedttl-backoff: Has all TTL-backoff retry options with defaults applied
When using ttl-backoff mode, setupAmqpTopology derives and declares one wait queue per distinct backoff delay (see deriveTtlBackoffInfrastructure).
ResolvedTtlBackoffRetryOptions
type ResolvedTtlBackoffRetryOptions = object;Defined in: types.ts:137
Resolved TTL-Backoff retry options with all defaults applied.
This is what queue definitions carry after defineQueue has applied default values. All fields are required.
Properties
| Property | Type | Defined in |
|---|---|---|
backoffMultiplier | number | types.ts:142 |
initialDelayMs | number | types.ts:140 |
jitter | boolean | types.ts:143 |
maxDelayMs | number | types.ts:141 |
maxRetries | number | types.ts:139 |
mode | "ttl-backoff" | types.ts:138 |
RetryOptions
type RetryOptions =
| NoneRetryOptions
| ImmediateRequeueRetryOptions
| TtlBackoffRetryOptions;Defined in: types.ts:129
Retry configuration options.
This is a discriminated union based on the mode field:
none(default): No retry attempts are made; failed messages are handled by DLQ/rejectimmediate-requeue: Requeues failed messages immediatelyttl-backoff: Uses wait queues with exponential backoff
RoutableRoutingKey
type RoutableRoutingKey<Key, Patterns> = IsStringLiteral<Key> extends false ? Key : IsStringLiteral<Patterns> extends false ? Key : MatchesAnyPattern<Key, Patterns> extends true ? Key : `Error: routing key '${Key}' matches none of the declared binding patterns; the broker would confirm and discard every message`;Defined in: builder/routing-types.ts:268
A publisher routing key validated against the binding patterns declared on its exchange.
A message routed to zero queues is confirmed by RabbitMQ and then discarded, so an unmatched routing key is silent total message loss. On no match this resolves to a human-readable error-message string type, so the compile error explains the problem instead of collapsing to never — matching the MatchingBindingPattern convention.
Skipped (resolves to Key) when either side is non-literal, or when no patterns are declared: those cases cannot be decided at compile time and are left to the define-time check in defineContract.
Scope: single-hop queue bindings on topic and direct exchanges. Fanout, headers, and exchange-to-exchange forwards are deliberately not modelled here — deciding them needs graph traversal in the type system, which risks recursion-depth failures and false compile errors on valid contracts. Those cases fall through to the define-time check, which sees the whole graph.
Type Parameters
| Type Parameter | Description |
|---|---|
Key extends string | The publisher's concrete routing key |
Patterns extends string | Union of binding patterns declared on the exchange |
Example
type Ok = RoutableRoutingKey<"order.created", "order.#" | "user.#">; // "order.created"
type Bad = RoutableRoutingKey<"order.created", "user.#">;
// "Error: routing key 'order.created' matches none of the declared binding
// patterns; the broker would confirm and discard every message"RoutingKey
type RoutingKey<S> = S extends "" ? never : S extends `${string}*${string}` | `${string}#${string}` ? never : S;Defined in: builder/routing-types.ts:25
Type-safe routing key that validates basic format.
Validates that a routing key follows basic AMQP routing key rules:
- Must not contain wildcards (* or #)
- Must not be empty
- Should contain alphanumeric characters, dots, hyphens, and underscores
Note: Full character-by-character validation is not performed to avoid TypeScript recursion depth limits. Runtime validation is still recommended.
Type Parameters
| Type Parameter | Description |
|---|---|
S extends string | The routing key string to validate |
Example
type Valid = RoutingKey<"order.created">; // "order.created"
type Invalid = RoutingKey<"order.*">; // never (contains wildcard)
type Invalid2 = RoutingKey<"">; // never (empty string)RpcDefinition
type RpcDefinition<TRequestMessage, TResponseMessage, TQueue, TErrors> = object;Defined in: types.ts:1077
Definition of an RPC operation: a request/response pair flowing over a request queue with replies routed back via direct reply-to.
An RPC is bidirectional on both ends — the server consumes requests and publishes responses; the client publishes requests and consumes responses — so it has its own slot in the contract (rpcs) rather than being shoehorned into consumers or publishers.
See
defineRpc for creating RPC definitions
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TRequestMessage extends MessageDefinition | MessageDefinition | The request message definition |
TResponseMessage extends MessageDefinition | MessageDefinition | The response message definition |
TQueue extends QueueDefinition | QueueDefinition | The request queue entry |
TErrors extends RpcErrorMap | undefined | RpcErrorMap | undefined | The typed error map (undefined when the RPC declares none) |
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
errors? | TErrors | Typed business errors the handler may return via Err(rpcError(code, data)). Error data is validated against the declared schema on the worker before the error reply is published, and re-validated on the client when it arrives. Business errors are replied and acked — never retried. | types.ts:1095 |
queue | TQueue | The queue that receives RPC requests. Replies are routed back via direct reply-to. | types.ts:1084 |
request | TRequestMessage | Schema for the request payload (validated on both publish and consume). | types.ts:1086 |
response | TResponseMessage | Schema for the response payload (validated on both worker reply and client receive). | types.ts:1088 |
RpcErrorDefinition
type RpcErrorDefinition<TData> = object;Defined in: types.ts:1049
A single declared RPC error: the Standard Schema for its data payload, plus an optional default human-readable message.
The default message is used when the handler constructs the error without one (helpers.errors.CODE(data)) and as the client-side fallback when a reply arrives without a message on the wire.
See
defineRpc for declaring errors on an RPC
Type Parameters
| Type Parameter | Default type |
|---|---|
TData extends StandardSchemaV1 | StandardSchemaV1 |
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
data | TData | Schema validating the error's data payload (worker before replying, client on receipt). | types.ts:1051 |
message? | string | Default human-readable message when the handler does not supply one. | types.ts:1053 |
RpcErrorMap
type RpcErrorMap = Record<string, RpcErrorDefinition>;Defined in: types.ts:1059
Typed error map for an RPC: error code → RpcErrorDefinition.
TopicExchangeDefinition
type TopicExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;Defined in: types.ts:457
A topic exchange definition.
Topic exchanges route messages to queues based on routing key patterns with wildcards:
*(star) matches exactly one word#(hash) matches zero or more words
Words are separated by dots (e.g., order.created.high-value).
Type Declaration
| Name | Type | Defined in |
|---|---|---|
type | "topic" | types.ts:459 |
Type Parameters
| Type Parameter | Default type |
|---|---|
TName extends string | string |
Example
const ordersExchange: TopicExchangeDefinition = defineExchange('orders', {
type: 'topic', // This is the default type, so it can be omitted
});
// Can be bound with patterns like 'order.*' or 'order.#'TtlBackoffInfrastructure
type TtlBackoffInfrastructure = object;Defined in: types.ts:728
TTL-backoff retry infrastructure derived from a queue definition.
This is computed (never stored on the contract) by deriveTtlBackoffInfrastructure: setupAmqpTopology declares the wait queues at channel-setup time, and the worker's retry pipeline publishes the retry copy to the tier queue matching the attempt's base delay. Each wait queue dead-letters back to the main queue via the default exchange.
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
durable | boolean | Durability shared by the wait queues (mirrors the main queue). | types.ts:740 |
queueName | string | Name of the main queue messages return to after the delay. | types.ts:732 |
queueType | QueueType | Queue type shared by the wait queues (mirrors the main queue). | types.ts:736 |
waitQueues | TtlBackoffWaitQueueDefinition[] | One wait queue per distinct backoff delay, ascending by delayMs. | types.ts:744 |
TtlBackoffRetryOptions
type TtlBackoffRetryOptions = object;Defined in: types.ts:51
TTL-Backoff retry options for exponential backoff with configurable delays.
Uses the TTL + wait queue pattern. Failed messages are published to a per-delay-tier wait queue with per-message TTL, then dead-lettered back to the main queue after the TTL expires. One wait queue per distinct backoff delay means a long-delay retry never blocks a short-delay retry; within a tier, head-of-line skew is bounded by the jitter spread (zero when jitter is disabled).
Benefits: Configurable delays with exponential backoff and jitter. Limitation: More topology (one wait queue per distinct delay).
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
backoffMultiplier? | number | Exponential backoff multiplier. Default 2 | types.ts:76 |
initialDelayMs? | number | Initial delay in ms before first retry. Default 1000 | types.ts:66 |
jitter? | boolean | Add jitter to prevent thundering herd. Default true | types.ts:81 |
maxDelayMs? | number | Maximum delay in ms between retries. Default 30000 | types.ts:71 |
maxRetries? | number | Maximum retry attempts before sending to DLQ. Minimum 1 - Must be a positive integer (1 or greater) Default 3 | types.ts:61 |
mode | "ttl-backoff" | TTL-Backoff mode uses wait queues with per-message TTL for exponential backoff. | types.ts:55 |
TtlBackoffWaitQueueDefinition
type TtlBackoffWaitQueueDefinition = object;Defined in: types.ts:700
One derived TTL-backoff wait queue — a per-delay-tier holding queue.
Each distinct backoff delay in a queue's retry schedule gets its own wait queue so a long-delay retry can never block a short-delay retry behind it (RabbitMQ only dead-letters expired messages at the head of a queue).
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
delayMs | number | The tier's base backoff delay in ms (pre-jitter). | types.ts:708 |
messageTtlMs | number | Queue-level x-message-ttl backstop. With jitter enabled this is the jitter ceiling (ceil(delayMs * 1.5)); without jitter it equals delayMs. The per-message expiration carries the actual (jittered) delay; this queue-level TTL bounds head-of-line skew within the tier to the jitter spread (zero when jitter is disabled). | types.ts:716 |
name | string | Broker name of the tier's wait queue: {queueName}-wait-{delayMs}ms. | types.ts:704 |
Functions
defineCommandConsumer()
Call Signature
function defineCommandConsumer<TMessage, TQueueDefinition, TExchange>(
queue,
exchange,
message,
options?): CommandConsumerConfig<TMessage, TExchange, undefined, TQueueDefinition>;Defined in: builder/command.ts:104
Define a command consumer for receiving commands via fanout exchange.
Commands are sent by publishers to a specific queue. The consumer "owns" the queue and defines what commands it accepts.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TQueueDefinition extends QueueDefinition |
TExchange extends FanoutExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | TQueueDefinition | The queue that will receive commands |
exchange | TExchange | The fanout exchange that routes commands |
message | TMessage | The message definition (schema and metadata) |
options? | { arguments?: Record<string, unknown>; } | Optional binding configuration |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
Returns
CommandConsumerConfig<TMessage, TExchange, undefined, TQueueDefinition>
A command consumer configuration
Example
const tasksExchange = defineExchange('tasks', { type: 'fanout' });
const taskMessage = defineMessage(z.object({ taskId: z.string() }));
// Consumer owns the queue
const executeTask = defineCommandConsumer(taskQueue, tasksExchange, taskMessage);
// Publishers send commands to it
const sendTask = defineCommandPublisher(executeTask);Call Signature
function defineCommandConsumer<TMessage, TQueueDefinition, TExchange>(
queue,
exchange,
message,
options?): CommandConsumerConfig<TMessage, TExchange, undefined, TQueueDefinition>;Defined in: builder/command.ts:142
Define a command consumer for receiving commands via headers exchange.
Commands are sent by publishers to a specific queue. The consumer "owns" the queue and defines what commands it accepts.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TQueueDefinition extends QueueDefinition |
TExchange extends HeadersExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | TQueueDefinition | The queue that will receive commands |
exchange | TExchange | The headers exchange that routes commands |
message | TMessage | The message definition (schema and metadata) |
options? | { arguments?: Record<string, unknown>; } | Optional binding configuration |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
Returns
CommandConsumerConfig<TMessage, TExchange, undefined, TQueueDefinition>
A command consumer configuration
Example
const tasksExchange = defineExchange('tasks', { type: 'headers' });
const taskMessage = defineMessage(z.object({ taskId: z.string() }));
// Consumer owns the queue
const executeTask = defineCommandConsumer(taskQueue, tasksExchange, taskMessage);
// Publishers send commands to it
const sendTask = defineCommandPublisher(executeTask);Call Signature
function defineCommandConsumer<TMessage, TRoutingKey, TQueueDefinition, TExchange>(
queue,
exchange,
message,
options): CommandConsumerConfig<TMessage, TExchange, TRoutingKey, TQueueDefinition>;Defined in: builder/command.ts:181
Define a command consumer for receiving commands via direct exchange.
Commands are sent by publishers with a specific routing key that matches the binding pattern.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TQueueDefinition extends QueueDefinition |
TExchange extends DirectExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | TQueueDefinition | The queue that will receive commands |
exchange | TExchange | The direct exchange that routes commands |
message | TMessage | The message definition (schema and metadata) |
options | { arguments?: Record<string, unknown>; routingKey: RoutingKey<TRoutingKey>; } | Configuration with required routing key |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.routingKey | RoutingKey<TRoutingKey> | The routing key for the binding |
Returns
CommandConsumerConfig<TMessage, TExchange, TRoutingKey, TQueueDefinition>
A command consumer configuration
Example
const tasksExchange = defineExchange('tasks', { type: 'direct' });
const taskMessage = defineMessage(z.object({ taskId: z.string() }));
const executeTask = defineCommandConsumer(taskQueue, tasksExchange, taskMessage, {
routingKey: 'task.execute',
});
const sendTask = defineCommandPublisher(executeTask);Call Signature
function defineCommandConsumer<TMessage, TRoutingKey, TQueueDefinition, TExchange>(
queue,
exchange,
message,
options): CommandConsumerConfig<TMessage, TExchange, TRoutingKey, TQueueDefinition>;Defined in: builder/command.ts:229
Define a command consumer for receiving commands via topic exchange.
The consumer binds with a routing key pattern (can use * and # wildcards). Publishers then send commands with concrete routing keys that match the pattern.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TQueueDefinition extends QueueDefinition |
TExchange extends TopicExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | TQueueDefinition | The queue that will receive commands |
exchange | TExchange | The topic exchange that routes commands |
message | TMessage | The message definition (schema and metadata) |
options | { arguments?: Record<string, unknown>; routingKey: BindingPattern<TRoutingKey>; } | Configuration with required routing key pattern |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.routingKey | BindingPattern<TRoutingKey> | The routing key pattern for the binding |
Returns
CommandConsumerConfig<TMessage, TExchange, TRoutingKey, TQueueDefinition>
A command consumer configuration
Example
const ordersExchange = defineExchange('orders', { type: 'topic' });
const orderMessage = defineMessage(z.object({ orderId: z.string() }));
// Consumer uses pattern to receive multiple command types
const processOrder = defineCommandConsumer(orderQueue, ordersExchange, orderMessage, {
routingKey: 'order.*',
});
// Publishers send with concrete keys
const createOrder = defineCommandPublisher(processOrder, {
routingKey: 'order.create',
});
const updateOrder = defineCommandPublisher(processOrder, {
routingKey: 'order.update',
});defineCommandPublisher()
Call Signature
function defineCommandPublisher<TMessage, TExchange, TBridgeExchange>(commandConsumer, options): BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>;Defined in: builder/command.ts:283
Create a bridged publisher that sends commands to a fanout exchange consumer via a bridge exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends FanoutExchangeDefinition |
TBridgeExchange extends FanoutExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, TExchange, undefined> | The command consumer configuration |
options | { bridgeExchange: TBridgeExchange; externalConsumers?: boolean; } | Configuration with required bridgeExchange |
options.bridgeExchange | TBridgeExchange | The local domain exchange to bridge through (must be fanout to match target) |
options.externalConsumers? | boolean | Declare that the command's owner lives in another service, opting this publisher out of defineContract's define-time routability check |
Returns
BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>
A bridged publisher configuration
Call Signature
function defineCommandPublisher<TMessage, TExchange, TBridgeExchange>(commandConsumer, options): BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>;Defined in: builder/command.ts:303
Create a bridged publisher that sends commands to a headers exchange consumer via a bridge exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends HeadersExchangeDefinition |
TBridgeExchange extends HeadersExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, TExchange, undefined> | The command consumer configuration |
options | { bridgeExchange: TBridgeExchange; externalConsumers?: boolean; } | Configuration with required bridgeExchange |
options.bridgeExchange | TBridgeExchange | The local domain exchange to bridge through (must be headers to match target) |
options.externalConsumers? | boolean | - |
Returns
BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>
A bridged publisher configuration
Call Signature
function defineCommandPublisher<TMessage, TRoutingKey, TExchange, TBridgeExchange>(commandConsumer, options): BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>;Defined in: builder/command.ts:326
Create a bridged publisher that sends commands to a direct exchange consumer via a bridge exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TExchange extends DirectExchangeDefinition |
TBridgeExchange extends | DirectExchangeDefinition | TopicExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, TExchange, TRoutingKey> | The command consumer configuration |
options | { bridgeExchange: TBridgeExchange; externalConsumers?: boolean; } | Configuration with required bridgeExchange |
options.bridgeExchange | TBridgeExchange | The bridge exchange (must be direct or topic to preserve routing keys) |
options.externalConsumers? | boolean | Declare that the command's owner lives in another service, opting this publisher out of defineContract's define-time routability check |
Returns
BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>
A bridged publisher configuration
Call Signature
function defineCommandPublisher<TMessage, TRoutingKey, TExchange, TBridgeExchange, TPublisherRoutingKey>(commandConsumer, options): BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>;Defined in: builder/command.ts:351
Create a bridged publisher that sends commands to a topic exchange consumer via a bridge exchange.
Type Parameters
| Type Parameter | Default type |
|---|---|
TMessage extends MessageDefinition | - |
TRoutingKey extends string | - |
TExchange extends TopicExchangeDefinition | - |
TBridgeExchange extends | DirectExchangeDefinition | TopicExchangeDefinition | - |
TPublisherRoutingKey extends string | TRoutingKey |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, TExchange, TRoutingKey> | The command consumer configuration |
options | { bridgeExchange: TBridgeExchange; externalConsumers?: boolean; routingKey?: RoutingKey<TPublisherRoutingKey>; } | Configuration with required bridgeExchange and optional routingKey override |
options.bridgeExchange | TBridgeExchange | The bridge exchange (must be direct or topic to preserve routing keys) |
options.externalConsumers? | boolean | Declare that the command's owner lives in another service, opting this publisher out of defineContract's define-time routability check |
options.routingKey? | RoutingKey<TPublisherRoutingKey> | Override routing key (must match consumer's pattern) |
Returns
BridgedPublisherConfig<TMessage, TBridgeExchange, TExchange>
A bridged publisher configuration
Call Signature
function defineCommandPublisher<TMessage>(commandConsumer, options?): object;Defined in: builder/command.ts:378
Create a publisher that sends commands to a fanout exchange consumer.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, FanoutExchangeDefinition, undefined> | The command consumer configuration |
options? | { externalConsumers?: boolean; } | - |
options.externalConsumers? | boolean | - |
Returns
object
A publisher definition
| Name | Type | Defined in |
|---|---|---|
exchange | FanoutExchangeDefinition | builder/command.ts:383 |
externalConsumers? | boolean | builder/command.ts:383 |
message | TMessage | builder/command.ts:383 |
Example
const executeTask = defineCommandConsumer(taskQueue, fanoutExchange, taskMessage);
const sendTask = defineCommandPublisher(executeTask);Call Signature
function defineCommandPublisher<TMessage>(commandConsumer, options?): object;Defined in: builder/command.ts:397
Create a publisher that sends commands to a headers exchange consumer.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, HeadersExchangeDefinition, undefined> | The command consumer configuration |
options? | { externalConsumers?: boolean; } | - |
options.externalConsumers? | boolean | - |
Returns
object
A publisher definition
| Name | Type | Defined in |
|---|---|---|
exchange | HeadersExchangeDefinition | builder/command.ts:402 |
externalConsumers? | boolean | builder/command.ts:402 |
message | TMessage | builder/command.ts:402 |
Example
const executeTask = defineCommandConsumer(taskQueue, headersExchange, taskMessage);
const sendTask = defineCommandPublisher(executeTask);Call Signature
function defineCommandPublisher<TMessage, TRoutingKey>(commandConsumer, options?): object;Defined in: builder/command.ts:410
Create a publisher that sends commands to a direct exchange consumer.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, DirectExchangeDefinition, TRoutingKey> | The command consumer configuration |
options? | { externalConsumers?: boolean; } | - |
options.externalConsumers? | boolean | - |
Returns
object
A publisher definition
| Name | Type | Defined in |
|---|---|---|
exchange | DirectExchangeDefinition | builder/command.ts:420 |
externalConsumers? | boolean | builder/command.ts:422 |
message | TMessage | builder/command.ts:419 |
routingKey | TRoutingKey | builder/command.ts:421 |
Call Signature
function defineCommandPublisher<TMessage, TRoutingKey, TPublisherRoutingKey>(commandConsumer, options?): object;Defined in: builder/command.ts:452
Create a publisher that sends commands to a topic exchange consumer.
For topic exchanges where the consumer uses a pattern, the publisher can optionally specify a concrete routing key that matches the pattern.
Type Parameters
| Type Parameter | Default type |
|---|---|
TMessage extends MessageDefinition | - |
TRoutingKey extends string | - |
TPublisherRoutingKey extends string | TRoutingKey |
Parameters
| Parameter | Type | Description |
|---|---|---|
commandConsumer | CommandConsumerConfig<TMessage, TopicExchangeDefinition, TRoutingKey> | The command consumer configuration |
options? | { externalConsumers?: boolean; routingKey?: RoutingKey<TPublisherRoutingKey>; } | Optional binding configuration |
options.externalConsumers? | boolean | Declare that the command's owner lives in another service, opting this publisher out of defineContract's define-time routability check |
options.routingKey? | RoutingKey<TPublisherRoutingKey> | Override routing key (must match consumer's pattern) |
Returns
object
A publisher definition
| Name | Type | Defined in |
|---|---|---|
exchange | TopicExchangeDefinition | builder/command.ts:464 |
externalConsumers? | boolean | builder/command.ts:466 |
message | TMessage | builder/command.ts:463 |
routingKey | TPublisherRoutingKey | builder/command.ts:465 |
Example
// Consumer binds with pattern
const processOrder = defineCommandConsumer(orderQueue, topicExchange, orderMessage, {
routingKey: 'order.*',
});
// Publisher uses concrete key matching the pattern
const createOrder = defineCommandPublisher(processOrder, {
routingKey: 'order.create',
});defineConsumer()
function defineConsumer<TMessage>(
queue,
message,
options?): ConsumerDefinition<TMessage>;Defined in: builder/consumer.ts:123
Define a message consumer.
A consumer receives and processes messages from a queue. The message schema is validated automatically when messages are consumed, ensuring type safety for your handlers.
Consumers are associated with a specific queue and message type. When you create a worker with this consumer, it will process messages from the queue according to the schema.
Which pattern to use:
| Pattern | Best for | Description |
|---|---|---|
definePublisher + defineConsumer | Independent definition | Define publishers and consumers separately with manual schema consistency |
defineEventPublisher + defineEventConsumer | Event broadcasting | Define event publisher first, create consumers that subscribe to it |
defineCommandConsumer + defineCommandPublisher | Task queues | Define command consumer first, create publishers that send commands to it |
Use defineCommandConsumer when:
- One consumer receives from multiple publishers
- You want automatic schema consistency between consumer and publishers
- You're building task queue or command patterns
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | QueueDefinition | The queue definition to consume from |
message | TMessage | The message definition with payload schema |
options? | Omit<ConsumerDefinition<TMessage>, "queue" | "message"> | Optional consumer configuration |
Returns
ConsumerDefinition<TMessage>
A consumer definition with inferred message types
Example
import { z } from 'zod';
const orderQueue = defineQueue('order-processing');
const orderMessage = defineMessage(
z.object({
orderId: z.string().uuid(),
customerId: z.string().uuid(),
amount: z.number().positive(),
})
);
const processOrderConsumer = defineConsumer(orderQueue, orderMessage);
// Later, when creating a worker, you'll provide a handler for this consumer.
// Handlers return AsyncResult<void, HandlerError> (from unthrown):
// const worker = await TypedAmqpWorker.create({
// contract,
// handlers: {
// processOrder: ({ payload }) => {
// // payload is automatically typed based on the schema
// console.log(payload.orderId); // string
// return OkAsync();
// },
// },
// urls: ['amqp://localhost'],
// }).get();See
- defineCommandConsumer - For task queue patterns with automatic schema consistency
- defineEventPublisher - For event-driven patterns with automatic schema consistency
defineContract()
function defineContract<TContract>(definition): ContractOutput<TContract>;Defined in: builder/contract.ts:138
Define an AMQP contract.
A contract is the central definition of your AMQP messaging topology. It brings together publishers and consumers in a single, type-safe definition. Exchanges, queues, and bindings are automatically extracted from publishers and consumers.
The contract is used by both clients (for publishing) and workers (for consuming) to ensure type safety throughout your messaging infrastructure. TypeScript will infer all message types and publisher/consumer names from the contract.
Type Parameters
| Type Parameter |
|---|
TContract extends ContractDefinitionInput |
Parameters
| Parameter | Type | Description |
|---|---|---|
definition | TContract | The contract definition containing publishers and consumers |
Returns
ContractOutput<TContract>
The contract definition with fully inferred exchanges, queues, bindings, publishers, and consumers
Example
import {
defineContract,
defineExchange,
defineQueue,
defineEventPublisher,
defineEventConsumer,
defineMessage,
} from '@amqp-contract/contract';
import { z } from 'zod';
// Define resources
const ordersExchange = defineExchange('orders');
const dlx = defineExchange('orders-dlx', { type: 'direct' });
const orderQueue = defineQueue('order-processing', {
deadLetter: { exchange: dlx },
retry: { mode: 'immediate-requeue', maxRetries: 3 },
});
const orderMessage = defineMessage(
z.object({
orderId: z.string(),
amount: z.number(),
})
);
// Define event publisher
const orderCreatedEvent = defineEventPublisher(ordersExchange, orderMessage, {
routingKey: 'order.created',
});
// Compose contract - exchanges, queues, bindings are auto-extracted
export const contract = defineContract({
publishers: {
orderCreated: orderCreatedEvent,
},
consumers: {
processOrder: defineEventConsumer(orderCreatedEvent, orderQueue),
},
});
// TypeScript now knows:
// - contract.exchanges.orders, contract.exchanges['orders-dlx']
// - contract.queues['order-processing']
// - contract.bindings.processOrderBinding
// - client.publish('orderCreated', { orderId: string, amount: number })
// - handler: ({ payload }: { payload: { orderId: string, amount: number } }) => AsyncResult<void, HandlerError>defineEventConsumer()
Call Signature
function defineEventConsumer<TMessage, TExchange, TQueueDefinition, TBridgeExchange>(
eventPublisher,
queue,
options): EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>;Defined in: builder/event.ts:339
Create a consumer that subscribes to an event from a fanout exchange via a bridge exchange.
When bridgeExchange is provided, the queue binds to the bridge exchange instead of the source exchange, and an exchange-to-exchange binding is created from the source to the bridge.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends FanoutExchangeDefinition |
TQueueDefinition extends QueueDefinition |
TBridgeExchange extends FanoutExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, undefined> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options | { arguments?: Record<string, unknown>; bridgeExchange: TBridgeExchange; } | Binding configuration with required bridgeExchange |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.bridgeExchange | TBridgeExchange | The fanout bridge exchange (must be fanout to match source) |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>
An object with the consumer definition, queue binding, and exchange binding
Call Signature
function defineEventConsumer<TMessage, TExchange, TQueueDefinition, TBridgeExchange>(
eventPublisher,
queue,
options): EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>;Defined in: builder/event.ts:372
Create a consumer that subscribes to an event from a headers exchange via a bridge exchange.
When bridgeExchange is provided, the queue binds to the bridge exchange instead of the source exchange, and an exchange-to-exchange binding is created from the source to the bridge.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends HeadersExchangeDefinition |
TQueueDefinition extends QueueDefinition |
TBridgeExchange extends HeadersExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, undefined> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options | { arguments?: Record<string, unknown>; bridgeExchange: TBridgeExchange; } | Binding configuration with required bridgeExchange |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.bridgeExchange | TBridgeExchange | The headers bridge exchange (must be headers to match source) |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>
An object with the consumer definition, queue binding, and exchange binding
Call Signature
function defineEventConsumer<TMessage, TRoutingKey, TExchange, TQueueDefinition, TBridgeExchange>(
eventPublisher,
queue,
options): EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>;Defined in: builder/event.ts:402
Create a consumer that subscribes to an event from a direct exchange via a bridge exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TExchange extends DirectExchangeDefinition |
TQueueDefinition extends QueueDefinition |
TBridgeExchange extends | DirectExchangeDefinition | TopicExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, TRoutingKey> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options | { arguments?: Record<string, unknown>; bridgeExchange: TBridgeExchange; } | Binding configuration with required bridgeExchange |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.bridgeExchange | TBridgeExchange | The bridge exchange (must be direct or topic to preserve routing keys) |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>
An object with the consumer definition, queue binding, and exchange binding
Call Signature
function defineEventConsumer<TMessage, TRoutingKey, TExchange, TQueueDefinition, TBridgeExchange, TConsumerRoutingKey>(
eventPublisher,
queue,
options): EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>;Defined in: builder/event.ts:436
Create a consumer that subscribes to an event from a topic exchange via a bridge exchange.
Type Parameters
| Type Parameter | Default type |
|---|---|
TMessage extends MessageDefinition | - |
TRoutingKey extends string | - |
TExchange extends TopicExchangeDefinition | - |
TQueueDefinition extends QueueDefinition | - |
TBridgeExchange extends | DirectExchangeDefinition | TopicExchangeDefinition | - |
TConsumerRoutingKey extends string | TRoutingKey |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, TRoutingKey> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options | { arguments?: Record<string, unknown>; bridgeExchange: TBridgeExchange; routingKey?: MatchingBindingPattern<TConsumerRoutingKey, TRoutingKey>; } | Binding configuration with required bridgeExchange |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.bridgeExchange | TBridgeExchange | The bridge exchange (must be direct or topic to preserve routing keys) |
options.routingKey? | MatchingBindingPattern<TConsumerRoutingKey, TRoutingKey> | Override routing key with a pattern that can match the publisher's routing key (defaults to the publisher's key). A pattern that can never match is a compile-time error. |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition, ExchangeBindingDefinition, TBridgeExchange>
An object with the consumer definition, queue binding, and exchange binding
Call Signature
function defineEventConsumer<TMessage, TExchange, TQueueDefinition>(
eventPublisher,
queue,
options?): EventConsumerResult<TMessage, TExchange, TQueueDefinition>;Defined in: builder/event.ts:474
Create a consumer that subscribes to an event from a fanout exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends FanoutExchangeDefinition |
TQueueDefinition extends QueueDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, undefined> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options? | { arguments?: Record<string, unknown>; } | Optional binding configuration |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition>
An object with the consumer definition and binding
Example
const logEvent = defineEventPublisher(logsExchange, logMessage);
const { consumer, binding } = defineEventConsumer(logEvent, logsQueue);Call Signature
function defineEventConsumer<TMessage, TExchange, TQueueDefinition>(
eventPublisher,
queue,
options?): EventConsumerResult<TMessage, TExchange, TQueueDefinition>;Defined in: builder/event.ts:501
Create a consumer that subscribes to an event from a headers exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends HeadersExchangeDefinition |
TQueueDefinition extends QueueDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, undefined> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options? | { arguments?: Record<string, unknown>; } | Optional binding configuration |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition>
An object with the consumer definition and binding
Example
const logEvent = defineEventPublisher(logsExchange, logMessage);
const { consumer, binding } = defineEventConsumer(logEvent, logsQueue);Call Signature
function defineEventConsumer<TMessage, TRoutingKey, TExchange, TQueueDefinition>(
eventPublisher,
queue,
options?): EventConsumerResult<TMessage, TExchange, TQueueDefinition>;Defined in: builder/event.ts:522
Create a consumer that subscribes to an event from a direct exchange.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TExchange extends DirectExchangeDefinition |
TQueueDefinition extends QueueDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, TRoutingKey> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options? | { arguments?: Record<string, unknown>; } | Optional binding configuration |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition>
An object with the consumer definition and binding
Call Signature
function defineEventConsumer<TMessage, TRoutingKey, TExchange, TQueueDefinition, TConsumerRoutingKey>(
eventPublisher,
queue,
options?): EventConsumerResult<TMessage, TExchange, TQueueDefinition>;Defined in: builder/event.ts:571
Create a consumer that subscribes to an event from a topic exchange.
For topic exchanges, the consumer can optionally override the routing key with a pattern to subscribe to multiple events.
Type Parameters
| Type Parameter | Default type |
|---|---|
TMessage extends MessageDefinition | - |
TRoutingKey extends string | - |
TExchange extends TopicExchangeDefinition | - |
TQueueDefinition extends QueueDefinition | - |
TConsumerRoutingKey extends string | TRoutingKey |
Parameters
| Parameter | Type | Description |
|---|---|---|
eventPublisher | EventPublisherConfig<TMessage, TExchange, TRoutingKey> | The event publisher configuration |
queue | TQueueDefinition | The queue that will receive messages |
options? | { arguments?: Record<string, unknown>; routingKey?: MatchingBindingPattern<TConsumerRoutingKey, TRoutingKey>; } | Optional binding configuration |
options.arguments? | Record<string, unknown> | Additional AMQP arguments |
options.routingKey? | MatchingBindingPattern<TConsumerRoutingKey, TRoutingKey> | Override routing key with a pattern that can match the publisher's routing key (defaults to the publisher's key). A pattern that can never match the publisher's concrete routing key — e.g. user.* against order.created — is a compile-time error, because the binding would silently receive nothing at runtime. |
Returns
EventConsumerResult<TMessage, TExchange, TQueueDefinition>
An object with the consumer definition and binding
Example
const orderCreatedEvent = defineEventPublisher(ordersExchange, orderMessage, {
routingKey: 'order.created',
});
// Use exact routing key from publisher
const { consumer: exactConsumer } = defineEventConsumer(orderCreatedEvent, exactQueue);
// Override with pattern to receive all order events
const { consumer: allConsumer } = defineEventConsumer(orderCreatedEvent, allQueue, {
routingKey: 'order.*',
});
// A pattern that can never match the publisher's key fails to compile:
// defineEventConsumer(orderCreatedEvent, allQueue, { routingKey: 'user.*' });
// Error: binding pattern 'user.*' can never match the publisher routing key 'order.created'defineEventPublisher()
Call Signature
function defineEventPublisher<TMessage, TExchange>(
exchange,
message,
options?): EventPublisherConfig<TMessage, TExchange, undefined>;Defined in: builder/event.ts:132
Define an event publisher for broadcasting messages via fanout exchange.
Events are published without knowing who consumes them. Multiple consumers can subscribe to the same event using defineEventConsumer.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends FanoutExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
exchange | TExchange | The fanout exchange to publish to |
message | TMessage | The message definition (schema and metadata) |
options? | { bindingArguments?: Record<string, unknown>; externalConsumers?: boolean; } | Optional configuration |
options.bindingArguments? | Record<string, unknown> | Default AMQP binding arguments applied to this event's consumers' queue bindings (a consumer's own arguments option takes precedence) |
options.externalConsumers? | boolean | Declare that this event's consumers are owned by another service, opting the event out of defineContract's define-time routability check |
Returns
EventPublisherConfig<TMessage, TExchange, undefined>
An event publisher configuration
Example
const logsExchange = defineExchange('logs', { type: 'fanout' });
const logMessage = defineMessage(z.object({
level: z.enum(['info', 'warn', 'error']),
message: z.string(),
}));
// Create event publisher
const logEvent = defineEventPublisher(logsExchange, logMessage);
// Multiple consumers can subscribe
const { consumer: fileConsumer, binding: fileBinding } =
defineEventConsumer(logEvent, fileLogsQueue);
const { consumer: alertConsumer, binding: alertBinding } =
defineEventConsumer(logEvent, alertsQueue);Call Signature
function defineEventPublisher<TMessage, TExchange>(
exchange,
message,
options?): EventPublisherConfig<TMessage, TExchange, undefined>;Defined in: builder/event.ts:179
Define an event publisher for broadcasting messages via headers exchange.
Events are published without knowing who consumes them. Multiple consumers can subscribe to the same event using defineEventConsumer.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TExchange extends HeadersExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
exchange | TExchange | The headers exchange to publish to |
message | TMessage | The message definition (schema and metadata) |
options? | { bindingArguments?: Record<string, unknown>; externalConsumers?: boolean; } | Optional configuration |
options.bindingArguments? | Record<string, unknown> | Default AMQP binding arguments applied to this event's consumers' queue bindings (a consumer's own arguments option takes precedence) |
options.externalConsumers? | boolean | Declare that this event's consumers are owned by another service, opting the event out of defineContract's define-time routability check |
Returns
EventPublisherConfig<TMessage, TExchange, undefined>
An event publisher configuration
Example
const logsExchange = defineExchange('logs', { type: 'headers' });
const logMessage = defineMessage(z.object({
level: z.enum(['info', 'warn', 'error']),
message: z.string(),
}));
// Create event publisher
const logEvent = defineEventPublisher(logsExchange, logMessage);
// Multiple consumers can subscribe
const { consumer: fileConsumer, binding: fileBinding } =
defineEventConsumer(logEvent, fileLogsQueue);
const { consumer: alertConsumer, binding: alertBinding } =
defineEventConsumer(logEvent, alertsQueue);Call Signature
function defineEventPublisher<TMessage, TRoutingKey, TExchange>(
exchange,
message,
options): EventPublisherConfig<TMessage, TExchange, TRoutingKey>;Defined in: builder/event.ts:219
Define an event publisher for broadcasting messages via direct exchange.
Events are published with a specific routing key. Consumers will receive messages that match the routing key exactly.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TExchange extends DirectExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
exchange | TExchange | The direct exchange to publish to |
message | TMessage | The message definition (schema and metadata) |
options | { bindingArguments?: Record<string, unknown>; externalConsumers?: boolean; routingKey: RoutingKey<TRoutingKey>; } | Configuration with required routing key |
options.bindingArguments? | Record<string, unknown> | Default AMQP binding arguments applied to this event's consumers' queue bindings (a consumer's own arguments option takes precedence) |
options.externalConsumers? | boolean | Declare that this event's consumers are owned by another service, opting the event out of defineContract's define-time routability check |
options.routingKey | RoutingKey<TRoutingKey> | The routing key for message routing |
Returns
EventPublisherConfig<TMessage, TExchange, TRoutingKey>
An event publisher configuration
Example
const tasksExchange = defineExchange('tasks', { type: 'direct' });
const taskMessage = defineMessage(z.object({ taskId: z.string() }));
const taskEvent = defineEventPublisher(tasksExchange, taskMessage, {
routingKey: 'task.execute',
});Call Signature
function defineEventPublisher<TMessage, TRoutingKey, TExchange>(
exchange,
message,
options): EventPublisherConfig<TMessage, TExchange, TRoutingKey>;Defined in: builder/event.ts:272
Define an event publisher for broadcasting messages via topic exchange.
Events are published with a concrete routing key. Consumers can subscribe using patterns (with * and # wildcards) to receive matching messages.
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
TRoutingKey extends string |
TExchange extends TopicExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
exchange | TExchange | The topic exchange to publish to |
message | TMessage | The message definition (schema and metadata) |
options | { bindingArguments?: Record<string, unknown>; externalConsumers?: boolean; routingKey: RoutingKey<TRoutingKey>; } | Configuration with required routing key |
options.bindingArguments? | Record<string, unknown> | Default AMQP binding arguments applied to this event's consumers' queue bindings (a consumer's own arguments option takes precedence) |
options.externalConsumers? | boolean | Declare that this event's consumers are owned by another service, opting the event out of defineContract's define-time routability check |
options.routingKey | RoutingKey<TRoutingKey> | The concrete routing key (no wildcards) |
Returns
EventPublisherConfig<TMessage, TExchange, TRoutingKey>
An event publisher configuration
Example
const ordersExchange = defineExchange('orders', { type: 'topic' });
const orderMessage = defineMessage(z.object({
orderId: z.string(),
amount: z.number(),
}));
// Publisher uses concrete routing key
const orderCreatedEvent = defineEventPublisher(ordersExchange, orderMessage, {
routingKey: 'order.created',
});
// Consumer can use pattern
const { consumer, binding } = defineEventConsumer(
orderCreatedEvent,
allOrdersQueue,
{ routingKey: 'order.*' },
);defineExchange()
Call Signature
function defineExchange<TName>(name, options?): TopicExchangeDefinition<TName>;Defined in: builder/exchange.ts:35
Define a topic exchange.
A topic exchange routes messages to queues based on routing key patterns. Routing keys can use wildcards: * matches one word, # matches zero or more words. This exchange type is ideal for flexible message routing based on hierarchical topics.
Type Parameters
| Type Parameter |
|---|
TName extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | The name of the exchange |
options? | object & Omit<BaseExchangeDefinition, "type" | "name"> | Optional exchange configuration |
Returns
TopicExchangeDefinition<TName>
A topic exchange definition
Example
const ordersExchange = defineExchange('orders', { type: 'topic' });
// Or omit type for default topic exchange
const ordersExchange = defineExchange('orders');Call Signature
function defineExchange<TName>(name, options): DirectExchangeDefinition<TName>;Defined in: builder/exchange.ts:60
Define a direct exchange.
A direct exchange routes messages to queues based on exact routing key matches. This exchange type is ideal for point-to-point messaging.
Type Parameters
| Type Parameter |
|---|
TName extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | The name of the exchange |
options | object & Omit<BaseExchangeDefinition, "type" | "name"> | Exchange configuration |
Returns
DirectExchangeDefinition<TName>
A direct exchange definition
Example
const tasksExchange = defineExchange('tasks', { type: 'direct' });Call Signature
function defineExchange<TName>(name, options): FanoutExchangeDefinition<TName>;Defined in: builder/exchange.ts:85
Define a fanout exchange.
A fanout exchange routes messages to all bound queues without considering routing keys. This exchange type is ideal for broadcasting messages to multiple consumers.
Type Parameters
| Type Parameter |
|---|
TName extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | The name of the exchange |
options | object & Omit<BaseExchangeDefinition, "type" | "name"> | Exchange configuration |
Returns
FanoutExchangeDefinition<TName>
A fanout exchange definition
Example
const logsExchange = defineExchange('logs', { type: 'fanout' });Call Signature
function defineExchange<TName>(name, options): HeadersExchangeDefinition<TName>;Defined in: builder/exchange.ts:110
Define a headers exchange.
A headers exchange routes messages to all bound queues based on header matching. This exchange type is ideal for complex routing scenarios.
Type Parameters
| Type Parameter |
|---|
TName extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | The name of the exchange |
options | object & Omit<BaseExchangeDefinition, "type" | "name"> | Exchange configuration |
Returns
HeadersExchangeDefinition<TName>
A headers exchange definition
Example
const routesExchange = defineExchange('routes', { type: 'headers' });defineExchangeBinding()
Call Signature
function defineExchangeBinding(
destination,
source,
options?): object & object;Defined in: builder/binding.ts:172
Define a binding between two exchanges (exchange-to-exchange routing).
Binds a destination exchange to a fanout or headers source exchange. Messages published to the source exchange will be forwarded to the destination exchange. Fanout and headers exchanges ignore routing keys, so this overload doesn't require one.
Parameters
| Parameter | Type | Description |
|---|---|---|
destination | ExchangeDefinition | The destination exchange definition |
source | | FanoutExchangeDefinition | HeadersExchangeDefinition | The fanout or headers source exchange definition |
options? | Omit<object & object, "type" | "source" | "destination" | "routingKey"> | Optional binding configuration |
Returns
An exchange binding definition
Example
const sourceExchange = defineExchange('logs', { type: 'fanout' });
const destExchange = defineExchange('all-logs', { type: 'fanout' });
const binding = defineExchangeBinding(destExchange, sourceExchange);Call Signature
function defineExchangeBinding(
destination,
source,
options): object & object;Defined in: builder/binding.ts:211
Define a binding between two exchanges (exchange-to-exchange routing).
Binds a destination exchange to a direct or topic source exchange with a routing key pattern. Messages are forwarded from source to destination only if the routing key matches the pattern.
Parameters
| Parameter | Type | Description |
|---|---|---|
destination | ExchangeDefinition | The destination exchange definition |
source | | DirectExchangeDefinition | TopicExchangeDefinition | The direct or topic source exchange definition |
options | Omit<Extract<ExchangeBindingDefinition, { source: | DirectExchangeDefinition | TopicExchangeDefinition; }>, "type" | "source" | "destination"> | Binding configuration (routingKey is required) |
Returns
An exchange binding definition
Example
const ordersExchange = defineExchange('orders');
const importantExchange = defineExchange('important-orders');
// Forward only high-value orders
const binding = defineExchangeBinding(importantExchange, ordersExchange, {
routingKey: 'order.high-value.*'
});defineMessage()
function defineMessage<TPayload, THeaders>(payload, options?): MessageDefinition<TPayload, THeaders>;Defined in: builder/message.ts:41
Define a message definition with payload and optional headers/metadata.
A message definition specifies the schema for message payloads and headers using Standard Schema v1 compatible libraries (Zod, Valibot, ArkType, etc.). The schemas are used for automatic validation when publishing or consuming messages.
Type Parameters
| Type Parameter | Default type |
|---|---|
TPayload extends AnySchema | - |
THeaders extends | StandardSchemaV1<Record<string, unknown>, Record<string, unknown>> | undefined | undefined |
Parameters
| Parameter | Type | Description |
|---|---|---|
payload | TPayload | The payload schema (must be Standard Schema v1 compatible) |
options? | { description?: string; headers?: THeaders; summary?: string; } | Optional message metadata |
options.description? | string | Detailed description for documentation (used in AsyncAPI generation) |
options.headers? | THeaders | Optional header schema for message headers |
options.summary? | string | Brief description for documentation (used in AsyncAPI generation) |
Returns
MessageDefinition<TPayload, THeaders>
A message definition with inferred types
Example
import { z } from 'zod';
const orderMessage = defineMessage(
z.object({
orderId: z.string().uuid(),
customerId: z.string().uuid(),
amount: z.number().positive(),
items: z.array(z.object({
productId: z.string(),
quantity: z.number().int().positive(),
})),
}),
{
summary: 'Order created event',
description: 'Emitted when a new order is created in the system'
}
);definePublisher()
Call Signature
function definePublisher<TMessage>(
exchange,
message,
options?): object & object;Defined in: builder/publisher.ts:58
Define a message publisher for a fanout or headers exchange.
A publisher sends messages to an exchange. For fanout exchanges, messages are broadcast to all bound queues regardless of routing key, so no routing key is required. For headers exchanges, routing is based on message headers rather than routing keys, so no routing key is required either.
The message schema is validated when publishing to ensure type safety.
Which pattern to use:
| Pattern | Best for | Description |
|---|---|---|
definePublisher + defineConsumer | Independent definition | Define publishers and consumers separately with manual schema consistency |
defineEventPublisher + defineEventConsumer | Event broadcasting | Define event publisher first, create consumers that subscribe to it |
defineCommandConsumer + defineCommandPublisher | Task queues | Define command consumer first, create publishers that send commands to it |
Use defineEventPublisher when:
- One publisher feeds multiple consumers
- You want automatic schema consistency between publisher and consumers
- You're building event-driven architectures
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
exchange | | FanoutExchangeDefinition | HeadersExchangeDefinition | The fanout or headers exchange definition to publish to |
message | TMessage | The message definition with payload schema |
options? | Omit<object & object, "message" | "routingKey" | "exchange"> | Optional publisher configuration |
Returns
A publisher definition with inferred message types
Example
import { z } from 'zod';
const logsExchange = defineExchange('logs', { type: 'fanout' });
const logMessage = defineMessage(
z.object({
level: z.enum(['info', 'warn', 'error']),
message: z.string(),
timestamp: z.string().datetime(),
})
);
const logPublisher = definePublisher(logsExchange, logMessage);See
- defineEventPublisher - For event-driven patterns with automatic schema consistency
- defineCommandConsumer - For task queue patterns with automatic schema consistency
Call Signature
function definePublisher<TMessage>(
exchange,
message,
options): object & object;Defined in: builder/publisher.ts:124
Define a message publisher for a direct or topic exchange.
A publisher sends messages to an exchange with a specific routing key. The routing key determines which queues receive the message.
The message schema is validated when publishing to ensure type safety.
Which pattern to use:
| Pattern | Best for | Description |
|---|---|---|
definePublisher + defineConsumer | Independent definition | Define publishers and consumers separately with manual schema consistency |
defineEventPublisher + defineEventConsumer | Event broadcasting | Define event publisher first, create consumers that subscribe to it |
defineCommandConsumer + defineCommandPublisher | Task queues | Define command consumer first, create publishers that send commands to it |
Use defineEventPublisher when:
- One publisher feeds multiple consumers
- You want automatic schema consistency between publisher and consumers
- You're building event-driven architectures
Type Parameters
| Type Parameter |
|---|
TMessage extends MessageDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
exchange | | DirectExchangeDefinition | TopicExchangeDefinition | The direct or topic exchange definition to publish to |
message | TMessage | The message definition with payload schema |
options | Omit<Extract<PublisherDefinition<TMessage>, { exchange: | DirectExchangeDefinition | TopicExchangeDefinition; }>, "exchange" | "message"> | Publisher configuration (routingKey is required) |
Returns
A publisher definition with inferred message types
Example
import { z } from 'zod';
const ordersExchange = defineExchange('orders');
const orderMessage = defineMessage(
z.object({
orderId: z.string().uuid(),
amount: z.number().positive(),
}),
{
summary: 'Order created event',
description: 'Emitted when a new order is created'
}
);
const orderCreatedPublisher = definePublisher(ordersExchange, orderMessage, {
routingKey: 'order.created'
});See
- defineEventPublisher - For event-driven patterns with automatic schema consistency
- defineCommandConsumer - For task queue patterns with automatic schema consistency
defineQueue()
Call Signature
function defineQueue<TName, TDlx>(name, options): QueueDefinitionWithDeadLetterExchange<TName, TDlx>;Defined in: builder/queue.ts:110
Define an AMQP queue.
A queue stores messages until they are consumed by workers. Queues can be bound to exchanges to receive messages based on routing rules.
By default, queues are created as quorum queues which provide better durability and high-availability. Use type: 'classic' for special cases like non-durable queues or priority queues.
Type Parameters
| Type Parameter |
|---|
TName extends string |
TDlx extends ExchangeDefinition |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | The name of the queue |
options | DefineQueueOptionsWithDeadLetterExchange<TDlx> | Optional queue configuration |
Returns
QueueDefinitionWithDeadLetterExchange<TName, TDlx>
A queue definition
Example
// Quorum queue (default, recommended for production)
const orderQueue = defineQueue('order-processing');
// Explicit quorum queue with dead letter exchange
const dlx = defineExchange('orders-dlx');
const orderQueueWithDLX = defineQueue('order-processing', {
type: 'quorum',
deadLetter: {
exchange: dlx,
routingKey: 'order.failed'
},
arguments: {
'x-message-ttl': 86400000, // 24 hours
}
});
// Classic queue (for special cases)
const tempQueue = defineQueue('temp-queue', {
type: 'classic',
durable: false,
autoDelete: true,
});
// Priority queue (requires classic type)
const taskQueue = defineQueue('urgent-tasks', {
type: 'classic',
maxPriority: 10,
});
// Queue with TTL-backoff retry (wait queues are derived at setup time)
const retryDlx = defineExchange('payments-dlx', { type: 'direct' });
const paymentQueue = defineQueue('payment-processing', {
deadLetter: { exchange: retryDlx },
retry: { mode: 'ttl-backoff', maxRetries: 5 },
});
// paymentQueue is a plain QueueDefinition; setupAmqpTopology declares the
// per-delay wait queues derived from its retry configCall Signature
function defineQueue<TName>(name, options?): QueueDefinition<TName>;Defined in: builder/queue.ts:115
Define an AMQP queue.
A queue stores messages until they are consumed by workers. Queues can be bound to exchanges to receive messages based on routing rules.
By default, queues are created as quorum queues which provide better durability and high-availability. Use type: 'classic' for special cases like non-durable queues or priority queues.
Type Parameters
| Type Parameter |
|---|
TName extends string |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | TName | The name of the queue |
options? | DefineQueueOptions | Optional queue configuration |
Returns
QueueDefinition<TName>
A queue definition
Example
// Quorum queue (default, recommended for production)
const orderQueue = defineQueue('order-processing');
// Explicit quorum queue with dead letter exchange
const dlx = defineExchange('orders-dlx');
const orderQueueWithDLX = defineQueue('order-processing', {
type: 'quorum',
deadLetter: {
exchange: dlx,
routingKey: 'order.failed'
},
arguments: {
'x-message-ttl': 86400000, // 24 hours
}
});
// Classic queue (for special cases)
const tempQueue = defineQueue('temp-queue', {
type: 'classic',
durable: false,
autoDelete: true,
});
// Priority queue (requires classic type)
const taskQueue = defineQueue('urgent-tasks', {
type: 'classic',
maxPriority: 10,
});
// Queue with TTL-backoff retry (wait queues are derived at setup time)
const retryDlx = defineExchange('payments-dlx', { type: 'direct' });
const paymentQueue = defineQueue('payment-processing', {
deadLetter: { exchange: retryDlx },
retry: { mode: 'ttl-backoff', maxRetries: 5 },
});
// paymentQueue is a plain QueueDefinition; setupAmqpTopology declares the
// per-delay wait queues derived from its retry configdefineQueueBinding()
Call Signature
function defineQueueBinding(
queue,
exchange,
options?): object & object;Defined in: builder/binding.ts:33
Define a binding between a queue and a fanout or headers exchange.
Binds a queue to a fanout or headers exchange (no routing key needed). Fanout and headers exchanges ignore routing keys, so this overload doesn't require one.
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | QueueDefinition | The queue definition to bind |
exchange | | FanoutExchangeDefinition | HeadersExchangeDefinition | The fanout or headers exchange definition |
options? | Omit<object & object, "queue" | "type" | "routingKey" | "exchange"> | Optional binding configuration |
Returns
A queue binding definition
Example
const logsQueue = defineQueue('logs-queue');
const logsExchange = defineExchange('logs', { type: 'fanout' });
const binding = defineQueueBinding(logsQueue, logsExchange);Call Signature
function defineQueueBinding(
queue,
exchange,
options): object & object;Defined in: builder/binding.ts:82
Define a binding between a queue and a direct or topic exchange.
Binds a queue to an exchange with a specific routing key pattern. Messages are only routed to the queue if the routing key matches the pattern.
For direct exchanges: The routing key must match exactly. For topic exchanges: The routing key can include wildcards:
*matches exactly one word#matches zero or more words
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | QueueDefinition | The queue definition to bind |
exchange | | DirectExchangeDefinition | TopicExchangeDefinition | The direct or topic exchange definition |
options | Omit<Extract<QueueBindingDefinition, { exchange: | DirectExchangeDefinition | TopicExchangeDefinition; }>, "type" | "queue" | "exchange"> | Binding configuration (routingKey is required) |
Returns
A queue binding definition
Example
const orderQueue = defineQueue('order-processing');
const ordersExchange = defineExchange('orders');
// Bind with exact routing key
const binding = defineQueueBinding(orderQueue, ordersExchange, {
routingKey: 'order.created'
});
// Bind with wildcard pattern
const allOrdersBinding = defineQueueBinding(orderQueue, ordersExchange, {
routingKey: 'order.*' // Matches order.created, order.updated, etc.
});defineRpc()
function defineRpc<TRequestMessage, TResponseMessage, TQueue, TErrors>(queue, messages): RpcDefinition<TRequestMessage, TResponseMessage, TQueue, TErrors>;Defined in: builder/rpc.ts:58
Define an RPC operation: a request/response pair flowing over a request queue with replies routed back via RabbitMQ direct reply-to.
RPC is bidirectional on both ends — the worker handler consumes the request and produces the response; client.call(name, request, options) publishes the request and awaits the typed response. Both sides share the same definition, so request and response schemas cannot drift between them.
Plug the result into defineContract({ rpcs: { name: ... } }). RPCs do not appear in publishers or consumers.
Type Parameters
| Type Parameter | Default type |
|---|---|
TRequestMessage extends MessageDefinition | - |
TResponseMessage extends MessageDefinition | - |
TQueue extends QueueDefinition | - |
TErrors extends RpcErrorMap | undefined | undefined |
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | TQueue | The queue that receives RPC requests. The queue name is used as the routing key on the AMQP default direct exchange. |
messages | { errors?: TErrors; request: TRequestMessage; response: TResponseMessage; } | - |
messages.errors? | TErrors | Optional typed error map: error code → { data, message? }, where data is the Standard Schema for the error's payload and message an optional default human-readable message. Declared errors widen the handler's Err channel (return Err(rpcError(code, data))) and the client's call() error union; error data is schema-validated on both sides. Business errors are replied and acked — never retried. |
messages.request | TRequestMessage | Schema validated against incoming request payloads (server side) and outgoing requests (client side). |
messages.response | TResponseMessage | Schema validated against handler return values (server side) and incoming replies (client side). |
Returns
RpcDefinition<TRequestMessage, TResponseMessage, TQueue, TErrors>
Example
import { defineQueue, defineMessage, defineRpc, defineContract } from '@amqp-contract/contract';
import { z } from 'zod';
const getOrder = defineRpc(defineQueue('rpc.get-order'), {
request: defineMessage(z.object({ orderId: z.string() })),
response: defineMessage(z.object({ orderId: z.string(), status: z.string() })),
errors: {
ORDER_NOT_FOUND: { data: z.object({ orderId: z.string() }), message: 'Order not found' },
},
});
const contract = defineContract({ rpcs: { getOrder } });
// Server (worker): return the response, or a declared typed error
// handlers: {
// getOrder: ({ payload }) =>
// orders.has(payload.orderId)
// ? OkAsync(orders.get(payload.orderId))
// : ErrAsync(rpcError('ORDER_NOT_FOUND', { orderId: payload.orderId })),
// }
// Client: typed call — the error union includes RpcError<'ORDER_NOT_FOUND', { orderId: string }>
// const result = await client.call('getOrder', { orderId: '42' }, { timeoutMs: 5_000 });
// if (result.isErr() && isRpcError(result.error)) console.log(result.error.code);deriveTtlBackoffInfrastructure()
function deriveTtlBackoffInfrastructure(queue): TtlBackoffInfrastructure | undefined;Defined in: builder/ttl-backoff.ts:84
Derive the TTL-backoff retry infrastructure for a queue: one wait queue per distinct backoff delay in the retry schedule.
The infrastructure is derived, not stored — defineQueue returns a plain QueueDefinition and the contract output contains only the queues you declared. setupAmqpTopology calls this helper at channel-setup time to declare the wait queues, and the worker's retry pipeline uses it to publish the retry copy to the tier queue matching the attempt's base delay.
How the retry hop works:
- The worker publishes the failed message to the tier's wait queue via the default exchange (routing key = wait queue name), with a per-message
expirationcarrying the (jittered) delay. - The wait queue is declared with
x-message-ttlset to the tier's jitter ceiling as a backstop, and dead-letters to the default exchange withx-dead-letter-routing-keyset to the main queue name. - When the TTL expires, RabbitMQ routes the message straight back to the main queue.
Because every message in a tier shares the same base delay, a long-delay retry can never block a short-delay retry: head-of-line skew within a tier is bounded by the jitter spread (at most delayMs), and is zero when jitter is disabled.
Parameters
| Parameter | Type | Description |
|---|---|---|
queue | QueueDefinition | The main queue definition |
Returns
TtlBackoffInfrastructure | undefined
The derived infrastructure, or undefined when the queue's retry mode is not ttl-backoff
Example
const queue = defineQueue('order-processing', {
retry: { mode: 'ttl-backoff', maxRetries: 3, initialDelayMs: 1000 },
});
const infra = deriveTtlBackoffInfrastructure(queue);
// infra.waitQueues → [
// { name: 'order-processing-wait-1000ms', delayMs: 1000, messageTtlMs: 1500 },
// { name: 'order-processing-wait-2000ms', delayMs: 2000, messageTtlMs: 3000 },
// { name: 'order-processing-wait-4000ms', delayMs: 4000, messageTtlMs: 6000 },
// ]extractConsumer()
function extractConsumer(entry): ConsumerDefinition;Defined in: builder/consumer.ts:55
Extract the ConsumerDefinition from any ConsumerEntry type.
Handles the following entry types:
- ConsumerDefinition: returned as-is
- EventConsumerResult: returns the nested
.consumerproperty - CommandConsumerConfig: returns the nested
.consumerproperty
Use this function when you need to access the underlying ConsumerDefinition from a consumer entry that may have been created with defineEventConsumer or defineCommandConsumer.
Parameters
| Parameter | Type | Description |
|---|---|---|
entry | ConsumerEntry | The consumer entry to extract from |
Returns
The underlying ConsumerDefinition
Example
// Works with plain ConsumerDefinition
const consumer1 = defineConsumer(queue, message);
extractConsumer(consumer1).queue.name; // "my-queue"
// Works with EventConsumerResult
const consumer2 = defineEventConsumer(eventPublisher, queue);
extractConsumer(consumer2).queue.name; // "my-queue"
// Works with CommandConsumerConfig
const consumer3 = defineCommandConsumer(queue, exchange, message, { routingKey: "cmd" });
extractConsumer(consumer3).queue.name; // "my-queue"formatIssue()
function formatIssue(issue): string;Defined in: issues.ts:11
Render a single Standard Schema issue as path.to.field: message (or just the message for root-level issues). Path segments may be raw property keys or { key } objects per the Standard Schema spec; both are handled.
Single source of truth for issue rendering across the client and worker — mirrors temporal-contract's shared formatter (org DNA).
Parameters
| Parameter | Type |
|---|---|
issue | Issue |
Returns
string
isBridgedPublisherConfig()
function isBridgedPublisherConfig(value): value is BridgedPublisherConfig<MessageDefinition, ExchangeDefinition, ExchangeDefinition>;Defined in: builder/command.ts:561
Type guard to check if a value is a BridgedPublisherConfig.
Parameters
| Parameter | Type | Description |
|---|---|---|
value | unknown | The value to check |
Returns
value is BridgedPublisherConfig<MessageDefinition, ExchangeDefinition, ExchangeDefinition>
True if the value is a BridgedPublisherConfig
isCommandConsumerConfig()
function isCommandConsumerConfig(value): value is CommandConsumerConfig<MessageDefinition, ExchangeDefinition, string | undefined, QueueDefinition>;Defined in: builder/command.ts:549
Type guard to check if a value is a CommandConsumerConfig.
Parameters
| Parameter | Type | Description |
|---|---|---|
value | unknown | The value to check |
Returns
value is CommandConsumerConfig<MessageDefinition, ExchangeDefinition, string | undefined, QueueDefinition>
True if the value is a CommandConsumerConfig
isEventConsumerResult()
function isEventConsumerResult(value): value is EventConsumerResult<MessageDefinition, ExchangeDefinition, QueueDefinition, ExchangeBindingDefinition | undefined, ExchangeDefinition | undefined>;Defined in: builder/event.ts:678
Type guard to check if a value is an EventConsumerResult.
Parameters
| Parameter | Type | Description |
|---|---|---|
value | unknown | The value to check |
Returns
value is EventConsumerResult<MessageDefinition, ExchangeDefinition, QueueDefinition, ExchangeBindingDefinition | undefined, ExchangeDefinition | undefined>
True if the value is an EventConsumerResult
isEventPublisherConfig()
function isEventPublisherConfig(value): value is EventPublisherConfig<MessageDefinition, ExchangeDefinition, string | undefined>;Defined in: builder/event.ts:666
Type guard to check if a value is an EventPublisherConfig.
Parameters
| Parameter | Type | Description |
|---|---|---|
value | unknown | The value to check |
Returns
value is EventPublisherConfig<MessageDefinition, ExchangeDefinition, string | undefined>
True if the value is an EventPublisherConfig
summarizeIssues()
function summarizeIssues(issues, limit?): string;Defined in: issues.ts:28
Render a list of Standard Schema issues as a single human-readable line: the first limit issues joined with ; , plus a (+N more) suffix when truncated. Empty input renders as "no issues" (defensive — validation failures always carry at least one issue).
Parameters
| Parameter | Type | Default value |
|---|---|---|
issues | readonly Issue[] | undefined |
limit | number | 3 |
Returns
string
ttlBackoffBaseDelay()
function ttlBackoffBaseDelay(retry, retryCount): number;Defined in: builder/ttl-backoff.ts:19
Base (pre-jitter) backoff delay for a given retry attempt: min(initialDelayMs * backoffMultiplier ^ retryCount, maxDelayMs).
retryCount is zero-based — the delay applied before retry attempt retryCount + 1.
Parameters
| Parameter | Type | Description |
|---|---|---|
retry | ResolvedTtlBackoffRetryOptions | Resolved TTL-backoff retry options |
retryCount | number | Number of retries already attempted (0 for the first retry) |
Returns
number
The base delay in milliseconds
ttlBackoffWaitQueueName()
function ttlBackoffWaitQueueName(queueName, delayMs): string;Defined in: builder/ttl-backoff.ts:38
Broker name of the wait queue for a delay tier: {queueName}-wait-{delayMs}ms.
Parameters
| Parameter | Type | Description |
|---|---|---|
queueName | string | The main queue name |
delayMs | number | The tier's base delay in milliseconds |
Returns
string
The wait queue name