hooksend 0.0.0-stage → 1.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,719 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ BlockedError: () => BlockedError,
34
+ DEFAULT_JITTER: () => DEFAULT_JITTER,
35
+ DEFAULT_MAX_RETRY_AFTER_MS: () => DEFAULT_MAX_RETRY_AFTER_MS,
36
+ DEFAULT_SCHEDULE: () => DEFAULT_SCHEDULE,
37
+ DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
38
+ MemoryStore: () => MemoryStore,
39
+ VERSION: () => VERSION,
40
+ applyJitter: () => applyJitter,
41
+ checkUrl: () => checkUrl,
42
+ createDispatcher: () => createDispatcher,
43
+ createMessageId: () => createMessageId,
44
+ createSafeLookup: () => createSafeLookup,
45
+ decodeSecret: () => decodeSecret,
46
+ deliver: () => deliver,
47
+ generateSecret: () => generateSecret,
48
+ isPrivateAddress: () => isPrivateAddress,
49
+ parseRetryAfter: () => parseRetryAfter,
50
+ prepareMessage: () => prepareMessage,
51
+ sendOnce: () => sendOnce,
52
+ shouldRetry: () => shouldRetry,
53
+ sign: () => sign
54
+ });
55
+ module.exports = __toCommonJS(src_exports);
56
+
57
+ // src/sign.ts
58
+ var import_node_crypto = require("crypto");
59
+ var SECRET_PREFIX = "whsec_";
60
+ var BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
61
+ function generateSecret() {
62
+ return SECRET_PREFIX + (0, import_node_crypto.randomBytes)(32).toString("base64");
63
+ }
64
+ var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
65
+ function createMessageId() {
66
+ let id = "msg_";
67
+ while (id.length < 28) {
68
+ for (const byte of (0, import_node_crypto.randomBytes)(32)) {
69
+ if (byte < 248 && id.length < 28) id += ALPHABET[byte % 62];
70
+ }
71
+ }
72
+ return id;
73
+ }
74
+ function decodeSecret(secret) {
75
+ if (typeof secret !== "string") throw new TypeError("Secret must be a string");
76
+ const raw = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : secret;
77
+ if (raw.length === 0 || !BASE64.test(raw)) {
78
+ throw new TypeError('Invalid secret: expected "whsec_" followed by base64 (use generateSecret())');
79
+ }
80
+ return Buffer.from(raw, "base64");
81
+ }
82
+ function toSeconds(timestamp) {
83
+ if (timestamp === void 0) return Math.floor(Date.now() / 1e3);
84
+ if (timestamp instanceof Date) return Math.floor(timestamp.getTime() / 1e3);
85
+ if (!Number.isFinite(timestamp)) throw new TypeError("Invalid timestamp");
86
+ return Math.floor(timestamp);
87
+ }
88
+ function secretList(options) {
89
+ const list = [];
90
+ if (Array.isArray(options.secret)) list.push(...options.secret);
91
+ else if (options.secret !== void 0) list.push(options.secret);
92
+ if (options.secrets) list.push(...options.secrets);
93
+ if (list.length === 0) throw new TypeError("A secret is required to sign a webhook");
94
+ return list;
95
+ }
96
+ function sign(options) {
97
+ const id = options.id ?? createMessageId();
98
+ if (typeof id !== "string" || id.length === 0) throw new TypeError("Message id must be a non-empty string");
99
+ const timestamp = toSeconds(options.timestamp);
100
+ const body = typeof options.body === "string" ? Buffer.from(options.body, "utf8") : options.body;
101
+ if (!(body instanceof Uint8Array)) throw new TypeError("Body must be a string or Uint8Array");
102
+ const keys = secretList(options).map(decodeSecret);
103
+ const prefix = Buffer.from(`${id}.${timestamp}.`, "utf8");
104
+ const signatures = keys.map(
105
+ (key) => "v1," + (0, import_node_crypto.createHmac)("sha256", key).update(prefix).update(body).digest("base64")
106
+ );
107
+ return {
108
+ "webhook-id": id,
109
+ "webhook-timestamp": String(timestamp),
110
+ "webhook-signature": signatures.join(" ")
111
+ };
112
+ }
113
+
114
+ // src/ssrf.ts
115
+ var import_node_dns = require("dns");
116
+ var import_node_net = require("net");
117
+ var BlockedError = class extends Error {
118
+ code = "HOOKSEND_BLOCKED";
119
+ constructor(message) {
120
+ super(message);
121
+ this.name = "BlockedError";
122
+ }
123
+ };
124
+ function parseIPv4(ip) {
125
+ const parts = ip.split(".");
126
+ if (parts.length !== 4) return null;
127
+ const out = [];
128
+ for (const part of parts) {
129
+ if (!/^\d{1,3}$/.test(part)) return null;
130
+ const n = Number(part);
131
+ if (n > 255) return null;
132
+ out.push(n);
133
+ }
134
+ return out;
135
+ }
136
+ function ipv4Private(b) {
137
+ const [a, c] = [b[0], b[1]];
138
+ const d = b[2];
139
+ return a === 0 || // "this" network
140
+ a === 10 || // private
141
+ a === 100 && c >= 64 && c <= 127 || // CGNAT 100.64/10
142
+ a === 127 || // loopback
143
+ a === 169 && c === 254 || // link-local, cloud metadata
144
+ a === 172 && c >= 16 && c <= 31 || // private
145
+ a === 192 && c === 0 && d === 0 || // IETF protocol assignments
146
+ a === 192 && c === 0 && d === 2 || // TEST-NET-1
147
+ a === 192 && c === 88 && d === 99 || // 6to4 relay anycast
148
+ a === 192 && c === 168 || // private
149
+ a === 198 && (c === 18 || c === 19) || // benchmarking
150
+ a === 198 && c === 51 && d === 100 || // TEST-NET-2
151
+ a === 203 && c === 0 && d === 113 || // TEST-NET-3
152
+ a >= 224;
153
+ }
154
+ function parseIPv6(input) {
155
+ let ip = input;
156
+ const zone = ip.indexOf("%");
157
+ if (zone !== -1) ip = ip.slice(0, zone);
158
+ if ((0, import_node_net.isIP)(ip) !== 6) return null;
159
+ const lastColon = ip.lastIndexOf(":");
160
+ const tail = ip.slice(lastColon + 1);
161
+ if (tail.includes(".")) {
162
+ const v4 = parseIPv4(tail);
163
+ if (!v4) return null;
164
+ ip = `${ip.slice(0, lastColon + 1)}${(v4[0] << 8 | v4[1]).toString(16)}:${(v4[2] << 8 | v4[3]).toString(16)}`;
165
+ }
166
+ const [head, rest] = ip.split("::");
167
+ const headParts = head ? head.split(":") : [];
168
+ const restParts = rest !== void 0 && rest !== "" ? rest.split(":") : [];
169
+ const fill = rest !== void 0 ? 8 - headParts.length - restParts.length : 0;
170
+ const hextets = [...headParts, ...Array(Math.max(fill, 0)).fill("0"), ...restParts].map(
171
+ (h) => parseInt(h, 16)
172
+ );
173
+ if (hextets.length !== 8 || hextets.some((h) => Number.isNaN(h))) return null;
174
+ return hextets;
175
+ }
176
+ function embeddedV4(h, from) {
177
+ return [h[from] >> 8, h[from] & 255, h[from + 1] >> 8, h[from + 1] & 255];
178
+ }
179
+ function ipv6Private(h) {
180
+ const zeroUntil = (n) => h.slice(0, n).every((x) => x === 0);
181
+ if (zeroUntil(8)) return true;
182
+ if (zeroUntil(7) && h[7] === 1) return true;
183
+ if (zeroUntil(5) && h[5] === 65535) return ipv4Private(embeddedV4(h, 6));
184
+ if (zeroUntil(6)) return true;
185
+ if (zeroUntil(4) && h[4] === 65535 && h[5] === 0) return true;
186
+ if (h[0] === 100 && h[1] === 65435 && h.slice(2, 6).every((x) => x === 0)) {
187
+ return ipv4Private(embeddedV4(h, 6));
188
+ }
189
+ if (h[0] === 8194) return ipv4Private(embeddedV4(h, 1));
190
+ const first = h[0];
191
+ return (first & 65024) === 64512 || // unique local fc00::/7
192
+ (first & 65472) === 65152 || // link-local fe80::/10
193
+ (first & 65472) === 65216 || // site-local fec0::/10 (deprecated)
194
+ (first & 65280) === 65280 || // multicast ff00::/8
195
+ first === 8193 && h[1] === 3512 || // documentation 2001:db8::/32
196
+ first === 256 && h[1] === 0 && h[2] === 0 && h[3] === 0;
197
+ }
198
+ function isPrivateAddress(ip) {
199
+ const raw = ip.startsWith("[") && ip.endsWith("]") ? ip.slice(1, -1) : ip;
200
+ const v4 = parseIPv4(raw);
201
+ if (v4) return ipv4Private(v4);
202
+ const v6 = parseIPv6(raw);
203
+ if (v6) return ipv6Private(v6);
204
+ return true;
205
+ }
206
+ function bareHost(hostname) {
207
+ const h = hostname.toLowerCase();
208
+ return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
209
+ }
210
+ function allowSet(policy) {
211
+ return new Set((policy.allowHosts ?? []).map(bareHost));
212
+ }
213
+ function checkUrl(url, policy = {}) {
214
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
215
+ throw new BlockedError(`Blocked: only http: and https: URLs are allowed (got ${url.protocol})`);
216
+ }
217
+ if (policy.allowPrivateNetworks) return;
218
+ const host = bareHost(url.hostname);
219
+ if (allowSet(policy).has(host)) return;
220
+ if ((0, import_node_net.isIP)(host) !== 0 && isPrivateAddress(host)) {
221
+ throw new BlockedError(`Blocked: ${url.hostname} is a private address${host === url.hostname ? "" : ` (${host})`}`);
222
+ }
223
+ }
224
+ var defaultResolver = (hostname) => new Promise((resolve, reject) => {
225
+ (0, import_node_dns.lookup)(hostname, { all: true, family: 0 }, (err, addresses) => {
226
+ if (err) reject(err);
227
+ else resolve(addresses);
228
+ });
229
+ });
230
+ function createSafeLookup(policy = {}) {
231
+ const resolver = policy.resolver ?? defaultResolver;
232
+ const allowed = allowSet(policy);
233
+ return (hostname, options, callback) => {
234
+ const opts = typeof options === "object" && options !== null ? options : {};
235
+ const family = opts.family === 4 || opts.family === "IPv4" ? 4 : opts.family === 6 || opts.family === "IPv6" ? 6 : 0;
236
+ resolver(hostname).then(
237
+ (all) => {
238
+ const addresses = family === 0 ? all : all.filter((a) => a.family === family);
239
+ if (addresses.length === 0) {
240
+ const err = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
241
+ err.code = "ENOTFOUND";
242
+ callback(err, "");
243
+ return;
244
+ }
245
+ const skip = policy.allowPrivateNetworks || allowed.has(bareHost(hostname));
246
+ if (!skip) {
247
+ for (const a of addresses) {
248
+ if (isPrivateAddress(a.address) && !allowed.has(bareHost(a.address))) {
249
+ callback(new BlockedError(`Blocked: ${hostname} resolves to a private address (${a.address})`), "");
250
+ return;
251
+ }
252
+ }
253
+ }
254
+ if (opts.all) callback(null, addresses);
255
+ else callback(null, addresses[0].address, addresses[0].family);
256
+ },
257
+ (err) => callback(err, "")
258
+ );
259
+ };
260
+ }
261
+
262
+ // src/send.ts
263
+ var import_node_http = __toESM(require("http"), 1);
264
+ var import_node_https = __toESM(require("https"), 1);
265
+
266
+ // src/version.ts
267
+ var VERSION = true ? "1.0.0" : "dev";
268
+
269
+ // src/send.ts
270
+ var MAX_RESPONSE_BYTES = 2048;
271
+ var DEFAULT_TIMEOUT_MS = 15e3;
272
+ function prepareMessage(message, now = Date.now) {
273
+ const id = message.id ?? createMessageId();
274
+ if (message.body !== void 0) {
275
+ const body = typeof message.body === "string" ? Buffer.from(message.body, "utf8") : message.body;
276
+ return { id, body };
277
+ }
278
+ if (typeof message.type !== "string" || message.type.length === 0) {
279
+ throw new TypeError("Message needs a `type` (or a raw `body`)");
280
+ }
281
+ const date = message.timestamp === void 0 ? new Date(now()) : new Date(message.timestamp);
282
+ if (Number.isNaN(date.getTime())) throw new TypeError("Invalid message timestamp");
283
+ const timestamp = date.toISOString();
284
+ const json = JSON.stringify({ type: message.type, timestamp, data: message.data ?? null });
285
+ return { id, body: Buffer.from(json, "utf8") };
286
+ }
287
+ function parseRetryAfter(value, now = Date.now()) {
288
+ if (value === void 0) return void 0;
289
+ const v = value.trim();
290
+ if (v === "") return void 0;
291
+ if (/^\d+(\.\d+)?$/.test(v)) return Math.round(Number(v) * 1e3);
292
+ const date = Date.parse(v);
293
+ if (Number.isNaN(date)) return void 0;
294
+ return Math.max(0, date - now);
295
+ }
296
+ function describeError(err) {
297
+ if (err instanceof BlockedError) return { message: err.message, type: "blocked" };
298
+ if (err instanceof AggregateError) {
299
+ const blocked = err.errors.find((e) => e instanceof BlockedError);
300
+ if (blocked) return { message: blocked.message, type: "blocked" };
301
+ const first = err.errors[0];
302
+ if (first) return describeError(first);
303
+ }
304
+ if (err instanceof Error) {
305
+ const code = err.code;
306
+ return { message: err.message || code || "Network error", type: "network" };
307
+ }
308
+ return { message: String(err), type: "network" };
309
+ }
310
+ function lowerHeaders(headers) {
311
+ const out = {};
312
+ if (headers) for (const [k, v] of Object.entries(headers)) out[k.toLowerCase()] = String(v);
313
+ return out;
314
+ }
315
+ async function sendOnce(endpoint, message, options = {}) {
316
+ const now = options.now ?? Date.now;
317
+ const attempt = options.attempt ?? 1;
318
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
319
+ const prepared = "body" in message && message.body instanceof Uint8Array && typeof message.id === "string" ? message : prepareMessage(message, now);
320
+ const started = performance.now();
321
+ const base = { attempt, url: endpoint.url, id: prepared.id };
322
+ const fail = (error, errorType) => ({
323
+ ...base,
324
+ ok: false,
325
+ status: null,
326
+ durationMs: Math.round(performance.now() - started),
327
+ error,
328
+ errorType
329
+ });
330
+ let url;
331
+ try {
332
+ url = new URL(endpoint.url);
333
+ } catch {
334
+ return fail(`Invalid URL: ${endpoint.url}`, "invalid");
335
+ }
336
+ try {
337
+ checkUrl(url, options);
338
+ } catch (err) {
339
+ return fail(err.message, "blocked");
340
+ }
341
+ if (options.signal?.aborted) return fail("Aborted", "aborted");
342
+ const signature = sign({
343
+ id: prepared.id,
344
+ timestamp: Math.floor(now() / 1e3),
345
+ body: prepared.body,
346
+ secret: endpoint.secret
347
+ });
348
+ const headers = {
349
+ "content-type": "application/json",
350
+ "user-agent": `hooksend/${VERSION}`,
351
+ ...lowerHeaders(options.headers),
352
+ ...lowerHeaders(endpoint.headers),
353
+ ...signature,
354
+ "content-length": String(prepared.body.byteLength)
355
+ };
356
+ const mod = url.protocol === "https:" ? import_node_https.default : import_node_http.default;
357
+ return new Promise((resolve) => {
358
+ let settled = false;
359
+ const finish = (result) => {
360
+ if (settled) return;
361
+ settled = true;
362
+ clearTimeout(timer);
363
+ options.signal?.removeEventListener("abort", onAbort);
364
+ resolve(result);
365
+ };
366
+ let failure;
367
+ const req = mod.request(url, {
368
+ method: "POST",
369
+ headers,
370
+ agent: false,
371
+ lookup: createSafeLookup(options)
372
+ });
373
+ const timer = setTimeout(() => {
374
+ failure = { message: `Timed out after ${timeoutMs}ms`, type: "timeout" };
375
+ req.destroy(new Error(failure.message));
376
+ }, timeoutMs);
377
+ const onAbort = () => {
378
+ failure = { message: "Aborted", type: "aborted" };
379
+ req.destroy(new Error("Aborted"));
380
+ };
381
+ options.signal?.addEventListener("abort", onAbort, { once: true });
382
+ req.on("error", (err) => {
383
+ const info = failure ?? describeError(err);
384
+ finish(fail(info.message, info.type));
385
+ });
386
+ req.on("response", (res) => {
387
+ const status = res.statusCode ?? 0;
388
+ const durationMs = Math.round(performance.now() - started);
389
+ const chunks = [];
390
+ let size = 0;
391
+ const done = () => {
392
+ const responseBody = Buffer.concat(chunks).subarray(0, MAX_RESPONSE_BYTES).toString("utf8");
393
+ const retryAfter = res.headers["retry-after"];
394
+ const retryAfterMs = parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] : retryAfter, now());
395
+ const ok = status >= 200 && status < 300;
396
+ let error;
397
+ if (!ok) {
398
+ error = status >= 300 && status < 400 ? `Redirect not followed (${status}${res.headers.location ? ` to ${res.headers.location}` : ""})` : `HTTP ${status}${res.statusMessage ? ` ${res.statusMessage}` : ""}`;
399
+ }
400
+ finish({
401
+ ...base,
402
+ ok,
403
+ status,
404
+ ...res.statusMessage ? { statusText: res.statusMessage } : {},
405
+ durationMs,
406
+ ...error !== void 0 ? { error } : {},
407
+ ...responseBody !== "" ? { responseBody } : {},
408
+ ...retryAfterMs !== void 0 ? { retryAfterMs } : {}
409
+ });
410
+ res.destroy();
411
+ };
412
+ res.on("data", (chunk) => {
413
+ if (size >= MAX_RESPONSE_BYTES) return;
414
+ chunks.push(chunk);
415
+ size += chunk.length;
416
+ if (size >= MAX_RESPONSE_BYTES) done();
417
+ });
418
+ res.on("end", done);
419
+ res.on("error", done);
420
+ res.on("close", done);
421
+ });
422
+ req.end(prepared.body);
423
+ });
424
+ }
425
+
426
+ // src/deliver.ts
427
+ var SECOND = 1e3;
428
+ var MINUTE = 60 * SECOND;
429
+ var HOUR = 60 * MINUTE;
430
+ var DEFAULT_SCHEDULE = Object.freeze([
431
+ 0,
432
+ 5 * SECOND,
433
+ 5 * MINUTE,
434
+ 30 * MINUTE,
435
+ 2 * HOUR,
436
+ 5 * HOUR,
437
+ 10 * HOUR,
438
+ 10 * HOUR
439
+ ]);
440
+ var DEFAULT_JITTER = 0.2;
441
+ var DEFAULT_MAX_RETRY_AFTER_MS = HOUR;
442
+ function shouldRetry(result) {
443
+ if (result.ok) return false;
444
+ if (result.status === null) return result.errorType === "network" || result.errorType === "timeout";
445
+ return result.status === 408 || result.status === 429 || result.status >= 500;
446
+ }
447
+ var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
448
+ if (signal?.aborted) {
449
+ reject(new Error("Aborted"));
450
+ return;
451
+ }
452
+ const timer = setTimeout(() => {
453
+ signal?.removeEventListener("abort", onAbort);
454
+ resolve();
455
+ }, ms);
456
+ const onAbort = () => {
457
+ clearTimeout(timer);
458
+ reject(new Error("Aborted"));
459
+ };
460
+ signal?.addEventListener("abort", onAbort, { once: true });
461
+ });
462
+ function applyJitter(ms, jitter = DEFAULT_JITTER, random = Math.random) {
463
+ if (ms <= 0 || jitter <= 0) return Math.max(0, ms);
464
+ return Math.max(0, Math.round(ms * (1 + (random() * 2 - 1) * jitter)));
465
+ }
466
+ function safeCall(fn, arg) {
467
+ if (!fn) return;
468
+ try {
469
+ fn(arg);
470
+ } catch {
471
+ }
472
+ }
473
+ async function deliverWith(endpoint, message, options = {}, hooks = {}) {
474
+ const now = options.now ?? Date.now;
475
+ const schedule = options.schedule ?? DEFAULT_SCHEDULE;
476
+ if (schedule.length === 0 || schedule.some((ms) => !Number.isFinite(ms) || ms < 0)) {
477
+ throw new TypeError("schedule must be a non-empty array of waits in ms (>= 0)");
478
+ }
479
+ const jitter = options.jitter ?? DEFAULT_JITTER;
480
+ const random = options.random ?? Math.random;
481
+ const sleep = options.sleep ?? defaultSleep;
482
+ const retryOn = options.retryOn ?? shouldRetry;
483
+ const maxRetryAfter = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
484
+ const limit = hooks.limit ?? ((fn) => fn());
485
+ const start = Math.max(1, Math.floor(options.startAttempt ?? 1));
486
+ const prepared = "body" in message && message.body instanceof Uint8Array && typeof message.id === "string" ? message : prepareMessage(message, now);
487
+ const attempts = [];
488
+ const result = (extra = {}) => ({
489
+ delivered: false,
490
+ disabled: false,
491
+ aborted: false,
492
+ id: prepared.id,
493
+ attempts,
494
+ ...extra
495
+ });
496
+ let wait = start === 1 ? applyJitter(schedule[0], jitter, random) : 0;
497
+ for (let attempt = start; attempt <= schedule.length; attempt++) {
498
+ if (wait > 0) {
499
+ try {
500
+ await sleep(wait, hooks.waitSignal ?? options.signal);
501
+ } catch {
502
+ return result({ aborted: true });
503
+ }
504
+ }
505
+ if (options.signal?.aborted || hooks.waitSignal?.aborted) return result({ aborted: true });
506
+ const sendOptions = { ...options, attempt };
507
+ const res = await limit(() => sendOnce(endpoint, prepared, sendOptions));
508
+ attempts.push(res);
509
+ if (res.ok) {
510
+ safeCall(options.onAttempt, res);
511
+ return result({ delivered: true });
512
+ }
513
+ if (res.status === 410) {
514
+ safeCall(options.onAttempt, res);
515
+ return result({ disabled: true });
516
+ }
517
+ if (res.errorType === "aborted") {
518
+ safeCall(options.onAttempt, res);
519
+ return result({ aborted: true });
520
+ }
521
+ const retry = attempt < schedule.length && retryOn(res);
522
+ if (!retry) {
523
+ safeCall(options.onAttempt, res);
524
+ return result();
525
+ }
526
+ wait = applyJitter(schedule[attempt], jitter, random);
527
+ if (res.retryAfterMs !== void 0) wait = Math.max(wait, Math.min(res.retryAfterMs, maxRetryAfter));
528
+ res.retryInMs = wait;
529
+ safeCall(options.onAttempt, res);
530
+ if (hooks.onRetryScheduled) await hooks.onRetryScheduled(attempt + 1, wait);
531
+ }
532
+ return result();
533
+ }
534
+ function deliver(endpoint, message, options = {}) {
535
+ return deliverWith(endpoint, message, options);
536
+ }
537
+
538
+ // src/dispatcher.ts
539
+ var MemoryStore = class {
540
+ jobs = /* @__PURE__ */ new Map();
541
+ save(job) {
542
+ this.jobs.set(job.id, { ...job });
543
+ }
544
+ remove(id) {
545
+ this.jobs.delete(id);
546
+ }
547
+ due(now) {
548
+ return [...this.jobs.values()].filter((job) => job.nextAttemptAt <= now).map((job) => ({ ...job }));
549
+ }
550
+ };
551
+ function createLimiter(max) {
552
+ let active = 0;
553
+ const queue = [];
554
+ const next = () => {
555
+ if (active >= max) return;
556
+ const run = queue.shift();
557
+ if (run) {
558
+ active++;
559
+ run();
560
+ }
561
+ };
562
+ return (fn) => new Promise((resolve, reject) => {
563
+ queue.push(() => {
564
+ fn().then(resolve, reject).finally(() => {
565
+ active--;
566
+ next();
567
+ });
568
+ });
569
+ next();
570
+ });
571
+ }
572
+ function safeCall2(fn, arg) {
573
+ if (!fn) return;
574
+ try {
575
+ fn(arg);
576
+ } catch {
577
+ }
578
+ }
579
+ function createDispatcher(options = {}) {
580
+ const {
581
+ concurrency = 10,
582
+ store = new MemoryStore(),
583
+ onAttempt,
584
+ onDelivered,
585
+ onFailed,
586
+ onDisabled,
587
+ ...deliverOptions
588
+ } = options;
589
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new TypeError("concurrency must be a positive integer");
590
+ const now = options.now ?? Date.now;
591
+ const limit = createLimiter(concurrency);
592
+ const controller = new AbortController();
593
+ const active = /* @__PURE__ */ new Map();
594
+ let closed = false;
595
+ async function runJob(job) {
596
+ const base = { url: job.endpoint.url, jobId: job.id };
597
+ let res;
598
+ try {
599
+ await store.save(job);
600
+ res = await deliverWith(
601
+ job.endpoint,
602
+ { id: job.messageId, body: Buffer.from(job.body, "utf8") },
603
+ {
604
+ ...deliverOptions,
605
+ startAttempt: job.attempt,
606
+ ...onAttempt ? { onAttempt } : {}
607
+ },
608
+ {
609
+ limit,
610
+ waitSignal: controller.signal,
611
+ onRetryScheduled: async (nextAttempt, delayMs) => {
612
+ job.attempt = nextAttempt;
613
+ job.nextAttemptAt = now() + delayMs;
614
+ await store.save(job);
615
+ }
616
+ }
617
+ );
618
+ } catch (err) {
619
+ return {
620
+ ...base,
621
+ delivered: false,
622
+ disabled: false,
623
+ aborted: false,
624
+ id: job.messageId,
625
+ attempts: [],
626
+ error: `Store error: ${err instanceof Error ? err.message : String(err)}`
627
+ };
628
+ }
629
+ const out = { ...base, ...res };
630
+ if (res.aborted) return out;
631
+ try {
632
+ await store.remove(job.id);
633
+ } catch (err) {
634
+ out.error = `Store error: ${err instanceof Error ? err.message : String(err)}`;
635
+ }
636
+ if (res.delivered) safeCall2(onDelivered, out);
637
+ else if (res.disabled) safeCall2(onDisabled, out);
638
+ else safeCall2(onFailed, out);
639
+ return out;
640
+ }
641
+ function track(job) {
642
+ const existing = active.get(job.id);
643
+ if (existing) return existing;
644
+ const p = runJob(job).finally(() => active.delete(job.id));
645
+ active.set(job.id, p);
646
+ return p;
647
+ }
648
+ return {
649
+ async dispatch(input) {
650
+ if (closed) throw new Error("Dispatcher is closed");
651
+ if (!input || typeof input.type !== "string" || input.type.length === 0) {
652
+ throw new TypeError("dispatch() needs a `type`");
653
+ }
654
+ if (!Array.isArray(input.endpoints)) throw new TypeError("dispatch() needs an `endpoints` array");
655
+ const id = input.id ?? createMessageId();
656
+ const prepared = prepareMessage(
657
+ { type: input.type, data: input.data, id, ...input.timestamp !== void 0 ? { timestamp: input.timestamp } : {} },
658
+ now
659
+ );
660
+ const body = Buffer.from(prepared.body).toString("utf8");
661
+ const createdAt = now();
662
+ const results = await Promise.all(
663
+ input.endpoints.map(
664
+ (endpoint, i) => track({
665
+ id: `${id}:${i}`,
666
+ messageId: id,
667
+ type: input.type,
668
+ body,
669
+ endpoint,
670
+ attempt: 1,
671
+ nextAttemptAt: createdAt,
672
+ createdAt
673
+ })
674
+ )
675
+ );
676
+ return { id, results };
677
+ },
678
+ async resume() {
679
+ if (closed) throw new Error("Dispatcher is closed");
680
+ const jobs = await store.due(now());
681
+ return Promise.all(jobs.map((job) => track({ ...job })));
682
+ },
683
+ async drain() {
684
+ while (active.size > 0) await Promise.allSettled([...active.values()]);
685
+ },
686
+ async close() {
687
+ closed = true;
688
+ controller.abort();
689
+ while (active.size > 0) await Promise.allSettled([...active.values()]);
690
+ },
691
+ get pending() {
692
+ return active.size;
693
+ }
694
+ };
695
+ }
696
+ // Annotate the CommonJS export names for ESM import in node:
697
+ 0 && (module.exports = {
698
+ BlockedError,
699
+ DEFAULT_JITTER,
700
+ DEFAULT_MAX_RETRY_AFTER_MS,
701
+ DEFAULT_SCHEDULE,
702
+ DEFAULT_TIMEOUT_MS,
703
+ MemoryStore,
704
+ VERSION,
705
+ applyJitter,
706
+ checkUrl,
707
+ createDispatcher,
708
+ createMessageId,
709
+ createSafeLookup,
710
+ decodeSecret,
711
+ deliver,
712
+ generateSecret,
713
+ isPrivateAddress,
714
+ parseRetryAfter,
715
+ prepareMessage,
716
+ sendOnce,
717
+ shouldRetry,
718
+ sign
719
+ });