@vite-hub/webhooks 0.0.0-stage → 0.4.1
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/LICENSE +201 -0
- package/README.md +123 -2
- package/dist/database-COdjz9Vi.d.ts +608 -0
- package/dist/database.d.ts +2 -0
- package/dist/database.js +171 -0
- package/dist/errors-1y5fWGlX.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +22 -0
- package/dist/object-BJb1W_q5.js +7 -0
- package/dist/operations-7ycAhDCw.d.ts +165 -0
- package/dist/operations.d.ts +8 -0
- package/dist/operations.js +1333 -0
- package/dist/queue-name-CGeTSHId.d.ts +5 -0
- package/dist/queue-name-RURp9SQf.js +5 -0
- package/dist/runtime-DVBMk9vu.js +486 -0
- package/dist/runtime-mqwMGfyX.d.ts +184 -0
- package/dist/runtime.d.ts +3 -0
- package/dist/runtime.js +3 -0
- package/dist/table-names-DVvicXhh.js +8 -0
- package/dist/vite.d.ts +299 -0
- package/dist/vite.js +328 -0
- package/package.json +90 -3
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import { t as webhooksErrors } from "./errors-1y5fWGlX.js";
|
|
2
|
+
import { signWebhook } from "@vite-hub/env";
|
|
3
|
+
import { onRunFailed, runFailedEventNames } from "@vite-hub/runtime/internal/run-failed";
|
|
4
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
5
|
+
import { parseDuration } from "@vite-hub/runtime";
|
|
6
|
+
//#region ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
7
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
8
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
9
|
+
let activeEnv;
|
|
10
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
11
|
+
function getScopedCloudflareEnv() {
|
|
12
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
13
|
+
}
|
|
14
|
+
function getActiveCloudflareEnv() {
|
|
15
|
+
const scoped = getScopedCloudflareEnv();
|
|
16
|
+
if (scoped) return scoped.env;
|
|
17
|
+
const host = globalThis;
|
|
18
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/define.ts
|
|
22
|
+
const definitionBrand = Symbol.for("vitehub.webhooks.definition");
|
|
23
|
+
const variableName = /^[A-Z_][A-Z0-9_]*$/i;
|
|
24
|
+
function isWebhookEvent(value) {
|
|
25
|
+
return runFailedEventNames.some((name) => name === value);
|
|
26
|
+
}
|
|
27
|
+
function invalid(message) {
|
|
28
|
+
return webhooksErrors.WEBHOOKS_DEFINITION_INVALID({ message: `[vitehub] ${message}` });
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Defines a webhook: where ViteHub sends events, how it signs them, and how long it waits to collapse them. Default-export
|
|
32
|
+
* it from `server/webhooks/<name>.ts`, then call `sendWebhook("<name>", body)` from server code, or list `events` that
|
|
33
|
+
* ViteHub sends by itself.
|
|
34
|
+
*
|
|
35
|
+
* ```ts [server/webhooks/t3.ts]
|
|
36
|
+
* import { defineWebhook } from "@vite-hub/webhooks"
|
|
37
|
+
*
|
|
38
|
+
* export default defineWebhook({
|
|
39
|
+
* url: "T3_WEBHOOK_URL",
|
|
40
|
+
* secret: "T3_WEBHOOK_SECRET",
|
|
41
|
+
* debounce: "30m",
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
function defineWebhook(options) {
|
|
46
|
+
for (const key of ["url", "secret"]) {
|
|
47
|
+
const value = options?.[key];
|
|
48
|
+
if (typeof value !== "string" || !variableName.test(value)) throw invalid(`\`${key}\` must be the name of a server variable, such as ${key === "url" ? "\"T3_WEBHOOK_URL\"" : "\"T3_WEBHOOK_SECRET\""}, not ${JSON.stringify(value)}.`);
|
|
49
|
+
}
|
|
50
|
+
const signature = options.signature ?? "github";
|
|
51
|
+
if (signature !== "github" && signature !== "stripe") throw invalid(`\`signature\` must be "github" or "stripe", not ${JSON.stringify(signature)}.`);
|
|
52
|
+
const debounceMs = options.debounce === void 0 ? 0 : parseDuration(options.debounce, "debounce");
|
|
53
|
+
if (debounceMs > 864e5) throw webhooksErrors.WEBHOOKS_DEBOUNCE_TOO_LONG({ debounce: JSON.stringify(options.debounce) });
|
|
54
|
+
const listed = options.events ?? [];
|
|
55
|
+
if (!Array.isArray(listed)) throw invalid(`\`events\` must be a list such as ["workflow.failed"], not ${JSON.stringify(listed)}.`);
|
|
56
|
+
const items = listed;
|
|
57
|
+
const events = /* @__PURE__ */ new Set();
|
|
58
|
+
for (const event of items) {
|
|
59
|
+
if (!isWebhookEvent(event)) throw invalid(`\`events\` lists ${JSON.stringify(event)}. Use ${runFailedEventNames.map((name) => JSON.stringify(name)).join(", ")}.`);
|
|
60
|
+
events.add(event);
|
|
61
|
+
}
|
|
62
|
+
return Object.defineProperty({
|
|
63
|
+
url: options.url,
|
|
64
|
+
secret: options.secret,
|
|
65
|
+
signature,
|
|
66
|
+
debounceMs,
|
|
67
|
+
events: [...events]
|
|
68
|
+
}, definitionBrand, { value: true });
|
|
69
|
+
}
|
|
70
|
+
function isWebhookDefinition(value) {
|
|
71
|
+
return typeof value === "object" && value !== null && Reflect.get(value, definitionBrand) === true;
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/runtime.ts
|
|
75
|
+
/** Attempts of one delivery before it is `dead`: one delivery and three retries, as Cloudflare Queues does by default. */
|
|
76
|
+
const webhookMaxAttempts = 4;
|
|
77
|
+
/** How long a receiver has to answer. */
|
|
78
|
+
const webhookTimeoutMs = 1e4;
|
|
79
|
+
/** A `sending` claim older than this was left by a stopped server, so another wake can take it. */
|
|
80
|
+
const claimLeaseMs = 7e4;
|
|
81
|
+
const installedKey = Symbol.for("vitehub.webhooks.installed");
|
|
82
|
+
/** The webhooks that `installWebhooks()` installed in this process. */
|
|
83
|
+
function installedWebhooks() {
|
|
84
|
+
const value = Reflect.get(globalThis, installedKey);
|
|
85
|
+
return value === void 0 ? void 0 : value;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Installs the webhooks of the app for `sendWebhook()`, the Queue handler, and the delivery functions. The generated
|
|
89
|
+
* server code of a ViteHub app calls it when the server starts. A test calls it with its own store and wake sender.
|
|
90
|
+
*/
|
|
91
|
+
function installWebhooks(options) {
|
|
92
|
+
const webhooks = /* @__PURE__ */ new Map();
|
|
93
|
+
for (const [name, definition] of Object.entries(options.webhooks)) {
|
|
94
|
+
if (!isWebhookDefinition(definition)) throw webhooksErrors.WEBHOOKS_DEFINITION_INVALID({ message: `[vitehub] server/webhooks/${name} must default-export defineWebhook({ url, secret }).` });
|
|
95
|
+
webhooks.set(name, definition);
|
|
96
|
+
}
|
|
97
|
+
const installed = {
|
|
98
|
+
webhooks,
|
|
99
|
+
store: options.store,
|
|
100
|
+
wake: options.wake
|
|
101
|
+
};
|
|
102
|
+
Reflect.set(globalThis, installedKey, installed);
|
|
103
|
+
if (!Reflect.get(globalThis, listenerKey)) Reflect.set(globalThis, listenerKey, onRunFailed(sendRunFailed));
|
|
104
|
+
return installed;
|
|
105
|
+
}
|
|
106
|
+
const listenerKey = Symbol.for("vitehub.webhooks.runFailedListener");
|
|
107
|
+
/** The Agent, Workflow, or Schedule that failed: the key that collapses repeated failures of it while a debounce waits. */
|
|
108
|
+
function failedSubject(event) {
|
|
109
|
+
if (event.event === "invocation.failed") return event.agent ?? event.invocationId;
|
|
110
|
+
return event.event === "workflow.failed" ? event.workflow : event.schedule;
|
|
111
|
+
}
|
|
112
|
+
function toWebhookEventBody(event) {
|
|
113
|
+
const subject = event.event === "invocation.failed" ? `The Agent Invocation ${event.invocationId}${event.agent ? ` of ${JSON.stringify(event.agent)}` : ""}` : event.event === "workflow.failed" ? `The Workflow run ${event.runId} of ${JSON.stringify(event.workflow)}` : `The Schedule run ${event.runId} of ${JSON.stringify(event.schedule)}`;
|
|
114
|
+
return {
|
|
115
|
+
...event,
|
|
116
|
+
text: `${subject} failed: ${event.error.message}`
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Sends a failed run to each webhook that lists its event. With a debounce, failures of the same Agent, Workflow, or
|
|
121
|
+
* Schedule collapse into one delivery that holds the last failure, and `x-vitehub-events` counts them.
|
|
122
|
+
*/
|
|
123
|
+
async function sendRunFailed(event) {
|
|
124
|
+
const installed = installedWebhooks();
|
|
125
|
+
if (!installed) return;
|
|
126
|
+
const body = toWebhookEventBody(event);
|
|
127
|
+
for (const [name, definition] of installed.webhooks) {
|
|
128
|
+
if (!definition.events.includes(event.event)) continue;
|
|
129
|
+
const key = definition.debounceMs > 0 ? `${event.event}:${failedSubject(event)}` : null;
|
|
130
|
+
const [error] = await enqueue(name, body, {
|
|
131
|
+
event: event.event,
|
|
132
|
+
key,
|
|
133
|
+
delayMs: definition.debounceMs
|
|
134
|
+
});
|
|
135
|
+
if (error) console.error(`[vitehub] The webhook ${name} did not store the ${event.event} event.`, error);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function requireInstalled() {
|
|
139
|
+
const installed = installedWebhooks();
|
|
140
|
+
if (!installed) throw webhooksErrors.WEBHOOKS_NOT_INSTALLED();
|
|
141
|
+
return installed;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The Database that keeps the deliveries: the one that `useDatabase()` of `@vite-hub/database/runtime/registry` returns
|
|
145
|
+
* without a name. That is the Database that `vitehub database generate` adds the table to: `default`, else the only one.
|
|
146
|
+
* The registry also holds a placeholder `default` that throws, so code must not pick from it by name.
|
|
147
|
+
*/
|
|
148
|
+
function selectDefaultDatabase(useDatabase) {
|
|
149
|
+
try {
|
|
150
|
+
return useDatabase().db;
|
|
151
|
+
} catch (cause) {
|
|
152
|
+
throw webhooksErrors.WEBHOOKS_DATABASE_MISSING({ cause });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** The server variables: Node's `process.env`, the Cloudflare bindings, and the values of `setEnv()` in app tests. */
|
|
156
|
+
function serverEnv() {
|
|
157
|
+
return {
|
|
158
|
+
...typeof process === "object" && process?.env ? process.env : {},
|
|
159
|
+
...getActiveCloudflareEnv(),
|
|
160
|
+
...getViteHubTestMode()?.env
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function readString(env, name) {
|
|
164
|
+
const value = env[name];
|
|
165
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
166
|
+
}
|
|
167
|
+
/** The URL and secret of a webhook, or the error that names the missing variable. Errors never hold the values. */
|
|
168
|
+
function resolveTarget(name, definition) {
|
|
169
|
+
const env = serverEnv();
|
|
170
|
+
const url = readString(env, definition.url);
|
|
171
|
+
if (!url) return [webhooksErrors.WEBHOOKS_URL_UNSET({
|
|
172
|
+
name: definition.url,
|
|
173
|
+
webhook: name
|
|
174
|
+
}), void 0];
|
|
175
|
+
if (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) return [webhooksErrors.WEBHOOKS_URL_INVALID({
|
|
176
|
+
name: definition.url,
|
|
177
|
+
webhook: name
|
|
178
|
+
}), void 0];
|
|
179
|
+
const secret = readString(env, definition.secret);
|
|
180
|
+
if (!secret) return [webhooksErrors.WEBHOOKS_SECRET_UNSET({
|
|
181
|
+
name: definition.secret,
|
|
182
|
+
webhook: name
|
|
183
|
+
}), void 0];
|
|
184
|
+
return [void 0, {
|
|
185
|
+
url,
|
|
186
|
+
secret
|
|
187
|
+
}];
|
|
188
|
+
}
|
|
189
|
+
function createDeliveryId() {
|
|
190
|
+
return `whd_${crypto.randomUUID()}`;
|
|
191
|
+
}
|
|
192
|
+
async function wake(installed, delivery, delayMs) {
|
|
193
|
+
try {
|
|
194
|
+
const [error] = await installed.wake({
|
|
195
|
+
id: delivery.id,
|
|
196
|
+
revision: delivery.revision
|
|
197
|
+
}, { delay: `${Math.ceil(Math.max(0, delayMs) / 1e3)}s` });
|
|
198
|
+
return error === void 0 ? void 0 : webhooksErrors.WEBHOOKS_WAKE_FAILED({
|
|
199
|
+
webhook: delivery.webhook,
|
|
200
|
+
cause: error
|
|
201
|
+
});
|
|
202
|
+
} catch (cause) {
|
|
203
|
+
return webhooksErrors.WEBHOOKS_WAKE_FAILED({
|
|
204
|
+
webhook: delivery.webhook,
|
|
205
|
+
cause
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Stores a delivery of `body` and wakes the Queue after `delayMs`. A `null` key never collapses with another send. */
|
|
210
|
+
async function enqueue(name, body, options) {
|
|
211
|
+
const installed = requireInstalled();
|
|
212
|
+
const definition = installed.webhooks.get(name);
|
|
213
|
+
if (!definition) throw webhooksErrors.WEBHOOKS_NOT_FOUND({ name: JSON.stringify(name) });
|
|
214
|
+
const [targetError] = resolveTarget(name, definition);
|
|
215
|
+
if (targetError) return [targetError, void 0];
|
|
216
|
+
let text;
|
|
217
|
+
try {
|
|
218
|
+
text = JSON.stringify(body);
|
|
219
|
+
} catch {
|
|
220
|
+
text = void 0;
|
|
221
|
+
}
|
|
222
|
+
if (text === void 0) return [webhooksErrors.WEBHOOKS_BODY_INVALID({ webhook: name }), void 0];
|
|
223
|
+
const now = Date.now();
|
|
224
|
+
let recorded;
|
|
225
|
+
try {
|
|
226
|
+
recorded = await installed.store.record({
|
|
227
|
+
id: createDeliveryId(),
|
|
228
|
+
webhook: name,
|
|
229
|
+
key: options.key,
|
|
230
|
+
event: options.event,
|
|
231
|
+
body: text,
|
|
232
|
+
dueAt: now + options.delayMs,
|
|
233
|
+
now
|
|
234
|
+
});
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (webhooksErrors.WEBHOOKS_STORE_FAILED.is(error) || webhooksErrors.WEBHOOKS_DATABASE_MISSING.is(error)) return [error, void 0];
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
const wakeError = await wake(installed, {
|
|
240
|
+
...recorded,
|
|
241
|
+
webhook: name
|
|
242
|
+
}, options.delayMs);
|
|
243
|
+
if (wakeError) return [wakeError, void 0];
|
|
244
|
+
return [void 0, {
|
|
245
|
+
id: recorded.id,
|
|
246
|
+
status: "pending"
|
|
247
|
+
}];
|
|
248
|
+
}
|
|
249
|
+
/** Sends a body to a webhook. `sendWebhook()` of `@vite-hub/webhooks` calls it with a typed name. */
|
|
250
|
+
async function sendDynamicWebhook(name, body, options) {
|
|
251
|
+
const debounceMs = requireInstalled().webhooks.get(name)?.debounceMs ?? 0;
|
|
252
|
+
return enqueue(name, body, {
|
|
253
|
+
event: options.event,
|
|
254
|
+
key: debounceMs > 0 ? options.key ?? name : null,
|
|
255
|
+
delayMs: debounceMs
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
/** The event of a test delivery. */
|
|
259
|
+
const webhookTestEvent = "webhooks.test";
|
|
260
|
+
/**
|
|
261
|
+
* Sends a test delivery to a webhook now, without its debounce and apart from the pending sends, with the event
|
|
262
|
+
* `webhooks.test`. Use it to check the URL, the secret, and the receiver. The default body is
|
|
263
|
+
* `{ test: true, webhook: name }`. An unknown name throws.
|
|
264
|
+
*/
|
|
265
|
+
async function testWebhook(name, options = {}) {
|
|
266
|
+
return enqueue(name, options.body === void 0 ? {
|
|
267
|
+
test: true,
|
|
268
|
+
webhook: name
|
|
269
|
+
} : options.body, {
|
|
270
|
+
event: webhookTestEvent,
|
|
271
|
+
key: null,
|
|
272
|
+
delayMs: 0
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
function isWake(value) {
|
|
276
|
+
return typeof value === "object" && value !== null && typeof Reflect.get(value, "id") === "string" && Number.isInteger(Reflect.get(value, "revision"));
|
|
277
|
+
}
|
|
278
|
+
/** Why an attempt failed, without the URL, its query, or the secret. */
|
|
279
|
+
function describeFailure(error) {
|
|
280
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `no answer within ${webhookTimeoutMs / 1e3} seconds`;
|
|
281
|
+
const cause = error instanceof Error ? error.cause : void 0;
|
|
282
|
+
const code = typeof cause === "object" && cause !== null ? Reflect.get(cause, "code") : void 0;
|
|
283
|
+
return typeof code === "string" ? `network error ${code}` : "network error";
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The Queue handler of `vitehub-webhooks`. It posts the delivery of a wake when the wake carries the latest revision and
|
|
287
|
+
* the delivery is pending. A 2xx answer marks it `sent`. Any other answer throws, so the Queue tries again, until the
|
|
288
|
+
* last attempt marks it `dead`. A wake that is out of date does nothing.
|
|
289
|
+
*/
|
|
290
|
+
async function deliverWebhookWake(payload) {
|
|
291
|
+
if (!isWake(payload)) {
|
|
292
|
+
console.error("[vitehub] The webhooks Queue got a job that is not a delivery wake. It skips the job.");
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const installed = requireInstalled();
|
|
296
|
+
const { store } = installed;
|
|
297
|
+
const now = Date.now();
|
|
298
|
+
const claim = await store.claim(payload.id, payload.revision, now, now - claimLeaseMs);
|
|
299
|
+
if (!claim) {
|
|
300
|
+
const current = await store.get(payload.id);
|
|
301
|
+
if (current?.revision === payload.revision && current.state === "sending") {
|
|
302
|
+
const error = await wake(installed, current, current.updatedAt + claimLeaseMs + 1 - Date.now());
|
|
303
|
+
if (error) throw error;
|
|
304
|
+
}
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const definition = installed.webhooks.get(claim.webhook);
|
|
308
|
+
if (!definition) {
|
|
309
|
+
await store.failed(claim, {
|
|
310
|
+
status: null,
|
|
311
|
+
error: `No webhook is named ${JSON.stringify(claim.webhook)} in this build.`
|
|
312
|
+
}, Date.now(), true);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const [targetError, target] = resolveTarget(claim.webhook, definition);
|
|
316
|
+
if (targetError) {
|
|
317
|
+
await store.failed(claim, {
|
|
318
|
+
status: null,
|
|
319
|
+
error: targetError.message
|
|
320
|
+
}, Date.now(), true);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const body = JSON.stringify(claim.body);
|
|
324
|
+
let status = null;
|
|
325
|
+
let failure;
|
|
326
|
+
try {
|
|
327
|
+
const signed = await signWebhook(body, {
|
|
328
|
+
provider: definition.signature,
|
|
329
|
+
secret: target.secret
|
|
330
|
+
});
|
|
331
|
+
const response = await fetch(target.url, {
|
|
332
|
+
method: "POST",
|
|
333
|
+
body,
|
|
334
|
+
headers: {
|
|
335
|
+
...signed,
|
|
336
|
+
"content-type": "application/json",
|
|
337
|
+
"user-agent": "ViteHub-Webhooks",
|
|
338
|
+
"x-vitehub-delivery": claim.id,
|
|
339
|
+
"x-vitehub-event": claim.event,
|
|
340
|
+
"x-vitehub-events": String(claim.count)
|
|
341
|
+
},
|
|
342
|
+
redirect: "manual",
|
|
343
|
+
signal: AbortSignal.timeout(webhookTimeoutMs)
|
|
344
|
+
});
|
|
345
|
+
status = response.status;
|
|
346
|
+
await response.body?.cancel().catch(() => {});
|
|
347
|
+
if (response.ok) {
|
|
348
|
+
await store.sent(claim, {
|
|
349
|
+
status,
|
|
350
|
+
error: null
|
|
351
|
+
}, Date.now());
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
failure = `HTTP ${status}`;
|
|
355
|
+
} catch (error) {
|
|
356
|
+
failure = describeFailure(error);
|
|
357
|
+
}
|
|
358
|
+
const dead = claim.attempts >= 4;
|
|
359
|
+
if (await store.failed(claim, {
|
|
360
|
+
status,
|
|
361
|
+
error: failure
|
|
362
|
+
}, Date.now(), dead) === "pending") throw webhooksErrors.WEBHOOKS_DELIVERY_FAILED({
|
|
363
|
+
reason: failure,
|
|
364
|
+
webhook: claim.webhook
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
const deliveryErrorCodes = [
|
|
368
|
+
"WEBHOOKS_DATABASE_MISSING",
|
|
369
|
+
"WEBHOOKS_DELIVERY_ACTIVE",
|
|
370
|
+
"WEBHOOKS_DELIVERY_NOT_FOUND",
|
|
371
|
+
"WEBHOOKS_DELIVERY_NOT_PENDING",
|
|
372
|
+
"WEBHOOKS_STORE_FAILED",
|
|
373
|
+
"WEBHOOKS_WAKE_FAILED"
|
|
374
|
+
];
|
|
375
|
+
function isDeliveryError(error) {
|
|
376
|
+
return webhooksErrors.is(error) && deliveryErrorCodes.includes(error.code);
|
|
377
|
+
}
|
|
378
|
+
/** Runs a delivery function. Its known failures come back as `[error, undefined]`; a definition error still throws. */
|
|
379
|
+
async function attempt(run) {
|
|
380
|
+
const installed = requireInstalled();
|
|
381
|
+
try {
|
|
382
|
+
return [void 0, await run(installed)];
|
|
383
|
+
} catch (error) {
|
|
384
|
+
if (isDeliveryError(error)) return [error, void 0];
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/** Every webhook of the app, with the names of its variables and whether they are set. */
|
|
389
|
+
function listWebhooks() {
|
|
390
|
+
const installed = requireInstalled();
|
|
391
|
+
const env = serverEnv();
|
|
392
|
+
return [...installed.webhooks].sort(([left], [right]) => left.localeCompare(right)).map(([name, definition]) => {
|
|
393
|
+
const url = readString(env, definition.url);
|
|
394
|
+
return {
|
|
395
|
+
name,
|
|
396
|
+
url: definition.url,
|
|
397
|
+
secret: definition.secret,
|
|
398
|
+
signature: definition.signature,
|
|
399
|
+
debounceMs: definition.debounceMs,
|
|
400
|
+
events: definition.events,
|
|
401
|
+
urlSet: url !== void 0,
|
|
402
|
+
secretSet: readString(env, definition.secret) !== void 0,
|
|
403
|
+
host: url !== void 0 && URL.canParse(url) ? new URL(url).host || null : null
|
|
404
|
+
};
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/** Deliveries, newest first. */
|
|
408
|
+
function listWebhookDeliveries(options) {
|
|
409
|
+
return attempt((installed) => installed.store.list(options));
|
|
410
|
+
}
|
|
411
|
+
/** Pending deliveries, the soonest due first: the debounce timers that run now. */
|
|
412
|
+
function listPendingWebhookDeliveries(options) {
|
|
413
|
+
return attempt((installed) => installed.store.pending(options));
|
|
414
|
+
}
|
|
415
|
+
async function findDelivery(installed, id) {
|
|
416
|
+
const delivery = await installed.store.get(id);
|
|
417
|
+
if (!delivery) throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_FOUND({ id: JSON.stringify(id) });
|
|
418
|
+
return delivery;
|
|
419
|
+
}
|
|
420
|
+
function getWebhookDelivery(id) {
|
|
421
|
+
return attempt((installed) => findDelivery(installed, id));
|
|
422
|
+
}
|
|
423
|
+
/** Delivers a pending delivery now, without the rest of its debounce. */
|
|
424
|
+
function flushWebhookDelivery(id) {
|
|
425
|
+
return attempt(async (installed) => {
|
|
426
|
+
const delivery = await installed.store.due(id, Date.now());
|
|
427
|
+
if (!delivery) {
|
|
428
|
+
const current = await findDelivery(installed, id);
|
|
429
|
+
throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_PENDING({
|
|
430
|
+
id: JSON.stringify(id),
|
|
431
|
+
state: current.state
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
const error = await wake(installed, delivery, 0);
|
|
435
|
+
if (error) throw error;
|
|
436
|
+
return delivery;
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
/** Cancels a pending delivery. Its wake then does nothing. */
|
|
440
|
+
function cancelWebhookDelivery(id) {
|
|
441
|
+
return attempt(async (installed) => {
|
|
442
|
+
const delivery = await installed.store.cancel(id, Date.now());
|
|
443
|
+
if (delivery) return delivery;
|
|
444
|
+
const current = await findDelivery(installed, id);
|
|
445
|
+
throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_PENDING({
|
|
446
|
+
id: JSON.stringify(id),
|
|
447
|
+
state: current.state
|
|
448
|
+
});
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Sends a sent, dead, or cancelled delivery again, now, as a new delivery with a new id. It keeps the body, the event,
|
|
453
|
+
* and the count. The webhook must still exist.
|
|
454
|
+
*/
|
|
455
|
+
function redeliverWebhookDelivery(id) {
|
|
456
|
+
return attempt(async (installed) => {
|
|
457
|
+
const source = await findDelivery(installed, id);
|
|
458
|
+
if (source.state === "pending" || source.state === "sending") throw webhooksErrors.WEBHOOKS_DELIVERY_ACTIVE({
|
|
459
|
+
id: JSON.stringify(id),
|
|
460
|
+
state: source.state
|
|
461
|
+
});
|
|
462
|
+
if (!installed.webhooks.has(source.webhook)) throw webhooksErrors.WEBHOOKS_NOT_FOUND({ name: JSON.stringify(source.webhook) });
|
|
463
|
+
const now = Date.now();
|
|
464
|
+
const recorded = await installed.store.record({
|
|
465
|
+
id: createDeliveryId(),
|
|
466
|
+
webhook: source.webhook,
|
|
467
|
+
key: null,
|
|
468
|
+
event: source.event,
|
|
469
|
+
body: JSON.stringify(source.body),
|
|
470
|
+
count: source.count,
|
|
471
|
+
dueAt: now,
|
|
472
|
+
now
|
|
473
|
+
});
|
|
474
|
+
const error = await wake(installed, {
|
|
475
|
+
...recorded,
|
|
476
|
+
webhook: source.webhook
|
|
477
|
+
}, 0);
|
|
478
|
+
if (error) throw error;
|
|
479
|
+
return {
|
|
480
|
+
id: recorded.id,
|
|
481
|
+
status: "pending"
|
|
482
|
+
};
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
//#endregion
|
|
486
|
+
export { defineWebhook as _, installWebhooks as a, listWebhookDeliveries as c, selectDefaultDatabase as d, sendDynamicWebhook as f, webhookTimeoutMs as g, webhookTestEvent as h, getWebhookDelivery as i, listWebhooks as l, webhookMaxAttempts as m, deliverWebhookWake as n, installedWebhooks as o, testWebhook as p, flushWebhookDelivery as r, listPendingWebhookDeliveries as s, cancelWebhookDelivery as t, redeliverWebhookDelivery as u };
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { a as WebhookDeliveryStore, r as WebhookDelivery, s as WebhooksDatabase, t as ListWebhookDeliveriesOptions } from "./database-COdjz9Vi.js";
|
|
2
|
+
import { RunFailedEvent, RunFailedEventName } from "@vite-hub/runtime/internal/run-failed";
|
|
3
|
+
import { Duration, Result } from "@vite-hub/runtime";
|
|
4
|
+
//#region src/errors.d.ts
|
|
5
|
+
/** The codes that `sendWebhook()` returns. Definition errors throw instead. */
|
|
6
|
+
type SendWebhookErrorCode = "WEBHOOKS_BODY_INVALID" | "WEBHOOKS_DATABASE_MISSING" | "WEBHOOKS_SECRET_UNSET" | "WEBHOOKS_STORE_FAILED" | "WEBHOOKS_URL_INVALID" | "WEBHOOKS_URL_UNSET" | "WEBHOOKS_WAKE_FAILED";
|
|
7
|
+
/** The codes that the delivery functions of `@vite-hub/webhooks/runtime` return. */
|
|
8
|
+
type WebhookDeliveryErrorCode = "WEBHOOKS_DATABASE_MISSING" | "WEBHOOKS_DELIVERY_ACTIVE" | "WEBHOOKS_DELIVERY_NOT_FOUND" | "WEBHOOKS_DELIVERY_NOT_PENDING" | "WEBHOOKS_STORE_FAILED" | "WEBHOOKS_WAKE_FAILED";
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/define.d.ts
|
|
11
|
+
/** How a delivery is signed. Both use HMAC-SHA256 of the raw body with the secret. */
|
|
12
|
+
type WebhookSignature = "github" | "stripe";
|
|
13
|
+
/**
|
|
14
|
+
* An event that ViteHub sends by itself, with no `sendWebhook()` call: an Agent Invocation, a Workflow run, or a Schedule
|
|
15
|
+
* run that ended in failure with no retry left.
|
|
16
|
+
*/
|
|
17
|
+
type WebhookEvent = RunFailedEventName;
|
|
18
|
+
/** What `defineWebhook()` accepts. */
|
|
19
|
+
interface WebhookOptions {
|
|
20
|
+
/**
|
|
21
|
+
* The name of the server variable that holds the receiver URL, such as `"T3_WEBHOOK_URL"`. It is a name, not the URL,
|
|
22
|
+
* because a URL often holds a token.
|
|
23
|
+
*/
|
|
24
|
+
url: string;
|
|
25
|
+
/** The name of the server variable that holds the signing secret, such as `"T3_WEBHOOK_SECRET"`. */
|
|
26
|
+
secret: string;
|
|
27
|
+
/**
|
|
28
|
+
* `"github"` (default) sends `x-hub-signature-256: sha256=<hex>`. `"stripe"` sends
|
|
29
|
+
* `stripe-signature: t=<time>,v1=<hex>`. `verifyWebhook()` from `@vite-hub/env` checks both.
|
|
30
|
+
*/
|
|
31
|
+
signature?: WebhookSignature;
|
|
32
|
+
/**
|
|
33
|
+
* Wait this long after the last send before one delivery, such as `"30m"`. Each send in the window replaces the body
|
|
34
|
+
* and restarts the wait. Sends with the same `key` collapse, and the key defaults to the webhook name. At most `"1d"`.
|
|
35
|
+
* Without it, each send is delivered at once.
|
|
36
|
+
*/
|
|
37
|
+
debounce?: Duration;
|
|
38
|
+
/**
|
|
39
|
+
* Events that ViteHub sends to this webhook by itself: `"invocation.failed"`, `"workflow.failed"`, and
|
|
40
|
+
* `"schedule.failed"`. Each is sent once, when the run ends in failure with no retry left.
|
|
41
|
+
*/
|
|
42
|
+
events?: readonly WebhookEvent[];
|
|
43
|
+
}
|
|
44
|
+
/** A webhook of `server/webhooks/<name>.ts`. */
|
|
45
|
+
interface WebhookDefinition {
|
|
46
|
+
readonly url: string;
|
|
47
|
+
readonly secret: string;
|
|
48
|
+
readonly signature: WebhookSignature;
|
|
49
|
+
/** The debounce in milliseconds. `0` delivers each send at once. */
|
|
50
|
+
readonly debounceMs: number;
|
|
51
|
+
/** The events that ViteHub sends to this webhook by itself. */
|
|
52
|
+
readonly events: readonly WebhookEvent[];
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Defines a webhook: where ViteHub sends events, how it signs them, and how long it waits to collapse them. Default-export
|
|
56
|
+
* it from `server/webhooks/<name>.ts`, then call `sendWebhook("<name>", body)` from server code, or list `events` that
|
|
57
|
+
* ViteHub sends by itself.
|
|
58
|
+
*
|
|
59
|
+
* ```ts [server/webhooks/t3.ts]
|
|
60
|
+
* import { defineWebhook } from "@vite-hub/webhooks"
|
|
61
|
+
*
|
|
62
|
+
* export default defineWebhook({
|
|
63
|
+
* url: "T3_WEBHOOK_URL",
|
|
64
|
+
* secret: "T3_WEBHOOK_SECRET",
|
|
65
|
+
* debounce: "30m",
|
|
66
|
+
* })
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
declare function defineWebhook(options: WebhookOptions): WebhookDefinition;
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region src/runtime.d.ts
|
|
72
|
+
/** Attempts of one delivery before it is `dead`: one delivery and three retries, as Cloudflare Queues does by default. */
|
|
73
|
+
declare const webhookMaxAttempts = 4;
|
|
74
|
+
/** How long a receiver has to answer. */
|
|
75
|
+
declare const webhookTimeoutMs = 10000;
|
|
76
|
+
/** The Queue job of a delivery. Only the wake of the latest revision delivers, so an older wake does nothing. */
|
|
77
|
+
interface WebhookWake {
|
|
78
|
+
id: string;
|
|
79
|
+
revision: number;
|
|
80
|
+
}
|
|
81
|
+
/** Sends a wake to the `vitehub-webhooks` Queue. `dynamicQueue.send()` of `@vite-hub/queue` fits. */
|
|
82
|
+
type WebhookWakeSender = (wake: WebhookWake, options: {
|
|
83
|
+
delay: Duration;
|
|
84
|
+
}) => Promise<readonly [unknown, unknown]>;
|
|
85
|
+
/** What the generated server code of a ViteHub app passes. */
|
|
86
|
+
interface InstallWebhooksOptions {
|
|
87
|
+
/** The default export of each `server/webhooks/<name>.ts`, by name. */
|
|
88
|
+
webhooks: Record<string, unknown>;
|
|
89
|
+
/** Where deliveries live: `createDrizzleWebhookStore()` from `@vite-hub/webhooks/database`. */
|
|
90
|
+
store: WebhookDeliveryStore;
|
|
91
|
+
wake: WebhookWakeSender;
|
|
92
|
+
}
|
|
93
|
+
/** The webhooks of the running app. */
|
|
94
|
+
interface InstalledWebhooks {
|
|
95
|
+
webhooks: ReadonlyMap<string, WebhookDefinition>;
|
|
96
|
+
store: WebhookDeliveryStore;
|
|
97
|
+
wake: WebhookWakeSender;
|
|
98
|
+
}
|
|
99
|
+
/** One webhook, as the CLI and the Console list it. It names the variables, never their values. */
|
|
100
|
+
interface WebhookInfo {
|
|
101
|
+
name: string;
|
|
102
|
+
/** The name of the variable with the URL. */
|
|
103
|
+
url: string;
|
|
104
|
+
/** The name of the variable with the secret. */
|
|
105
|
+
secret: string;
|
|
106
|
+
signature: WebhookSignature;
|
|
107
|
+
debounceMs: number;
|
|
108
|
+
/** The events that ViteHub sends to this webhook by itself. */
|
|
109
|
+
events: readonly WebhookEvent[];
|
|
110
|
+
/** Whether this server has a value for `url` and for `secret`. */
|
|
111
|
+
urlSet: boolean;
|
|
112
|
+
secretSet: boolean;
|
|
113
|
+
/** The host of the URL, such as `t3.example.com`, when it is set and valid. Never the path or the query, which can hold a token. */
|
|
114
|
+
host: string | null;
|
|
115
|
+
}
|
|
116
|
+
/** What `sendWebhook()` returns. `id` is the delivery: sends that a debounce collapses return the same id. */
|
|
117
|
+
interface SendWebhookResult {
|
|
118
|
+
id: string;
|
|
119
|
+
status: "pending";
|
|
120
|
+
}
|
|
121
|
+
/** The webhooks that `installWebhooks()` installed in this process. */
|
|
122
|
+
declare function installedWebhooks(): InstalledWebhooks | undefined;
|
|
123
|
+
/**
|
|
124
|
+
* Installs the webhooks of the app for `sendWebhook()`, the Queue handler, and the delivery functions. The generated
|
|
125
|
+
* server code of a ViteHub app calls it when the server starts. A test calls it with its own store and wake sender.
|
|
126
|
+
*/
|
|
127
|
+
declare function installWebhooks(options: InstallWebhooksOptions): InstalledWebhooks;
|
|
128
|
+
/**
|
|
129
|
+
* The body of an event that ViteHub sends by itself, such as `workflow.failed`. `text` is one line that a person reads,
|
|
130
|
+
* so a Slack incoming webhook shows it as the message.
|
|
131
|
+
*/
|
|
132
|
+
type WebhookEventBody = RunFailedEvent & {
|
|
133
|
+
text: string;
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* The Database that keeps the deliveries: the one that `useDatabase()` of `@vite-hub/database/runtime/registry` returns
|
|
137
|
+
* without a name. That is the Database that `vitehub database generate` adds the table to: `default`, else the only one.
|
|
138
|
+
* The registry also holds a placeholder `default` that throws, so code must not pick from it by name.
|
|
139
|
+
*/
|
|
140
|
+
declare function selectDefaultDatabase(useDatabase: () => {
|
|
141
|
+
db: WebhooksDatabase;
|
|
142
|
+
}): WebhooksDatabase;
|
|
143
|
+
/** Sends a body to a webhook. `sendWebhook()` of `@vite-hub/webhooks` calls it with a typed name. */
|
|
144
|
+
declare function sendDynamicWebhook(name: string, body: unknown, options: {
|
|
145
|
+
event: string;
|
|
146
|
+
key?: string;
|
|
147
|
+
}): Promise<Result<SendWebhookResult, SendWebhookErrorCode>>;
|
|
148
|
+
/** The event of a test delivery. */
|
|
149
|
+
declare const webhookTestEvent = "webhooks.test";
|
|
150
|
+
/**
|
|
151
|
+
* Sends a test delivery to a webhook now, without its debounce and apart from the pending sends, with the event
|
|
152
|
+
* `webhooks.test`. Use it to check the URL, the secret, and the receiver. The default body is
|
|
153
|
+
* `{ test: true, webhook: name }`. An unknown name throws.
|
|
154
|
+
*/
|
|
155
|
+
declare function testWebhook(name: string, options?: {
|
|
156
|
+
body?: unknown;
|
|
157
|
+
}): Promise<Result<SendWebhookResult, SendWebhookErrorCode>>;
|
|
158
|
+
/**
|
|
159
|
+
* The Queue handler of `vitehub-webhooks`. It posts the delivery of a wake when the wake carries the latest revision and
|
|
160
|
+
* the delivery is pending. A 2xx answer marks it `sent`. Any other answer throws, so the Queue tries again, until the
|
|
161
|
+
* last attempt marks it `dead`. A wake that is out of date does nothing.
|
|
162
|
+
*/
|
|
163
|
+
declare function deliverWebhookWake(payload: unknown): Promise<void>;
|
|
164
|
+
/** Every webhook of the app, with the names of its variables and whether they are set. */
|
|
165
|
+
declare function listWebhooks(): WebhookInfo[];
|
|
166
|
+
/** Deliveries, newest first. */
|
|
167
|
+
declare function listWebhookDeliveries(options?: ListWebhookDeliveriesOptions): Promise<Result<WebhookDelivery[], WebhookDeliveryErrorCode>>;
|
|
168
|
+
/** Pending deliveries, the soonest due first: the debounce timers that run now. */
|
|
169
|
+
declare function listPendingWebhookDeliveries(options?: {
|
|
170
|
+
webhook?: string;
|
|
171
|
+
limit?: number;
|
|
172
|
+
}): Promise<Result<WebhookDelivery[], WebhookDeliveryErrorCode>>;
|
|
173
|
+
declare function getWebhookDelivery(id: string): Promise<Result<WebhookDelivery, WebhookDeliveryErrorCode>>;
|
|
174
|
+
/** Delivers a pending delivery now, without the rest of its debounce. */
|
|
175
|
+
declare function flushWebhookDelivery(id: string): Promise<Result<WebhookDelivery, WebhookDeliveryErrorCode>>;
|
|
176
|
+
/** Cancels a pending delivery. Its wake then does nothing. */
|
|
177
|
+
declare function cancelWebhookDelivery(id: string): Promise<Result<WebhookDelivery, WebhookDeliveryErrorCode>>;
|
|
178
|
+
/**
|
|
179
|
+
* Sends a sent, dead, or cancelled delivery again, now, as a new delivery with a new id. It keeps the body, the event,
|
|
180
|
+
* and the count. The webhook must still exist.
|
|
181
|
+
*/
|
|
182
|
+
declare function redeliverWebhookDelivery(id: string): Promise<Result<SendWebhookResult, WebhookDeliveryErrorCode>>;
|
|
183
|
+
//#endregion
|
|
184
|
+
export { WebhookDeliveryErrorCode as A, webhookTimeoutMs as C, WebhookSignature as D, WebhookOptions as E, defineWebhook as O, webhookTestEvent as S, WebhookEvent as T, redeliverWebhookDelivery as _, WebhookInfo as a, testWebhook as b, cancelWebhookDelivery as c, getWebhookDelivery as d, installWebhooks as f, listWebhooks as g, listWebhookDeliveries as h, WebhookEventBody as i, SendWebhookErrorCode as k, deliverWebhookWake as l, listPendingWebhookDeliveries as m, InstalledWebhooks as n, WebhookWake as o, installedWebhooks as p, SendWebhookResult as r, WebhookWakeSender as s, InstallWebhooksOptions as t, flushWebhookDelivery as u, selectDefaultDatabase as v, WebhookDefinition as w, webhookMaxAttempts as x, sendDynamicWebhook as y };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { C as webhookTimeoutMs, S as webhookTestEvent, _ as redeliverWebhookDelivery, a as WebhookInfo, b as testWebhook, c as cancelWebhookDelivery, d as getWebhookDelivery, f as installWebhooks, g as listWebhooks, h as listWebhookDeliveries, i as WebhookEventBody, l as deliverWebhookWake, m as listPendingWebhookDeliveries, n as InstalledWebhooks, o as WebhookWake, p as installedWebhooks, r as SendWebhookResult, s as WebhookWakeSender, t as InstallWebhooksOptions, u as flushWebhookDelivery, v as selectDefaultDatabase, x as webhookMaxAttempts, y as sendDynamicWebhook } from "./runtime-mqwMGfyX.js";
|
|
2
|
+
import { t as webhooksQueueName } from "./queue-name-CGeTSHId.js";
|
|
3
|
+
export { InstallWebhooksOptions, InstalledWebhooks, SendWebhookResult, WebhookEventBody, WebhookInfo, WebhookWake, WebhookWakeSender, cancelWebhookDelivery, deliverWebhookWake, flushWebhookDelivery, getWebhookDelivery, installWebhooks, installedWebhooks, listPendingWebhookDeliveries, listWebhookDeliveries, listWebhooks, redeliverWebhookDelivery, selectDefaultDatabase, sendDynamicWebhook, testWebhook, webhookMaxAttempts, webhookTestEvent, webhookTimeoutMs, webhooksQueueName };
|