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