@jini-ai/integrations 0.4.1 → 0.4.3

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 (146) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api-connections/access-token.d.ts +9 -0
  3. package/dist/api-connections/access-token.js +92 -0
  4. package/dist/api-connections/account-actions.d.ts +40 -0
  5. package/dist/api-connections/account-actions.js +110 -0
  6. package/dist/api-connections/attempt-state.d.ts +28 -0
  7. package/dist/api-connections/attempt-state.js +73 -0
  8. package/dist/api-connections/authorization.d.ts +45 -0
  9. package/dist/api-connections/authorization.js +120 -0
  10. package/dist/api-connections/deps.d.ts +41 -0
  11. package/dist/api-connections/deps.js +13 -0
  12. package/dist/api-connections/descriptor.d.ts +6 -0
  13. package/dist/api-connections/descriptor.js +111 -0
  14. package/dist/api-connections/errors.d.ts +23 -0
  15. package/dist/api-connections/errors.js +24 -0
  16. package/dist/api-connections/finish-authorization.d.ts +24 -0
  17. package/dist/api-connections/finish-authorization.js +117 -0
  18. package/dist/api-connections/index.d.ts +18 -0
  19. package/dist/api-connections/index.js +10 -0
  20. package/dist/api-connections/install-credential.d.ts +19 -0
  21. package/dist/api-connections/install-credential.js +12 -0
  22. package/dist/api-connections/keys.d.ts +27 -0
  23. package/dist/api-connections/keys.js +22 -0
  24. package/dist/api-connections/ports.d.ts +73 -0
  25. package/dist/api-connections/ports.js +2 -0
  26. package/dist/api-connections/records.d.ts +27 -0
  27. package/dist/api-connections/records.js +52 -0
  28. package/dist/api-connections/request-checks.d.ts +18 -0
  29. package/dist/api-connections/request-checks.js +67 -0
  30. package/dist/api-connections/service.d.ts +25 -0
  31. package/dist/api-connections/service.js +26 -0
  32. package/dist/api-connections/status.d.ts +28 -0
  33. package/dist/api-connections/status.js +36 -0
  34. package/dist/api-connections/token-store/errors.d.ts +20 -0
  35. package/dist/api-connections/token-store/errors.js +38 -0
  36. package/dist/api-connections/token-store/index.d.ts +6 -0
  37. package/dist/api-connections/token-store/index.js +6 -0
  38. package/dist/api-connections/token-store/record.d.ts +69 -0
  39. package/dist/api-connections/token-store/record.js +97 -0
  40. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  41. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  42. package/dist/api-connections/types.d.ts +101 -0
  43. package/dist/api-connections/types.js +9 -0
  44. package/dist/credentialed-http/auth-schemes.js +8 -4
  45. package/dist/credentialed-http/credentialed-request.js +47 -77
  46. package/dist/credentialed-http/response-redaction.d.ts +5 -0
  47. package/dist/credentialed-http/response-redaction.js +62 -0
  48. package/dist/media-providers/catalog.d.ts +3 -1
  49. package/dist/media-providers/catalog.js +3 -1
  50. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  51. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  52. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  53. package/dist/media-providers/dispatch/context.js +10 -2
  54. package/dist/media-providers/dispatch/credentials.d.ts +1 -1
  55. package/dist/media-providers/dispatch/credentials.js +3 -3
  56. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  57. package/dist/media-providers/dispatch/engine.js +102 -109
  58. package/dist/media-providers/dispatch/index.d.ts +4 -2
  59. package/dist/media-providers/dispatch/index.js +3 -1
  60. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  61. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  62. package/dist/media-providers/dispatch/node.d.ts +13 -0
  63. package/dist/media-providers/dispatch/node.js +24 -0
  64. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  66. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  67. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  68. package/dist/media-providers/dispatch/outbound.js +27 -26
  69. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  71. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  75. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  77. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  79. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  80. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  82. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  84. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  86. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  87. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  88. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  89. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  90. package/dist/media-providers/dispatch/sqlite-async-operation-store.d.ts +35 -1
  91. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +13 -32
  92. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  93. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  94. package/dist/media-providers/dispatch/types.d.ts +76 -2
  95. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  96. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  97. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  98. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  99. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  100. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  101. package/dist/media-providers/policy.js +25 -17
  102. package/dist/media-providers/providers.d.ts +39 -0
  103. package/dist/media-providers/providers.js +50 -18
  104. package/dist/media-providers/sqlite-driver.adapter.d.ts +4 -0
  105. package/dist/media-providers/sqlite-driver.adapter.js +5 -0
  106. package/dist/media-providers/sqlite-task-store.d.ts +50 -2
  107. package/dist/media-providers/sqlite-task-store.js +20 -84
  108. package/dist/media-providers/staging.js +77 -58
  109. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  110. package/dist/media-providers/task-lifecycle.js +124 -0
  111. package/dist/media-providers/task-store.js +8 -86
  112. package/dist/media-providers/ui-defaults.d.ts +10 -0
  113. package/dist/media-providers/ui-defaults.js +167 -0
  114. package/dist/media-providers/video-request.js +112 -90
  115. package/dist/webhooks/delivery.d.ts +14 -0
  116. package/dist/webhooks/delivery.js +41 -10
  117. package/dist/webhooks/index.d.ts +1 -0
  118. package/dist/webhooks/index.js +1 -0
  119. package/dist/webhooks/ports.d.ts +23 -0
  120. package/dist/webhooks/subscriptions.d.ts +1 -1
  121. package/dist/webhooks/subscriptions.js +5 -1
  122. package/dist/webhooks/worker.d.ts +83 -0
  123. package/dist/webhooks/worker.js +105 -0
  124. package/package.json +35 -7
  125. package/dist/composio/bounded-data.d.ts +0 -36
  126. package/dist/composio/bounded-data.js +0 -181
  127. package/dist/composio/catalog.d.ts +0 -147
  128. package/dist/composio/catalog.js +0 -126
  129. package/dist/composio/composio-config.d.ts +0 -42
  130. package/dist/composio/composio-config.js +0 -145
  131. package/dist/composio/composio-descriptions.d.ts +0 -16
  132. package/dist/composio/composio-descriptions.js +0 -766
  133. package/dist/composio/composio.d.ts +0 -364
  134. package/dist/composio/composio.js +0 -1902
  135. package/dist/composio/errors.d.ts +0 -15
  136. package/dist/composio/errors.js +0 -16
  137. package/dist/composio/file-lock.d.ts +0 -13
  138. package/dist/composio/file-lock.js +0 -92
  139. package/dist/composio/index.d.ts +0 -18
  140. package/dist/composio/index.js +0 -7
  141. package/dist/composio/json-schema.d.ts +0 -93
  142. package/dist/composio/json-schema.js +0 -498
  143. package/dist/composio/output-protection.d.ts +0 -32
  144. package/dist/composio/output-protection.js +0 -105
  145. package/dist/composio/service.d.ts +0 -181
  146. package/dist/composio/service.js +0 -758
