@vite-hub/webhooks 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { n as isRecordOrFunction, t as isRecord } from "./object-CAK6UYR5.js";
2
- import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
3
- import { t as webhooksQueueName } from "./queue-name-jmgeppja.js";
2
+ import { i as resolveWebhooksRetention, t as webhooksQueueName } from "./queue-name-BL96iCCH.js";
3
+ import { t as webhooksErrors } from "./errors-8u_DGHUd.js";
4
4
  import { n as webhooksTableNames, t as webhookEndpointsTableNames } from "./table-names-DAUip4v2.js";
5
5
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
8
8
  import { mkdir, writeFile } from "node:fs/promises";
9
+ import { env } from "@vite-hub/env/vite";
10
+ import { parseSync } from "vite";
9
11
  // ../internal/src/build/vite.ts
10
12
  const projectRootDirectoryMarkers = [
11
13
  ["server", "agents"],
@@ -29,6 +31,11 @@ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
29
31
  * Later entries are Nuxt layers in Nuxt priority order.
30
32
  */
31
33
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
34
+ /**
35
+ * Server Env declarations that ViteHub features add before `hubEnv()` builds the registry, such as the Server Env of
36
+ * discovered Channels. The application's `env.server` wins field by field.
37
+ */
38
+ const VITEHUB_ENV_SERVER = "__vitehubEnvServer";
32
39
  function resolveViteHubProjectRoot(root, options = {}) {
33
40
  const resolvedRoot = resolve(root);
34
41
  const temporaryRoot = resolve(tmpdir());
@@ -79,6 +86,177 @@ function isMissingProjectMarker(error) {
79
86
  const code = error.code;
80
87
  return code === "ENOENT" || code === "ENOTDIR";
81
88
  }
89
+ // ../internal/src/build/ast-walk.ts
90
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
91
+ function moduleLanguage(file) {
92
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
93
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
94
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
95
+ return "ts";
96
+ }
97
+ // ../internal/src/build/scan-module.ts
98
+ /**
99
+ * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
100
+ * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
101
+ * `dynamic`, so callers can report their own diagnostics.
102
+ */
103
+ /** The value of an expression that the scanner cannot read without running the module. */
104
+ const dynamic = Symbol("dynamic");
105
+ /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
106
+ function scanModule(source, file = "module.ts") {
107
+ const result = parseSync(file, source, {
108
+ lang: moduleLanguage(file),
109
+ preserveParens: false,
110
+ sourceType: "module"
111
+ });
112
+ return {
113
+ comments: result.comments,
114
+ errors: result.errors,
115
+ file,
116
+ program: result.program,
117
+ source
118
+ };
119
+ }
120
+ /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
121
+ function unwrapExpression(node) {
122
+ while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
123
+ return node;
124
+ }
125
+ /** A call argument without assertions, or undefined for a spread or missing argument. */
126
+ function argumentExpression(argument) {
127
+ return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
128
+ }
129
+ /** The expression of `export default <expression>`, without assertions. Declarations return undefined. */
130
+ function defaultExportExpression(module) {
131
+ for (const statement of module.program.body) {
132
+ if (statement.type !== "ExportDefaultDeclaration") continue;
133
+ const declaration = statement.declaration;
134
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") return;
135
+ return unwrapExpression(declaration);
136
+ }
137
+ }
138
+ /**
139
+ * Finds `export default defineX({ ... })` for one of `names`. With `positionalOptionsIndex`, a call whose first
140
+ * argument is not an object and that has more than one argument reads its options from that argument. Returns
141
+ * undefined when the options are not an object literal.
142
+ */
143
+ function findDefaultExportCall(module, names, options = {}) {
144
+ const call = defaultExportExpression(module);
145
+ if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || !names.includes(call.callee.name)) return;
146
+ const name = call.callee.name;
147
+ const first = argumentExpression(call.arguments[0]);
148
+ if (first?.type === "ObjectExpression") return {
149
+ call,
150
+ name,
151
+ options: first
152
+ };
153
+ if (options.positionalOptionsIndex === void 0 || first === void 0 || call.arguments.length < 2) return;
154
+ const positional = call.arguments[options.positionalOptionsIndex];
155
+ if (positional === void 0) return {
156
+ call,
157
+ name
158
+ };
159
+ const object = argumentExpression(positional);
160
+ return object?.type === "ObjectExpression" ? {
161
+ call,
162
+ name,
163
+ options: object
164
+ } : void 0;
165
+ }
166
+ function staticKey(property) {
167
+ const key = property.key;
168
+ if (key.type === "Identifier" && !property.computed) return key.name;
169
+ if (key.type === "PrivateIdentifier") return;
170
+ const value = staticValue(key);
171
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
172
+ }
173
+ /** The members of an object literal in source order. */
174
+ function objectProperties(object) {
175
+ return object.properties.map((node) => node.type === "SpreadElement" ? {
176
+ computed: false,
177
+ key: void 0,
178
+ node,
179
+ value: void 0
180
+ } : {
181
+ computed: node.computed,
182
+ key: staticKey(node),
183
+ node,
184
+ value: unwrapExpression(node.value)
185
+ });
186
+ }
187
+ /** The value of a template literal without substitutions. */
188
+ function staticTemplate(node) {
189
+ if (node.expressions.length) return dynamic;
190
+ return node.quasis[0]?.value.cooked ?? dynamic;
191
+ }
192
+ const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
193
+ /**
194
+ * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
195
+ * and accepts legacy octal escapes, so the scanner checks them again.
196
+ */
197
+ function hasInvalidEscape(raw) {
198
+ for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
199
+ const code = escape.slice(2, -1);
200
+ if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
201
+ } else if (escape.startsWith("u")) {
202
+ if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
203
+ } else if (escape.startsWith("x")) {
204
+ if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
205
+ } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
206
+ return false;
207
+ }
208
+ /**
209
+ * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
210
+ * and arrays and objects of these. Any other expression gives `dynamic`.
211
+ */
212
+ function staticValue(node) {
213
+ node = unwrapExpression(node);
214
+ switch (node.type) {
215
+ case "Literal":
216
+ if ("regex" in node) return dynamic;
217
+ return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic : node.value;
218
+ case "TemplateLiteral": return staticTemplate(node);
219
+ case "Identifier": return node.name === "undefined" ? void 0 : dynamic;
220
+ case "UnaryExpression": {
221
+ if (node.operator === "void") return staticValue(node.argument) === dynamic ? dynamic : void 0;
222
+ const value = staticValue(node.argument);
223
+ if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
224
+ return dynamic;
225
+ }
226
+ case "ArrayExpression": {
227
+ const values = [];
228
+ for (const element of node.elements) {
229
+ if (element === null || element.type === "SpreadElement") return dynamic;
230
+ const value = staticValue(element);
231
+ if (value === dynamic) return dynamic;
232
+ values.push(value);
233
+ }
234
+ return values;
235
+ }
236
+ case "ObjectExpression": {
237
+ const values = {};
238
+ for (const property of objectProperties(node)) {
239
+ if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic;
240
+ const value = staticValue(property.value);
241
+ if (value === dynamic) return dynamic;
242
+ Object.defineProperty(values, property.key, {
243
+ configurable: true,
244
+ enumerable: true,
245
+ value,
246
+ writable: true
247
+ });
248
+ }
249
+ return values;
250
+ }
251
+ default: return dynamic;
252
+ }
253
+ }
254
+ /** The static string value of an expression, or undefined when it is not a string literal. */
255
+ function staticString(node) {
256
+ if (node === void 0) return;
257
+ const value = staticValue(node);
258
+ return typeof value === "string" ? value : void 0;
259
+ }
82
260
  // ../internal/src/vite-stage.ts
