@objectstack/plugin-webhooks 5.1.0 → 6.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 (55) hide show
  1. package/.turbo/turbo-build.log +35 -13
  2. package/CHANGELOG.md +17 -33
  3. package/dist/chunk-33LYZT7O.js +184 -0
  4. package/dist/chunk-33LYZT7O.js.map +1 -0
  5. package/dist/chunk-BS2QTZH3.js +256 -0
  6. package/dist/chunk-BS2QTZH3.js.map +1 -0
  7. package/dist/chunk-FA66GQEO.cjs +256 -0
  8. package/dist/chunk-FA66GQEO.cjs.map +1 -0
  9. package/dist/chunk-MJZGD37S.cjs +184 -0
  10. package/dist/chunk-MJZGD37S.cjs.map +1 -0
  11. package/dist/index.cjs +908 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +469 -0
  14. package/dist/index.d.ts +435 -70
  15. package/dist/index.js +872 -217
  16. package/dist/index.js.map +1 -1
  17. package/dist/outbox-CIn7LSyB.d.cts +155 -0
  18. package/dist/outbox-CIn7LSyB.d.ts +155 -0
  19. package/dist/schema.cjs +9 -0
  20. package/dist/schema.cjs.map +1 -0
  21. package/dist/schema.d.cts +4787 -0
  22. package/dist/schema.d.ts +4787 -0
  23. package/dist/schema.js +9 -0
  24. package/dist/schema.js.map +1 -0
  25. package/dist/sql-outbox.cjs +8 -0
  26. package/dist/sql-outbox.cjs.map +1 -0
  27. package/dist/sql-outbox.d.cts +55 -0
  28. package/dist/sql-outbox.d.ts +55 -0
  29. package/dist/sql-outbox.js +8 -0
  30. package/dist/sql-outbox.js.map +1 -0
  31. package/package.json +30 -10
  32. package/src/auto-enqueuer.test.ts +391 -0
  33. package/src/auto-enqueuer.ts +335 -0
  34. package/src/dispatcher.test.ts +324 -0
  35. package/src/dispatcher.ts +218 -0
  36. package/src/http-sender.ts +187 -0
  37. package/src/index.ts +49 -12
  38. package/src/memory-outbox.test.ts +86 -0
  39. package/src/memory-outbox.ts +155 -0
  40. package/src/outbox.ts +175 -0
  41. package/src/partition.ts +19 -0
  42. package/src/retention.test.ts +116 -0
  43. package/src/retention.ts +144 -0
  44. package/src/schema.ts +22 -0
  45. package/src/sql-outbox.test.ts +490 -0
  46. package/src/sql-outbox.ts +343 -0
  47. package/src/sys-webhook-delivery.object.ts +224 -0
  48. package/src/webhook-outbox-plugin.ts +442 -0
  49. package/tsconfig.json +5 -13
  50. package/tsup.config.ts +14 -0
  51. package/dist/index.d.mts +0 -104
  52. package/dist/index.mjs +0 -216
  53. package/dist/index.mjs.map +0 -1
  54. package/src/webhooks-plugin.test.ts +0 -218
  55. package/src/webhooks-plugin.ts +0 -294