@@ -95,11 +95,13 @@ function mergeExtraBody(body, cap, passthrough) {
95
95
  body[def.name] = def.default;
96
96
  }
97
97
  if (passthrough && cap.allowedPassthroughParameters?.length) {
98
- const allow = new Set(cap.allowedPassthroughParameters);
99
- for (const [k, v] of Object.entries(passthrough)) {
100
- if (allow.has(k) && v !== undefined)
101
- body[k] = v;
102
- }
98
+ applyAllowedPassthrough(body, new Set(cap.allowedPassthroughParameters), passthrough);
99
+ }
100
+ }
101
+ function applyAllowedPassthrough(body, allow, passthrough) {
102
+ for (const [k, v] of Object.entries(passthrough)) {
103
+ if (allow.has(k) && v !== undefined)
104
+ body[k] = v;
103
105
  }
104
106
  }
105
107
  /** Builds the seedance multimodal content array (text + reference images). */
@@ -115,105 +117,125 @@ function buildSeedanceContent(input) {
115
117
  }
116
118
  return content;
117
119
  }
120
+ /** `generate_audio` (only a real boolean) then `seed` (only a real number), in that wire order. */
121
+ function audioAndSeed(input) {
122
+ return {
123
+ ...(typeof input.generateAudio === 'boolean' ? { generate_audio: input.generateAudio } : {}),
124
+ ...seedField(input),
125
+ };
126
+ }
127
+ function seedField(input) {
128
+ return typeof input.seed === 'number' ? { seed: input.seed } : {};
129
+ }
130
+ function buildSeedanceBody({ input, wireModel, seconds }) {
131
+ return {
132
+ model: wireModel,
133
+ prompt: input.prompt,
134
+ duration: seconds,
135
+ content: buildSeedanceContent(input),
136
+ resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }),
137
+ ...(input.aspectRatio ? { ratio: input.aspectRatio } : {}),
138
+ ...audioAndSeed(input),
139
+ };
140
+ }
141
+ function buildWanBody({ input, wireModel, seconds, referenceUrl }) {
142
+ return {
143
+ model: wireModel,
144
+ input: {
145
+ prompt: input.prompt,
146
+ ...(referenceUrl ? { media: [{ type: 'first_frame', url: referenceUrl }] } : {}),
147
+ },
148
+ parameters: {
149
+ resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }).toUpperCase(),
150
+ duration: seconds,
151
+ prompt_extend: true,
152
+ watermark: false,
153
+ ...(input.aspectRatio ? { aspect_ratio: input.aspectRatio } : {}),
154
+ ...seedField(input),
155
+ },
156
+ };
157
+ }
158
+ function buildVeoBody({ input, wireModel, seconds }) {
159
+ return {
160
+ model: wireModel,
161
+ prompt: input.prompt,
162
+ seconds,
163
+ size: snapVeoSize({ size: input.size }),
164
+ ...audioAndSeed(input),
165
+ };
166
+ }
167
+ function buildGenericBody({ cap, input, wireModel, seconds, referenceUrl }) {
168
+ const genericSize = snapSizeToSupported({ size: input.size, supported: cap.supportedSizes });
169
+ return {
170
+ model: wireModel,
171
+ prompt: input.prompt,
172
+ seconds: String(seconds),
173
+ ...(genericSize ? { size: genericSize } : {}),
174
+ ...(input.resolution ? { resolution: input.resolution } : {}),
175
+ ...(referenceUrl ? { input_reference: referenceUrl } : {}),
176
+ ...audioAndSeed(input),
177
+ };
178
+ }
179
+ const FAMILY_BODY_BUILDERS = {
180
+ seedance: buildSeedanceBody,
181
+ wan: buildWanBody,
182
+ veo: buildVeoBody,
183
+ generic: buildGenericBody,
184
+ };
185
+ /**
186
+ * An unrecognized `cap.family` (untyped host config) gets the generic body,
187
+ * as the original if/else chain's final `else` did. `Object.hasOwn` keeps a
188
+ * prototype key such as `"toString"` from resolving to a non-builder.
189
+ */
190
+ function bodyBuilderFor(family) {
191
+ return Object.hasOwn(FAMILY_BODY_BUILDERS, family) ? FAMILY_BODY_BUILDERS[family] : buildGenericBody;
192
+ }
118
193
  /**
119
194
  * Builds the upstream video request body for a model. Pure: no fetch, no
120
195
  * auth. Caller: `POST \`${baseUrl}${pathSuffix}\`` with auth headers +
121
196
  * `JSON.stringify(body)`.
122
197
  */