83
261
  /**
84
262
  * Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
@@ -204,6 +382,50 @@ function discoverWebhooks(projectRoot, serverDirs = ["server"]) {
204
382
  }
205
383
  return [...found.values()].sort((left, right) => left.name.localeCompare(right.name));
206
384
  }
385
+ const variableName = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
386
+ /**
387
+ * The variable names that a webhook file passes to `defineWebhook()` as string literals: `{ url?: "NAME", secret?: "NAME" }`.
388
+ * A name that the build cannot read, such as one from a constant, is omitted.
389
+ */
390
+ function readWebhookVariableNames(source, file) {
391
+ const options = findDefaultExportCall(scanModule(source, file), ["defineWebhook"])?.options;
392
+ if (!options) return {};
393
+ const properties = objectProperties(options);
394
+ const names = {};
395
+ for (const field of ["url", "secret"]) {
396
+ const property = properties.findLast((property) => property.key === field || property.key === void 0);
397
+ if (property?.key !== field) continue;
398
+ const name = staticString(property.value);
399
+ if (name !== void 0 && variableName.test(name)) names[field] = name;
400
+ }
401
+ return names;
402
+ }
403
+ /**
404
+ * Server Env declarations for the variables of each webhook, as `env.server.webhooks.<name>.url` and `.secret`. They read
405
+ * only the names in the webhook file, so the Console Env section, `describeServerEnv()`, `inspectServerEnv()`, and
406
+ * `vitehub env push` know them without a second declaration in the app.
407
+ */
408
+ function webhooksServerEnv(webhooks) {
409
+ const group = {};
410
+ for (const webhook of webhooks) {
411
+ const names = readWebhookVariableNames(readFileSync(webhook.file, "utf8"), webhook.file);
412
+ const fields = {};
413
+ if (names.url) fields.url = env({
414
+ optional: true,
415
+ secret: true,
416
+ source: env.source(names.url, { canonical: false }),
417
+ description: `The receiver URL of the ${webhook.name} webhook.`
418
+ });
419
+ if (names.secret) fields.secret = env({
420
+ optional: true,
421
+ secret: true,
422
+ source: env.source(names.secret, { canonical: false }),
423
+ description: `Signs the ${webhook.name} webhook. The receiver checks the signature with it.`
424
+ });
425
+ if (Object.keys(fields).length) group[webhook.name] = fields;
426
+ }
427
+ return Object.keys(group).length ? group : void 0;
428
+ }
207
429
  /** Whether the app has a webhook. */