package/dist/index.cjs ADDED
@@ -0,0 +1,908 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+ var _chunkFA66GQEOcjs = require('./chunk-FA66GQEO.cjs');
6
+
7
+
8
+
9
+ var _chunkMJZGD37Scjs = require('./chunk-MJZGD37S.cjs');
10
+
11
+ // src/webhook-outbox-plugin.ts
12
+ var _integration = require('@objectstack/platform-objects/integration');
13
+
14
+ // src/auto-enqueuer.ts
15
+ var AutoEnqueuer = class {
16
+ constructor(engine, realtime, outbox, opts = {}) {
17
+ this.engine = engine;
18
+ this.realtime = realtime;
19
+ this.outbox = outbox;
20
+ this.subscriptions = /* @__PURE__ */ new Map();
21
+ this.running = false;
22
+ this.subscriptionsObject = _nullishCoalesce(opts.subscriptionsObject, () => ( "sys_webhook"));
23
+ this.refreshIntervalMs = _nullishCoalesce(opts.refreshIntervalMs, () => ( 6e4));
24
+ this.logger = _nullishCoalesce(opts.logger, () => ( {}));
25
+ }
26
+ /**
27
+ * Load the subscription cache and start listening for events.
28
+ */
29
+ async start() {
30
+ if (this.running) return;
31
+ this.running = true;
32
+ await this.refresh();
33
+ this.subId = await this.realtime.subscribe(
34
+ "webhook-auto-enqueuer",
35
+ (event) => this.handleEvent(event)
36
+ );
37
+ this.subIdSelfHeal = await this.realtime.subscribe(
38
+ "webhook-auto-enqueuer-self-heal",
39
+ (event) => this.handleSelfHealEvent(event),
40
+ { object: this.subscriptionsObject }
41
+ );
42
+ if (this.refreshIntervalMs > 0) {
43
+ this.refreshTimer = setInterval(() => {
44
+ this.refresh().catch(
45
+ (err) => _optionalChain([this, 'access', _ => _.logger, 'access', _2 => _2.warn, 'optionalCall', _3 => _3("[webhook-auto-enqueuer] periodic refresh failed", err)])
46
+ );
47
+ }, this.refreshIntervalMs);
48
+ _optionalChain([this, 'access', _4 => _4.refreshTimer, 'access', _5 => _5.unref, 'optionalCall', _6 => _6()]);
49
+ }
50
+ }
51
+ async stop() {
52
+ if (!this.running) return;
53
+ this.running = false;
54
+ if (this.subId) await this.realtime.unsubscribe(this.subId);
55
+ if (this.subIdSelfHeal) await this.realtime.unsubscribe(this.subIdSelfHeal);
56
+ if (this.refreshTimer) clearInterval(this.refreshTimer);
57
+ this.subId = void 0;
58
+ this.subIdSelfHeal = void 0;
59
+ this.refreshTimer = void 0;
60
+ }
61
+ /**
62
+ * Force-refresh the subscription cache from storage. Concurrent
63
+ * callers share a single in-flight refresh.
64
+ */
65
+ async refresh() {
66
+ if (this.refreshing) return this.refreshing;
67
+ this.refreshing = this.doRefresh().finally(() => {
68
+ this.refreshing = void 0;
69
+ });
70
+ return this.refreshing;
71
+ }
72
+ async doRefresh() {
73
+ let rows;
74
+ try {
75
+ rows = await this.engine.find(this.subscriptionsObject, {
76
+ where: { active: true }
77
+ });
78
+ } catch (err) {
79
+ _optionalChain([this, 'access', _7 => _7.logger, 'access', _8 => _8.warn, 'optionalCall', _9 => _9(
80
+ `[webhook-auto-enqueuer] failed to load ${this.subscriptionsObject}`,
81
+ err
82
+ )]);
83
+ return;
84
+ }
85
+ const next = /* @__PURE__ */ new Map();
86
+ for (const row of rows) {
87
+ const sub = this.parseRow(row);
88
+ if (!sub) continue;
89
+ const key = _nullishCoalesce(sub.objectName, () => ( "*"));
90
+ const arr = _nullishCoalesce(next.get(key), () => ( []));
91
+ arr.push(sub);
92
+ next.set(key, arr);
93
+ }
94
+ this.subscriptions.clear();
95
+ for (const [k, v] of next) this.subscriptions.set(k, v);
96
+ _optionalChain([this, 'access', _10 => _10.logger, 'access', _11 => _11.debug, 'optionalCall', _12 => _12("[webhook-auto-enqueuer] cache refreshed", {
97
+ objects: this.subscriptions.size,
98
+ rows: rows.length
99
+ })]);
100
+ }
101
+ parseRow(row) {
102
+ if (!_optionalChain([row, 'optionalAccess', _13 => _13.id]) || !_optionalChain([row, 'optionalAccess', _14 => _14.url])) return null;
103
+ const triggersField = _nullishCoalesce(row.triggers, () => ( ""));
104
+ const triggers = new Set(
105
+ triggersField.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
106
+ );
107
+ if (triggers.size === 0) {
108
+ return null;
109
+ }
110
+ let defn = {};
111
+ if (typeof row.definition_json === "string" && row.definition_json.length > 0) {
112
+ try {
113
+ defn = _nullishCoalesce(JSON.parse(row.definition_json), () => ( {}));
114
+ } catch (e2) {
115
+ defn = {};
116
+ }
117
+ }
118
+ return {
119
+ id: row.id,
120
+ name: _nullishCoalesce(row.name, () => ( row.id)),
121
+ objectName: row.object_name ? String(row.object_name) : void 0,
122
+ triggers,
123
+ url: String(row.url),
124
+ method: _nullishCoalesce(_nullishCoalesce(row.method, () => ( defn.method)), () => ( "POST")),
125
+ headers: defn.headers,
126
+ secret: defn.secret,
127
+ timeoutMs: defn.timeoutMs
128
+ };
129
+ }
130
+ /**
131
+ * Handler for the firehose subscription.
132
+ *
133
+ * NOTE: we intentionally `void` the inner enqueue() so the realtime
134
+ * publisher (and therefore the user's request) is never blocked on
135
+ * webhook persistence.
136
+ */
137
+ handleEvent(event) {
138
+ if (!_optionalChain([event, 'access', _15 => _15.type, 'optionalAccess', _16 => _16.startsWith, 'call', _17 => _17("data.record.")])) return;
139
+ if (!event.object) return;
140
+ if (event.object === this.subscriptionsObject) return;
141
+ const action = event.type.slice("data.record.".length);
142
+ const trigger = mapActionToTrigger(action);
143
+ if (!trigger) return;
144
+ const subs = [
145
+ ..._nullishCoalesce(this.subscriptions.get(event.object), () => ( [])),
146
+ ..._nullishCoalesce(this.subscriptions.get("*"), () => ( []))
147
+ ];
148
+ if (subs.length === 0) return;
149
+ const payload = _nullishCoalesce(event.payload, () => ( {}));
150
+ const recordId = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(payload.recordId, () => ( payload.id)), () => ( _optionalChain([payload, 'access', _18 => _18.after, 'optionalAccess', _19 => _19.id]))), () => ( _optionalChain([payload, 'access', _20 => _20.before, 'optionalAccess', _21 => _21.id]))), () => ( "unknown"));
151
+ const eventId = `${event.object}:${recordId}:${action}:${event.timestamp}`;
152
+ for (const sub of subs) {
153
+ if (!sub.triggers.has(trigger)) continue;
154
+ void this.outbox.enqueue({
155
+ webhookId: sub.id,
156
+ eventId,
157
+ eventType: event.type,
158
+ url: sub.url,
159
+ method: sub.method,
160
+ headers: sub.headers,
161
+ secret: sub.secret,
162
+ timeoutMs: sub.timeoutMs,
163
+ payload: {
164
+ object: event.object,
165
+ recordId,
166
+ action,
167
+ timestamp: event.timestamp,
168
+ ...payload
169
+ }
170
+ }).catch(
171
+ (err) => _optionalChain([this, 'access', _22 => _22.logger, 'access', _23 => _23.warn, 'optionalCall', _24 => _24("[webhook-auto-enqueuer] enqueue failed", {
172
+ webhook: sub.name,
173
+ eventId,
174
+ err: _nullishCoalesce(_optionalChain([err, 'optionalAccess', _25 => _25.message]), () => ( err))
175
+ })])
176
+ );
177
+ }
178
+ }
179
+ handleSelfHealEvent(event) {
180
+ if (event.object !== this.subscriptionsObject) return;
181
+ if (!_optionalChain([event, 'access', _26 => _26.type, 'optionalAccess', _27 => _27.startsWith, 'call', _28 => _28("data.record.")])) return;
182
+ this.refresh().catch(
183
+ (err) => _optionalChain([this, 'access', _29 => _29.logger, 'access', _30 => _30.warn, 'optionalCall', _31 => _31("[webhook-auto-enqueuer] self-heal refresh failed", err)])
184
+ );
185
+ }
186
+ /** Test / admin accessor. */
187
+ snapshot() {
188
+ return this.subscriptions;
189
+ }
190
+ };
191
+ function mapActionToTrigger(action) {
192
+ switch (action) {
193
+ case "created":
194
+ return "create";
195
+ case "updated":
196
+ return "update";
197
+ case "deleted":
198
+ return "delete";
199
+ case "undeleted":
200
+ return "undelete";
201
+ default:
202
+ return null;
203
+ }
204
+ }
205
+
206
+ // src/http-sender.ts
207
+ var _crypto = require('crypto');
208
+ var DEFAULT_TIMEOUT_MS = 15e3;
209
+ var RESPONSE_BODY_CAP = 16 * 1024;
210
+ async function sendOnce(delivery, fetchImpl) {
211
+ const body = typeof delivery.payload === "string" ? delivery.payload : JSON.stringify(delivery.payload);
212
+ const headers = {
213
+ "Content-Type": "application/json",
214
+ "User-Agent": "ObjectStack-Webhooks/1.0",
215
+ "X-Objectstack-Event": delivery.eventType,
216
+ "X-Objectstack-Delivery": delivery.id,
217
+ "X-Objectstack-Attempt": String(delivery.attempts + 1),
218
+ ..._nullishCoalesce(delivery.headers, () => ( {}))
219
+ };
220
+ if (delivery.secret) {
221
+ const sig = _crypto.createHmac.call(void 0, "sha256", delivery.secret).update(body).digest("hex");
222
+ headers["X-Objectstack-Signature"] = `sha256=${sig}`;
223
+ }
224
+ const timeoutMs = _nullishCoalesce(delivery.timeoutMs, () => ( DEFAULT_TIMEOUT_MS));
225
+ const controller = new AbortController();
226
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
227
+ const start = Date.now();
228
+ try {
229
+ const res = await fetchImpl(delivery.url, {
230
+ method: _nullishCoalesce(delivery.method, () => ( "POST")),
231
+ headers,
232
+ body,
233
+ signal: controller.signal
234
+ });
235
+ clearTimeout(timer);
236
+ const responseText = await safeReadBody(res);
237
+ const durationMs = Date.now() - start;
238
+ if (res.ok) {
239
+ return { success: true, httpStatus: res.status, responseBody: responseText, durationMs };
240
+ }
241
+ const retriable = res.status === 408 || res.status === 429 || res.status >= 500;
242
+ return {
243
+ success: false,
244
+ retriable,
245
+ httpStatus: res.status,
246
+ responseBody: responseText,
247
+ error: `HTTP ${res.status}`,
248
+ durationMs
249
+ };
250
+ } catch (err) {
251
+ clearTimeout(timer);
252
+ const durationMs = Date.now() - start;
253
+ const e = err;
254
+ const error = _optionalChain([e, 'optionalAccess', _32 => _32.name]) === "AbortError" ? `timeout after ${timeoutMs}ms` : _nullishCoalesce(_optionalChain([e, 'optionalAccess', _33 => _33.message]), () => ( String(err)));
255
+ return { success: false, retriable: true, error, durationMs };
256
+ }
257
+ }
258
+ async function safeReadBody(res) {
259
+ try {
260
+ const text = await res.text();
261
+ return text.length > RESPONSE_BODY_CAP ? text.slice(0, RESPONSE_BODY_CAP) : text;
262
+ } catch (e3) {
263
+ return void 0;
264
+ }
265
+ }
266
+ function nextRetryDelayMs(attemptsSoFar, rng = Math.random) {
267
+ const SCHEDULE = [1e3, 1e4, 6e4, 6e5, 36e5, 216e5, 864e5];
268
+ if (attemptsSoFar < 1 || attemptsSoFar > SCHEDULE.length) return null;
269
+ const base = SCHEDULE[attemptsSoFar - 1];
270
+ const jitter = 0.8 + rng() * 0.4;
271
+ return Math.floor(base * jitter);
272
+ }
273
+ function classifyAttempt(outcome, attemptsSoFar, now = Date.now(), rng) {
274
+ if (outcome.success) return outcome;
275
+ if (!outcome.retriable) {
276
+ return {
277
+ success: false,
278
+ httpStatus: outcome.httpStatus,
279
+ responseBody: outcome.responseBody,
280
+ error: outcome.error,
281
+ durationMs: outcome.durationMs,
282
+ dead: true
283
+ };
284
+ }
285
+ const delay = nextRetryDelayMs(attemptsSoFar + 1, rng);
286
+ if (delay === null) {
287
+ return {
288
+ success: false,
289
+ httpStatus: outcome.httpStatus,
290
+ responseBody: outcome.responseBody,
291
+ error: outcome.error,
292
+ durationMs: outcome.durationMs,
293
+ dead: true
294
+ };
295
+ }
296
+ return {
297
+ success: false,
298
+ httpStatus: outcome.httpStatus,
299
+ responseBody: outcome.responseBody,
300
+ error: outcome.error,
301
+ durationMs: outcome.durationMs,
302
+ nextRetryAt: now + delay
303
+ };
304
+ }
305
+
306
+ // src/dispatcher.ts
307
+ var WebhookDispatcher = class {
308
+ constructor(options) {
309
+ this.running = false;
310
+ const intervalMs = _nullishCoalesce(options.intervalMs, () => ( 250));
311
+ const lockTtlMs = _nullishCoalesce(options.lockTtlMs, () => ( intervalMs * 5));
312
+ this.opts = {
313
+ nodeId: options.nodeId,
314
+ cluster: options.cluster,
315
+ outbox: options.outbox,
316
+ partitionCount: _nullishCoalesce(options.partitionCount, () => ( 8)),
317
+ batchSize: _nullishCoalesce(options.batchSize, () => ( 32)),
318
+ intervalMs,
319
+ lockTtlMs,
320
+ claimTtlMs: _nullishCoalesce(options.claimTtlMs, () => ( lockTtlMs * 2)),
321
+ onAttempt: options.onAttempt,
322
+ fetchImpl: options.fetchImpl,
323
+ rng: options.rng,
324
+ logger: options.logger
325
+ };
326
+ }
327
+ /** Begin the periodic loop. Safe to call once; subsequent calls are no-ops. */
328
+ start() {
329
+ if (this.running) return;
330
+ this.running = true;
331
+ this.scheduleTick();
332
+ this.timer = setInterval(() => this.scheduleTick(), this.opts.intervalMs);
333
+ }
334
+ /** Stop the loop and wait for the in-flight tick to drain. */
335
+ async stop() {
336
+ if (!this.running) return;
337
+ this.running = false;
338
+ if (this.timer) {
339
+ clearInterval(this.timer);
340
+ this.timer = void 0;
341
+ }
342
+ if (this.inflightTick) {
343
+ try {
344
+ await this.inflightTick;
345
+ } catch (e4) {
346
+ }
347
+ }
348
+ }
349
+ /**
350
+ * Run one full tick (all partitions, single attempt each). Exposed for
351
+ * deterministic tests that want to step the dispatcher manually.
352
+ */
353
+ async tick() {
354
+ await this.runTick();
355
+ }
356
+ scheduleTick() {
357
+ if (this.inflightTick) return;
358
+ this.inflightTick = this.runTick().catch((err) => {
359
+ _optionalChain([this, 'access', _34 => _34.opts, 'access', _35 => _35.logger, 'optionalAccess', _36 => _36.warn, 'optionalCall', _37 => _37("webhook-dispatcher: tick failed", {
360
+ nodeId: this.opts.nodeId,
361
+ error: _nullishCoalesce(_optionalChain([err, 'optionalAccess', _38 => _38.message]), () => ( String(err)))
362
+ })]);
363
+ }).finally(() => {
364
+ this.inflightTick = void 0;
365
+ });
366
+ }
367
+ async runTick() {
368
+ const partitionCount = this.opts.partitionCount;
369
+ const offset = stableNodeOffset(this.opts.nodeId, partitionCount);
370
+ for (let step = 0; step < partitionCount; step++) {
371
+ const i = (offset + step) % partitionCount;
372
+ await this.runPartition(i);
373
+ }
374
+ }
375
+ async runPartition(index) {
376
+ const key = `webhook.dispatcher.partition.${index}`;
377
+ const handle = await this.opts.cluster.lock.acquire(key, {
378
+ ttlMs: this.opts.lockTtlMs,
379
+ // waitMs=0 → fail-fast; we'll try this partition again next tick.
380
+ waitMs: 0
381
+ });
382
+ if (!handle) return;
383
+ try {
384
+ const claimed = await this.opts.outbox.claim({
385
+ nodeId: this.opts.nodeId,
386
+ limit: this.opts.batchSize,
387
+ partition: { index, count: this.opts.partitionCount },
388
+ claimTtlMs: this.opts.claimTtlMs
389
+ });
390
+ if (claimed.length === 0) return;
391
+ await handle.renew(this.opts.lockTtlMs);
392
+ for (const row of claimed) {
393
+ if (!handle.isHeld()) break;
394
+ await this.processRow(row);
395
+ }
396
+ } finally {
397
+ await handle.release();
398
+ }
399
+ }
400
+ async processRow(row) {
401
+ const fetchImpl = _nullishCoalesce(this.opts.fetchImpl, () => ( globalThis.fetch));
402
+ if (!fetchImpl) {
403
+ _optionalChain([this, 'access', _39 => _39.opts, 'access', _40 => _40.logger, 'optionalAccess', _41 => _41.warn, 'optionalCall', _42 => _42("webhook-dispatcher: no fetch impl available", {
404
+ rowId: row.id
405
+ })]);
406
+ await this.opts.outbox.ack(row.id, {
407
+ success: false,
408
+ error: "no fetch implementation",
409
+ durationMs: 0,
410
+ dead: true
411
+ });
412
+ return;
413
+ }
414
+ const outcome = await sendOnce(row, fetchImpl);
415
+ const result = classifyAttempt(outcome, row.attempts, Date.now(), this.opts.rng);
416
+ await this.opts.outbox.ack(row.id, result);
417
+ _optionalChain([this, 'access', _43 => _43.opts, 'access', _44 => _44.onAttempt, 'optionalCall', _45 => _45(row, result.success)]);
418
+ }
419
+ };
420
+ function stableNodeOffset(nodeId, partitionCount) {
421
+ let h = 0;
422
+ for (let i = 0; i < nodeId.length; i++) {
423
+ h = h * 31 + nodeId.charCodeAt(i) | 0;
424
+ }
425
+ return Math.abs(h) % partitionCount;
426
+ }
427
+
428
+ // src/memory-outbox.ts
429
+
430
+ var MemoryWebhookOutbox = class {
431
+ constructor() {
432
+ this.rows = /* @__PURE__ */ new Map();
433
+ /** Dedup index keyed by `${eventId}::${webhookId}` -> row id. */
434
+ this.dedup = /* @__PURE__ */ new Map();
435
+ }
436
+ async enqueue(input) {
437
+ const dedupKey = `${input.eventId}::${input.webhookId}`;
438
+ const existing = this.dedup.get(dedupKey);
439
+ if (existing) return existing;
440
+ const id = _crypto.randomUUID.call(void 0, );
441
+ const now = Date.now();
442
+ const row = {
443
+ id,
444
+ webhookId: input.webhookId,
445
+ eventId: input.eventId,
446
+ eventType: input.eventType,
447
+ url: input.url,
448
+ method: _nullishCoalesce(input.method, () => ( "POST")),
449
+ headers: input.headers,
450
+ secret: input.secret,
451
+ timeoutMs: input.timeoutMs,
452
+ payload: input.payload,
453
+ status: "pending",
454
+ attempts: 0,
455
+ createdAt: now,
456
+ updatedAt: now
457
+ };
458
+ this.rows.set(id, row);
459
+ this.dedup.set(dedupKey, id);
460
+ return id;
461
+ }
462
+ async claim(opts) {
463
+ const now = _nullishCoalesce(opts.now, () => ( Date.now()));
464
+ const claimed = [];
465
+ for (const row of this.rows.values()) {
466
+ if (row.status === "in_flight" && row.claimedAt !== void 0 && now - row.claimedAt > opts.claimTtlMs) {
467
+ row.status = "pending";
468
+ row.claimedBy = void 0;
469
+ row.claimedAt = void 0;
470
+ row.updatedAt = now;
471
+ }
472
+ }
473
+ for (const row of this.rows.values()) {
474
+ if (claimed.length >= opts.limit) break;
475
+ if (row.status !== "pending") continue;
476
+ if (row.nextRetryAt !== void 0 && row.nextRetryAt > now) continue;
477
+ if (opts.partition) {
478
+ const p = _chunkFA66GQEOcjs.hashPartition.call(void 0, row.webhookId, opts.partition.count);
479
+ if (p !== opts.partition.index) continue;
480
+ }
481
+ row.status = "in_flight";
482
+ row.claimedBy = opts.nodeId;
483
+ row.claimedAt = now;
484
+ row.updatedAt = now;
485
+ claimed.push({ ...row });
486
+ }
487
+ return claimed;
488
+ }
489
+ async ack(id, result) {
490
+ const row = this.rows.get(id);
491
+ if (!row) return;
492
+ const now = Date.now();
493
+ row.attempts += 1;
494
+ row.lastAttemptedAt = now;
495
+ row.updatedAt = now;
496
+ row.claimedBy = void 0;
497
+ row.claimedAt = void 0;
498
+ row.responseCode = result.httpStatus;
499
+ row.responseBody = result.responseBody;
500
+ let status;
501
+ if (result.success) {
502
+ status = "success";
503
+ row.nextRetryAt = void 0;
504
+ row.error = void 0;
505
+ } else if (result.dead) {
506
+ status = "dead";
507
+ row.error = result.error;
508
+ row.nextRetryAt = void 0;
509
+ } else {
510
+ status = "pending";
511
+ row.error = result.error;
512
+ row.nextRetryAt = result.nextRetryAt;
513
+ }
514
+ row.status = status;
515
+ }
516
+ async list(filter) {
517
+ const all = Array.from(this.rows.values()).map((r) => ({ ...r }));
518
+ return _optionalChain([filter, 'optionalAccess', _46 => _46.status]) ? all.filter((r) => r.status === filter.status) : all;
519
+ }
520
+ async redeliver(id) {
521
+ const row = this.rows.get(id);
522
+ if (!row) {
523
+ throw new (0, _chunkFA66GQEOcjs.RedeliverError)(
524
+ `Delivery row '${id}' not found`,
525
+ "not_found"
526
+ );
527
+ }
528
+ if (row.status !== "success" && row.status !== "failed" && row.status !== "dead") {
529
+ throw new (0, _chunkFA66GQEOcjs.RedeliverError)(
530
+ `Delivery row '${id}' is '${row.status}', expected one of: success, failed, dead`,
531
+ "not_eligible"
532
+ );
533
+ }
534
+ const now = Date.now();
535
+ row.status = "pending";
536
+ row.attempts = 0;
537
+ row.claimedBy = void 0;
538
+ row.claimedAt = void 0;
539
+ row.nextRetryAt = void 0;
540
+ row.error = void 0;
541
+ row.responseCode = void 0;
542
+ row.responseBody = void 0;
543
+ row.updatedAt = now;
544
+ return { ...row };
545
+ }
546
+ };
547
+
548
+ // src/retention.ts
549
+ var DEFAULTS = {
550
+ successTtlMs: 7 * 24 * 60 * 60 * 1e3,
551
+ deadTtlMs: 30 * 24 * 60 * 60 * 1e3,
552
+ sweepIntervalMs: 60 * 60 * 1e3
553
+ };
554
+ var DeliveryRetentionSweeper = class {
555
+ constructor(engine, opts = {}) {
556
+ this.engine = engine;
557
+ this.running = false;
558
+ this.objectName = _nullishCoalesce(opts.objectName, () => ( _chunkMJZGD37Scjs.SYS_WEBHOOK_DELIVERY));
559
+ this.successTtlMs = _nullishCoalesce(opts.successTtlMs, () => ( DEFAULTS.successTtlMs));
560
+ this.deadTtlMs = _nullishCoalesce(opts.deadTtlMs, () => ( DEFAULTS.deadTtlMs));
561
+ this.sweepIntervalMs = _nullishCoalesce(opts.sweepIntervalMs, () => ( DEFAULTS.sweepIntervalMs));
562
+ this.logger = _nullishCoalesce(opts.logger, () => ( {}));
563
+ }
564
+ start() {
565
+ if (this.running) return;
566
+ this.running = true;
567
+ this.timer = setInterval(() => {
568
+ this.sweep().catch(
569
+ (err) => _optionalChain([this, 'access', _47 => _47.logger, 'access', _48 => _48.warn, 'optionalCall', _49 => _49("[webhook-retention] sweep failed", err)])
570
+ );
571
+ }, this.sweepIntervalMs);
572
+ _optionalChain([this, 'access', _50 => _50.timer, 'access', _51 => _51.unref, 'optionalCall', _52 => _52()]);
573
+ }
574
+ stop() {
575
+ if (!this.running) return;
576
+ this.running = false;
577
+ if (this.timer) clearInterval(this.timer);
578
+ this.timer = void 0;
579
+ }
580
+ /** Run one sweep immediately. Returns the number of rows deleted. */
581
+ async sweep(now = Date.now()) {
582
+ let successDeleted = 0;
583
+ let deadDeleted = 0;
584
+ if (this.successTtlMs > 0) {
585
+ try {
586
+ const res = await this.engine.delete(this.objectName, {
587
+ where: {
588
+ status: "success",
589
+ updated_at: { $lt: now - this.successTtlMs }
590
+ }
591
+ });
592
+ successDeleted = _nullishCoalesce(_optionalChain([res, 'optionalAccess', _53 => _53.affected]), () => ( 0));
593
+ } catch (err) {
594
+ _optionalChain([this, 'access', _54 => _54.logger, 'access', _55 => _55.warn, 'optionalCall', _56 => _56("[webhook-retention] success sweep failed", err)]);
595
+ }
596
+ }
597
+ if (this.deadTtlMs > 0) {
598
+ try {
599
+ const res = await this.engine.delete(this.objectName, {
600
+ where: {
601
+ status: "dead",
602
+ updated_at: { $lt: now - this.deadTtlMs }
603
+ }
604
+ });
605
+ deadDeleted = _nullishCoalesce(_optionalChain([res, 'optionalAccess', _57 => _57.affected]), () => ( 0));
606
+ } catch (err) {
607
+ _optionalChain([this, 'access', _58 => _58.logger, 'access', _59 => _59.warn, 'optionalCall', _60 => _60("[webhook-retention] dead sweep failed", err)]);
608
+ }
609
+ }
610
+ if (successDeleted + deadDeleted > 0) {
611
+ _optionalChain([this, 'access', _61 => _61.logger, 'access', _62 => _62.info, 'optionalCall', _63 => _63("[webhook-retention] sweep complete", {
612
+ success: successDeleted,
613
+ dead: deadDeleted
614
+ })]);
615
+ }
616
+ return { success: successDeleted, dead: deadDeleted };
617
+ }
618
+ };
619
+
620
+ // src/webhook-outbox-plugin.ts
621
+ var WebhookOutboxPlugin = class {
622
+ constructor(options = {}) {
623
+ this.options = options;
624
+ this.name = "com.objectstack.plugin-webhook-outbox";
625
+ this.version = "1.1.0";
626
+ this.type = "standard";
627
+ this.dependencies = ["com.objectstack.service.cluster"];
628
+ }
629
+ async init(ctx) {
630
+ const cluster = ctx.getService("cluster");
631
+ if (!cluster) {
632
+ throw new Error(
633
+ 'WebhookOutboxPlugin: required service "cluster" not found \u2014 register ClusterServicePlugin first'
634
+ );
635
+ }
636
+ const manifest = ctx.getService("manifest");
637
+ if (manifest && typeof manifest.register === "function") {
638
+ manifest.register({
639
+ id: "com.objectstack.plugin-webhook-outbox.schema",
640
+ namespace: "sys",
641
+ version: this.version,
642
+ type: "plugin",
643
+ scope: "system",
644
+ name: "Webhook Outbox Schemas",
645
+ description: "Registers sys_webhook (configuration) and sys_webhook_delivery (durable outbox telemetry).",
646
+ objects: [_integration.SysWebhook, _chunkMJZGD37Scjs.SysWebhookDelivery]
647
+ });
648
+ } else {
649
+ _optionalChain([ctx, 'access', _64 => _64.logger, 'access', _65 => _65.warn, 'optionalCall', _66 => _66(
650
+ "[webhook-outbox] manifest service unavailable \u2014 sys_webhook / sys_webhook_delivery will NOT appear in REST or Studio nav. Register MetadataService before WebhookOutboxPlugin."
651
+ )]);
652
+ }
653
+ const outbox = this.resolveOutbox(ctx);
654
+ this.outboxInstance = outbox;
655
+ const nodeId = _nullishCoalesce(_nullishCoalesce(this.options.nodeId, () => ( process.env.OBJECTSTACK_NODE_ID)), () => ( `node-${Math.random().toString(36).slice(2, 10)}`));
656
+ const dispatcher = new WebhookDispatcher({
657
+ nodeId,
658
+ cluster,
659
+ outbox,
660
+ partitionCount: this.options.partitionCount,
661
+ batchSize: this.options.batchSize,
662
+ intervalMs: this.options.intervalMs,
663
+ lockTtlMs: this.options.lockTtlMs,
664
+ claimTtlMs: this.options.claimTtlMs,
665
+ fetchImpl: this.options.fetchImpl,
666
+ onAttempt: this.options.onAttempt,
667
+ rng: this.options.rng,
668
+ logger: ctx.logger
669
+ });
670
+ this.dispatcher = dispatcher;
671
+ ctx.registerService("webhook.outbox", outbox);
672
+ ctx.registerService("webhook.dispatcher", dispatcher);
673
+ if (this.options.autoStart !== false) {
674
+ dispatcher.start();
675
+ }
676
+ const usingMemoryOutbox = outbox instanceof MemoryWebhookOutbox;
677
+ if (usingMemoryOutbox && process.env.NODE_ENV === "production") {
678
+ _optionalChain([ctx, 'access', _67 => _67.logger, 'access', _68 => _68.warn, 'optionalCall', _69 => _69(
679
+ "[webhook-outbox] MemoryWebhookOutbox in production \u2014 webhook deliveries WILL be lost on process exit. Ensure ObjectQL is registered before WebhookOutboxPlugin so the SQL outbox can auto-select."
680
+ )]);
681
+ }
682
+ const autoEnqueueOpt = _nullishCoalesce(this.options.autoEnqueue, () => ( true));
683
+ const retentionOpt = _nullishCoalesce(this.options.retention, () => ( true));
684
+ const needsReadyHook = autoEnqueueOpt !== false || retentionOpt !== false;
685
+ if (needsReadyHook && typeof ctx.hook === "function") {
686
+ ctx.hook("kernel:ready", async () => {
687
+ await this.bootAutoEnqueue(ctx, autoEnqueueOpt);
688
+ this.bootRetention(ctx, retentionOpt);
689
+ });
690
+ }
691
+ if (typeof ctx.hook === "function") {
692
+ ctx.hook("kernel:ready", () => {
693
+ this.registerAdminRoutes(ctx);
694
+ });
695
+ }
696
+ _optionalChain([ctx, 'access', _70 => _70.logger, 'access', _71 => _71.info, 'optionalCall', _72 => _72("[webhook-outbox] initialised", {
697
+ nodeId,
698
+ partitions: _nullishCoalesce(this.options.partitionCount, () => ( 8)),
699
+ interval: _nullishCoalesce(this.options.intervalMs, () => ( 250)),
700
+ autoEnqueue: autoEnqueueOpt !== false,
701
+ retention: retentionOpt !== false
702
+ })]);
703
+ }
704
+ async dispose() {
705
+ await _optionalChain([this, 'access', _73 => _73.autoEnqueuer, 'optionalAccess', _74 => _74.stop, 'call', _75 => _75()]);
706
+ _optionalChain([this, 'access', _76 => _76.retention, 'optionalAccess', _77 => _77.stop, 'call', _78 => _78()]);
707
+ await _optionalChain([this, 'access', _79 => _79.dispatcher, 'optionalAccess', _80 => _80.stop, 'call', _81 => _81()]);
708
+ }
709
+ resolveOutbox(ctx) {
710
+ const opt = this.options.outbox;
711
+ if (opt) {
712
+ return typeof opt === "function" ? opt(ctx) : opt;
713
+ }
714
+ const engine = this.tryGetService(ctx, ["objectql", "data"]);
715
+ if (engine) {
716
+ const partitionCount = _nullishCoalesce(this.options.partitionCount, () => ( 8));
717
+ const sql = new (0, _chunkFA66GQEOcjs.SqlWebhookOutbox)(engine, { partitionCount });
718
+ _optionalChain([ctx, 'access', _82 => _82.logger, 'access', _83 => _83.info, 'optionalCall', _84 => _84(
719
+ "[webhook-outbox] auto-selected SqlWebhookOutbox (objectql engine detected)",
720
+ { partitionCount }
721
+ )]);
722
+ return sql;
723
+ }
724
+ _optionalChain([ctx, 'access', _85 => _85.logger, 'access', _86 => _86.warn, 'optionalCall', _87 => _87(
725
+ "[webhook-outbox] no IDataEngine available \u2014 falling back to MemoryWebhookOutbox. Deliveries will NOT survive process restart and the redeliver REST endpoint will not see rows written through ObjectQL."
726
+ )]);
727
+ return new MemoryWebhookOutbox();
728
+ }
729
+ async bootAutoEnqueue(ctx, opt) {
730
+ if (opt === false) return;
731
+ const engine = this.tryGetService(ctx, ["objectql", "data"]);
732
+ const realtime = this.tryGetService(ctx, ["realtime"]);
733
+ if (!engine || !realtime) {
734
+ _optionalChain([ctx, 'access', _88 => _88.logger, 'access', _89 => _89.warn, 'optionalCall', _90 => _90(
735
+ "[webhook-auto-enqueuer] disabled \u2014 ObjectQL or Realtime service not available",
736
+ { hasEngine: !!engine, hasRealtime: !!realtime }
737
+ )]);
738
+ return;
739
+ }
740
+ if (!this.outboxInstance) return;
741
+ const enqOpts = typeof opt === "object" ? opt : {};
742
+ this.autoEnqueuer = new AutoEnqueuer(
743
+ engine,
744
+ realtime,
745
+ this.outboxInstance,
746
+ { ...enqOpts, logger: ctx.logger }
747
+ );
748
+ await this.autoEnqueuer.start();
749
+ ctx.registerService("webhook.autoEnqueuer", this.autoEnqueuer);
750
+ _optionalChain([ctx, 'access', _91 => _91.logger, 'access', _92 => _92.info, 'optionalCall', _93 => _93("[webhook-auto-enqueuer] started")]);
751
+ }
752
+ bootRetention(ctx, opt) {
753
+ if (opt === false) return;
754
+ if (this.outboxInstance instanceof MemoryWebhookOutbox) return;
755
+ const engine = this.tryGetService(ctx, ["objectql", "data"]);
756
+ if (!engine) {
757
+ _optionalChain([ctx, 'access', _94 => _94.logger, 'access', _95 => _95.warn, 'optionalCall', _96 => _96(
758
+ "[webhook-retention] disabled \u2014 ObjectQL service not available"
759
+ )]);
760
+ return;
761
+ }
762
+ const retOpts = typeof opt === "object" ? opt : {};
763
+ this.retention = new DeliveryRetentionSweeper(engine, {
764
+ ...retOpts,
765
+ logger: ctx.logger
766
+ });
767
+ this.retention.start();
768
+ ctx.registerService("webhook.retention", this.retention);
769
+ _optionalChain([ctx, 'access', _97 => _97.logger, 'access', _98 => _98.info, 'optionalCall', _99 => _99("[webhook-retention] sweeper started")]);
770
+ }
771
+ tryGetService(ctx, names) {
772
+ for (const n of names) {
773
+ try {
774
+ const svc = ctx.getService(n);
775
+ if (svc) return svc;
776
+ } catch (e5) {
777
+ }
778
+ }
779
+ return void 0;
780
+ }
781
+ /**
782
+ * Mount POST /api/v1/webhooks/redeliver on the host Hono app, if one
783
+ * is available. Silently no-ops in environments without an HTTP
784
+ * server (MSW, edge tests, pure library use). Auth is delegated to
785
+ * the better-auth session cookie — every authenticated user counts.
786
+ */
787
+ registerAdminRoutes(ctx) {
788
+ const http = this.tryGetService(ctx, ["http-server"]);
789
+ if (!http || typeof http.getRawApp !== "function") {
790
+ _optionalChain([ctx, 'access', _100 => _100.logger, 'access', _101 => _101.debug, 'optionalCall', _102 => _102(
791
+ "[webhook-outbox] HTTP server not available; redeliver REST endpoint not mounted"
792
+ )]);
793
+ return;
794
+ }
795
+ const rawApp = http.getRawApp();
796
+ const outbox = this.outboxInstance;
797
+ if (!rawApp || !outbox) return;
798
+ rawApp.post("/api/v1/webhooks/redeliver", async (c) => {
799
+ const userId = await this.resolveSessionUserId(ctx, c);
800
+ if (!userId) {
801
+ return c.json(
802
+ {
803
+ success: false,
804
+ error: "unauthenticated",
805
+ message: "Sign in to redeliver webhook deliveries."
806
+ },
807
+ 401
808
+ );
809
+ }
810
+ let body;
811
+ try {
812
+ body = await c.req.json();
813
+ } catch (e6) {
814
+ return c.json(
815
+ {
816
+ success: false,
817
+ error: "invalid_body",
818
+ message: "Request body must be JSON."
819
+ },
820
+ 400
821
+ );
822
+ }
823
+ const deliveryId = typeof _optionalChain([body, 'optionalAccess', _103 => _103.deliveryId]) === "string" ? body.deliveryId.trim() : "";
824
+ if (!deliveryId) {
825
+ return c.json(
826
+ {
827
+ success: false,
828
+ error: "missing_delivery_id",
829
+ message: "Body must include `deliveryId: string`."
830
+ },
831
+ 400
832
+ );
833
+ }
834
+ try {
835
+ const row = await outbox.redeliver(deliveryId);
836
+ _optionalChain([ctx, 'access', _104 => _104.logger, 'access', _105 => _105.info, 'optionalCall', _106 => _106("[webhook-outbox] redelivered", {
837
+ deliveryId,
838
+ requestedBy: userId
839
+ })]);
840
+ return c.json({ success: true, data: { id: row.id, status: row.status } });
841
+ } catch (err) {
842
+ const code = _optionalChain([err, 'optionalAccess', _107 => _107.code]);
843
+ if (code === "not_found") {
844
+ return c.json(
845
+ { success: false, error: "not_found", message: err.message },
846
+ 404
847
+ );
848
+ }
849
+ if (code === "not_eligible") {
850
+ return c.json(
851
+ { success: false, error: "not_eligible", message: err.message },
852
+ 409
853
+ );
854
+ }
855
+ _optionalChain([ctx, 'access', _108 => _108.logger, 'access', _109 => _109.error, 'optionalCall', _110 => _110(
856
+ "[webhook-outbox] redeliver failed",
857
+ err
858
+ )]);
859
+ return c.json(
860
+ {
861
+ success: false,
862
+ error: "internal_error",
863
+ message: _nullishCoalesce(_optionalChain([err, 'optionalAccess', _111 => _111.message]), () => ( String(err)))
864
+ },
865
+ 500
866
+ );
867
+ }
868
+ });
869
+ _optionalChain([ctx, 'access', _112 => _112.logger, 'access', _113 => _113.info, 'optionalCall', _114 => _114(
870
+ "[webhook-outbox] redeliver endpoint mounted at POST /api/v1/webhooks/redeliver"
871
+ )]);
872
+ }
873
+ /**
874
+ * Resolve the requesting user's id from a better-auth session cookie.
875
+ * Returns `undefined` for anonymous callers — the caller decides
876
+ * whether that's a 401.
877
+ */
878
+ async resolveSessionUserId(ctx, c) {
879
+ try {
880
+ const authService = this.tryGetService(ctx, ["auth"]);
881
+ if (!authService) return void 0;
882
+ let api = authService.api;
883
+ if (!api && typeof authService.getApi === "function") {
884
+ api = await authService.getApi();
885
+ }
886
+ if (!_optionalChain([api, 'optionalAccess', _115 => _115.getSession])) return void 0;
887
+ const session = await api.getSession({ headers: c.req.raw.headers });
888
+ const uid = _optionalChain([session, 'optionalAccess', _116 => _116.user, 'optionalAccess', _117 => _117.id]);
889
+ return typeof uid === "string" && uid.length > 0 ? uid : void 0;
890
+ } catch (e7) {
891
+ return void 0;
892
+ }
893
+ }
894
+ };
895
+
896
+
897
+
898
+
899
+
900
+
901
+
902
+
903
+
904
+
905
+
906
+
907
+ exports.AutoEnqueuer = AutoEnqueuer; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.DeliveryRetentionSweeper = DeliveryRetentionSweeper; exports.MemoryWebhookOutbox = MemoryWebhookOutbox; exports.RedeliverError = _chunkFA66GQEOcjs.RedeliverError; exports.WebhookDispatcher = WebhookDispatcher; exports.WebhookOutboxPlugin = WebhookOutboxPlugin; exports.classifyAttempt = classifyAttempt; exports.hashPartition = _chunkFA66GQEOcjs.hashPartition; exports.nextRetryDelayMs = nextRetryDelayMs; exports.sendOnce = sendOnce;
908
+ //# sourceMappingURL=index.cjs.map