123
198
  export function buildVideoRequest({ cap, input }) {
124
- const hasReference = Boolean(input.imageRef?.dataUrl);
125
- const wireModel = resolveWireModel({ cap: cap, hasReference: hasReference });
126
- const family = deriveVideoFamily({ wireModel: wireModel }, { cap: cap });
127
- const seconds = snapDuration({ cap: cap, requested: input.durationSeconds });
128
- let body;
129
- if (family === 'seedance') {
130
- body = {
131
- model: wireModel,
132
- prompt: input.prompt,
133
- duration: seconds,
134
- content: buildSeedanceContent(input),
135
- resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }),
136
- };
137
- if (input.aspectRatio)
138
- body.ratio = input.aspectRatio;
139
- if (typeof input.generateAudio === 'boolean')
140
- body.generate_audio = input.generateAudio;
141
- if (typeof input.seed === 'number')
142
- body.seed = input.seed;
143
- }
144
- else if (family === 'wan') {
145
- const wanInput = { prompt: input.prompt };
146
- if (hasReference) {
147
- wanInput.media = [{ type: 'first_frame', url: input.imageRef.dataUrl }];
148
- }
149
- const parameters = {
150
- resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }).toUpperCase(),
151
- duration: seconds,
152
- prompt_extend: true,
153
- watermark: false,
154
- };
155
- if (input.aspectRatio)
156
- parameters.aspect_ratio = input.aspectRatio;
157
- if (typeof input.seed === 'number')
158
- parameters.seed = input.seed;
159
- body = { model: wireModel, input: wanInput, parameters };
160
- }
161
- else if (family === 'veo') {
162
- body = {
163
- model: wireModel,
164
- prompt: input.prompt,
165
- seconds,
166
- size: snapVeoSize({ size: input.size }),
167
- };
168
- if (typeof input.generateAudio === 'boolean')
169
- body.generate_audio = input.generateAudio;
170
- if (typeof input.seed === 'number')
171
- body.seed = input.seed;
172
- }
173
- else {
174
- body = {
175
- model: wireModel,
176
- prompt: input.prompt,
177
- seconds: String(seconds),
178
- };
179
- const genericSize = snapSizeToSupported({ size: input.size, supported: cap.supportedSizes });
180
- if (genericSize)
181
- body.size = genericSize;
182
- if (input.resolution)
183
- body.resolution = input.resolution;
184
- if (hasReference)
185
- body.input_reference = input.imageRef.dataUrl;
186
- if (typeof input.generateAudio === 'boolean')
187
- body.generate_audio = input.generateAudio;
188
- if (typeof input.seed === 'number')
189
- body.seed = input.seed;
190
- }
199
+ const referenceUrl = input.imageRef?.dataUrl;
200
+ const hasReference = Boolean(referenceUrl);
201
+ const wireModel = resolveWireModel({ cap, hasReference });
202
+ const family = deriveVideoFamily({ wireModel }, { cap });
203
+ const seconds = snapDuration({ cap, requested: input.durationSeconds });
204
+ const body = bodyBuilderFor(family)({ cap, input, wireModel, seconds, referenceUrl });
191
205
  mergeExtraBody(body, cap, input.passthrough);
192
206
  return { wireModel, family, pathSuffix: '/videos', contentType: 'application/json', body, hasReference };
193
207
  }
208
+ /** The first value that is neither `undefined` nor `null` — a `??` chain over a list. */
209
+ function firstPresent(...values) {
210
+ return values.find((v) => v !== undefined && v !== null);
211
+ }
212
+ /** `error.message` (object form), the string `error`, then `failure_reason`, then `message`. */
213
+ function responseError(d) {
214
+ const errorObj = d.error;
215
+ const fromObject = typeof errorObj === 'object' && errorObj ? errorObj.message : undefined;
216
+ const fromString = typeof errorObj === 'string' ? errorObj : undefined;
217
+ return firstPresent(fromObject, fromString, d.failure_reason, d.message);
218
+ }
219
+ function responseUrl(d, data) {
220
+ const dataArray = Array.isArray(d.data) ? d.data : undefined;
221
+ const unsignedUrls = Array.isArray(d.unsigned_urls) ? d.unsigned_urls : undefined;
222
+ return firstPresent(d.video_url, d.url, d.output_url, data?.video_url, data?.url, dataArray?.[0]?.url, unsignedUrls?.[0]);
223
+ }
194
224
  /** Best-effort normalization of an async-submit / poll response across vendor families. */
