amqp-extension 4.0.0 → 5.0.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.
Files changed (46) hide show
  1. package/README.MD +284 -40
  2. package/dist/index.d.mts +287 -0
  3. package/dist/index.mjs +502 -0
  4. package/dist/index.mjs.map +1 -0
  5. package/package.json +53 -39
  6. package/.editorconfig +0 -13
  7. package/.eslintrc +0 -27
  8. package/.husky/commit-msg +0 -4
  9. package/CHANGELOG.md +0 -149
  10. package/commitlint.config.js +0 -10
  11. package/dist/config/index.d.ts +0 -3
  12. package/dist/config/index.js +0 -25
  13. package/dist/config/module.d.ts +0 -2
  14. package/dist/config/module.js +0 -23
  15. package/dist/config/type.d.ts +0 -13
  16. package/dist/config/type.js +0 -8
  17. package/dist/consume/constants.d.ts +0 -1
  18. package/dist/consume/constants.js +0 -10
  19. package/dist/consume/index.d.ts +0 -3
  20. package/dist/consume/index.js +0 -25
  21. package/dist/consume/type.d.ts +0 -24
  22. package/dist/consume/type.js +0 -8
  23. package/dist/consume/utils.d.ts +0 -2
  24. package/dist/consume/utils.js +0 -16
  25. package/dist/exchange/constants.d.ts +0 -6
  26. package/dist/exchange/constants.js +0 -10
  27. package/dist/exchange/index.d.ts +0 -3
  28. package/dist/exchange/index.js +0 -19
  29. package/dist/exchange/type.d.ts +0 -8
  30. package/dist/exchange/type.js +0 -2
  31. package/dist/exchange/utils.d.ts +0 -4
  32. package/dist/exchange/utils.js +0 -13
  33. package/dist/index.d.ts +0 -6
  34. package/dist/index.js +0 -28
  35. package/dist/module.d.ts +0 -18
  36. package/dist/module.js +0 -187
  37. package/dist/publish/index.d.ts +0 -1
  38. package/dist/publish/index.js +0 -23
  39. package/dist/publish/type.d.ts +0 -7
  40. package/dist/publish/type.js +0 -8
  41. package/dist/type.d.ts +0 -14
  42. package/dist/type.js +0 -2
  43. package/dist/utils.d.ts +0 -2
  44. package/dist/utils.js +0 -23
  45. package/release.config.js +0 -3
  46. package/tsconfig.eslint.json +0 -12
