@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.
package/dist/vite.d.ts ADDED
@@ -0,0 +1,299 @@
1
+ import { t as webhooksQueueName } from "./queue-name-CGeTSHId.js";
2
+ import { n as OperationContributions } from "./operations-D4A1Fcgf.js";
3
+ import { Plugin } from "vite";
4
+ //#region ../internal/src/console.d.ts
5
+ /** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
6
+ interface ViteHubConsoleDefinitionCatalogView {
7
+ kind: "definition-catalog";
8
+ /** States which runtime data this catalog does not include. */
9
+ notice: string;
10
+ }
11
+ /** Lists Workspace Definitions like a catalog, and browses the refs, revisions, and files of the selected one. */
12
+ interface ViteHubConsoleWorkspaceBrowserView {
13
+ kind: "workspace-browser";
14
+ /** States which runtime data the browser does not include. */
15
+ notice: string;
16
+ }
17
+ interface ViteHubConsoleRecordColumn {
18
+ /** Set it for a column with few values, such as a status. The Console then filters the table by its values. */
19
+ filter?: boolean;
20
+ /** Key in `ViteHubConsoleRecord.cells`. */
21
+ key: string;
22
+ label: string;
23
+ }
24
+ /** Shows records in a table and the selected record's fields in a detail panel. */
25
+ interface ViteHubConsoleRecordTableView {
26
+ columns: readonly ViteHubConsoleRecordColumn[];
27
+ kind: "record-table";
28
+ /** States the source and limits of the records. */
29
+ notice: string;
30
+ }
31
+ /**
32
+ * Lists the collections and documents of an owner runtime and edits them with owner actions: a form generated from each
33
+ * collection's JSON Schema, a Markdown body, save, publish, and revision history.
34
+ */
35
+ interface ViteHubConsoleDocumentEditorView {
36
+ kind: "document-editor";
37
+ /** States where documents are stored and what the editor does not do. */
38
+ notice: string;
39
+ }
40
+ interface ViteHubConsoleOperationColumn {
41
+ /** Dot path into each item of the result, such as `author.name` or `messages.0.body`. */
42
+ key: string;
43
+ label: string;
44
+ /**
45
+ * `datetime` shows a time in milliseconds since the epoch as a relative date, such as `5m ago`. `excerpt` cuts a long
46
+ * text. `status` shows the value as a status with a colored dot, such as `Open`. `tones` picks the color of each value.
47
+ * `switch` shows a boolean as a switch that calls the `switch` operation.
48
+ */
49
+ format?: "datetime" | "excerpt" | "status" | "switch";
50
+ /** The color of each value of a `status` column, such as `{ open: "info", resolved: "success" }`. Other values are neutral. */
51
+ tones?: Readonly<Record<string, "error" | "info" | "neutral" | "success" | "warning">>;
52
+ /**
53
+ * What a `switch` column calls when the user flips it: `operation` with an input that maps each key of `input` to a
54
+ * dot path of the item, and the column `key` to the new value. `{ operation: "skills.set", input: { name: "name" } }`
55
+ * on the column `enabled` calls `skills.set` with `{ name, enabled }`, then loads the list again. A user who may only
56
+ * read the section sees the switch disabled.
57
+ */
58
+ switch?: {
59
+ operation: string;
60
+ input: Readonly<Record<string, string>>;
61
+ };
62
+ }
63
+ /**
64
+ * A button on each row that calls `operation` with the Console user, then loads the list again. `input` maps each input
65
+ * key to a dot path of the item, as a `switch` column does.
66
+ */
67
+ interface ViteHubConsoleOperationAction {
68
+ label: string;
69
+ operation: string;
70
+ input: Readonly<Record<string, string>>;
71
+ /**
72
+ * The result is `{ url }`, such as a one-time link or a provider sign-in: the Console opens it in a new tab, and loads
73
+ * the list again when the person comes back. The URL must be `https:`, or `http:` on a loopback host.
74
+ */
75
+ tab?: true;
76
+ /** Show the button only on rows where each dot path holds one of the listed values. */
77
+ when?: Readonly<Record<string, readonly string[]>>;
78
+ /** Ask this question before the call. `{path}` takes a value from the item. */
79
+ confirm?: string;
80
+ }
81
+ /** A chip above the list. Choosing it merges `input` into the operation input. The first chip is the default. */
82
+ interface ViteHubConsoleOperationFilter {
83
+ id: string;
84
+ label: string;
85
+ input: Readonly<Record<string, unknown>>;
86
+ }
87
+ /**
88
+ * Lists the items that an operation returns, called over the Console RPC with the signed-in Console user. The operation
89
+ * checks the access of that user for each item, so the view shows only what the user may read. `operation` must return an
90
+ * array of objects with an `id`. A failure of the operation, with its `fix`, shows where the list would be.
91
+ */
92
+ interface ViteHubConsoleOperationView {
93
+ /** Buttons on each row. A user who may only read the section does not see them. */
94
+ actions?: readonly ViteHubConsoleOperationAction[];
95
+ columns: readonly ViteHubConsoleOperationColumn[];
96
+ /**
97
+ * Opens the item of a row in a side panel. `comment-thread` shows an item of `comments.list` as a comment thread
98
+ * where the user reads, replies, resolves, reopens, and mentions people. The panel calls the `comments.*` operations
99
+ * with the Console user, and `?thread=<id>` in the URL opens it.
100
+ */
101
+ detail?: {
102
+ kind: "comment-thread";
103
+ };
104
+ filters?: readonly ViteHubConsoleOperationFilter[];
105
+ kind: "operation-view";
106
+ /**
107
+ * Makes each row a link: `{path}` placeholders take values from the item and are URL-encoded, and `{path:path}` takes an
108
+ * app path and encodes each segment (a value that is not an app path, such as `//evil.com/x`, gives no link).
109
+ * `{path:href}` takes an app URL that is already encoded, with its query, as it is. Rows where `when.path` is not
110
+ * `when.equals` get none.
111
+ */
112
+ link?: {
113
+ label?: string;
114
+ template: string;
115
+ when?: {
116
+ equals: string;
117
+ path: string;
118
+ };
119
+ };
120
+ notice: string;
121
+ /** Operation name, such as `comments.list`. */
122
+ operation: string;
123
+ /** Fetch every page with `limit` and a `before` object whose keys read these dot paths from the last item. */
124
+ pagination?: {
125
+ limit: number;
126
+ cursor: Readonly<Record<string, string>>;
127
+ };
128
+ }
129
+ interface ViteHubConsoleAuthView {
130
+ kind: "auth-management";
131
+ notice: string;
132
+ }
133
+ /**
134
+ * The webhooks of the app, their pending debounce timers, and their delivery log. The Console calls the `webhooks.*`
135
+ * operations of `@vite-hub/webhooks` with the Console user to list them, send a test, send a pending delivery now,
136
+ * cancel it, and redeliver. It has no build-time data.
137
+ */
138
+ interface ViteHubConsoleWebhooksView {
139
+ kind: "webhooks";
140
+ notice: string;
141
+ }
142
+ interface ViteHubConsoleWebhooksSection extends ViteHubConsoleSectionDescriptor<ViteHubConsoleWebhooksView> {}
143
+ type ViteHubConsoleSectionView = ViteHubConsoleOperationView | ViteHubConsoleAuthView | ViteHubConsoleWebhooksView | ViteHubConsoleDefinitionCatalogView | ViteHubConsoleRecordTableView | ViteHubConsoleDocumentEditorView | ViteHubConsoleWorkspaceBrowserView;
144
+ /**
145
+ * The overview of a document editor section: document counts by state, the changes that wait for a publish, recent
146
+ * activity, and a New button per collection. It reads the owner `overview` action.
147
+ */
148
+ interface ViteHubConsoleDocumentDashboardView {
149
+ kind: "document-dashboard";
150
+ }
151
+ /**
152
+ * The media library of a document editor section: folders, uploads, alt text, focal points, and crops of the Blob Store
153
+ * that `blob.serve` serves. The owner decides who may use it with `mediaAccess`, and finds the documents that use a file
154
+ * with `references`. The page needs the Blob section, so declare it with `requires: ["blob"]`.
155
+ */
156
+ interface ViteHubConsoleMediaLibraryView {
157
+ kind: "media-library";
158
+ }
159
+ /**
160
+ * The singletons of a document editor section, such as site settings: one row per singleton that opens it in the
161
+ * editor. Singletons appear here instead of among the collections, and the Console hides the page when the section has
162
+ * none.
163
+ */
164
+ interface ViteHubConsoleDocumentSettingsView {
165
+ kind: "document-settings";
166
+ }
167
+ /** A view that the Console UI in `vite-hub` renders for a section page. */
168
+ type ViteHubConsoleSectionPageView = ViteHubConsoleDocumentDashboardView | ViteHubConsoleDocumentSettingsView | ViteHubConsoleMediaLibraryView;
169
+ /**
170
+ * A page of a section next to its main view, such as the Content dashboard or media library. The section sidebar lists
171
+ * the pages, and each page has its own URL:
172
+ *
173
+ * - `/_vitehub/<section>` serves the `index` page, or the main view when the section has none.
174
+ * - `/_vitehub/<section>/-/<page>` serves every other page. The `-` segment keeps page URLs apart from the main view's
175
+ * own segments, such as a collection name.
176
+ *
177
+ * Pages share the access of their section: `console.authorize` that allows the section allows every page of it.
178
+ */
179
+ interface ViteHubConsoleSectionPage {
180
+ /** Lowercase route segment, for example `media`. */
181
+ id: string;
182
+ /** Display name, for example `Media`. */
183
+ label: string;
184
+ /** Iconify class name, for example `i-lucide-image`. */
185
+ icon: string;
186
+ view: ViteHubConsoleSectionPageView;
187
+ /**
188
+ * Serve this page at the section root. At most one page sets it, and `/_vitehub/<section>/-/<id>` then redirects to
189
+ * the root.
190
+ */
191
+ index?: boolean;
192
+ /**
193
+ * Sidebar heading, for example `Assets`. Pages without a group lead the sidebar, above the main view's navigation.
194
+ * Grouped pages follow it, in the order their group first appears.
195
+ */
196
+ group?: string;
197
+ /** Section ids that the project must enable, such as `["blob"]`. The Console leaves the page out otherwise. */
198
+ requires?: readonly string[];
199
+ }
200
+ /** Serializable description of a Console section. The Console UI in `vite-hub` renders the view. */
201
+ interface ViteHubConsoleSectionDescriptor<TView extends ViteHubConsoleSectionView = ViteHubConsoleSectionView> {
202
+ description: string;
203
+ /**
204
+ * Iconify class name, for example `i-lucide-inbox`. The Console draws with Lucide; `ph` also resolves. The
205
+ * Console build bundles the icon of every section in the `vite-hub` Console registry and fails if it cannot resolve one.
206
+ */
207
+ icon: string;
208
+ /** Lowercase route segment, for example `queues`. The Console serves the section at `/_vitehub/<id>`. */
209
+ id: string;
210
+ /** Plural display name, for example `Queues`. */
211
+ label: string;
212
+ view: TView;
213
+ /** Pages next to the main view, in sidebar order. Only document editor sections render pages today. */
214
+ pages?: readonly ViteHubConsoleSectionPage[];
215
+ }
216
+ //#endregion
217
+ //#region src/console.d.ts
218
+ /**
219
+ * Console section for the webhooks of `server/webhooks/`: each endpoint, the pending debounce timers, and the delivery
220
+ * log, with Send test, Send now, Cancel, and Redeliver. It calls the `webhooks.*` operations with the Console user.
221
+ */
222
+ export declare const webhooksConsoleSection: ViteHubConsoleWebhooksSection;
223
+ //#endregion
224
+ //#region src/vite.d.ts
225
+ export declare const WEBHOOKS_VITE_PLUGIN_NAME = "@vite-hub/webhooks/vite";
226
+ /** One file of `server/webhooks/`. */
227
+ export interface DiscoveredWebhook {
228
+ name: string;
229
+ file: string;
230
+ }
231
+ /** The webhooks of `<serverDir>/webhooks/<name>.ts`. A name is lowercase letters, digits, and dashes. */
232
+ export declare function discoverWebhooks(projectRoot: string, serverDirs?: readonly string[]): DiscoveredWebhook[];
233
+ /** Whether the app has a webhook. */
234
+ export declare function usesWebhooks(options: {
235
+ projectRoot: string;
236
+ serverDirs?: readonly string[];
237
+ }): boolean;
238
+ /** The module specifiers that the generated code imports. `vite-hub` passes its own subpaths. */
239
+ export interface WebhooksImports {
240
+ /** `installWebhooks` and `deliverWebhookWake`. */
241
+ runtime: string;
242
+ /** `webhooksOperations`: the operations of the Console, `vitehub webhooks`, and MCP. */
243
+ operations: string;
244
+ /** `createDrizzleWebhookStore` and `webhooksSchema`. */
245
+ database: string;
246
+ /** The Database registry of the app, with `useDatabase()`. */
247
+ databases: string;
248
+ /** `defineQueue` and `dynamicQueue`. */
249
+ queue: string;
250
+ /** The module whose `WebhookRegistry` the generated types extend. */
251
+ types: string;
252
+ }
253
+ export interface HubWebhooksOptions {
254
+ imports?: Partial<WebhooksImports>;
255
+ /** The app has a ViteHub Database. Webhooks keeps each delivery in its Default Database. */
256
+ database?: boolean;
257
+ /** The app has ViteHub Queue. Webhooks delivers through its `vitehub-webhooks` Queue. */
258
+ queue?: boolean;
259
+ }
260
+ /** The files that `hubWebhooks()` writes in `<projectRoot>/.vitehub`. */
261
+ export declare function webhooksGeneratedFiles(projectRoot: string): {
262
+ directory: string;
263
+ registry: string;
264
+ queue: string;
265
+ plugin: string;
266
+ types: string;
267
+ };
268
+ /** The generated module that installs the webhooks. The Queue handler and the Nitro plugin import it. */
269
+ export declare function renderWebhooksRegistry(webhooks: readonly DiscoveredWebhook[], imports: WebhooksImports): string;
270
+ /** The Queue Definition of `vitehub-webhooks`, which Webhooks contributes to the Queue. */
271
+ export declare function renderWebhooksQueue(imports: WebhooksImports): string;
272
+ /** The webhook names for `sendWebhook()`, from the files of `server/webhooks/`. */
273
+ export declare function renderWebhooksTypes(file: string, webhooks: readonly DiscoveredWebhook[], typesImport: string): string;
274
+ interface ContributionContext {
275
+ projectRoot?: string;
276
+ root?: string;
277
+ rootDir?: string;
278
+ serverDirs?: readonly string[];
279
+ }
280
+ /**
281
+ * Webhooks in a ViteHub app: each `server/webhooks/<name>.ts` that default-exports `defineWebhook()` gets a name for
282
+ * `sendWebhook()`. Deliveries go to the `vitehub_webhook_deliveries` table of the Default Database and out through the
283
+ * `vitehub-webhooks` Queue, which this plugin contributes. Both features must be on.
284
+ */
285
+ export declare function hubWebhooks(options?: HubWebhooksOptions): Plugin & {
286
+ vitehub: {
287
+ databases: (context: ContributionContext) => unknown[];
288
+ queues: (context: ContributionContext) => Array<{
289
+ name: string;
290
+ definition: {
291
+ module: string;
292
+ };
293
+ reason: string;
294
+ }>;
295
+ operations: OperationContributions;
296
+ };
297
+ };
298
+ //#endregion
299
+ export { webhooksQueueName };
package/dist/vite.js ADDED
@@ -0,0 +1,328 @@
1
+ import { t as webhooksErrors } from "./errors-DtL3aUWW.js";
2
+ import { t as webhooksQueueName } from "./queue-name-RURp9SQf.js";
3
+ import { t as webhooksTableNames } from "./table-names-DVvicXhh.js";
4
+ import { t as isRecordOrFunction } from "./object-BJb1W_q5.js";
5
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { basename, dirname, join, parse, relative, resolve } from "node:path";
8
+ //#region ../internal/src/build/vite.ts
9
+ const projectRootDirectoryMarkers = [
10
+ ["server", "agents"],
11
+ ["server", "channels"],
12
+ ["server", "connections"],
13
+ ["server", "browsers"],
14
+ ["server", "emails"],
15
+ ["server", "schedules"],
16
+ ["server", "workspaces"]
17
+ ];
18
+ const projectRootFileMarkers = [
19
+ ["package.json"],
20
+ ["nuxt.config.ts"],
21
+ ["nuxt.config.mts"],
22
+ ["nuxt.config.js"],
23
+ ["nuxt.config.mjs"]
24
+ ];
25
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
26
+ /**
27
+ * Server directories that ViteHub scans for Definitions. The first entry is the application.
28
+ * Later entries are Nuxt layers in Nuxt priority order.
29
+ */
30
+ const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
31
+ function resolveViteHubProjectRoot(root, options = {}) {
32
+ const resolvedRoot = resolve(root);
33
+ const temporaryRoot = resolve(tmpdir());
34
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
35
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
36
+ if (basename(resolvedRoot) === "app") {
37
+ const parent = dirname(resolvedRoot);
38
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
39
+ "nuxt.config.ts",
40
+ "nuxt.config.mts",
41
+ "nuxt.config.js",
42
+ "nuxt.config.mjs"
43
+ ]))) return parent;
44
+ }
45
+ let current = resolvedRoot;
46
+ while (true) {
47
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
48
+ if (hasProjectRootMarker(current)) return current;
49
+ const parent = dirname(current);
50
+ if (parent === current) return resolvedRoot;
51
+ current = parent;
52
+ }
53
+ }
54
+ function hasProjectRootDirectoryMarker(root) {
55
+ for (const marker of projectRootDirectoryMarkers) try {
56
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
57
+ } catch (error) {
58
+ if (error.code !== "ENOENT") throw error;
59
+ }
60
+ return false;
61
+ }
62
+ function hasProjectRootMarker(root) {
63
+ if (hasProjectRootDirectoryMarker(root)) return true;
64
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
65
+ }
66
+ function hasProjectRootFileMarker(root, markers) {
67
+ for (const marker of markers) {
68
+ const path = Array.isArray(marker) ? marker : [marker];
69
+ try {
70
+ if (statSync(resolve(root, ...path)).isFile()) return true;
71
+ } catch (error) {
72
+ if (error.code !== "ENOENT") throw error;
73
+ }
74
+ }
75
+ return false;
76
+ }
77
+ //#endregion
78
+ //#region ../internal/src/definition-catalog.ts
79
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
80
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
81
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
82
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
83
+ function isDefinitionSourceFile(name) {
84
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
85
+ }
86
+ //#endregion
87
+ //#region ../internal/src/nitro-kit.ts
88
+ function cloneArray(value) {
89
+ return Array.isArray(value) ? [...value] : [];
90
+ }
91
+ function sameHandler(left, right) {
92
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
93
+ }
94
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
95
+ function createNitroServerKit(value = {}) {
96
+ const config = isRecordOrFunction(value) ? { ...value } : {};
97
+ const handlers = cloneArray(config.handlers);
98
+ const plugins = cloneArray(config.plugins);
99
+ config.handlers = handlers;
100
+ config.plugins = plugins;
101
+ return {
102
+ config,
103
+ addHandler(handler, position = "end") {
104
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
105
+ if (position === "start") handlers.unshift({ ...handler });
106
+ else handlers.push({ ...handler });
107
+ },
108
+ addPlugin(plugin, position = "end") {
109
+ if (plugins.includes(plugin)) return;
110
+ if (position === "start") plugins.unshift(plugin);
111
+ else plugins.push(plugin);
112
+ }
113
+ };
114
+ }
115
+ //#endregion
116
+ //#region src/console.ts
117
+ /**
118
+ * Console section for the webhooks of `server/webhooks/`: each endpoint, the pending debounce timers, and the delivery
119
+ * log, with Send test, Send now, Cancel, and Redeliver. It calls the `webhooks.*` operations with the Console user.
120
+ */
121
+ const webhooksConsoleSection = {
122
+ description: "See, test, flush, and redeliver the webhooks that the app sends.",
123
+ icon: "i-vitehub-webhooks",
124
+ id: "webhooks",
125
+ label: "Webhooks",
126
+ view: {
127
+ kind: "webhooks",
128
+ notice: "The list comes from the webhooks.* operations. The Console shows the names of the URL and secret variables and the URL host, never the full URL or the secret. `vitehub webhooks` and the webhooks MCP tools do the same."
129
+ }
130
+ };
131
+ //#endregion
132
+ //#region src/vite.ts
133
+ const WEBHOOKS_VITE_PLUGIN_NAME = "@vite-hub/webhooks/vite";
134
+ const extensions = [
135
+ ".ts",
136
+ ".mts",
137
+ ".js",
138
+ ".mjs"
139
+ ];
140
+ const namePattern = /^[a-z0-9][a-z0-9-]*$/;
141
+ /** The webhooks of `<serverDir>/webhooks/<name>.ts`. A name is lowercase letters, digits, and dashes. */
142
+ function discoverWebhooks(projectRoot, serverDirs = ["server"]) {
143
+ const found = /* @__PURE__ */ new Map();
144
+ for (const directory of serverDirs) {
145
+ const folder = resolve(projectRoot, directory, "webhooks");
146
+ if (!existsSync(folder)) continue;
147
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
148
+ const extension = extensions.find((candidate) => entry.name.endsWith(candidate));
149
+ if (!entry.isFile() || !extension || !isDefinitionSourceFile(entry.name)) continue;
150
+ const name = entry.name.slice(0, -extension.length);
151
+ const file = join(folder, entry.name);
152
+ if (!namePattern.test(name)) throw webhooksErrors.WEBHOOKS_FILE_INVALID({ message: `[vitehub] The webhook ${relative(projectRoot, file)} needs a name of lowercase letters, digits, and dashes, such as t3 or slack-alerts.` });
153
+ const existing = found.get(name);
154
+ if (existing) throw webhooksErrors.WEBHOOKS_FILE_INVALID({ message: `[vitehub] Two files define the webhook ${JSON.stringify(name)}: ${relative(projectRoot, existing.file)} and ${relative(projectRoot, file)}.` });
155
+ found.set(name, {
156
+ name,
157
+ file
158
+ });
159
+ }
160
+ }
161
+ return [...found.values()].sort((left, right) => left.name.localeCompare(right.name));
162
+ }
163
+ /** Whether the app has a webhook. */
164
+ function usesWebhooks(options) {
165
+ return discoverWebhooks(options.projectRoot, options.serverDirs).length > 0;
166
+ }
167
+ const defaultImports = {
168
+ runtime: "@vite-hub/webhooks/runtime",
169
+ operations: "@vite-hub/webhooks/operations",
170
+ database: "@vite-hub/webhooks/database",
171
+ databases: "@vite-hub/database/runtime/registry",
172
+ queue: "@vite-hub/queue",
173
+ types: "@vite-hub/webhooks"
174
+ };
175
+ /** The files that `hubWebhooks()` writes in `<projectRoot>/.vitehub`. */
176
+ function webhooksGeneratedFiles(projectRoot) {
177
+ const directory = resolve(projectRoot, ".vitehub/nitro/webhooks");
178
+ return {
179
+ directory,
180
+ registry: join(directory, "registry.mjs"),
181
+ queue: join(directory, "queue.mjs"),
182
+ plugin: join(directory, "plugin.mjs"),
183
+ types: resolve(projectRoot, ".vitehub/webhooks.d.ts")
184
+ };
185
+ }
186
+ /** The generated module that installs the webhooks. The Queue handler and the Nitro plugin import it. */
187
+ function renderWebhooksRegistry(webhooks, imports) {
188
+ return [
189
+ `import { installWebhooks, selectDefaultDatabase } from ${JSON.stringify(imports.runtime)}`,
190
+ `import { createDrizzleWebhookStore } from ${JSON.stringify(imports.database)}`,
191
+ `import { useDatabase } from ${JSON.stringify(imports.databases)}`,
192
+ `import { dynamicQueue } from ${JSON.stringify(imports.queue)}`,
193
+ ...webhooks.map((webhook, index) => `import webhook${index} from ${JSON.stringify(webhook.file)}`),
194
+ "",
195
+ "installWebhooks({",
196
+ ` webhooks: { ${webhooks.map((webhook, index) => `${JSON.stringify(webhook.name)}: webhook${index}`).join(", ")} },`,
197
+ " store: createDrizzleWebhookStore(() => selectDefaultDatabase(() => useDatabase())),",
198
+ ` wake: (wake, options) => dynamicQueue.send(${JSON.stringify(webhooksQueueName)}, wake, options),`,
199
+ "})",
200
+ ""
201
+ ].join("\n");
202
+ }
203
+ /** The Queue Definition of `vitehub-webhooks`, which Webhooks contributes to the Queue. */
204
+ function renderWebhooksQueue(imports) {
205
+ return [
206
+ `import { defineQueue } from ${JSON.stringify(imports.queue)}`,
207
+ `import { deliverWebhookWake } from ${JSON.stringify(imports.runtime)}`,
208
+ "import \"./registry.mjs\"",
209
+ "",
210
+ "// A slow receiver must not hold back the deliveries of other webhooks.",
211
+ "export default defineQueue(job => deliverWebhookWake(job.payload), { concurrency: 4 })",
212
+ ""
213
+ ].join("\n");
214
+ }
215
+ /** The webhook names for `sendWebhook()`, from the files of `server/webhooks/`. */
216
+ function renderWebhooksTypes(file, webhooks, typesImport) {
217
+ const entries = webhooks.map((webhook) => {
218
+ const path = relative(dirname(file), webhook.file).replaceAll("\\", "/");
219
+ return ` ${JSON.stringify(webhook.name)}: typeof import(${JSON.stringify(path.startsWith(".") ? path : `./${path}`)}).default`;
220
+ });
221
+ return [
222
+ `import ${JSON.stringify(typesImport)}`,
223
+ `declare module ${JSON.stringify(typesImport)} {`,
224
+ " interface WebhookRegistry {",
225
+ ...entries,
226
+ " }",
227
+ "}",
228
+ ""
229
+ ].join("\n");
230
+ }
231
+ function writeIfChanged(file, contents) {
232
+ if (existsSync(file) && readFileSync(file, "utf8") === contents) return;
233
+ mkdirSync(dirname(file), { recursive: true });
234
+ writeFileSync(file, contents);
235
+ }
236
+ /** Writes the generated files of the webhooks, or removes them when the app has none. Returns the files. */
237
+ function writeWebhooksFiles(projectRoot, webhooks, imports) {
238
+ const files = webhooksGeneratedFiles(projectRoot);
239
+ if (!webhooks.length) {
240
+ rmSync(files.directory, {
241
+ force: true,
242
+ recursive: true
243
+ });
244
+ rmSync(files.types, { force: true });
245
+ return files;
246
+ }
247
+ writeIfChanged(files.registry, renderWebhooksRegistry(webhooks, imports));
248
+ writeIfChanged(files.queue, renderWebhooksQueue(imports));
249
+ writeIfChanged(files.plugin, "import \"./registry.mjs\"\n\nexport default () => {}\n");
250
+ writeIfChanged(files.types, renderWebhooksTypes(files.types, webhooks, imports.types));
251
+ return files;
252
+ }
253
+ /**
254
+ * Webhooks in a ViteHub app: each `server/webhooks/<name>.ts` that default-exports `defineWebhook()` gets a name for
255
+ * `sendWebhook()`. Deliveries go to the `vitehub_webhook_deliveries` table of the Default Database and out through the
256
+ * `vitehub-webhooks` Queue, which this plugin contributes. Both features must be on.
257
+ */
258
+ function hubWebhooks(options = {}) {
259
+ const imports = {
260
+ ...defaultImports,
261
+ ...options.imports
262
+ };
263
+ let projectRoot;
264
+ let serverDirs;
265
+ const project = (context) => ({
266
+ projectRoot: projectRoot ?? context.projectRoot ?? context.rootDir ?? context.root ?? process.cwd(),
267
+ serverDirs: serverDirs ?? context.serverDirs
268
+ });
269
+ return {
270
+ name: WEBHOOKS_VITE_PLUGIN_NAME,
271
+ enforce: "pre",
272
+ vitehub: {
273
+ operations: () => usesWebhooks(project({})) ? [{
274
+ export: "webhooksOperations",
275
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).webhooksOperations,
276
+ module: imports.operations
277
+ }] : [],
278
+ databases(context) {
279
+ const { projectRoot: root, serverDirs: dirs } = project(context);
280
+ if (!options.database || !usesWebhooks({
281
+ projectRoot: root,
282
+ ...dirs ? { serverDirs: dirs } : {}
283
+ })) return [];
284
+ return [{
285
+ definition: {
286
+ export: "webhooksSchema",
287
+ module: imports.database
288
+ },
289
+ dialect: "sqlite",
290
+ tables: webhooksTableNames,
291
+ name: "webhooks",
292
+ reason: "Keeps the deliveries of `server/webhooks/`."
293
+ }];
294
+ },
295
+ queues(context) {
296
+ const { projectRoot: root, serverDirs: dirs } = project(context);
297
+ const webhooks = discoverWebhooks(root, dirs);
298
+ if (!webhooks.length || !options.queue || !options.database) return [];
299
+ const files = writeWebhooksFiles(root, webhooks, imports);
300
+ return [{
301
+ name: webhooksQueueName,
302
+ definition: { module: files.queue },
303
+ reason: "Delivers the webhooks of `server/webhooks/`."
304
+ }];
305
+ }
306
+ },
307
+ config: { handler(config) {
308
+ const configuredRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
309
+ projectRoot = typeof configuredRoot === "string" ? resolve(configuredRoot) : resolveViteHubProjectRoot(resolve(config.root ?? process.cwd()));
310
+ const dirs = Reflect.get(config, VITEHUB_SERVER_DIRS);
311
+ serverDirs = Array.isArray(dirs) ? dirs.filter((dir) => typeof dir === "string") : void 0;
312
+ const root = projectRoot;
313
+ const webhooks = discoverWebhooks(root, serverDirs);
314
+ if (webhooks.length) {
315
+ const listed = webhooks.map((webhook) => relative(root, webhook.file)).join(", ");
316
+ if (!options.queue) throw webhooksErrors.WEBHOOKS_QUEUE_OFF({ files: listed });
317
+ if (!options.database) throw webhooksErrors.WEBHOOKS_DATABASE_OFF({ files: listed });
318
+ }
319
+ const files = writeWebhooksFiles(root, webhooks, imports);
320
+ if (!webhooks.length) return;
321
+ const kit = createNitroServerKit(Reflect.get(config, "nitro"));
322
+ kit.addPlugin(files.plugin);
323
+ Reflect.set(config, "nitro", kit.config);
324
+ } }
325
+ };
326
+ }
327
+ //#endregion
328
+ export { WEBHOOKS_VITE_PLUGIN_NAME, discoverWebhooks, hubWebhooks, renderWebhooksQueue, renderWebhooksRegistry, renderWebhooksTypes, usesWebhooks, webhooksConsoleSection, webhooksGeneratedFiles, webhooksQueueName };