195
225
  export function normalizeVideoResponse({ raw }) {
196
226
  const d = (raw ?? {});
197
227
  const data = d.data;
198
- const dataArray = Array.isArray(d.data) ? d.data : undefined;
199
- const unsignedUrls = Array.isArray(d.unsigned_urls) ? d.unsigned_urls : undefined;
200
- const id = d.id ?? d.task_id ?? data?.id ?? data?.task_id;
201
- const status = d.status ?? data?.status;
202
- const url = d.video_url ?? d.url ?? d.output_url ?? data?.video_url ?? data?.url ?? dataArray?.[0]?.url ?? unsignedUrls?.[0];
203
- const errorObj = d.error;
204
- const error = (typeof errorObj === 'object' && errorObj ? errorObj.message : undefined) ??
205
- (typeof errorObj === 'string' ? errorObj : undefined) ??
206
- d.failure_reason ??
207
- d.message;
228
+ const fields = {
229
+ id: firstPresent(d.id, d.task_id, data?.id, data?.task_id),
230
+ status: firstPresent(d.status, data?.status),
231
+ url: responseUrl(d, data),
232
+ error: responseError(d),
233
+ };
208
234
  const result = {};
209
- if (id !== undefined && id !== null)
210
- result.id = String(id);
211
- if (status !== undefined && status !== null)
212
- result.status = String(status);
213
- if (url !== undefined && url !== null)
214
- result.url = String(url);
215
- if (error !== undefined && error !== null)
216
- result.error = String(error);
235
+ for (const key of Object.keys(fields)) {
236
+ if (fields[key] !== undefined)
237
+ result[key] = String(fields[key]);
238
+ }
217
239
  return result;
218
240
  }
219
241
  //# sourceMappingURL=video-request.js.map
@@ -61,10 +61,24 @@ export interface ProcessDueDeliveriesRequired {
61
61
  export interface ProcessDueDeliveriesOptional {
62
62
  batchSize?: number;
63
63
  hooks?: readonly WebhookBeforeDispatchHook[];
64
+ /** Socket idle budget per request. A receiver that keeps trickling bytes never trips it. */
64
65
  requestTimeoutMs?: number;
66
+ /** Whole-request budget (DNS, connect, body) per delivery; default {@link DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS}. */
67
+ requestTotalDeadlineMs?: number;
68
+ /** Claim lease; default batchSize x requestTotalDeadlineMs + {@link WEBHOOK_CLAIM_LEASE_MARGIN_MS}. */
69
+ claimLeaseMs?: number;
70
+ /** Host shutdown: aborts the in-flight request and releases the batch's unattempted claims. */
71
+ signal?: AbortSignal;
65
72
  maxAttempts?: number;
66
73
  random?: (() => number) | undefined;
67
74
  }
75
+ /**
76
+ * The idle timeout alone lets one receiver that trickles a byte at a time hold the single-flight
77
+ * worker, and every other subscription's delivery, indefinitely. 30 s bounds each delivery.
78
+ */
79
+ export declare const DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS = 30000;
80
+ /** Slack for hooks, signing and storage writes on top of the batch's request deadlines. */
81
+ export declare const WEBHOOK_CLAIM_LEASE_MARGIN_MS = 60000;
68
82
  export interface ProcessDueDeliveriesResult {
69
83
  processed: number;
70
84
  delivered: number;
@@ -91,16 +91,32 @@ async function isAlreadyEnqueued(params) {
91
91
  });
92
92
  return existing.some((delivery) => delivery.eventId === params.eventId);
93
93
  }
94
+ /**
95
+ * The idle timeout alone lets one receiver that trickles a byte at a time hold the single-flight
96
+ * worker, and every other subscription's delivery, indefinitely. 30 s bounds each delivery.
97
+ */
98
+ export const DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS = 30_000;
99
+ /** Slack for hooks, signing and storage writes on top of the batch's request deadlines. */
100
+ export const WEBHOOK_CLAIM_LEASE_MARGIN_MS = 60_000;
94
101
  // Throwing/rejecting redaction hooks and explicit vetoes fail this attempt before signing/sending;
95
102
  // an unfiltered envelope must never fall through. Retry with normal backoff, then dead-letter.
96
103
  /** Claim and process a bounded batch; hooks fail closed and unsuccessful attempts back off or dead-letter. */
