amqp-extension 5.1.1 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.MD CHANGED
@@ -102,7 +102,7 @@ The package is ESM-only and requires Node.js `>=22`.
102
102
 
103
103
  ### Client
104
104
 
105
- A `Client` owns one connection and is bound to one exchange. Leave out `exchange` to use the **default exchange**, which routes each message straight to the queue named in the call.
105
+ A `Client` owns one connection and is bound to one exchange. Leave out `exchange` (or pass a `direct` one without a `name`) to use the **default exchange**, which routes each message straight to the queue named in the call. A `direct` exchange with a `name` is a named exchange like `topic`, `fanout` and `headers`.
106
106
 
107
107
  ```typescript
108
108
  import { Client } from 'amqp-extension';
@@ -297,7 +297,7 @@ const client = new Client({
297
297
  | `retry` | consume | none | `{ maxAttempts?, delay? }`: retry messages whose handler threw (see [Retry & redelivery](#retry--redelivery)) |
298
298
  | `onError` | consume | none | `(error, message) => void \| Promise<void>`, called when a handler threw or none matched (also with `noAck`). A call-site `onError` replaces the client default |
299
299
  | Queue options | both | none | `queueType`, `deliveryLimit`, `deadLetterExchange`, `deadLetterRoutingKey`, `messageTtl`, `maxLength`, `singleActiveConsumer` (see below) |
300
- | `timeout` | publish | none | Milliseconds to wait for the broker to take the message before rejecting with a `ClientError` (`PUBLISH_TIMEOUT`), e.g. while it is unreachable. Without it the call waits for the reconnect |
300
+ | `timeout` | publish | `30_000` | Milliseconds to wait for the broker to confirm the message before rejecting with a `ClientError` (`PUBLISH_TIMEOUT`), e.g. while it is unreachable or every publish channel is in use. `0` waits without limit (e.g. for the reconnect) |
301
301
 
302
302
  ### Queue options
303
303
 
@@ -339,8 +339,10 @@ await client.publish('<queue>', { foo: 'bar' }, queueOptions);
339
339
  | Export | Kind | Purpose |
340
340
  |---|---|---|
341
341
  | `Client` | class | `publish()`, `consume()`, `of()`, `close()`, `[Symbol.asyncDispose]()`, plus the underlying `connection` |
342
- | `ClientContext` | type | Constructor input: `connection` / `connectionOptions`, `connectionManagerOptions`, `exchange`, `publishOptions`, `consumeOptions` |
343
- | `ExchangeType` | enum | `direct` (default exchange), `topic`, `fanout`, `headers` |
342
+ | `ClientContext` | type | Constructor input: `connection` / `connectionOptions`, `connectionManagerOptions`, `exchange`, `publishOptions`, `consumeOptions`, `publishChannelMax`, `publishChannelLimiter` |
343
+ | `PublishChannelLimiter`, `IPublishChannelLimiter` | class, interface | Bounds the publish channels open at once (FIFO slots); pass one as `publishChannelLimiter` to share a limit between clients |
344
+ | `PUBLISH_TIMEOUT`, `PUBLISH_CHANNEL_MAX` | constant | Defaults of the `timeout` publish option (30 s) and of `publishChannelMax` (256) |
345
+ | `ExchangeType` | enum | `direct` (the default exchange without a `name`), `topic`, `fanout`, `headers` |
344
346
  | `ConsumeHandlers` | type | Map from message `type` to handler, with the `$any` fallback key |
345
347
  | `Consumer` | type | Resolved by `consume()`: `cancel()` and `[Symbol.asyncDispose]()` |
346
348
  | `ConsumeOptions` / `PublishOptions` | type | amqplib options plus the extensions listed above |
@@ -356,7 +358,8 @@ await client.publish('<queue>', { foo: 'bar' }, queueOptions);
356
358
 
357
359
  - **Close the client when you are done:** `await client.close()`. It closes the shared connection, so every `of()` sibling stops too. Nothing is closed automatically on `SIGINT`; hook it into your app's shutdown, e.g. `process.once('SIGTERM', () => client.close())`. For scoped code (scripts, jobs, tests) use `await using client = new Client(...)`: the client closes when the scope ends, also on a throw. Disposal runs at scope exit, not on a signal, and like `close()` it closes the shared connection, so use it on the root client rather than on `of()` siblings.
358
360
  - **Broker errors reject the call.** If the broker rejects the setup, e.g. `PRECONDITION_FAILED` for a queue re-declared with different queue options or `ACCESS_REFUSED` for a queue that is already consumed exclusively, `publish()` / `consume()` reject with a `BrokerError` (the amqplib error is its `cause`). Only that channel closes; the connection stays up. A connection that merely drops during the call is not an error: the call completes after the reconnect (`publish` is bounded by its `timeout` option).
359
- - **Calls after `close()` reject** with a `ClientError` (`CLIENT_CLOSED`), also on `of()` siblings.
361
+ - **Each publish uses its own channel, at most `publishChannelMax` at once** (default 256, shared by `of()` siblings). Further publishes wait for a free channel within their `timeout`, so a burst of publishes cannot exceed the broker's `channel_max` (2047 per connection by default, also counting the consume channels). Keep the limit below it when you raise it; it must be a positive integer (`RangeError` otherwise). Separate `Client`s on one injected connection each get their own limit unless they share one `publishChannelLimiter: new PublishChannelLimiter(n)`.
362
+ - **Calls after `close()` reject** with a `ClientError` (`CLIENT_CLOSED`), also on `of()` siblings. A publish still waiting for a free channel when the client closes rejects like any pending publish (`CHANNEL_CLOSED`).
360
363
  - **A consumer cancelled by the broker stays cancelled**, e.g. when its queue is deleted. Call `consume()` again after re-creating the queue.
361
364
  - **Invalid input rejects before anything touches the broker:** an empty queue name on the default exchange, a named exchange type without a `name`, or an empty routing key when publishing to a named exchange, with a `TopologyError`.
362
365
  - **Unconsumed fanout/topic messages are dropped**, unless `consume` passes `queue` and has declared it at least once. Without it, named exchanges bind an exclusive, auto-deleted queue per `consume` call, which lives only as long as that consumer.
package/dist/index.d.mts CHANGED
@@ -1,10 +1,16 @@
1
1
  import { BaseError, ErrorInput } from "@ebec/core";
2
2
  import { AmqpConnectionManagerOptions, connect } from "amqp-connection-manager";
3
3
  import { Channel, ConsumeMessage, Options } from "amqplib";
4
- //#region src/consume/constants.d.ts
5
4
  export declare const ConsumeHandlerAnyKey = "$any";
6
- //#endregion
7
- //#region src/queue/types.d.ts
5
+ /**
6
+ * The default publish timeout in milliseconds.
7
+ */
8
+ export declare const PUBLISH_TIMEOUT = 30000;
9
+ /**
10
+ * The default number of publish channels a client (and its of() siblings) opens at once.
11
+ * Well below RabbitMQ's default channel_max (2047 per connection), which also counts the consume channels.
12
+ */
13
+ export declare const PUBLISH_CHANNEL_MAX = 256;
8
14
  /**
9
15
  * Options of a named, durable queue, accepted flat on both ConsumeOptions and PublishOptions.
10
16
  * They map to queue arguments (x-*) and are not validated client-side:
@@ -51,8 +57,6 @@ export type QueueOptions = {
51
57
  */
52
58
  singleActiveConsumer?: boolean;
53
59
  };
54
- //#endregion
55
- //#region src/publish/types.d.ts
56
60
  /**
57
61
  * The AMQP properties of a published message (type, messageId, headers, persistent, …).
58
62
  */
@@ -64,10 +68,11 @@ export type RepublishOptions = PublishProperties;
64
68
  export type PublishOptions = PublishProperties & QueueOptions & {
65
69
  /**
66
70
  * Reject with ClientError (PUBLISH_TIMEOUT) when the message is not
67
- * handed to the broker within this many milliseconds, e.g. while the
68
- * broker is unreachable and the connection manager is reconnecting.
71
+ * confirmed by the broker within this many milliseconds, e.g. while the
72
+ * broker is unreachable and the connection manager is reconnecting, or
73
+ * while every publish channel is in use. 0 waits without limit.
69
74
  *
70
- * Default: undefined (wait for the reconnect)
75
+ * Default: 30_000 (PUBLISH_TIMEOUT)
71
76
  */
72
77
  timeout?: number;
73
78
  };
@@ -76,8 +81,34 @@ export type PublishContext = {
76
81
  data: any;
77
82
  options?: PublishOptions;
78
83
  };
79
- //#endregion
80
- //#region src/consume/types.d.ts
84
+ /**
85
+ * Bounds how many publish channels are open at once.
86
+ */
87
+ export interface IPublishChannelLimiter {
88
+ /**
89
+ * Take a slot if one is free right now and return its release function, else undefined.
90
+ */
91
+ tryAcquire(): (() => void) | undefined;
92
+ /**
93
+ * Resolve with a release function once a slot is free.
94
+ * Reject with ClientError (PUBLISH_TIMEOUT) when none is free within `timeout` ms (0: wait without limit).
95
+ */
96
+ acquire(timeout: number): Promise<() => void>;
97
+ }
98
+ /**
99
+ * Bounds how many publish channels are open at once: a slot is handed to the
100
+ * next waiting publish in order (FIFO) when it is released.
101
+ */
102
+ export declare class PublishChannelLimiter implements IPublishChannelLimiter {
103
+ protected readonly limit: number;
104
+ protected active: number;
105
+ protected waiting: (() => void)[];
106
+ constructor(limit: number);
107
+ tryAcquire(): (() => void) | undefined;
108
+ acquire(timeout: number): Promise<() => void>;
109
+ protected createRelease(): () => void;
110
+ protected release(): void;
111
+ }
81
112
  export type ConsumeMessageHandler = (message: ConsumeMessage, channel: Channel) => Promise<void> | void;
82
113
  export type ConsumeHandlers = {
83
114
  [ConsumeHandlerAnyKey]?: ConsumeMessageHandler;
@@ -152,8 +183,6 @@ export type ConsumeContext = {
152
183
  options?: ConsumeOptions;
153
184
  handlers: ConsumeHandlers;
154
185
  };
155
- //#endregion
156
- //#region src/consume/retry.d.ts
157
186
  /**
158
187
  * The 1-based delivery attempt of a re-published message.
159
188
  */
@@ -166,8 +195,6 @@ export declare const ATTEMPT_HEADER = "x-attempt";
166
195
  export declare function resolveAttempt(properties: {
167
196
  headers?: Record<string, unknown>;
168
197
  }): number;
169
- //#endregion
170
- //#region src/errors/base.d.ts
171
198
  /**
172
199
  * Root of every error thrown by amqp-extension.
173
200
  *
@@ -179,8 +206,6 @@ export declare class AmqpExtensionError extends BaseError {
179
206
  static [Symbol.hasInstance](input: unknown): boolean;
180
207
  constructor(input?: ErrorInput);
181
208
  }
182
- //#endregion
183
- //#region src/errors/types.d.ts
184
209
  export type BrokerReply = {
185
210
  replyCode: number;
186
211
  classId?: number;
@@ -194,8 +219,6 @@ export type AmqpReplyError = Error & {
194
219
  classId?: number;
195
220
  methodId?: number;
196
221
  };
197
- //#endregion
198
- //#region src/errors/broker.d.ts
199
222
  /**
200
223
  * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.
201
224
  */
@@ -219,8 +242,6 @@ export declare class BrokerError extends AmqpExtensionError {
219
242
  };
220
243
  static fromAmqp(err: AmqpReplyError): BrokerError;
221
244
  }
222
- //#endregion
223
- //#region src/errors/client.d.ts
224
245
  export declare class ClientError extends AmqpExtensionError {
225
246
  static [Symbol.hasInstance](input: unknown): boolean;
226
247
  constructor(input?: ErrorInput);
@@ -230,15 +251,11 @@ export declare class ClientError extends AmqpExtensionError {
230
251
  static attemptsExhausted(type?: string, cause?: unknown): ClientError;
231
252
  static timeout(cause?: unknown): ClientError;
232
253
  }
233
- //#endregion
234
- //#region src/errors/serialization.d.ts
235
254
  export declare class SerializationError extends AmqpExtensionError {
236
255
  static [Symbol.hasInstance](input: unknown): boolean;
237
256
  constructor(input?: ErrorInput);
238
257
  static payload(cause?: unknown): SerializationError;
239
258
  }
240
- //#endregion
241
- //#region src/errors/topology.d.ts
242
259
  export declare class TopologyError extends AmqpExtensionError {
243
260
  static [Symbol.hasInstance](input: unknown): boolean;
244
261
  constructor(input?: ErrorInput);
@@ -246,15 +263,11 @@ export declare class TopologyError extends AmqpExtensionError {
246
263
  static exchangeNameMissing(): TopologyError;
247
264
  static destinationMissing(): TopologyError;
248
265
  }
249
- //#endregion
250
- //#region src/errors/check.d.ts
251
266
  export declare function isAmqpExtensionError(input: unknown): input is AmqpExtensionError;
252
267
  export declare function isTopologyError(input: unknown): input is TopologyError;
253
268
  export declare function isClientError(input: unknown): input is ClientError;
254
269
  export declare function isBrokerError(input: unknown): input is BrokerError;
255
270
  export declare function isSerializationError(input: unknown): input is SerializationError;
256
- //#endregion
257
- //#region src/errors/constants.d.ts
258
271
  export declare enum ErrorCode {
259
272
  QUEUE_NAME_EMPTY = "QUEUE_NAME_EMPTY",
260
273
  EXCHANGE_NAME_MISSING = "EXCHANGE_NAME_MISSING",
@@ -272,27 +285,19 @@ export declare const TOPOLOGY_ERROR_MARKER: unique symbol;
272
285
  export declare const CLIENT_ERROR_MARKER: unique symbol;
273
286
  export declare const BROKER_ERROR_MARKER: unique symbol;
274
287
  export declare const SERIALIZATION_ERROR_MARKER: unique symbol;
275
- //#endregion
276
- //#region src/exchange/constants.d.ts
277
288
  export declare enum ExchangeType {
278
289
  FANOUT = "fanout",
279
290
  DIRECT = "direct",
280
291
  TOPIC = "topic",
281
292
  HEADERS = "headers"
282
293
  }
283
- //#endregion
284
- //#region src/exchange/types.d.ts
285
294
  export type ExchangeOptions = Options.AssertExchange;
286
295
  export type Exchange = {
287
296
  type: `${ExchangeType}`;
288
297
  name?: string;
289
298
  options?: ExchangeOptions;
290
299
  };
291
- //#endregion
292
- //#region src/exchange/utils.d.ts
293
300
  export declare function isDefaultExchange(input?: `${ExchangeType}`): input is ExchangeType.DIRECT;
294
- //#endregion
295
- //#region src/types.d.ts
296
301
  export type Connection = ReturnType<typeof connect>;
297
302
  export type ConnectionOptions = Options.Connect | string;
298
303
  export type ClientContext = {
@@ -306,14 +311,30 @@ export type ClientContext = {
306
311
  exchange?: Exchange;
307
312
  publishOptions?: PublishOptions;
308
313
  consumeOptions?: ConsumeOptions;
314
+ /**
315
+ * How many publish channels (one per message) the client and its of() siblings open at once;
316
+ * further publishes wait for a free one, within their timeout. Keep it below the broker's
317
+ * channel_max (2047 per connection by default), which also counts the consume channels.
318
+ *
319
+ * Default: 256 (PUBLISH_CHANNEL_MAX)
320
+ */
321
+ publishChannelMax?: number;
322
+ /**
323
+ * Bounds the publish channels instead of a new PublishChannelLimiter of publishChannelMax,
324
+ * e.g. to share one limit between Clients on the same connection.
325
+ * of() passes its own, so siblings share it.
326
+ */
327
+ publishChannelLimiter?: IPublishChannelLimiter;
309
328
  };
310
- //#endregion
311
- //#region src/module.d.ts
312
329
  export declare class Client {
313
330
  readonly connection: Connection;
314
331
  protected publishOptions: PublishOptions;
315
332
  protected consumeOptions: ConsumeOptions;
316
333
  protected exchange: Exchange;
334
+ /**
335
+ * Bounds the channels publish() and republish() open at once, shared with of() siblings.
336
+ */
337
+ protected readonly publishChannelLimiter: IPublishChannelLimiter;
317
338
  constructor(ctx: ClientContext);
318
339
  of(exchange: Exchange): Client;
319
340
  /**
@@ -339,10 +360,14 @@ export declare class Client {
339
360
  * message from before it is unroutable and dropped by the broker.
340
361
  */
341
362
  protected republish(queue: string, content: Buffer, options: RepublishOptions): Promise<void>;
363
+ /**
364
+ * Run a publish once a publish channel slot is free: an unbounded burst of channels
365
+ * exceeds the broker's channel_max, and the channels beyond it never open.
366
+ * The time spent waiting counts against the timeout (0: no limit); the rest is passed on.
367
+ */
368
+ protected withPublishChannel<T>(timeout: number, run: (timeout: number) => Promise<T>): Promise<T>;
342
369
  publish(ctx: PublishContext): Promise<boolean>;
343
370
  publish(to: string, data: any): Promise<boolean>;
344
371
  publish(to: string, data: any, options: PublishOptions): Promise<boolean>;
345
372
  }
346
- //#endregion
347
- export type { ConsumeMessage };
348
- //# sourceMappingURL=index.d.mts.map
373
+ export type { ConsumeMessage };
package/dist/index.mjs CHANGED
@@ -1,10 +1,9 @@
1
1
  import { BaseError, hasInstanceof, markInstanceof, matchesInstanceof } from "@ebec/core";
2
2
  import { connect } from "amqp-connection-manager";
3
- import { createMerger } from "smob";
4
- //#region src/consume/constants.ts
3
+ import { createMerger, isObject } from "smob";
4
+ // src/consume/constants.ts
5
5
  const ConsumeHandlerAnyKey = "$any";
6
- //#endregion
7
- //#region src/consume/retry.ts
6
+ // src/consume/retry.ts
8
7
  /**
9
8
  * The 1-based delivery attempt of a re-published message.
10
9
  */
@@ -49,8 +48,7 @@ async function retryMessage(message, publish, options) {
49
48
  await publish(message.content, properties);
50
49
  return true;
51
50
  }
52
- //#endregion
53
- //#region src/errors/constants.ts
51
+ // src/errors/constants.ts
54
52
  let ErrorCode = /* @__PURE__ */ function(ErrorCode) {
55
53
  ErrorCode["QUEUE_NAME_EMPTY"] = "QUEUE_NAME_EMPTY";
56
54
  ErrorCode["EXCHANGE_NAME_MISSING"] = "EXCHANGE_NAME_MISSING";
@@ -69,8 +67,7 @@ const TOPOLOGY_ERROR_MARKER = Symbol.for("amqp-extension/TopologyError");
69
67
  const CLIENT_ERROR_MARKER = Symbol.for("amqp-extension/ClientError");
70
68
  const BROKER_ERROR_MARKER = Symbol.for("amqp-extension/BrokerError");
71
69
  const SERIALIZATION_ERROR_MARKER = Symbol.for("amqp-extension/SerializationError");
72
- //#endregion
73
- //#region src/errors/base.ts
70
+ // src/errors/base.ts
74
71
  /**
75
72
  * Root of every error thrown by amqp-extension.
76
73
  *
@@ -87,8 +84,7 @@ var AmqpExtensionError = class extends BaseError {
87
84
  markInstanceof(this, AMQP_EXTENSION_ERROR_MARKER);
88
85
  }
89
86
  };
90
- //#endregion
91
- //#region src/errors/broker.ts
87
+ // src/errors/broker.ts
92
88
  /**
93
89
  * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.
94
90
  */
@@ -126,8 +122,7 @@ var BrokerError = class BrokerError extends AmqpExtensionError {
126
122
  });
127
123
  }
128
124
  };
129
- //#endregion
130
- //#region src/errors/check.ts
125
+ // src/errors/check.ts
131
126
  function isAmqpExtensionError(input) {
132
127
  return matchesInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);
133
128
  }
@@ -143,8 +138,7 @@ function isBrokerError(input) {
143
138
  function isSerializationError(input) {
144
139
  return matchesInstanceof(input, SERIALIZATION_ERROR_MARKER);
145
140
  }
146
- //#endregion
147
- //#region src/errors/client.ts
141
+ // src/errors/client.ts
148
142
  var ClientError = class ClientError extends AmqpExtensionError {
149
143
  static [Symbol.hasInstance](input) {
150
144
  return hasInstanceof(input, CLIENT_ERROR_MARKER);
@@ -187,8 +181,7 @@ var ClientError = class ClientError extends AmqpExtensionError {
187
181
  });
188
182
  }
189
183
  };
190
- //#endregion
191
- //#region src/errors/serialization.ts
184
+ // src/errors/serialization.ts
192
185
  var SerializationError = class SerializationError extends AmqpExtensionError {
193
186
  static [Symbol.hasInstance](input) {
194
187
  return hasInstanceof(input, SERIALIZATION_ERROR_MARKER);
@@ -205,8 +198,7 @@ var SerializationError = class SerializationError extends AmqpExtensionError {
205
198
  });
206
199
  }
207
200
  };
208
- //#endregion
209
- //#region src/errors/topology.ts
201
+ // src/errors/topology.ts
210
202
  var TopologyError = class TopologyError extends AmqpExtensionError {
211
203
  static [Symbol.hasInstance](input) {
212
204
  return hasInstanceof(input, TOPOLOGY_ERROR_MARKER);
@@ -234,8 +226,7 @@ var TopologyError = class TopologyError extends AmqpExtensionError {
234
226
  });
235
227
  }
236
228
  };
237
- //#endregion
238
- //#region src/exchange/constants.ts
229
+ // src/exchange/constants.ts
239
230
  let ExchangeType = /* @__PURE__ */ function(ExchangeType) {
240
231
  ExchangeType["FANOUT"] = "fanout";
241
232
  ExchangeType["DIRECT"] = "direct";
@@ -243,13 +234,11 @@ let ExchangeType = /* @__PURE__ */ function(ExchangeType) {
243
234
  ExchangeType["HEADERS"] = "headers";
244
235
  return ExchangeType;
245
236
  }({});
246
- //#endregion
247
- //#region src/exchange/utils.ts
237
+ // src/exchange/utils.ts
248
238
  function isDefaultExchange(input) {
249
239
  return typeof input === "undefined" || input === "direct";
250
240
  }
251
- //#endregion
252
- //#region src/consume/utils.ts
241
+ // src/consume/utils.ts
253
242
  function settle(fn) {
254
243
  try {
255
244
  fn();
@@ -344,8 +333,7 @@ async function fail(message, channel, options, context, failure) {
344
333
  else if (failure) await report(options, failure.error, message);
345
334
  return false;
346
335
  }
347
- //#endregion
348
- //#region src/errors/utils.ts
336
+ // src/errors/utils.ts
349
337
  /**
350
338
  * Map anything thrown below the Client (amqplib, amqp-connection-manager) onto the error tree.
351
339
  */
@@ -363,8 +351,68 @@ function toError(e) {
363
351
  cause: e
364
352
  });
365
353
  }
366
- //#endregion
367
- //#region src/queue/utils.ts
354
+ // src/publish/constants.ts
355
+ /**
356
+ * The default publish timeout in milliseconds.
357
+ */
358
+ const PUBLISH_TIMEOUT = 3e4;
359
+ /**
360
+ * The default number of publish channels a client (and its of() siblings) opens at once.
361
+ * Well below RabbitMQ's default channel_max (2047 per connection), which also counts the consume channels.
362
+ */
363
+ const PUBLISH_CHANNEL_MAX = 256;
364
+ // src/publish/limiter.ts
365
+ /**
366
+ * Bounds how many publish channels are open at once: a slot is handed to the
367
+ * next waiting publish in order (FIFO) when it is released.
368
+ */
369
+ var PublishChannelLimiter = class {
370
+ limit;
371
+ active = 0;
372
+ waiting = [];
373
+ constructor(limit) {
374
+ this.limit = limit;
375
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new RangeError(`The publish channel max must be a positive integer, got ${limit}.`);
376
+ }
377
+ tryAcquire() {
378
+ if (this.active >= this.limit) return;
379
+ this.active++;
380
+ return this.createRelease();
381
+ }
382
+ acquire(timeout) {
383
+ return new Promise((resolve, reject) => {
384
+ const release = this.tryAcquire();
385
+ if (release) {
386
+ resolve(release);
387
+ return;
388
+ }
389
+ let timer;
390
+ const waiter = () => {
391
+ clearTimeout(timer);
392
+ resolve(this.createRelease());
393
+ };
394
+ this.waiting.push(waiter);
395
+ if (timeout > 0) timer = setTimeout(() => {
396
+ this.waiting.splice(this.waiting.indexOf(waiter), 1);
397
+ reject(ClientError.timeout());
398
+ }, timeout);
399
+ });
400
+ }
401
+ createRelease() {
402
+ let released = false;
403
+ return () => {
404
+ if (released) return;
405
+ released = true;
406
+ this.release();
407
+ };
408
+ }
409
+ release() {
410
+ const next = this.waiting.shift();
411
+ if (next) next();
412
+ else this.active--;
413
+ }
414
+ };
415
+ // src/queue/utils.ts
368
416
  const QueueArguments = {
369
417
  queueType: "x-queue-type",
370
418
  deliveryLimit: "x-delivery-limit",
@@ -391,7 +439,7 @@ function planQueueOptions(options) {
391
439
  * Throws on invalid input, before anything touches the broker.
392
440
  */
393
441
  function planTopology(exchange, key, options, consume) {
394
- if (isDefaultExchange(exchange.type)) {
442
+ if (isDefaultExchange(exchange.type) && !exchange.name) {
395
443
  if (!key) throw TopologyError.queueNameEmpty();
396
444
  return { queue: {
397
445
  name: key,
@@ -434,8 +482,7 @@ async function assertTopology(channel, topology) {
434
482
  if (topology.exchange && typeof topology.bind === "string") await channel.bindQueue(queue, topology.exchange.name, topology.bind);
435
483
  return queue;
436
484
  }
437
- //#endregion
438
- //#region src/utils.ts
485
+ // src/utils.ts
439
486
  const mergeOptions = createMerger({
440
487
  priority: "left",
441
488
  inPlace: false,
@@ -443,8 +490,7 @@ const mergeOptions = createMerger({
443
490
  array: true,
444
491
  arrayDistinct: true
445
492
  });
446
- //#endregion
447
- //#region src/module.ts
493
+ // src/module.ts
448
494
  const closed = /* @__PURE__ */ new WeakSet();
449
495
  const noop = () => void 0;
450
496
  /**
@@ -472,7 +518,7 @@ function guard(setup) {
472
518
  function failure(channel) {
473
519
  const promise = new Promise((_resolve, reject) => {
474
520
  channel.on("error", (err) => {
475
- if (typeof err.code === "number") reject(err);
521
+ if (isObject(err) && typeof err.code === "number") reject(err);
476
522
  });
477
523
  channel.once("close", () => reject(ClientError.channelClosed()));
478
524
  });
@@ -484,7 +530,12 @@ var Client = class Client {
484
530
  publishOptions;
485
531
  consumeOptions;
486
532
  exchange;
533
+ /**
534
+ * Bounds the channels publish() and republish() open at once, shared with of() siblings.
535
+ */
536
+ publishChannelLimiter;
487
537
  constructor(ctx) {
538
+ this.publishChannelLimiter = ctx.publishChannelLimiter ?? new PublishChannelLimiter(ctx.publishChannelMax ?? 256);
488
539
  this.connection = ctx.connection ?? connect(ctx.connectionOptions, ctx.connectionManagerOptions);
489
540
  this.publishOptions = ctx.publishOptions || {};
490
541
  this.consumeOptions = ctx.consumeOptions || {};
@@ -498,6 +549,7 @@ var Client = class Client {
498
549
  connection: this.connection,
499
550
  publishOptions: this.publishOptions,
500
551
  consumeOptions: this.consumeOptions,
552
+ publishChannelLimiter: this.publishChannelLimiter,
501
553
  exchange
502
554
  });
503
555
  }
@@ -598,16 +650,35 @@ var Client = class Client {
598
650
  */
599
651
  async republish(queue, content, options) {
600
652
  this.assertOpen();
601
- const channel = this.connection.createChannel();
602
- const published = channel.publish("", queue, content, {
603
- ...options,
604
- timeout: 3e4
653
+ await this.withPublishChannel(PUBLISH_TIMEOUT, async (timeout) => {
654
+ const channel = this.connection.createChannel();
655
+ const published = channel.publish("", queue, content, {
656
+ ...options,
657
+ timeout
658
+ });
659
+ published.catch(noop);
660
+ try {
661
+ await Promise.race([published, failure(channel)]);
662
+ } finally {
663
+ channel.close().catch(noop);
664
+ }
605
665
  });
606
- published.catch(noop);
666
+ }
667
+ /**
668
+ * Run a publish once a publish channel slot is free: an unbounded burst of channels
669
+ * exceeds the broker's channel_max, and the channels beyond it never open.
670
+ * The time spent waiting counts against the timeout (0: no limit); the rest is passed on.
671
+ */
672
+ async withPublishChannel(timeout, run) {
673
+ const started = Date.now();
674
+ let release = this.publishChannelLimiter.tryAcquire();
675
+ const waited = !release;
676
+ if (!release) release = await this.publishChannelLimiter.acquire(timeout);
607
677
  try {
608
- await Promise.race([published, failure(channel)]);
678
+ if (waited && closed.has(this.connection)) throw ClientError.channelClosed();
679
+ return await run(timeout > 0 ? Math.max(1, timeout - (Date.now() - started)) : 0);
609
680
  } finally {
610
- channel.close().catch(noop);
681
+ release();
611
682
  }
612
683
  }
613
684
  async publish(_toOrCtx, _data, _options) {
@@ -633,20 +704,24 @@ var Client = class Client {
633
704
  if (typeof json === "undefined") throw SerializationError.payload();
634
705
  content = Buffer.from(json, "utf-8");
635
706
  }
636
- const channel = this.connection.createChannel({ setup: guard((ch) => assertTopology(ch, topology)) });
637
- const published = channel.publish(this.exchange.name || "", ctx.to, content, options);
638
- published.catch(noop);
639
- try {
640
- return await Promise.race([published, failure(channel)]);
641
- } finally {
642
- channel.close().catch(noop);
643
- }
707
+ return await this.withPublishChannel(options.timeout ?? 3e4, async (timeout) => {
708
+ const channel = this.connection.createChannel({ setup: guard((ch) => assertTopology(ch, topology)) });
709
+ const published = channel.publish(this.exchange.name || "", ctx.to, content, {
710
+ ...options,
711
+ timeout
712
+ });
713
+ published.catch(noop);
714
+ try {
715
+ return await Promise.race([published, failure(channel)]);
716
+ } finally {
717
+ channel.close().catch(noop);
718
+ }
719
+ });
644
720
  } catch (e) {
645
721
  throw toError(e);
646
722
  }
647
723
  }
648
724
  };
649
- //#endregion
650
- export { AMQP_EXTENSION_ERROR_MARKER, ATTEMPT_HEADER, AmqpExtensionError, BROKER_ERROR_MARKER, BrokerError, CLIENT_ERROR_MARKER, Client, ClientError, ConsumeHandlerAnyKey, ErrorCode, ExchangeType, SERIALIZATION_ERROR_MARKER, SerializationError, TOPOLOGY_ERROR_MARKER, TopologyError, isAmqpExtensionError, isBrokerError, isClientError, isDefaultExchange, isSerializationError, isTopologyError, resolveAttempt };
725
+ export { AMQP_EXTENSION_ERROR_MARKER, ATTEMPT_HEADER, AmqpExtensionError, BROKER_ERROR_MARKER, BrokerError, CLIENT_ERROR_MARKER, Client, ClientError, ConsumeHandlerAnyKey, ErrorCode, ExchangeType, PUBLISH_CHANNEL_MAX, PUBLISH_TIMEOUT, PublishChannelLimiter, SERIALIZATION_ERROR_MARKER, SerializationError, TOPOLOGY_ERROR_MARKER, TopologyError, isAmqpExtensionError, isBrokerError, isClientError, isDefaultExchange, isSerializationError, isTopologyError, resolveAttempt };
651
726
 
652
727
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/consume/constants.ts","../src/consume/retry.ts","../src/errors/constants.ts","../src/errors/base.ts","../src/errors/broker.ts","../src/errors/check.ts","../src/errors/client.ts","../src/errors/serialization.ts","../src/errors/topology.ts","../src/exchange/constants.ts","../src/exchange/utils.ts","../src/consume/utils.ts","../src/errors/utils.ts","../src/queue/utils.ts","../src/utils.ts","../src/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport const ConsumeHandlerAnyKey = '$any';\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ConsumeMessage } from 'amqplib';\nimport type { RepublishOptions } from '../publish';\nimport type { ConsumeRetryOptions } from './types';\n\n/**\n * The 1-based delivery attempt of a re-published message.\n */\nexport const ATTEMPT_HEADER = 'x-attempt';\n\n/**\n * The attempt a message is on. A missing or invalid header (a first delivery, an\n * older publisher counting elsewhere) is attempt 1: at worst a message is retried\n * more often, never dropped early.\n */\nexport function resolveAttempt(properties: { headers?: Record<string, unknown> }) : number {\n const value = properties.headers?.[ATTEMPT_HEADER];\n\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : 1;\n}\n\n/**\n * Delay before the given attempt: base, doubled per attempt, capped at 30s.\n */\nexport function resolveRetryDelay(attempt: number, base: number) : number {\n return Math.min(base * 2 ** (attempt - 2), 30_000);\n}\n\n/**\n * Re-publish a message with the next attempt in its x-attempt header, after the backoff.\n * Resolves false (without re-publishing) once the attempts are exhausted.\n * Rejects when the re-publish fails.\n *\n * ponytail: the backoff holds the prefetch slot, fine for seconds;\n * move to TTL + dead-letter-exchange delay queues for longer delays.\n */\nexport async function retryMessage(\n message: ConsumeMessage,\n publish: (content: Buffer, options: RepublishOptions) => Promise<void>,\n options: ConsumeRetryOptions,\n) : Promise<boolean> {\n const attempt = resolveAttempt(message.properties) + 1;\n if (attempt > (options.maxAttempts ?? 5)) {\n return false;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, resolveRetryDelay(attempt, options.delay ?? 1000));\n });\n\n const properties : RepublishOptions = {\n ...message.properties,\n headers: { ...message.properties.headers, [ATTEMPT_HEADER]: attempt },\n };\n // the broker rejects a user-id that is not the re-publishing connection's user\n delete properties.userId;\n\n await publish(message.content, properties);\n\n return true;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum ErrorCode {\n QUEUE_NAME_EMPTY = 'QUEUE_NAME_EMPTY',\n EXCHANGE_NAME_MISSING = 'EXCHANGE_NAME_MISSING',\n DESTINATION_MISSING = 'DESTINATION_MISSING',\n CLIENT_CLOSED = 'CLIENT_CLOSED',\n CHANNEL_CLOSED = 'CHANNEL_CLOSED',\n PUBLISH_TIMEOUT = 'PUBLISH_TIMEOUT',\n HANDLER_MISSING = 'HANDLER_MISSING',\n ATTEMPTS_EXHAUSTED = 'ATTEMPTS_EXHAUSTED',\n BROKER_REJECTED = 'BROKER_REJECTED',\n SERIALIZATION_FAILED = 'SERIALIZATION_FAILED',\n}\n\n// Symbol.for markers, shared by every copy of the library (see check.ts)\nexport const AMQP_EXTENSION_ERROR_MARKER = Symbol.for('amqp-extension/AmqpExtensionError');\nexport const TOPOLOGY_ERROR_MARKER = Symbol.for('amqp-extension/TopologyError');\nexport const CLIENT_ERROR_MARKER = Symbol.for('amqp-extension/ClientError');\nexport const BROKER_ERROR_MARKER = Symbol.for('amqp-extension/BrokerError');\nexport const SERIALIZATION_ERROR_MARKER = Symbol.for('amqp-extension/SerializationError');\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { BaseError, hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AMQP_EXTENSION_ERROR_MARKER } from './constants';\n\n/**\n * Root of every error thrown by amqp-extension.\n *\n * instanceof is duck-typed through @ebec/core's marker chain, so it also matches errors\n * from a duplicate copy of the library. Every subclass overrides Symbol.hasInstance with\n * its own marker, otherwise it would inherit this one and match every library error.\n */\nexport class AmqpExtensionError extends BaseError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, AMQP_EXTENSION_ERROR_MARKER);\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { BROKER_ERROR_MARKER, ErrorCode } from './constants';\nimport type { AmqpReplyError, BrokerReply } from './types';\n\n/**\n * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.\n */\nexport class BrokerError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, BROKER_ERROR_MARKER);\n }\n\n readonly replyCode: number;\n\n readonly classId?: number;\n\n readonly methodId?: number;\n\n constructor(input: ErrorInput, reply: BrokerReply) {\n super(input);\n\n this.replyCode = reply.replyCode;\n this.classId = reply.classId;\n this.methodId = reply.methodId;\n\n markInstanceof(this, BROKER_ERROR_MARKER);\n }\n\n override toJSON() {\n return {\n ...super.toJSON(),\n replyCode: this.replyCode,\n classId: this.classId,\n methodId: this.methodId,\n };\n }\n\n static fromAmqp(err: AmqpReplyError) {\n return new BrokerError(\n {\n code: ErrorCode.BROKER_REJECTED,\n message: err.message,\n cause: err,\n },\n {\n replyCode: err.code,\n classId: err.classId,\n methodId: err.methodId,\n },\n );\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { matchesInstanceof } from '@ebec/core';\nimport type { AmqpExtensionError } from './base';\nimport type { BrokerError } from './broker';\nimport type { ClientError } from './client';\nimport {\n AMQP_EXTENSION_ERROR_MARKER,\n BROKER_ERROR_MARKER,\n CLIENT_ERROR_MARKER,\n SERIALIZATION_ERROR_MARKER,\n TOPOLOGY_ERROR_MARKER,\n} from './constants';\nimport type { SerializationError } from './serialization';\nimport type { TopologyError } from './topology';\n\n// Unlike instanceof, the guards also match an error that crossed a boundary as JSON\n// (toJSON() keeps the marker chain as strings). ponytail: such a plain object has the\n// fields but not the methods of the class it is narrowed to.\n\nexport function isAmqpExtensionError(input: unknown) : input is AmqpExtensionError {\n return matchesInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n}\n\nexport function isTopologyError(input: unknown) : input is TopologyError {\n return matchesInstanceof(input, TOPOLOGY_ERROR_MARKER);\n}\n\nexport function isClientError(input: unknown) : input is ClientError {\n return matchesInstanceof(input, CLIENT_ERROR_MARKER);\n}\n\nexport function isBrokerError(input: unknown) : input is BrokerError {\n return matchesInstanceof(input, BROKER_ERROR_MARKER);\n}\n\nexport function isSerializationError(input: unknown) : input is SerializationError {\n return matchesInstanceof(input, SERIALIZATION_ERROR_MARKER);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { CLIENT_ERROR_MARKER, ErrorCode } from './constants';\n\nexport class ClientError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, CLIENT_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, CLIENT_ERROR_MARKER);\n }\n static closed() {\n return new ClientError({ code: ErrorCode.CLIENT_CLOSED, message: 'The client is closed.' });\n }\n\n static channelClosed(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.CHANNEL_CLOSED,\n message: 'Channel closed',\n cause,\n });\n }\n\n static handlerMissing(type?: string) {\n return new ClientError({\n code: ErrorCode.HANDLER_MISSING,\n message: typeof type === 'string' ? `No handler for the message type \"${type}\".` : 'No handler for a message without type.',\n });\n }\n\n static attemptsExhausted(type?: string, cause?: unknown) {\n return new ClientError({\n code: ErrorCode.ATTEMPTS_EXHAUSTED,\n message: typeof type === 'string' ?\n `The retry attempts for the message type \"${type}\" are exhausted.` :\n 'The retry attempts for a message without type are exhausted.',\n cause,\n });\n }\n\n static timeout(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.PUBLISH_TIMEOUT,\n message: 'The publish operation timed out.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, SERIALIZATION_ERROR_MARKER } from './constants';\n\nexport class SerializationError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, SERIALIZATION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, SERIALIZATION_ERROR_MARKER);\n }\n static payload(cause?: unknown) {\n return new SerializationError({\n code: ErrorCode.SERIALIZATION_FAILED,\n message: 'The message payload could not be serialized.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, TOPOLOGY_ERROR_MARKER } from './constants';\n\nexport class TopologyError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, TOPOLOGY_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, TOPOLOGY_ERROR_MARKER);\n }\n static queueNameEmpty() {\n return new TopologyError({\n code: ErrorCode.QUEUE_NAME_EMPTY,\n message: 'The queue name can not be empty if the default exchange is selected.',\n });\n }\n\n static exchangeNameMissing() {\n return new TopologyError({\n code: ErrorCode.EXCHANGE_NAME_MISSING,\n message: 'A non default exchange requires a name.',\n });\n }\n\n static destinationMissing() {\n return new TopologyError({\n code: ErrorCode.DESTINATION_MISSING,\n message: 'The publish operation requires a destination.',\n });\n }\n}\n","export enum ExchangeType {\n FANOUT = 'fanout',\n DIRECT = 'direct',\n TOPIC = 'topic',\n HEADERS = 'headers',\n}\n","import { ExchangeType } from './constants';\n\nexport function isDefaultExchange(\n input?: `${ExchangeType}`,\n) : input is ExchangeType.DIRECT {\n return typeof input === 'undefined' || input === ExchangeType.DIRECT;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport { ClientError } from '../errors';\nimport { ConsumeHandlerAnyKey } from './constants';\nimport { retryMessage } from './retry';\nimport type { ConsumeHandlers, ConsumeOptions, HandleMessageContext } from './types';\n\ntype Settlement = Pick<Channel, 'ack' | 'nack'>;\n\nfunction settle(fn: () => void) : void {\n try {\n fn();\n } catch {\n // the channel closed while the handler ran (e.g. reconnect): the broker redelivers the message anyway\n }\n}\n\nasync function report(options: ConsumeOptions, error: unknown, message: ConsumeMessage) : Promise<void> {\n if (!options.onError) {\n return;\n }\n\n try {\n await options.onError(error, message);\n } catch {\n // never reject: amqplib discards the consumer callback's promise\n }\n}\n\n/**\n * Track a run by message id until it settles, so redelivered copies can find it.\n * A run resolves true when it handed the message back to the broker (nack with requeue).\n */\nasync function track(inFlight: Map<string, Promise<boolean>>, id: string, run: Promise<boolean>) : Promise<boolean> {\n inFlight.set(id, run);\n\n try {\n return await run;\n } finally {\n if (inFlight.get(id) === run) {\n inFlight.delete(id);\n }\n }\n}\n\n/**\n * Dispatch a delivery to the handler for its type (or $any) and settle it:\n * ack on success, nack (requeue = requeueOnFailure) on failure or without handler, nothing with noAck.\n * With retry, a handler failure is re-published with the next attempt and the original acked instead,\n * and redeliveries of messages with a messageId are guarded (see ConsumeOptions.retry).\n * A failure is then reported to onError.\n */\nexport async function handleMessage(\n message: ConsumeMessage | null,\n channel: Settlement,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n) : Promise<void> {\n // null = the broker cancelled the consumer\n if (!message) {\n return;\n }\n\n const id = message.properties.messageId;\n if (!options.retry || options.noAck || !context || typeof id !== 'string') {\n await dispatch(message, channel, handlers, options, context);\n return;\n }\n\n if (message.fields.redelivered) {\n const running = context.inFlight.get(id);\n if (running) {\n // the channel was reset while this consumer still handles the original: the copy is not\n // run again. It waits for the original (runs never reject), since the original's settlement\n // goes to the reset channel: when the original meant to requeue (its re-publish failed),\n // the copy is requeued in its place, else dropped. Waiting holds the prefetch slot, which\n // also keeps the next message of an ordered stream from running next to the original.\n const requeued = await running;\n if (requeued) {\n settle(() => channel.nack(message, false, true));\n } else {\n settle(() => channel.ack(message));\n }\n return;\n }\n\n // the consumer died mid-handling (crash, consumer timeout), or a channel reset lost the ack\n // of a run that succeeded (that one runs again, at-least-once): a failed attempt.\n // Tracked through the backoff, so a reset during it does not retry it twice.\n // ponytail: in-process only; a redelivery landing on another consumer runs again.\n await track(context.inFlight, id, fail(message, channel, options, context));\n return;\n }\n\n await track(context.inFlight, id, dispatch(message, channel, handlers, options, context));\n}\n\nasync function dispatch(\n message: ConsumeMessage,\n channel: Settlement,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n) : Promise<boolean> {\n // the type is set by the publisher (untrusted): never resolve inherited properties like 'toString'\n const { type } = message.properties;\n const handler = (typeof type === 'string' && Object.hasOwn(handlers, type) ? handlers[type] : undefined) ||\n handlers[ConsumeHandlerAnyKey];\n\n if (!handler) {\n const requeue = !options.noAck && (options.requeueOnFailure ?? false);\n if (!options.noAck) {\n settle(() => channel.nack(message, false, requeue));\n }\n\n await report(options, ClientError.handlerMissing(type), message);\n return requeue;\n }\n\n try {\n await handler(message, channel as Channel);\n } catch (error) {\n return fail(message, channel, options, context, { error });\n }\n\n if (!options.noAck) {\n settle(() => channel.ack(message));\n }\n\n return false;\n}\n\n/**\n * Settle a failed message: retry it (with retry), else nack it.\n * failure is undefined for a redelivery of a message whose consumer died: there is no error to report.\n */\nasync function fail(\n message: ConsumeMessage,\n channel: Settlement,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n failure?: { error: unknown },\n) : Promise<boolean> {\n if (options.noAck) {\n if (failure) await report(options, failure.error, message);\n return false;\n }\n\n if (!options.retry || !context) {\n const requeue = options.requeueOnFailure ?? false;\n settle(() => channel.nack(message, false, requeue));\n if (failure) await report(options, failure.error, message);\n return requeue;\n }\n\n let retried : boolean;\n try {\n retried = await retryMessage(message, context.republish, options.retry);\n } catch {\n // the re-publish failed (e.g. broker unavailable): requeue, so it comes back as a redelivery\n settle(() => channel.nack(message, false, true));\n if (failure) await report(options, failure.error, message);\n return true;\n }\n\n // ponytail: a crash between the re-publish and this ack duplicates the message (at-least-once)\n settle(() => channel.ack(message));\n\n if (!retried) {\n await report(options, ClientError.attemptsExhausted(message.properties.type, failure?.error), message);\n } else if (failure) {\n await report(options, failure.error, message);\n }\n\n return false;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { AmqpExtensionError } from './base';\nimport { BrokerError } from './broker';\nimport { ClientError } from './client';\nimport type { AmqpReplyError } from './types';\n\n/**\n * Map anything thrown below the Client (amqplib, amqp-connection-manager) onto the error tree.\n */\nexport function toError(e: unknown) : AmqpExtensionError {\n if (e instanceof AmqpExtensionError) {\n return e;\n }\n\n if (!(e instanceof Error)) {\n return new AmqpExtensionError({ message: String(e), cause: e });\n }\n\n if (typeof (e as Partial<AmqpReplyError>).code === 'number') {\n return BrokerError.fromAmqp(e as AmqpReplyError);\n }\n\n // ponytail: amqp-connection-manager's errors carry no class or code, only these messages;\n // a reworded message falls through to the base class\n if (e.message === 'timeout') {\n return ClientError.timeout(e);\n }\n\n if (e.message === 'Channel closed') {\n return ClientError.channelClosed(e);\n }\n\n return new AmqpExtensionError({ message: e.message, cause: e });\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, Options } from 'amqplib';\nimport type { Exchange } from '../exchange';\nimport { TopologyError } from '../errors';\nimport { isDefaultExchange } from '../exchange';\nimport type { QueueOptions, Topology } from './types';\n\n\nconst QueueArguments = {\n queueType: 'x-queue-type',\n deliveryLimit: 'x-delivery-limit',\n deadLetterExchange: 'x-dead-letter-exchange',\n deadLetterRoutingKey: 'x-dead-letter-routing-key',\n messageTtl: 'x-message-ttl',\n maxLength: 'x-max-length',\n singleActiveConsumer: 'x-single-active-consumer',\n} as const satisfies Record<keyof QueueOptions, string>;\n\nfunction planQueueOptions(options: QueueOptions) : Options.AssertQueue {\n const queueOptions : Options.AssertQueue = { durable: true };\n\n const keys = Object.keys(QueueArguments) as (keyof QueueOptions)[];\n for (const key of keys) {\n const value = options[key];\n // false is left out like undefined, so a queue declared without the option stays equivalent\n if (typeof value !== 'undefined' && value !== false) {\n queueOptions.arguments = { ...queueOptions.arguments, [QueueArguments[key]]: value };\n }\n }\n\n return queueOptions;\n}\n\n/**\n * Plan the topology for publishing to or consuming from (consume = true) a key.\n * Throws on invalid input, before anything touches the broker.\n */\nexport function planTopology(\n exchange: Exchange,\n key: string,\n options: QueueOptions & { queue?: string },\n consume?: boolean,\n) : Topology {\n if (isDefaultExchange(exchange.type)) {\n if (!key) {\n throw TopologyError.queueNameEmpty();\n }\n\n return { queue: { name: key, options: planQueueOptions(options) } };\n }\n\n if (!exchange.name) {\n throw TopologyError.exchangeNameMissing();\n }\n\n const topology : Topology = {\n exchange: {\n name: exchange.name,\n type: exchange.type,\n options: exchange.options,\n },\n };\n\n if (!consume) {\n if (!key) {\n throw TopologyError.destinationMissing();\n }\n\n return topology;\n }\n\n if (options.queue === '') {\n throw TopologyError.queueNameEmpty();\n }\n\n topology.queue = options.queue ?\n { name: options.queue, options: planQueueOptions(options) } :\n {\n name: '',\n options: {\n durable: false,\n autoDelete: true,\n exclusive: true,\n },\n };\n topology.bind = key;\n\n return topology;\n}\n\n/**\n * Declare a planned topology. Returns the (possibly server generated) queue name.\n * Must run inside a channel setup function, so it is replayed on reconnect.\n */\nexport async function assertTopology(channel: Channel, topology: Topology) : Promise<string | undefined> {\n if (topology.exchange) {\n await channel.assertExchange(topology.exchange.name, topology.exchange.type, topology.exchange.options);\n }\n\n if (!topology.queue) {\n return undefined;\n }\n\n const { queue } = await channel.assertQueue(topology.queue.name, topology.queue.options);\n if (topology.exchange && typeof topology.bind === 'string') {\n await channel.bindQueue(queue, topology.exchange.name, topology.bind);\n }\n\n return queue;\n}\n","import { createMerger } from 'smob';\n\nconst mergeOptions = createMerger({\n priority: 'left',\n inPlace: false,\n clone: true,\n array: true,\n arrayDistinct: true,\n});\n\nexport {\n mergeOptions,\n};\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ChannelWrapper } from 'amqp-connection-manager';\nimport { connect } from 'amqp-connection-manager';\nimport type { Channel } from 'amqplib';\nimport type {\n ConsumeContext,\n ConsumeHandlers,\n ConsumeOptions,\n Consumer,\n HandleMessageContext,\n} from './consume';\nimport { handleMessage } from './consume/utils';\nimport { ClientError, SerializationError } from './errors';\nimport { toError } from './errors/utils';\nimport type { Exchange } from './exchange';\nimport { ExchangeType } from './exchange';\nimport type { PublishContext, PublishOptions, RepublishOptions } from './publish';\nimport { assertTopology, planTopology } from './queue/utils';\nimport type { ClientContext, Connection } from './types';\nimport { mergeOptions } from './utils';\n\n// connections closed through Client.close(), shared by of() siblings\nconst closed = new WeakSet<Connection>();\n\nconst noop = () => undefined;\n\n/**\n * Wrap a setup function, so a broker rejection during it (e.g. 403/406) closes only this channel:\n * without an 'error' listener on the raw channel, amqplib rethrows it and tears down the whole connection.\n * Only during setup: a channel error afterwards must still recycle the connection, because\n * amqp-connection-manager never recovers a channel-only close, so consumers would silently die.\n */\nfunction guard(setup: (channel: Channel) => Promise<unknown>) {\n return async (channel: Channel) => {\n channel.on('error', noop);\n\n try {\n await setup(channel);\n } finally {\n channel.off('error', noop);\n }\n };\n}\n\n/**\n * Reject when the broker rejects a setup function (an error with an AMQP reply code)\n * or the channel is closed (client.close()).\n * Errors without a reply code (connection dropped mid-setup) are transient:\n * the setup runs again on reconnect, so keep waiting.\n */\nfunction failure(channel: ChannelWrapper) : Promise<never> {\n const promise = new Promise<never>((_resolve, reject) => {\n // ponytail: the listener stays, so setup errors after a reconnect are swallowed instead of crashing the process\n channel.on('error', (err: Error & { code?: unknown }) => {\n if (typeof err.code === 'number') {\n reject(err);\n }\n });\n channel.once('close', () => reject(ClientError.channelClosed()));\n });\n\n // it may reject long after the call settled (e.g. close()), which is not an unhandled rejection\n promise.catch(noop);\n\n return promise;\n}\n\nexport class Client {\n public readonly connection: Connection;\n\n protected publishOptions : PublishOptions;\n\n protected consumeOptions : ConsumeOptions;\n\n protected exchange: Exchange;\n\n constructor(ctx: ClientContext) {\n this.connection = ctx.connection ?? connect(ctx.connectionOptions, ctx.connectionManagerOptions);\n this.publishOptions = ctx.publishOptions || {};\n this.consumeOptions = ctx.consumeOptions || {};\n this.exchange = ctx.exchange || {\n type: ExchangeType.DIRECT,\n name: '',\n };\n }\n\n of(exchange: Exchange) : Client {\n return new Client({\n connection: this.connection,\n publishOptions: this.publishOptions,\n consumeOptions: this.consumeOptions,\n exchange,\n });\n }\n\n /**\n * Close the (shared) connection and all its channels.\n */\n async close() : Promise<void> {\n closed.add(this.connection);\n await this.connection.close();\n }\n\n /**\n * `await using client = new Client(...)` closes the client when the scope ends.\n * Like close(), it closes the shared connection, so use it on the root client, not on of() siblings.\n */\n async [Symbol.asyncDispose]() : Promise<void> {\n await this.close();\n }\n\n protected assertOpen() : void {\n if (closed.has(this.connection)) {\n throw ClientError.closed();\n }\n }\n\n async consume(ctx: ConsumeContext) : Promise<Consumer>;\n\n async consume(from: string, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(\n _ctxOrFrom: ConsumeContext | string,\n _optionsOrHandlers?: ConsumeOptions | ConsumeHandlers,\n _handlers?: ConsumeHandlers,\n ) : Promise<Consumer> {\n const ctx : ConsumeContext = typeof _ctxOrFrom === 'string' ?\n {\n from: _ctxOrFrom,\n options: _handlers ? _optionsOrHandlers as ConsumeOptions : undefined,\n handlers: _handlers || _optionsOrHandlers as ConsumeHandlers,\n } :\n _ctxOrFrom;\n\n try {\n this.assertOpen();\n\n let options = this.consumeOptions;\n if (ctx.options) {\n // smob clones through structuredClone, which throws on functions\n const { onError, ...rest } = ctx.options;\n const { onError: fallback, ...defaults } = this.consumeOptions;\n options = { ...mergeOptions(rest, defaults), onError: onError ?? fallback };\n }\n\n const topology = planTopology(this.exchange, ctx.from, options, true);\n\n let cancelled = false;\n // the raw channel and consumer tag of the latest setup run\n let current : { ch: Channel, consumerTag: string } | undefined;\n // the latest setup run, awaited by cancel(): one in progress during a reconnect still registers a consumer\n let running : Promise<void> | undefined;\n const inFlight = new Set<Promise<void>>();\n // with retry: the same runs by messageId, for the redelivery guard; kept across setup runs (reconnects)\n const tracked = new Map<string, Promise<boolean>>();\n\n const channel = this.connection.createChannel({\n setup: guard((ch: Channel) => {\n running = (async () => {\n if (cancelled) {\n return;\n }\n\n const queue = await assertTopology(ch, topology) as string;\n\n if (typeof options.prefetchCount === 'number') {\n await ch.prefetch(options.prefetchCount);\n }\n\n const context : HandleMessageContext = {\n inFlight: tracked,\n republish: (content, props) => this.republish(queue, content, props),\n };\n\n const { consumerTag } = await ch.consume(queue, (message) => {\n const handled = handleMessage(message, ch, ctx.handlers, options, context);\n inFlight.add(handled);\n // handleMessage never rejects\n handled.then(() => inFlight.delete(handled));\n }, options);\n current = { ch, consumerTag };\n })();\n\n return running;\n }),\n });\n\n try {\n await Promise.race([channel.waitForConnect(), failure(channel)]);\n } catch (e) {\n // not awaited: amqplib never settles the close when the connection drops before close-ok\n channel.close().catch(noop);\n throw e;\n }\n\n let cancelling : Promise<void> | undefined;\n const cancel = () => {\n cancelling ??= (async () => {\n // no setup run after this one: a reconnect does not re-register the consumer\n cancelled = true;\n await running?.catch(noop);\n\n // basic.cancel: no new deliveries, the channel stays open to settle the in-flight ones\n // (fails on a closed channel, e.g. after close() or during a reconnect)\n await current?.ch.cancel(current.consumerTag).catch(noop);\n\n // ponytail: a handler that never settles hangs cancel()\n // (a loop: deliveries that arrived before the cancel took effect add to the set)\n while (inFlight.size > 0) {\n await Promise.all(inFlight);\n }\n\n // ponytail: hangs if the connection drops between ChannelClose and CloseOk (amqplib)\n await channel.close().catch(noop);\n })();\n\n return cancelling;\n };\n\n return { cancel, [Symbol.asyncDispose]: cancel };\n } catch (e) {\n throw toError(e);\n }\n }\n\n /**\n * Re-publish a message for a retry, through the default exchange by queue name:\n * that reaches the queue whatever exchange delivered it, without re-declaring it.\n * Its own channel, not the consume channel: that one may have been reset while\n * the handler ran, and this one waits for the broker's confirm.\n *\n * ponytail: a server-named queue is gone after a reconnect, so a retry of a\n * message from before it is unroutable and dropped by the broker.\n */\n protected async republish(queue: string, content: Buffer, options: RepublishOptions) : Promise<void> {\n this.assertOpen();\n\n const channel = this.connection.createChannel();\n\n // bounded, so a broker outage reaches the requeue nack instead of hanging cancel()\n const published = channel.publish('', queue, content, { ...options, timeout: 30_000 });\n published.catch(noop);\n\n try {\n // failure() also listens for the channel's errors: without a listener, a connection\n // lost while the channel opens surfaces as an unhandled rejection\n await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n }\n\n async publish(ctx: PublishContext) : Promise<boolean>;\n\n async publish(to: string, data: any) : Promise<boolean>;\n\n async publish(to: string, data: any, options: PublishOptions): Promise<boolean>;\n\n async publish(\n _toOrCtx: PublishContext | string,\n _data?: any,\n _options?: PublishOptions,\n ) : Promise<boolean> {\n const ctx : PublishContext = typeof _toOrCtx === 'string' ?\n {\n to: _toOrCtx,\n data: _data,\n options: _options,\n } :\n _toOrCtx;\n\n try {\n this.assertOpen();\n\n const options = ctx.options ? mergeOptions(ctx.options, this.publishOptions) : this.publishOptions;\n const topology = planTopology(this.exchange, ctx.to, options);\n\n let content : Buffer;\n if (Buffer.isBuffer(ctx.data)) {\n content = ctx.data;\n } else if (typeof ctx.data === 'string') {\n content = Buffer.from(ctx.data, 'utf-8');\n } else {\n let json : string | undefined;\n try {\n json = JSON.stringify(ctx.data);\n } catch (e) {\n throw SerializationError.payload(e);\n }\n\n // undefined, functions and symbols serialize to undefined\n if (typeof json === 'undefined') {\n throw SerializationError.payload();\n }\n\n content = Buffer.from(json, 'utf-8');\n }\n\n // ponytail: one channel per publish (self-healing, no shared state), reuse channels when throughput matters\n const channel = this.connection.createChannel({ setup: guard((ch: Channel) => assertTopology(ch, topology)) });\n\n // queued right away: sent once the setup ran, bounded by options.timeout, rejected by close()\n const published = channel.publish(this.exchange.name || '', ctx.to, content, options);\n published.catch(noop);\n\n try {\n return await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n } catch (e) {\n throw toError(e);\n }\n }\n}\n"],"mappings":";;;;AAOA,MAAa,uBAAuB;;;;;;ACOpC,MAAa,iBAAiB;;;;;;AAO9B,SAAgB,eAAe,YAA4D;CACvF,MAAM,QAAQ,WAAW,UAAU;CAEnC,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,SAAS,IAAI,QAAQ;AAC5F;;;;AAKA,SAAgB,kBAAkB,SAAiB,MAAuB;CACtE,OAAO,KAAK,IAAI,OAAO,MAAM,UAAU,IAAI,GAAM;AACrD;;;;;;;;;AAUA,eAAsB,aAClB,SACA,SACA,SACiB;CACjB,MAAM,UAAU,eAAe,QAAQ,UAAU,IAAI;CACrD,IAAI,WAAW,QAAQ,eAAe,IAClC,OAAO;CAGX,MAAM,IAAI,SAAS,YAAY;EAC3B,WAAW,SAAS,kBAAkB,SAAS,QAAQ,SAAS,GAAI,CAAC;CACzE,CAAC;CAED,MAAM,aAAgC;EAClC,GAAG,QAAQ;EACX,SAAS;GAAE,GAAG,QAAQ,WAAW;IAAU,iBAAiB;EAAQ;CACxE;CAEA,OAAO,WAAW;CAElB,MAAM,QAAQ,QAAQ,SAAS,UAAU;CAEzC,OAAO;AACX;;;AC3DA,IAAY,YAAL,yBAAA,WAAA;CACH,UAAA,sBAAA;CACA,UAAA,2BAAA;CACA,UAAA,yBAAA;CACA,UAAA,mBAAA;CACA,UAAA,oBAAA;CACA,UAAA,qBAAA;CACA,UAAA,qBAAA;CACA,UAAA,wBAAA;CACA,UAAA,qBAAA;CACA,UAAA,0BAAA;;AACJ,EAAA,CAAA,CAAA;AAGA,MAAa,8BAA8B,OAAO,IAAI,mCAAmC;AACzF,MAAa,wBAAwB,OAAO,IAAI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AAC;IACtC;IAGA,IAAI,OAAO,SAAS,aAChB,MAAM,mBAAmB,QAAQ;IAGrC,UAAU,OAAO,KAAK,MAAM,OAAO;GACvC;GAGA,MAAM,UAAU,KAAK,WAAW,cAAc,EAAE,OAAO,OAAO,OAAgB,eAAe,IAAI,QAAQ,CAAC,EAAE,CAAC;GAG7G,MAAM,YAAY,QAAQ,QAAQ,KAAK,SAAS,QAAQ,IAAI,IAAI,IAAI,SAAS,OAAO;GACpF,UAAU,MAAM,IAAI;GAEpB,IAAI;IACA,OAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,QAAQ,OAAO,CAAC,CAAC;GAC3D,UAAU;IAEN,QAAQ,MAAM,CAAC,CAAC,MAAM,IAAI;GAC9B;EACJ,SAAS,GAAG;GACR,MAAM,QAAQ,CAAC;EACnB;CACJ;AACJ"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/consume/constants.ts","../src/consume/retry.ts","../src/errors/constants.ts","../src/errors/base.ts","../src/errors/broker.ts","../src/errors/check.ts","../src/errors/client.ts","../src/errors/serialization.ts","../src/errors/topology.ts","../src/exchange/constants.ts","../src/exchange/utils.ts","../src/consume/utils.ts","../src/errors/utils.ts","../src/publish/constants.ts","../src/publish/limiter.ts","../src/queue/utils.ts","../src/utils.ts","../src/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport const ConsumeHandlerAnyKey = '$any';\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ConsumeMessage } from 'amqplib';\nimport type { RepublishOptions } from '../publish';\nimport type { ConsumeRetryOptions } from './types';\n\n/**\n * The 1-based delivery attempt of a re-published message.\n */\nexport const ATTEMPT_HEADER = 'x-attempt';\n\n/**\n * The attempt a message is on. A missing or invalid header (a first delivery, an\n * older publisher counting elsewhere) is attempt 1: at worst a message is retried\n * more often, never dropped early.\n */\nexport function resolveAttempt(properties: { headers?: Record<string, unknown> }) : number {\n const value = properties.headers?.[ATTEMPT_HEADER];\n\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : 1;\n}\n\n/**\n * Delay before the given attempt: base, doubled per attempt, capped at 30s.\n */\nexport function resolveRetryDelay(attempt: number, base: number) : number {\n return Math.min(base * 2 ** (attempt - 2), 30_000);\n}\n\n/**\n * Re-publish a message with the next attempt in its x-attempt header, after the backoff.\n * Resolves false (without re-publishing) once the attempts are exhausted.\n * Rejects when the re-publish fails.\n *\n * ponytail: the backoff holds the prefetch slot, fine for seconds;\n * move to TTL + dead-letter-exchange delay queues for longer delays.\n */\nexport async function retryMessage(\n message: ConsumeMessage,\n publish: (content: Buffer, options: RepublishOptions) => Promise<void>,\n options: ConsumeRetryOptions,\n) : Promise<boolean> {\n const attempt = resolveAttempt(message.properties) + 1;\n\n if (attempt > (options.maxAttempts ?? 5)) {\n return false;\n }\n\n await new Promise((resolve) => {\n setTimeout(resolve, resolveRetryDelay(attempt, options.delay ?? 1000));\n });\n\n const properties : RepublishOptions = {\n ...message.properties,\n headers: { ...message.properties.headers, [ATTEMPT_HEADER]: attempt },\n };\n\n // the broker rejects a user-id that is not the re-publishing connection's user\n delete properties.userId;\n\n await publish(message.content, properties);\n\n return true;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum ErrorCode {\n QUEUE_NAME_EMPTY = 'QUEUE_NAME_EMPTY',\n EXCHANGE_NAME_MISSING = 'EXCHANGE_NAME_MISSING',\n DESTINATION_MISSING = 'DESTINATION_MISSING',\n CLIENT_CLOSED = 'CLIENT_CLOSED',\n CHANNEL_CLOSED = 'CHANNEL_CLOSED',\n PUBLISH_TIMEOUT = 'PUBLISH_TIMEOUT',\n HANDLER_MISSING = 'HANDLER_MISSING',\n ATTEMPTS_EXHAUSTED = 'ATTEMPTS_EXHAUSTED',\n BROKER_REJECTED = 'BROKER_REJECTED',\n SERIALIZATION_FAILED = 'SERIALIZATION_FAILED',\n}\n\n// Symbol.for markers, shared by every copy of the library (see check.ts)\nexport const AMQP_EXTENSION_ERROR_MARKER = Symbol.for('amqp-extension/AmqpExtensionError');\nexport const TOPOLOGY_ERROR_MARKER = Symbol.for('amqp-extension/TopologyError');\nexport const CLIENT_ERROR_MARKER = Symbol.for('amqp-extension/ClientError');\nexport const BROKER_ERROR_MARKER = Symbol.for('amqp-extension/BrokerError');\nexport const SERIALIZATION_ERROR_MARKER = Symbol.for('amqp-extension/SerializationError');\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { BaseError, hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AMQP_EXTENSION_ERROR_MARKER } from './constants';\n\n/**\n * Root of every error thrown by amqp-extension.\n *\n * instanceof is duck-typed through @ebec/core's marker chain, so it also matches errors\n * from a duplicate copy of the library. Every subclass overrides Symbol.hasInstance with\n * its own marker, otherwise it would inherit this one and match every library error.\n */\nexport class AmqpExtensionError extends BaseError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, AMQP_EXTENSION_ERROR_MARKER);\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { BROKER_ERROR_MARKER, ErrorCode } from './constants';\nimport type { AmqpReplyError, BrokerReply } from './types';\n\n/**\n * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.\n */\nexport class BrokerError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, BROKER_ERROR_MARKER);\n }\n\n readonly replyCode: number;\n\n readonly classId?: number;\n\n readonly methodId?: number;\n\n constructor(input: ErrorInput, reply: BrokerReply) {\n super(input);\n\n this.replyCode = reply.replyCode;\n this.classId = reply.classId;\n this.methodId = reply.methodId;\n\n markInstanceof(this, BROKER_ERROR_MARKER);\n }\n\n override toJSON() {\n return {\n ...super.toJSON(),\n replyCode: this.replyCode,\n classId: this.classId,\n methodId: this.methodId,\n };\n }\n\n static fromAmqp(err: AmqpReplyError) {\n return new BrokerError(\n {\n code: ErrorCode.BROKER_REJECTED,\n message: err.message,\n cause: err,\n },\n {\n replyCode: err.code,\n classId: err.classId,\n methodId: err.methodId,\n },\n );\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { matchesInstanceof } from '@ebec/core';\nimport type { AmqpExtensionError } from './base';\nimport type { BrokerError } from './broker';\nimport type { ClientError } from './client';\nimport {\n AMQP_EXTENSION_ERROR_MARKER,\n BROKER_ERROR_MARKER,\n CLIENT_ERROR_MARKER,\n SERIALIZATION_ERROR_MARKER,\n TOPOLOGY_ERROR_MARKER,\n} from './constants';\nimport type { SerializationError } from './serialization';\nimport type { TopologyError } from './topology';\n\n// Unlike instanceof, the guards also match an error that crossed a boundary as JSON\n// (toJSON() keeps the marker chain as strings). ponytail: such a plain object has the\n// fields but not the methods of the class it is narrowed to.\n\nexport function isAmqpExtensionError(input: unknown) : input is AmqpExtensionError {\n return matchesInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);\n}\n\nexport function isTopologyError(input: unknown) : input is TopologyError {\n return matchesInstanceof(input, TOPOLOGY_ERROR_MARKER);\n}\n\nexport function isClientError(input: unknown) : input is ClientError {\n return matchesInstanceof(input, CLIENT_ERROR_MARKER);\n}\n\nexport function isBrokerError(input: unknown) : input is BrokerError {\n return matchesInstanceof(input, BROKER_ERROR_MARKER);\n}\n\nexport function isSerializationError(input: unknown) : input is SerializationError {\n return matchesInstanceof(input, SERIALIZATION_ERROR_MARKER);\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { CLIENT_ERROR_MARKER, ErrorCode } from './constants';\n\nexport class ClientError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, CLIENT_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, CLIENT_ERROR_MARKER);\n }\n static closed() {\n return new ClientError({ code: ErrorCode.CLIENT_CLOSED, message: 'The client is closed.' });\n }\n\n static channelClosed(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.CHANNEL_CLOSED,\n message: 'Channel closed',\n cause,\n });\n }\n\n static handlerMissing(type?: string) {\n return new ClientError({\n code: ErrorCode.HANDLER_MISSING,\n message: typeof type === 'string' ? `No handler for the message type \"${type}\".` : 'No handler for a message without type.',\n });\n }\n\n static attemptsExhausted(type?: string, cause?: unknown) {\n return new ClientError({\n code: ErrorCode.ATTEMPTS_EXHAUSTED,\n message: typeof type === 'string' ?\n `The retry attempts for the message type \"${type}\" are exhausted.` :\n 'The retry attempts for a message without type are exhausted.',\n cause,\n });\n }\n\n static timeout(cause?: unknown) {\n return new ClientError({\n code: ErrorCode.PUBLISH_TIMEOUT,\n message: 'The publish operation timed out.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, SERIALIZATION_ERROR_MARKER } from './constants';\n\nexport class SerializationError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, SERIALIZATION_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, SERIALIZATION_ERROR_MARKER);\n }\n static payload(cause?: unknown) {\n return new SerializationError({\n code: ErrorCode.SERIALIZATION_FAILED,\n message: 'The message payload could not be serialized.',\n cause,\n });\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ErrorInput } from '@ebec/core';\nimport { hasInstanceof, markInstanceof } from '@ebec/core';\nimport { AmqpExtensionError } from './base';\nimport { ErrorCode, TOPOLOGY_ERROR_MARKER } from './constants';\n\nexport class TopologyError extends AmqpExtensionError {\n static override [Symbol.hasInstance](input: unknown) : boolean {\n return hasInstanceof(input, TOPOLOGY_ERROR_MARKER);\n }\n\n constructor(input?: ErrorInput) {\n super(input);\n markInstanceof(this, TOPOLOGY_ERROR_MARKER);\n }\n static queueNameEmpty() {\n return new TopologyError({\n code: ErrorCode.QUEUE_NAME_EMPTY,\n message: 'The queue name can not be empty if the default exchange is selected.',\n });\n }\n\n static exchangeNameMissing() {\n return new TopologyError({\n code: ErrorCode.EXCHANGE_NAME_MISSING,\n message: 'A non default exchange requires a name.',\n });\n }\n\n static destinationMissing() {\n return new TopologyError({\n code: ErrorCode.DESTINATION_MISSING,\n message: 'The publish operation requires a destination.',\n });\n }\n}\n","export enum ExchangeType {\n FANOUT = 'fanout',\n DIRECT = 'direct',\n TOPIC = 'topic',\n HEADERS = 'headers',\n}\n","import { ExchangeType } from './constants';\n\nexport function isDefaultExchange(\n input?: `${ExchangeType}`,\n) : input is ExchangeType.DIRECT {\n return typeof input === 'undefined' || input === ExchangeType.DIRECT;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport { ClientError } from '../errors';\nimport { ConsumeHandlerAnyKey } from './constants';\nimport { retryMessage } from './retry';\nimport type { ConsumeHandlers, ConsumeOptions, HandleMessageContext } from './types';\n\ntype Settlement = Pick<Channel, 'ack' | 'nack'>;\n\nfunction settle(fn: () => void) : void {\n try {\n fn();\n } catch {\n // the channel closed while the handler ran (e.g. reconnect): the broker redelivers the message anyway\n }\n}\n\nasync function report(options: ConsumeOptions, error: unknown, message: ConsumeMessage) : Promise<void> {\n if (!options.onError) {\n return;\n }\n\n try {\n await options.onError(error, message);\n } catch {\n // never reject: amqplib discards the consumer callback's promise\n }\n}\n\n/**\n * Track a run by message id until it settles, so redelivered copies can find it.\n * A run resolves true when it handed the message back to the broker (nack with requeue).\n */\nasync function track(inFlight: Map<string, Promise<boolean>>, id: string, run: Promise<boolean>) : Promise<boolean> {\n inFlight.set(id, run);\n\n try {\n return await run;\n } finally {\n if (inFlight.get(id) === run) {\n inFlight.delete(id);\n }\n }\n}\n\n/**\n * Dispatch a delivery to the handler for its type (or $any) and settle it:\n * ack on success, nack (requeue = requeueOnFailure) on failure or without handler, nothing with noAck.\n * With retry, a handler failure is re-published with the next attempt and the original acked instead,\n * and redeliveries of messages with a messageId are guarded (see ConsumeOptions.retry).\n * A failure is then reported to onError.\n */\nexport async function handleMessage(\n message: ConsumeMessage | null,\n channel: Settlement,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n) : Promise<void> {\n // null = the broker cancelled the consumer\n if (!message) {\n return;\n }\n\n const id = message.properties.messageId;\n\n if (!options.retry || options.noAck || !context || typeof id !== 'string') {\n await dispatch(message, channel, handlers, options, context);\n\n return;\n }\n\n if (message.fields.redelivered) {\n const running = context.inFlight.get(id);\n\n if (running) {\n // the channel was reset while this consumer still handles the original: the copy is not\n // run again. It waits for the original (runs never reject), since the original's settlement\n // goes to the reset channel: when the original meant to requeue (its re-publish failed),\n // the copy is requeued in its place, else dropped. Waiting holds the prefetch slot, which\n // also keeps the next message of an ordered stream from running next to the original.\n const requeued = await running;\n\n if (requeued) {\n settle(() => channel.nack(message, false, true));\n } else {\n settle(() => channel.ack(message));\n }\n\n return;\n }\n\n // the consumer died mid-handling (crash, consumer timeout), or a channel reset lost the ack\n // of a run that succeeded (that one runs again, at-least-once): a failed attempt.\n // Tracked through the backoff, so a reset during it does not retry it twice.\n // ponytail: in-process only; a redelivery landing on another consumer runs again.\n await track(context.inFlight, id, fail(message, channel, options, context));\n\n return;\n }\n\n await track(context.inFlight, id, dispatch(message, channel, handlers, options, context));\n}\n\nasync function dispatch(\n message: ConsumeMessage,\n channel: Settlement,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n) : Promise<boolean> {\n // the type is set by the publisher (untrusted): never resolve inherited properties like 'toString'\n const { type } = message.properties;\n const handler = (typeof type === 'string' && Object.hasOwn(handlers, type) ? handlers[type] : undefined) ||\n handlers[ConsumeHandlerAnyKey];\n\n if (!handler) {\n const requeue = !options.noAck && (options.requeueOnFailure ?? false);\n\n if (!options.noAck) {\n settle(() => channel.nack(message, false, requeue));\n }\n\n await report(options, ClientError.handlerMissing(type), message);\n\n return requeue;\n }\n\n try {\n await handler(message, channel as Channel);\n } catch (error) {\n return fail(message, channel, options, context, { error });\n }\n\n if (!options.noAck) {\n settle(() => channel.ack(message));\n }\n\n return false;\n}\n\n/**\n * Settle a failed message: retry it (with retry), else nack it.\n * failure is undefined for a redelivery of a message whose consumer died: there is no error to report.\n */\nasync function fail(\n message: ConsumeMessage,\n channel: Settlement,\n options: ConsumeOptions,\n context?: HandleMessageContext,\n failure?: { error: unknown },\n) : Promise<boolean> {\n if (options.noAck) {\n if (failure) {\n await report(options, failure.error, message);\n }\n\n return false;\n }\n\n if (!options.retry || !context) {\n const requeue = options.requeueOnFailure ?? false;\n\n settle(() => channel.nack(message, false, requeue));\n\n if (failure) {\n await report(options, failure.error, message);\n }\n\n return requeue;\n }\n\n let retried : boolean;\n\n try {\n retried = await retryMessage(message, context.republish, options.retry);\n } catch {\n // the re-publish failed (e.g. broker unavailable): requeue, so it comes back as a redelivery\n settle(() => channel.nack(message, false, true));\n\n if (failure) {\n await report(options, failure.error, message);\n }\n\n return true;\n }\n\n // ponytail: a crash between the re-publish and this ack duplicates the message (at-least-once)\n settle(() => channel.ack(message));\n\n if (!retried) {\n await report(options, ClientError.attemptsExhausted(message.properties.type, failure?.error), message);\n } else if (failure) {\n await report(options, failure.error, message);\n }\n\n return false;\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { AmqpExtensionError } from './base';\nimport { BrokerError } from './broker';\nimport { ClientError } from './client';\nimport type { AmqpReplyError } from './types';\n\n/**\n * Map anything thrown below the Client (amqplib, amqp-connection-manager) onto the error tree.\n */\nexport function toError(e: unknown) : AmqpExtensionError {\n if (e instanceof AmqpExtensionError) {\n return e;\n }\n\n if (!(e instanceof Error)) {\n return new AmqpExtensionError({ message: String(e), cause: e });\n }\n\n if (typeof (e as Partial<AmqpReplyError>).code === 'number') {\n return BrokerError.fromAmqp(e as AmqpReplyError);\n }\n\n // ponytail: amqp-connection-manager's errors carry no class or code, only these messages;\n // a reworded message falls through to the base class\n if (e.message === 'timeout') {\n return ClientError.timeout(e);\n }\n\n if (e.message === 'Channel closed') {\n return ClientError.channelClosed(e);\n }\n\n return new AmqpExtensionError({ message: e.message, cause: e });\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * The default publish timeout in milliseconds.\n */\nexport const PUBLISH_TIMEOUT = 30_000;\n\n/**\n * The default number of publish channels a client (and its of() siblings) opens at once.\n * Well below RabbitMQ's default channel_max (2047 per connection), which also counts the consume channels.\n */\nexport const PUBLISH_CHANNEL_MAX = 256;\n","import { ClientError } from '../errors';\nimport type { IPublishChannelLimiter } from './types';\n\n/**\n * Bounds how many publish channels are open at once: a slot is handed to the\n * next waiting publish in order (FIFO) when it is released.\n */\nexport class PublishChannelLimiter implements IPublishChannelLimiter {\n protected active = 0;\n\n protected waiting : (() => void)[] = [];\n\n constructor(protected readonly limit: number) {\n if (!Number.isSafeInteger(limit) || limit < 1) {\n throw new RangeError(`The publish channel max must be a positive integer, got ${limit}.`);\n }\n }\n\n tryAcquire() : (() => void) | undefined {\n if (this.active >= this.limit) {\n return undefined;\n }\n\n this.active++;\n\n return this.createRelease();\n }\n\n acquire(timeout: number) : Promise<() => void> {\n return new Promise((resolve, reject) => {\n const release = this.tryAcquire();\n\n if (release) {\n resolve(release);\n\n return;\n }\n\n let timer : ReturnType<typeof setTimeout> | undefined;\n const waiter = () => {\n clearTimeout(timer);\n // the releasing publish handed its slot over, active stays\n resolve(this.createRelease());\n };\n\n this.waiting.push(waiter);\n\n if (timeout > 0) {\n timer = setTimeout(() => {\n this.waiting.splice(this.waiting.indexOf(waiter), 1);\n reject(ClientError.timeout());\n }, timeout);\n }\n });\n }\n\n protected createRelease() : () => void {\n let released = false;\n\n return () => {\n if (released) {\n return;\n }\n\n released = true;\n this.release();\n };\n }\n\n protected release() {\n const next = this.waiting.shift();\n\n if (next) {\n // hand the slot over, active stays\n next();\n } else {\n this.active--;\n }\n }\n}\n","/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { Channel, Options } from 'amqplib';\nimport type { Exchange } from '../exchange';\nimport { TopologyError } from '../errors';\nimport { isDefaultExchange } from '../exchange';\nimport type { QueueOptions, Topology } from './types';\n\n\nconst QueueArguments = {\n queueType: 'x-queue-type',\n deliveryLimit: 'x-delivery-limit',\n deadLetterExchange: 'x-dead-letter-exchange',\n deadLetterRoutingKey: 'x-dead-letter-routing-key',\n messageTtl: 'x-message-ttl',\n maxLength: 'x-max-length',\n singleActiveConsumer: 'x-single-active-consumer',\n} as const satisfies Record<keyof QueueOptions, string>;\n\nfunction planQueueOptions(options: QueueOptions) : Options.AssertQueue {\n const queueOptions : Options.AssertQueue = { durable: true };\n\n const keys = Object.keys(QueueArguments) as (keyof QueueOptions)[];\n\n for (const key of keys) {\n const value = options[key];\n\n // false is left out like undefined, so a queue declared without the option stays equivalent\n if (typeof value !== 'undefined' && value !== false) {\n queueOptions.arguments = { ...queueOptions.arguments, [QueueArguments[key]]: value };\n }\n }\n\n return queueOptions;\n}\n\n/**\n * Plan the topology for publishing to or consuming from (consume = true) a key.\n * Throws on invalid input, before anything touches the broker.\n */\nexport function planTopology(\n exchange: Exchange,\n key: string,\n options: QueueOptions & { queue?: string },\n consume?: boolean,\n) : Topology {\n // a named direct exchange is a named exchange like any other; only a nameless one is the default exchange\n if (isDefaultExchange(exchange.type) && !exchange.name) {\n if (!key) {\n throw TopologyError.queueNameEmpty();\n }\n\n return { queue: { name: key, options: planQueueOptions(options) } };\n }\n\n if (!exchange.name) {\n throw TopologyError.exchangeNameMissing();\n }\n\n const topology : Topology = {\n exchange: {\n name: exchange.name,\n type: exchange.type,\n options: exchange.options,\n },\n };\n\n if (!consume) {\n if (!key) {\n throw TopologyError.destinationMissing();\n }\n\n return topology;\n }\n\n if (options.queue === '') {\n throw TopologyError.queueNameEmpty();\n }\n\n topology.queue = options.queue ?\n { name: options.queue, options: planQueueOptions(options) } :\n {\n name: '',\n options: {\n durable: false,\n autoDelete: true,\n exclusive: true,\n },\n };\n topology.bind = key;\n\n return topology;\n}\n\n/**\n * Declare a planned topology. Returns the (possibly server generated) queue name.\n * Must run inside a channel setup function, so it is replayed on reconnect.\n */\nexport async function assertTopology(channel: Channel, topology: Topology) : Promise<string | undefined> {\n if (topology.exchange) {\n await channel.assertExchange(topology.exchange.name, topology.exchange.type, topology.exchange.options);\n }\n\n if (!topology.queue) {\n return undefined;\n }\n\n const { queue } = await channel.assertQueue(topology.queue.name, topology.queue.options);\n\n if (topology.exchange && typeof topology.bind === 'string') {\n await channel.bindQueue(queue, topology.exchange.name, topology.bind);\n }\n\n return queue;\n}\n","import { createMerger } from 'smob';\n\nconst mergeOptions = createMerger({\n priority: 'left',\n inPlace: false,\n clone: true,\n array: true,\n arrayDistinct: true,\n});\n\nexport {\n mergeOptions,\n};\n","/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type { ChannelWrapper } from 'amqp-connection-manager';\nimport { connect } from 'amqp-connection-manager';\nimport type { Channel } from 'amqplib';\nimport { isObject } from 'smob';\nimport type {\n ConsumeContext,\n ConsumeHandlers,\n ConsumeOptions,\n Consumer,\n HandleMessageContext,\n} from './consume';\nimport { handleMessage } from './consume/utils';\nimport { ClientError, SerializationError } from './errors';\nimport { toError } from './errors/utils';\nimport type { Exchange } from './exchange';\nimport { ExchangeType } from './exchange';\nimport type {\n IPublishChannelLimiter, \n PublishContext, \n PublishOptions, \n RepublishOptions,\n} from './publish';\nimport { PUBLISH_CHANNEL_MAX, PUBLISH_TIMEOUT, PublishChannelLimiter } from './publish';\nimport { assertTopology, planTopology } from './queue/utils';\nimport type { ClientContext, Connection } from './types';\nimport { mergeOptions } from './utils';\n\n// connections closed through Client.close(), shared by of() siblings\nconst closed = new WeakSet<Connection>();\n\nconst noop = () => undefined;\n\n/**\n * Wrap a setup function, so a broker rejection during it (e.g. 403/406) closes only this channel:\n * without an 'error' listener on the raw channel, amqplib rethrows it and tears down the whole connection.\n * Only during setup: a channel error afterwards must still recycle the connection, because\n * amqp-connection-manager never recovers a channel-only close, so consumers would silently die.\n */\nfunction guard(setup: (channel: Channel) => Promise<unknown>) {\n return async (channel: Channel) => {\n channel.on('error', noop);\n\n try {\n await setup(channel);\n } finally {\n channel.off('error', noop);\n }\n };\n}\n\n/**\n * Reject when the broker rejects a setup function (an error with an AMQP reply code)\n * or the channel is closed (client.close()).\n * Errors without a reply code (connection dropped mid-setup) are transient:\n * the setup runs again on reconnect, so keep waiting.\n */\nfunction failure(channel: ChannelWrapper) : Promise<never> {\n const promise = new Promise<never>((_resolve, reject) => {\n // ponytail: the listener stays, so setup errors after a reconnect are swallowed instead of crashing the process\n channel.on('error', (err: unknown) => {\n if (isObject(err) && typeof err.code === 'number') {\n reject(err);\n }\n });\n channel.once('close', () => reject(ClientError.channelClosed()));\n });\n\n // it may reject long after the call settled (e.g. close()), which is not an unhandled rejection\n promise.catch(noop);\n\n return promise;\n}\n\nexport class Client {\n public readonly connection: Connection;\n\n protected publishOptions : PublishOptions;\n\n protected consumeOptions : ConsumeOptions;\n\n protected exchange: Exchange;\n\n /**\n * Bounds the channels publish() and republish() open at once, shared with of() siblings.\n */\n protected readonly publishChannelLimiter: IPublishChannelLimiter;\n\n constructor(ctx: ClientContext) {\n // first: an invalid publishChannelMax throws before a connection exists that nobody could close\n this.publishChannelLimiter = ctx.publishChannelLimiter ??\n new PublishChannelLimiter(ctx.publishChannelMax ?? PUBLISH_CHANNEL_MAX);\n this.connection = ctx.connection ?? connect(ctx.connectionOptions, ctx.connectionManagerOptions);\n this.publishOptions = ctx.publishOptions || {};\n this.consumeOptions = ctx.consumeOptions || {};\n this.exchange = ctx.exchange || {\n type: ExchangeType.DIRECT,\n name: '',\n };\n }\n\n of(exchange: Exchange) : Client {\n return new Client({\n connection: this.connection,\n publishOptions: this.publishOptions,\n consumeOptions: this.consumeOptions,\n publishChannelLimiter: this.publishChannelLimiter,\n exchange,\n });\n }\n\n /**\n * Close the (shared) connection and all its channels.\n */\n async close() : Promise<void> {\n closed.add(this.connection);\n await this.connection.close();\n }\n\n /**\n * `await using client = new Client(...)` closes the client when the scope ends.\n * Like close(), it closes the shared connection, so use it on the root client, not on of() siblings.\n */\n async [Symbol.asyncDispose]() : Promise<void> {\n await this.close();\n }\n\n protected assertOpen() : void {\n if (closed.has(this.connection)) {\n throw ClientError.closed();\n }\n }\n\n async consume(ctx: ConsumeContext) : Promise<Consumer>;\n\n async consume(from: string, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<Consumer>;\n\n async consume(\n _ctxOrFrom: ConsumeContext | string,\n _optionsOrHandlers?: ConsumeOptions | ConsumeHandlers,\n _handlers?: ConsumeHandlers,\n ) : Promise<Consumer> {\n const ctx : ConsumeContext = typeof _ctxOrFrom === 'string' ?\n {\n from: _ctxOrFrom,\n options: _handlers ? _optionsOrHandlers as ConsumeOptions : undefined,\n handlers: _handlers || _optionsOrHandlers as ConsumeHandlers,\n } :\n _ctxOrFrom;\n\n try {\n this.assertOpen();\n\n let options = this.consumeOptions;\n\n if (ctx.options) {\n // smob clones through structuredClone, which throws on functions\n const { onError, ...rest } = ctx.options;\n const { onError: fallback, ...defaults } = this.consumeOptions;\n\n options = { ...mergeOptions(rest, defaults), onError: onError ?? fallback };\n }\n\n const topology = planTopology(this.exchange, ctx.from, options, true);\n\n let cancelled = false;\n // the raw channel and consumer tag of the latest setup run\n let current : { ch: Channel, consumerTag: string } | undefined;\n // the latest setup run, awaited by cancel(): one in progress during a reconnect still registers a consumer\n let running : Promise<void> | undefined;\n const inFlight = new Set<Promise<void>>();\n // with retry: the same runs by messageId, for the redelivery guard; kept across setup runs (reconnects)\n const tracked = new Map<string, Promise<boolean>>();\n\n const channel = this.connection.createChannel({\n setup: guard((ch: Channel) => {\n running = (async () => {\n if (cancelled) {\n return;\n }\n\n const queue = await assertTopology(ch, topology) as string;\n\n if (typeof options.prefetchCount === 'number') {\n await ch.prefetch(options.prefetchCount);\n }\n\n const context : HandleMessageContext = {\n inFlight: tracked,\n republish: (content, props) => this.republish(queue, content, props),\n };\n\n const { consumerTag } = await ch.consume(queue, (message) => {\n const handled = handleMessage(message, ch, ctx.handlers, options, context);\n\n inFlight.add(handled);\n // handleMessage never rejects\n handled.then(() => inFlight.delete(handled));\n }, options);\n\n current = { ch, consumerTag };\n })();\n\n return running;\n }),\n });\n\n try {\n await Promise.race([channel.waitForConnect(), failure(channel)]);\n } catch (e) {\n // not awaited: amqplib never settles the close when the connection drops before close-ok\n channel.close().catch(noop);\n\n throw e;\n }\n\n let cancelling : Promise<void> | undefined;\n const cancel = () => {\n cancelling ??= (async () => {\n // no setup run after this one: a reconnect does not re-register the consumer\n cancelled = true;\n await running?.catch(noop);\n\n // basic.cancel: no new deliveries, the channel stays open to settle the in-flight ones\n // (fails on a closed channel, e.g. after close() or during a reconnect)\n await current?.ch.cancel(current.consumerTag).catch(noop);\n\n // ponytail: a handler that never settles hangs cancel()\n // (a loop: deliveries that arrived before the cancel took effect add to the set)\n while (inFlight.size > 0) {\n await Promise.all(inFlight);\n }\n\n // ponytail: hangs if the connection drops between ChannelClose and CloseOk (amqplib)\n await channel.close().catch(noop);\n })();\n\n return cancelling;\n };\n\n return { cancel, [Symbol.asyncDispose]: cancel };\n } catch (e) {\n throw toError(e);\n }\n }\n\n /**\n * Re-publish a message for a retry, through the default exchange by queue name:\n * that reaches the queue whatever exchange delivered it, without re-declaring it.\n * Its own channel, not the consume channel: that one may have been reset while\n * the handler ran, and this one waits for the broker's confirm.\n *\n * ponytail: a server-named queue is gone after a reconnect, so a retry of a\n * message from before it is unroutable and dropped by the broker.\n */\n protected async republish(queue: string, content: Buffer, options: RepublishOptions) : Promise<void> {\n this.assertOpen();\n\n // bounded, so a broker outage reaches the requeue nack instead of hanging cancel()\n await this.withPublishChannel(PUBLISH_TIMEOUT, async (timeout) => {\n const channel = this.connection.createChannel();\n\n const published = channel.publish('', queue, content, { ...options, timeout });\n\n published.catch(noop);\n\n try {\n // failure() also listens for the channel's errors: without a listener, a connection\n // lost while the channel opens surfaces as an unhandled rejection\n await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n });\n }\n\n /**\n * Run a publish once a publish channel slot is free: an unbounded burst of channels\n * exceeds the broker's channel_max, and the channels beyond it never open.\n * The time spent waiting counts against the timeout (0: no limit); the rest is passed on.\n */\n protected async withPublishChannel<T>(timeout: number, run: (timeout: number) => Promise<T>) : Promise<T> {\n const started = Date.now();\n\n // a free slot is taken synchronously, so the channel opens in the publish() call\n // itself, as without a limit; only a publish that has to wait awaits one\n let release = this.publishChannelLimiter.tryAcquire();\n const waited = !release;\n\n if (!release) {\n release = await this.publishChannelLimiter.acquire(timeout);\n }\n\n try {\n // closed while this publish waited for a slot: reject it like a pending\n // publish (CHANNEL_CLOSED), without opening a channel on the closed connection\n if (waited && closed.has(this.connection)) {\n throw ClientError.channelClosed();\n }\n\n return await run(timeout > 0 ? Math.max(1, timeout - (Date.now() - started)) : 0);\n } finally {\n release();\n }\n }\n\n async publish(ctx: PublishContext) : Promise<boolean>;\n\n async publish(to: string, data: any) : Promise<boolean>;\n\n async publish(to: string, data: any, options: PublishOptions): Promise<boolean>;\n\n async publish(\n _toOrCtx: PublishContext | string,\n _data?: any,\n _options?: PublishOptions,\n ) : Promise<boolean> {\n const ctx : PublishContext = typeof _toOrCtx === 'string' ?\n {\n to: _toOrCtx,\n data: _data,\n options: _options,\n } :\n _toOrCtx;\n\n try {\n this.assertOpen();\n\n const options = ctx.options ? mergeOptions(ctx.options, this.publishOptions) : this.publishOptions;\n const topology = planTopology(this.exchange, ctx.to, options);\n\n let content : Buffer;\n\n if (Buffer.isBuffer(ctx.data)) {\n content = ctx.data;\n } else if (typeof ctx.data === 'string') {\n content = Buffer.from(ctx.data, 'utf-8');\n } else {\n let json : string | undefined;\n\n try {\n json = JSON.stringify(ctx.data);\n } catch (e) {\n throw SerializationError.payload(e);\n }\n\n // undefined, functions and symbols serialize to undefined\n if (typeof json === 'undefined') {\n throw SerializationError.payload();\n }\n\n content = Buffer.from(json, 'utf-8');\n }\n\n return await this.withPublishChannel(options.timeout ?? PUBLISH_TIMEOUT, async (timeout) => {\n // ponytail: one channel per publish (self-healing, no shared state), reuse channels when throughput matters\n const channel = this.connection.createChannel({ setup: guard((ch: Channel) => assertTopology(ch, topology)) });\n\n // queued right away: sent once the setup ran, bounded by the timeout, rejected by close()\n const published = channel.publish(this.exchange.name || '', ctx.to, content, { ...options, timeout });\n\n published.catch(noop);\n\n try {\n return await Promise.race([published, failure(channel)]);\n } finally {\n // not awaited, see consume()\n channel.close().catch(noop);\n }\n });\n } catch (e) {\n throw toError(e);\n }\n }\n}\n"],"mappings":";;;;AAOA,MAAa,uBAAuB;;;;;ACOpC,MAAa,iBAAiB;;;;;;AAO9B,SAAgB,eAAe,YAA4D;CACvF,MAAM,QAAQ,WAAW,UAAU;CAEnC,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,SAAS,IAAI,QAAQ;AAC5F;;;;AAKA,SAAgB,kBAAkB,SAAiB,MAAuB;CACtE,OAAO,KAAK,IAAI,OAAO,MAAM,UAAU,IAAI,GAAM;AACrD;;;;;;;;;AAUA,eAAsB,aAClB,SACA,SACA,SACiB;CACjB,MAAM,UAAU,eAAe,QAAQ,UAAU,IAAI;CAErD,IAAI,WAAW,QAAQ,eAAe,IAClC,OAAO;CAGX,MAAM,IAAI,SAAS,YAAY;EAC3B,WAAW,SAAS,kBAAkB,SAAS,QAAQ,SAAS,GAAI,CAAC;CACzE,CAAC;CAED,MAAM,aAAgC;EAClC,GAAG,QAAQ;EACX,SAAS;GAAE,GAAG,QAAQ,WAAW;IAAU,iBAAiB;EAAQ;CACxE;CAGA,OAAO,WAAW;CAElB,MAAM,QAAQ,QAAQ,SAAS,UAAU;CAEzC,OAAO;AACX;;AC7DA,IAAY,YAAL,yBAAA,WAAA;CACH,UAAA,sBAAA;CACA,UAAA,2BAAA;CACA,UAAA,yBAAA;CACA,UAAA,mBAAA;CACA,UAAA,oBAAA;CACA,UAAA,qBAAA;CACA,UAAA,qBAAA;CACA,UAAA,wBAAA;CACA,UAAA,qBAAA;CACA,UAAA,0BAAA;;AACJ,EAAA,CAAA,CAAA;AAGA,MAAa,8BAA8B,OAAO,IAA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EJ,IAAI;GACA,KAAK,WAAW;GAEhB,MAAM,UAAU,IAAI,UAAU,aAAa,IAAI,SAAS,KAAK,cAAc,IAAI,KAAK;GACpF,MAAM,WAAW,aAAa,KAAK,UAAU,IAAI,IAAI,OAAO;GAE5D,IAAI;GAEJ,IAAI,OAAO,SAAS,IAAI,IAAI,GACxB,UAAU,IAAI;QACX,IAAI,OAAO,IAAI,SAAS,UAC3B,UAAU,OAAO,KAAK,IAAI,MAAM,OAAO;QACpC;IACH,IAAI;IAEJ,IAAI;KACA,OAAO,KAAK,UAAU,IAAI,IAAI;IAClC,SAAS,GAAG;KACR,MAAM,mBAAmB,QAAQ,CAAC;IACtC;IAGA,IAAI,OAAO,SAAS,aAChB,MAAM,mBAAmB,QAAQ;IAGrC,UAAU,OAAO,KAAK,MAAM,OAAO;GACvC;GAEA,OAAO,MAAM,KAAK,mBAAmB,QAAQ,WAAA,KAA4B,OAAO,YAAY;IAExF,MAAM,UAAU,KAAK,WAAW,cAAc,EAAE,OAAO,OAAO,OAAgB,eAAe,IAAI,QAAQ,CAAC,EAAE,CAAC;IAG7G,MAAM,YAAY,QAAQ,QAAQ,KAAK,SAAS,QAAQ,IAAI,IAAI,IAAI,SAAS;KAAE,GAAG;KAAS;IAAQ,CAAC;IAEpG,UAAU,MAAM,IAAI;IAEpB,IAAI;KACA,OAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,QAAQ,OAAO,CAAC,CAAC;IAC3D,UAAU;KAEN,QAAQ,MAAM,CAAC,CAAC,MAAM,IAAI;IAC9B;GACJ,CAAC;EACL,SAAS,GAAG;GACR,MAAM,QAAQ,CAAC;EACnB;CACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "amqp-extension",
3
- "version": "5.1.1",
3
+ "version": "5.2.0",
4
4
  "type": "module",
5
5
  "description": "An amqp extension with functions and utility functions to consume and publish queue messages.",
6
6
  "author": {
@@ -10,12 +10,12 @@
10
10
  },
11
11
  "repository": {
12
12
  "type": "git",
13
- "url": "git+https://github.com/Tada5hi/amqp-extension.git"
13
+ "url": "git+https://github.com/tada5hi/amqp-extension.git"
14
14
  },
15
15
  "bugs": {
16
- "url": "https://github.com/Tada5hi/amqp-extension/issues"
16
+ "url": "https://github.com/tada5hi/amqp-extension/issues"
17
17
  },
18
- "homepage": "https://github.com/Tada5hi/amqp-extension#readme",
18
+ "homepage": "https://github.com/tada5hi/amqp-extension#readme",
19
19
  "main": "dist/index.mjs",
20
20
  "types": "dist/index.d.mts",
21
21
  "exports": {
@@ -54,23 +54,29 @@
54
54
  "license": "MIT",
55
55
  "dependencies": {
56
56
  "@ebec/core": "^1.3.2",
57
- "amqp-connection-manager": "^5.0.0",
58
- "amqplib": "^2.2.0",
57
+ "amqp-connection-manager": "^5.0.1",
58
+ "amqplib": "^2.4.0",
59
59
  "smob": "^1.6.2"
60
60
  },
61
+ "devEngines": {
62
+ "runtime": {
63
+ "name": "node",
64
+ "version": "^24.11.0 || >=26.0.0"
65
+ }
66
+ },
61
67
  "devDependencies": {
62
- "@commitlint/cli": "^21.2.3",
63
- "@tada5hi/commitlint-config": "^1.3.2",
64
- "@tada5hi/eslint-config": "^2.4.0",
68
+ "@commitlint/cli": "^21.2.4",
69
+ "@tada5hi/commitlint-config": "^1.3.3",
70
+ "@tada5hi/eslint-config": "^3.3.1",
65
71
  "@tada5hi/tsconfig": "^0.7.2",
66
- "@types/node": "^26.6.5",
67
- "@vitest/coverage-v8": "^5.0.4",
68
- "eslint": "^10.12.0",
72
+ "@types/node": "^26.6.6",
73
+ "@vitest/coverage-v8": "^5.1.1",
74
+ "eslint": "^10.15.0",
69
75
  "husky": "^9.1.7",
70
- "testcontainers": "^12.2.1",
71
- "tsdown": "^0.23.1",
76
+ "testcontainers": "^12.2.2",
77
+ "tsdown": "^0.23.7",
72
78
  "typescript": "^6.0.3",
73
- "typescript-eslint": "^8.71.2",
74
- "vitest": "^5.0.4"
79
+ "typescript-eslint": "^8.73.0",
80
+ "vitest": "^5.1.0"
75
81
  }
76
82
  }