208
430
  function usesWebhooks(options) {
209
431
  return discoverWebhooks(options.projectRoot, options.serverDirs).length > 0;
@@ -272,6 +494,7 @@ function renderWebhooksRegistry(webhooks, imports, features = {
272
494
  ...features.developmentKeyFile ? [` developmentKey: readFileSync(${JSON.stringify(features.developmentKeyFile)}, "utf8").trim(),`] : [],
273
495
  ...auth ? [" resolveVerifiedOwner: findVerifiedAuthUserId,"] : [],
274
496
  ...features.queue ? [` wake: (wake, options) => dynamicQueue.send(${JSON.stringify(webhooksQueueName)}, wake, options),`] : [],
497
+ ...features.retention ? [` retention: ${JSON.stringify(features.retention)},`] : [],
275
498
  "})",
276
499
  ""
277
500
  ].join("\n");
@@ -361,6 +584,7 @@ function hubWebhooks(options = {}) {
361
584
  ...defaultImports,
362
585
  ...options.imports
363
586
  };
587
+ resolveWebhooksRetention(options.retention);
364
588
  let projectRoot;
365
589
  let serverDirs;
366
590
  let memberEndpointsOn = false;
@@ -453,8 +677,17 @@ function hubWebhooks(options = {}) {
453
677
  const developmentKeyFile = features.memberEndpoints && env.command === "serve" ? await ensureDevelopmentKey(root, config.envDir === false ? false : resolve(config.root ?? root, config.envDir ?? "."), env.mode) : void 0;
454
678
  const files = writeWebhooksFiles(root, webhooks, imports, {
455
679
  ...features,
456
- developmentKeyFile
680
+ developmentKeyFile,
681
+ retention: options.retention
457
682
  });
683
+ const serverEnv = webhooksServerEnv(webhooks);
684
+ if (serverEnv) {
685
+ const contributed = Reflect.get(config, VITEHUB_ENV_SERVER);
686
+ Reflect.set(config, VITEHUB_ENV_SERVER, {
687
+ ...isRecord(contributed) ? contributed : {},
688
+ webhooks: serverEnv
689
+ });
690
+ }
458
691
  if (!webhooks.length && !features.memberEndpoints) return;
459
692
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
460
693
  kit.addPlugin(files.plugin);
@@ -462,4 +695,4 @@ function hubWebhooks(options = {}) {
462
695
  } }
463
696
  };
464
697
  }
465
- export { WEBHOOKS_VITE_PLUGIN_NAME, collectWebhooksUses, discoverWebhooks, hubWebhooks, renderWebhooksQueue, renderWebhooksRegistry, renderWebhooksTypes, usesWebhooks, webhooksConsoleSection, webhooksDevelopmentKeyFile, webhooksGeneratedFiles, webhooksQueueName };
698
+ export { WEBHOOKS_VITE_PLUGIN_NAME, collectWebhooksUses, discoverWebhooks, hubWebhooks, readWebhookVariableNames, renderWebhooksQueue, renderWebhooksRegistry, renderWebhooksTypes, usesWebhooks, webhooksConsoleSection, webhooksDevelopmentKeyFile, webhooksGeneratedFiles, webhooksQueueName, webhooksServerEnv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/webhooks",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Send ViteHub events to an outside URL: signed, retried, and debounced on every host.",
5
5
  "keywords": [
6
6
  "debounce",
@@ -56,8 +56,8 @@
56
56
  "dependencies": {
57
57
  "@standard-schema/spec": "^1.1.0",
58
58
  "@valibot/to-json-schema": "^1.8.0",
59
- "@vite-hub/env": "0.6.0",
60
- "@vite-hub/runtime": "0.6.0",
59
+ "@vite-hub/env": "0.7.0",
60
+ "@vite-hub/runtime": "0.7.0",
61
61
  "valibot": "^1.5.0"
62
62
  },
63
63
  "devDependencies": {
@@ -1,3 +0,0 @@
1
- /** The internal Queue that delivers every webhook. Its own module, so the Vite plugin reads it without the runtime. */
2
- declare const webhooksQueueName = "vitehub-webhooks";
3
- export { webhooksQueueName as t };
@@ -1,4 +0,0 @@
1
- // 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
- export { webhooksQueueName as t };