97
104
  export async function processDueDeliveries(required, optional = {}) {
98
105
  const { deliveryRepo, subscriptionRepo, envelopeStore, httpClient, signer, clock, headers } = required.deps;
99
- const { batchSize, hooks, requestTimeoutMs, maxAttempts, random } = resolveProcessDueDeliveriesOptions(optional);
106
+ const { batchSize, hooks, request, claimLeaseMs, signal, maxAttempts, random } = resolveProcessDueDeliveriesOptions(optional);
107
+ const result = { processed: 0, delivered: 0, failed: 0, dead: 0 };
108
+ if (signal?.aborted)
109
+ return result;
100
110
  const claimedAt = nowIso({ clock });
101
- const claimed = await deliveryRepo.claimPending({ batchSize, nowIso: claimedAt });
102
- const result = { processed: claimed.length, delivered: 0, failed: 0, dead: 0 };
103
- for (const row of claimed) {
111
+ // The lease makes a batch abandoned mid-flight (crash, or a shutdown that outlived its grace)
112
+ // reclaimable instead of stranding its rows in `delivering`; it covers the whole batch's deadlines.
113
+ const claimed = await deliveryRepo.claimPending({ batchSize, nowIso: claimedAt }, { claimLeaseMs });
114
+ result.processed = claimed.length;
115
+ for (const [index, row] of claimed.entries()) {
116
+ if (signal?.aborted) {
117
+ await releaseClaims(claimed.slice(index), { deliveryRepo, nextAttemptAt: claimedAt });
118
+ break;
119
+ }
104
120
  const outcome = await attemptOneDelivery(row, {
105
121
  subscriptionRepo,
106
122
  envelopeStore,
@@ -109,7 +125,7 @@ export async function processDueDeliveries(required, optional = {}) {
109
125
  headers,
110
126
  clock,
111
127
  hooks,
112
- requestTimeoutMs,
128
+ request,
113
129
  });
114
130
  const disposition = await recordDeliveryOutcome(row, outcome, { deliveryRepo, clock, maxAttempts, random });
115
131
  result[disposition] += 1;
@@ -117,8 +133,23 @@ export async function processDueDeliveries(required, optional = {}) {
117
133
  return result;
118
134
  }
119
135
  function resolveProcessDueDeliveriesOptions(optional) {
120
- const { batchSize = 20, hooks = [], requestTimeoutMs = 10_000, maxAttempts = MAX_DELIVERY_ATTEMPTS, random, } = optional;
121
- return { batchSize, hooks, requestTimeoutMs, maxAttempts, random };
136
+ const { batchSize = 20, hooks = [], requestTimeoutMs = 10_000, requestTotalDeadlineMs = DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS, signal, maxAttempts = MAX_DELIVERY_ATTEMPTS, random, } = optional;
137
+ const claimLeaseMs = optional.claimLeaseMs ?? batchSize * requestTotalDeadlineMs + WEBHOOK_CLAIM_LEASE_MARGIN_MS;
138
+ const request = { timeoutMs: requestTimeoutMs, totalDeadlineMs: requestTotalDeadlineMs, ...(signal ? { signal } : {}) };
139
+ return { batchSize, hooks, request, claimLeaseMs, signal, maxAttempts, random };
140
+ }
141
+ /**
142
+ * Cancelled before these rows were attempted: hand them straight back (attempts restored, due at
143
+ * once) so a restart delivers them without waiting out the lease. A repo without `releaseClaim`
144
+ * leaves them to the lease.
145
+ */
146
+ async function releaseClaims(rows, deps) {
147
+ const { deliveryRepo, nextAttemptAt } = deps;
148
+ if (!deliveryRepo.releaseClaim)
149
+ return;
150
+ for (const row of rows) {
151
+ await deliveryRepo.releaseClaim({ workspaceId: row.workspaceId, id: row.id, claimedAttempts: row.attempts, nextAttemptAt });
152
+ }
122
153
  }
123
154
  async function recordDeliveryOutcome(row, outcome, deps) {
124
155
  if (outcome.ok) {
@@ -127,7 +158,7 @@ async function recordDeliveryOutcome(row, outcome, deps) {
127
158
  id: row.id,
128
159
  responseStatus: outcome.responseStatus,
129
160
  deliveredAtIso: nowIso({ clock: deps.clock }),
130
- });
161
+ }, { claimedAttempts: row.attempts });
131
162
  return "delivered";
132
163
  }
133
164
  const isExhausted = row.attempts >= deps.maxAttempts;
@@ -143,7 +174,7 @@ async function recordDeliveryOutcome(row, outcome, deps) {
143
174
  responseStatus: outcome.responseStatus,
144
175
  nextStatus,
145
176
  nextAttemptAt,
146
- }, isExhausted ? { deadAtIso: failedAtIso } : {});
177
+ }, { claimedAttempts: row.attempts, ...(isExhausted ? { deadAtIso: failedAtIso } : {}) });
147
178
  return isExhausted ? "dead" : "failed";
148
179
  }
149
180
  // Missing/inactive subscriptions, missing envelopes, hook failures, transport failures and
@@ -185,7 +216,7 @@ async function attemptOneDelivery(row, deps) {
185
216
  [deps.headers.deliveryId]: row.id,
186
217
  [deps.headers.eventId]: row.eventId,
187
218
  },
188
- timeoutMs: deps.requestTimeoutMs,
219
+ ...deps.request,
189
220
  body: rawBody,
190
221
  } });
191
222
  if (response.status >= 200 && response.status < 300) {
@@ -4,4 +4,5 @@ export * from "./subscriptions.js";
4
4
  export * from "./delivery.js";
5
5
  export * from "./signing.js";
6
6
  export * from "./signing.keyring.js";
7
+ export * from "./worker.js";
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -4,4 +4,5 @@ export * from "./subscriptions.js";
4
4
  export * from "./delivery.js";
5
5
  export * from "./signing.js";
6
6
  export * from "./signing.keyring.js";
7
+ export * from "./worker.js";
7
8
  //# sourceMappingURL=index.js.map
@@ -50,15 +50,26 @@ export interface WebhookDeliveryRepoPort {
50
50
  }, optional?: {
51
51
  envelope?: WebhookEventEnvelope;
52
52
  }): Promise<void>;
