@vite-hub/rate-limit 0.0.4 → 0.3.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.
@@ -0,0 +1,1355 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, parse, resolve } from "node:path";
4
+ import { createInterface } from "node:readline/promises";
5
+ import { tmpdir } from "node:os";
6
+ import "node:url";
7
+ import { createBirpc } from "birpc";
8
+ import { toJsonSchema } from "@valibot/to-json-schema";
9
+ //#region ../internal/src/object.ts
10
+ /** A non-null object that is not an array. Functions do not pass. */
11
+ function isRecord(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ /** A non-null object or a function that is not an array. */
15
+ function isRecordOrFunction(value) {
16
+ return Object(value) === value && !Array.isArray(value);
17
+ }
18
+ /** A shallow copy of a non-array object, or an empty object for any other value. */
19
+ function cloneRecord(value) {
20
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
21
+ }
22
+ function parseViteHubDevTimeout(value, error) {
23
+ if (!/^\d+$/.test(value)) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
24
+ const timeout = Number(value);
25
+ if (timeout > 2147483647) throw error("--timeout must be at most 2147483647 milliseconds.");
26
+ if (!Number.isInteger(timeout) || timeout < 1) throw error("--timeout must be an integer from 1 to 2147483647 milliseconds.");
27
+ return timeout;
28
+ }
29
+ /**
30
+ * Reads one dev target option at `args[index]`: `--url <url>`, `--server <url>`,
31
+ * `--url=<url>`, `--timeout <ms>` or `--timeout=<ms>`.
32
+ *
33
+ * Returns the number of extra arguments that the option used (`0` or `1`), or
34
+ * `undefined` when `args[index]` is not a dev target option.
35
+ */
36
+ function readViteHubDevTargetOption(args, index, target, errors) {
37
+ const arg = args[index];
38
+ if (arg === void 0) return;
39
+ const readValue = () => {
40
+ const value = args[index + 1];
41
+ if (!value || value.startsWith("-")) throw errors.missingValue(`Missing value for ${arg}.`);
42
+ return value;
43
+ };
44
+ if (arg === "--url" || arg === "--server") {
45
+ target.url = readValue();
46
+ return 1;
47
+ }
48
+ if (arg.startsWith("--url=")) {
49
+ const value = arg.slice(6);
50
+ if (!value) throw errors.missingValue(`Missing value for ${arg}.`);
51
+ target.url = value;
52
+ return 0;
53
+ }
54
+ if (arg === "--timeout") {
55
+ target.timeout = parseViteHubDevTimeout(readValue(), errors.invalidTimeout);
56
+ return 1;
57
+ }
58
+ if (arg.startsWith("--timeout=")) {
59
+ target.timeout = parseViteHubDevTimeout(arg.slice(10), errors.invalidInlineTimeout);
60
+ return 0;
61
+ }
62
+ }
63
+ /** Writes a command failure: as `{ error }` JSON on stdout with `--json`, else the message and fix on stderr. Returns exit code 1. */
64
+ function writeCliFailure(json, streams, failure) {
65
+ if (json) streams.stdout.write(`${JSON.stringify({ error: failure }, null, 2)}\n`);
66
+ else streams.stderr.write(`${failure.message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
67
+ return 1;
68
+ }
69
+ /** Asks a question on the terminal through stderr. Only `y` or `yes`, in any case, is a yes. */
70
+ async function askOnTerminal(question) {
71
+ const terminal = createInterface({
72
+ input: process.stdin,
73
+ output: process.stderr
74
+ });
75
+ try {
76
+ return /^y(es)?$/i.test((await terminal.question(question)).trim());
77
+ } finally {
78
+ terminal.close();
79
+ }
80
+ }
81
+ /** File in the project root where the running dev server tells commands where it listens. */
82
+ const viteHubDevServerFile = ".vitehub/dev-server.json";
83
+ function writeViteHubDevServerFile(root, info) {
84
+ const file = join(root, viteHubDevServerFile);
85
+ mkdirSync(dirname(file), { recursive: true });
86
+ writeFileSync(file, `${JSON.stringify(info)}\n`);
87
+ }
88
+ function removeViteHubDevServerFile(root) {
89
+ rmSync(join(root, viteHubDevServerFile), { force: true });
90
+ }
91
+ /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
92
+ function readViteHubDevServerFile(root) {
93
+ try {
94
+ const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
95
+ const url = isRecord(value) ? value.url : void 0;
96
+ const served = isRecord(value) ? value.root : void 0;
97
+ return typeof url === "string" && url && typeof served === "string" && served ? {
98
+ root: served,
99
+ url
100
+ } : void 0;
101
+ } catch {
102
+ return;
103
+ }
104
+ }
105
+ /**
106
+ * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
107
+ * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
108
+ */
109
+ function findViteHubDevServerUrl(roots, env) {
110
+ for (const root of roots) {
111
+ const file = readViteHubDevServerFile(root);
112
+ if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
113
+ }
114
+ return env["VITEHUB_DEV_SERVER_URL"] || void 0;
115
+ }
116
+ //#endregion
117
+ //#region ../internal/src/build/vite.ts
118
+ const projectRootDirectoryMarkers = [
119
+ ["server", "agents"],
120
+ ["server", "channels"],
121
+ ["server", "connections"],
122
+ ["server", "browsers"],
123
+ ["server", "emails"],
124
+ ["server", "schedules"],
125
+ ["server", "workspaces"]
126
+ ];
127
+ const projectRootFileMarkers = [
128
+ ["package.json"],
129
+ ["nuxt.config.ts"],
130
+ ["nuxt.config.mts"],
131
+ ["nuxt.config.js"],
132
+ ["nuxt.config.mjs"]
133
+ ];
134
+ function createNoExternalAddition(...packageNames) {
135
+ return (current) => {
136
+ if (current === true) return;
137
+ const values = Array.isArray(current) ? current : [current];
138
+ const missing = packageNames.filter((packageName) => !values.includes(packageName));
139
+ return missing.length ? missing : void 0;
140
+ };
141
+ }
142
+ function isServerEnvironment(name, config) {
143
+ return name === "ssr" || config.consumer === "server";
144
+ }
145
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
146
+ /** The deployment host that `vitehub()` selected, such as `"cloudflare"`. */
147
+ const VITEHUB_DEPLOYMENT_HOST = "__vitehubDeploymentHost";
148
+ /**
149
+ * Feature options that `vitehub()` and `vite-hub/nuxt` resolve for owner plugins during config hooks, such as the Queue
150
+ * provider of the host. Apps set features only in `vitehub()`, so this key is private.
151
+ */
152
+ const VITEHUB_FEATURES = "__vitehubFeatures";
153
+ /** The options that ViteHub resolved for a feature on this Vite config. The owner plugin names their type. */
154
+ function getResolvedFeatureOptions(config, feature) {
155
+ const features = Reflect.get(config, VITEHUB_FEATURES);
156
+ if (!features || typeof features !== "object") return void 0;
157
+ return Reflect.get(features, feature);
158
+ }
159
+ /** The deployment host that `vitehub()` selected on this Vite config. */
160
+ function getDeploymentHost(config) {
161
+ const host = Reflect.get(config, VITEHUB_DEPLOYMENT_HOST);
162
+ return typeof host === "string" ? host : void 0;
163
+ }
164
+ function shouldSkipViteProviderBuild(command) {
165
+ return command === "serve";
166
+ }
167
+ function resolveViteHubProjectRoot(root, options = {}) {
168
+ const resolvedRoot = resolve(root);
169
+ const temporaryRoot = resolve(tmpdir());
170
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
171
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
172
+ if (basename(resolvedRoot) === "app") {
173
+ const parent = dirname(resolvedRoot);
174
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
175
+ "nuxt.config.ts",
176
+ "nuxt.config.mts",
177
+ "nuxt.config.js",
178
+ "nuxt.config.mjs"
179
+ ]))) return parent;
180
+ }
181
+ let current = resolvedRoot;
182
+ while (true) {
183
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
184
+ if (hasProjectRootMarker(current)) return current;
185
+ const parent = dirname(current);
186
+ if (parent === current) return resolvedRoot;
187
+ current = parent;
188
+ }
189
+ }
190
+ function hasProjectRootDirectoryMarker(root) {
191
+ for (const marker of projectRootDirectoryMarkers) try {
192
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
193
+ } catch (error) {
194
+ if (error.code !== "ENOENT") throw error;
195
+ }
196
+ return false;
197
+ }
198
+ function hasProjectRootMarker(root) {
199
+ if (hasProjectRootDirectoryMarker(root)) return true;
200
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
201
+ }
202
+ function hasProjectRootFileMarker(root, markers) {
203
+ for (const marker of markers) {
204
+ const path = Array.isArray(marker) ? marker : [marker];
205
+ try {
206
+ if (statSync(resolve(root, ...path)).isFile()) return true;
207
+ } catch (error) {
208
+ if (error.code !== "ENOENT") throw error;
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+ //#endregion
214
+ //#region ../internal/src/error-diagnostics.ts
215
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
216
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
217
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
218
+ codes: {
219
+ INTERNAL_R0012: {
220
+ ...dynamicError,
221
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
222
+ },
223
+ INTERNAL_R0013: {
224
+ ...dynamicError,
225
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
226
+ },
227
+ INTERNAL_R0014: {
228
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
229
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
230
+ },
231
+ INTERNAL_R0020: {
232
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
233
+ why: ({ message }) => message === void 0 ? "" : String(message)
234
+ },
235
+ INTERNAL_R0021: {
236
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
237
+ why: ({ message }) => message === void 0 ? "" : String(message)
238
+ },
239
+ INTERNAL_R0022: {
240
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
241
+ why: ({ message }) => message === void 0 ? "" : String(message)
242
+ },
243
+ INTERNAL_R0024: {
244
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
245
+ why: ({ message }) => message === void 0 ? "" : String(message)
246
+ },
247
+ INTERNAL_R0023: {
248
+ fix: "Ask for access to the section of this operation.",
249
+ why: ({ message }) => message === void 0 ? "" : String(message)
250
+ },
251
+ INTERNAL_B0001: {
252
+ ...dynamicError,
253
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
254
+ },
255
+ INTERNAL_B0015: {
256
+ ...dynamicError,
257
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
258
+ },
259
+ INTERNAL_B0016: {
260
+ ...dynamicError,
261
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
262
+ },
263
+ INTERNAL_B0017: {
264
+ ...dynamicError,
265
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
266
+ },
267
+ INTERNAL_B0018: {
268
+ ...dynamicError,
269
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
270
+ },
271
+ INTERNAL_B0019: {
272
+ ...dynamicError,
273
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
274
+ },
275
+ INTERNAL_B0020: {
276
+ ...dynamicError,
277
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
278
+ },
279
+ INTERNAL_B0021: {
280
+ ...dynamicError,
281
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
282
+ },
283
+ INTERNAL_B0022: {
284
+ ...dynamicError,
285
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
286
+ },
287
+ INTERNAL_B0025: {
288
+ ...dynamicError,
289
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
290
+ },
291
+ INTERNAL_B0026: {
292
+ ...dynamicError,
293
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
294
+ },
295
+ INTERNAL_B0027: {
296
+ ...dynamicError,
297
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
298
+ },
299
+ INTERNAL_B0028: {
300
+ ...dynamicError,
301
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
302
+ },
303
+ INTERNAL_B0029: {
304
+ ...dynamicError,
305
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
306
+ },
307
+ INTERNAL_B0031: {
308
+ ...dynamicError,
309
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
310
+ },
311
+ INTERNAL_B0032: {
312
+ ...dynamicError,
313
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
314
+ },
315
+ INTERNAL_B0035: {
316
+ ...dynamicError,
317
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
318
+ },
319
+ INTERNAL_B0039: {
320
+ ...dynamicError,
321
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
322
+ },
323
+ INTERNAL_B0040: {
324
+ ...dynamicError,
325
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
326
+ },
327
+ INTERNAL_B0043: {
328
+ ...dynamicError,
329
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
330
+ },
331
+ INTERNAL_B0046: {
332
+ ...dynamicError,
333
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
334
+ },
335
+ INTERNAL_B0047: {
336
+ ...dynamicError,
337
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
338
+ },
339
+ INTERNAL_B0048: {
340
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
341
+ why: ({ message }) => message === void 0 ? "" : String(message)
342
+ },
343
+ INTERNAL_B0049: {
344
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
345
+ why: ({ message }) => message === void 0 ? "" : String(message)
346
+ },
347
+ INTERNAL_B0050: {
348
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
349
+ why: ({ message }) => message === void 0 ? "" : String(message)
350
+ },
351
+ INTERNAL_B0051: {
352
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
353
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
354
+ },
355
+ INTERNAL_B0052: {
356
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
357
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
358
+ },
359
+ INTERNAL_R0025: {
360
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
361
+ why: ({ message }) => message === void 0 ? "" : String(message)
362
+ },
363
+ INTERNAL_R0026: {
364
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
365
+ fix: "Review the operation, then run it again with --yes to confirm the change."
366
+ },
367
+ INTERNAL_C0001: {
368
+ ...dynamicError,
369
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
370
+ },
371
+ INTERNAL_C0002: {
372
+ ...dynamicError,
373
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
374
+ },
375
+ INTERNAL_R0001: {
376
+ ...dynamicError,
377
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
378
+ },
379
+ INTERNAL_R0002: {
380
+ ...dynamicError,
381
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
382
+ },
383
+ INTERNAL_R0004: {
384
+ ...dynamicError,
385
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
386
+ },
387
+ INTERNAL_R0005: {
388
+ ...dynamicError,
389
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
390
+ },
391
+ INTERNAL_R0006: {
392
+ ...dynamicError,
393
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
394
+ },
395
+ INTERNAL_R0007: {
396
+ ...dynamicError,
397
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
398
+ },
399
+ INTERNAL_R0008: {
400
+ ...dynamicError,
401
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
402
+ },
403
+ INTERNAL_R0009: {
404
+ ...dynamicError,
405
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
406
+ },
407
+ INTERNAL_R0010: {
408
+ ...dynamicError,
409
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
410
+ },
411
+ INTERNAL_R0011: {
412
+ ...dynamicError,
413
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
414
+ },
415
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
416
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
417
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
418
+ },
419
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
420
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
421
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
422
+ },
423
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
424
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
425
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
426
+ },
427
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
428
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
429
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
430
+ },
431
+ INTERNAL_FORGE_NOT_INSTALLED: {
432
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
433
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
434
+ },
435
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
436
+ why: ({ detail }) => detail,
437
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
438
+ },
439
+ INTERNAL_MCP_METHOD_FAILED: {
440
+ why: ({ name }) => `${name} failed on the server.`,
441
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
442
+ },
443
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
444
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
445
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
446
+ },
447
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
448
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
449
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
450
+ },
451
+ INTERNAL_PRESET_TUPLE_INVALID: {
452
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
453
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
454
+ },
455
+ INTERNAL_SECRET_PURPOSE_MISSING: {
456
+ why: "[vitehub] A derived secret requires a purpose.",
457
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
458
+ },
459
+ INTERNAL_SECRET_TOO_SHORT: {
460
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
461
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
462
+ },
463
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
464
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
465
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
466
+ },
467
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
468
+ why: "Received integer which cannot be safely represented as a JavaScript number",
469
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
470
+ },
471
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
472
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
473
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
474
+ }
475
+ }
476
+ });
477
+ //#endregion
478
+ //#region ../internal/src/invariant.ts
479
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
480
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
481
+ codes: { INTERNAL_INVARIANT_FAILED: {
482
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
483
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
484
+ } }
485
+ });
486
+ /**
487
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
488
+ * Use a code from the package catalog when a developer can cause the error or fix it.
489
+ */
490
+ function invariantError(what) {
491
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
492
+ }
493
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
494
+ function invariant(condition, what) {
495
+ if (!condition) throw invariantError(what);
496
+ }
497
+ //#endregion
498
+ //#region ../internal/src/operation-rpc.ts
499
+ /** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
500
+ const operationRpcPath = "/_vitehub/rpc";
501
+ const maximumIdLength = 128;
502
+ function text$1(value) {
503
+ return String(value) === value && value ? value : void 0;
504
+ }
505
+ /** Read an untrusted failure body. It keeps only the diagnostic fields, so a stack never passes through. */
506
+ function readOperationRpcError(value) {
507
+ if (!isRecord(value)) return void 0;
508
+ const code = text$1(value.code);
509
+ const message = text$1(value.message);
510
+ const status = value.status;
511
+ if (!code || !message || !Number.isInteger(status)) return void 0;
512
+ const failure = {
513
+ code,
514
+ message,
515
+ status: Number(status)
516
+ };
517
+ if (text$1(value.fix)) failure.fix = text$1(value.fix);
518
+ if (text$1(value.docs)) failure.docs = text$1(value.docs);
519
+ if (isRecord(value.details)) failure.details = value.details;
520
+ return failure;
521
+ }
522
+ /** Read one request message. Events without an id, the `o` flag of optional calls, and more than one argument are refused. */
523
+ function readOperationRpcCall(value) {
524
+ if (!isRecord(value) || value.t !== "q") return void 0;
525
+ const { a: args, i: id, m: name } = value;
526
+ if (Object.keys(value).some((key) => key !== "t" && key !== "i" && key !== "m" && key !== "a")) return void 0;
527
+ if (!text$1(id) || String(id).length > maximumIdLength || String(name) !== name) return void 0;
528
+ if (!Array.isArray(args) || args.length > 1) return void 0;
529
+ return {
530
+ t: "q",
531
+ i: String(id),
532
+ m: name,
533
+ a: args.length ? [args[0]] : []
534
+ };
535
+ }
536
+ /** Read one response message. */
537
+ function readOperationRpcReply(value) {
538
+ if (!isRecord(value) || value.t !== "s") return void 0;
539
+ const id = text$1(value.i);
540
+ if (Object.hasOwn(value, "e")) {
541
+ const error = readOperationRpcError(value.e);
542
+ return error ? {
543
+ t: "s",
544
+ ...id ? { i: id } : {},
545
+ e: error
546
+ } : void 0;
547
+ }
548
+ return id ? {
549
+ t: "s",
550
+ i: id,
551
+ r: value.r
552
+ } : void 0;
553
+ }
554
+ /** A refusal of a request that the server could not read as a call. */
555
+ function operationRpcRefusal(failure) {
556
+ return {
557
+ t: "s",
558
+ e: failure
559
+ };
560
+ }
561
+ /**
562
+ * Answer one call with birpc. Its resolver returns only own entries of `operations`. birpc would otherwise look the name
563
+ * up on a plain object and call `toString` or `constructor` from its prototype.
564
+ */
565
+ async function answerOperationRpc(call, server) {
566
+ let receive;
567
+ let posted;
568
+ let resolved = false;
569
+ let rejection;
570
+ createBirpc({}, {
571
+ on: (listener) => {
572
+ receive = listener;
573
+ },
574
+ post: (message) => {
575
+ posted = message;
576
+ },
577
+ resolver: (name) => {
578
+ if (!Object.hasOwn(server.operations, name)) return void 0;
579
+ resolved = true;
580
+ const operation = server.operations[name];
581
+ return async (...args) => {
582
+ try {
583
+ return await server.run(operation, args[0]);
584
+ } catch (reason) {
585
+ rejection = { reason };
586
+ throw rejection;
587
+ }
588
+ };
589
+ },
590
+ proxify: false,
591
+ timeout: -1
592
+ });
593
+ await receive(call);
594
+ invariant(posted, "birpc posts one reply for each request message that it receives");
595
+ if (!Object.hasOwn(posted, "e")) return {
596
+ t: "s",
597
+ i: call.i,
598
+ r: posted.r
599
+ };
600
+ const error = rejection ? rejection.reason : resolved ? posted.e : server.unknown(call.m);
601
+ return {
602
+ t: "s",
603
+ i: call.i,
604
+ e: server.failure(error)
605
+ };
606
+ }
607
+ /**
608
+ * Call one operation with birpc over a request and answer transport, such as one HTTP POST per call. `send` posts the
609
+ * JSON message and returns the parsed answer; its own failures, such as a network error or an abort, reject.
610
+ */
611
+ async function callOperationRpc(name, input, send) {
612
+ let receive;
613
+ let answer;
614
+ const notReply = /* @__PURE__ */ new Error("The answer is not a reply to the operation call.");
615
+ const rpc = createBirpc({}, {
616
+ on: (listener) => {
617
+ receive = listener;
618
+ },
619
+ post: async (message) => {
620
+ answer = await send(JSON.stringify(message));
621
+ const reply = readOperationRpcReply(answer.body);
622
+ if (!reply || reply.i !== void 0 && reply.i !== message.i) throw notReply;
623
+ await receive({
624
+ ...reply,
625
+ i: message.i
626
+ });
627
+ },
628
+ proxify: false,
629
+ timeout: -1
630
+ });
631
+ try {
632
+ return {
633
+ ok: true,
634
+ value: await rpc.$call(name, ...input === void 0 ? [] : [input]),
635
+ answer
636
+ };
637
+ } catch (error) {
638
+ if (!answer) throw error;
639
+ if (error === notReply) return {
640
+ ok: false,
641
+ error: void 0,
642
+ answer
643
+ };
644
+ return {
645
+ ok: false,
646
+ error: readOperationRpcError(error),
647
+ answer
648
+ };
649
+ }
650
+ }
651
+ //#endregion
652
+ //#region ../internal/src/console-signature.ts
653
+ /**
654
+ * Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
655
+ * CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
656
+ * its env cannot sign a request. The module uses only Web Crypto, so it runs in Node, Workers, Deno, and browsers.
657
+ *
658
+ * The signature covers this text, one field per line:
659
+ *
660
+ * ```txt
661
+ * vitehub-signature-v1
662
+ * POST
663
+ * /_vitehub/rpc
664
+ * https://app.example.com
665
+ * 1794400000
666
+ * CONSOLE_3F9A12BC
667
+ * <SHA-256 of the body bytes, base64url>
668
+ * <the x-vitehub-caller header>
669
+ * ```
670
+ */
671
+ /** The signature header: `key=<NAME>, t=<seconds>, origin=<app origin>, body=<SHA-256>, v1=<signature>`. */
672
+ const consoleSignatureHeader = "x-vitehub-signature";
673
+ /** Who calls, as base64url JSON. The signature covers it. See {@link ConsoleCaller}. */
674
+ const consoleCallerHeader = "x-vitehub-caller";
675
+ /** The first line of the signed text. A new format gets a new tag. */
676
+ const consoleSignatureVersion = "vitehub-signature-v1";
677
+ /** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
678
+ const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
679
+ const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
680
+ const encoder = new TextEncoder();
681
+ new TextDecoder();
682
+ const ed25519 = { name: "Ed25519" };
683
+ const pkcs8Prefix = Uint8Array.of(48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32);
684
+ function base64url(bytes) {
685
+ let binary = "";
686
+ for (const byte of bytes) binary += String.fromCharCode(byte);
687
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
688
+ }
689
+ /** The bytes of a base64url value, or `undefined` when it is not canonical base64url without padding. */
690
+ function fromBase64url(value) {
691
+ if (!/^[\w-]*$/.test(value) || value.length % 4 === 1) return void 0;
692
+ const bytes = Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
693
+ return base64url(bytes) === value ? bytes : void 0;
694
+ }
695
+ function bytesOf(body) {
696
+ if (typeof body === "string") return encoder.encode(body);
697
+ return body instanceof Uint8Array ? Uint8Array.from(body) : new Uint8Array(body);
698
+ }
699
+ /** The SHA-256 of the exact body bytes, base64url. A request without a body hashes zero bytes. */
700
+ async function consoleBodySha256(body = "") {
701
+ return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytesOf(body))));
702
+ }
703
+ /** The text that the signature covers. Fields are joined with `\n`. */
704
+ function consoleSignedText(fields) {
705
+ return [
706
+ consoleSignatureVersion,
707
+ fields.method.toUpperCase(),
708
+ fields.target,
709
+ fields.origin,
710
+ fields.timestamp,
711
+ fields.key,
712
+ fields.bodySha256,
713
+ fields.caller
714
+ ].join("\n");
715
+ }
716
+ /** The path and query of a URL, the part of the request target that the signature covers. */
717
+ function requestTarget(url) {
718
+ return `${url.pathname}${url.search}`;
719
+ }
720
+ /** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
721
+ function isConsoleKeyName(name) {
722
+ return keyNamePattern.test(name);
723
+ }
724
+ async function importPrivateKey(seed) {
725
+ const bytes = fromBase64url(seed.trim());
726
+ if (bytes?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_INVALID();
727
+ const der = new Uint8Array(pkcs8Prefix.length + 32);
728
+ der.set(pkcs8Prefix);
729
+ der.set(bytes, pkcs8Prefix.length);
730
+ return await crypto.subtle.importKey("pkcs8", der, ed25519, false, ["sign"]);
731
+ }
732
+ /** The `x-vitehub-caller` value of a caller: its JSON as base64url. */
733
+ function encodeConsoleCaller(caller) {
734
+ return base64url(encoder.encode(JSON.stringify(caller)));
735
+ }
736
+ /**
737
+ * Sign one request. `url` is the full URL that the request goes to, and `body` is the exact body that it sends. Returns
738
+ * the two headers to add: `x-vitehub-signature` and `x-vitehub-caller`.
739
+ */
740
+ async function signConsoleRequest(options) {
741
+ if (!isConsoleKeyName(options.key.name)) throw internalErrorDiagnostics.INTERNAL_CONSOLE_KEY_NAME_INVALID({ name: options.key.name });
742
+ const url = new URL(options.url);
743
+ const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
744
+ const bodySha256 = await consoleBodySha256(options.body);
745
+ const caller = encodeConsoleCaller(options.caller);
746
+ const text = consoleSignedText({
747
+ bodySha256,
748
+ caller,
749
+ key: options.key.name,
750
+ method: options.method,
751
+ origin: url.origin,
752
+ target: requestTarget(url),
753
+ timestamp
754
+ });
755
+ const signature = new Uint8Array(await crypto.subtle.sign(ed25519, await importPrivateKey(options.key.privateKey), encoder.encode(text)));
756
+ return {
757
+ [consoleCallerHeader]: caller,
758
+ [consoleSignatureHeader]: `key=${options.key.name}, t=${timestamp}, origin=${url.origin}, body=${bodySha256}, v1=${base64url(signature)}`
759
+ };
760
+ }
761
+ /**
762
+ * The signing key of a CLI from its env: the one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable. Returns `undefined`
763
+ * without one. Throws a coded error when there are several, or when the value is not a 32-byte seed.
764
+ */
765
+ function readConsoleSigningKey(env) {
766
+ const variables = Object.keys(env).filter((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && env[name]?.trim()).sort();
767
+ if (!variables.length) return void 0;
768
+ if (variables.length > 1) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE({
769
+ prefix: consolePrivateKeyPrefix,
770
+ variables: variables.join(", ")
771
+ });
772
+ const variable = variables[0];
773
+ const name = variable.slice(28);
774
+ const privateKey = env[variable].trim();
775
+ if (!isConsoleKeyName(name) || fromBase64url(privateKey)?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID({ variable });
776
+ return {
777
+ name,
778
+ privateKey
779
+ };
780
+ }
781
+ //#endregion
782
+ //#region ../internal/src/standard-schema.ts
783
+ function readOwn(value, key) {
784
+ if (value === null || Object(value) !== value) return;
785
+ try {
786
+ return Reflect.get(Object(value), key);
787
+ } catch {
788
+ return;
789
+ }
790
+ }
791
+ /**
792
+ * Read a Standard JSON Schema projection without throwing.
793
+ *
794
+ * Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
795
+ * (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
796
+ */
797
+ function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
798
+ const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
799
+ const project = readOwn(jsonSchema, direction);
800
+ if (typeof project !== "function") return;
801
+ try {
802
+ const result = project.call(jsonSchema, libraryOptions ? {
803
+ target,
804
+ libraryOptions
805
+ } : { target });
806
+ return isRecordOrFunction(result) ? result : void 0;
807
+ } catch {
808
+ return;
809
+ }
810
+ }
811
+ //#endregion
812
+ //#region ../internal/src/valibot.ts
813
+ const valibotTargets = /* @__PURE__ */ new Set([
814
+ "draft-07",
815
+ "draft-2020-12",
816
+ "openapi-3.0"
817
+ ]);
818
+ function isValibotTarget(value) {
819
+ return valibotTargets.has(String(value));
820
+ }
821
+ /**
822
+ * Add Standard JSON Schema conversion to a plain Valibot schema. Valibot schemas validate as Standard Schema but carry
823
+ * no JSON Schema, so forms, tools, and model providers would get no shape for them. Other schemas, Valibot schemas that
824
+ * already convert, and async Valibot schemas return unchanged. The copy keeps every Valibot property, so validation
825
+ * does not change.
826
+ *
827
+ * `target` fixes the JSON Schema dialect. Without it, each conversion uses the dialect that the caller asks for.
828
+ */
829
+ function withValibotJsonSchema(schema, options = {}) {
830
+ const standard = schema["~standard"];
831
+ if (standard.vendor !== "valibot" || Reflect.get(schema, "async") === true) return schema;
832
+ if (Object.hasOwn(standard, "jsonSchema") && standard.jsonSchema) return schema;
833
+ const convert = (typeMode) => (request) => {
834
+ const target = options.target ?? request.target;
835
+ if (!isValibotTarget(target)) throw internalErrorDiagnostics.INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED({ target: String(target) });
836
+ return toJsonSchema(schema, {
837
+ target,
838
+ typeMode,
839
+ errorMode: "ignore"
840
+ });
841
+ };
842
+ return {
843
+ ...schema,
844
+ "~standard": {
845
+ ...standard,
846
+ jsonSchema: {
847
+ input: convert("input"),
848
+ output: convert("output")
849
+ }
850
+ }
851
+ };
852
+ }
853
+ //#endregion
854
+ //#region ../internal/src/operation-definition.ts
855
+ const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
856
+ const kinds = /* @__PURE__ */ new Set([
857
+ "read",
858
+ "write",
859
+ "destructive"
860
+ ]);
861
+ function invalidDefinition(name, reason) {
862
+ return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
863
+ }
864
+ function checkDefinition(definition) {
865
+ if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
866
+ const { name } = definition;
867
+ if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
868
+ if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
869
+ const { section } = definition;
870
+ if (section !== false && !(section instanceof Function) && !isSectionId(section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false; section ids cannot contain ':'.");
871
+ if (definition.scope !== void 0 && (!(definition.scope instanceof Function) || String(section) !== section)) throw invalidDefinition(name, "scope must be a function, and it needs a section id.");
872
+ if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
873
+ const input = definition.input;
874
+ if (!isRecordOrFunction(input) || !isRecordOrFunction(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
875
+ if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
876
+ const { maxRequestBytes } = definition;
877
+ if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
878
+ if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
879
+ const { mcp } = definition;
880
+ if (mcp !== void 0 && mcp !== false && (!isRecordOrFunction(mcp) || mcp.title !== void 0 && (String(mcp.title) !== mcp.title || !mcp.title) || mcp.format !== void 0 && !(mcp.format instanceof Function))) throw invalidDefinition(name, "mcp must be false, or an object with a title string and a format function.");
881
+ }
882
+ /** The default limit of a call, in bytes. */
883
+ const defaultRequestBytes = 65536;
884
+ /** CLI namespaces owned by built-in commands. */
885
+ const reservedOperationNamespaces = [
886
+ "inspect",
887
+ "provision",
888
+ "seed",
889
+ ...[
890
+ "init",
891
+ "add",
892
+ "remove",
893
+ "status",
894
+ "catalog",
895
+ "link",
896
+ "unlink",
897
+ "deploy",
898
+ "deployments",
899
+ "drain",
900
+ "login",
901
+ "logout",
902
+ "whoami"
903
+ ]
904
+ ];
905
+ /** Input keys that the generated CLI commands read themselves. */
906
+ const reservedOperationFlags = [
907
+ "input",
908
+ "json",
909
+ "timeout",
910
+ "url",
911
+ "yes"
912
+ ];
913
+ /**
914
+ * Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
915
+ * `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
916
+ */
917
+ function defineOperation(definition) {
918
+ checkDefinition(definition);
919
+ const defined = {
920
+ ...definition,
921
+ input: withValibotJsonSchema(definition.input)
922
+ };
923
+ const properties = operationInputJsonSchema(defined).properties;
924
+ const clashes = isRecordOrFunction(properties) ? Object.keys(properties).filter((key) => reservedOperationFlags.includes(key)) : [];
925
+ if (clashes.length) throw invalidDefinition(definition.name, `the input key ${clashes.map((key) => JSON.stringify(key)).join(", ")} is a CLI flag of every command (${reservedOperationFlags.join(", ")}). Rename it.`);
926
+ return defined;
927
+ }
928
+ function isOperation(value) {
929
+ try {
930
+ checkDefinition(value);
931
+ return true;
932
+ } catch {
933
+ return false;
934
+ }
935
+ }
936
+ function isSectionId(section) {
937
+ return typeof section === "string" && section !== "" && !section.includes(":");
938
+ }
939
+ /** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
940
+ function operationInputJsonSchema(operation) {
941
+ return standardJsonSchema(operation.input, "input") ?? { type: "object" };
942
+ }
943
+ //#endregion
944
+ //#region ../internal/src/operations.ts
945
+ /** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
946
+ const operationRpcHeader = "x-vitehub-console";
947
+ /** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
948
+ const operationRootHeader = "x-vitehub-root";
949
+ const operationExpectedRootsHeader = "x-vitehub-expected-roots";
950
+ /** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
951
+ function projectRootHash(root) {
952
+ const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
953
+ let first = 3735928559;
954
+ let second = 1103547991;
955
+ for (let index = 0; index < normalized.length; index++) {
956
+ const code = normalized.charCodeAt(index);
957
+ first = Math.imul(first ^ code, 2654435761);
958
+ second = Math.imul(second ^ code, 1597334677);
959
+ }
960
+ first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
961
+ second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
962
+ return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
963
+ }
964
+ /** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
965
+ const operationSurfaceHeader = "x-vitehub-surface";
966
+ /** Generated CLI commands ask the server to check confirmation after it parses the input. */
967
+ const operationConfirmationHeader = "x-vitehub-confirmation";
968
+ function pluginName(plugin) {
969
+ const name = Reflect.get(plugin, "name");
970
+ return String(name) === name && name ? name : "unnamed plugin";
971
+ }
972
+ /** Reads `plugin.vitehub.operations` from resolved Vite plugins. The same module and export from two plugins counts once. */
973
+ async function collectOperationContributions(plugins) {
974
+ const collected = /* @__PURE__ */ new Map();
975
+ for (const plugin of plugins) {
976
+ if (!isRecordOrFunction(plugin) || !Object.hasOwn(plugin, "vitehub")) continue;
977
+ const declared = Reflect.get(Object(Reflect.get(plugin, "vitehub")), "operations");
978
+ if (declared === void 0) continue;
979
+ const entries = declared instanceof Function ? await declared() : declared;
980
+ const owner = pluginName(plugin);
981
+ if (!Array.isArray(entries)) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} sets vitehub.operations, which must be a list of { module, export }.` });
982
+ for (const entry of entries) {
983
+ if (!isRecordOrFunction(entry) || String(entry.module) !== entry.module || !entry.module) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} contributes an operation entry without a module.` });
984
+ const exportName = String(entry.export) === entry.export && entry.export ? entry.export : "default";
985
+ const key = `${entry.module}#${exportName}`;
986
+ if (collected.has(key)) continue;
987
+ collected.set(key, {
988
+ module: entry.module,
989
+ export: exportName,
990
+ plugin: owner,
991
+ ...entry.load instanceof Function ? { load: entry.load } : {},
992
+ ...entry.runtime === false ? { runtime: false } : {}
993
+ });
994
+ }
995
+ }
996
+ return [...collected.values()];
997
+ }
998
+ /** Operations of one module export, flat. A single operation or an array both work. */
999
+ function operationsOf(value) {
1000
+ const list = Array.isArray(value) ? value : [value];
1001
+ const operations = [];
1002
+ for (const item of list) {
1003
+ if (!isOperation(item)) throw invalidDefinition(isRecordOrFunction(item) ? item.name : void 0, "a contributed export must hold defineOperation() results.");
1004
+ operations.push(item);
1005
+ }
1006
+ return operations;
1007
+ }
1008
+ /** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
1009
+ function operationCliPath(operation) {
1010
+ const dot = operation.name.indexOf(".");
1011
+ return {
1012
+ command: operation.cli?.command ?? operation.name.slice(dot + 1),
1013
+ namespace: operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
1014
+ };
1015
+ }
1016
+ /**
1017
+ * The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
1018
+ * Claude reject a dot in a tool name. `content.publish` is `content_publish`.
1019
+ */
1020
+ function operationToolName(name) {
1021
+ return name.replace(/[^\w-]/g, "_");
1022
+ }
1023
+ /** Build the registry by name. A duplicate name or CLI command fails with `INTERNAL_B0048` or `INTERNAL_B0049`, two MCP tool names that match with `INTERNAL_B0050`. */
1024
+ function createOperationRegistry(sources) {
1025
+ const byName = /* @__PURE__ */ new Map();
1026
+ for (const source of sources) for (const operation of source.operations) {
1027
+ const existing = byName.get(operation.name);
1028
+ if (existing && existing.operation !== operation) {
1029
+ const owners = [existing.plugin, source.plugin].filter(Boolean).join(" and ");
1030
+ throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] Two operations are named ${JSON.stringify(operation.name)}${owners ? ` (${owners})` : ""}.` });
1031
+ }
1032
+ byName.set(operation.name, {
1033
+ operation,
1034
+ ...source.plugin ? { plugin: source.plugin } : {}
1035
+ });
1036
+ }
1037
+ const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
1038
+ const commands = /* @__PURE__ */ new Map();
1039
+ for (const operation of operations) {
1040
+ const { command, namespace } = operationCliPath(operation);
1041
+ if (reservedOperationNamespaces.includes(namespace)) throw invalidDefinition(operation.name, `the CLI namespace ${JSON.stringify(namespace)} is reserved for built-in commands. Set cli.namespace to another name.`);
1042
+ const key = `${namespace} ${command}`;
1043
+ const other = commands.get(key);
1044
+ if (other) throw internalErrorDiagnostics.INTERNAL_B0049({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the CLI command \`vitehub ${key}\`.` });
1045
+ commands.set(key, operation);
1046
+ }
1047
+ const tools = /* @__PURE__ */ new Map();
1048
+ for (const operation of operations) {
1049
+ if (operation.mcp === false) continue;
1050
+ const tool = operationToolName(operation.name);
1051
+ const other = tools.get(tool);
1052
+ if (other) throw internalErrorDiagnostics.INTERNAL_B0050({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the MCP tool ${JSON.stringify(tool)}.` });
1053
+ tools.set(tool, operation);
1054
+ }
1055
+ return {
1056
+ get: (name) => byName.get(name)?.operation,
1057
+ list: () => [...operations]
1058
+ };
1059
+ }
1060
+ /** Issues of a failed Standard Schema check as one short line per issue. */
1061
+ function describeInputIssues(issues) {
1062
+ return issues.slice(0, 5).map((issue) => {
1063
+ const path = (issue.path ?? []).map((segment) => String(isRecordOrFunction(segment) && "key" in segment ? segment.key : segment)).join(".");
1064
+ return path ? `${path}: ${issue.message}` : issue.message;
1065
+ }).join(" ");
1066
+ }
1067
+ /** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
1068
+ async function parseOperationInput(operation, input) {
1069
+ const result = await operation.input["~standard"].validate(input ?? {});
1070
+ if (!result.issues) return result.value;
1071
+ const error = internalErrorDiagnostics.INTERNAL_R0022({ message: `Invalid input for ${operation.name}. ${describeInputIssues(result.issues)}` });
1072
+ throw Object.assign(error, { status: 400 });
1073
+ }
1074
+ /**
1075
+ * The section that grants a call, or `false` for any Console user. `undefined` means the input names no valid section.
1076
+ * A scoped operation answers `"<section>:<scope>"`, such as `"blob:media"`.
1077
+ */
1078
+ function operationSection(operation, input) {
1079
+ const section = operation.section;
1080
+ if (section instanceof Function) {
1081
+ const resolved = section(input);
1082
+ return isSectionId(resolved) ? resolved : void 0;
1083
+ }
1084
+ if (section === false) return section;
1085
+ if (!isSectionId(section)) return void 0;
1086
+ if (!operation.scope) return section;
1087
+ const scope = operation.scope(input);
1088
+ return isSectionScope(scope) ? `${section}:${scope}` : section;
1089
+ }
1090
+ function isSectionScope(scope) {
1091
+ return isSectionId(scope) && scope !== "read";
1092
+ }
1093
+ /** `"blob:media"` → `["blob:media", "blob"]`: a grant of the section covers each of its scopes. */
1094
+ function grantsFor(section) {
1095
+ const separator = section.indexOf(":");
1096
+ return separator === -1 ? [section] : [section, section.slice(0, separator)];
1097
+ }
1098
+ /**
1099
+ * Whether the checked access covers the section. Without `call`, a read-only grant (`"kv:read"`) counts, so the answer
1100
+ * is whether the section is visible. With `call`, a read-only grant allows only a `read` operation or a call that only
1101
+ * reads. Every surface (RPC, CLI, agents, MCP) checks access here.
1102
+ */
1103
+ function operationAccessAllows(access, section, call) {
1104
+ if (section === void 0) return false;
1105
+ if (section === false || access.sections === "all") return true;
1106
+ const { sections } = access;
1107
+ const grants = grantsFor(section);
1108
+ if (grants.some((grant) => sections.includes(grant))) return true;
1109
+ if (!grants.some((grant) => sections.includes(`${grant}:read`))) return false;
1110
+ return call === void 0 || call.kind === "read" || call.readOnly === true;
1111
+ }
1112
+ /**
1113
+ * Why the access refuses a call to a section, with the `console.authorize` grant that would allow it. A scoped section,
1114
+ * such as `"blob:default"`, names the scope and the whole section.
1115
+ */
1116
+ function operationAccessDenial(operationName, section) {
1117
+ if (!section) return {
1118
+ fix: "Check the input of the call.",
1119
+ message: `The input of ${operationName} names no section that this access can check.`
1120
+ };
1121
+ const separator = section.indexOf(":");
1122
+ if (separator === -1) return {
1123
+ fix: `Return ${JSON.stringify(section)} in the sections of console.authorize.`,
1124
+ message: `This access does not include the ${JSON.stringify(section)} section, which ${operationName} needs.`
1125
+ };
1126
+ const parent = section.slice(0, separator);
1127
+ return {
1128
+ fix: `Return ${JSON.stringify(section)} (only this scope) or ${JSON.stringify(parent)} (every scope) in the sections of console.authorize.`,
1129
+ message: `This access does not include ${JSON.stringify(section)}. ${operationName} needs it for the ${JSON.stringify(section.slice(separator + 1))} scope of the ${JSON.stringify(parent)} section.`
1130
+ };
1131
+ }
1132
+ /** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
1133
+ function operationCall(operation, input) {
1134
+ return {
1135
+ kind: operation.kind,
1136
+ readOnly: operation.readOnlyWhen?.(input) === true
1137
+ };
1138
+ }
1139
+ function text(value) {
1140
+ return String(value) === value && value ? value : void 0;
1141
+ }
1142
+ /** Read the shared failure fields from anything an operation throws. */
1143
+ function toOperationFailure(error) {
1144
+ const value = Object(error);
1145
+ const rawStatus = Reflect.get(value, "status") ?? Reflect.get(value, "statusCode");
1146
+ const status = Number.isInteger(rawStatus) && Number(rawStatus) >= 400 && Number(rawStatus) <= 599 ? Number(rawStatus) : 500;
1147
+ const message = text(Reflect.get(value, "statusMessage")) ?? (error instanceof Error ? error.message : void 0) ?? "The operation failed.";
1148
+ const failure = {
1149
+ code: text(Reflect.get(value, "code")) ?? (status >= 500 ? "OPERATION_FAILED" : "OPERATION_REJECTED"),
1150
+ message,
1151
+ status
1152
+ };
1153
+ const fix = text(Reflect.get(value, "fix"));
1154
+ const docs = text(Reflect.get(value, "docs"));
1155
+ const details = Reflect.get(value, "details");
1156
+ if (fix) failure.fix = fix;
1157
+ if (docs) failure.docs = docs;
1158
+ if (isRecordOrFunction(details)) failure.details = details;
1159
+ return failure;
1160
+ }
1161
+ /**
1162
+ * Run one operation by name: validate the input, check the section against `context.access`, and run. Never throws.
1163
+ * The Console RPC and agent tools call it.
1164
+ */
1165
+ async function runOperation(registry, name, input, context, options = {}) {
1166
+ const failure = options.failure ?? toOperationFailure;
1167
+ try {
1168
+ const operation = registry.get(name);
1169
+ if (!operation) throw Object.assign(internalErrorDiagnostics.INTERNAL_R0021({ message: `No operation is named ${JSON.stringify(name)}.` }), { status: 404 });
1170
+ return await runParsedOperation(operation, await parseOperationInput(operation, input), context, options);
1171
+ } catch (error) {
1172
+ return {
1173
+ ok: false,
1174
+ ...failure(error)
1175
+ };
1176
+ }
1177
+ }
1178
+ /** Run input already validated by parseOperationInput, so approval and execution can share one normalization. */
1179
+ async function runParsedOperation(operation, parsed, context, options = {}) {
1180
+ const failure = options.failure ?? toOperationFailure;
1181
+ try {
1182
+ const section = operationSection(operation, parsed);
1183
+ if (!operationAccessAllows(context.access, section)) {
1184
+ const denial = operationAccessDenial(operation.name, section);
1185
+ throw Object.assign(internalErrorDiagnostics.INTERNAL_R0023({ message: `${denial.message} ${denial.fix}` }), { status: 403 });
1186
+ }
1187
+ if (!operationAccessAllows(context.access, section, operationCall(operation, parsed))) throw Object.assign(internalErrorDiagnostics.INTERNAL_R0023({ message: `This access to the ${JSON.stringify(section)} section is read-only, and ${operation.name} is a ${operation.kind} operation. Grant the section without ":read" to allow it.` }), { status: 403 });
1188
+ return {
1189
+ ok: true,
1190
+ value: await operation.run(parsed, context)
1191
+ };
1192
+ } catch (error) {
1193
+ return {
1194
+ ok: false,
1195
+ ...failure(error)
1196
+ };
1197
+ }
1198
+ }
1199
+ const operationCredentialHint = "Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key that `vitehub secret console-key` printed, and its public key in VITEHUB_CONSOLE_KEY_<NAME> on the app.";
1200
+ /** Headers of an operation call, without a signature. */
1201
+ function operationHeaders() {
1202
+ const headers = new Headers();
1203
+ headers.set("accept", "application/json");
1204
+ headers.set("content-type", "application/json");
1205
+ headers.set(operationRpcHeader, "1");
1206
+ headers.set(operationSurfaceHeader, "cli");
1207
+ return headers;
1208
+ }
1209
+ /**
1210
+ * The headers of one operation call to a deployed app: {@link operationHeaders}, and the signature of `body` when the
1211
+ * env has a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. The CLI signs as itself, `via: "cli"`. Throws a `TypeError` for a
1212
+ * malformed private key.
1213
+ */
1214
+ async function signedOperationHeaders(env, url, body) {
1215
+ const headers = operationHeaders();
1216
+ const key = readConsoleSigningKey(env);
1217
+ if (key) {
1218
+ const signed = await signConsoleRequest({
1219
+ body,
1220
+ caller: { via: "cli" },
1221
+ key,
1222
+ method: "POST",
1223
+ url
1224
+ });
1225
+ for (const [name, value] of Object.entries(signed)) headers.set(name, value);
1226
+ }
1227
+ return headers;
1228
+ }
1229
+ function unreachable(message, status = 503) {
1230
+ const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
1231
+ return {
1232
+ ok: false,
1233
+ code: error.code,
1234
+ fix: error.fix,
1235
+ message,
1236
+ status
1237
+ };
1238
+ }
1239
+ function hasCredentials(env) {
1240
+ return Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && Boolean(env[name]));
1241
+ }
1242
+ /** Refuse a stale local discovery target before dispatching any operation. */
1243
+ function assertOperationProject(request, root) {
1244
+ const expected = request.headers.get(operationExpectedRootsHeader);
1245
+ if (expected === null) return;
1246
+ if (root && expected.split(",").includes(projectRootHash(root))) return;
1247
+ throw Object.assign(internalErrorDiagnostics.INTERNAL_R0025({ message: "The server runs another project than the command expects." }), { status: 409 });
1248
+ }
1249
+ /** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
1250
+ async function callOperation(target, name, input) {
1251
+ let origin = "the ViteHub app";
1252
+ try {
1253
+ const base = new URL(target.url);
1254
+ if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
1255
+ const url = new URL(operationRpcPath.slice(1), base);
1256
+ origin = url.origin;
1257
+ const env = target.roots?.length ? {} : target.env;
1258
+ try {
1259
+ readConsoleSigningKey(env);
1260
+ } catch (error) {
1261
+ return {
1262
+ ok: false,
1263
+ code: "INTERNAL_R0024",
1264
+ fix: "Run `vitehub secret console-key` for a new key pair. Set its private key here and its public key on the app.",
1265
+ message: error instanceof Error ? error.message : String(error),
1266
+ status: 401
1267
+ };
1268
+ }
1269
+ const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
1270
+ const headers = await signedOperationHeaders(env, url, body);
1271
+ if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
1272
+ if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
1273
+ const response = await (target.fetch ?? fetch)(url.href, {
1274
+ body,
1275
+ headers,
1276
+ method: "POST",
1277
+ redirect: "manual",
1278
+ signal: AbortSignal.timeout(target.timeout ?? 3e4)
1279
+ });
1280
+ const text = await response.text();
1281
+ let json;
1282
+ try {
1283
+ json = text ? JSON.parse(text) : void 0;
1284
+ } catch {
1285
+ json = void 0;
1286
+ }
1287
+ return {
1288
+ body: json,
1289
+ response
1290
+ };
1291
+ });
1292
+ const { response } = outcome.answer;
1293
+ const served = response.headers.get(operationRootHeader);
1294
+ if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
1295
+ const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
1296
+ const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
1297
+ return {
1298
+ ok: false,
1299
+ code: error.code,
1300
+ fix: error.fix,
1301
+ message,
1302
+ status: 409
1303
+ };
1304
+ }
1305
+ if (outcome.ok) return {
1306
+ ok: true,
1307
+ value: outcome.value
1308
+ };
1309
+ const failure = outcome.error ?? readOperationRpcError(isRecordOrFunction(outcome.answer.body) ? {
1310
+ status: response.status,
1311
+ ...outcome.answer.body
1312
+ } : void 0);
1313
+ if (failure) {
1314
+ if (target.roots?.length && failure.status === 401) failure.fix = `Pass --url ${base.href.slice(0, -1)} to send credentials. A command sends none to the dev server that it finds. ${failure.fix ?? "Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key that `vitehub secret console-key` printed, and its public key in VITEHUB_CONSOLE_KEY_<NAME> on the app."}`;
1315
+ if ((failure.status === 401 || failure.status === 403) && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
1316
+ return {
1317
+ ok: false,
1318
+ ...failure
1319
+ };
1320
+ }
1321
+ if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
1322
+ return unreachable(`${url.origin} did not answer as a ViteHub app (HTTP ${response.status}). Pass the origin of an app that runs ViteHub.`, response.status);
1323
+ } catch (error) {
1324
+ return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
1325
+ }
1326
+ }
1327
+ /**
1328
+ * Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
1329
+ * started. Never throws. Without a dev server the result is an `INTERNAL_R0024` failure that says to start one.
1330
+ */
1331
+ async function callOperationFromCli(call, name, input) {
1332
+ let roots;
1333
+ try {
1334
+ roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
1335
+ } catch {
1336
+ roots = [call.rootDir];
1337
+ }
1338
+ const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
1339
+ if (!url) return unreachable(`No dev server is running for ${roots.at(-1)}.`);
1340
+ return await callOperation({
1341
+ ...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
1342
+ env: call.env,
1343
+ ...call.fetch ? { fetch: call.fetch } : {},
1344
+ ...call.url ? {} : { roots },
1345
+ ...call.timeout ? { timeout: call.timeout } : {},
1346
+ url
1347
+ }, name, input);
1348
+ }
1349
+ /** Align rows of text cells in columns for CLI output. The last column is not padded. */
1350
+ function table(rows) {
1351
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
1352
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
1353
+ }
1354
+ //#endregion
1355
+ export { writeCliFailure as A, isServerEnvironment as C, readViteHubDevServerFile as D, askOnTerminal as E, cloneRecord as M, isRecord as N, readViteHubDevTargetOption as O, isRecordOrFunction as P, getResolvedFeatureOptions as S, shouldSkipViteProviderBuild as T, invariant as _, operationRootHeader as a, createNoExternalAddition as b, projectRootHash as c, toOperationFailure as d, defineOperation as f, readOperationRpcCall as g, operationRpcRefusal as h, createOperationRegistry as i, writeViteHubDevServerFile as j, removeViteHubDevServerFile as k, runOperation as l, operationRpcPath as m, callOperationFromCli as n, operationRpcHeader as o, answerOperationRpc as p, collectOperationContributions as r, operationsOf as s, assertOperationProject as t, table as u, internalErrorDiagnostics as v, resolveViteHubProjectRoot as w, getDeploymentHost as x, VITEHUB_PROJECT_ROOT as y };