package/dist/index.mjs ADDED
@@ -0,0 +1,502 @@
1
+ import { BaseError, hasInstanceof, markInstanceof, matchesInstanceof } from "@ebec/core";
2
+ import { connect } from "amqp-connection-manager";
3
+ import { createMerger } from "smob";
4
+ //#region src/consume/constants.ts
5
+ const ConsumeHandlerAnyKey = "$any";
6
+ //#endregion
7
+ //#region src/errors/constants.ts
8
+ let ErrorCode = /* @__PURE__ */ function(ErrorCode) {
9
+ ErrorCode["QUEUE_NAME_EMPTY"] = "QUEUE_NAME_EMPTY";
10
+ ErrorCode["EXCHANGE_NAME_MISSING"] = "EXCHANGE_NAME_MISSING";
11
+ ErrorCode["DESTINATION_MISSING"] = "DESTINATION_MISSING";
12
+ ErrorCode["CLIENT_CLOSED"] = "CLIENT_CLOSED";
13
+ ErrorCode["CHANNEL_CLOSED"] = "CHANNEL_CLOSED";
14
+ ErrorCode["PUBLISH_TIMEOUT"] = "PUBLISH_TIMEOUT";
15
+ ErrorCode["HANDLER_MISSING"] = "HANDLER_MISSING";
16
+ ErrorCode["BROKER_REJECTED"] = "BROKER_REJECTED";
17
+ ErrorCode["SERIALIZATION_FAILED"] = "SERIALIZATION_FAILED";
18
+ return ErrorCode;
19
+ }({});
20
+ const AMQP_EXTENSION_ERROR_MARKER = Symbol.for("amqp-extension/AmqpExtensionError");
21
+ const TOPOLOGY_ERROR_MARKER = Symbol.for("amqp-extension/TopologyError");
22
+ const CLIENT_ERROR_MARKER = Symbol.for("amqp-extension/ClientError");
23
+ const BROKER_ERROR_MARKER = Symbol.for("amqp-extension/BrokerError");
24
+ const SERIALIZATION_ERROR_MARKER = Symbol.for("amqp-extension/SerializationError");
25
+ //#endregion
26
+ //#region src/errors/base.ts
27
+ /**
28
+ * Root of every error thrown by amqp-extension.
29
+ *
30
+ * instanceof is duck-typed through @ebec/core's marker chain, so it also matches errors
31
+ * from a duplicate copy of the library. Every subclass overrides Symbol.hasInstance with
32
+ * its own marker, otherwise it would inherit this one and match every library error.
33
+ */
34
+ var AmqpExtensionError = class extends BaseError {
35
+ static [Symbol.hasInstance](input) {
36
+ return hasInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);
37
+ }
38
+ constructor(input) {
39
+ super(input);
40
+ markInstanceof(this, AMQP_EXTENSION_ERROR_MARKER);
41
+ }
42
+ };
43
+ //#endregion
44
+ //#region src/errors/broker.ts
45
+ /**
46
+ * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.
47
+ */
48
+ var BrokerError = class BrokerError extends AmqpExtensionError {
49
+ static [Symbol.hasInstance](input) {
50
+ return hasInstanceof(input, BROKER_ERROR_MARKER);
51
+ }
52
+ replyCode;
53
+ classId;
54
+ methodId;
55
+ constructor(input, reply) {
56
+ super(input);
57
+ this.replyCode = reply.replyCode;
58
+ this.classId = reply.classId;
59
+ this.methodId = reply.methodId;
60
+ markInstanceof(this, BROKER_ERROR_MARKER);
61
+ }
62
+ toJSON() {
63
+ return {
64
+ ...super.toJSON(),
65
+ replyCode: this.replyCode,
66
+ classId: this.classId,
67
+ methodId: this.methodId
68
+ };
69
+ }
70
+ static fromAmqp(err) {
71
+ return new BrokerError({
72
+ code: "BROKER_REJECTED",
73
+ message: err.message,
74
+ cause: err
75
+ }, {
76
+ replyCode: err.code,
77
+ classId: err.classId,
78
+ methodId: err.methodId
79
+ });
80
+ }
81
+ };
82
+ //#endregion
83
+ //#region src/errors/check.ts
84
+ function isAmqpExtensionError(input) {
85
+ return matchesInstanceof(input, AMQP_EXTENSION_ERROR_MARKER);
86
+ }
87
+ function isTopologyError(input) {
88
+ return matchesInstanceof(input, TOPOLOGY_ERROR_MARKER);
89
+ }
90
+ function isClientError(input) {
91
+ return matchesInstanceof(input, CLIENT_ERROR_MARKER);
92
+ }
93
+ function isBrokerError(input) {
94
+ return matchesInstanceof(input, BROKER_ERROR_MARKER);
95
+ }
96
+ function isSerializationError(input) {
97
+ return matchesInstanceof(input, SERIALIZATION_ERROR_MARKER);
98
+ }
99
+ //#endregion
100
+ //#region src/errors/client.ts
101
+ var ClientError = class ClientError extends AmqpExtensionError {
102
+ static [Symbol.hasInstance](input) {
103
+ return hasInstanceof(input, CLIENT_ERROR_MARKER);
104
+ }
105
+ constructor(input) {
106
+ super(input);
107
+ markInstanceof(this, CLIENT_ERROR_MARKER);
108
+ }
109
+ static closed() {
110
+ return new ClientError({
111
+ code: "CLIENT_CLOSED",
112
+ message: "The client is closed."
113
+ });
114
+ }
115
+ static channelClosed(cause) {
116
+ return new ClientError({
117
+ code: "CHANNEL_CLOSED",
118
+ message: "Channel closed",
119
+ cause
120
+ });
121
+ }
122
+ static handlerMissing(type) {
123
+ return new ClientError({
124
+ code: "HANDLER_MISSING",
125
+ message: typeof type === "string" ? `No handler for the message type "${type}".` : "No handler for a message without type."
126
+ });
127
+ }
128
+ static timeout(cause) {
129
+ return new ClientError({
130
+ code: "PUBLISH_TIMEOUT",
131
+ message: "The publish operation timed out.",
132
+ cause
133
+ });
134
+ }
135
+ };
136
+ //#endregion
137
+ //#region src/errors/serialization.ts
138
+ var SerializationError = class SerializationError extends AmqpExtensionError {
139
+ static [Symbol.hasInstance](input) {
140
+ return hasInstanceof(input, SERIALIZATION_ERROR_MARKER);
141
+ }
142
+ constructor(input) {
143
+ super(input);
144
+ markInstanceof(this, SERIALIZATION_ERROR_MARKER);
145
+ }
146
+ static payload(cause) {
147
+ return new SerializationError({
148
+ code: "SERIALIZATION_FAILED",
149
+ message: "The message payload could not be serialized.",
150
+ cause
151
+ });
152
+ }
153
+ };
154
+ //#endregion
155
+ //#region src/errors/topology.ts
156
+ var TopologyError = class TopologyError extends AmqpExtensionError {
157
+ static [Symbol.hasInstance](input) {
158
+ return hasInstanceof(input, TOPOLOGY_ERROR_MARKER);
159
+ }
160
+ constructor(input) {
161
+ super(input);
162
+ markInstanceof(this, TOPOLOGY_ERROR_MARKER);
163
+ }
164
+ static queueNameEmpty() {
165
+ return new TopologyError({
166
+ code: "QUEUE_NAME_EMPTY",
167
+ message: "The queue name can not be empty if the default exchange is selected."
168
+ });
169
+ }
170
+ static exchangeNameMissing() {
171
+ return new TopologyError({
172
+ code: "EXCHANGE_NAME_MISSING",
173
+ message: "A non default exchange requires a name."
174
+ });
175
+ }
176
+ static destinationMissing() {
177
+ return new TopologyError({
178
+ code: "DESTINATION_MISSING",
179
+ message: "The publish operation requires a destination."
180
+ });
181
+ }
182
+ };
183
+ //#endregion
184
+ //#region src/exchange/constants.ts
185
+ let ExchangeType = /* @__PURE__ */ function(ExchangeType) {
186
+ ExchangeType["FANOUT"] = "fanout";
187
+ ExchangeType["DIRECT"] = "direct";
188
+ ExchangeType["TOPIC"] = "topic";
189
+ ExchangeType["HEADERS"] = "headers";
190
+ return ExchangeType;
191
+ }({});
192
+ //#endregion
193
+ //#region src/exchange/utils.ts
194
+ function isDefaultExchange(input) {
195
+ return typeof input === "undefined" || input === "direct";
196
+ }
197
+ //#endregion
198
+ //#region src/consume/utils.ts
199
+ /**
200
+ * Dispatch a delivery to the handler for its type (or $any) and settle it:
201
+ * ack on success, nack (requeue = requeueOnFailure) on failure or without handler, nothing with noAck.
202
+ * A failure is then reported to onError.
203
+ */
204
+ async function handleMessage(message, channel, handlers, options) {
205
+ if (!message) return;
206
+ const { type } = message.properties;
207
+ const handler = (typeof type === "string" && Object.hasOwn(handlers, type) ? handlers[type] : void 0) || handlers["$any"];
208
+ let ok = !!handler;
209
+ let error;
210
+ if (handler) try {
211
+ await handler(message, channel);
212
+ } catch (e) {
213
+ ok = false;
214
+ error = e;
215
+ }
216
+ else error = ClientError.handlerMissing(type);
217
+ if (!options.noAck) try {
218
+ if (ok) channel.ack(message);
219
+ else channel.nack(message, false, options.requeueOnFailure ?? false);
220
+ } catch {}
221
+ if (!ok && options.onError) try {
222
+ await options.onError(error, message);
223
+ } catch {}
224
+ }
225
+ //#endregion
226
+ //#region src/errors/utils.ts
227
+ /**
228
+ * Map anything thrown below the Client (amqplib, amqp-connection-manager) onto the error tree.
229
+ */
230
+ function toError(e) {
231
+ if (e instanceof AmqpExtensionError) return e;
232
+ if (!(e instanceof Error)) return new AmqpExtensionError({
233
+ message: String(e),
234
+ cause: e
235
+ });
236
+ if (typeof e.code === "number") return BrokerError.fromAmqp(e);
237
+ if (e.message === "timeout") return ClientError.timeout(e);
238
+ if (e.message === "Channel closed") return ClientError.channelClosed(e);
239
+ return new AmqpExtensionError({
240
+ message: e.message,
241
+ cause: e
242
+ });
243
+ }
244
+ //#endregion
245
+ //#region src/queue/utils.ts
246
+ const QueueArguments = {
247
+ queueType: "x-queue-type",
248
+ deliveryLimit: "x-delivery-limit",
249
+ deadLetterExchange: "x-dead-letter-exchange",
250
+ deadLetterRoutingKey: "x-dead-letter-routing-key",
251
+ messageTtl: "x-message-ttl",
252
+ maxLength: "x-max-length",
253
+ singleActiveConsumer: "x-single-active-consumer"
254
+ };
255
+ function planQueueOptions(options) {
256
+ const queueOptions = { durable: true };
257
+ const keys = Object.keys(QueueArguments);
258
+ for (const key of keys) {
259
+ const value = options[key];
260
+ if (typeof value !== "undefined" && value !== false) queueOptions.arguments = {
261
+ ...queueOptions.arguments,
262
+ [QueueArguments[key]]: value
263
+ };
264
+ }
265
+ return queueOptions;
266
+ }
267
+ /**
268
+ * Plan the topology for publishing to or consuming from (consume = true) a key.
269
+ * Throws on invalid input, before anything touches the broker.
270
+ */
271
+ function planTopology(exchange, key, options, consume) {
272
+ if (isDefaultExchange(exchange.type)) {
273
+ if (!key) throw TopologyError.queueNameEmpty();
274
+ return { queue: {
275
+ name: key,
276
+ options: planQueueOptions(options)
277
+ } };
278
+ }
279
+ if (!exchange.name) throw TopologyError.exchangeNameMissing();
280
+ const topology = { exchange: {
281
+ name: exchange.name,
282
+ type: exchange.type,
283
+ options: exchange.options
284
+ } };
285
+ if (!consume) {
286
+ if (!key) throw TopologyError.destinationMissing();
287
+ return topology;
288
+ }
289
+ if (options.queue === "") throw TopologyError.queueNameEmpty();
290
+ topology.queue = options.queue ? {
291
+ name: options.queue,
292
+ options: planQueueOptions(options)
293
+ } : {
294
+ name: "",
295
+ options: {
296
+ durable: false,
297
+ autoDelete: true,
298
+ exclusive: true
299
+ }
300
+ };
301
+ topology.bind = key;
302
+ return topology;
303
+ }
304
+ /**
305
+ * Declare a planned topology. Returns the (possibly server generated) queue name.
306
+ * Must run inside a channel setup function, so it is replayed on reconnect.
307
+ */
308
+ async function assertTopology(channel, topology) {
309
+ if (topology.exchange) await channel.assertExchange(topology.exchange.name, topology.exchange.type, topology.exchange.options);
310
+ if (!topology.queue) return;
311
+ const { queue } = await channel.assertQueue(topology.queue.name, topology.queue.options);
312
+ if (topology.exchange && typeof topology.bind === "string") await channel.bindQueue(queue, topology.exchange.name, topology.bind);
313
+ return queue;
314
+ }
315
+ //#endregion
316
+ //#region src/utils.ts
317
+ const mergeOptions = createMerger({
318
+ priority: "left",
319
+ inPlace: false,
320
+ clone: true,
321
+ array: true,
322
+ arrayDistinct: true
323
+ });
324
+ //#endregion
325
+ //#region src/module.ts
326
+ const closed = /* @__PURE__ */ new WeakSet();
327
+ const noop = () => void 0;
328
+ /**
329
+ * Wrap a setup function, so a broker rejection during it (e.g. 403/406) closes only this channel:
330
+ * without an 'error' listener on the raw channel, amqplib rethrows it and tears down the whole connection.
331
+ * Only during setup: a channel error afterwards must still recycle the connection, because
332
+ * amqp-connection-manager never recovers a channel-only close, so consumers would silently die.
333
+ */
334
+ function guard(setup) {
335
+ return async (channel) => {
336
+ channel.on("error", noop);
337
+ try {
338
+ await setup(channel);
339
+ } finally {
340
+ channel.off("error", noop);
341
+ }
342
+ };
343
+ }
344
+ /**
345
+ * Reject when the broker rejects a setup function (an error with an AMQP reply code)
346
+ * or the channel is closed (client.close()).
347
+ * Errors without a reply code (connection dropped mid-setup) are transient:
348
+ * the setup runs again on reconnect, so keep waiting.
349
+ */
350
+ function failure(channel) {
351
+ const promise = new Promise((_resolve, reject) => {
352
+ channel.on("error", (err) => {
353
+ if (typeof err.code === "number") reject(err);
354
+ });
355
+ channel.once("close", () => reject(ClientError.channelClosed()));
356
+ });
357
+ promise.catch(noop);
358
+ return promise;
359
+ }
360
+ var Client = class Client {
361
+ connection;
362
+ publishOptions;
363
+ consumeOptions;
364
+ exchange;
365
+ constructor(ctx) {
366
+ this.connection = ctx.connection ?? connect(ctx.connectionOptions, ctx.connectionManagerOptions);
367
+ this.publishOptions = ctx.publishOptions || {};
368
+ this.consumeOptions = ctx.consumeOptions || {};
369
+ this.exchange = ctx.exchange || {
370
+ type: "direct",
371
+ name: ""
372
+ };
373
+ }
374
+ of(exchange) {
375
+ return new Client({
376
+ connection: this.connection,
377
+ publishOptions: this.publishOptions,
378
+ consumeOptions: this.consumeOptions,
379
+ exchange
380
+ });
381
+ }
382
+ /**
383
+ * Close the (shared) connection and all its channels.
384
+ */
385
+ async close() {
386
+ closed.add(this.connection);
387
+ await this.connection.close();
388
+ }
389
+ /**
390
+ * `await using client = new Client(...)` closes the client when the scope ends.
391
+ * Like close(), it closes the shared connection, so use it on the root client, not on of() siblings.
392
+ */
393
+ async [Symbol.asyncDispose]() {
394
+ await this.close();
395
+ }
396
+ assertOpen() {
397
+ if (closed.has(this.connection)) throw ClientError.closed();
398
+ }
399
+ async consume(_ctxOrFrom, _optionsOrHandlers, _handlers) {
400
+ const ctx = typeof _ctxOrFrom === "string" ? {
401
+ from: _ctxOrFrom,
402
+ options: _handlers ? _optionsOrHandlers : void 0,
403
+ handlers: _handlers || _optionsOrHandlers
404
+ } : _ctxOrFrom;
405
+ try {
406
+ this.assertOpen();
407
+ let options = this.consumeOptions;
408
+ if (ctx.options) {
409
+ const { onError, ...rest } = ctx.options;
410
+ const { onError: fallback, ...defaults } = this.consumeOptions;
411
+ options = {
412
+ ...mergeOptions(rest, defaults),
413
+ onError: onError ?? fallback
414
+ };
415
+ }
416
+ const topology = planTopology(this.exchange, ctx.from, options, true);
417
+ let cancelled = false;
418
+ let current;
419
+ let running;
420
+ const inFlight = /* @__PURE__ */ new Set();
421
+ const channel = this.connection.createChannel({ setup: guard((ch) => {
422
+ running = (async () => {
423
+ if (cancelled) return;
424
+ const queue = await assertTopology(ch, topology);
425
+ if (typeof options.prefetchCount === "number") await ch.prefetch(options.prefetchCount);
426
+ const { consumerTag } = await ch.consume(queue, (message) => {
427
+ const handled = handleMessage(message, ch, ctx.handlers, options);
428
+ inFlight.add(handled);
429
+ handled.then(() => inFlight.delete(handled));
430
+ }, options);
431
+ current = {
432
+ ch,
433
+ consumerTag
434
+ };
435
+ })();
436
+ return running;
437
+ }) });
438
+ try {
439
+ await Promise.race([channel.waitForConnect(), failure(channel)]);
440
+ } catch (e) {
441
+ channel.close().catch(noop);
442
+ throw e;
443
+ }
444
+ let cancelling;
445
+ const cancel = () => {
446
+ cancelling ??= (async () => {
447
+ cancelled = true;
448
+ await running?.catch(noop);
449
+ await current?.ch.cancel(current.consumerTag).catch(noop);
450
+ while (inFlight.size > 0) await Promise.all(inFlight);
451
+ await channel.close().catch(noop);
452
+ })();
453
+ return cancelling;
454
+ };
455
+ return {
456
+ cancel,
457
+ [Symbol.asyncDispose]: cancel
458
+ };
459
+ } catch (e) {
460
+ throw toError(e);
461
+ }
462
+ }
463
+ async publish(_toOrCtx, _data, _options) {
464
+ const ctx = typeof _toOrCtx === "string" ? {
465
+ to: _toOrCtx,
466
+ data: _data,
467
+ options: _options
468
+ } : _toOrCtx;
469
+ try {
470
+ this.assertOpen();
471
+ const options = ctx.options ? mergeOptions(ctx.options, this.publishOptions) : this.publishOptions;
472
+ const topology = planTopology(this.exchange, ctx.to, options);
473
+ let content;
474
+ if (Buffer.isBuffer(ctx.data)) content = ctx.data;
475
+ else if (typeof ctx.data === "string") content = Buffer.from(ctx.data, "utf-8");
476
+ else {
477
+ let json;
478
+ try {
479
+ json = JSON.stringify(ctx.data);
480
+ } catch (e) {
481
+ throw SerializationError.payload(e);
482
+ }
483
+ if (typeof json === "undefined") throw SerializationError.payload();
484
+ content = Buffer.from(json, "utf-8");
485
+ }
486
+ const channel = this.connection.createChannel({ setup: guard((ch) => assertTopology(ch, topology)) });
487
+ const published = channel.publish(this.exchange.name || "", ctx.to, content, options);
488
+ published.catch(noop);
489
+ try {
490
+ return await Promise.race([published, failure(channel)]);
491
+ } finally {
492
+ channel.close().catch(noop);
493
+ }
494
+ } catch (e) {
495
+ throw toError(e);
496
+ }
497
+ }
498
+ };
499
+ //#endregion
500
+ export { AMQP_EXTENSION_ERROR_MARKER, 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 };
501
+
502
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/consume/constants.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\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 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 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 type { ConsumeHandlers, ConsumeOptions } from './types';\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 * A failure is then reported to onError.\n */\nexport async function handleMessage(\n message: ConsumeMessage | null,\n channel: Pick<Channel, 'ack' | 'nack'>,\n handlers: ConsumeHandlers,\n options: ConsumeOptions,\n) : Promise<void> {\n // null = the broker cancelled the consumer\n if (!message) {\n return;\n }\n\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 let ok = !!handler;\n let error : unknown;\n if (handler) {\n try {\n await handler(message, channel as Channel);\n } catch (e) {\n ok = false;\n error = e;\n }\n } else {\n error = ClientError.handlerMissing(type);\n }\n\n if (!options.noAck) {\n try {\n if (ok) {\n channel.ack(message);\n } else {\n channel.nack(message, false, options.requeueOnFailure ?? false);\n }\n } catch {\n // the channel closed while the handler ran (e.g. reconnect): the broker redelivers the message anyway\n }\n }\n\n if (!ok && options.onError) {\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 * 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} 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 } 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\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 { consumerTag } = await ch.consume(queue, (message) => {\n const handled = handleMessage(message, ch, ctx.handlers, options);\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 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;;;ACApC,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,qBAAA;CACA,UAAA,0BAAA;;AACJ,EAAA,CAAA,CAAA;AAGA,MAAa,8BAA8B,OAAO,IAAI,mCAAmC;AACzF,MAAa,wBAAwB,OAAO,IAAI,8BAA8B;AAC9E,MAAa,sBAAsB,OAAO,IAAI,4BAA4B;AAC1E,MAAa,sBAAsB,OAAO,IAAI,4BAA4B;AAC1E,MAAa,6BAA6B,OAAO,IAAI,mCAAmC;;;;;;;;;;ACNxF,IAAa,qBAAb,cAAwC,UAAU;CAC9C,QAAiB,OAAO,aAAa,OAA0B;EAC3D,OAAO,cAAc,OAAO,2BAA2B;CAC3D;CAEA,YAAY,OAAoB;EAC5B,MAAM,KAAK;EACX,eAAe,MAAM,2BAA2B;CACpD;AACJ;;;;;;ACXA,IAAa,cAAb,MAAa,oBAAoB,mBAAmB;CAChD,QAAiB,OAAO,aAAa,OAA0B;EAC3D,OAAO,cAAc,OAAO,mBAAmB;CACnD;CAEA;CAEA;CAEA;CAEA,YAAY,OAAmB,OAAoB;EAC/C,MAAM,KAAK;EAEX,KAAK,YAAY,MAAM;EACvB,KAAK,UAAU,MAAM;EACrB,KAAK,WAAW,MAAM;EAEtB,eAAe,MAAM,mBAAmB;CAC5C;CAEA,SAAkB;EACd,OAAO;GACH,GAAG,MAAM,OAAO;GAChB,WAAW,KAAK;GAChB,SAAS,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