53
+ /**
54
+ * Atomically claim due `pending` rows, increment `attempts` and mark them `delivering`.
55
+ * With `claimLeaseMs`, also reclaim `delivering` rows whose lease has expired and persist
56
+ * nowIso + claimLeaseMs as each claimed row's lease (its `nextAttemptAt` while delivering): a
57
+ * claimer that died or was abandoned at shutdown must not strand its rows in `delivering` forever.
58
+ */
53
59
  claimPending(required: {
54
60
  batchSize: number;
55
61
  nowIso: ISODateTime;
62
+ }, optional?: {
63
+ claimLeaseMs?: number;
56
64
  }): Promise<WebhookDeliveryRecord[]>;
65
+ /** With `claimedAttempts`, a stale outcome (the row was reclaimed since) must not overwrite the newer claim. */
57
66
  markDelivered(required: {
58
67
  workspaceId: UUID;
59
68
  id: IntegrationId;
60
69
  responseStatus: number;
61
70
  deliveredAtIso: ISODateTime;
71
+ }, optional?: {
72
+ claimedAttempts?: number;
62
73
  }): Promise<void>;
63
74
  markFailed(required: {
64
75
  workspaceId: UUID;
@@ -69,7 +80,19 @@ export interface WebhookDeliveryRepoPort {
69
80
  nextAttemptAt: ISODateTime;
70
81
  }, optional?: {
71
82
  deadAtIso?: ISODateTime;
83
+ claimedAttempts?: number;
72
84
  }): Promise<void>;
85
+ /**
86
+ * Return a claim that was never attempted (the batch was cancelled first) to `pending`, due at
87
+ * `nextAttemptAt`, undoing the claim's `attempts` increment. Fenced on `claimedAttempts`: a
88
+ * row reclaimed since is left alone. Optional: without it, the claim lease recovers the row.
89
+ */
90
+ releaseClaim?(required: {
91
+ workspaceId: UUID;
92
+ id: IntegrationId;
93
+ claimedAttempts: number;
94
+ nextAttemptAt: ISODateTime;
95
+ }, optional?: Record<string, never>): Promise<void>;
73
96
  findById(required: {
74
97
  workspaceId: UUID;
75
98
  id: IntegrationId;
@@ -44,7 +44,7 @@ export interface UpdateSubscriptionRequired {
44
44
  deps: WebhookSubscriptionDeps;
45
45
  input: UpdateSubscriptionInput;
46
46
  }
47
- /** Validate a replacement before saving; missing workspace-scoped rows throw. */
47
+ /** Validate a replacement before saving; missing or soft-deleted workspace-scoped rows throw. */
48
48
  export declare function updateSubscription(required: UpdateSubscriptionRequired, _optional?: WebhookSubscriptionOptional): Promise<{
49
49
  subscription: WebhookSubscriptionRecord;
50
50
  }>;
@@ -39,13 +39,17 @@ export async function createSubscription(required, optional = {}) {
39
39
  await deps.repo.insert(subscription);
40
40
  return { subscription };
41
41
  }
42
- /** Validate a replacement before saving; missing workspace-scoped rows throw. */
42
+ /** Validate a replacement before saving; missing or soft-deleted workspace-scoped rows throw. */
43
43
  export async function updateSubscription(required, _optional = {}) {
44
44
  const { deps, input } = required;
45
45
  const existing = await deps.repo.findById({ workspaceId: input.workspaceId, id: input.id });
46
46
  if (!existing) {
47
47
  throw new WebhookSubscriptionNotFoundError({ message: `webhook subscription '${input.id}' was not found` });
48
48
  }
49
+ // Soft deletion is terminal: an update must preserve the disabled row's audit history.
50
+ if (existing.status === "disabled") {
51
+ throw new WebhookSubscriptionValidationError({ message: `webhook subscription '${input.id}' is disabled (deleted) and cannot be updated` });
52
+ }
49
53
  const label = input.label.trim();
50
54
  if (!label)
51
55
  throw new WebhookSubscriptionValidationError({ message: "label is required" });
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @file The generic outbound webhook delivery loop: every interval it runs one delivery pass
3
+ * (`processDueDeliveries` bound to the host's ports), single flight, and on `stop` it cancels the
4
+ * running pass through an AbortSignal so the in-flight request settles and unattempted claims are
5
+ * released before the host closes its storage. Hosts own where it runs and which ports it binds.
6
+ *
7
+ * Single flight: a tick that finds the previous one still running does nothing, so a slow receiver
8
+ * (up to the per-request total deadline times the batch) never stacks claims on top of each other.
9
+ */
10
+ /** Idle wait between ticks. Short enough that a delivery leaves within seconds, long enough that
11
+ * an idle site costs one indexed `SELECT` per interval. */
12
+ export declare const WEBHOOK_DELIVERY_INTERVAL_MS = 15000;
13
+ /**
14
+ * How long `stop` waits for the cancelled pass to settle. Cancellation makes the in-flight request
15
+ * reject at once, so what remains is a few storage writes; a pass still running after the grace is
16
+ * abandoned, not awaited, and its claims are recovered by their lease.
17
+ */
18
+ export declare const WEBHOOK_DELIVERY_STOP_GRACE_MS = 1000;
19
+ /** Prefix of the one line logged for a failed tick; the loop keeps running after it. */
20
+ export declare const WEBHOOK_DELIVERY_FAILED_LINE = "[webhooks] delivery tick failed; retrying after the interval";
21
+ /** Logged when `stop` gives up waiting on a running tick. */
22
+ export declare const WEBHOOK_DELIVERY_STOP_LATE_LINE = "[webhooks] a delivery tick was still running at shutdown; it was abandoned";
23
+ /** A cancellable timer. The default implementation never keeps the process alive. */
24
+ export interface WebhookDeliveryTimer {
25
+ cancel(): void;
26
+ }
27
+ /** Timer port, injected so tests drive ticks with a fake clock. */
28
+ export interface WebhookDeliveryScheduler {
29
+ every(required: {
30
+ ms: number;
31
+ run: () => void;
32
+ }): WebhookDeliveryTimer;
33
+ after(required: {
34
+ ms: number;
35
+ run: () => void;
36
+ }): WebhookDeliveryTimer;
37
+ }
38
+ /** Node timers, unref'd: like the outbox drainer's, the loop must never hold a stopping process open. */
39
+ export declare const nodeWebhookDeliveryScheduler: WebhookDeliveryScheduler;
40
+ export interface WebhookDeliveryWorker {
41
+ /** Runs one tick now, unless one is already running (then resolves with that one). Never rejects. */
42
+ tick(): Promise<void>;
43
+ /** Stops scheduling ticks, cancels a running one and waits up to the stop grace for it. Idempotent. */
44
+ stop(): Promise<void>;
45
+ }
46
+ export interface WebhookDeliveryWorkerRequired {
47
+ /** One delivery pass. `signal` aborts when the worker stops; pass it to `processDueDeliveries`. */
48
+ processDue: (required: {
49
+ signal: AbortSignal;
50
+ }) => Promise<unknown>;
51
+ }
52
+ export interface WebhookDeliveryWorkerOptional {
53
+ intervalMs?: number;
54
+ /** How long `stop` waits for the cancelled pass; default {@link WEBHOOK_DELIVERY_STOP_GRACE_MS}. */
55
+ stopGraceMs?: number;
56
+ scheduler?: WebhookDeliveryScheduler;
57
+ log?: (line: string) => void;
58
+ }
59
+ /** The abort reason a running pass sees; recorded as the interrupted attempt's error. */
60
+ export declare class WebhookDeliveryWorkerStoppedError extends Error {
61
+ constructor();
62
+ }
63
+ /**
64
+ * One log line for a failed tick: the error's name, message (URLs removed, length capped) and
65
+ * `code`. Never the error object itself, its `cause`, stack or extra fields: a repo or transport
66
+ * error can carry a receiver URL with credentials, request headers or a payload.
67
+ *
68
+ * @complexity O(message length).
69
+ */
70
+ export declare function describeWebhookTickError(required: {
71
+ error: unknown;
72
+ }, _optional?: {}): string;
73
+ /**
74
+ * Starts the loop. The first tick runs one interval after start.
75
+ *
76
+ * @param required.processDue one delivery pass, given the worker's stop signal.
77
+ * @param optional.intervalMs idle wait between ticks; default {@link WEBHOOK_DELIVERY_INTERVAL_MS}.
78
+ * @throws RangeError when `intervalMs` or `stopGraceMs` is not a positive finite number.
79
+ * @example const worker = startWebhookDeliveryWorker({ processDue: ({ signal }) => processDueDeliveries({ deps }, { signal }) }); await worker.stop();
80
+ * @complexity O(1) per tick, beyond `processDue`.
81
+ */
82
+ export declare function startWebhookDeliveryWorker(required: WebhookDeliveryWorkerRequired, optional?: WebhookDeliveryWorkerOptional): WebhookDeliveryWorker;
83
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @file The generic outbound webhook delivery loop: every interval it runs one delivery pass
3
+ * (`processDueDeliveries` bound to the host's ports), single flight, and on `stop` it cancels the
4
+ * running pass through an AbortSignal so the in-flight request settles and unattempted claims are
5
+ * released before the host closes its storage. Hosts own where it runs and which ports it binds.
6
+ *
7
+ * Single flight: a tick that finds the previous one still running does nothing, so a slow receiver
8
+ * (up to the per-request total deadline times the batch) never stacks claims on top of each other.
9
+ */
10
+ /** Idle wait between ticks. Short enough that a delivery leaves within seconds, long enough that
11
+ * an idle site costs one indexed `SELECT` per interval. */
12
+ export const WEBHOOK_DELIVERY_INTERVAL_MS = 15_000;
13
+ /**
14
+ * How long `stop` waits for the cancelled pass to settle. Cancellation makes the in-flight request
15
+ * reject at once, so what remains is a few storage writes; a pass still running after the grace is
16
+ * abandoned, not awaited, and its claims are recovered by their lease.
17
+ */
18
+ export const WEBHOOK_DELIVERY_STOP_GRACE_MS = 1_000;
19
+ /** Prefix of the one line logged for a failed tick; the loop keeps running after it. */
20
+ export const WEBHOOK_DELIVERY_FAILED_LINE = "[webhooks] delivery tick failed; retrying after the interval";
21
+ /** Logged when `stop` gives up waiting on a running tick. */
22
+ export const WEBHOOK_DELIVERY_STOP_LATE_LINE = "[webhooks] a delivery tick was still running at shutdown; it was abandoned";
23
+ const MAX_LOGGED_MESSAGE_CHARS = 200;
24
+ /** Bounds the scan of a pathological message before URLs are removed. */
25
+ const MAX_SCANNED_MESSAGE_CHARS = 2_000;
26
+ /** Node timers, unref'd: like the outbox drainer's, the loop must never hold a stopping process open. */
27
+ export const nodeWebhookDeliveryScheduler = {
28
+ every: ({ ms, run }) => {
29
+ const handle = setInterval(run, ms);
30
+ handle.unref();
31
+ return { cancel: () => clearInterval(handle) };
32
+ },
33
+ after: ({ ms, run }) => {
34
+ const handle = setTimeout(run, ms);
35
+ handle.unref();
36
+ return { cancel: () => clearTimeout(handle) };
37
+ },
38
+ };
39
+ /** The abort reason a running pass sees; recorded as the interrupted attempt's error. */
40
+ export class WebhookDeliveryWorkerStoppedError extends Error {
41
+ constructor() {
42
+ super("webhook delivery worker stopped");
43
+ this.name = "AbortError";
44
+ }
45
+ }
46
+ /**
47
+ * One log line for a failed tick: the error's name, message (URLs removed, length capped) and
48
+ * `code`. Never the error object itself, its `cause`, stack or extra fields: a repo or transport
49
+ * error can carry a receiver URL with credentials, request headers or a payload.
50
+ *
51
+ * @complexity O(message length).
52
+ */
53
+ export function describeWebhookTickError(required, _optional = {}) {
54
+ const { error } = required;
55
+ if (!(error instanceof Error))
56
+ return `${WEBHOOK_DELIVERY_FAILED_LINE}: a non-Error value was thrown`;
57
+ // Any space-separated word holding "://" is dropped whole (scheme, userinfo, host, query alike).
58
+ const words = error.message.slice(0, MAX_SCANNED_MESSAGE_CHARS).split(" ");
59
+ const message = words.map((word) => (word.includes("://") ? "[url]" : word)).join(" ").slice(0, MAX_LOGGED_MESSAGE_CHARS);
60
+ const code = error.code;
61
+ const codeSuffix = typeof code === "string" || typeof code === "number" ? ` (code ${code})` : "";
62
+ return `${WEBHOOK_DELIVERY_FAILED_LINE}: ${error.name}: ${message}${codeSuffix}`;
63
+ }
64
+ function assertPositiveFinite(value, name) {
65
+ if (!(Number.isFinite(value) && value > 0))
66
+ throw new RangeError(`webhook delivery ${name} must be a positive finite number`);
67
+ }
68
+ /**
69
+ * Starts the loop. The first tick runs one interval after start.
70
+ *
71
+ * @param required.processDue one delivery pass, given the worker's stop signal.
72
+ * @param optional.intervalMs idle wait between ticks; default {@link WEBHOOK_DELIVERY_INTERVAL_MS}.
73
+ * @throws RangeError when `intervalMs` or `stopGraceMs` is not a positive finite number.
74
+ * @example const worker = startWebhookDeliveryWorker({ processDue: ({ signal }) => processDueDeliveries({ deps }, { signal }) }); await worker.stop();
75
+ * @complexity O(1) per tick, beyond `processDue`.
76
+ */
77
+ export function startWebhookDeliveryWorker(required, optional = {}) {
78
+ const { intervalMs = WEBHOOK_DELIVERY_INTERVAL_MS, stopGraceMs = WEBHOOK_DELIVERY_STOP_GRACE_MS, scheduler = nodeWebhookDeliveryScheduler, log = (line) => console.error(line) } = optional;
79
+ assertPositiveFinite(intervalMs, "intervalMs");
80
+ assertPositiveFinite(stopGraceMs, "stopGraceMs");
81
+ const controller = new AbortController();
82
+ let running;
83
+ const tick = () => {
84
+ if (controller.signal.aborted)
85
+ return Promise.resolve();
86
+ running ??= required.processDue({ signal: controller.signal }).then(() => undefined, (error) => log(describeWebhookTickError({ error }))).finally(() => { running = undefined; });
87
+ return running;
88
+ };
89
+ const timer = scheduler.every({ ms: intervalMs, run: () => { void tick(); } });
90
+ const stop = async () => {
91
+ if (!controller.signal.aborted)
92
+ controller.abort(new WebhookDeliveryWorkerStoppedError());
93
+ timer.cancel();
94
+ if (running === undefined)
95
+ return;
96
+ let grace;
97
+ const late = new Promise((resolve) => { grace = scheduler.after({ ms: stopGraceMs, run: () => resolve("late") }); });
98
+ const outcome = await Promise.race([running, late]);
99
+ grace.cancel();
100
+ if (outcome === "late")
101
+ log(WEBHOOK_DELIVERY_STOP_LATE_LINE);
102
+ };
103
+ return { tick, stop };
104
+ }
105
+ //# sourceMappingURL=worker.js.map