@vite-hub/cli 0.6.1 → 0.8.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/README.md +6 -3
- package/dist/{commands-FOmqEZUi.js → commands-w7tEEJph.js} +469 -160
- package/dist/console-apps-BQX-Np9Q.js +271 -0
- package/dist/console-auth-cCodgT_T.js +2813 -0
- package/dist/{console-env-lQ3_eMOy.js → console-env-eXdVI6kw.js} +7 -4
- package/dist/{deploy-DDen0JC0.js → deploy-CqR6pJa-.js} +49 -17
- package/dist/dist-CEIUyD15.js +2495 -0
- package/dist/env-D_CN5DyX.js +2169 -0
- package/dist/envelope-BJQ7xPyX.js +99 -0
- package/dist/help-cache-BI6y5pN8.js +195 -0
- package/dist/index.d.ts +13 -14
- package/dist/index.js +217 -66
- package/dist/link-BRNWNqT9.js +663 -0
- package/dist/provision-9QsGgeiq.js +1741 -0
- package/dist/{provision-kiD8Emd7.d.ts → provision-ByxmUa19.d.ts} +16 -1
- package/dist/provision-Fiosv3Un.js +1391 -0
- package/dist/setup/index.d.ts +37 -15
- package/dist/setup/index.js +12 -9
- package/dist/status-gjvZVutV.js +599 -0
- package/dist/vercel-B5CJLsT0.js +701 -0
- package/package.json +5 -4
- package/dist/env-DzYHxq9A.js +0 -5657
- package/dist/provision-YzxNsbhs.js +0 -4139
- package/dist/rolldown-runtime-BJohB4LM.js +0 -13
|
@@ -1,4139 +0,0 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
|
-
import { spawn } from "node:child_process";
|
|
3
|
-
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
|
-
import { dirname, join, resolve } from "pathe";
|
|
5
|
-
import { defineDiagnostics } from "nostics";
|
|
6
|
-
import { chmod, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
7
|
-
import { basename as basename$1, dirname as dirname$1, join as join$1, parse, resolve as resolve$1 } from "node:path";
|
|
8
|
-
import "node:readline/promises";
|
|
9
|
-
import "node:url";
|
|
10
|
-
import { homedir, hostname, tmpdir } from "node:os";
|
|
11
|
-
import { createBirpc } from "birpc";
|
|
12
|
-
import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
13
|
-
import { parseArgs } from "node:util";
|
|
14
|
-
// ../internal/dist/error-diagnostics-B5oT1e3D.js
|
|
15
|
-
const dynamicError$1 = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
16
|
-
const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
17
|
-
docsBase: "https://vitehub.dev/docs/development/diagnostics",
|
|
18
|
-
codes: {
|
|
19
|
-
INTERNAL_R0012: {
|
|
20
|
-
...dynamicError$1,
|
|
21
|
-
fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
|
|
22
|
-
},
|
|
23
|
-
INTERNAL_R0013: {
|
|
24
|
-
...dynamicError$1,
|
|
25
|
-
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."
|
|
26
|
-
},
|
|
27
|
-
INTERNAL_R0014: {
|
|
28
|
-
why: ({ path }) => `Cannot read Provision State from "${path}".`,
|
|
29
|
-
fix: "Check file access and restore valid JSON while preserving existing resource IDs."
|
|
30
|
-
},
|
|
31
|
-
INTERNAL_R0020: {
|
|
32
|
-
fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
|
|
33
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
34
|
-
},
|
|
35
|
-
INTERNAL_R0021: {
|
|
36
|
-
fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
|
|
37
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
38
|
-
},
|
|
39
|
-
INTERNAL_R0022: {
|
|
40
|
-
fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields, and the list_operations tool of the ViteHub MCP gives the input schema of each operation.",
|
|
41
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
42
|
-
},
|
|
43
|
-
INTERNAL_R0024: {
|
|
44
|
-
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>.",
|
|
45
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
46
|
-
},
|
|
47
|
-
INTERNAL_R0023: {
|
|
48
|
-
fix: "Ask for access to the section of this operation.",
|
|
49
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
50
|
-
},
|
|
51
|
-
INTERNAL_B0001: {
|
|
52
|
-
...dynamicError$1,
|
|
53
|
-
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."
|
|
54
|
-
},
|
|
55
|
-
INTERNAL_B0015: {
|
|
56
|
-
...dynamicError$1,
|
|
57
|
-
fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
|
|
58
|
-
},
|
|
59
|
-
INTERNAL_B0016: {
|
|
60
|
-
...dynamicError$1,
|
|
61
|
-
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."
|
|
62
|
-
},
|
|
63
|
-
INTERNAL_B0017: {
|
|
64
|
-
...dynamicError$1,
|
|
65
|
-
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."
|
|
66
|
-
},
|
|
67
|
-
INTERNAL_B0018: {
|
|
68
|
-
...dynamicError$1,
|
|
69
|
-
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."
|
|
70
|
-
},
|
|
71
|
-
INTERNAL_B0019: {
|
|
72
|
-
...dynamicError$1,
|
|
73
|
-
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."
|
|
74
|
-
},
|
|
75
|
-
INTERNAL_B0020: {
|
|
76
|
-
...dynamicError$1,
|
|
77
|
-
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."
|
|
78
|
-
},
|
|
79
|
-
INTERNAL_B0021: {
|
|
80
|
-
...dynamicError$1,
|
|
81
|
-
fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
|
|
82
|
-
},
|
|
83
|
-
INTERNAL_B0022: {
|
|
84
|
-
...dynamicError$1,
|
|
85
|
-
fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
|
|
86
|
-
},
|
|
87
|
-
INTERNAL_B0025: {
|
|
88
|
-
...dynamicError$1,
|
|
89
|
-
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."
|
|
90
|
-
},
|
|
91
|
-
INTERNAL_B0026: {
|
|
92
|
-
...dynamicError$1,
|
|
93
|
-
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>\")`."
|
|
94
|
-
},
|
|
95
|
-
INTERNAL_B0027: {
|
|
96
|
-
...dynamicError$1,
|
|
97
|
-
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`."
|
|
98
|
-
},
|
|
99
|
-
INTERNAL_B0028: {
|
|
100
|
-
...dynamicError$1,
|
|
101
|
-
fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
|
|
102
|
-
},
|
|
103
|
-
INTERNAL_B0029: {
|
|
104
|
-
...dynamicError$1,
|
|
105
|
-
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."
|
|
106
|
-
},
|
|
107
|
-
INTERNAL_B0031: {
|
|
108
|
-
...dynamicError$1,
|
|
109
|
-
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."
|
|
110
|
-
},
|
|
111
|
-
INTERNAL_B0032: {
|
|
112
|
-
...dynamicError$1,
|
|
113
|
-
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."
|
|
114
|
-
},
|
|
115
|
-
INTERNAL_B0035: {
|
|
116
|
-
...dynamicError$1,
|
|
117
|
-
fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
|
|
118
|
-
},
|
|
119
|
-
INTERNAL_B0039: {
|
|
120
|
-
...dynamicError$1,
|
|
121
|
-
fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
|
|
122
|
-
},
|
|
123
|
-
INTERNAL_B0040: {
|
|
124
|
-
...dynamicError$1,
|
|
125
|
-
fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
|
|
126
|
-
},
|
|
127
|
-
INTERNAL_B0043: {
|
|
128
|
-
...dynamicError$1,
|
|
129
|
-
fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
|
|
130
|
-
},
|
|
131
|
-
INTERNAL_B0046: {
|
|
132
|
-
...dynamicError$1,
|
|
133
|
-
fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
|
|
134
|
-
},
|
|
135
|
-
INTERNAL_B0047: {
|
|
136
|
-
...dynamicError$1,
|
|
137
|
-
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."
|
|
138
|
-
},
|
|
139
|
-
INTERNAL_B0048: {
|
|
140
|
-
fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
|
|
141
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
142
|
-
},
|
|
143
|
-
INTERNAL_B0049: {
|
|
144
|
-
fix: "Set `cli: { namespace, command }` on one of the two operations.",
|
|
145
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
146
|
-
},
|
|
147
|
-
INTERNAL_B0050: {
|
|
148
|
-
fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
|
|
149
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
150
|
-
},
|
|
151
|
-
INTERNAL_B0051: {
|
|
152
|
-
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}.`,
|
|
153
|
-
fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
|
|
154
|
-
},
|
|
155
|
-
INTERNAL_B0052: {
|
|
156
|
-
why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
|
|
157
|
-
fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
|
|
158
|
-
},
|
|
159
|
-
INTERNAL_R0025: {
|
|
160
|
-
fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
|
|
161
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
162
|
-
},
|
|
163
|
-
INTERNAL_R0026: {
|
|
164
|
-
why: "The server parsed a destructive operation that the CLI did not confirm.",
|
|
165
|
-
fix: "Review the operation, then run it again with --yes to confirm the change."
|
|
166
|
-
},
|
|
167
|
-
INTERNAL_C0001: {
|
|
168
|
-
...dynamicError$1,
|
|
169
|
-
fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
|
|
170
|
-
},
|
|
171
|
-
INTERNAL_C0002: {
|
|
172
|
-
...dynamicError$1,
|
|
173
|
-
fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
|
|
174
|
-
},
|
|
175
|
-
INTERNAL_R0001: {
|
|
176
|
-
...dynamicError$1,
|
|
177
|
-
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."
|
|
178
|
-
},
|
|
179
|
-
INTERNAL_R0002: {
|
|
180
|
-
...dynamicError$1,
|
|
181
|
-
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."
|
|
182
|
-
},
|
|
183
|
-
INTERNAL_R0004: {
|
|
184
|
-
...dynamicError$1,
|
|
185
|
-
fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
|
|
186
|
-
},
|
|
187
|
-
INTERNAL_R0005: {
|
|
188
|
-
...dynamicError$1,
|
|
189
|
-
fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
|
|
190
|
-
},
|
|
191
|
-
INTERNAL_R0006: {
|
|
192
|
-
...dynamicError$1,
|
|
193
|
-
fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
|
|
194
|
-
},
|
|
195
|
-
INTERNAL_R0007: {
|
|
196
|
-
...dynamicError$1,
|
|
197
|
-
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."
|
|
198
|
-
},
|
|
199
|
-
INTERNAL_R0008: {
|
|
200
|
-
...dynamicError$1,
|
|
201
|
-
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."
|
|
202
|
-
},
|
|
203
|
-
INTERNAL_R0009: {
|
|
204
|
-
...dynamicError$1,
|
|
205
|
-
fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
|
|
206
|
-
},
|
|
207
|
-
INTERNAL_R0010: {
|
|
208
|
-
...dynamicError$1,
|
|
209
|
-
fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
|
|
210
|
-
},
|
|
211
|
-
INTERNAL_R0011: {
|
|
212
|
-
...dynamicError$1,
|
|
213
|
-
fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
|
|
214
|
-
},
|
|
215
|
-
INTERNAL_CONSOLE_KEY_NAME_INVALID: {
|
|
216
|
-
why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
|
|
217
|
-
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>`."
|
|
218
|
-
},
|
|
219
|
-
INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
|
|
220
|
-
why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
|
|
221
|
-
fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
|
|
222
|
-
},
|
|
223
|
-
INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
|
|
224
|
-
why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
|
|
225
|
-
fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
|
|
226
|
-
},
|
|
227
|
-
INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
|
|
228
|
-
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 _.`,
|
|
229
|
-
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>`."
|
|
230
|
-
},
|
|
231
|
-
INTERNAL_DEV_SERVER_NOT_FOUND: {
|
|
232
|
-
why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
|
|
233
|
-
fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
|
|
234
|
-
},
|
|
235
|
-
INTERNAL_FORGE_NOT_INSTALLED: {
|
|
236
|
-
why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
|
|
237
|
-
fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
|
|
238
|
-
},
|
|
239
|
-
INTERNAL_MCP_ARGUMENTS_INVALID: {
|
|
240
|
-
why: ({ detail }) => detail,
|
|
241
|
-
fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
|
|
242
|
-
},
|
|
243
|
-
INTERNAL_MCP_METHOD_FAILED: {
|
|
244
|
-
why: ({ name }) => `${name} failed on the server.`,
|
|
245
|
-
fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
|
|
246
|
-
},
|
|
247
|
-
INTERNAL_MCP_RESOURCE_NOT_FOUND: {
|
|
248
|
-
why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
|
|
249
|
-
fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
|
|
250
|
-
},
|
|
251
|
-
INTERNAL_PRESET_OPTION_UNKNOWN: {
|
|
252
|
-
why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
|
|
253
|
-
fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
|
|
254
|
-
},
|
|
255
|
-
INTERNAL_PRESET_TUPLE_INVALID: {
|
|
256
|
-
why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
|
|
257
|
-
fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
|
|
258
|
-
},
|
|
259
|
-
INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT: {
|
|
260
|
-
why: ({ first, name, second }) => `[vitehub] One server function needs ${name} from two installations: ${first} and ${second}.`,
|
|
261
|
-
fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`, then build again."
|
|
262
|
-
},
|
|
263
|
-
INTERNAL_SECRET_PURPOSE_MISSING: {
|
|
264
|
-
why: "[vitehub] A derived secret requires a purpose.",
|
|
265
|
-
fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
|
|
266
|
-
},
|
|
267
|
-
INTERNAL_SECRET_TOO_SHORT: {
|
|
268
|
-
why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
|
|
269
|
-
fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
|
|
270
|
-
},
|
|
271
|
-
INTERNAL_SITE_TOKEN_TOO_LONG: {
|
|
272
|
-
why: ({ length, maximum }) => `The Site access token is ${length} characters, and an app accepts ${maximum}.`,
|
|
273
|
-
fix: "Open the app with a shorter path, or give the person and the project shorter names, so that the Site access token fits."
|
|
274
|
-
},
|
|
275
|
-
INTERNAL_SQLITE_ARGUMENT_INVALID: {
|
|
276
|
-
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",
|
|
277
|
-
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."
|
|
278
|
-
},
|
|
279
|
-
INTERNAL_SQLITE_INTEGER_UNSAFE: {
|
|
280
|
-
why: "Received integer which cannot be safely represented as a JavaScript number",
|
|
281
|
-
fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
|
|
282
|
-
},
|
|
283
|
-
INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
|
|
284
|
-
why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
|
|
285
|
-
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 })`."
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
});
|
|
289
|
-
// ../internal/dist/object.js
|
|
290
|
-
/** A non-null object that is not an array. Functions do not pass. */
|
|
291
|
-
function isRecord(value) {
|
|
292
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
293
|
-
}
|
|
294
|
-
/** A non-null object or a function that is not an array. */
|
|
295
|
-
function isRecordOrFunction(value) {
|
|
296
|
-
return Object(value) === value && !Array.isArray(value);
|
|
297
|
-
}
|
|
298
|
-
// ../internal/dist/cli.js
|
|
299
|
-
/** Validate an explicit `--url` before sending a Console request. The caller adds the RPC path. */
|
|
300
|
-
function appUrlError(url) {
|
|
301
|
-
let base;
|
|
302
|
-
try {
|
|
303
|
-
base = new URL(url);
|
|
304
|
-
} catch {
|
|
305
|
-
return "--url must be a URL.";
|
|
306
|
-
}
|
|
307
|
-
const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
|
|
308
|
-
if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return "--url must use HTTPS, except for localhost.";
|
|
309
|
-
if (base.username || base.password || base.search || base.hash) return "--url must not contain credentials, a query, or a fragment.";
|
|
310
|
-
const consolePath = /(?:^|\/)_vitehub(?:\/|$)/.exec(base.pathname);
|
|
311
|
-
if (consolePath) return `--url is the app URL, not the Console URL. Pass --url ${`${base.origin}${base.pathname.slice(0, consolePath.index).replace(/\/$/, "")}`}.`;
|
|
312
|
-
}
|
|
313
|
-
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
314
|
-
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
315
|
-
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
316
|
-
const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
|
|
317
|
-
const stdoutRedirectGlobal = globalThis;
|
|
318
|
-
/**
|
|
319
|
-
* Sends `process.stdout` writes to stderr while `run` loads project config.
|
|
320
|
-
* Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
|
|
321
|
-
*/
|
|
322
|
-
async function withStdoutOnStderr(run, stderr = process.stderr) {
|
|
323
|
-
getStableStdoutWrite();
|
|
324
|
-
const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
|
|
325
|
-
let release;
|
|
326
|
-
stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
|
|
327
|
-
release = resolve;
|
|
328
|
-
});
|
|
329
|
-
await previous;
|
|
330
|
-
const write = process.stdout.write;
|
|
331
|
-
if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
|
|
332
|
-
stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
|
|
333
|
-
stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
|
|
334
|
-
}
|
|
335
|
-
stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
|
|
336
|
-
process.stdout.write = ((chunk, encoding, callback) => {
|
|
337
|
-
const done = typeof encoding === "function" ? encoding : callback;
|
|
338
|
-
let called = false;
|
|
339
|
-
const onComplete = (error) => {
|
|
340
|
-
if (called) return;
|
|
341
|
-
called = true;
|
|
342
|
-
done?.(error);
|
|
343
|
-
};
|
|
344
|
-
const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
|
|
345
|
-
if (done && !called) {
|
|
346
|
-
if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
|
|
347
|
-
else if (stderr.write.length < 2) onComplete();
|
|
348
|
-
}
|
|
349
|
-
return result;
|
|
350
|
-
});
|
|
351
|
-
try {
|
|
352
|
-
return await run();
|
|
353
|
-
} finally {
|
|
354
|
-
process.stdout.write = write;
|
|
355
|
-
stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
|
|
356
|
-
release();
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
/**
|
|
360
|
-
* A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
|
|
361
|
-
* Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
|
|
362
|
-
* config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
|
|
363
|
-
* then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
|
|
364
|
-
*/
|
|
365
|
-
function createCliDiscoveryNitroCloser() {
|
|
366
|
-
const instances = [];
|
|
367
|
-
return {
|
|
368
|
-
close: async () => {
|
|
369
|
-
await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
|
|
370
|
-
},
|
|
371
|
-
plugin: {
|
|
372
|
-
name: "vite-hub/cli-discovery-nitro",
|
|
373
|
-
nitro: { setup: (nitro) => {
|
|
374
|
-
instances.push(nitro);
|
|
375
|
-
} }
|
|
376
|
-
}
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
/** Let Vite load its config normally, without overriding the root declared by the project. */
|
|
380
|
-
function viteCliProjectConfig(rootDir) {
|
|
381
|
-
const configFile = [
|
|
382
|
-
"js",
|
|
383
|
-
"mjs",
|
|
384
|
-
"ts",
|
|
385
|
-
"cjs",
|
|
386
|
-
"mts",
|
|
387
|
-
"cts"
|
|
388
|
-
].map((extension) => resolve$1(rootDir, `vite.config.${extension}`)).find((file) => existsSync(file));
|
|
389
|
-
if (!configFile) return {
|
|
390
|
-
root: rootDir,
|
|
391
|
-
plugins: []
|
|
392
|
-
};
|
|
393
|
-
return {
|
|
394
|
-
configFile,
|
|
395
|
-
plugins: [{
|
|
396
|
-
name: "vite-hub/cli-discovery-root",
|
|
397
|
-
enforce: "pre",
|
|
398
|
-
config: {
|
|
399
|
-
order: "pre",
|
|
400
|
-
handler: ({ root }) => ({ root: resolve$1(rootDir, root || ".") })
|
|
401
|
-
}
|
|
402
|
-
}]
|
|
403
|
-
};
|
|
404
|
-
}
|
|
405
|
-
/** Returns the unredirected process stdout writer for payload output. */
|
|
406
|
-
function getStableStdoutWrite() {
|
|
407
|
-
const current = process.stdout.write;
|
|
408
|
-
if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
|
|
409
|
-
stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
|
|
410
|
-
stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
|
|
411
|
-
}
|
|
412
|
-
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
413
|
-
}
|
|
414
|
-
async function resolveContributor(value) {
|
|
415
|
-
return typeof value === "function" ? await value() : value;
|
|
416
|
-
}
|
|
417
|
-
/** Resolves command namespaces and Provision Steps from one contribution per plugin. */
|
|
418
|
-
async function collectViteHubCliContribution(plugins) {
|
|
419
|
-
const namespaces = /* @__PURE__ */ new Map();
|
|
420
|
-
const steps = /* @__PURE__ */ new Map();
|
|
421
|
-
const seeds = /* @__PURE__ */ new Map();
|
|
422
|
-
let publicUrl;
|
|
423
|
-
for (const plugin of plugins) {
|
|
424
|
-
if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
425
|
-
const metadata = plugin.vitehub;
|
|
426
|
-
const contributor = await resolveContributor(metadata?.cli);
|
|
427
|
-
if (!contributor) continue;
|
|
428
|
-
publicUrl ??= contributor.publicUrl;
|
|
429
|
-
for (const namespace of contributor.namespaces) {
|
|
430
|
-
const existing = namespaces.get(namespace.name);
|
|
431
|
-
if (!existing) {
|
|
432
|
-
namespaces.set(namespace.name, {
|
|
433
|
-
...namespace,
|
|
434
|
-
features: [...namespace.features]
|
|
435
|
-
});
|
|
436
|
-
continue;
|
|
437
|
-
}
|
|
438
|
-
const features = new Map(existing.features.map((feature) => [feature.name, feature]));
|
|
439
|
-
for (const feature of namespace.features) features.set(feature.name, feature);
|
|
440
|
-
existing.features = [...features.values()];
|
|
441
|
-
}
|
|
442
|
-
for (const step of contributor.provision ?? []) steps.set(step.id, step);
|
|
443
|
-
for (const seed of contributor.seeds ?? []) seeds.set(seed.name, seed);
|
|
444
|
-
}
|
|
445
|
-
return {
|
|
446
|
-
namespaces: [...namespaces.values()],
|
|
447
|
-
provision: [...steps.values()],
|
|
448
|
-
seeds: [...seeds.values()],
|
|
449
|
-
...publicUrl ? { publicUrl } : {}
|
|
450
|
-
};
|
|
451
|
-
}
|
|
452
|
-
/** File in the project root where the running dev server tells commands where it listens. */
|
|
453
|
-
const viteHubDevServerFile = ".vitehub/dev-server.json";
|
|
454
|
-
/** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
|
|
455
|
-
function readViteHubDevServerFile(root) {
|
|
456
|
-
try {
|
|
457
|
-
const value = JSON.parse(readFileSync(join$1(root, viteHubDevServerFile), "utf8"));
|
|
458
|
-
const url = isRecord(value) ? value.url : void 0;
|
|
459
|
-
const served = isRecord(value) ? value.root : void 0;
|
|
460
|
-
return typeof url === "string" && url && typeof served === "string" && served ? {
|
|
461
|
-
root: served,
|
|
462
|
-
url
|
|
463
|
-
} : void 0;
|
|
464
|
-
} catch {
|
|
465
|
-
return;
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* Where a command finds the dev server of its project: the file that the server wrote in a project root, else
|
|
470
|
-
* `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
|
|
471
|
-
*/
|
|
472
|
-
function findViteHubDevServerUrl(roots, env) {
|
|
473
|
-
for (const root of roots) {
|
|
474
|
-
const file = readViteHubDevServerFile(root);
|
|
475
|
-
if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
|
|
476
|
-
}
|
|
477
|
-
return env["VITEHUB_DEV_SERVER_URL"] || void 0;
|
|
478
|
-
}
|
|
479
|
-
// ../internal/dist/invariant.js
|
|
480
|
-
const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
481
|
-
docsBase: "https://vitehub.dev/docs/development/diagnostics",
|
|
482
|
-
codes: { INTERNAL_INVARIANT_FAILED: {
|
|
483
|
-
why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
|
|
484
|
-
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."
|
|
485
|
-
} }
|
|
486
|
-
});
|
|
487
|
-
/**
|
|
488
|
-
* The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
|
|
489
|
-
* Use a code from the package catalog when a developer can cause the error or fix it.
|
|
490
|
-
*/
|
|
491
|
-
function invariantError(what) {
|
|
492
|
-
return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
|
|
493
|
-
}
|
|
494
|
-
/** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
|
|
495
|
-
function invariant(condition, what) {
|
|
496
|
-
if (!condition) throw invariantError(what);
|
|
497
|
-
}
|
|
498
|
-
// ../internal/dist/features.js
|
|
499
|
-
/**
|
|
500
|
-
* The feature keys of `vitehub({...})`. `vitehub add <feature>` and `vitehub status` read this list before the owner
|
|
501
|
-
* package of a feature is installed, so the catalog is plain data with no owner imports.
|
|
502
|
-
*/
|
|
503
|
-
const featureIds = [
|
|
504
|
-
"agent",
|
|
505
|
-
"auth",
|
|
506
|
-
"blob",
|
|
507
|
-
"browser",
|
|
508
|
-
"cache",
|
|
509
|
-
"channels",
|
|
510
|
-
"comments",
|
|
511
|
-
"connections",
|
|
512
|
-
"console",
|
|
513
|
-
"database",
|
|
514
|
-
"email",
|
|
515
|
-
"env",
|
|
516
|
-
"i18n",
|
|
517
|
-
"kv",
|
|
518
|
-
"mcp",
|
|
519
|
-
"observability",
|
|
520
|
-
"queue",
|
|
521
|
-
"rateLimit",
|
|
522
|
-
"realtime",
|
|
523
|
-
"sandboxTask",
|
|
524
|
-
"schedule",
|
|
525
|
-
"workflow",
|
|
526
|
-
"workspace"
|
|
527
|
-
];
|
|
528
|
-
/** `dev` stores default Node development support. Use `featureSupport()` with the configured host for development lookups. */
|
|
529
|
-
const featureHosts = [
|
|
530
|
-
"dev",
|
|
531
|
-
"cloudflare",
|
|
532
|
-
"vercel",
|
|
533
|
-
"netlify",
|
|
534
|
-
"deno",
|
|
535
|
-
"node"
|
|
536
|
-
];
|
|
537
|
-
const noHostLimit = "No host limit in ViteHub.";
|
|
538
|
-
function native(driver, display, detail, guarantee = "native") {
|
|
539
|
-
return {
|
|
540
|
-
detail,
|
|
541
|
-
display,
|
|
542
|
-
driver,
|
|
543
|
-
guarantee,
|
|
544
|
-
level: "native"
|
|
545
|
-
};
|
|
546
|
-
}
|
|
547
|
-
function explicit(option, display, detail) {
|
|
548
|
-
return {
|
|
549
|
-
detail,
|
|
550
|
-
display,
|
|
551
|
-
level: "explicit",
|
|
552
|
-
option
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
function unsupported$1(detail) {
|
|
556
|
-
return {
|
|
557
|
-
detail,
|
|
558
|
-
level: "unsupported"
|
|
559
|
-
};
|
|
560
|
-
}
|
|
561
|
-
function everywhere(driver, display, detail = noHostLimit) {
|
|
562
|
-
const support = native(driver, display, detail);
|
|
563
|
-
return {
|
|
564
|
-
cloudflare: support,
|
|
565
|
-
deno: support,
|
|
566
|
-
dev: support,
|
|
567
|
-
netlify: support,
|
|
568
|
-
node: support,
|
|
569
|
-
vercel: support
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
function feature(definition) {
|
|
573
|
-
return {
|
|
574
|
-
devPackages: [],
|
|
575
|
-
enabledByDefault: false,
|
|
576
|
-
implies: [],
|
|
577
|
-
packages: [],
|
|
578
|
-
...definition
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
const sourceExtensions = [
|
|
582
|
-
"ts",
|
|
583
|
-
"mts",
|
|
584
|
-
"js",
|
|
585
|
-
"mjs",
|
|
586
|
-
"cts",
|
|
587
|
-
"cjs"
|
|
588
|
-
];
|
|
589
|
-
/** `<base>.<ext>` for each source extension. */
|
|
590
|
-
function sourceFiles(base) {
|
|
591
|
-
return sourceExtensions.map((extension) => `${base}.${extension}`);
|
|
592
|
-
}
|
|
593
|
-
/**
|
|
594
|
-
* A starter for Definitions in `dir`, one `<name>.ts` file each. With `suffix`, the owner also discovers the Vite
|
|
595
|
-
* form `src/<name>.<suffix>.ts`, and a Definition folder `<dir>/<name>/` when `folder` names its entry file.
|
|
596
|
-
*/
|
|
597
|
-
function starter(dir, template, options = {}) {
|
|
598
|
-
return {
|
|
599
|
-
conflicts: (name) => [
|
|
600
|
-
...sourceFiles(`${dir}/${name}`).slice(1),
|
|
601
|
-
...options.folder ? sourceFiles(`${dir}/${name}/${options.folder}`) : [],
|
|
602
|
-
...options.suffix ? [...sourceFiles(`src/${name}.${options.suffix}`), ...sourceFiles(`${name}.${options.suffix}`)] : []
|
|
603
|
-
],
|
|
604
|
-
dir,
|
|
605
|
-
file: (name) => `${dir}/${name}.ts`,
|
|
606
|
-
template
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
const features = {
|
|
610
|
-
agent: feature({
|
|
611
|
-
definition: starter("server/agents", (name) => `import { defineAgent } from "vite-hub/agent"
|
|
612
|
-
|
|
613
|
-
export default defineAgent({
|
|
614
|
-
driver: { run: () => ({ text: "Hello from ${name}." }) },
|
|
615
|
-
})
|
|
616
|
-
`, {
|
|
617
|
-
folder: "agent",
|
|
618
|
-
suffix: "agent"
|
|
619
|
-
}),
|
|
620
|
-
docs: "/docs/agents",
|
|
621
|
-
enabledByDiscovery: ["agents"],
|
|
622
|
-
hosts: {
|
|
623
|
-
...everywhere("nitro", "Nitro"),
|
|
624
|
-
deno: native("nitro", "Nitro", "Agent routes run in the Nitro output. The Agent Deno runtime is not supported on this host."),
|
|
625
|
-
netlify: native("nitro", "Nitro", "Agent HTTP routes run in generated functions. `agent.invocations` is not supported, so `agent: true` fails the build. Set `agent: { invocations: false }` and configure invocations on each Agent Definition.")
|
|
626
|
-
},
|
|
627
|
-
id: "agent",
|
|
628
|
-
packages: ["@vite-hub/agent"],
|
|
629
|
-
summary: "Agents in `server/agents/` with tools, Capabilities, channels, and invocations.",
|
|
630
|
-
title: "Agent"
|
|
631
|
-
}),
|
|
632
|
-
auth: feature({
|
|
633
|
-
docs: "/docs/auth",
|
|
634
|
-
enabledByDiscovery: sourceFiles("auth"),
|
|
635
|
-
hosts: everywhere("better-auth", "Better Auth"),
|
|
636
|
-
id: "auth",
|
|
637
|
-
packages: [
|
|
638
|
-
"@vite-hub/auth",
|
|
639
|
-
"better-auth",
|
|
640
|
-
"drizzle-orm"
|
|
641
|
-
],
|
|
642
|
-
summary: "Better Auth sign-in, sessions, and organizations, with tables that ViteHub owns.",
|
|
643
|
-
title: "Auth"
|
|
644
|
-
}),
|
|
645
|
-
blob: feature({
|
|
646
|
-
docs: "/docs/blob",
|
|
647
|
-
hosts: {
|
|
648
|
-
cloudflare: native("cloudflare", "R2", "Cloudflare R2 binding or S3-compatible HTTP access."),
|
|
649
|
-
deno: explicit("blob.driver", "S3", "Use a remote S3-compatible store. No Deno-native Blob driver is provided."),
|
|
650
|
-
dev: native("fs", "fs", "Local filesystem storage for development.", "single-host"),
|
|
651
|
-
netlify: native("netlify-blobs", "Netlify Blobs", "Netlify Blobs selected from the detected host."),
|
|
652
|
-
node: native("fs", "fs / S3", "Filesystem, S3-compatible, MinIO, or files-sdk drivers.", "single-host"),
|
|
653
|
-
vercel: native("vercel", "Vercel Blob", "Vercel Blob through the vercel driver.")
|
|
654
|
-
},
|
|
655
|
-
id: "blob",
|
|
656
|
-
packages: ["@vite-hub/blob"],
|
|
657
|
-
providerPackages: { driver: { s3: [
|
|
658
|
-
"@aws-sdk/client-s3",
|
|
659
|
-
"@aws-sdk/lib-storage",
|
|
660
|
-
"@aws-sdk/s3-presigned-post",
|
|
661
|
-
"@aws-sdk/s3-request-presigner"
|
|
662
|
-
] } },
|
|
663
|
-
service: "blob",
|
|
664
|
-
summary: "Object storage for files and uploads, with one API on every host.",
|
|
665
|
-
title: "Blob"
|
|
666
|
-
}),
|
|
667
|
-
browser: feature({
|
|
668
|
-
docs: "/docs/browser",
|
|
669
|
-
enabledByDiscovery: ["browsers"],
|
|
670
|
-
hosts: {
|
|
671
|
-
cloudflare: native("cloudflare", "Browser Run", "Cloudflare Browser Run binding and provider output."),
|
|
672
|
-
deno: unsupported$1("Browser Definitions do not have a Deno provider."),
|
|
673
|
-
dev: unsupported$1("Browser Definitions need the Cloudflare host. Use createBrowser({ driver: localBrowser({ executablePath }) }) from code for a trusted local process."),
|
|
674
|
-
netlify: unsupported$1("Browser Definitions do not have a Netlify provider."),
|
|
675
|
-
node: unsupported$1("The Node host has no built-in Browser Provider. Use localBrowser() from code for a trusted process."),
|
|
676
|
-
vercel: unsupported$1("Browser Definitions do not have a Vercel provider.")
|
|
677
|
-
},
|
|
678
|
-
id: "browser",
|
|
679
|
-
packages: ["@vite-hub/browser"],
|
|
680
|
-
service: "browser",
|
|
681
|
-
summary: "Headless browser sessions for Agents and server code.",
|
|
682
|
-
title: "Browser"
|
|
683
|
-
}),
|
|
684
|
-
cache: feature({
|
|
685
|
-
developmentOverrides: [
|
|
686
|
-
"cloudflare",
|
|
687
|
-
"deno",
|
|
688
|
-
"vercel"
|
|
689
|
-
],
|
|
690
|
-
docs: "/docs/reference/config-options",
|
|
691
|
-
hosts: {
|
|
692
|
-
cloudflare: native("cloudflare", "Workers KV", "Workers KV binding `CACHE`."),
|
|
693
|
-
deno: native("deno-kv", "Deno KV", "Native Deno KV."),
|
|
694
|
-
dev: native("fs-lite", "fs-lite", "`.vitehub/data/cache` during development.", "single-host"),
|
|
695
|
-
netlify: explicit("cache.driver", "KV", "`cache: true` has no default store on Netlify. Set `cache: { driver: \"kv\" }` and enable `kv`."),
|
|
696
|
-
node: native("fs-lite", "fs-lite", "`.vitehub/data/cache` on the server disk.", "single-host"),
|
|
697
|
-
vercel: native("vercel", "Runtime Cache", "Vercel Runtime Cache.")
|
|
698
|
-
},
|
|
699
|
-
id: "cache",
|
|
700
|
-
summary: "Storage for Nitro's cache mount, used by defineCachedFunction() and defineCachedEventHandler().",
|
|
701
|
-
title: "Cache"
|
|
702
|
-
}),
|
|
703
|
-
channels: feature({
|
|
704
|
-
docs: "/docs/channels",
|
|
705
|
-
enabledByDiscovery: ["channels"],
|
|
706
|
-
hosts: everywhere("nitro", "Nitro"),
|
|
707
|
-
id: "channels",
|
|
708
|
-
packages: ["@vite-hub/channels"],
|
|
709
|
-
summary: "Chat channels such as Slack, Discord, and GitHub that deliver messages to Agents.",
|
|
710
|
-
title: "Channels"
|
|
711
|
-
}),
|
|
712
|
-
comments: feature({
|
|
713
|
-
docs: "/docs/comments",
|
|
714
|
-
enabledByDiscovery: [
|
|
715
|
-
"comments.ts",
|
|
716
|
-
"comments.mts",
|
|
717
|
-
"comments.js",
|
|
718
|
-
"comments.mjs"
|
|
719
|
-
],
|
|
720
|
-
hosts: everywhere("database", "Database"),
|
|
721
|
-
id: "comments",
|
|
722
|
-
implies: [{ feature: "database" }],
|
|
723
|
-
packages: ["@vite-hub/comments"],
|
|
724
|
-
summary: "Comments on the app's pages, stored in a ViteHub Database.",
|
|
725
|
-
title: "Comments"
|
|
726
|
-
}),
|
|
727
|
-
connections: feature({
|
|
728
|
-
docs: "/docs/connections",
|
|
729
|
-
enabledByDiscovery: ["connections"],
|
|
730
|
-
hosts: everywhere("database", "Database"),
|
|
731
|
-
id: "connections",
|
|
732
|
-
implies: [{ feature: "database" }],
|
|
733
|
-
packages: [
|
|
734
|
-
"@vite-hub/connections",
|
|
735
|
-
"@vite-hub/database",
|
|
736
|
-
"drizzle-orm"
|
|
737
|
-
],
|
|
738
|
-
summary: "OAuth and API key Connections in `server/connections/`, with grants stored in a Database.",
|
|
739
|
-
title: "Connections"
|
|
740
|
-
}),
|
|
741
|
-
console: feature({
|
|
742
|
-
docs: "/docs/console",
|
|
743
|
-
hosts: everywhere("nitro", "Nitro"),
|
|
744
|
-
id: "console",
|
|
745
|
-
packages: [],
|
|
746
|
-
summary: "The Operations endpoint and MCP at `/_vitehub`, which the hosted Console at console.vitehub.dev and the CLI call.",
|
|
747
|
-
title: "Console"
|
|
748
|
-
}),
|
|
749
|
-
database: feature({
|
|
750
|
-
definition: {
|
|
751
|
-
conflicts: (name) => [
|
|
752
|
-
...sourceFiles(`server/databases/${name}`).slice(1),
|
|
753
|
-
...sourceFiles(`server/databases/${name}/index`),
|
|
754
|
-
...name === "default" ? ["src/database.ts"] : [...sourceFiles(`src/${name}.database`), "src/database.ts"]
|
|
755
|
-
],
|
|
756
|
-
dir: "server/databases",
|
|
757
|
-
file: (name) => `server/databases/${name}.ts`,
|
|
758
|
-
template: (name) => `import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
|
|
759
|
-
import { defineDatabase } from "vite-hub/database"
|
|
760
|
-
|
|
761
|
-
export default defineDatabase({
|
|
762
|
-
${name === "default" ? "" : ` name: ${JSON.stringify(name)},\n`} schema: {
|
|
763
|
-
notes: sqliteTable("notes", {
|
|
764
|
-
id: integer("id").primaryKey(),
|
|
765
|
-
title: text("title").notNull(),
|
|
766
|
-
}),
|
|
767
|
-
},
|
|
768
|
-
})
|
|
769
|
-
`
|
|
770
|
-
},
|
|
771
|
-
developmentOverrides: [
|
|
772
|
-
"deno",
|
|
773
|
-
"netlify",
|
|
774
|
-
"vercel"
|
|
775
|
-
],
|
|
776
|
-
devPackages: ["drizzle-kit"],
|
|
777
|
-
docs: "/docs/database",
|
|
778
|
-
hosts: {
|
|
779
|
-
cloudflare: native("cloudflare", "D1", "Cloudflare D1 binding, with authenticated HTTP available for development. A PostgreSQL Database Definition connects through Hyperdrive or `connection.url`."),
|
|
780
|
-
deno: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. No Deno-native database driver is provided."),
|
|
781
|
-
dev: native("sqlite", "SQLite", "Local SQLite through libSQL and Drizzle.", "single-host"),
|
|
782
|
-
netlify: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. No Netlify-native database driver is provided."),
|
|
783
|
-
node: native("sqlite", "SQLite / libSQL / Postgres", "SQLite or hosted libSQL through the selected Database connection, or a PostgreSQL Database Definition. Several servers can share Postgres and migrate on start under one advisory lock.", "single-host"),
|
|
784
|
-
vercel: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. The default local SQLite file is not supported in Vercel functions.")
|
|
785
|
-
},
|
|
786
|
-
id: "database",
|
|
787
|
-
packages: ["@vite-hub/database", "drizzle-orm"],
|
|
788
|
-
summary: "Drizzle Databases in `server/databases/` with migrations and a local SQLite in development.",
|
|
789
|
-
title: "Database"
|
|
790
|
-
}),
|
|
791
|
-
email: feature({
|
|
792
|
-
docs: "/docs/email",
|
|
793
|
-
hosts: {
|
|
794
|
-
cloudflare: native("cloudflare", "Cloudflare Email", "The Cloudflare Email driver is the default. Resend is also supported."),
|
|
795
|
-
deno: explicit("email.driver", "Resend", "Configure the built-in fetch-based Resend driver."),
|
|
796
|
-
dev: native("log", "Log", "`email: true` keeps each message in the development outbox and sends nothing. Set `email.driver` for a production build.", "process-local"),
|
|
797
|
-
netlify: explicit("email.driver", "Resend", "Configure the built-in Resend driver."),
|
|
798
|
-
node: explicit("email.driver", "Resend / SMTP / custom", "Configure Resend, `smtp` with the `nodemailer` package, or a driver module for another provider."),
|
|
799
|
-
vercel: explicit("email.driver", "Resend", "Configure the built-in Resend driver.")
|
|
800
|
-
},
|
|
801
|
-
developmentOverrides: [
|
|
802
|
-
"deno",
|
|
803
|
-
"netlify",
|
|
804
|
-
"vercel"
|
|
805
|
-
],
|
|
806
|
-
id: "email",
|
|
807
|
-
packages: ["@vite-hub/email"],
|
|
808
|
-
summary: "Send email from server code and Agents, with a development outbox.",
|
|
809
|
-
title: "Email"
|
|
810
|
-
}),
|
|
811
|
-
env: feature({
|
|
812
|
-
docs: "/docs/env",
|
|
813
|
-
enabledByDefault: true,
|
|
814
|
-
hosts: everywhere("nitro", "Nitro"),
|
|
815
|
-
id: "env",
|
|
816
|
-
summary: "Typed environment variables and secrets, validated at build and at runtime.",
|
|
817
|
-
title: "Env"
|
|
818
|
-
}),
|
|
819
|
-
i18n: feature({
|
|
820
|
-
docs: "/docs/i18n",
|
|
821
|
-
hosts: everywhere("nitro", "Nitro 3", "Requires Nitro 3 with request async context: Nuxt 4.7 or newer with the nitro package, Nuxt 5, or Vite with Nitro 3. On Nuxt 4, use i18n without i18n.workspace. Nitro 2 and Nuxt before 4.7 are unsupported."),
|
|
822
|
-
id: "i18n",
|
|
823
|
-
packages: ["@vite-hub/i18n"],
|
|
824
|
-
requiredOptions: [{
|
|
825
|
-
option: "i18n.locales",
|
|
826
|
-
detail: "Pass a nonempty JSON array of locale names or set locales in your I18n config."
|
|
827
|
-
}],
|
|
828
|
-
summary: "Messages with translation records for each locale and a locale for each request.",
|
|
829
|
-
title: "I18n"
|
|
830
|
-
}),
|
|
831
|
-
kv: feature({
|
|
832
|
-
developmentOverrides: ["netlify"],
|
|
833
|
-
docs: "/docs/kv",
|
|
834
|
-
hosts: {
|
|
835
|
-
cloudflare: native("cloudflare", "Workers KV", "Cloudflare Workers KV binding."),
|
|
836
|
-
deno: native("deno-kv", "Deno KV", "Native Deno KV through Deno.openKv()."),
|
|
837
|
-
dev: native("fs-lite", "fs-lite", "Local filesystem-backed KV for development.", "single-host"),
|
|
838
|
-
netlify: explicit("kv.driver", "Upstash / Redis", "Set `kv.driver` (or `kv.stores.default.driver` when using multiple stores) to `upstash`, `redis`, or `database`, or set Upstash REST credentials at build time. No Netlify-native KV output is provided. Without them, KV uses a Postgres Default Database, else `fs-lite` files that other function instances cannot read."),
|
|
839
|
-
node: native("fs-lite", "Redis / Postgres / fs-lite", "A table in a Postgres Default Database, else local files. Redis requires kv: { driver: 'redis' }; REDIS_URL supplies its URL on every server. Upstash with REST credentials at build time.", "single-host"),
|
|
840
|
-
vercel: native("upstash", "Upstash", "Upstash Redis with KV REST credentials.")
|
|
841
|
-
},
|
|
842
|
-
id: "kv",
|
|
843
|
-
packages: ["@vite-hub/kv"],
|
|
844
|
-
providerPackages: { driver: { upstash: ["@upstash/redis"] } },
|
|
845
|
-
summary: "Key-value storage with one API on every host.",
|
|
846
|
-
title: "KV"
|
|
847
|
-
}),
|
|
848
|
-
mcp: feature({
|
|
849
|
-
docs: "/docs/mcp",
|
|
850
|
-
hosts: everywhere("nitro", "Nitro"),
|
|
851
|
-
id: "mcp",
|
|
852
|
-
packages: ["@vite-hub/mcp"],
|
|
853
|
-
requiredOptions: [{
|
|
854
|
-
option: "mcp.auth",
|
|
855
|
-
detail: "Choose an access mode when Auth is disabled. With Auth enabled, MCP requires sign-in by default. The optional mode requires Auth and lets anyone call public tools. Set false only when anyone may call every tool."
|
|
856
|
-
}],
|
|
857
|
-
summary: "The app's own MCP server, with one tool per file in `server/mcp/tools/`.",
|
|
858
|
-
title: "MCP server"
|
|
859
|
-
}),
|
|
860
|
-
observability: feature({
|
|
861
|
-
docs: "/docs/agents/observability",
|
|
862
|
-
hosts: everywhere("evlog", "Evlog"),
|
|
863
|
-
id: "observability",
|
|
864
|
-
packages: ["evlog"],
|
|
865
|
-
summary: "Request logs through Evlog, the logs that the Console reads, and Agent telemetry with a service name.",
|
|
866
|
-
title: "Observability"
|
|
867
|
-
}),
|
|
868
|
-
queue: feature({
|
|
869
|
-
definition: starter("server/queues", (name) => `import { defineQueue } from "vite-hub/queue"
|
|
870
|
-
|
|
871
|
-
export default defineQueue<{ id: string }>({
|
|
872
|
-
handler: async ({ payload }) => {
|
|
873
|
-
console.log("${name}", payload.id)
|
|
874
|
-
},
|
|
875
|
-
})
|
|
876
|
-
`, { suffix: "queue" }),
|
|
877
|
-
docs: "/docs/queue",
|
|
878
|
-
enabledByDiscovery: ["queues"],
|
|
879
|
-
hosts: {
|
|
880
|
-
cloudflare: native("cloudflare", "Queues", "Cloudflare Queues bindings and consumers."),
|
|
881
|
-
deno: unsupported$1("No Deno Queue driver is provided."),
|
|
882
|
-
dev: native("local", "Local driver", "The local driver stores jobs in .vitehub/data/queue and runs them in the dev server process.", "single-host"),
|
|
883
|
-
netlify: unsupported$1("Netlify has no Queue driver, so `vitehub({ queue })` fails on Netlify."),
|
|
884
|
-
node: native("local", "Postgres / local driver", "With a Postgres Default Database, the postgres driver keeps jobs in Postgres and every instance runs them. Else the local driver keeps jobs on the disk of one host.", "single-host"),
|
|
885
|
-
vercel: native("vercel", "Vercel Queues", "Vercel Queues callbacks and runtime client.")
|
|
886
|
-
},
|
|
887
|
-
id: "queue",
|
|
888
|
-
packages: ["@vite-hub/queue"],
|
|
889
|
-
providerPackages: { driver: { postgres: ["postgres"] } },
|
|
890
|
-
service: "queue",
|
|
891
|
-
summary: "Background jobs in `server/queues/` with retries and delivery on every supported host.",
|
|
892
|
-
title: "Queue"
|
|
893
|
-
}),
|
|
894
|
-
rateLimit: feature({
|
|
895
|
-
developmentOverrides: ["cloudflare"],
|
|
896
|
-
docs: "/docs/rate-limit",
|
|
897
|
-
hosts: {
|
|
898
|
-
cloudflare: native("cloudflare", "Cloudflare", "Native Cloudflare Rate Limiting binding."),
|
|
899
|
-
deno: unsupported$1("ViteHub has no native Deno Rate Limit driver."),
|
|
900
|
-
dev: native("memory", "memory", "Process-local memory driver for development and tests.", "process-local"),
|
|
901
|
-
netlify: unsupported$1("ViteHub has no native Netlify Rate Limit driver."),
|
|
902
|
-
node: native("memory", "memory, or KV", "Without KV, each process counts alone. With KV on, ViteHub selects the kv provider, which shares the counts when KV uses Redis or a Postgres Database.", "process-local"),
|
|
903
|
-
vercel: unsupported$1("ViteHub has no native Vercel Rate Limit driver.")
|
|
904
|
-
},
|
|
905
|
-
id: "rateLimit",
|
|
906
|
-
packages: ["@vite-hub/rate-limit"],
|
|
907
|
-
service: "rateLimit",
|
|
908
|
-
summary: "Rate limits in `server/rate-limits/` that protect routes and Agent tools.",
|
|
909
|
-
title: "Rate Limit"
|
|
910
|
-
}),
|
|
911
|
-
realtime: feature({
|
|
912
|
-
definition: starter("server/realtime", (name) => `import { defineRealtime } from "vite-hub/realtime"
|
|
913
|
-
|
|
914
|
-
export default defineRealtime({
|
|
915
|
-
authorize: true,
|
|
916
|
-
document: { workspace: "${name}" },
|
|
917
|
-
})
|
|
918
|
-
`),
|
|
919
|
-
developmentOverrides: [
|
|
920
|
-
"cloudflare",
|
|
921
|
-
"deno",
|
|
922
|
-
"netlify",
|
|
923
|
-
"vercel"
|
|
924
|
-
],
|
|
925
|
-
docs: "/docs/realtime",
|
|
926
|
-
enabledByDiscovery: ["realtime"],
|
|
927
|
-
hosts: {
|
|
928
|
-
cloudflare: native("cloudflare", "Durable Objects", "Cloudflare Durable Objects run the production rooms."),
|
|
929
|
-
deno: unsupported$1("Realtime has no distributed Deno driver, and process memory is rejected for the Deno host."),
|
|
930
|
-
dev: native("memory", "memory", "Process-memory driver for local development.", "process-local"),
|
|
931
|
-
netlify: unsupported$1("Realtime has no distributed Netlify driver, and process memory is rejected for the Netlify host."),
|
|
932
|
-
node: native("node", "Postgres or Redis", "Each instance keeps its rooms in memory and shares them through Redis with REDIS_URL, else Postgres on a Postgres Default Database. Without either, rooms stay in one process."),
|
|
933
|
-
vercel: unsupported$1("Realtime has no distributed Vercel driver, and process memory is rejected for the Vercel host.")
|
|
934
|
-
},
|
|
935
|
-
id: "realtime",
|
|
936
|
-
packages: ["@vite-hub/realtime"],
|
|
937
|
-
service: "realtime",
|
|
938
|
-
summary: "Shared rooms with presence and Yjs documents.",
|
|
939
|
-
title: "Realtime"
|
|
940
|
-
}),
|
|
941
|
-
sandboxTask: feature({
|
|
942
|
-
docs: "/docs/sandbox",
|
|
943
|
-
hosts: {
|
|
944
|
-
cloudflare: native("cloudflare", "CF Sandbox", "Cloudflare Sandbox execution provider."),
|
|
945
|
-
deno: unsupported$1("No Deno Sandbox driver is provided."),
|
|
946
|
-
dev: unsupported$1("The default Node host has no Sandbox Provider. With the Cloudflare or Vercel host, `vite dev` runs each Sandbox Task as a process on this machine, with no isolation and no provider account. `sandboxTask: { remote: true }` uses the host's Sandbox instead."),
|
|
947
|
-
netlify: explicit("sandboxTask.driver", "Vercel Sandbox", "The Netlify host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
|
|
948
|
-
node: explicit("sandboxTask.driver", "Vercel Sandbox", "The Node host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
|
|
949
|
-
vercel: native("vercel", "Vercel Sandbox", "Vercel Sandbox execution provider.")
|
|
950
|
-
},
|
|
951
|
-
id: "sandboxTask",
|
|
952
|
-
packages: ["@vite-hub/sandbox"],
|
|
953
|
-
service: "sandbox",
|
|
954
|
-
summary: "Sandbox Tasks in `server/sandbox-tasks/`. Each run starts an isolated Cloudflare or Vercel Sandbox.",
|
|
955
|
-
title: "Sandbox"
|
|
956
|
-
}),
|
|
957
|
-
schedule: feature({
|
|
958
|
-
definition: starter("server/schedules", (name) => `import { defineSchedule } from "vite-hub/schedule"
|
|
959
|
-
|
|
960
|
-
export default defineSchedule({
|
|
961
|
-
cron: "0 * * * *",
|
|
962
|
-
handler: () => {
|
|
963
|
-
console.log("${name}")
|
|
964
|
-
},
|
|
965
|
-
})
|
|
966
|
-
`, { suffix: "schedule" }),
|
|
967
|
-
developmentOverrides: [
|
|
968
|
-
"cloudflare",
|
|
969
|
-
"netlify",
|
|
970
|
-
"vercel"
|
|
971
|
-
],
|
|
972
|
-
docs: "/docs/schedule",
|
|
973
|
-
enabledByDiscovery: ["schedules"],
|
|
974
|
-
hosts: {
|
|
975
|
-
cloudflare: native("cloudflare", "Cron triggers", "Cloudflare scheduled events and Nitro Provider Wake."),
|
|
976
|
-
deno: native("deno", "Deno.cron", "`Deno.cron` output that the generated `.output/main.ts` loads before the Nitro server."),
|
|
977
|
-
dev: native("local", "Local / process", "Local development runner and the explicit process runtime.", "single-host"),
|
|
978
|
-
netlify: native("netlify", "Scheduled fn", "One generated Netlify scheduled function per static Schedule."),
|
|
979
|
-
node: native("process", "process", "Process runtime in the server process. `schedule: true` uses it. Set `providerOutput: false` to wake Schedules yourself. With a Postgres or remote libSQL Default Database, servers claim occurrences in `vitehub_leases`. A run can repeat if its lease expires. Without a shared lease store, run one server.", "single-host"),
|
|
980
|
-
vercel: native("vercel", "Vercel Cron", "Vercel Cron Jobs provider output.")
|
|
981
|
-
},
|
|
982
|
-
id: "schedule",
|
|
983
|
-
packages: ["@vite-hub/schedule"],
|
|
984
|
-
summary: "Cron Schedules in `server/schedules/` that run on the host's scheduler.",
|
|
985
|
-
title: "Schedule"
|
|
986
|
-
}),
|
|
987
|
-
workflow: feature({
|
|
988
|
-
definition: starter("server/workflows", () => `import { defineWorkflow } from "vite-hub/workflow"
|
|
989
|
-
|
|
990
|
-
export default defineWorkflow<{ id: string }>({
|
|
991
|
-
handler: async ({ payload }) => {
|
|
992
|
-
return { id: payload.id }
|
|
993
|
-
},
|
|
994
|
-
})
|
|
995
|
-
`, {
|
|
996
|
-
folder: "index",
|
|
997
|
-
suffix: "workflow"
|
|
998
|
-
}),
|
|
999
|
-
docs: "/docs/workflows",
|
|
1000
|
-
enabledByDiscovery: ["workflows"],
|
|
1001
|
-
hosts: {
|
|
1002
|
-
cloudflare: native("cloudflare", "CF Workflows", "Cloudflare Workflows provider."),
|
|
1003
|
-
deno: explicit("workflow.driver", "OpenWorkflow", "Set `workflow.driver` to \"openworkflow\" with `workflow.postgres.url`, and start its worker. A build without a driver fails."),
|
|
1004
|
-
dev: native("openworkflow", "OpenWorkflow", "The Node host runs OpenWorkflow and its worker in the dev server, on .vitehub/data/openworkflow.sqlite.db. workflow.remote lets it use the Postgres Default Database or OPENWORKFLOW_POSTGRES_URL."),
|
|
1005
|
-
netlify: explicit("workflow.driver", "OpenWorkflow", "Use OpenWorkflow explicitly. No Netlify-native Workflow driver is provided."),
|
|
1006
|
-
node: {
|
|
1007
|
-
...native("openworkflow", "OpenWorkflow", "OpenWorkflow is the default, and each server runs its worker. It uses OPENWORKFLOW_POSTGRES_URL or the Postgres Default Database. Without them, runs use a SQLite file on one host.", "single-host"),
|
|
1008
|
-
envOverrides: ["OPENWORKFLOW_POSTGRES_URL"].map((env) => ({
|
|
1009
|
-
env,
|
|
1010
|
-
support: native("openworkflow", "OpenWorkflow (Postgres)", `${env} selects Postgres. Several servers can run the worker on the same database, and each run executes once.`)
|
|
1011
|
-
}))
|
|
1012
|
-
},
|
|
1013
|
-
vercel: native("vercel", "Vercel Workflow", "Vercel Workflow provider and Workflow DevKit output.")
|
|
1014
|
-
},
|
|
1015
|
-
id: "workflow",
|
|
1016
|
-
packages: ["@vite-hub/workflow"],
|
|
1017
|
-
summary: "Durable Workflows in `server/workflows/` with steps and driver retries.",
|
|
1018
|
-
title: "Workflow"
|
|
1019
|
-
}),
|
|
1020
|
-
workspace: feature({
|
|
1021
|
-
developmentOverrides: [
|
|
1022
|
-
"cloudflare",
|
|
1023
|
-
"deno",
|
|
1024
|
-
"netlify",
|
|
1025
|
-
"vercel"
|
|
1026
|
-
],
|
|
1027
|
-
docs: "/docs/workspace",
|
|
1028
|
-
enabledByDiscovery: ["workspaces"],
|
|
1029
|
-
hosts: {
|
|
1030
|
-
cloudflare: native("memory", "Artifacts / GitHub", "Memory by default, or Cloudflare Artifacts beta and GitHub for durable state.", "process-local"),
|
|
1031
|
-
deno: explicit("workspace.store", "GitHub", "Select the GitHub Workspace Store explicitly for durable state."),
|
|
1032
|
-
dev: native("local", "local / memory", "Local filesystem or in-memory Workspace Store.", "single-host"),
|
|
1033
|
-
netlify: explicit("workspace.store", "GitHub", "Select the GitHub Workspace Store explicitly for durable state."),
|
|
1034
|
-
node: native("local", "local / GitHub", "Local filesystem, memory, or GitHub Workspace Store.", "single-host"),
|
|
1035
|
-
vercel: {
|
|
1036
|
-
...native("memory", "memory / Blob / GitHub", "Process-local memory by default. BLOB_READ_WRITE_TOKEN selects Vercel Blob; GitHub can be selected explicitly for durable state.", "process-local"),
|
|
1037
|
-
envOverrides: [{
|
|
1038
|
-
env: "BLOB_READ_WRITE_TOKEN",
|
|
1039
|
-
support: native("vercel", "Blob / GitHub", "BLOB_READ_WRITE_TOKEN selects durable Vercel Blob storage by default.")
|
|
1040
|
-
}]
|
|
1041
|
-
}
|
|
1042
|
-
},
|
|
1043
|
-
id: "workspace",
|
|
1044
|
-
packages: ["@vite-hub/workspace"],
|
|
1045
|
-
summary: "File workspaces that Agents read and edit, backed by local, Blob, or GitHub stores.",
|
|
1046
|
-
title: "Workspace"
|
|
1047
|
-
})
|
|
1048
|
-
};
|
|
1049
|
-
/** Packages needed by a feature, its provider, and its enabled feature integrations. */
|
|
1050
|
-
function featurePackages(id, value, host, enabled = []) {
|
|
1051
|
-
const definition = features[id];
|
|
1052
|
-
const options = value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1053
|
-
const stores = options?.stores;
|
|
1054
|
-
const selected = ((id === "blob" || id === "kv") && stores && typeof stores === "object" && !Array.isArray(stores) ? [value, ...Object.values(stores)] : [value]).flatMap((value) => Object.entries(definition.providerPackages ?? {}).flatMap(([key, choices]) => {
|
|
1055
|
-
const choice = value && typeof value === "object" && !Array.isArray(value) ? Reflect.get(value, key) : void 0;
|
|
1056
|
-
return typeof choice === "string" ? choices[choice] ?? [] : [];
|
|
1057
|
-
}));
|
|
1058
|
-
if (id === "observability" && typeof options?.service === "string") selected.push("@vite-hub/agent");
|
|
1059
|
-
if (id === "observability" && options?.posthog) selected.push("posthog-node");
|
|
1060
|
-
const sandboxDriver = typeof options?.driver === "string" ? options.driver : host;
|
|
1061
|
-
if (id === "sandboxTask" && (sandboxDriver === "vercel" || sandboxDriver === "cloudflare")) selected.push(sandboxDriverPackages[sandboxDriver]);
|
|
1062
|
-
if ((id === "queue" || id === "workflow") && host === "vercel" && (options?.driver ?? "vercel") === "vercel") selected.push(...vercelProviderPackages[id]);
|
|
1063
|
-
if (id === "email" && options?.driver === "smtp" && host !== "cloudflare") selected.push(...ownerCheckedPackages.email ?? []);
|
|
1064
|
-
if (id === "console" && enabled.includes("agent")) selected.push(...consoleFeaturePackages.agents);
|
|
1065
|
-
return [.../* @__PURE__ */ new Set([...definition.packages, ...selected])];
|
|
1066
|
-
}
|
|
1067
|
-
const ownerCheckedPackages = { email: ["nodemailer"] };
|
|
1068
|
-
const sandboxDriverPackages = {
|
|
1069
|
-
cloudflare: "@cloudflare/sandbox",
|
|
1070
|
-
vercel: "@vercel/sandbox"
|
|
1071
|
-
};
|
|
1072
|
-
/**
|
|
1073
|
-
* The SDKs of the Vercel provider. Native Vercel Workflows also need `workflow` and `@workflow/builders`, but only
|
|
1074
|
-
* `@vite-hub/workflow` knows when a Workflow is native, so it checks those two itself.
|
|
1075
|
-
*/
|
|
1076
|
-
const vercelProviderPackages = {
|
|
1077
|
-
queue: ["@vercel/queue", "@vercel/functions"],
|
|
1078
|
-
workflow: ["@vercel/functions"]
|
|
1079
|
-
};
|
|
1080
|
-
const drizzleRange = "1.0.0-rc.5 || 1.0.0-rc.6 || ^1.0.0";
|
|
1081
|
-
const installRanges = {
|
|
1082
|
-
"drizzle-kit": drizzleRange,
|
|
1083
|
-
"drizzle-orm": drizzleRange
|
|
1084
|
-
};
|
|
1085
|
-
/**
|
|
1086
|
-
* The package manager argument that installs `name`, such as `drizzle-orm@1.0.0-rc.5 || 1.0.0-rc.6 || ^1.0.0`. Drizzle tags 0.x as
|
|
1087
|
-
* `latest` and the next 1.0 candidate as `rc`, so a plain name installs a version that ViteHub cannot import. npm saves
|
|
1088
|
-
* the range as written, and an exact version would be saved as `^1.0.0-rc.5`, which also matches later candidates.
|
|
1089
|
-
* Other packages keep their name. Feature catalogs, status, and removal use the plain name.
|
|
1090
|
-
*/
|
|
1091
|
-
function installSpecifier(name) {
|
|
1092
|
-
const range = installRanges[name];
|
|
1093
|
-
return range ? `${name}@${range}` : name;
|
|
1094
|
-
}
|
|
1095
|
-
function quoteSupportedInstallSpecifier(value) {
|
|
1096
|
-
const separator = value.indexOf("@", 1);
|
|
1097
|
-
if (separator < 0) return void 0;
|
|
1098
|
-
const name = value.slice(0, separator);
|
|
1099
|
-
return Object.hasOwn(installRanges, name) && value === installSpecifier(name) ? `"${value}"` : void 0;
|
|
1100
|
-
}
|
|
1101
|
-
function formatInstallArgument(value) {
|
|
1102
|
-
return quoteSupportedInstallSpecifier(value) ?? (/^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`);
|
|
1103
|
-
}
|
|
1104
|
-
/** Additional Console owners selected by its enabled Agent integration. */
|
|
1105
|
-
const consoleFeaturePackages = { agents: ["@libsql/client", "drizzle-orm"] };
|
|
1106
|
-
function featureSupport(id, host, appHost) {
|
|
1107
|
-
const definition = features[id];
|
|
1108
|
-
if (host !== "dev") return definition.hosts[host];
|
|
1109
|
-
invariant(appHost, "every caller of featureSupport() for the dev host passes the configured ViteHub host");
|
|
1110
|
-
if (id === "workflow" && appHost === "deno") return native("vercel", "Inline", "Development runs each Workflow inline unless OpenWorkflow storage or a provider is configured.", "process-local");
|
|
1111
|
-
return definition.hosts[appHost === "node" || definition.developmentOverrides?.includes(appHost) ? "dev" : appHost];
|
|
1112
|
-
}
|
|
1113
|
-
/**
|
|
1114
|
-
* The features that `enabled` turn on through implications, without the ones already in `enabled`.
|
|
1115
|
-
* This follows implications transitively.
|
|
1116
|
-
* `disabled` lists features that the app sets to `false`; an implication never turns them on.
|
|
1117
|
-
*/
|
|
1118
|
-
function impliedFeatures(enabled, disabled = []) {
|
|
1119
|
-
const on = new Set(enabled);
|
|
1120
|
-
const implied = [];
|
|
1121
|
-
const pending = [...enabled];
|
|
1122
|
-
while (pending.length) {
|
|
1123
|
-
const id = pending.shift();
|
|
1124
|
-
for (const implication of features[id].implies) {
|
|
1125
|
-
if (on.has(implication.feature) || disabled.includes(implication.feature)) continue;
|
|
1126
|
-
on.add(implication.feature);
|
|
1127
|
-
implied.push(implication.feature);
|
|
1128
|
-
pending.push(implication.feature);
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
return implied;
|
|
1132
|
-
}
|
|
1133
|
-
// ../internal/dist/vite-D86Q14G4.js
|
|
1134
|
-
const projectRootDirectoryMarkers = [
|
|
1135
|
-
["server", "agents"],
|
|
1136
|
-
["server", "channels"],
|
|
1137
|
-
["server", "connections"],
|
|
1138
|
-
["server", "browsers"],
|
|
1139
|
-
["server", "emails"],
|
|
1140
|
-
["server", "schedules"],
|
|
1141
|
-
["server", "workspaces"]
|
|
1142
|
-
];
|
|
1143
|
-
const projectRootFileMarkers = [
|
|
1144
|
-
["package.json"],
|
|
1145
|
-
["nuxt.config.ts"],
|
|
1146
|
-
["nuxt.config.mts"],
|
|
1147
|
-
["nuxt.config.js"],
|
|
1148
|
-
["nuxt.config.mjs"]
|
|
1149
|
-
];
|
|
1150
|
-
function resolveViteHubProjectRoot(root, options = {}) {
|
|
1151
|
-
const resolvedRoot = resolve$1(root);
|
|
1152
|
-
const temporaryRoot = resolve$1(tmpdir());
|
|
1153
|
-
const sharedTemporaryRoot = dirname$1(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
1154
|
-
if (options.projectRoot) return resolve$1(resolvedRoot, options.projectRoot);
|
|
1155
|
-
if (basename$1(resolvedRoot) === "app") {
|
|
1156
|
-
const parent = dirname$1(resolvedRoot);
|
|
1157
|
-
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
1158
|
-
"nuxt.config.ts",
|
|
1159
|
-
"nuxt.config.mts",
|
|
1160
|
-
"nuxt.config.js",
|
|
1161
|
-
"nuxt.config.mjs"
|
|
1162
|
-
]))) return parent;
|
|
1163
|
-
}
|
|
1164
|
-
let current = resolvedRoot;
|
|
1165
|
-
while (true) {
|
|
1166
|
-
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
1167
|
-
if (hasProjectRootMarker(current)) return current;
|
|
1168
|
-
const parent = dirname$1(current);
|
|
1169
|
-
if (parent === current) return resolvedRoot;
|
|
1170
|
-
current = parent;
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
function hasProjectRootDirectoryMarker(root) {
|
|
1174
|
-
for (const marker of projectRootDirectoryMarkers) try {
|
|
1175
|
-
if (statSync(resolve$1(root, ...marker)).isDirectory()) return true;
|
|
1176
|
-
} catch (error) {
|
|
1177
|
-
if (!isMissingProjectMarker(error)) throw error;
|
|
1178
|
-
}
|
|
1179
|
-
return false;
|
|
1180
|
-
}
|
|
1181
|
-
function hasProjectRootMarker(root) {
|
|
1182
|
-
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
1183
|
-
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
1184
|
-
}
|
|
1185
|
-
function hasProjectRootFileMarker(root, markers) {
|
|
1186
|
-
for (const marker of markers) {
|
|
1187
|
-
const path = Array.isArray(marker) ? marker : [marker];
|
|
1188
|
-
try {
|
|
1189
|
-
if (statSync(resolve$1(root, ...path)).isFile()) return true;
|
|
1190
|
-
} catch (error) {
|
|
1191
|
-
if (!isMissingProjectMarker(error)) throw error;
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
return false;
|
|
1195
|
-
}
|
|
1196
|
-
function isMissingProjectMarker(error) {
|
|
1197
|
-
const code = error.code;
|
|
1198
|
-
return code === "ENOENT" || code === "ENOTDIR";
|
|
1199
|
-
}
|
|
1200
|
-
// ../internal/dist/operation-rpc.js
|
|
1201
|
-
/** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
|
|
1202
|
-
const operationRpcPath = "/_vitehub/rpc";
|
|
1203
|
-
function text(value) {
|
|
1204
|
-
return String(value) === value && value ? value : void 0;
|
|
1205
|
-
}
|
|
1206
|
-
/** Read an untrusted failure body. It keeps only the diagnostic fields, so a stack never passes through. */
|
|
1207
|
-
function readOperationRpcError(value) {
|
|
1208
|
-
if (!isRecord(value)) return void 0;
|
|
1209
|
-
const code = text(value.code);
|
|
1210
|
-
const message = text(value.message);
|
|
1211
|
-
const status = value.status;
|
|
1212
|
-
if (!code || !message || !Number.isInteger(status)) return void 0;
|
|
1213
|
-
const failure = {
|
|
1214
|
-
code,
|
|
1215
|
-
message,
|
|
1216
|
-
status: Number(status)
|
|
1217
|
-
};
|
|
1218
|
-
if (text(value.fix)) failure.fix = text(value.fix);
|
|
1219
|
-
if (text(value.docs)) failure.docs = text(value.docs);
|
|
1220
|
-
if (isRecord(value.details)) failure.details = value.details;
|
|
1221
|
-
return failure;
|
|
1222
|
-
}
|
|
1223
|
-
/** Read one response message. */
|
|
1224
|
-
function readOperationRpcReply(value) {
|
|
1225
|
-
if (!isRecord(value) || value.t !== "s") return void 0;
|
|
1226
|
-
const id = text(value.i);
|
|
1227
|
-
if (Object.hasOwn(value, "e")) {
|
|
1228
|
-
const error = readOperationRpcError(value.e);
|
|
1229
|
-
return error ? {
|
|
1230
|
-
t: "s",
|
|
1231
|
-
...id ? { i: id } : {},
|
|
1232
|
-
e: error
|
|
1233
|
-
} : void 0;
|
|
1234
|
-
}
|
|
1235
|
-
return id ? {
|
|
1236
|
-
t: "s",
|
|
1237
|
-
i: id,
|
|
1238
|
-
r: value.r
|
|
1239
|
-
} : void 0;
|
|
1240
|
-
}
|
|
1241
|
-
/**
|
|
1242
|
-
* Call one operation with birpc over a request and answer transport, such as one HTTP POST per call. `send` posts the
|
|
1243
|
-
* JSON message and returns the parsed answer; its own failures, such as a network error or an abort, reject.
|
|
1244
|
-
*/
|
|
1245
|
-
async function callOperationRpc(name, input, send) {
|
|
1246
|
-
let receive;
|
|
1247
|
-
let answer;
|
|
1248
|
-
const notReply = /* @__PURE__ */ new Error("The answer is not a reply to the operation call.");
|
|
1249
|
-
const rpc = createBirpc({}, {
|
|
1250
|
-
on: (listener) => {
|
|
1251
|
-
receive = listener;
|
|
1252
|
-
},
|
|
1253
|
-
post: async (message) => {
|
|
1254
|
-
answer = await send(JSON.stringify(message));
|
|
1255
|
-
const reply = readOperationRpcReply(answer.body);
|
|
1256
|
-
if (!reply || reply.i !== void 0 && reply.i !== message.i) throw notReply;
|
|
1257
|
-
await receive({
|
|
1258
|
-
...reply,
|
|
1259
|
-
i: message.i
|
|
1260
|
-
});
|
|
1261
|
-
},
|
|
1262
|
-
proxify: false,
|
|
1263
|
-
timeout: -1
|
|
1264
|
-
});
|
|
1265
|
-
try {
|
|
1266
|
-
return {
|
|
1267
|
-
ok: true,
|
|
1268
|
-
value: await rpc.$call(name, ...input === void 0 ? [] : [input]),
|
|
1269
|
-
answer
|
|
1270
|
-
};
|
|
1271
|
-
} catch (error) {
|
|
1272
|
-
if (!answer) throw error;
|
|
1273
|
-
if (error === notReply) return {
|
|
1274
|
-
ok: false,
|
|
1275
|
-
error: void 0,
|
|
1276
|
-
answer
|
|
1277
|
-
};
|
|
1278
|
-
return {
|
|
1279
|
-
ok: false,
|
|
1280
|
-
error: readOperationRpcError(error),
|
|
1281
|
-
answer
|
|
1282
|
-
};
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
// ../internal/dist/console-signature.js
|
|
1286
|
-
/**
|
|
1287
|
-
* Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
|
|
1288
|
-
* CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
|
|
1289
|
-
* its env cannot sign a request. The module uses only Web Crypto, so it runs in Node, Workers, Deno, and browsers.
|
|
1290
|
-
*
|
|
1291
|
-
* The signature covers this text, one field per line:
|
|
1292
|
-
*
|
|
1293
|
-
* ```txt
|
|
1294
|
-
* vitehub-signature-v1
|
|
1295
|
-
* POST
|
|
1296
|
-
* /_vitehub/rpc
|
|
1297
|
-
* https://app.example.com
|
|
1298
|
-
* 1794400000
|
|
1299
|
-
* CONSOLE_3F9A12BC
|
|
1300
|
-
* <SHA-256 of the body bytes, base64url>
|
|
1301
|
-
* <the x-vitehub-caller header>
|
|
1302
|
-
* ```
|
|
1303
|
-
*/
|
|
1304
|
-
/** The signature header: `key=<NAME>, t=<seconds>, origin=<app origin>, body=<SHA-256>, v1=<signature>`. */
|
|
1305
|
-
const consoleSignatureHeader = "x-vitehub-signature";
|
|
1306
|
-
/** Who calls, as base64url JSON. The signature covers it. See {@link ConsoleCaller}. */
|
|
1307
|
-
const consoleCallerHeader = "x-vitehub-caller";
|
|
1308
|
-
/** The first line of the signed text. A new format gets a new tag. */
|
|
1309
|
-
const consoleSignatureVersion = "vitehub-signature-v1";
|
|
1310
|
-
/** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
|
|
1311
|
-
const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
|
|
1312
|
-
const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
|
|
1313
|
-
const encoder = new TextEncoder();
|
|
1314
|
-
new TextDecoder();
|
|
1315
|
-
const ed25519 = { name: "Ed25519" };
|
|
1316
|
-
const pkcs8Prefix = Uint8Array.of(48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32);
|
|
1317
|
-
function base64url(bytes) {
|
|
1318
|
-
let binary = "";
|
|
1319
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1320
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1321
|
-
}
|
|
1322
|
-
/** The bytes of a base64url value, or `undefined` when it is not canonical base64url without padding. */
|
|
1323
|
-
function fromBase64url(value) {
|
|
1324
|
-
if (!/^[\w-]*$/.test(value) || value.length % 4 === 1) return void 0;
|
|
1325
|
-
const bytes = Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
|
|
1326
|
-
return base64url(bytes) === value ? bytes : void 0;
|
|
1327
|
-
}
|
|
1328
|
-
function bytesOf(body) {
|
|
1329
|
-
if (typeof body === "string") return encoder.encode(body);
|
|
1330
|
-
return body instanceof Uint8Array ? Uint8Array.from(body) : new Uint8Array(body);
|
|
1331
|
-
}
|
|
1332
|
-
/** The SHA-256 of the exact body bytes, base64url. A request without a body hashes zero bytes. */
|
|
1333
|
-
async function consoleBodySha256(body = "") {
|
|
1334
|
-
return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytesOf(body))));
|
|
1335
|
-
}
|
|
1336
|
-
/** The text that the signature covers. Fields are joined with `\n`. */
|
|
1337
|
-
function consoleSignedText(fields) {
|
|
1338
|
-
return [
|
|
1339
|
-
consoleSignatureVersion,
|
|
1340
|
-
fields.method.toUpperCase(),
|
|
1341
|
-
fields.target,
|
|
1342
|
-
fields.origin,
|
|
1343
|
-
fields.timestamp,
|
|
1344
|
-
fields.key,
|
|
1345
|
-
fields.bodySha256,
|
|
1346
|
-
fields.caller
|
|
1347
|
-
].join("\n");
|
|
1348
|
-
}
|
|
1349
|
-
/** The path and query of a URL, the part of the request target that the signature covers. */
|
|
1350
|
-
function requestTarget(url) {
|
|
1351
|
-
return `${url.pathname}${url.search}`;
|
|
1352
|
-
}
|
|
1353
|
-
/** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
|
|
1354
|
-
function isConsoleKeyName(name) {
|
|
1355
|
-
return keyNamePattern.test(name);
|
|
1356
|
-
}
|
|
1357
|
-
async function importPrivateKey(seed) {
|
|
1358
|
-
const bytes = fromBase64url(seed.trim());
|
|
1359
|
-
if (bytes?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_INVALID();
|
|
1360
|
-
const der = new Uint8Array(pkcs8Prefix.length + 32);
|
|
1361
|
-
der.set(pkcs8Prefix);
|
|
1362
|
-
der.set(bytes, pkcs8Prefix.length);
|
|
1363
|
-
return await crypto.subtle.importKey("pkcs8", der, ed25519, false, ["sign"]);
|
|
1364
|
-
}
|
|
1365
|
-
/** The `x-vitehub-caller` value of a caller: its JSON as base64url. */
|
|
1366
|
-
function encodeConsoleCaller(caller) {
|
|
1367
|
-
return base64url(encoder.encode(JSON.stringify(caller)));
|
|
1368
|
-
}
|
|
1369
|
-
/**
|
|
1370
|
-
* Sign one request. `url` is the full URL that the request goes to, and `body` is the exact body that it sends. Returns
|
|
1371
|
-
* the two headers to add: `x-vitehub-signature` and `x-vitehub-caller`.
|
|
1372
|
-
*/
|
|
1373
|
-
async function signConsoleRequest(options) {
|
|
1374
|
-
if (!isConsoleKeyName(options.key.name)) throw internalErrorDiagnostics.INTERNAL_CONSOLE_KEY_NAME_INVALID({ name: options.key.name });
|
|
1375
|
-
const url = new URL(options.url);
|
|
1376
|
-
const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
|
|
1377
|
-
const bodySha256 = await consoleBodySha256(options.body);
|
|
1378
|
-
const caller = encodeConsoleCaller(options.caller);
|
|
1379
|
-
const text = consoleSignedText({
|
|
1380
|
-
bodySha256,
|
|
1381
|
-
caller,
|
|
1382
|
-
key: options.key.name,
|
|
1383
|
-
method: options.method,
|
|
1384
|
-
origin: url.origin,
|
|
1385
|
-
target: requestTarget(url),
|
|
1386
|
-
timestamp
|
|
1387
|
-
});
|
|
1388
|
-
const signature = new Uint8Array(await crypto.subtle.sign(ed25519, await importPrivateKey(options.key.privateKey), encoder.encode(text)));
|
|
1389
|
-
return {
|
|
1390
|
-
[consoleCallerHeader]: caller,
|
|
1391
|
-
[consoleSignatureHeader]: `key=${options.key.name}, t=${timestamp}, origin=${url.origin}, body=${bodySha256}, v1=${base64url(signature)}`
|
|
1392
|
-
};
|
|
1393
|
-
}
|
|
1394
|
-
/**
|
|
1395
|
-
* The signing key of a CLI from its env: the one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable. Returns `undefined`
|
|
1396
|
-
* without one. Throws a coded error when there are several, or when the value is not a 32-byte seed.
|
|
1397
|
-
*/
|
|
1398
|
-
function readConsoleSigningKey(env) {
|
|
1399
|
-
const variables = Object.keys(env).filter((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && env[name]?.trim()).sort();
|
|
1400
|
-
if (!variables.length) return void 0;
|
|
1401
|
-
if (variables.length > 1) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE({
|
|
1402
|
-
prefix: consolePrivateKeyPrefix,
|
|
1403
|
-
variables: variables.join(", ")
|
|
1404
|
-
});
|
|
1405
|
-
const variable = variables[0];
|
|
1406
|
-
const name = variable.slice(28);
|
|
1407
|
-
const privateKey = env[variable].trim();
|
|
1408
|
-
if (!isConsoleKeyName(name) || fromBase64url(privateKey)?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID({ variable });
|
|
1409
|
-
return {
|
|
1410
|
-
name,
|
|
1411
|
-
privateKey
|
|
1412
|
-
};
|
|
1413
|
-
}
|
|
1414
|
-
// ../internal/dist/standard-schema.js
|
|
1415
|
-
function readOwn(value, key) {
|
|
1416
|
-
if (value === null || Object(value) !== value) return;
|
|
1417
|
-
try {
|
|
1418
|
-
return Reflect.get(Object(value), key);
|
|
1419
|
-
} catch {
|
|
1420
|
-
return;
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
/**
|
|
1424
|
-
* Read a Standard JSON Schema projection without throwing.
|
|
1425
|
-
*
|
|
1426
|
-
* Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
|
|
1427
|
-
* (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
|
|
1428
|
-
*/
|
|
1429
|
-
function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
|
|
1430
|
-
const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
|
|
1431
|
-
const project = readOwn(jsonSchema, direction);
|
|
1432
|
-
if (typeof project !== "function") return;
|
|
1433
|
-
try {
|
|
1434
|
-
const result = project.call(jsonSchema, libraryOptions ? {
|
|
1435
|
-
target,
|
|
1436
|
-
libraryOptions
|
|
1437
|
-
} : { target });
|
|
1438
|
-
return isRecordOrFunction(result) ? result : void 0;
|
|
1439
|
-
} catch {
|
|
1440
|
-
return;
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
// ../internal/dist/operation-definition.js
|
|
1444
|
-
const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
|
|
1445
|
-
const kinds = /* @__PURE__ */ new Set([
|
|
1446
|
-
"read",
|
|
1447
|
-
"write",
|
|
1448
|
-
"destructive"
|
|
1449
|
-
]);
|
|
1450
|
-
function invalidDefinition(name, reason) {
|
|
1451
|
-
return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
|
|
1452
|
-
}
|
|
1453
|
-
function checkDefinition(definition) {
|
|
1454
|
-
if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
|
|
1455
|
-
const { name } = definition;
|
|
1456
|
-
if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
|
|
1457
|
-
if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
|
|
1458
|
-
const { section } = definition;
|
|
1459
|
-
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 ':'.");
|
|
1460
|
-
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.");
|
|
1461
|
-
if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
|
|
1462
|
-
const input = definition.input;
|
|
1463
|
-
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.");
|
|
1464
|
-
if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
|
|
1465
|
-
const { maxRequestBytes } = definition;
|
|
1466
|
-
if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
|
|
1467
|
-
if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
|
|
1468
|
-
const { mcp } = definition;
|
|
1469
|
-
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.");
|
|
1470
|
-
}
|
|
1471
|
-
/** The default limit of a call, in bytes. */
|
|
1472
|
-
const defaultRequestBytes = 65536;
|
|
1473
|
-
/** The top-level setup commands of the CLI, such as `vitehub status`. They run before the project config loads. */
|
|
1474
|
-
const setupCommandNames = [
|
|
1475
|
-
"init",
|
|
1476
|
-
"add",
|
|
1477
|
-
"remove",
|
|
1478
|
-
"status",
|
|
1479
|
-
"catalog",
|
|
1480
|
-
"link",
|
|
1481
|
-
"unlink",
|
|
1482
|
-
"deploy",
|
|
1483
|
-
"deployments",
|
|
1484
|
-
"drain",
|
|
1485
|
-
"login",
|
|
1486
|
-
"logout",
|
|
1487
|
-
"update",
|
|
1488
|
-
"whoami",
|
|
1489
|
-
"apps"
|
|
1490
|
-
];
|
|
1491
|
-
/** CLI namespaces owned by built-in commands. */
|
|
1492
|
-
const reservedOperationNamespaces = [
|
|
1493
|
-
"inspect",
|
|
1494
|
-
"provision",
|
|
1495
|
-
"seed",
|
|
1496
|
-
...setupCommandNames
|
|
1497
|
-
];
|
|
1498
|
-
function isOperation(value) {
|
|
1499
|
-
try {
|
|
1500
|
-
checkDefinition(value);
|
|
1501
|
-
return true;
|
|
1502
|
-
} catch {
|
|
1503
|
-
return false;
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1506
|
-
function isSectionId(section) {
|
|
1507
|
-
return typeof section === "string" && section !== "" && !section.includes(":");
|
|
1508
|
-
}
|
|
1509
|
-
/** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
|
|
1510
|
-
function operationInputJsonSchema(operation) {
|
|
1511
|
-
return standardJsonSchema(operation.input, "input") ?? { type: "object" };
|
|
1512
|
-
}
|
|
1513
|
-
// ../internal/dist/operations.js
|
|
1514
|
-
/** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
|
|
1515
|
-
const operationRpcHeader = "x-vitehub-console";
|
|
1516
|
-
/** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
|
|
1517
|
-
const operationRootHeader = "x-vitehub-root";
|
|
1518
|
-
const operationExpectedRootsHeader = "x-vitehub-expected-roots";
|
|
1519
|
-
/** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
|
|
1520
|
-
function projectRootHash(root) {
|
|
1521
|
-
const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
1522
|
-
let first = 3735928559;
|
|
1523
|
-
let second = 1103547991;
|
|
1524
|
-
for (let index = 0; index < normalized.length; index++) {
|
|
1525
|
-
const code = normalized.charCodeAt(index);
|
|
1526
|
-
first = Math.imul(first ^ code, 2654435761);
|
|
1527
|
-
second = Math.imul(second ^ code, 1597334677);
|
|
1528
|
-
}
|
|
1529
|
-
first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
|
|
1530
|
-
second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
|
|
1531
|
-
return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
|
|
1532
|
-
}
|
|
1533
|
-
/** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
|
|
1534
|
-
const operationSurfaceHeader = "x-vitehub-surface";
|
|
1535
|
-
/** Generated CLI commands ask the server to check confirmation after it parses the input. */
|
|
1536
|
-
const operationConfirmationHeader = "x-vitehub-confirmation";
|
|
1537
|
-
function pluginName(plugin) {
|
|
1538
|
-
const name = Reflect.get(plugin, "name");
|
|
1539
|
-
return String(name) === name && name ? name : "unnamed plugin";
|
|
1540
|
-
}
|
|
1541
|
-
/** Reads `plugin.vitehub.operations` from resolved Vite plugins. The same module and export from two plugins counts once. */
|
|
1542
|
-
async function collectOperationContributions(plugins) {
|
|
1543
|
-
const collected = /* @__PURE__ */ new Map();
|
|
1544
|
-
for (const plugin of plugins) {
|
|
1545
|
-
if (!isRecordOrFunction(plugin) || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
1546
|
-
const declared = Reflect.get(Object(Reflect.get(plugin, "vitehub")), "operations");
|
|
1547
|
-
if (declared === void 0) continue;
|
|
1548
|
-
const entries = declared instanceof Function ? await declared() : declared;
|
|
1549
|
-
const owner = pluginName(plugin);
|
|
1550
|
-
if (!Array.isArray(entries)) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} sets vitehub.operations, which must be a list of { module, export }.` });
|
|
1551
|
-
for (const entry of entries) {
|
|
1552
|
-
if (!isRecordOrFunction(entry) || String(entry.module) !== entry.module || !entry.module) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} contributes an operation entry without a module.` });
|
|
1553
|
-
const exportName = String(entry.export) === entry.export && entry.export ? entry.export : "default";
|
|
1554
|
-
const key = `${entry.module}#${exportName}`;
|
|
1555
|
-
if (collected.has(key)) continue;
|
|
1556
|
-
collected.set(key, {
|
|
1557
|
-
module: entry.module,
|
|
1558
|
-
export: exportName,
|
|
1559
|
-
plugin: owner,
|
|
1560
|
-
...entry.load instanceof Function ? { load: entry.load } : {},
|
|
1561
|
-
...entry.runtime === false ? { runtime: false } : {}
|
|
1562
|
-
});
|
|
1563
|
-
}
|
|
1564
|
-
}
|
|
1565
|
-
return [...collected.values()];
|
|
1566
|
-
}
|
|
1567
|
-
/** Operations of one module export, flat. A single operation or an array both work. */
|
|
1568
|
-
function operationsOf(value) {
|
|
1569
|
-
const list = Array.isArray(value) ? value : [value];
|
|
1570
|
-
const operations = [];
|
|
1571
|
-
for (const item of list) {
|
|
1572
|
-
if (!isOperation(item)) throw invalidDefinition(isRecordOrFunction(item) ? item.name : void 0, "a contributed export must hold defineOperation() results.");
|
|
1573
|
-
operations.push(item);
|
|
1574
|
-
}
|
|
1575
|
-
return operations;
|
|
1576
|
-
}
|
|
1577
|
-
/** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
|
|
1578
|
-
function operationCliPath(operation) {
|
|
1579
|
-
const dot = operation.name.indexOf(".");
|
|
1580
|
-
const cli = operationCliOptions(operation);
|
|
1581
|
-
return {
|
|
1582
|
-
command: cli?.command ?? operation.name.slice(dot + 1),
|
|
1583
|
-
namespace: cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
|
|
1584
|
-
};
|
|
1585
|
-
}
|
|
1586
|
-
/** The CLI options of an operation, or undefined for an operation without options or with `cli: false`. */
|
|
1587
|
-
function operationCliOptions(operation) {
|
|
1588
|
-
return operation.cli || void 0;
|
|
1589
|
-
}
|
|
1590
|
-
/**
|
|
1591
|
-
* The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
|
|
1592
|
-
* Claude reject a dot in a tool name. `content.publish` is `content_publish`.
|
|
1593
|
-
*/
|
|
1594
|
-
function operationToolName(name) {
|
|
1595
|
-
return name.replace(/[^\w-]/g, "_");
|
|
1596
|
-
}
|
|
1597
|
-
/** 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`. */
|
|
1598
|
-
function createOperationRegistry(sources) {
|
|
1599
|
-
const byName = /* @__PURE__ */ new Map();
|
|
1600
|
-
for (const source of sources) for (const operation of source.operations) {
|
|
1601
|
-
const existing = byName.get(operation.name);
|
|
1602
|
-
if (existing && existing.operation !== operation) {
|
|
1603
|
-
const owners = [existing.plugin, source.plugin].filter(Boolean).join(" and ");
|
|
1604
|
-
throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] Two operations are named ${JSON.stringify(operation.name)}${owners ? ` (${owners})` : ""}.` });
|
|
1605
|
-
}
|
|
1606
|
-
byName.set(operation.name, {
|
|
1607
|
-
operation,
|
|
1608
|
-
...source.plugin ? { plugin: source.plugin } : {}
|
|
1609
|
-
});
|
|
1610
|
-
}
|
|
1611
|
-
const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
|
|
1612
|
-
const commands = /* @__PURE__ */ new Map();
|
|
1613
|
-
for (const operation of operations) {
|
|
1614
|
-
if (operation.cli === false) continue;
|
|
1615
|
-
const { command, namespace } = operationCliPath(operation);
|
|
1616
|
-
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.`);
|
|
1617
|
-
const key = `${namespace} ${command}`;
|
|
1618
|
-
const other = commands.get(key);
|
|
1619
|
-
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}\`.` });
|
|
1620
|
-
commands.set(key, operation);
|
|
1621
|
-
}
|
|
1622
|
-
const tools = /* @__PURE__ */ new Map();
|
|
1623
|
-
for (const operation of operations) {
|
|
1624
|
-
if (operation.mcp === false) continue;
|
|
1625
|
-
const tool = operationToolName(operation.name);
|
|
1626
|
-
const other = tools.get(tool);
|
|
1627
|
-
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)}.` });
|
|
1628
|
-
tools.set(tool, operation);
|
|
1629
|
-
}
|
|
1630
|
-
return {
|
|
1631
|
-
get: (name) => byName.get(name)?.operation,
|
|
1632
|
-
list: () => [...operations]
|
|
1633
|
-
};
|
|
1634
|
-
}
|
|
1635
|
-
/** Issues of a failed Standard Schema check as one short line per issue. */
|
|
1636
|
-
function describeInputIssues(issues) {
|
|
1637
|
-
return issues.slice(0, 5).map((issue) => {
|
|
1638
|
-
const path = (issue.path ?? []).map((segment) => String(isRecordOrFunction(segment) && "key" in segment ? segment.key : segment)).join(".");
|
|
1639
|
-
return path ? `${path}: ${issue.message}` : issue.message;
|
|
1640
|
-
}).join(" ");
|
|
1641
|
-
}
|
|
1642
|
-
function describeInputFields(schema) {
|
|
1643
|
-
const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).map((shape) => {
|
|
1644
|
-
if (!isRecordOrFunction(shape) || !isRecordOrFunction(shape.properties)) return void 0;
|
|
1645
|
-
const required = Array.isArray(shape.required) ? shape.required : [];
|
|
1646
|
-
const fields = Object.keys(shape.properties).map((field) => required.includes(field) ? field : `${field}?`);
|
|
1647
|
-
return fields.length ? `{ ${fields.join(", ")} }` : "{}";
|
|
1648
|
-
});
|
|
1649
|
-
return shapes.every((shape) => shape !== void 0) ? shapes.join(" or ") : void 0;
|
|
1650
|
-
}
|
|
1651
|
-
/** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
|
|
1652
|
-
async function parseOperationInput(operation, input) {
|
|
1653
|
-
const result = await operation.input["~standard"].validate(input ?? {});
|
|
1654
|
-
if (!result.issues) return result.value;
|
|
1655
|
-
const fields = describeInputFields(operationInputJsonSchema(operation));
|
|
1656
|
-
const issues = describeInputIssues(result.issues);
|
|
1657
|
-
const message = `Invalid input for ${operation.name}. ${issues}${fields ? `${/[.!?]$/.test(issues) ? "" : "."} ${operation.name} takes ${fields}.` : ""}`;
|
|
1658
|
-
throw Object.assign(internalErrorDiagnostics.INTERNAL_R0022({ message }), { status: 400 });
|
|
1659
|
-
}
|
|
1660
|
-
/** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
|
|
1661
|
-
function operationCall(operation, input) {
|
|
1662
|
-
return {
|
|
1663
|
-
kind: operation.kind,
|
|
1664
|
-
readOnly: operation.readOnlyWhen?.(input) === true
|
|
1665
|
-
};
|
|
1666
|
-
}
|
|
1667
|
-
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.";
|
|
1668
|
-
/** Headers of an operation call, without a signature. */
|
|
1669
|
-
function operationHeaders() {
|
|
1670
|
-
const headers = new Headers();
|
|
1671
|
-
headers.set("accept", "application/json");
|
|
1672
|
-
headers.set("content-type", "application/json");
|
|
1673
|
-
headers.set(operationRpcHeader, "1");
|
|
1674
|
-
headers.set(operationSurfaceHeader, "cli");
|
|
1675
|
-
return headers;
|
|
1676
|
-
}
|
|
1677
|
-
/**
|
|
1678
|
-
* The headers of one operation call to a deployed app: {@link operationHeaders}, and the signature of `body` when the
|
|
1679
|
-
* env has a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. The CLI signs as itself, `via: "cli"`. Throws a `TypeError` for a
|
|
1680
|
-
* malformed private key.
|
|
1681
|
-
*/
|
|
1682
|
-
async function signedOperationHeaders(env, url, body) {
|
|
1683
|
-
const headers = operationHeaders();
|
|
1684
|
-
const key = readConsoleSigningKey(env);
|
|
1685
|
-
if (key) {
|
|
1686
|
-
const signed = await signConsoleRequest({
|
|
1687
|
-
body,
|
|
1688
|
-
caller: { via: "cli" },
|
|
1689
|
-
key,
|
|
1690
|
-
method: "POST",
|
|
1691
|
-
url
|
|
1692
|
-
});
|
|
1693
|
-
for (const [name, value] of Object.entries(signed)) headers.set(name, value);
|
|
1694
|
-
}
|
|
1695
|
-
return headers;
|
|
1696
|
-
}
|
|
1697
|
-
function unreachable(message, status = 503) {
|
|
1698
|
-
const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
|
|
1699
|
-
return {
|
|
1700
|
-
ok: false,
|
|
1701
|
-
code: error.code,
|
|
1702
|
-
fix: error.fix,
|
|
1703
|
-
message,
|
|
1704
|
-
status
|
|
1705
|
-
};
|
|
1706
|
-
}
|
|
1707
|
-
function hasCredentials(env) {
|
|
1708
|
-
return Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && Boolean(env[name]));
|
|
1709
|
-
}
|
|
1710
|
-
/** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
|
|
1711
|
-
async function callOperation(target, name, input) {
|
|
1712
|
-
let origin = "the ViteHub app";
|
|
1713
|
-
try {
|
|
1714
|
-
const base = new URL(target.url);
|
|
1715
|
-
if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
|
|
1716
|
-
const url = new URL(operationRpcPath.slice(1), base);
|
|
1717
|
-
origin = url.origin;
|
|
1718
|
-
const env = target.roots?.length ? {} : target.env;
|
|
1719
|
-
if (!target.authorization) try {
|
|
1720
|
-
readConsoleSigningKey(env);
|
|
1721
|
-
} catch (error) {
|
|
1722
|
-
return {
|
|
1723
|
-
ok: false,
|
|
1724
|
-
code: "INTERNAL_R0024",
|
|
1725
|
-
fix: "Run `vitehub secret console-key` for a new key pair. Set its private key here and its public key on the app.",
|
|
1726
|
-
message: error instanceof Error ? error.message : String(error),
|
|
1727
|
-
status: 401
|
|
1728
|
-
};
|
|
1729
|
-
}
|
|
1730
|
-
const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
|
|
1731
|
-
const signal = target.signal ?? AbortSignal.timeout(target.timeout ?? 3e4);
|
|
1732
|
-
const headers = target.authorization ? operationHeaders() : await signedOperationHeaders(env, url, body);
|
|
1733
|
-
if (target.authorization) headers.set("authorization", target.authorization);
|
|
1734
|
-
if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
|
|
1735
|
-
if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
|
|
1736
|
-
signal.throwIfAborted();
|
|
1737
|
-
const response = await (target.fetch ?? fetch)(url.href, {
|
|
1738
|
-
body,
|
|
1739
|
-
headers,
|
|
1740
|
-
method: "POST",
|
|
1741
|
-
redirect: "manual",
|
|
1742
|
-
signal
|
|
1743
|
-
});
|
|
1744
|
-
const text = await response.text();
|
|
1745
|
-
let json;
|
|
1746
|
-
try {
|
|
1747
|
-
json = text ? JSON.parse(text) : void 0;
|
|
1748
|
-
} catch {
|
|
1749
|
-
json = void 0;
|
|
1750
|
-
}
|
|
1751
|
-
return {
|
|
1752
|
-
body: json,
|
|
1753
|
-
response
|
|
1754
|
-
};
|
|
1755
|
-
});
|
|
1756
|
-
const { response } = outcome.answer;
|
|
1757
|
-
const served = response.headers.get(operationRootHeader);
|
|
1758
|
-
if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
|
|
1759
|
-
const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
|
|
1760
|
-
const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
|
|
1761
|
-
return {
|
|
1762
|
-
ok: false,
|
|
1763
|
-
code: error.code,
|
|
1764
|
-
fix: error.fix,
|
|
1765
|
-
message,
|
|
1766
|
-
status: 409
|
|
1767
|
-
};
|
|
1768
|
-
}
|
|
1769
|
-
if (outcome.ok) return {
|
|
1770
|
-
ok: true,
|
|
1771
|
-
value: outcome.value
|
|
1772
|
-
};
|
|
1773
|
-
const failure = outcome.error ?? readOperationRpcError(isRecordOrFunction(outcome.answer.body) ? {
|
|
1774
|
-
status: response.status,
|
|
1775
|
-
...outcome.answer.body
|
|
1776
|
-
} : void 0);
|
|
1777
|
-
if (failure) {
|
|
1778
|
-
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."}`;
|
|
1779
|
-
if ((failure.status === 401 || failure.status === 403) && !target.authorization && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
|
|
1780
|
-
return {
|
|
1781
|
-
ok: false,
|
|
1782
|
-
...failure
|
|
1783
|
-
};
|
|
1784
|
-
}
|
|
1785
|
-
if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
|
|
1786
|
-
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);
|
|
1787
|
-
} catch (error) {
|
|
1788
|
-
return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1789
|
-
}
|
|
1790
|
-
}
|
|
1791
|
-
/**
|
|
1792
|
-
* Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
|
|
1793
|
-
* started. Never throws. Without a dev server the result is an `INTERNAL_R0024` failure that says to start one.
|
|
1794
|
-
*/
|
|
1795
|
-
async function callOperationFromCli(call, name, input) {
|
|
1796
|
-
let roots;
|
|
1797
|
-
try {
|
|
1798
|
-
roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
|
|
1799
|
-
} catch {
|
|
1800
|
-
roots = [call.rootDir];
|
|
1801
|
-
}
|
|
1802
|
-
const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
|
|
1803
|
-
if (!url) return unreachable(`No dev server is running for ${roots.at(-1)}.`);
|
|
1804
|
-
return await callOperation({
|
|
1805
|
-
...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
|
|
1806
|
-
env: call.env,
|
|
1807
|
-
...call.fetch ? { fetch: call.fetch } : {},
|
|
1808
|
-
...call.url ? {} : { roots },
|
|
1809
|
-
...call.timeout ? { timeout: call.timeout } : {},
|
|
1810
|
-
url
|
|
1811
|
-
}, name, input);
|
|
1812
|
-
}
|
|
1813
|
-
// ../internal/dist/vite-stage.js
|
|
1814
|
-
/**
|
|
1815
|
-
* Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
|
|
1816
|
-
* logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
|
|
1817
|
-
*/
|
|
1818
|
-
function loadAllEnv(loadEnv, mode, envDir) {
|
|
1819
|
-
const write = process.stderr.write;
|
|
1820
|
-
process.stderr.write = () => true;
|
|
1821
|
-
try {
|
|
1822
|
-
return loadEnv(mode, envDir, "");
|
|
1823
|
-
} finally {
|
|
1824
|
-
process.stderr.write = write;
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
const viteStageQueueKey = Symbol.for("vitehub.cli.vite-stage-queue");
|
|
1828
|
-
function definedEntries(env) {
|
|
1829
|
-
return Object.entries(env).filter((entry) => entry[1] !== void 0);
|
|
1830
|
-
}
|
|
1831
|
-
function replaceProcessEnv(entries) {
|
|
1832
|
-
for (const key of Object.keys(process.env)) delete process.env[key];
|
|
1833
|
-
for (const [key, value] of entries) process.env[key] = value;
|
|
1834
|
-
}
|
|
1835
|
-
/** Load stage config and modules under the same serialized, temporary process environment. */
|
|
1836
|
-
async function withViteStageEnvironment(env, callback) {
|
|
1837
|
-
const carrier = globalThis;
|
|
1838
|
-
const previous = carrier[viteStageQueueKey] ?? Promise.resolve();
|
|
1839
|
-
let release;
|
|
1840
|
-
carrier[viteStageQueueKey] = new Promise((resolve) => {
|
|
1841
|
-
release = resolve;
|
|
1842
|
-
});
|
|
1843
|
-
await previous;
|
|
1844
|
-
const previousEnvironment = definedEntries(process.env);
|
|
1845
|
-
const selectedEnvironment = definedEntries(env);
|
|
1846
|
-
try {
|
|
1847
|
-
replaceProcessEnv(selectedEnvironment);
|
|
1848
|
-
return await callback();
|
|
1849
|
-
} finally {
|
|
1850
|
-
replaceProcessEnv(previousEnvironment);
|
|
1851
|
-
release();
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
// ../internal/dist/provision-state.js
|
|
1855
|
-
const PROVISION_STATE_FILE = ".vitehub/provision.json";
|
|
1856
|
-
function getProvisionStatePath(rootDir) {
|
|
1857
|
-
return resolve(rootDir, PROVISION_STATE_FILE);
|
|
1858
|
-
}
|
|
1859
|
-
async function readProvisionState(rootDir) {
|
|
1860
|
-
const path = getProvisionStatePath(rootDir);
|
|
1861
|
-
try {
|
|
1862
|
-
return parseProvisionState(await readFile(path, "utf8"));
|
|
1863
|
-
} catch (cause) {
|
|
1864
|
-
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
|
|
1865
|
-
throw internalErrorDiagnostics.INTERNAL_R0014({
|
|
1866
|
-
path,
|
|
1867
|
-
cause
|
|
1868
|
-
});
|
|
1869
|
-
}
|
|
1870
|
-
}
|
|
1871
|
-
function readProvisionStateSync(rootDir) {
|
|
1872
|
-
const path = getProvisionStatePath(rootDir);
|
|
1873
|
-
try {
|
|
1874
|
-
return parseProvisionState(readFileSync(path, "utf8"));
|
|
1875
|
-
} catch (cause) {
|
|
1876
|
-
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
|
|
1877
|
-
throw internalErrorDiagnostics.INTERNAL_R0014({
|
|
1878
|
-
path,
|
|
1879
|
-
cause
|
|
1880
|
-
});
|
|
1881
|
-
}
|
|
1882
|
-
}
|
|
1883
|
-
async function writeProvisionState(rootDir, next) {
|
|
1884
|
-
const path = getProvisionStatePath(rootDir);
|
|
1885
|
-
const merged = mergeProvisionState(await readProvisionState(rootDir), next);
|
|
1886
|
-
await mkdir(dirname(path), { recursive: true });
|
|
1887
|
-
await writeFile(path, `${JSON.stringify(sortState(merged), null, 2)}\n`, "utf8");
|
|
1888
|
-
}
|
|
1889
|
-
function mergeProvisionState(base, next) {
|
|
1890
|
-
const merged = structuredClone(base);
|
|
1891
|
-
for (const provider of Object.keys(next)) {
|
|
1892
|
-
const categories = next[provider];
|
|
1893
|
-
if (!categories) continue;
|
|
1894
|
-
const target = merged[provider] ??= {};
|
|
1895
|
-
for (const [category, ids] of Object.entries(categories)) setOwn(target, category, {
|
|
1896
|
-
...(Object.hasOwn(target, category) ? target[category] : void 0) ?? {},
|
|
1897
|
-
...ids
|
|
1898
|
-
});
|
|
1899
|
-
}
|
|
1900
|
-
return merged;
|
|
1901
|
-
}
|
|
1902
|
-
function parseProvisionState(raw) {
|
|
1903
|
-
const parsed = JSON.parse(raw);
|
|
1904
|
-
if (!isRecord(parsed)) return {};
|
|
1905
|
-
const state = {};
|
|
1906
|
-
for (const provider of ["cloudflare", "vercel"]) {
|
|
1907
|
-
const categories = parsed[provider];
|
|
1908
|
-
if (!isRecord(categories)) continue;
|
|
1909
|
-
const validCategories = {};
|
|
1910
|
-
for (const [category, ids] of Object.entries(categories)) {
|
|
1911
|
-
if (!isRecord(ids)) continue;
|
|
1912
|
-
const validIds = {};
|
|
1913
|
-
for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
|
|
1914
|
-
if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
|
|
1915
|
-
}
|
|
1916
|
-
if (Object.keys(validCategories).length) state[provider] = validCategories;
|
|
1917
|
-
}
|
|
1918
|
-
return state;
|
|
1919
|
-
}
|
|
1920
|
-
function setOwn(target, key, value) {
|
|
1921
|
-
Object.defineProperty(target, key, {
|
|
1922
|
-
configurable: true,
|
|
1923
|
-
enumerable: true,
|
|
1924
|
-
value,
|
|
1925
|
-
writable: true
|
|
1926
|
-
});
|
|
1927
|
-
}
|
|
1928
|
-
function sortState(state) {
|
|
1929
|
-
return sortKeys(state);
|
|
1930
|
-
}
|
|
1931
|
-
function sortKeys(value) {
|
|
1932
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
1933
|
-
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]));
|
|
1934
|
-
}
|
|
1935
|
-
// src/error-diagnostics.ts
|
|
1936
|
-
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
1937
|
-
const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
1938
|
-
docsBase: "https://vitehub.dev/docs/cli/diagnostics",
|
|
1939
|
-
codes: {
|
|
1940
|
-
CLI_CONSOLE_LOGIN_FAILED: {
|
|
1941
|
-
fix: "Run `vitehub login` again, and approve the code in the browser within 15 minutes. Pass --console <url> for a self-hosted Console.",
|
|
1942
|
-
why: ({ console, message }) => `Sign-in to ${String(console)} did not finish. ${String(message)}`
|
|
1943
|
-
},
|
|
1944
|
-
CLI_CONSOLE_REQUEST_FAILED: {
|
|
1945
|
-
fix: ({ fix }) => typeof fix === "string" ? fix : "Check that you are an owner or admin of the team, and that the key opens the app. Run `vitehub whoami` to see both.",
|
|
1946
|
-
why: ({ code, console, message }) => `${String(console)} refused the request (${String(code)}). ${String(message)}`
|
|
1947
|
-
},
|
|
1948
|
-
CLI_CONSOLE_SIGNED_OUT: {
|
|
1949
|
-
fix: "Run `vitehub login`, or set VITEHUB_CONSOLE_TOKEN to an API key from Account settings in the Console.",
|
|
1950
|
-
why: ({ console }) => `There is no valid API key for ${String(console)}. The key is missing, expired, or revoked.`
|
|
1951
|
-
},
|
|
1952
|
-
CLI_ENV_FILE_EXISTS: {
|
|
1953
|
-
fix: ({ file }) => `Pass --yes to replace ${String(file)}, or move it first.`,
|
|
1954
|
-
why: ({ file }) => `${String(file)} exists. \`vitehub env pull\` does not replace a file without --yes.`
|
|
1955
|
-
},
|
|
1956
|
-
CLI_ENV_FILE_NOT_IGNORED: {
|
|
1957
|
-
fix: ({ file, tracked }) => tracked ? `Run \`git rm --cached ${String(file)}\` and add \`.env.*\` to .gitignore, then pull again.` : `Run \`echo '.env.*' >> .gitignore\`, then pull again.`,
|
|
1958
|
-
why: ({ file, tracked }) => tracked ? `git tracks ${String(file)}, so the values would be committed.` : `${String(file)} is not in .gitignore, so the values could be committed.`
|
|
1959
|
-
},
|
|
1960
|
-
CLI_ENV_PULL_FAILED: {
|
|
1961
|
-
fix: "Check that the Console stores env values, that the key opens the project, and that you are an owner or admin of the team.",
|
|
1962
|
-
why: ({ code, message }) => `The Console refused the pull (${String(code)}). ${String(message)}`
|
|
1963
|
-
},
|
|
1964
|
-
CLI_HOST_RESPONSE_INVALID: {
|
|
1965
|
-
fix: "Run the command again. If the error stays, check the status page of the host and update `@vite-hub/cli`.",
|
|
1966
|
-
why: ({ host }) => `[vitehub] The ${host} API returned an unexpected response.`
|
|
1967
|
-
},
|
|
1968
|
-
CLI_R0001: {
|
|
1969
|
-
...dynamicError,
|
|
1970
|
-
fix: "Install `nuxt` in the project, such as with `pnpm add nuxt`, then run the command again."
|
|
1971
|
-
},
|
|
1972
|
-
CLI_R0002: {
|
|
1973
|
-
...dynamicError,
|
|
1974
|
-
fix: "Install `@vite-hub/cli` again, such as with `pnpm add -D @vite-hub/cli`."
|
|
1975
|
-
},
|
|
1976
|
-
CLI_R0003: {
|
|
1977
|
-
fix: "Run the command with --help to see its input.",
|
|
1978
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
1979
|
-
},
|
|
1980
|
-
CLI_R0005: {
|
|
1981
|
-
fix: "Start `vite dev` in this project, or pass `--url <origin>` of a running or deployed app. `VITEHUB_DEV_SERVER_URL` also names a server.",
|
|
1982
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
1983
|
-
},
|
|
1984
|
-
CLI_SETUP_FAILED: {
|
|
1985
|
-
fix: "Fix the cause that the message names, then run the command again.",
|
|
1986
|
-
why: ({ message }) => message
|
|
1987
|
-
},
|
|
1988
|
-
CLI_UPDATE_INSTALL_FAILED: {
|
|
1989
|
-
fix: ({ command }) => `The package files already name the new versions. Fix the cause that the package manager printed, then run \`${String(command)}\`. To undo the update, restore the changed files with git.`,
|
|
1990
|
-
why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
|
|
1991
|
-
},
|
|
1992
|
-
CLI_UPDATE_NO_PACKAGES: {
|
|
1993
|
-
fix: "Run `vitehub update` in the folder of the app or of the workspace that installs `vite-hub`. To start, run `pnpm add vite-hub`.",
|
|
1994
|
-
why: ({ root }) => `No package.json in ${String(root)} or its workspace packages names \`vite-hub\` or an \`@vite-hub/*\` package with a version or a pkg.pr.new URL.`
|
|
1995
|
-
},
|
|
1996
|
-
CLI_UPDATE_PACKAGE_MISSING: {
|
|
1997
|
-
fix: ({ target }) => String(target) === "npm" ? "Pass --preview <commit> to use a pkg.pr.new build that has these packages, or remove them from package.json." : "Pass the commit of a build that has these packages, such as a newer commit of main, or remove them from package.json.",
|
|
1998
|
-
why: ({ packages, target }) => `The project depends on ${String(packages)}, which ${String(target)} does not have. Nothing was changed.`
|
|
1999
|
-
},
|
|
2000
|
-
CLI_UPDATE_REQUEST_FAILED: {
|
|
2001
|
-
fix: "Check the network and the npm registry in `npm_config_registry`, then run `vitehub update` again.",
|
|
2002
|
-
why: ({ status, url }) => `The request to ${String(url)} failed (${String(status)}). Nothing was changed.`
|
|
2003
|
-
},
|
|
2004
|
-
SETUP_CONFIG_NOT_LITERAL: {
|
|
2005
|
-
fix: "Write the options as an object literal, such as `vitehub({ kv: true })`, or edit the config by hand.",
|
|
2006
|
-
why: ({ file, reason }) => `The vitehub() options in ${String(file)} cannot be read without running the config (${String(reason)}).`
|
|
2007
|
-
},
|
|
2008
|
-
SETUP_LOGS_OPTION_MOVED: {
|
|
2009
|
-
why: "`observability.logs` is no longer a ViteHub option.",
|
|
2010
|
-
fix: "Remove the option from the command. Configure the top-level `logs` key by hand, for example `logs: { source: './server/logs.ts' }` to set `logs.source`."
|
|
2011
|
-
},
|
|
2012
|
-
SETUP_NOT_A_PROJECT: {
|
|
2013
|
-
fix: "Run the command in the folder of your Vite or Nuxt app, where its package.json is.",
|
|
2014
|
-
why: ({ root }) => `${String(root)} has no package.json, vite.config, or nuxt.config file.`
|
|
2015
|
-
},
|
|
2016
|
-
SETUP_CONFIG_MANUAL: {
|
|
2017
|
-
fix: ({ fix, snippet }) => fix ?? `Add these keys to the vitehub() options by hand:\n${String(snippet)}`,
|
|
2018
|
-
why: ({ file, reason }) => `ViteHub cannot edit the vitehub() options in ${String(file)} without running the config (${String(reason)}).`
|
|
2019
|
-
},
|
|
2020
|
-
SETUP_FEATURE_UNSUPPORTED: {
|
|
2021
|
-
fix: "Remove the feature from the command, or set `host` to a host that supports it. Run `vitehub catalog` to compare hosts.",
|
|
2022
|
-
why: ({ detail, feature, host }) => `${String(feature)} is not supported on the ${String(host)} host. ${String(detail)}`
|
|
2023
|
-
},
|
|
2024
|
-
SETUP_FILE_EXISTS: {
|
|
2025
|
-
fix: "Choose another --name, or edit the file by hand.",
|
|
2026
|
-
why: ({ definition, file, starter }) => starter === void 0 ? `${String(file)} exists and is not the starter Definition. ViteHub never overwrites a file.` : `${String(file)} already defines a ${String(definition)} Definition that conflicts with ${String(starter)}, so the build would reject both.`
|
|
2027
|
-
},
|
|
2028
|
-
SETUP_SERVER_DIR_MANUAL: {
|
|
2029
|
-
fix: ({ command }) => command === "remove" ? "Pass --force to turn the features off without checking unresolved Definition files, or use literal directory options without layers or directory overrides." : "Create the Definition in your evaluated Nuxt server directory and rerun without --name, or use literal directory options without layers or directory overrides.",
|
|
2030
|
-
why: "ViteHub cannot determine the Nuxt application server directory without running the config."
|
|
2031
|
-
},
|
|
2032
|
-
SETUP_INPUT_NEEDED: {
|
|
2033
|
-
fix: ({ fix }) => fix ?? "Run the `rerun` command, or pass the missing values with --option.",
|
|
2034
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
2035
|
-
},
|
|
2036
|
-
SETUP_INSTALL_FAILED: {
|
|
2037
|
-
fix: ({ filesWritten, workspaceFile }) => `Run the install command by hand to see the error, then run the command again. ${filesWritten === "possible" ? "Scaffolding may have left new app files on disk; inspect the target folder before retrying." : filesWritten ? "The new app files were written before installation failed; keep them when retrying." : "ViteHub did not write starter or config files; the package manager may have changed package manifests or lockfiles."}${workspaceFile ? ` If pnpm reports an ignored esbuild build script, set \`allowBuilds: { esbuild: false }\` in \`${workspaceFile}\` before retrying.` : ""}`,
|
|
2038
|
-
why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
|
|
2039
|
-
},
|
|
2040
|
-
SETUP_FEATURE_IMPLIED: {
|
|
2041
|
-
fix: ({ by, feature }) => `Remove ${String(by)} too, or pass --force to write \`${String(feature)}: false\`.`,
|
|
2042
|
-
why: ({ by, feature }) => `${String(feature)} stays on because ${String(by)} turns it on.`
|
|
2043
|
-
},
|
|
2044
|
-
SETUP_FEATURE_REQUIRED: {
|
|
2045
|
-
fix: ({ by, feature }) => `Remove ${String(by)} too, or change its options before removing ${String(feature)}. --force cannot remove a required feature.`,
|
|
2046
|
-
why: ({ by, feature }) => `${String(feature)} is required by the configured options of ${String(by)}.`
|
|
2047
|
-
},
|
|
2048
|
-
SETUP_FEATURE_IN_USE: {
|
|
2049
|
-
fix: "Delete or move the files in `references`, then run the command again. Pass --force to turn the feature off and keep the files.",
|
|
2050
|
-
why: ({ features, references }) => `The app still uses ${String(features)}:\n${String(references)}`
|
|
2051
|
-
},
|
|
2052
|
-
SETUP_UNINSTALL_FAILED: {
|
|
2053
|
-
fix: ({ configWritten }) => `Run the uninstall command by hand to see the error. ${configWritten === false ? "ViteHub kept the config unchanged; starter files may already be deleted. Plan the removal again after fixing the uninstall." : "ViteHub already changed the config and deleted the starter files."}`,
|
|
2054
|
-
why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
|
|
2055
|
-
},
|
|
2056
|
-
SETUP_PLAN_UNKNOWN: {
|
|
2057
|
-
fix: "Plan the change again. A plan applies once, and only on the dev server that made it.",
|
|
2058
|
-
why: () => "The dev server has no plan with this id. It was applied already, or the server restarted."
|
|
2059
|
-
},
|
|
2060
|
-
SETUP_STALE_PLAN: {
|
|
2061
|
-
fix: "Run the command again to plan from the current file.",
|
|
2062
|
-
why: ({ file }) => `${String(file)} changed after ViteHub planned the change.`
|
|
2063
|
-
},
|
|
2064
|
-
SETUP_LINK_HOST_UNSUPPORTED: {
|
|
2065
|
-
fix: "Pass --host cloudflare, vercel, netlify, or deno, or set `host` in vitehub().",
|
|
2066
|
-
why: ({ host }) => `The ${String(host)} host has no project to link. A self-hosted Node server needs no link.`
|
|
2067
|
-
},
|
|
2068
|
-
SETUP_LINK_CREDENTIALS_MISSING: {
|
|
2069
|
-
fix: ({ fix }) => fix === void 0 ? "Log in with the host CLI, such as `npx wrangler login`, or set the host token, such as CLOUDFLARE_API_TOKEN, VERCEL_TOKEN, NETLIFY_AUTH_TOKEN, or DENO_DEPLOY_TOKEN, then run the command again." : String(fix),
|
|
2070
|
-
why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login.`
|
|
2071
|
-
},
|
|
2072
|
-
SETUP_LINK_ACCOUNT_REQUIRED: {
|
|
2073
|
-
fix: "Run the command again with --account <id>, using one of the account ids in `missing`.",
|
|
2074
|
-
why: ({ count }) => Number(count) === 0 ? "The Cloudflare token has access to no account." : `The Cloudflare token has access to ${String(count)} accounts, so the account to link is not clear.`
|
|
2075
|
-
},
|
|
2076
|
-
SETUP_LINK_HOST_REQUIRED: {
|
|
2077
|
-
fix: ({ command }) => `Run \`${String(command)} --host <host>\`, or make one host the default with \`vitehub link --host <host> --default\`.`,
|
|
2078
|
-
why: ({ hosts }) => `The project links several hosts (${String(hosts)}) and none is the default, so the host is not clear.`
|
|
2079
|
-
},
|
|
2080
|
-
SETUP_LINK_NAME_REQUIRED: {
|
|
2081
|
-
fix: "Pass --project <name>, or set `name` in vitehub() or in package.json.",
|
|
2082
|
-
why: () => "The project name is not known. vitehub() has no literal `name` and package.json has no name."
|
|
2083
|
-
},
|
|
2084
|
-
SETUP_LINK_PROJECT_NOT_FOUND: {
|
|
2085
|
-
fix: ({ host, rerun }) => host === "deno" ? "Create the app in Deno Deploy first, then run `vitehub link --host deno`, or pass --project with the name of an existing app." : `Run \`${String(rerun)}\` to create it, or pass --project with the name of a project that exists.`,
|
|
2086
|
-
why: ({ host, project, account }) => `The ${String(host)} project ${JSON.stringify(String(project))} does not exist${account ? ` in account ${String(account)}` : ""}.`
|
|
2087
|
-
},
|
|
2088
|
-
SETUP_INIT_DIR_NOT_EMPTY: {
|
|
2089
|
-
fix: "Choose a new or empty folder, or run `vitehub init` on the folder of a Vite or Nuxt app.",
|
|
2090
|
-
why: ({ dir }) => `${String(dir)} is not empty and holds no Vite or Nuxt app. ViteHub never overwrites a file.`
|
|
2091
|
-
},
|
|
2092
|
-
SETUP_INIT_FRAMEWORK_MISMATCH: {
|
|
2093
|
-
fix: ({ found }) => `Pass --framework ${String(found)}, or choose another folder.`,
|
|
2094
|
-
why: ({ dir, found, framework }) => `${String(dir)} holds a ${String(found)} app, not a ${String(framework)} app.`
|
|
2095
|
-
},
|
|
2096
|
-
SETUP_INIT_HOST_MIGRATION: {
|
|
2097
|
-
fix: "Use the app's current host, or migrate its enabled features, providers and Definitions in the config before running init again.",
|
|
2098
|
-
why: ({ host }) => `init cannot change an enabled ViteHub stack to the ${String(host)} host.`
|
|
2099
|
-
},
|
|
2100
|
-
SETUP_INIT_NITRO_VERSION: {
|
|
2101
|
-
fix: ({ dir, range, scaffolded }) => `${scaffolded ? `The scaffold files remain in ${String(dir)}. ` : ""}Set nitro to \`${String(range)}\` in each section of package.json that declares it, then run init again.`,
|
|
2102
|
-
why: ({ dir, range }) => `${String(dir)} declares a Nitro version that init cannot verify against Nuxt 4.7's requirement (${String(range)}). ViteHub did not adopt it.`
|
|
2103
|
-
},
|
|
2104
|
-
SETUP_INIT_NUXT_VERSION: {
|
|
2105
|
-
fix: ({ dir, scaffolded }) => `${scaffolded ? `The scaffold files remain in ${String(dir)}. ` : ""}Upgrade to Nuxt 4.7 with Nitro 3 (\`pnpm add nuxt@^4.7.0 nitro\`), or set nuxt to a Nuxt 5 version. Then run init on that folder again.`,
|
|
2106
|
-
why: ({ dir }) => `${String(dir)} does not declare a supported Nuxt version. ViteHub needs Nitro 3, which runs on Nuxt 4.7 with the nitro package, or on Nuxt 5. ViteHub did not adopt it.`
|
|
2107
|
-
},
|
|
2108
|
-
SETUP_DEPLOY_HOST_UNSUPPORTED: {
|
|
2109
|
-
fix: "Set `host` in vitehub() to cloudflare, vercel, netlify, or deno, or start the Node server from `.output` yourself.",
|
|
2110
|
-
why: ({ host }) => `\`vitehub deploy\` has no upload for the ${String(host)} host.`
|
|
2111
|
-
},
|
|
2112
|
-
SETUP_DEPLOY_CREDENTIALS_MISSING: {
|
|
2113
|
-
fix: ({ fix }) => fix === void 0 ? "Log in with the host CLI, such as `npx wrangler login`, or set the host token, such as CLOUDFLARE_API_TOKEN, VERCEL_TOKEN, NETLIFY_AUTH_TOKEN, or DENO_DEPLOY_TOKEN, then run the command again." : String(fix),
|
|
2114
|
-
why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login.`
|
|
2115
|
-
},
|
|
2116
|
-
SETUP_DEPLOY_D1_MIGRATIONS_PENDING: {
|
|
2117
|
-
fix: ({ apply }) => `Set \`database.migrateOnDeploy: true\` so that \`vitehub deploy\` applies them before the Worker deploys. Or run \`${String(apply)}\` in the build output folder, then deploy again.`,
|
|
2118
|
-
why: ({ binding, migrations }) => `The build has D1 migrations that the remote database of the binding ${String(binding)} has not applied: ${String(migrations)}. The new code would query tables or columns that do not exist yet. Nothing was deployed.`
|
|
2119
|
-
},
|
|
2120
|
-
SETUP_DEPLOY_TEMPORARY_UNSUPPORTED: {
|
|
2121
|
-
fix: "Remove --temporary and deploy with your host login.",
|
|
2122
|
-
why: ({ reason }) => `--temporary cannot run here. ${String(reason)}`
|
|
2123
|
-
},
|
|
2124
|
-
SETUP_DEPLOY_PREVIEW_UNSUPPORTED: {
|
|
2125
|
-
fix: "Remove --preview to deploy to production.",
|
|
2126
|
-
why: ({ host }) => `The ${String(host)} deploy that the build writes always deploys to production.`
|
|
2127
|
-
},
|
|
2128
|
-
SETUP_DEPLOY_ORG_REQUIRED: {
|
|
2129
|
-
fix: "Set DENO_DEPLOY_ORG to your Deno Deploy organization, or run `vitehub link --host deno --account <org>`.",
|
|
2130
|
-
why: () => "The Deno Deploy organization is not known."
|
|
2131
|
-
},
|
|
2132
|
-
SETUP_DEPLOY_BUILD_FAILED: {
|
|
2133
|
-
fix: "Fix the build error above and run the command again, or pass --no-build to deploy the output that is there.",
|
|
2134
|
-
why: ({ command, exitCode }) => exitCode === void 0 ? `package.json has no \`build\` script, so \`${String(command)}\` cannot build the app.` : `\`${String(command)}\` exited with code ${String(exitCode)}.`
|
|
2135
|
-
},
|
|
2136
|
-
SETUP_DEPLOY_CHECK_FAILED: {
|
|
2137
|
-
fix: ({ rollback }) => `${String(rollback)} Then fix the app and deploy again. Pass --no-check only when the check itself is wrong.`,
|
|
2138
|
-
why: ({ failed, url }) => `The app is deployed to ${String(url)}, but a \`deploy.check\` path did not answer with a 2xx status: ${String(failed)}.`
|
|
2139
|
-
},
|
|
2140
|
-
SETUP_DEPLOY_OUTPUT_MISSING: {
|
|
2141
|
-
fix: "Build the app with vitehub() for this host, then run the command again without --no-build.",
|
|
2142
|
-
why: ({ file }) => `The build output has no ${String(file)}.`
|
|
2143
|
-
},
|
|
2144
|
-
SETUP_DEPLOY_HOST_MISMATCH: {
|
|
2145
|
-
fix: ({ host }) => `Build again for ${String(host)}: run \`vitehub deploy --host ${String(host)}\` without --no-build.`,
|
|
2146
|
-
why: ({ built, host }) => `The build output is for ${String(built)}, but this deploy goes to ${String(host)}.`
|
|
2147
|
-
},
|
|
2148
|
-
SETUP_DEPLOY_COMMAND_REJECTED: {
|
|
2149
|
-
fix: "Build again with vitehub(). If you set the deploy command yourself, run it yourself.",
|
|
2150
|
-
why: ({ command }) => `The build output names a deploy command that ViteHub did not write, so it does not run it: ${String(command)}`
|
|
2151
|
-
},
|
|
2152
|
-
SETUP_DEPLOY_ENV_MISSING: {
|
|
2153
|
-
fix: ({ console, firstDeploy, host }) => (console === true ? "For VITEHUB_CONSOLE_KEY_*, run `vitehub login`, and deploy links the app in the Console and sets its key. " : "") + (firstDeploy ? `Set each name in the shell or in .env.<stage>, then deploy again. If the ${String(host)} project already exists, run \`vitehub link --host ${String(host)}\` first, so deploy reads its variables.` : `Run \`vitehub env push --host ${String(host)}\`, set the names in the ${String(host)} dashboard, or set them in the shell or in .env.<stage> and deploy again.`),
|
|
2154
|
-
why: ({ firstDeploy, host, names, stage }) => firstDeploy ? `The app needs ${String(names)}, and no value was found. This is the first deploy to ${String(host)}: the project is not linked, so the host has no variables yet and every required name needs a local value for the ${String(stage)} stage. Nothing was deployed.` : `The app needs ${String(names)}, and neither ${String(host)} nor a local value for the ${String(stage)} stage has one. Nothing was deployed.`
|
|
2155
|
-
},
|
|
2156
|
-
SETUP_DEPLOY_ENV_NOT_LINKED: {
|
|
2157
|
-
fix: ({ host }) => host === "deno" ? "Create the app in Deno Deploy if needed, run `vitehub link --host deno`, then deploy again." : `Run \`vitehub link --host ${String(host)} --create\` to create the project, then deploy again.`,
|
|
2158
|
-
why: ({ host, names }) => `The ${String(host)} project is not linked, so deploy cannot set ${String(names)} before the first deploy. Nothing was deployed.`
|
|
2159
|
-
},
|
|
2160
|
-
SETUP_DEPLOY_ENV_STAGE_UNSAFE: {
|
|
2161
|
-
why: ({ names, stage }) => `These existing Cloudflare secrets have no local value for stage ${String(stage)}: ${String(names)}. The latest uploaded version may belong to another stage, so inheriting its values is unsafe. Nothing was deployed.`,
|
|
2162
|
-
fix: ({ console, stage }) => `Set every listed name in the shell or an untracked .env.${String(stage)} file and deploy again. Cloudflare deploys re-supply all existing secrets with the version to preserve stage isolation.${console ? " For a Console key, copy the public value of the existing link, or restore the Console connection with `vitehub login`." : ""}`
|
|
2163
|
-
},
|
|
2164
|
-
SETUP_DEPLOY_FAILED: {
|
|
2165
|
-
fix: "Read the host output above, fix the cause, and run the command again.",
|
|
2166
|
-
why: ({ exitCode, output, step }) => `\`${String(step)}\` failed${exitCode === void 0 ? "" : ` with exit code ${String(exitCode)}`}.${output ? `\n${String(output)}` : ""}`
|
|
2167
|
-
},
|
|
2168
|
-
SETUP_DEPLOYMENTS_NOT_LINKED: {
|
|
2169
|
-
fix: ({ host }) => host ? `Run \`vitehub link --host ${String(host)}\`, or deploy once with \`vitehub deploy --host ${String(host)}\`.` : "Run `vitehub link` to link the project to its host, or deploy once with `vitehub deploy`.",
|
|
2170
|
-
why: ({ host }) => host ? `The project has no ${String(host)} target in .vitehub/link.json, so the host project to read is not known.` : "The project has no host link in .vitehub/link.json, so the host project to read is not known."
|
|
2171
|
-
},
|
|
2172
|
-
SETUP_DEPLOYMENTS_CREDENTIALS_MISSING: {
|
|
2173
|
-
fix: ({ fix }) => fix === void 0 ? "Log in with the host CLI, such as `npx wrangler login`, or set the host token, such as CLOUDFLARE_API_TOKEN, VERCEL_TOKEN, NETLIFY_AUTH_TOKEN, or DENO_DEPLOY_TOKEN, then run the command again." : String(fix),
|
|
2174
|
-
why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login, so the deployments cannot be read.`
|
|
2175
|
-
},
|
|
2176
|
-
SETUP_DEPLOYMENTS_ACCOUNT_REQUIRED: {
|
|
2177
|
-
fix: "Set CLOUDFLARE_ACCOUNT_ID, or run `vitehub link --host cloudflare --account <id>`.",
|
|
2178
|
-
why: ({ host }) => `The ${String(host)} account of the linked project is not known.`
|
|
2179
|
-
},
|
|
2180
|
-
SETUP_DEPLOYMENTS_PROJECT_ID_REQUIRED: {
|
|
2181
|
-
fix: ({ host }) => `Run \`vitehub link --host ${String(host)}\` to store the project id.`,
|
|
2182
|
-
why: ({ host }) => `The ${String(host)} link has no project id, and the ${String(host)} API lists deployments by id.`
|
|
2183
|
-
},
|
|
2184
|
-
SETUP_DEPLOY_CHECKOUT_CONFLICT: {
|
|
2185
|
-
fix: "Edit each file and remove the conflict markers, or run `vitehub resolve` for a binary file. Then deploy again, or pass --no-push to deploy without the push.",
|
|
2186
|
-
why: ({ files }) => `A checkout folder of vitehub.lock has unresolved conflicts, so the Workspace push after the deploy would fail. Nothing was built or deployed: ${String(files)}`
|
|
2187
|
-
},
|
|
2188
|
-
SETUP_DEPLOY_CHECKOUT_MODULE_FAILED: {
|
|
2189
|
-
fix: "Reinstall the project dependencies and check that the Workspace package is the same version as the CLI. Or pass --no-push to deploy without the push.",
|
|
2190
|
-
why: ({ file, message, specifier }) => `The project installs ${String(specifier)}, but ViteHub cannot load it from ${String(file)}, so it cannot push the checkout folders of vitehub.lock. Nothing was built or deployed: ${String(message)}`
|
|
2191
|
-
},
|
|
2192
|
-
SETUP_DEPLOY_PROVISION_NEEDS_BUILD: {
|
|
2193
|
-
fix: "Deploy again without --no-build, so the build gets the new ids.",
|
|
2194
|
-
why: ({ count }) => `The deploy must create or change ${String(count)} resources, but --no-build deploys an output that was built without their ids. Nothing was created or deployed.`
|
|
2195
|
-
},
|
|
2196
|
-
SETUP_DEPLOY_PROVISION_UNCHECKED: {
|
|
2197
|
-
fix: "Set the credential that the reason names and deploy again. Or deploy with --no-provision to skip the resources.",
|
|
2198
|
-
why: ({ host, missing, warnings }) => `The deploy could not check the ${String(host)} resources of the app, so it created and deployed nothing: ${String(warnings)} ${String(missing)}`
|
|
2199
|
-
},
|
|
2200
|
-
SETUP_DEPLOY_PUSH_FAILED: {
|
|
2201
|
-
fix: ({ fix }) => `${fix ? `${String(fix)} ` : ""}Then run \`vitehub push\`. Do not deploy again.`,
|
|
2202
|
-
why: ({ message, url }) => `The app is deployed${url === void 0 ? "" : ` to ${String(url)}`}, but the Workspace push failed: ${String(message)}`
|
|
2203
|
-
},
|
|
2204
|
-
CLI_R0004: {
|
|
2205
|
-
fix: "Run it again with --yes, or check the change first with a dry run when the command has one.",
|
|
2206
|
-
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
2207
|
-
},
|
|
2208
|
-
SETUP_ENV_DECRYPT_FAILED: {
|
|
2209
|
-
fix: ({ file, key }) => `Set ${String(key)} to the private key that encrypted ${String(file)}. Check it with \`dotenvx get -f ${String(file)}\`.`,
|
|
2210
|
-
why: ({ file, key, name, reason }) => `${String(key)} cannot decrypt ${String(name)} in ${String(file)} (${String(reason)}).`
|
|
2211
|
-
},
|
|
2212
|
-
SETUP_ENV_FILE_NOT_IGNORED: {
|
|
2213
|
-
fix: ({ file }) => `Add \`.env*\` or \`${String(file)}\` to .gitignore. Or set the values in the shell for this command.`,
|
|
2214
|
-
why: ({ file, names }) => `The secret ${String(names)} reads ${String(file)}, which git does not ignore, so a commit can add it. \`vitehub env push\` pushes a secret only from a file that git ignores.`
|
|
2215
|
-
},
|
|
2216
|
-
SETUP_ENV_FILE_TRACKED: {
|
|
2217
|
-
fix: ({ file }) => `Run \`git rm --cached ${String(file)}\`, add \`.env*\` to .gitignore, and rotate the values that git has seen. Or set the values in the shell for this command.`,
|
|
2218
|
-
why: ({ file, names }) => `The secret ${String(names)} reads ${String(file)}, which git tracks, directly or through \`$NAME\` expansion or a symlink. \`vitehub env push\` does not push a secret that is in git.`
|
|
2219
|
-
},
|
|
2220
|
-
SETUP_ENV_GIT_FAILED: {
|
|
2221
|
-
fix: "Fix the git repository so that `git ls-files` and `git check-ignore` work, then run the command again. Or set the values in the shell for this command.",
|
|
2222
|
-
why: ({ file, reason }) => `Git could not tell whether it tracks or ignores ${String(file)}, which holds a secret: ${String(reason)}. Nothing was pushed.`
|
|
2223
|
-
},
|
|
2224
|
-
SETUP_ENV_KEYS_TRACKED: {
|
|
2225
|
-
fix: ({ file }) => `Run \`git rm --cached ${String(file)}\`, add it to .gitignore, and rotate the keys with \`dotenvx rotate\`. Everyone with the repository can decrypt the values until then.`,
|
|
2226
|
-
why: ({ file }) => `${String(file)} holds the private keys of the encrypted env files and is tracked by git. \`vitehub env push\` does not decrypt with a key that is in git.`
|
|
2227
|
-
},
|
|
2228
|
-
SETUP_ENV_NAME_UNKNOWN: {
|
|
2229
|
-
fix: "Pass names that `vitehub env diff` lists, or build again after you declare the name.",
|
|
2230
|
-
why: ({ names }) => `The build output lists no variable named ${String(names)}.`
|
|
2231
|
-
},
|
|
2232
|
-
SETUP_ENV_PRIVATE_KEY_MISSING: {
|
|
2233
|
-
fix: ({ key }) => `Set ${String(key)} in the shell, or add it to .env.keys, which git must ignore.`,
|
|
2234
|
-
why: ({ file, key, names }) => `${String(file)} holds the encrypted ${String(names)}, and ${String(key)} is not set.`
|
|
2235
|
-
},
|
|
2236
|
-
SETUP_ENV_STAGE_UNSUPPORTED: {
|
|
2237
|
-
fix: ({ host, stage }) => stage !== "preview" ? "Use --stage production or --stage preview, the stages of `vitehub deploy` and `vitehub deploy --preview`." : host === "cloudflare" ? "A Worker has one set of secrets for every version. Push production values with --stage production." : "`vitehub deploy` deploys this host to production only. Push with --stage production.",
|
|
2238
|
-
why: ({ host, stage }) => `The ${String(host)} host has no environment for the ${String(stage)} stage.`
|
|
2239
|
-
},
|
|
2240
|
-
SETUP_ENV_VALUE_UNSUPPORTED: {
|
|
2241
|
-
fix: ({ host }) => `Set this value in the ${String(host)} dashboard.`,
|
|
2242
|
-
why: ({ host, name, reason }) => `The value of ${String(name)} cannot go to ${String(host)} without a terminal prompt or argv. ${String(reason)}`
|
|
2243
|
-
},
|
|
2244
|
-
SETUP_GITHUB_REPOSITORY_REQUIRED: {
|
|
2245
|
-
fix: "Pass --repo owner/name, or add a GitHub remote named origin.",
|
|
2246
|
-
why: ({ remote }) => remote ? `The git remote origin (${String(remote)}) is not a github.com repository.` : "This folder has no git remote named origin."
|
|
2247
|
-
},
|
|
2248
|
-
SETUP_GITHUB_REQUEST_FAILED: {
|
|
2249
|
-
fix: "Check that the token can write the Actions secrets of the repository, and that the repository and environment exist.",
|
|
2250
|
-
why: ({ operation, reason }) => `GitHub refused \`${String(operation)}\`: ${String(reason)}`
|
|
2251
|
-
}
|
|
2252
|
-
}
|
|
2253
|
-
});
|
|
2254
|
-
// src/setup/envelope.ts
|
|
2255
|
-
/** Exit codes of the setup commands. */
|
|
2256
|
-
const setupExitCodes = {
|
|
2257
|
-
done: 0,
|
|
2258
|
-
error: 1,
|
|
2259
|
-
inputNeeded: 2,
|
|
2260
|
-
conflict: 3,
|
|
2261
|
-
stalePlan: 4
|
|
2262
|
-
};
|
|
2263
|
-
function isDiagnostic(error) {
|
|
2264
|
-
return error instanceof Error && typeof Reflect.get(error, "code") === "string" && typeof Reflect.get(error, "why") === "string";
|
|
2265
|
-
}
|
|
2266
|
-
function toSetupError(error) {
|
|
2267
|
-
const diagnostic = isDiagnostic(error) ? error : cliErrorDiagnostics.CLI_SETUP_FAILED({ message: error instanceof Error ? error.message : String(error) });
|
|
2268
|
-
const why = diagnostic.why.replace(/^\[vitehub\] /u, "");
|
|
2269
|
-
return {
|
|
2270
|
-
code: diagnostic.code,
|
|
2271
|
-
message: /^.*?[.!?](?=\s|$)/u.exec(why)?.[0] ?? why,
|
|
2272
|
-
why,
|
|
2273
|
-
...diagnostic.fix ? { fix: diagnostic.fix } : {},
|
|
2274
|
-
...diagnostic.docs ? { docs: diagnostic.docs } : {}
|
|
2275
|
-
};
|
|
2276
|
-
}
|
|
2277
|
-
/** Prints one JSON document with `schemaVersion: 1` on stdout. */
|
|
2278
|
-
function writeSetupJson(context, data) {
|
|
2279
|
-
context.stdout.write(`${JSON.stringify({
|
|
2280
|
-
schemaVersion: 1,
|
|
2281
|
-
...data
|
|
2282
|
-
})}\n`);
|
|
2283
|
-
}
|
|
2284
|
-
/** Adds the exit code and the missing input of a setup command to its diagnostic. */
|
|
2285
|
-
function setupFailure(diagnostic, exitCode, details = {}) {
|
|
2286
|
-
return Object.assign(diagnostic, {
|
|
2287
|
-
details,
|
|
2288
|
-
exitCode
|
|
2289
|
-
});
|
|
2290
|
-
}
|
|
2291
|
-
/** Whether `error` is a diagnostic that `setupFailure()` gave an exit code. */
|
|
2292
|
-
function isSetupFailure(error) {
|
|
2293
|
-
if (!(error instanceof Error)) return false;
|
|
2294
|
-
const details = Reflect.get(error, "details");
|
|
2295
|
-
return typeof Reflect.get(error, "exitCode") === "number" && typeof details === "object" && details !== null;
|
|
2296
|
-
}
|
|
2297
|
-
function formatMissing(missing) {
|
|
2298
|
-
return missing.map((item) => {
|
|
2299
|
-
const choices = item.choices ?? [];
|
|
2300
|
-
if (choices.every((choice) => typeof choice === "string")) return `Missing: ${item.field}${choices.length ? ` (${choices.join(", ")})` : ""}\n`;
|
|
2301
|
-
return `Missing: ${item.field}\n${choices.map((choice) => typeof choice === "string" ? ` ${choice}\n` : ` ${choice.id}${choice.name ? ` ${choice.name}` : ""}\n`).join("")}`;
|
|
2302
|
-
}).join("");
|
|
2303
|
-
}
|
|
2304
|
-
/**
|
|
2305
|
-
* Reports `error` as one JSON document on stdout with `--json`, else on stderr, and returns its exit code.
|
|
2306
|
-
* A `SetupFailure` adds `missing`, `rerun`, and its `data` to the document. Any other error exits with 1.
|
|
2307
|
-
*/
|
|
2308
|
-
function writeSetupError(context, json, error) {
|
|
2309
|
-
if (isSetupFailure(error)) {
|
|
2310
|
-
const { data, missing, rerun } = error.details;
|
|
2311
|
-
if (json) writeSetupJson(context, {
|
|
2312
|
-
...data,
|
|
2313
|
-
error: toSetupError(error),
|
|
2314
|
-
...missing ? { missing } : {},
|
|
2315
|
-
...rerun ? { rerun } : {}
|
|
2316
|
-
});
|
|
2317
|
-
else context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n${formatMissing(missing ?? [])}${rerun ? `Run: ${rerun}\n` : ""}`);
|
|
2318
|
-
return error.exitCode;
|
|
2319
|
-
}
|
|
2320
|
-
if (json) writeSetupJson(context, { error: toSetupError(error) });
|
|
2321
|
-
else context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
|
|
2322
|
-
return setupExitCodes.error;
|
|
2323
|
-
}
|
|
2324
|
-
/** Reads `--json` and `--help`. Throws `CLI_R0003` for any other argument. */
|
|
2325
|
-
function readSetupArgs(args, usage) {
|
|
2326
|
-
const unknown = args.find((arg) => arg !== "--json" && arg !== "-h" && arg !== "--help");
|
|
2327
|
-
if (unknown !== void 0) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown argument ${JSON.stringify(unknown)}. Usage: ${usage}` });
|
|
2328
|
-
return {
|
|
2329
|
-
help: args.includes("-h") || args.includes("--help"),
|
|
2330
|
-
json: args.includes("--json")
|
|
2331
|
-
};
|
|
2332
|
-
}
|
|
2333
|
-
/** Rows as plain text columns, two spaces apart. */
|
|
2334
|
-
function table(rows) {
|
|
2335
|
-
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
2336
|
-
return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()).join("\n");
|
|
2337
|
-
}
|
|
2338
|
-
// src/setup/console-auth.ts
|
|
2339
|
-
/** The hosted Console. `--console` and `VITEHUB_CONSOLE_URL` name a self-hosted one. */
|
|
2340
|
-
const defaultConsoleUrl = "https://console.vitehub.dev";
|
|
2341
|
-
/** An API key for CI. It wins over the saved key, and `vitehub logout` does not remove it. */
|
|
2342
|
-
const consoleTokenVariable = "VITEHUB_CONSOLE_TOKEN";
|
|
2343
|
-
const consoleUrlVariable = "VITEHUB_CONSOLE_URL";
|
|
2344
|
-
const clientId = "vitehub-cli";
|
|
2345
|
-
/** `$XDG_CONFIG_HOME/vitehub/credentials.json`, else `~/.config/vitehub/credentials.json`. */
|
|
2346
|
-
function consoleCredentialsFile(env) {
|
|
2347
|
-
const base = env.XDG_CONFIG_HOME || join$1(env.HOME || env.USERPROFILE || homedir(), ".config");
|
|
2348
|
-
return join$1(base, "vitehub", "credentials.json");
|
|
2349
|
-
}
|
|
2350
|
-
async function readCredentials(file, signal) {
|
|
2351
|
-
const text = await readFile(file, {
|
|
2352
|
-
encoding: "utf8",
|
|
2353
|
-
signal
|
|
2354
|
-
}).catch((error) => {
|
|
2355
|
-
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return void 0;
|
|
2356
|
-
throw error;
|
|
2357
|
-
});
|
|
2358
|
-
if (text === void 0) return {
|
|
2359
|
-
version: 1,
|
|
2360
|
-
consoles: {}
|
|
2361
|
-
};
|
|
2362
|
-
const parsed = JSON.parse(text);
|
|
2363
|
-
const consoles = parsed instanceof Object ? Reflect.get(parsed, "consoles") : void 0;
|
|
2364
|
-
return {
|
|
2365
|
-
version: 1,
|
|
2366
|
-
consoles: consoles instanceof Object ? consoles : {}
|
|
2367
|
-
};
|
|
2368
|
-
}
|
|
2369
|
-
async function writeCredentials(file, value) {
|
|
2370
|
-
await mkdir(dirname$1(file), {
|
|
2371
|
-
mode: 448,
|
|
2372
|
-
recursive: true
|
|
2373
|
-
});
|
|
2374
|
-
const temporary = `${file}.${process.pid}.tmp`;
|
|
2375
|
-
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
|
|
2376
|
-
await chmod(temporary, 384);
|
|
2377
|
-
await rename(temporary, file);
|
|
2378
|
-
}
|
|
2379
|
-
/** The origin of a Console URL. Plain `http` is accepted only for a Console on this machine. */
|
|
2380
|
-
function consoleOrigin(value) {
|
|
2381
|
-
let url;
|
|
2382
|
-
try {
|
|
2383
|
-
url = new URL(value);
|
|
2384
|
-
} catch {
|
|
2385
|
-
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be a URL, such as ${defaultConsoleUrl}. Got ${JSON.stringify(value)}.` });
|
|
2386
|
-
}
|
|
2387
|
-
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
2388
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be an https:// URL. Plain http:// is only for a Console on localhost. Got ${url.origin}.` });
|
|
2389
|
-
return url.origin;
|
|
2390
|
-
}
|
|
2391
|
-
/**
|
|
2392
|
-
* The key that a command sends to a Console, and where it came from: `VITEHUB_CONSOLE_TOKEN`, else the key that
|
|
2393
|
-
* `vitehub login` saved for the Console. Without `console`, the Console is `VITEHUB_CONSOLE_URL`, else the only saved
|
|
2394
|
-
* Console, else console.vitehub.dev. `undefined` when there is no key.
|
|
2395
|
-
*/
|
|
2396
|
-
async function readConsoleCredential(env, console, signal) {
|
|
2397
|
-
const file = await readCredentials(consoleCredentialsFile(env), signal);
|
|
2398
|
-
const named = console ?? env["VITEHUB_CONSOLE_URL"];
|
|
2399
|
-
const saved = Object.keys(file.consoles);
|
|
2400
|
-
const origin = consoleOrigin(named ?? (saved.length === 1 ? saved[0] : "https://console.vitehub.dev"));
|
|
2401
|
-
const token = env[consoleTokenVariable];
|
|
2402
|
-
if (token) return {
|
|
2403
|
-
origin,
|
|
2404
|
-
source: "env",
|
|
2405
|
-
token
|
|
2406
|
-
};
|
|
2407
|
-
const credential = file.consoles[origin];
|
|
2408
|
-
return credential ? {
|
|
2409
|
-
origin,
|
|
2410
|
-
saved: credential,
|
|
2411
|
-
source: "file",
|
|
2412
|
-
token: credential.token
|
|
2413
|
-
} : void 0;
|
|
2414
|
-
}
|
|
2415
|
-
function readArgs(args, usage, extra = {}) {
|
|
2416
|
-
try {
|
|
2417
|
-
return parseArgs({
|
|
2418
|
-
args,
|
|
2419
|
-
options: {
|
|
2420
|
-
...extra.console ? { console: { type: "string" } } : {},
|
|
2421
|
-
help: {
|
|
2422
|
-
short: "h",
|
|
2423
|
-
type: "boolean",
|
|
2424
|
-
default: false
|
|
2425
|
-
},
|
|
2426
|
-
json: {
|
|
2427
|
-
type: "boolean",
|
|
2428
|
-
default: false
|
|
2429
|
-
}
|
|
2430
|
-
},
|
|
2431
|
-
strict: true
|
|
2432
|
-
}).values;
|
|
2433
|
-
} catch (error) {
|
|
2434
|
-
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
|
|
2435
|
-
}
|
|
2436
|
-
}
|
|
2437
|
-
async function postJson(context, url, body) {
|
|
2438
|
-
const response = await (context.fetch ?? fetch)(url, {
|
|
2439
|
-
body: JSON.stringify(body),
|
|
2440
|
-
headers: {
|
|
2441
|
-
accept: "application/json",
|
|
2442
|
-
"content-type": "application/json"
|
|
2443
|
-
},
|
|
2444
|
-
method: "POST"
|
|
2445
|
-
});
|
|
2446
|
-
const data = await response.json().catch(() => ({}));
|
|
2447
|
-
return {
|
|
2448
|
-
data: data instanceof Object ? data : {},
|
|
2449
|
-
headers: response.headers,
|
|
2450
|
-
status: response.status
|
|
2451
|
-
};
|
|
2452
|
-
}
|
|
2453
|
-
function loginFailed(origin, message) {
|
|
2454
|
-
return cliErrorDiagnostics.CLI_CONSOLE_LOGIN_FAILED({
|
|
2455
|
-
console: origin,
|
|
2456
|
-
message
|
|
2457
|
-
});
|
|
2458
|
-
}
|
|
2459
|
-
const wait = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
|
|
2460
|
-
const dateFormat = new Intl.DateTimeFormat("en-GB", {
|
|
2461
|
-
day: "numeric",
|
|
2462
|
-
month: "short",
|
|
2463
|
-
year: "numeric",
|
|
2464
|
-
timeZone: "UTC"
|
|
2465
|
-
});
|
|
2466
|
-
function groupCode(code) {
|
|
2467
|
-
return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
|
|
2468
|
-
}
|
|
2469
|
-
async function deviceLogin(origin, context, prompt) {
|
|
2470
|
-
const started = await postJson(context, `${origin}/api/auth/device/code`, {
|
|
2471
|
-
client_id: clientId,
|
|
2472
|
-
client_name: `vitehub CLI on ${hostname()}`
|
|
2473
|
-
}).catch((error) => {
|
|
2474
|
-
throw loginFailed(origin, `The Console did not answer: ${error instanceof Error ? error.message : String(error)}`);
|
|
2475
|
-
});
|
|
2476
|
-
if (started.status !== 200 || typeof started.data.device_code !== "string") throw loginFailed(origin, `The Console answered ${started.status} to the device code request${typeof started.data.error === "string" ? ` (${started.data.error})` : ""}. Is ${origin} a ViteHub Console?`);
|
|
2477
|
-
const code = started.data;
|
|
2478
|
-
prompt.write(`Open ${code.verification_uri} and enter the code ${groupCode(code.user_code)}\n`);
|
|
2479
|
-
if (code.verification_uri_complete) prompt.write(`Or open ${code.verification_uri_complete}\n`);
|
|
2480
|
-
prompt.write("Waiting for approval...\n");
|
|
2481
|
-
let interval = Number.isFinite(code.interval) ? code.interval : 5;
|
|
2482
|
-
const deadline = Date.now() + code.expires_in * 1e3;
|
|
2483
|
-
while (Date.now() < deadline) {
|
|
2484
|
-
await wait(interval);
|
|
2485
|
-
const answer = await postJson(context, `${origin}/api/auth/cli/token`, {
|
|
2486
|
-
client_id: clientId,
|
|
2487
|
-
device_code: code.device_code
|
|
2488
|
-
});
|
|
2489
|
-
if (answer.status === 200 && typeof answer.data.access_token === "string") return answer.data;
|
|
2490
|
-
if (answer.status === 429) {
|
|
2491
|
-
interval = Math.max(interval, Number(answer.headers.get("retry-after")) || 60);
|
|
2492
|
-
continue;
|
|
2493
|
-
}
|
|
2494
|
-
const error = answer.data.error;
|
|
2495
|
-
if (error === "authorization_pending") continue;
|
|
2496
|
-
if (error === "slow_down") {
|
|
2497
|
-
interval += 5;
|
|
2498
|
-
continue;
|
|
2499
|
-
}
|
|
2500
|
-
if (error === "access_denied") throw loginFailed(origin, "The sign-in was denied in the browser.");
|
|
2501
|
-
if (error === "expired_token") break;
|
|
2502
|
-
throw loginFailed(origin, `The Console answered ${answer.status}${typeof error === "string" ? ` (${error})` : ""}.`);
|
|
2503
|
-
}
|
|
2504
|
-
throw loginFailed(origin, "The code expired before anyone approved it.");
|
|
2505
|
-
}
|
|
2506
|
-
const loginUsage = "vitehub login [--console <url>] [--json]";
|
|
2507
|
-
const loginCommand = {
|
|
2508
|
-
description: `Sign in to a ViteHub Console with the device flow, and save an API key for this machine. The default Console is ${defaultConsoleUrl}; --console or ${consoleUrlVariable} names another.`,
|
|
2509
|
-
name: "login",
|
|
2510
|
-
usage: loginUsage,
|
|
2511
|
-
run: async (args, context) => {
|
|
2512
|
-
const json = args.includes("--json");
|
|
2513
|
-
try {
|
|
2514
|
-
const values = readArgs(args, loginUsage, { console: true });
|
|
2515
|
-
if (values.help) {
|
|
2516
|
-
context.stdout.write(`Usage: ${loginUsage}\n\n${loginCommand.description}\n`);
|
|
2517
|
-
return setupExitCodes.done;
|
|
2518
|
-
}
|
|
2519
|
-
const origin = consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev");
|
|
2520
|
-
const answer = await deviceLogin(origin, context, json ? context.stderr : context.stdout);
|
|
2521
|
-
const file = consoleCredentialsFile(context.env);
|
|
2522
|
-
const saved = await readCredentials(file);
|
|
2523
|
-
const credential = {
|
|
2524
|
-
expiresAt: Date.now() + answer.expires_in * 1e3,
|
|
2525
|
-
keyId: answer.key_id,
|
|
2526
|
-
team: answer.team,
|
|
2527
|
-
token: answer.access_token,
|
|
2528
|
-
user: answer.user
|
|
2529
|
-
};
|
|
2530
|
-
await writeCredentials(file, {
|
|
2531
|
-
version: 1,
|
|
2532
|
-
consoles: {
|
|
2533
|
-
...saved.consoles,
|
|
2534
|
-
[origin]: credential
|
|
2535
|
-
}
|
|
2536
|
-
});
|
|
2537
|
-
const result = {
|
|
2538
|
-
console: origin,
|
|
2539
|
-
expiresAt: new Date(credential.expiresAt).toISOString(),
|
|
2540
|
-
file,
|
|
2541
|
-
team: credential.team,
|
|
2542
|
-
user: credential.user
|
|
2543
|
-
};
|
|
2544
|
-
if (json) writeSetupJson(context, result);
|
|
2545
|
-
else context.stdout.write(`Signed in to ${origin} as ${credential.user.name}${credential.user.email ? ` (${credential.user.email})` : ""} in team ${credential.team.name}.\nThe API key expires on ${dateFormat.format(new Date(credential.expiresAt))}. Saved in ${file}.\n`);
|
|
2546
|
-
if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is set, so commands use it instead of this key.\n`);
|
|
2547
|
-
return setupExitCodes.done;
|
|
2548
|
-
} catch (error) {
|
|
2549
|
-
return writeSetupError(context, json, error);
|
|
2550
|
-
}
|
|
2551
|
-
}
|
|
2552
|
-
};
|
|
2553
|
-
const whoamiUsage = "vitehub whoami [--console <url>] [--json]";
|
|
2554
|
-
const whoamiCommand = {
|
|
2555
|
-
description: `Show the person and the team of the Console API key: ${consoleTokenVariable}, else the key of \`vitehub login\`.`,
|
|
2556
|
-
name: "whoami",
|
|
2557
|
-
usage: whoamiUsage,
|
|
2558
|
-
run: async (args, context) => {
|
|
2559
|
-
const json = args.includes("--json");
|
|
2560
|
-
try {
|
|
2561
|
-
const values = readArgs(args, whoamiUsage, { console: true });
|
|
2562
|
-
if (values.help) {
|
|
2563
|
-
context.stdout.write(`Usage: ${whoamiUsage}\n\n${whoamiCommand.description}\n`);
|
|
2564
|
-
return setupExitCodes.done;
|
|
2565
|
-
}
|
|
2566
|
-
const credential = await readConsoleCredential(context.env, values.console);
|
|
2567
|
-
if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
|
|
2568
|
-
const response = await (context.fetch ?? fetch)(`${credential.origin}/api/whoami`, { headers: {
|
|
2569
|
-
accept: "application/json",
|
|
2570
|
-
authorization: `Bearer ${credential.token}`
|
|
2571
|
-
} });
|
|
2572
|
-
if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
|
|
2573
|
-
if (!response.ok) throw cliErrorDiagnostics.CLI_R0001({ message: `[vitehub] ${credential.origin} answered ${response.status} to /api/whoami.` });
|
|
2574
|
-
const me = await response.json();
|
|
2575
|
-
const source = credential.source === "env" ? consoleTokenVariable : consoleCredentialsFile(context.env);
|
|
2576
|
-
if (json) writeSetupJson(context, {
|
|
2577
|
-
console: credential.origin,
|
|
2578
|
-
expiresAt: new Date(me.key.expiresAt).toISOString(),
|
|
2579
|
-
projectIds: me.projectIds,
|
|
2580
|
-
roles: me.roles,
|
|
2581
|
-
source,
|
|
2582
|
-
team: me.team,
|
|
2583
|
-
user: me.user
|
|
2584
|
-
});
|
|
2585
|
-
else {
|
|
2586
|
-
context.stdout.write(`${me.user.name}${me.user.email ? ` (${me.user.email})` : ""} in team ${me.team.name} (${me.roles.join(", ")}) on ${credential.origin}\n`);
|
|
2587
|
-
context.stdout.write(`Key from ${source}, for ${me.projectIds ? `${me.projectIds.length} project${me.projectIds.length === 1 ? "" : "s"}` : "every project of the team"}, expires on ${dateFormat.format(new Date(me.key.expiresAt))}.\n`);
|
|
2588
|
-
}
|
|
2589
|
-
return setupExitCodes.done;
|
|
2590
|
-
} catch (error) {
|
|
2591
|
-
return writeSetupError(context, json, error);
|
|
2592
|
-
}
|
|
2593
|
-
}
|
|
2594
|
-
};
|
|
2595
|
-
const logoutUsage = "vitehub logout [--console <url>] [--json]";
|
|
2596
|
-
const logoutCommand = {
|
|
2597
|
-
description: "Revoke the API key of `vitehub login` on the Console and remove it from this machine.",
|
|
2598
|
-
name: "logout",
|
|
2599
|
-
usage: logoutUsage,
|
|
2600
|
-
run: async (args, context) => {
|
|
2601
|
-
const json = args.includes("--json");
|
|
2602
|
-
try {
|
|
2603
|
-
const values = readArgs(args, logoutUsage, { console: true });
|
|
2604
|
-
if (values.help) {
|
|
2605
|
-
context.stdout.write(`Usage: ${logoutUsage}\n\n${logoutCommand.description}\n`);
|
|
2606
|
-
return setupExitCodes.done;
|
|
2607
|
-
}
|
|
2608
|
-
const file = consoleCredentialsFile(context.env);
|
|
2609
|
-
const saved = await readCredentials(file);
|
|
2610
|
-
const credential = await readConsoleCredential({
|
|
2611
|
-
...context.env,
|
|
2612
|
-
[consoleTokenVariable]: void 0
|
|
2613
|
-
}, values.console);
|
|
2614
|
-
if (!credential) {
|
|
2615
|
-
if (json) writeSetupJson(context, { removed: false });
|
|
2616
|
-
else context.stdout.write("Not signed in.\n");
|
|
2617
|
-
return setupExitCodes.done;
|
|
2618
|
-
}
|
|
2619
|
-
const response = await (context.fetch ?? fetch)(`${credential.origin}/api/api-keys/current`, {
|
|
2620
|
-
headers: { authorization: `Bearer ${credential.token}` },
|
|
2621
|
-
method: "DELETE"
|
|
2622
|
-
}).catch(() => void 0);
|
|
2623
|
-
const revoked = response !== void 0 && (response.status === 204 || response.status === 401 || response.status === 404);
|
|
2624
|
-
const { [credential.origin]: _removed, ...consoles } = saved.consoles;
|
|
2625
|
-
await writeCredentials(file, {
|
|
2626
|
-
version: 1,
|
|
2627
|
-
consoles
|
|
2628
|
-
});
|
|
2629
|
-
if (json) writeSetupJson(context, {
|
|
2630
|
-
console: credential.origin,
|
|
2631
|
-
removed: true,
|
|
2632
|
-
revoked
|
|
2633
|
-
});
|
|
2634
|
-
else {
|
|
2635
|
-
context.stdout.write(`Signed out of ${credential.origin}.\n`);
|
|
2636
|
-
if (!revoked) context.stderr.write("[vitehub] The Console did not revoke the key. Revoke it in Account settings, under API keys.\n");
|
|
2637
|
-
}
|
|
2638
|
-
if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is still set. Unset it to sign out completely.\n`);
|
|
2639
|
-
return setupExitCodes.done;
|
|
2640
|
-
} catch (error) {
|
|
2641
|
-
return writeSetupError(context, json, error);
|
|
2642
|
-
}
|
|
2643
|
-
}
|
|
2644
|
-
};
|
|
2645
|
-
// ../internal/dist/definition-catalog.js
|
|
2646
|
-
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
2647
|
-
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
2648
|
-
const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
|
|
2649
|
-
const ignoredDirs = /* @__PURE__ */ new Set([
|
|
2650
|
-
"node_modules",
|
|
2651
|
-
"dist",
|
|
2652
|
-
".output",
|
|
2653
|
-
".nuxt",
|
|
2654
|
-
".vercel",
|
|
2655
|
-
".git",
|
|
2656
|
-
".vitehub"
|
|
2657
|
-
]);
|
|
2658
|
-
function readDirEntries(root) {
|
|
2659
|
-
try {
|
|
2660
|
-
return readdirSync(root, { withFileTypes: true });
|
|
2661
|
-
} catch (error) {
|
|
2662
|
-
if (error.code === "ENOENT") return [];
|
|
2663
|
-
throw error;
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
function isGitRepositoryDirectory(directory) {
|
|
2667
|
-
return existsSync(resolve(directory, ".git"));
|
|
2668
|
-
}
|
|
2669
|
-
function listMatchingFiles(root, predicate, options = {}) {
|
|
2670
|
-
const files = [];
|
|
2671
|
-
for (const entry of readDirEntries(root)) {
|
|
2672
|
-
const absolute = resolve(root, entry.name);
|
|
2673
|
-
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
2674
|
-
if (isGitRepositoryDirectory(absolute)) continue;
|
|
2675
|
-
if (entry.name.startsWith(".")) continue;
|
|
2676
|
-
if (ignoredDirs.has(entry.name)) continue;
|
|
2677
|
-
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
2678
|
-
continue;
|
|
2679
|
-
}
|
|
2680
|
-
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
2681
|
-
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
2682
|
-
}
|
|
2683
|
-
return files.sort();
|
|
2684
|
-
}
|
|
2685
|
-
/** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
|
|
2686
|
-
function isDefinitionSourceFile(name) {
|
|
2687
|
-
return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
|
|
2688
|
-
}
|
|
2689
|
-
function listSourceFiles(root, options = {}) {
|
|
2690
|
-
return listMatchingFiles(root, isDefinitionSourceFile, options);
|
|
2691
|
-
}
|
|
2692
|
-
/**
|
|
2693
|
-
* Whether `path` is a file, or a folder that holds a Definition source file. A Definition file in a server directory,
|
|
2694
|
-
* such as `server/auth.ts` or a file in `server/queues/`, turns its feature on without a key. An empty folder, which
|
|
2695
|
-
* Git does not keep, turns nothing on.
|
|
2696
|
-
*/
|
|
2697
|
-
function hasDefinitionFiles(path) {
|
|
2698
|
-
if (!existsSync(path)) return false;
|
|
2699
|
-
return statSync(path).isFile() || listSourceFiles(path).length > 0;
|
|
2700
|
-
}
|
|
2701
|
-
// ../internal/dist/deployment.js
|
|
2702
|
-
const unsupported = (reason) => ({
|
|
2703
|
-
reason,
|
|
2704
|
-
supported: false
|
|
2705
|
-
});
|
|
2706
|
-
const plans = {
|
|
2707
|
-
cloudflare: {
|
|
2708
|
-
host: "cloudflare",
|
|
2709
|
-
nitroPreset: "cloudflare-module",
|
|
2710
|
-
output: {
|
|
2711
|
-
directory: ".output",
|
|
2712
|
-
entry: "server/index.mjs",
|
|
2713
|
-
packaging: "none"
|
|
2714
|
-
},
|
|
2715
|
-
runtime: "workerd",
|
|
2716
|
-
services: {
|
|
2717
|
-
blob: {
|
|
2718
|
-
driver: "cloudflare",
|
|
2719
|
-
guarantee: "native",
|
|
2720
|
-
supported: true
|
|
2721
|
-
},
|
|
2722
|
-
browser: {
|
|
2723
|
-
driver: "cloudflare",
|
|
2724
|
-
guarantee: "native",
|
|
2725
|
-
supported: true
|
|
2726
|
-
},
|
|
2727
|
-
queue: {
|
|
2728
|
-
driver: "cloudflare",
|
|
2729
|
-
guarantee: "native",
|
|
2730
|
-
supported: true
|
|
2731
|
-
},
|
|
2732
|
-
rateLimit: {
|
|
2733
|
-
driver: "cloudflare",
|
|
2734
|
-
guarantee: "native",
|
|
2735
|
-
supported: true
|
|
2736
|
-
},
|
|
2737
|
-
realtime: {
|
|
2738
|
-
driver: "cloudflare",
|
|
2739
|
-
guarantee: "native",
|
|
2740
|
-
supported: true
|
|
2741
|
-
},
|
|
2742
|
-
sandbox: {
|
|
2743
|
-
driver: "cloudflare",
|
|
2744
|
-
guarantee: "native",
|
|
2745
|
-
supported: true
|
|
2746
|
-
}
|
|
2747
|
-
}
|
|
2748
|
-
},
|
|
2749
|
-
deno: {
|
|
2750
|
-
host: "deno",
|
|
2751
|
-
nitroPreset: "deno-deploy",
|
|
2752
|
-
output: {
|
|
2753
|
-
directory: ".output",
|
|
2754
|
-
entry: "server/index.mjs",
|
|
2755
|
-
packaging: "deno-node-modules"
|
|
2756
|
-
},
|
|
2757
|
-
runtime: "deno",
|
|
2758
|
-
services: {
|
|
2759
|
-
blob: unsupported("Deno Deploy has no built-in durable Blob Store with ViteHub's object-storage contract."),
|
|
2760
|
-
browser: unsupported("Deno Deploy has no built-in Browser Provider."),
|
|
2761
|
-
queue: unsupported("Deno Deploy has no built-in Queue Provider with ViteHub's delivery contract."),
|
|
2762
|
-
rateLimit: unsupported("Deno Deploy has no built-in distributed Rate Limit driver."),
|
|
2763
|
-
realtime: unsupported("Deno Deploy has no shared room authority for Realtime."),
|
|
2764
|
-
sandbox: unsupported("Deno Deploy has no built-in isolated Sandbox Provider.")
|
|
2765
|
-
}
|
|
2766
|
-
},
|
|
2767
|
-
netlify: {
|
|
2768
|
-
host: "netlify",
|
|
2769
|
-
nitroPreset: "netlify",
|
|
2770
|
-
output: {
|
|
2771
|
-
directory: ".netlify",
|
|
2772
|
-
entry: "v1/functions/server/server.mjs",
|
|
2773
|
-
packaging: "none"
|
|
2774
|
-
},
|
|
2775
|
-
runtime: "node",
|
|
2776
|
-
services: {
|
|
2777
|
-
blob: {
|
|
2778
|
-
driver: "netlify-blobs",
|
|
2779
|
-
guarantee: "native",
|
|
2780
|
-
supported: true
|
|
2781
|
-
},
|
|
2782
|
-
browser: unsupported("Netlify has no built-in Browser Provider."),
|
|
2783
|
-
queue: unsupported("Netlify has no built-in Queue Provider with ViteHub's delivery contract."),
|
|
2784
|
-
rateLimit: unsupported("Netlify has no built-in distributed Rate Limit driver."),
|
|
2785
|
-
realtime: unsupported("Netlify has no shared room authority for Realtime."),
|
|
2786
|
-
sandbox: unsupported("Netlify has no built-in isolated Sandbox Provider.")
|
|
2787
|
-
}
|
|
2788
|
-
},
|
|
2789
|
-
node: {
|
|
2790
|
-
host: "node",
|
|
2791
|
-
nitroPreset: "node-server",
|
|
2792
|
-
output: {
|
|
2793
|
-
directory: ".output",
|
|
2794
|
-
entry: "server/index.mjs",
|
|
2795
|
-
packaging: "none"
|
|
2796
|
-
},
|
|
2797
|
-
runtime: "node",
|
|
2798
|
-
services: {
|
|
2799
|
-
blob: {
|
|
2800
|
-
driver: "fs",
|
|
2801
|
-
guarantee: "single-host",
|
|
2802
|
-
supported: true
|
|
2803
|
-
},
|
|
2804
|
-
browser: unsupported("The Node host has no built-in Browser Provider."),
|
|
2805
|
-
queue: {
|
|
2806
|
-
driver: "local",
|
|
2807
|
-
guarantee: "single-host",
|
|
2808
|
-
supported: true
|
|
2809
|
-
},
|
|
2810
|
-
rateLimit: {
|
|
2811
|
-
driver: "memory",
|
|
2812
|
-
guarantee: "process-local",
|
|
2813
|
-
supported: true
|
|
2814
|
-
},
|
|
2815
|
-
realtime: {
|
|
2816
|
-
driver: "node",
|
|
2817
|
-
guarantee: "native",
|
|
2818
|
-
supported: true
|
|
2819
|
-
},
|
|
2820
|
-
sandbox: unsupported("The Node host has no built-in isolated Sandbox Provider.")
|
|
2821
|
-
}
|
|
2822
|
-
},
|
|
2823
|
-
vercel: {
|
|
2824
|
-
host: "vercel",
|
|
2825
|
-
nitroPreset: "vercel",
|
|
2826
|
-
output: {
|
|
2827
|
-
directory: ".vercel/output",
|
|
2828
|
-
entry: "functions/__server.func/index.mjs",
|
|
2829
|
-
packaging: "none"
|
|
2830
|
-
},
|
|
2831
|
-
runtime: "node",
|
|
2832
|
-
services: {
|
|
2833
|
-
blob: {
|
|
2834
|
-
driver: "vercel",
|
|
2835
|
-
guarantee: "native",
|
|
2836
|
-
supported: true
|
|
2837
|
-
},
|
|
2838
|
-
browser: unsupported("Vercel has no built-in Browser Provider."),
|
|
2839
|
-
queue: {
|
|
2840
|
-
driver: "vercel",
|
|
2841
|
-
guarantee: "native",
|
|
2842
|
-
supported: true
|
|
2843
|
-
},
|
|
2844
|
-
rateLimit: unsupported("Vercel has no built-in distributed Rate Limit driver."),
|
|
2845
|
-
realtime: unsupported("Vercel has no shared room authority for Realtime."),
|
|
2846
|
-
sandbox: {
|
|
2847
|
-
driver: "vercel",
|
|
2848
|
-
guarantee: "native",
|
|
2849
|
-
supported: true
|
|
2850
|
-
}
|
|
2851
|
-
}
|
|
2852
|
-
}
|
|
2853
|
-
};
|
|
2854
|
-
function resolveDeploymentPlan(host) {
|
|
2855
|
-
const plan = plans[host];
|
|
2856
|
-
if (!plan) throw internalErrorDiagnostics.INTERNAL_R0001({ message: `Unknown ViteHub host: ${JSON.stringify(host)}.` });
|
|
2857
|
-
return plan;
|
|
2858
|
-
}
|
|
2859
|
-
/** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
|
|
2860
|
-
function hostFromNitroPreset(value) {
|
|
2861
|
-
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
2862
|
-
if (!normalized) return;
|
|
2863
|
-
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
2864
|
-
if (normalized.startsWith("deno")) return "deno";
|
|
2865
|
-
if (normalized.startsWith("netlify")) return "netlify";
|
|
2866
|
-
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
2867
|
-
if (normalized.startsWith("vercel")) return "vercel";
|
|
2868
|
-
}
|
|
2869
|
-
const providerHosts = [
|
|
2870
|
-
["WORKERS_CI", "cloudflare"],
|
|
2871
|
-
["NETLIFY", "netlify"],
|
|
2872
|
-
["NOW_BUILDER", "vercel"],
|
|
2873
|
-
["VERCEL", "vercel"],
|
|
2874
|
-
["VERCEL_ENV", "vercel"],
|
|
2875
|
-
["DENO_DEPLOY", "deno"],
|
|
2876
|
-
["DENO_DEPLOYMENT_ID", "deno"]
|
|
2877
|
-
];
|
|
2878
|
-
/**
|
|
2879
|
-
* Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
|
|
2880
|
-
* The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
|
|
2881
|
-
* `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
|
|
2882
|
-
* `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
|
|
2883
|
-
*/
|
|
2884
|
-
function detectHost(env = process.env) {
|
|
2885
|
-
for (const name of [
|
|
2886
|
-
"VITEHUB_HOST",
|
|
2887
|
-
"NITRO_PRESET",
|
|
2888
|
-
"SERVER_PRESET"
|
|
2889
|
-
]) {
|
|
2890
|
-
const host = hostFromNitroPreset(env[name]);
|
|
2891
|
-
if (host) return host;
|
|
2892
|
-
}
|
|
2893
|
-
return providerHosts.find(([name]) => env[name]?.trim())?.[1];
|
|
2894
|
-
}
|
|
2895
|
-
// src/setup/status.ts
|
|
2896
|
-
const addArgs = {
|
|
2897
|
-
bun: {
|
|
2898
|
-
dev: ["add", "-d"],
|
|
2899
|
-
prod: ["add"]
|
|
2900
|
-
},
|
|
2901
|
-
npm: {
|
|
2902
|
-
dev: ["install", "-D"],
|
|
2903
|
-
prod: ["install"]
|
|
2904
|
-
},
|
|
2905
|
-
pnpm: {
|
|
2906
|
-
dev: ["add", "-D"],
|
|
2907
|
-
prod: ["add"]
|
|
2908
|
-
},
|
|
2909
|
-
yarn: {
|
|
2910
|
-
dev: ["add", "-D"],
|
|
2911
|
-
prod: ["add"]
|
|
2912
|
-
}
|
|
2913
|
-
};
|
|
2914
|
-
/** Quotes `value` for a POSIX shell when it needs quotes. */
|
|
2915
|
-
function shellQuote(value) {
|
|
2916
|
-
return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
2917
|
-
}
|
|
2918
|
-
/** The arguments of the `packageManager` command that installs `packages`, such as `["add", "-D", "drizzle-kit"]`. */
|
|
2919
|
-
function installArgs(packageManager, packages, dev) {
|
|
2920
|
-
return [...addArgs[packageManager][dev ? "dev" : "prod"], ...packages];
|
|
2921
|
-
}
|
|
2922
|
-
const removeArgs = {
|
|
2923
|
-
bun: ["remove"],
|
|
2924
|
-
npm: ["uninstall"],
|
|
2925
|
-
pnpm: ["remove"],
|
|
2926
|
-
yarn: ["remove"]
|
|
2927
|
-
};
|
|
2928
|
-
/** The arguments of the `packageManager` command that uninstalls `packages`, such as `["remove", "@vite-hub/queue"]`. */
|
|
2929
|
-
function uninstallArgs(packageManager, packages) {
|
|
2930
|
-
return [...removeArgs[packageManager], ...packages];
|
|
2931
|
-
}
|
|
2932
|
-
function formatInstallCommand(command, args) {
|
|
2933
|
-
return [command, ...args].map(formatInstallArgument).join(" ");
|
|
2934
|
-
}
|
|
2935
|
-
function installCommand(packageManager, prod, dev) {
|
|
2936
|
-
const commands = [...prod.length ? [formatInstallCommand(packageManager, installArgs(packageManager, prod, false))] : [], ...dev.length ? [formatInstallCommand(packageManager, installArgs(packageManager, dev, true))] : []];
|
|
2937
|
-
return commands.length ? commands.join(" && ") : void 0;
|
|
2938
|
-
}
|
|
2939
|
-
function readHost(project, env) {
|
|
2940
|
-
const config = project.config;
|
|
2941
|
-
if (config && !config.ok && config.reason !== "no-vitehub") return {
|
|
2942
|
-
name: "unknown",
|
|
2943
|
-
source: "config"
|
|
2944
|
-
};
|
|
2945
|
-
const site = config?.ok ? config.site : void 0;
|
|
2946
|
-
const host = site?.keys.host;
|
|
2947
|
-
const fromConfig = host?.kind === "literal" && typeof host.value === "string" ? hostFromNitroPreset(host.value) : void 0;
|
|
2948
|
-
if (fromConfig) return {
|
|
2949
|
-
name: fromConfig,
|
|
2950
|
-
source: "config"
|
|
2951
|
-
};
|
|
2952
|
-
if (host || site?.spread) return {
|
|
2953
|
-
name: "unknown",
|
|
2954
|
-
source: "config"
|
|
2955
|
-
};
|
|
2956
|
-
const fromEnv = detectHost(env);
|
|
2957
|
-
return fromEnv ? {
|
|
2958
|
-
name: fromEnv,
|
|
2959
|
-
source: "env"
|
|
2960
|
-
} : {
|
|
2961
|
-
name: "node",
|
|
2962
|
-
source: "default"
|
|
2963
|
-
};
|
|
2964
|
-
}
|
|
2965
|
-
function readEnabled(project, id, withoutDefinitions) {
|
|
2966
|
-
const config = project.config;
|
|
2967
|
-
if (!config || !config.ok && config.reason === "no-vitehub") return {
|
|
2968
|
-
enabled: "off",
|
|
2969
|
-
reason: "default"
|
|
2970
|
-
};
|
|
2971
|
-
if (!config.ok) return {
|
|
2972
|
-
enabled: "unknown",
|
|
2973
|
-
reason: "config"
|
|
2974
|
-
};
|
|
2975
|
-
const value = config.site.keys[id];
|
|
2976
|
-
if (value?.kind === "expression") return {
|
|
2977
|
-
enabled: "unknown",
|
|
2978
|
-
reason: "config"
|
|
2979
|
-
};
|
|
2980
|
-
if (value) return {
|
|
2981
|
-
enabled: value.value === false ? "off" : "on",
|
|
2982
|
-
reason: "config"
|
|
2983
|
-
};
|
|
2984
|
-
if (config.site.spread) return {
|
|
2985
|
-
enabled: "unknown",
|
|
2986
|
-
reason: "config"
|
|
2987
|
-
};
|
|
2988
|
-
if (features[id].enabledByDefault) return {
|
|
2989
|
-
enabled: "on",
|
|
2990
|
-
reason: "default"
|
|
2991
|
-
};
|
|
2992
|
-
if (withoutDefinitions?.has(id)) return {
|
|
2993
|
-
enabled: "off",
|
|
2994
|
-
reason: "default"
|
|
2995
|
-
};
|
|
2996
|
-
const discovery = features[id].enabledByDiscovery;
|
|
2997
|
-
const directories = project.serverDirs ?? (project.framework === "nuxt" ? void 0 : [join(project.root, "server")]);
|
|
2998
|
-
if (discovery && !directories) return {
|
|
2999
|
-
enabled: "unknown",
|
|
3000
|
-
reason: "default"
|
|
3001
|
-
};
|
|
3002
|
-
return {
|
|
3003
|
-
enabled: discovery?.some((file) => directories?.some((directory) => hasDefinitionFiles(join(directory, file)))) ? "on" : "off",
|
|
3004
|
-
reason: "default"
|
|
3005
|
-
};
|
|
3006
|
-
}
|
|
3007
|
-
const kvDefaultStoreOption = "kv.stores.default.driver";
|
|
3008
|
-
function kvStores(value) {
|
|
3009
|
-
return isRecord(value) && isRecord(value.stores) ? value.stores : void 0;
|
|
3010
|
-
}
|
|
3011
|
-
function missingProviderOption(project, option, value) {
|
|
3012
|
-
const [id, key] = option.split(".");
|
|
3013
|
-
const configured = project.config?.ok ? project.config.site.keys[id] : void 0;
|
|
3014
|
-
if (configured?.kind === "expression") return;
|
|
3015
|
-
const options = value ?? configured?.value;
|
|
3016
|
-
const stores = option === "kv.driver" ? kvStores(options) : void 0;
|
|
3017
|
-
if (stores) {
|
|
3018
|
-
const store = stores.default;
|
|
3019
|
-
const driver = isRecord(store) ? store.driver : void 0;
|
|
3020
|
-
if (driver !== "upstash" && driver !== "redis" && driver !== "database") return kvDefaultStoreOption;
|
|
3021
|
-
return;
|
|
3022
|
-
}
|
|
3023
|
-
if (!isRecord(options) || !(key in options)) return option;
|
|
3024
|
-
}
|
|
3025
|
-
function featureFix(project, id, support, host, missing, providerChosen) {
|
|
3026
|
-
const install = installCommand(project.packageManager, missing.prod.map(installSpecifier), missing.dev.map(installSpecifier));
|
|
3027
|
-
if (install) return install;
|
|
3028
|
-
if (support.level === "unsupported") return `Set \`${id}: false\`, or build for another host than ${host}.`;
|
|
3029
|
-
if (support.level === "explicit" && !providerChosen) {
|
|
3030
|
-
const option = missingProviderOption(project, support.option);
|
|
3031
|
-
if (option) return `Set \`${option}\` in vitehub() to choose a provider on ${host}.`;
|
|
3032
|
-
}
|
|
3033
|
-
}
|
|
3034
|
-
/** What the project enables, on which host, and what each enabled feature still needs. Reads the config without running it. */
|
|
3035
|
-
function setupStatus(project, env, withoutDefinitions) {
|
|
3036
|
-
const host = readHost(project, env);
|
|
3037
|
-
const enabled = new Map(featureIds.map((id) => [id, readEnabled(project, id, withoutDefinitions)]));
|
|
3038
|
-
const on = featureIds.filter((id) => enabled.get(id).enabled === "on");
|
|
3039
|
-
const keep = featureIds.filter((id) => enabled.get(id).enabled !== "on" && enabled.get(id).reason === "config");
|
|
3040
|
-
const maybeOn = featureIds.filter((id) => enabled.get(id).enabled !== "off");
|
|
3041
|
-
const disabled = keep.filter((id) => enabled.get(id).enabled === "off");
|
|
3042
|
-
const definite = impliedFeatures(on, keep);
|
|
3043
|
-
for (const id of impliedFeatures(maybeOn, disabled)) {
|
|
3044
|
-
const state = enabled.get(id);
|
|
3045
|
-
if (state.enabled === "off" && state.reason === "default") enabled.set(id, {
|
|
3046
|
-
enabled: definite.includes(id) ? "on" : "unknown",
|
|
3047
|
-
reason: "implied"
|
|
3048
|
-
});
|
|
3049
|
-
}
|
|
3050
|
-
return {
|
|
3051
|
-
config: !project.config ? { manual: "no-vitehub" } : project.config.ok ? {
|
|
3052
|
-
file: project.configFile,
|
|
3053
|
-
form: project.config.site.form
|
|
3054
|
-
} : {
|
|
3055
|
-
file: project.configFile,
|
|
3056
|
-
manual: project.config.reason,
|
|
3057
|
-
...project.config.line === void 0 ? {} : { line: project.config.line }
|
|
3058
|
-
},
|
|
3059
|
-
features: featureIds.map((id) => {
|
|
3060
|
-
const state = enabled.get(id);
|
|
3061
|
-
const support = host.name === "unknown" ? {
|
|
3062
|
-
level: "unknown",
|
|
3063
|
-
detail: "The config does not statically identify the deployment host."
|
|
3064
|
-
} : featureSupport(id, host.name);
|
|
3065
|
-
const definition = features[id];
|
|
3066
|
-
const value = project.config?.ok ? project.config.site.keys[id] : void 0;
|
|
3067
|
-
const literal = value?.kind === "literal" ? value.value : void 0;
|
|
3068
|
-
const packages = featurePackages(id, literal, host.name, featureIds.filter((feature) => enabled.get(feature)?.enabled === "on"));
|
|
3069
|
-
const missing = state.enabled === "on" ? {
|
|
3070
|
-
dev: definition.devPackages.filter((name) => !project.installed(name)),
|
|
3071
|
-
prod: packages.filter((name) => !project.installed(name))
|
|
3072
|
-
} : {
|
|
3073
|
-
dev: [],
|
|
3074
|
-
prod: []
|
|
3075
|
-
};
|
|
3076
|
-
const providerChosen = id === "workflow" && host.name !== "netlify" && packages.includes("openworkflow");
|
|
3077
|
-
const fix = state.enabled === "on" ? featureFix(project, id, support, host.name, missing, providerChosen) : void 0;
|
|
3078
|
-
const resolvedSupport = support.level === "explicit" && support.option === "kv.driver" && kvStores(literal) ? {
|
|
3079
|
-
...support,
|
|
3080
|
-
option: kvDefaultStoreOption
|
|
3081
|
-
} : support;
|
|
3082
|
-
return {
|
|
3083
|
-
id,
|
|
3084
|
-
...state,
|
|
3085
|
-
missingPackages: [...missing.prod, ...missing.dev],
|
|
3086
|
-
support: resolvedSupport,
|
|
3087
|
-
...fix ? { fix } : {}
|
|
3088
|
-
};
|
|
3089
|
-
}),
|
|
3090
|
-
framework: project.framework,
|
|
3091
|
-
host,
|
|
3092
|
-
packageManager: project.packageManager,
|
|
3093
|
-
root: project.root,
|
|
3094
|
-
schemaVersion: 1
|
|
3095
|
-
};
|
|
3096
|
-
}
|
|
3097
|
-
// src/setup/console-apps.ts
|
|
3098
|
-
/** The Console of `--console`, else `VITEHUB_CONSOLE_URL`, else the only saved Console, else console.vitehub.dev. */
|
|
3099
|
-
async function openConsole(context, console) {
|
|
3100
|
-
const credential = await readConsoleCredential(context.env, console);
|
|
3101
|
-
if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
|
|
3102
|
-
return consoleClient(context, credential);
|
|
3103
|
-
}
|
|
3104
|
-
function consoleClient(context, credential, signal) {
|
|
3105
|
-
return {
|
|
3106
|
-
origin: credential.origin,
|
|
3107
|
-
async request(path, init = {}) {
|
|
3108
|
-
const response = await (context.fetch ?? fetch)(`${credential.origin}${path}`, {
|
|
3109
|
-
...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
|
|
3110
|
-
headers: {
|
|
3111
|
-
accept: "application/json",
|
|
3112
|
-
authorization: `Bearer ${credential.token}`,
|
|
3113
|
-
...init.body === void 0 ? {} : { "content-type": "application/json" }
|
|
3114
|
-
},
|
|
3115
|
-
method: init.method ?? "GET",
|
|
3116
|
-
...signal ? {
|
|
3117
|
-
redirect: "error",
|
|
3118
|
-
signal
|
|
3119
|
-
} : {}
|
|
3120
|
-
}).catch((error) => {
|
|
3121
|
-
throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
|
|
3122
|
-
code: "FETCH_FAILED",
|
|
3123
|
-
console: credential.origin,
|
|
3124
|
-
message: `The Console did not answer ${path}: ${error instanceof Error ? error.message : String(error)}`
|
|
3125
|
-
});
|
|
3126
|
-
});
|
|
3127
|
-
if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
|
|
3128
|
-
const body = response.status === 204 ? {} : await response.json().catch(() => ({}));
|
|
3129
|
-
const record = body instanceof Object ? body : {};
|
|
3130
|
-
if (!response.ok) throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
|
|
3131
|
-
code: typeof record.code === "string" ? record.code : String(response.status),
|
|
3132
|
-
console: credential.origin,
|
|
3133
|
-
...typeof record.fix === "string" ? { fix: record.fix } : {},
|
|
3134
|
-
message: typeof record.message === "string" ? record.message : `${credential.origin} answered ${response.status} to ${path}.`
|
|
3135
|
-
});
|
|
3136
|
-
return {
|
|
3137
|
-
body: record,
|
|
3138
|
-
status: response.status
|
|
3139
|
-
};
|
|
3140
|
-
}
|
|
3141
|
-
};
|
|
3142
|
-
}
|
|
3143
|
-
/** The apps of the team of the key. */
|
|
3144
|
-
async function listConsoleApps(client) {
|
|
3145
|
-
const { body } = await client.request("/api/projects");
|
|
3146
|
-
return Array.isArray(body.projects) ? body.projects : [];
|
|
3147
|
-
}
|
|
3148
|
-
/** Link an app, or register a site with `kind: "site"`. Linking a URL again returns the same link with `created: false`. */
|
|
3149
|
-
async function linkConsoleApp(client, input) {
|
|
3150
|
-
const { body, status } = await client.request("/api/projects", {
|
|
3151
|
-
body: input,
|
|
3152
|
-
method: "POST"
|
|
3153
|
-
});
|
|
3154
|
-
return {
|
|
3155
|
-
app: body.project,
|
|
3156
|
-
created: status === 201
|
|
3157
|
-
};
|
|
3158
|
-
}
|
|
3159
|
-
async function checkConsoleApp(client, id) {
|
|
3160
|
-
const { body } = await client.request(`/api/projects/${encodeURIComponent(id)}/check`, {
|
|
3161
|
-
body: {},
|
|
3162
|
-
method: "POST"
|
|
3163
|
-
});
|
|
3164
|
-
return {
|
|
3165
|
-
answer: body.answer,
|
|
3166
|
-
linked: body.linked === true,
|
|
3167
|
-
status: typeof body.status === "number" ? body.status : 0
|
|
3168
|
-
};
|
|
3169
|
-
}
|
|
3170
|
-
/** The Console page of an app. */
|
|
3171
|
-
function consoleAppUrl(origin, app) {
|
|
3172
|
-
return `${origin}/open?project=${encodeURIComponent(app.url)}`;
|
|
3173
|
-
}
|
|
3174
|
-
/** The text of a check that did not link, such as `401 CONSOLE_KEY_UNKNOWN: ...`. */
|
|
3175
|
-
function checkProblem(check) {
|
|
3176
|
-
const answer = Object(check.answer);
|
|
3177
|
-
const code = Reflect.get(answer, "code");
|
|
3178
|
-
const message = Reflect.get(answer, "message");
|
|
3179
|
-
return [check.status ? String(check.status) : "", typeof code === "string" ? code : ""].filter(Boolean).join(" ") + (typeof message === "string" ? `: ${message}` : "");
|
|
3180
|
-
}
|
|
3181
|
-
const usage = {
|
|
3182
|
-
check: "vitehub apps check <id> [--console <url>] [--json]",
|
|
3183
|
-
link: "vitehub apps link <url> [--label <name>] [--kind site] [--console <url>] [--json]",
|
|
3184
|
-
list: "vitehub apps list [--console <url>] [--json]",
|
|
3185
|
-
unlink: "vitehub apps unlink <id> --delete-hosted-comments [--console <url>] [--json]"
|
|
3186
|
-
};
|
|
3187
|
-
function readAppsArgs(command, args) {
|
|
3188
|
-
let parsed;
|
|
3189
|
-
try {
|
|
3190
|
-
parsed = parseArgs({
|
|
3191
|
-
allowPositionals: true,
|
|
3192
|
-
args,
|
|
3193
|
-
options: {
|
|
3194
|
-
"console": { type: "string" },
|
|
3195
|
-
"help": {
|
|
3196
|
-
default: false,
|
|
3197
|
-
short: "h",
|
|
3198
|
-
type: "boolean"
|
|
3199
|
-
},
|
|
3200
|
-
"json": {
|
|
3201
|
-
default: false,
|
|
3202
|
-
type: "boolean"
|
|
3203
|
-
},
|
|
3204
|
-
...command === "link" ? {
|
|
3205
|
-
kind: { type: "string" },
|
|
3206
|
-
label: { type: "string" }
|
|
3207
|
-
} : {},
|
|
3208
|
-
...command === "unlink" ? { "delete-hosted-comments": {
|
|
3209
|
-
default: false,
|
|
3210
|
-
type: "boolean"
|
|
3211
|
-
} } : {}
|
|
3212
|
-
},
|
|
3213
|
-
strict: true
|
|
3214
|
-
});
|
|
3215
|
-
} catch (error) {
|
|
3216
|
-
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage[command]}` });
|
|
3217
|
-
}
|
|
3218
|
-
const { positionals, values } = parsed;
|
|
3219
|
-
const expected = command === "list" ? 0 : 1;
|
|
3220
|
-
if (!values.help && positionals.length !== expected) {
|
|
3221
|
-
const message = expected ? `Pass one ${command === "link" ? "URL" : "app id"}.` : `Got ${JSON.stringify(positionals[0])}.`;
|
|
3222
|
-
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage[command]}` });
|
|
3223
|
-
}
|
|
3224
|
-
return {
|
|
3225
|
-
positionals,
|
|
3226
|
-
values: {
|
|
3227
|
-
"delete-hosted-comments": false,
|
|
3228
|
-
...values
|
|
3229
|
-
}
|
|
3230
|
-
};
|
|
3231
|
-
}
|
|
3232
|
-
function appName(app) {
|
|
3233
|
-
return app.label ? `${app.label} (${app.url})` : app.url;
|
|
3234
|
-
}
|
|
3235
|
-
async function runApps(command, args, context) {
|
|
3236
|
-
const { positionals, values } = readAppsArgs(command, args);
|
|
3237
|
-
if (values.help) {
|
|
3238
|
-
context.stdout.write(`Usage: ${usage[command]}\n\n${appsHelp[command]}\n`);
|
|
3239
|
-
return setupExitCodes.done;
|
|
3240
|
-
}
|
|
3241
|
-
const client = await openConsole(context, values.console);
|
|
3242
|
-
const write = (result, text) => {
|
|
3243
|
-
if (values.json) writeSetupJson(context, {
|
|
3244
|
-
console: client.origin,
|
|
3245
|
-
...result
|
|
3246
|
-
});
|
|
3247
|
-
else context.stdout.write(text);
|
|
3248
|
-
};
|
|
3249
|
-
if (command === "list") {
|
|
3250
|
-
const [apps, me] = await Promise.all([listConsoleApps(client), client.request("/api/whoami")]);
|
|
3251
|
-
const team = {
|
|
3252
|
-
...me.body.team,
|
|
3253
|
-
role: me.body.roles.join(",")
|
|
3254
|
-
};
|
|
3255
|
-
const rows = apps.map((app) => [
|
|
3256
|
-
app.id,
|
|
3257
|
-
app.label ?? "",
|
|
3258
|
-
app.url,
|
|
3259
|
-
app.keyVariable ? "app" : "site"
|
|
3260
|
-
]);
|
|
3261
|
-
write({
|
|
3262
|
-
apps,
|
|
3263
|
-
team
|
|
3264
|
-
}, apps.length ? `${table([[
|
|
3265
|
-
"id",
|
|
3266
|
-
"label",
|
|
3267
|
-
"url",
|
|
3268
|
-
"kind"
|
|
3269
|
-
], ...rows])}\n` : `Team ${team.name} has no apps. Run \`vitehub apps link <url>\`, or \`vitehub deploy\` in the app folder.\n`);
|
|
3270
|
-
return setupExitCodes.done;
|
|
3271
|
-
}
|
|
3272
|
-
if (command === "link") {
|
|
3273
|
-
if (values.kind !== void 0 && values.kind !== "site") throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --kind takes only "site". Usage: ${usage.link}` });
|
|
3274
|
-
const { app, created } = await linkConsoleApp(client, {
|
|
3275
|
-
url: positionals[0],
|
|
3276
|
-
...values.label ? { label: values.label } : {},
|
|
3277
|
-
...values.kind === "site" ? { kind: "site" } : {}
|
|
3278
|
-
});
|
|
3279
|
-
const verb = created ? "Linked" : "Already linked";
|
|
3280
|
-
if (app.keyVariable === null) {
|
|
3281
|
-
const script = `<script type="module" src="${client.origin}/hosted-comments.js" data-vitehub-comments="${app.id}"><\/script>`;
|
|
3282
|
-
const next = `Add the script to the HTML of ${app.url} and of the pages to review, then open ${app.url}?vitehub and choose Comments.`;
|
|
3283
|
-
write({
|
|
3284
|
-
app,
|
|
3285
|
-
script,
|
|
3286
|
-
next
|
|
3287
|
-
}, `${verb} the site ${appName(app)} as ${app.id}.\n${script}\n${next}\n`);
|
|
3288
|
-
return setupExitCodes.done;
|
|
3289
|
-
}
|
|
3290
|
-
const variable = `${app.keyVariable}=${app.publicKey}`;
|
|
3291
|
-
const check = `vitehub apps check ${shellQuote(app.id)} --console ${shellQuote(client.origin)}`;
|
|
3292
|
-
const next = `Set ${app.keyVariable} in the environment of ${app.url} and enable console: true in its vitehub config. On Node, also set publicUrl: ${JSON.stringify(new URL(app.url).origin)} in that config. Deploy it, then run \`${check}\`.`;
|
|
3293
|
-
write({
|
|
3294
|
-
app,
|
|
3295
|
-
variable,
|
|
3296
|
-
next
|
|
3297
|
-
}, `${verb} ${appName(app)} as ${app.id}.\n${variable}\n${next}\n`);
|
|
3298
|
-
return setupExitCodes.done;
|
|
3299
|
-
}
|
|
3300
|
-
const id = positionals[0];
|
|
3301
|
-
if (command === "check") {
|
|
3302
|
-
const check = await checkConsoleApp(client, id);
|
|
3303
|
-
write(check, check.linked ? `The app answers signed requests of ${client.origin}.\n` : `The app does not accept the Console yet: ${checkProblem(check)}\n`);
|
|
3304
|
-
return check.linked ? setupExitCodes.done : setupExitCodes.error;
|
|
3305
|
-
}
|
|
3306
|
-
if (!values["delete-hosted-comments"]) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unlinking permanently deletes the hosted comment threads and replies of the app. Pass --delete-hosted-comments to confirm. Usage: ${usage.unlink}` });
|
|
3307
|
-
const app = (await listConsoleApps(client)).find((item) => item.id === id);
|
|
3308
|
-
const { status } = await client.request(`/api/projects/${encodeURIComponent(id)}?deleteHostedComments=true`, { method: "DELETE" });
|
|
3309
|
-
if (status !== 204) throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
|
|
3310
|
-
code: String(status),
|
|
3311
|
-
console: client.origin,
|
|
3312
|
-
fix: "Check that the Console and its proxy return the project API response, not a sign-in page. Run `vitehub apps list` to see if the app is still linked.",
|
|
3313
|
-
message: "The Console did not confirm the unlink (expected status 204)."
|
|
3314
|
-
});
|
|
3315
|
-
const next = app?.keyVariable ? `Remove ${app.keyVariable} from the environment of ${app.url}.` : "";
|
|
3316
|
-
write({
|
|
3317
|
-
unlinked: id,
|
|
3318
|
-
next
|
|
3319
|
-
}, `Unlinked ${app ? appName(app) : id}.${next ? ` ${next}` : ""}\n`);
|
|
3320
|
-
return setupExitCodes.done;
|
|
3321
|
-
}
|
|
3322
|
-
const appsHelp = {
|
|
3323
|
-
check: "Call project.get on a linked app with a signed request from the Console. Exits with 1 if the request fails.",
|
|
3324
|
-
link: "Link a deployed ViteHub app to your team, or register a site for Hosted Comments with --kind site. Linking a URL again returns the same link and key. Only owners and admins may link.",
|
|
3325
|
-
list: "List the apps of the team of your Console key, with the id that the other commands take.",
|
|
3326
|
-
unlink: "Unlink an app. This deletes the private key of the link and the hosted comment threads of the app. Only owners and admins may unlink."
|
|
3327
|
-
};
|
|
3328
|
-
const appsUsage = "vitehub apps <list|link|check|unlink> [args...]";
|
|
3329
|
-
/** `vitehub apps`: the CLI side of the `list_apps`, `link_app`, `check_app`, and `unlink_app` tools of the Console MCP. */
|
|
3330
|
-
const appsCommand = {
|
|
3331
|
-
description: "List, link, check, and unlink the apps of your team in the ViteHub Console. Each command matches a tool of the Console MCP. Needs `vitehub login`.",
|
|
3332
|
-
name: "apps",
|
|
3333
|
-
usage: appsUsage,
|
|
3334
|
-
run: async (args, context) => {
|
|
3335
|
-
const json = args.includes("--json");
|
|
3336
|
-
try {
|
|
3337
|
-
const [command, ...rest] = args;
|
|
3338
|
-
if (command === void 0 || command === "-h" || command === "--help") {
|
|
3339
|
-
context.stdout.write(`Usage: ${appsUsage}\n\n${appsCommand.description}\n\n${Object.keys(usage).map((name) => ` ${usage[name]}\n ${appsHelp[name]}`).join("\n")}\n`);
|
|
3340
|
-
return setupExitCodes.done;
|
|
3341
|
-
}
|
|
3342
|
-
if (!Object.hasOwn(usage, command)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown command \`vitehub apps ${command}\`. Usage: ${appsUsage}` });
|
|
3343
|
-
return await runApps(command, rest, context);
|
|
3344
|
-
} catch (error) {
|
|
3345
|
-
return writeSetupError(context, json, error);
|
|
3346
|
-
}
|
|
3347
|
-
}
|
|
3348
|
-
};
|
|
3349
|
-
// ../internal/dist/host-credentials.js
|
|
3350
|
-
const missingFixes = {
|
|
3351
|
-
cloudflare: {
|
|
3352
|
-
missing: ["CLOUDFLARE_API_TOKEN"],
|
|
3353
|
-
fix: "Install Wrangler in the project and run `npx wrangler login`, or set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID."
|
|
3354
|
-
},
|
|
3355
|
-
vercel: {
|
|
3356
|
-
missing: ["VERCEL_TOKEN"],
|
|
3357
|
-
fix: "Set VERCEL_TOKEN to a token from https://vercel.com/account/tokens. Set VERCEL_TEAM_ID for a team."
|
|
3358
|
-
},
|
|
3359
|
-
netlify: {
|
|
3360
|
-
missing: ["NETLIFY_AUTH_TOKEN"],
|
|
3361
|
-
fix: "Set NETLIFY_AUTH_TOKEN to a token from https://app.netlify.com/user/applications#personal-access-tokens."
|
|
3362
|
-
},
|
|
3363
|
-
deno: {
|
|
3364
|
-
missing: ["DENO_DEPLOY_TOKEN"],
|
|
3365
|
-
fix: "Set DENO_DEPLOY_TOKEN to a token from your Deno Deploy account settings."
|
|
3366
|
-
}
|
|
3367
|
-
};
|
|
3368
|
-
const HOST_CLI_TIMEOUT_MS = 3e4;
|
|
3369
|
-
/** Reads host credentials from environment variables only. Returns undefined when the token is not set. */
|
|
3370
|
-
function readHostCredentialsFromEnv(host, env) {
|
|
3371
|
-
switch (host) {
|
|
3372
|
-
case "cloudflare": {
|
|
3373
|
-
const token = trimmed(env.CLOUDFLARE_API_TOKEN);
|
|
3374
|
-
const accountId = trimmed(env.CLOUDFLARE_ACCOUNT_ID);
|
|
3375
|
-
return token ? {
|
|
3376
|
-
token,
|
|
3377
|
-
...accountId && { accountId }
|
|
3378
|
-
} : void 0;
|
|
3379
|
-
}
|
|
3380
|
-
case "vercel": {
|
|
3381
|
-
const token = trimmed(env.VERCEL_TOKEN);
|
|
3382
|
-
const teamId = trimmed(env.VERCEL_TEAM_ID) ?? trimmed(env.VERCEL_ORG_ID);
|
|
3383
|
-
return token ? {
|
|
3384
|
-
token,
|
|
3385
|
-
...teamId && { teamId }
|
|
3386
|
-
} : void 0;
|
|
3387
|
-
}
|
|
3388
|
-
case "netlify": {
|
|
3389
|
-
const token = trimmed(env.NETLIFY_AUTH_TOKEN);
|
|
3390
|
-
return token ? { token } : void 0;
|
|
3391
|
-
}
|
|
3392
|
-
case "deno": {
|
|
3393
|
-
const token = trimmed(env.DENO_DEPLOY_TOKEN);
|
|
3394
|
-
return token ? { token } : void 0;
|
|
3395
|
-
}
|
|
3396
|
-
}
|
|
3397
|
-
}
|
|
3398
|
-
/**
|
|
3399
|
-
* Finds credentials for a host: environment variables first, then the host CLI login.
|
|
3400
|
-
* It never writes credentials and never reads another tool's auth files.
|
|
3401
|
-
*/
|
|
3402
|
-
async function resolveHostCredentials(host, context) {
|
|
3403
|
-
const fromEnv = readHostCredentialsFromEnv(host, context.env);
|
|
3404
|
-
if (fromEnv) return {
|
|
3405
|
-
ok: true,
|
|
3406
|
-
host,
|
|
3407
|
-
source: "env",
|
|
3408
|
-
...fromEnv
|
|
3409
|
-
};
|
|
3410
|
-
if (host === "cloudflare") {
|
|
3411
|
-
const token = await readWranglerToken(context);
|
|
3412
|
-
if (token) {
|
|
3413
|
-
const accountId = trimmed(context.env.CLOUDFLARE_ACCOUNT_ID) ?? await readWranglerAccountId(context);
|
|
3414
|
-
return {
|
|
3415
|
-
ok: true,
|
|
3416
|
-
host,
|
|
3417
|
-
source: "host-cli",
|
|
3418
|
-
token,
|
|
3419
|
-
...accountId && { accountId }
|
|
3420
|
-
};
|
|
3421
|
-
}
|
|
3422
|
-
}
|
|
3423
|
-
return {
|
|
3424
|
-
ok: false,
|
|
3425
|
-
host,
|
|
3426
|
-
...missingFixes[host]
|
|
3427
|
-
};
|
|
3428
|
-
}
|
|
3429
|
-
async function readWranglerToken(context) {
|
|
3430
|
-
const value = await runJson(context, "wrangler", [
|
|
3431
|
-
"auth",
|
|
3432
|
-
"token",
|
|
3433
|
-
"--json"
|
|
3434
|
-
]);
|
|
3435
|
-
if (!isRecord(value) || value.type !== "oauth" && value.type !== "api_token") return;
|
|
3436
|
-
return typeof value.token === "string" ? trimmed(value.token) : void 0;
|
|
3437
|
-
}
|
|
3438
|
-
async function readWranglerAccountId(context) {
|
|
3439
|
-
const value = await runJson(context, "wrangler", ["whoami", "--json"]);
|
|
3440
|
-
if (!isRecord(value) || value.loggedIn !== true || !Array.isArray(value.accounts) || value.accounts.length !== 1) return;
|
|
3441
|
-
const [account] = value.accounts;
|
|
3442
|
-
return isRecord(account) && typeof account.id === "string" ? trimmed(account.id) : void 0;
|
|
3443
|
-
}
|
|
3444
|
-
async function runJson(context, command, args) {
|
|
3445
|
-
const run = context.run ?? runHostCli;
|
|
3446
|
-
let result;
|
|
3447
|
-
let cwd;
|
|
3448
|
-
try {
|
|
3449
|
-
const local = command === "wrangler" ? localWrangler(context.cwd) : void 0;
|
|
3450
|
-
cwd = await mkdtemp(join$1(context.cwd ?? process.cwd(), ".vitehub-wrangler-auth-"));
|
|
3451
|
-
await writeFile(join$1(cwd, ".env"), "");
|
|
3452
|
-
await writeFile(join$1(cwd, "wrangler.json"), "{}");
|
|
3453
|
-
const isolatedArgs = [
|
|
3454
|
-
...args,
|
|
3455
|
-
"--env-file",
|
|
3456
|
-
".env",
|
|
3457
|
-
"--config",
|
|
3458
|
-
"wrangler.json"
|
|
3459
|
-
];
|
|
3460
|
-
result = await run(local ? process.execPath : command, local ? [local, ...isolatedArgs] : isolatedArgs, {
|
|
3461
|
-
cwd,
|
|
3462
|
-
env: context.env
|
|
3463
|
-
});
|
|
3464
|
-
} catch {
|
|
3465
|
-
return;
|
|
3466
|
-
} finally {
|
|
3467
|
-
if (cwd) await rm(cwd, {
|
|
3468
|
-
force: true,
|
|
3469
|
-
recursive: true
|
|
3470
|
-
});
|
|
3471
|
-
}
|
|
3472
|
-
if (result.exitCode !== 0) return;
|
|
3473
|
-
try {
|
|
3474
|
-
return JSON.parse(result.stdout);
|
|
3475
|
-
} catch {
|
|
3476
|
-
return;
|
|
3477
|
-
}
|
|
3478
|
-
}
|
|
3479
|
-
/** Resolve a project dependency before changing cwd, as package-manager invocations do. */
|
|
3480
|
-
function localWrangler(cwd) {
|
|
3481
|
-
if (!cwd) return;
|
|
3482
|
-
const require = createRequire(join$1(resolve$1(cwd), "package.json"));
|
|
3483
|
-
let directory = resolve$1(cwd);
|
|
3484
|
-
while (true) {
|
|
3485
|
-
try {
|
|
3486
|
-
const manifest = require.resolve(join$1(directory, "node_modules", "wrangler", "package.json"));
|
|
3487
|
-
const pkg = JSON.parse(readFileSync(manifest, "utf8"));
|
|
3488
|
-
if (!isRecord(pkg)) return;
|
|
3489
|
-
const bin = typeof pkg.bin === "string" ? pkg.bin : isRecord(pkg.bin) ? pkg.bin.wrangler : void 0;
|
|
3490
|
-
return typeof bin === "string" ? resolve$1(dirname$1(manifest), bin) : void 0;
|
|
3491
|
-
} catch {}
|
|
3492
|
-
const parent = dirname$1(directory);
|
|
3493
|
-
if (parent === directory) return;
|
|
3494
|
-
directory = parent;
|
|
3495
|
-
}
|
|
3496
|
-
}
|
|
3497
|
-
/** The default host CLI runner. stdin is closed so a CLI cannot wait for a prompt. */
|
|
3498
|
-
const runHostCli = (command, args, options) => new Promise((resolve, reject) => {
|
|
3499
|
-
const child = spawn(command, [...args], {
|
|
3500
|
-
cwd: options.cwd,
|
|
3501
|
-
env: options.env,
|
|
3502
|
-
shell: process.platform === "win32" && command !== process.execPath,
|
|
3503
|
-
stdio: [
|
|
3504
|
-
"ignore",
|
|
3505
|
-
"pipe",
|
|
3506
|
-
"ignore"
|
|
3507
|
-
],
|
|
3508
|
-
timeout: HOST_CLI_TIMEOUT_MS,
|
|
3509
|
-
...options.signal ? { signal: options.signal } : {}
|
|
3510
|
-
});
|
|
3511
|
-
const chunks = [];
|
|
3512
|
-
child.stdout.on("data", (chunk) => chunks.push(chunk));
|
|
3513
|
-
child.on("error", reject);
|
|
3514
|
-
child.on("close", (exitCode) => resolve({
|
|
3515
|
-
exitCode,
|
|
3516
|
-
stdout: Buffer.concat(chunks).toString("utf8")
|
|
3517
|
-
}));
|
|
3518
|
-
});
|
|
3519
|
-
function trimmed(value) {
|
|
3520
|
-
const result = value?.trim();
|
|
3521
|
-
return result ? result : void 0;
|
|
3522
|
-
}
|
|
3523
|
-
// ../internal/dist/provider-failure.js
|
|
3524
|
-
const cloudflareCodes = {
|
|
3525
|
-
d1: {},
|
|
3526
|
-
kv: { 10014: "conflict" },
|
|
3527
|
-
queues: {
|
|
3528
|
-
10104: "not-found",
|
|
3529
|
-
10106: "unauthorized",
|
|
3530
|
-
10107: "invalid",
|
|
3531
|
-
10201: "unavailable",
|
|
3532
|
-
10202: "invalid",
|
|
3533
|
-
10203: "invalid",
|
|
3534
|
-
10204: "invalid",
|
|
3535
|
-
10205: "invalid",
|
|
3536
|
-
10206: "invalid",
|
|
3537
|
-
10207: "invalid",
|
|
3538
|
-
10208: "invalid",
|
|
3539
|
-
10250: "throttled",
|
|
3540
|
-
10251: "throttled",
|
|
3541
|
-
10252: "throttled",
|
|
3542
|
-
10253: "throttled",
|
|
3543
|
-
15e3: "unavailable"
|
|
3544
|
-
},
|
|
3545
|
-
r2: {
|
|
3546
|
-
10001: "unavailable",
|
|
3547
|
-
10002: "unauthorized",
|
|
3548
|
-
10003: "unauthorized",
|
|
3549
|
-
10004: "conflict",
|
|
3550
|
-
10005: "invalid",
|
|
3551
|
-
10006: "not-found",
|
|
3552
|
-
10007: "not-found",
|
|
3553
|
-
10008: "conflict",
|
|
3554
|
-
10009: "invalid",
|
|
3555
|
-
10011: "invalid",
|
|
3556
|
-
10012: "invalid",
|
|
3557
|
-
10013: "invalid",
|
|
3558
|
-
10014: "invalid",
|
|
3559
|
-
10018: "unauthorized",
|
|
3560
|
-
10020: "invalid",
|
|
3561
|
-
10024: "not-found",
|
|
3562
|
-
10025: "invalid",
|
|
3563
|
-
10031: "conflict",
|
|
3564
|
-
10033: "invalid",
|
|
3565
|
-
10035: "unauthorized",
|
|
3566
|
-
10037: "invalid",
|
|
3567
|
-
10039: "invalid",
|
|
3568
|
-
10042: "unauthorized",
|
|
3569
|
-
10043: "unavailable",
|
|
3570
|
-
10048: "invalid",
|
|
3571
|
-
10054: "unavailable",
|
|
3572
|
-
10058: "throttled",
|
|
3573
|
-
10069: "conflict",
|
|
3574
|
-
10073: "conflict",
|
|
3575
|
-
100100: "invalid"
|
|
3576
|
-
}
|
|
3577
|
-
};
|
|
3578
|
-
const vercelCodes = {
|
|
3579
|
-
bad_request: "invalid",
|
|
3580
|
-
conflict_aliases: "conflict",
|
|
3581
|
-
forbidden: "unauthorized",
|
|
3582
|
-
internal_server_error: "unavailable",
|
|
3583
|
-
method_unknown: "invalid",
|
|
3584
|
-
not_found: "not-found",
|
|
3585
|
-
not_modified: "conflict",
|
|
3586
|
-
rate_limited: "throttled",
|
|
3587
|
-
service_unavailable: "unavailable"
|
|
3588
|
-
};
|
|
3589
|
-
function kindFromStatus(status) {
|
|
3590
|
-
if (status === 401 || status === 403) return "unauthorized";
|
|
3591
|
-
if (status === 404 || status === 410) return "not-found";
|
|
3592
|
-
if (status === 409 || status === 412) return "conflict";
|
|
3593
|
-
if (status === 429) return "throttled";
|
|
3594
|
-
if (status === 408 || status >= 500) return "unavailable";
|
|
3595
|
-
if (status >= 400) return "invalid";
|
|
3596
|
-
}
|
|
3597
|
-
/**
|
|
3598
|
-
* Classifies a failed provider call. A documented provider code wins over the HTTP status.
|
|
3599
|
-
* Returns `undefined` only when neither a known code nor an error status is present.
|
|
3600
|
-
*/
|
|
3601
|
-
function classifyProviderFailure(source, { codes = [], status }) {
|
|
3602
|
-
for (const code of codes) {
|
|
3603
|
-
const kind = source.host === "vercel" ? typeof code === "string" && Object.hasOwn(vercelCodes, code) ? vercelCodes[code] : void 0 : source.host === "cloudflare" && source.product && typeof code === "number" && Object.hasOwn(cloudflareCodes[source.product], code) ? cloudflareCodes[source.product][code] : void 0;
|
|
3604
|
-
if (kind) return kind;
|
|
3605
|
-
}
|
|
3606
|
-
return status === void 0 ? void 0 : kindFromStatus(status);
|
|
3607
|
-
}
|
|
3608
|
-
/** Finds the Cloudflare product of an account API path, such as `/r2/buckets`. */
|
|
3609
|
-
function cloudflareProductOfPath(path) {
|
|
3610
|
-
if (path.startsWith("/r2/")) return "r2";
|
|
3611
|
-
if (path.startsWith("/storage/kv/")) return "kv";
|
|
3612
|
-
if (path.startsWith("/d1/")) return "d1";
|
|
3613
|
-
if (path === "/queues" || path.startsWith("/queues/") || path.startsWith("/queues?")) return "queues";
|
|
3614
|
-
}
|
|
3615
|
-
/**
|
|
3616
|
-
* Reads the error codes of a Cloudflare (`errors[].code`) or Vercel (`error.code`) error body.
|
|
3617
|
-
* Keeps only codes that are safe to print: numbers, and short strings without spaces or line breaks.
|
|
3618
|
-
*/
|
|
3619
|
-
function readProviderErrorCodes(body) {
|
|
3620
|
-
if (!body || typeof body !== "object") return [];
|
|
3621
|
-
const error = Reflect.get(body, "error");
|
|
3622
|
-
const errors = Reflect.get(body, "errors");
|
|
3623
|
-
return [error && typeof error === "object" ? Reflect.get(error, "code") : void 0, ...Array.isArray(errors) ? errors.map((entry) => entry && typeof entry === "object" ? Reflect.get(entry, "code") : void 0) : []].filter((code) => typeof code === "number" && Number.isFinite(code) || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
|
|
3624
|
-
}
|
|
3625
|
-
// ../internal/dist/provision.js
|
|
3626
|
-
/** Plans one provider in step order and collects warnings and explicit unchecked state. */
|
|
3627
|
-
async function planProvisionSteps(provider, steps, context) {
|
|
3628
|
-
const warnings = [];
|
|
3629
|
-
let checked = true;
|
|
3630
|
-
const planContext = {
|
|
3631
|
-
...context,
|
|
3632
|
-
logger: {
|
|
3633
|
-
log: (message) => context.logger.log(message),
|
|
3634
|
-
warn(message) {
|
|
3635
|
-
warnings.push(message);
|
|
3636
|
-
context.logger.warn(message);
|
|
3637
|
-
}
|
|
3638
|
-
},
|
|
3639
|
-
markPlanUnchecked: () => {
|
|
3640
|
-
checked = false;
|
|
3641
|
-
}
|
|
3642
|
-
};
|
|
3643
|
-
const actions = [];
|
|
3644
|
-
for (const step of steps) {
|
|
3645
|
-
if (step.provider !== provider) continue;
|
|
3646
|
-
for (const action of await step.plan(planContext)) actions.push({
|
|
3647
|
-
action,
|
|
3648
|
-
step: step.id
|
|
3649
|
-
});
|
|
3650
|
-
}
|
|
3651
|
-
return {
|
|
3652
|
-
actions,
|
|
3653
|
-
checked,
|
|
3654
|
-
warnings
|
|
3655
|
-
};
|
|
3656
|
-
}
|
|
3657
|
-
function resolveCloudflareProvisionConfig(env) {
|
|
3658
|
-
const credentials = readHostCredentialsFromEnv("cloudflare", env);
|
|
3659
|
-
if (!credentials?.accountId) return;
|
|
3660
|
-
return {
|
|
3661
|
-
accountId: credentials.accountId,
|
|
3662
|
-
token: credentials.token
|
|
3663
|
-
};
|
|
3664
|
-
}
|
|
3665
|
-
function resolveVercelProvisionConfig(env) {
|
|
3666
|
-
const credentials = readHostCredentialsFromEnv("vercel", env);
|
|
3667
|
-
if (!credentials) return;
|
|
3668
|
-
return {
|
|
3669
|
-
token: credentials.token,
|
|
3670
|
-
teamId: credentials.teamId
|
|
3671
|
-
};
|
|
3672
|
-
}
|
|
3673
|
-
function ownParser(options) {
|
|
3674
|
-
if (!Object.hasOwn(options, "parse")) return;
|
|
3675
|
-
return options.parse;
|
|
3676
|
-
}
|
|
3677
|
-
function provisionRequestError(method, path, status, codes, kind) {
|
|
3678
|
-
const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
|
|
3679
|
-
return Object.assign(internalErrorDiagnostics.INTERNAL_R0013({ message: `Provision request failed: ${method} ${path} (${status}).${suffix}` }), {
|
|
3680
|
-
codes,
|
|
3681
|
-
kind,
|
|
3682
|
-
status
|
|
3683
|
-
});
|
|
3684
|
-
}
|
|
3685
|
-
/** Whether `error` is a failed provider API call of provisioning. */
|
|
3686
|
-
function isProvisionRequestError(error) {
|
|
3687
|
-
return error instanceof Error && Reflect.get(error, "code") === "INTERNAL_R0013";
|
|
3688
|
-
}
|
|
3689
|
-
function createJsonClient(source, baseURL, headers, fetchImpl, baseQuery) {
|
|
3690
|
-
return async function request(path, options = {}) {
|
|
3691
|
-
const url = new URL(`${baseURL}${path}`);
|
|
3692
|
-
const query = Object.hasOwn(options, "query") ? options.query : void 0;
|
|
3693
|
-
for (const [key, value] of Object.entries({
|
|
3694
|
-
...baseQuery,
|
|
3695
|
-
...query
|
|
3696
|
-
})) url.searchParams.set(key, value);
|
|
3697
|
-
const method = Object.hasOwn(options, "method") ? options.method : void 0;
|
|
3698
|
-
const body = Object.hasOwn(options, "body") ? options.body : void 0;
|
|
3699
|
-
const requestHeaders = Object.hasOwn(options, "headers") ? options.headers : void 0;
|
|
3700
|
-
const init = {
|
|
3701
|
-
method: method ?? "GET",
|
|
3702
|
-
headers: {
|
|
3703
|
-
...requestHeaders,
|
|
3704
|
-
...headers
|
|
3705
|
-
}
|
|
3706
|
-
};
|
|
3707
|
-
if (body !== void 0) {
|
|
3708
|
-
init.headers = {
|
|
3709
|
-
...init.headers,
|
|
3710
|
-
"content-type": "application/json"
|
|
3711
|
-
};
|
|
3712
|
-
init.body = JSON.stringify(body);
|
|
3713
|
-
}
|
|
3714
|
-
const response = await fetchImpl(url, init);
|
|
3715
|
-
if (!response.ok) {
|
|
3716
|
-
const codes = readProviderErrorCodes(await response.json().catch(() => void 0));
|
|
3717
|
-
const kind = classifyProviderFailure(source(path), {
|
|
3718
|
-
codes,
|
|
3719
|
-
status: response.status
|
|
3720
|
-
}) ?? "unavailable";
|
|
3721
|
-
throw provisionRequestError(method ?? "GET", path, response.status, codes, kind);
|
|
3722
|
-
}
|
|
3723
|
-
const value = await response.json();
|
|
3724
|
-
const parse = ownParser(options);
|
|
3725
|
-
return parse ? parse(value) : value;
|
|
3726
|
-
};
|
|
3727
|
-
}
|
|
3728
|
-
function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
|
|
3729
|
-
return createCloudflareClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, config.token, fetchImpl);
|
|
3730
|
-
}
|
|
3731
|
-
/** A Cloudflare REST client for requests outside one account, such as `GET /accounts`. */
|
|
3732
|
-
function createCloudflareApiClient(token, fetchImpl = globalThis.fetch) {
|
|
3733
|
-
return createCloudflareClient("https://api.cloudflare.com/client/v4", token, fetchImpl);
|
|
3734
|
-
}
|
|
3735
|
-
function createCloudflareClient(baseURL, token, fetchImpl) {
|
|
3736
|
-
const client = createJsonClient((path) => ({
|
|
3737
|
-
host: "cloudflare",
|
|
3738
|
-
product: cloudflareProductOfPath(path)
|
|
3739
|
-
}), baseURL, { authorization: `Bearer ${token}` }, fetchImpl);
|
|
3740
|
-
return async (path, options = {}) => {
|
|
3741
|
-
const parse = ownParser(options) ?? ((value) => value);
|
|
3742
|
-
return await client(path, {
|
|
3743
|
-
...options,
|
|
3744
|
-
parse(value) {
|
|
3745
|
-
if (!value || Object(value) !== value) throw internalErrorDiagnostics.INTERNAL_R0010({ message: "Cloudflare provisioning returned an invalid response." });
|
|
3746
|
-
const envelope = value;
|
|
3747
|
-
return {
|
|
3748
|
-
...envelope,
|
|
3749
|
-
result: envelope.result === void 0 ? void 0 : parse(envelope.result)
|
|
3750
|
-
};
|
|
3751
|
-
}
|
|
3752
|
-
});
|
|
3753
|
-
};
|
|
3754
|
-
}
|
|
3755
|
-
function createVercelProvisionClient(config, fetchImpl = globalThis.fetch) {
|
|
3756
|
-
return createJsonClient(() => ({ host: "vercel" }), "https://api.vercel.com", { authorization: `Bearer ${config.token}` }, fetchImpl, config.teamId ? { teamId: config.teamId } : void 0);
|
|
3757
|
-
}
|
|
3758
|
-
/** A Netlify REST client for `https://api.netlify.com/api/v1`. */
|
|
3759
|
-
function createNetlifyApiClient(token, fetchImpl = globalThis.fetch) {
|
|
3760
|
-
return createJsonClient(() => ({ host: "netlify" }), "https://api.netlify.com/api/v1", { authorization: `Bearer ${token}` }, fetchImpl);
|
|
3761
|
-
}
|
|
3762
|
-
// src/provision.ts
|
|
3763
|
-
const PROVISION_HOSTS = ["cloudflare", "vercel"];
|
|
3764
|
-
const HOST_CREDENTIALS = {
|
|
3765
|
-
cloudflare: "CLOUDFLARE_ACCOUNT_ID and a Cloudflare login (`wrangler login` or CLOUDFLARE_API_TOKEN)",
|
|
3766
|
-
vercel: "VERCEL_TOKEN"
|
|
3767
|
-
};
|
|
3768
|
-
const USAGE = {
|
|
3769
|
-
run: "vitehub provision run [--host <cloudflare|vercel>] [--dry-run] [--json]",
|
|
3770
|
-
status: "vitehub provision status [--host <cloudflare|vercel>] [--json]"
|
|
3771
|
-
};
|
|
3772
|
-
/** Whether ViteHub can provision resources on `host`. Only Cloudflare and Vercel have Provision Steps. */
|
|
3773
|
-
function isProvisionHost(value) {
|
|
3774
|
-
return PROVISION_HOSTS.some((host) => host === value);
|
|
3775
|
-
}
|
|
3776
|
-
function setVariable(env, name, value) {
|
|
3777
|
-
return env[name]?.trim() || !value ? env : {
|
|
3778
|
-
...env,
|
|
3779
|
-
[name]: value
|
|
3780
|
-
};
|
|
3781
|
-
}
|
|
3782
|
-
/**
|
|
3783
|
-
* The environment of a Provision Step: `env` with the host credentials that `resolveHostCredentials` found, such as a
|
|
3784
|
-
* `wrangler login` token, and the account and project ids of the host link. The selected link wins over environment scope.
|
|
3785
|
-
*/
|
|
3786
|
-
function provisionEnv(env, credentials, link = {}) {
|
|
3787
|
-
if (!credentials.ok) return env;
|
|
3788
|
-
if (credentials.host === "cloudflare") return {
|
|
3789
|
-
...setVariable(setVariable(env, "CLOUDFLARE_API_TOKEN", credentials.token), "CLOUDFLARE_ACCOUNT_ID", credentials.accountId),
|
|
3790
|
-
...link.accountId ? { CLOUDFLARE_ACCOUNT_ID: link.accountId } : {}
|
|
3791
|
-
};
|
|
3792
|
-
if (credentials.host === "vercel") {
|
|
3793
|
-
const teamId = credentials.teamId;
|
|
3794
|
-
const resolved = setVariable(setVariable(env, "VERCEL_TOKEN", credentials.token), "VERCEL_TEAM_ID", teamId);
|
|
3795
|
-
if (!link.accountId && !link.projectId) return resolved;
|
|
3796
|
-
return {
|
|
3797
|
-
...resolved,
|
|
3798
|
-
...link.accountId ? {
|
|
3799
|
-
VERCEL_TEAM_ID: link.accountId.startsWith("team_") ? link.accountId : void 0,
|
|
3800
|
-
VERCEL_ORG_ID: void 0
|
|
3801
|
-
} : {},
|
|
3802
|
-
...link.projectId ? { VERCEL_PROJECT_ID: link.projectId } : {}
|
|
3803
|
-
};
|
|
3804
|
-
}
|
|
3805
|
-
return env;
|
|
3806
|
-
}
|
|
3807
|
-
function parseArgs$1(command, args) {
|
|
3808
|
-
const parsed = {
|
|
3809
|
-
dryRun: false,
|
|
3810
|
-
help: false,
|
|
3811
|
-
json: false
|
|
3812
|
-
};
|
|
3813
|
-
for (let index = 0; index < args.length; index++) {
|
|
3814
|
-
const arg = args[index];
|
|
3815
|
-
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
3816
|
-
else if (arg === "--json") parsed.json = true;
|
|
3817
|
-
else if (arg === "--dry-run" && command === "run") parsed.dryRun = true;
|
|
3818
|
-
else if (arg === "--host") {
|
|
3819
|
-
const host = args[index + 1];
|
|
3820
|
-
if (!host || host.startsWith("-")) parsed.error = "Option --host requires a value.";
|
|
3821
|
-
else {
|
|
3822
|
-
parsed.host = host;
|
|
3823
|
-
index++;
|
|
3824
|
-
}
|
|
3825
|
-
} else if (arg?.startsWith("--host=")) {
|
|
3826
|
-
const host = arg.slice(7);
|
|
3827
|
-
if (!host) parsed.error = "Option --host requires a value.";
|
|
3828
|
-
else parsed.host = host;
|
|
3829
|
-
} else if (arg === "--provider" || arg?.startsWith("--provider=")) {
|
|
3830
|
-
const value = arg === "--provider" ? args[index + 1] : arg.slice(11);
|
|
3831
|
-
const host = value && !value.startsWith("-") ? value : "<cloudflare|vercel>";
|
|
3832
|
-
return {
|
|
3833
|
-
...parsed,
|
|
3834
|
-
error: `Option --provider is now --host.\nfix: run \`vitehub provision ${command} --host ${host}\`.`
|
|
3835
|
-
};
|
|
3836
|
-
} else if (arg) parsed.error = `Unknown provision argument: ${arg}`;
|
|
3837
|
-
}
|
|
3838
|
-
return parsed;
|
|
3839
|
-
}
|
|
3840
|
-
function writeUsage(command, stream) {
|
|
3841
|
-
const lines = command === "run" ? [
|
|
3842
|
-
`Usage: ${USAGE.run}`,
|
|
3843
|
-
"",
|
|
3844
|
-
"Idempotently creates missing host resources for the app's Definitions. `vitehub deploy` runs it before each deploy.",
|
|
3845
|
-
"Uses the credentials of `vitehub deploy`: environment variables first, then the `wrangler login` session.",
|
|
3846
|
-
"Never deletes resources. Changes an existing resource only for a planned update, such as D1 read replication.",
|
|
3847
|
-
"",
|
|
3848
|
-
"Options:",
|
|
3849
|
-
" --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`:",
|
|
3850
|
-
" the default target of .vitehub/link.json, else the only one, else `host` in vitehub().",
|
|
3851
|
-
" --dry-run Print the plan without applying it.",
|
|
3852
|
-
" --json Print one JSON result to stdout.",
|
|
3853
|
-
" -h, --help Show this help."
|
|
3854
|
-
] : [
|
|
3855
|
-
`Usage: ${USAGE.status}`,
|
|
3856
|
-
"",
|
|
3857
|
-
"Shows the ids recorded in .vitehub/provision.json and the actions the current plan would apply.",
|
|
3858
|
-
"Marks recorded ids that no Definition declares, with how to delete them on the host.",
|
|
3859
|
-
"Never creates or deletes provider resources, and never writes Provision State.",
|
|
3860
|
-
"",
|
|
3861
|
-
"Options:",
|
|
3862
|
-
" --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`.",
|
|
3863
|
-
" --json Print one JSON result to stdout.",
|
|
3864
|
-
" -h, --help Show this help."
|
|
3865
|
-
];
|
|
3866
|
-
stream.write(`${lines.join("\n")}\n\n`);
|
|
3867
|
-
}
|
|
3868
|
-
async function resolveHost(command, parsed, context) {
|
|
3869
|
-
if (parsed.help) {
|
|
3870
|
-
writeUsage(command, context.stdout);
|
|
3871
|
-
return { exitCode: 0 };
|
|
3872
|
-
}
|
|
3873
|
-
if (parsed.error) {
|
|
3874
|
-
context.stderr.write(`${parsed.error}\n`);
|
|
3875
|
-
writeUsage(command, context.stderr);
|
|
3876
|
-
return { exitCode: 1 };
|
|
3877
|
-
}
|
|
3878
|
-
let host = parsed.host;
|
|
3879
|
-
let link;
|
|
3880
|
-
if (host === void 0) {
|
|
3881
|
-
const { resolveDefaultDeployTarget } = await import("./deploy-DDen0JC0.js").then((n) => n.n);
|
|
3882
|
-
try {
|
|
3883
|
-
const target = await resolveDefaultDeployTarget(resolveViteHubProjectRoot(context.rootDir), context.env, `vitehub provision ${command}`);
|
|
3884
|
-
host = target.host;
|
|
3885
|
-
link = target.link;
|
|
3886
|
-
} catch (error) {
|
|
3887
|
-
context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
|
|
3888
|
-
return { exitCode: 1 };
|
|
3889
|
-
}
|
|
3890
|
-
if (!isProvisionHost(host)) {
|
|
3891
|
-
context.stderr.write(`The host of this project is ${host}, and provision supports cloudflare and vercel. Pass --host cloudflare|vercel to provision another host.\n`);
|
|
3892
|
-
return { exitCode: 1 };
|
|
3893
|
-
}
|
|
3894
|
-
}
|
|
3895
|
-
if (!isProvisionHost(host)) {
|
|
3896
|
-
context.stderr.write("Provision requires --host cloudflare|vercel.\n");
|
|
3897
|
-
writeUsage(command, context.stderr);
|
|
3898
|
-
return { exitCode: 1 };
|
|
3899
|
-
}
|
|
3900
|
-
return {
|
|
3901
|
-
host,
|
|
3902
|
-
...link ? { link } : {}
|
|
3903
|
-
};
|
|
3904
|
-
}
|
|
3905
|
-
function hasHostCredentials(host, env) {
|
|
3906
|
-
return Boolean(host === "cloudflare" ? resolveCloudflareProvisionConfig(env) : resolveVercelProvisionConfig(env));
|
|
3907
|
-
}
|
|
3908
|
-
async function withHostCredentials(host, context, link) {
|
|
3909
|
-
const credentials = await resolveHostCredentials(host, {
|
|
3910
|
-
cwd: context.rootDir,
|
|
3911
|
-
env: context.env,
|
|
3912
|
-
...context.runHostCli ? { run: context.runHostCli } : {}
|
|
3913
|
-
});
|
|
3914
|
-
return {
|
|
3915
|
-
...context,
|
|
3916
|
-
env: provisionEnv(context.env, credentials, {
|
|
3917
|
-
...link?.account?.id ? { accountId: link.account.id } : {},
|
|
3918
|
-
...link?.project.id ? { projectId: link.project.id } : {}
|
|
3919
|
-
})
|
|
3920
|
-
};
|
|
3921
|
-
}
|
|
3922
|
-
async function planProvision(provider, context, steps, json) {
|
|
3923
|
-
return await planProvisionSteps(provider, [...steps], {
|
|
3924
|
-
env: context.env,
|
|
3925
|
-
fetch: globalThis.fetch,
|
|
3926
|
-
logger: {
|
|
3927
|
-
log: (message) => (json ? context.stderr : context.stdout).write(`${message}\n`),
|
|
3928
|
-
warn: (message) => {
|
|
3929
|
-
if (!json) context.stderr.write(`${message}\n`);
|
|
3930
|
-
}
|
|
3931
|
-
}
|
|
3932
|
-
});
|
|
3933
|
-
}
|
|
3934
|
-
function findUndeclaredEntries(provider, recorded, steps, env) {
|
|
3935
|
-
const categories = /* @__PURE__ */ new Map();
|
|
3936
|
-
const unverifiedDeclarations = /* @__PURE__ */ new Set();
|
|
3937
|
-
const activeDeclarations = /* @__PURE__ */ new Set();
|
|
3938
|
-
for (const step of steps) {
|
|
3939
|
-
if (step.provider !== provider) continue;
|
|
3940
|
-
const described = step.recordedState?.({ env }) ?? [];
|
|
3941
|
-
for (const category of described) categories.set(category.category, category);
|
|
3942
|
-
if (described.some((category) => category.declared.length)) for (const category of described) activeDeclarations.add(category.category);
|
|
3943
|
-
if (described.some((category) => category.declared.some((key) => {
|
|
3944
|
-
const ids = recorded[category.category] ?? {};
|
|
3945
|
-
const id = Object.hasOwn(ids, key) ? ids[key] : void 0;
|
|
3946
|
-
const expected = category.declaredResourceIdentity?.(key);
|
|
3947
|
-
const identity = id === void 0 ? void 0 : category.resourceIdentity ? category.resourceIdentity({
|
|
3948
|
-
id,
|
|
3949
|
-
key
|
|
3950
|
-
}) : id;
|
|
3951
|
-
return expected === void 0 || identity === void 0 || identity !== expected;
|
|
3952
|
-
}))) for (const category of described) unverifiedDeclarations.add(category.category);
|
|
3953
|
-
}
|
|
3954
|
-
const resourceIdentity = (category, key, id) => {
|
|
3955
|
-
const describe = categories.get(category)?.resourceIdentity;
|
|
3956
|
-
return describe ? describe({
|
|
3957
|
-
id,
|
|
3958
|
-
key
|
|
3959
|
-
}) : id;
|
|
3960
|
-
};
|
|
3961
|
-
const isDeclared = (category, key, id) => {
|
|
3962
|
-
const description = categories.get(category);
|
|
3963
|
-
if (!description?.declared.includes(key)) return false;
|
|
3964
|
-
const expected = description.declaredResourceIdentity?.(key);
|
|
3965
|
-
const identity = resourceIdentity(category, key, id);
|
|
3966
|
-
return expected === void 0 || identity === void 0 || identity === expected;
|
|
3967
|
-
};
|
|
3968
|
-
const declaredById = /* @__PURE__ */ new Map();
|
|
3969
|
-
for (const [category, ids] of Object.entries(recorded)) for (const [key, id] of Object.entries(ids)) {
|
|
3970
|
-
const identity = resourceIdentity(category, key, id);
|
|
3971
|
-
if (identity !== void 0 && isDeclared(category, key, id) && !declaredById.has(identity)) declaredById.set(identity, `${category} ${JSON.stringify(key)}`);
|
|
3972
|
-
}
|
|
3973
|
-
const stateEdit = `remove the entry from ${PROVISION_STATE_FILE}`;
|
|
3974
|
-
const entries = [];
|
|
3975
|
-
for (const [category, ids] of Object.entries(recorded)) for (const [key, id] of Object.entries(ids)) {
|
|
3976
|
-
if (isDeclared(category, key, id)) continue;
|
|
3977
|
-
const identity = resourceIdentity(category, key, id);
|
|
3978
|
-
const sharedWith = identity === void 0 ? void 0 : declaredById.get(identity);
|
|
3979
|
-
let fix;
|
|
3980
|
-
if (sharedWith) fix = `${sharedWith} uses the same id, so keep the resource and only ${stateEdit}.`;
|
|
3981
|
-
else if (unverifiedDeclarations.has(category) || identity === void 0 && activeDeclarations.has(category)) fix = "A current Definition may still use this recorded resource, but its identity cannot be verified from local state and config. Verify its resource id before deleting anything by comparing the provider's resource names and bindings with current Definitions.";
|
|
3982
|
-
else fix = `No Definition declares it. If no deployment uses ${id}, ${categories.get(category)?.deleteHint({
|
|
3983
|
-
id,
|
|
3984
|
-
key
|
|
3985
|
-
}) ?? `delete resource ${id} in the ${provider === "cloudflare" ? "Cloudflare" : "Vercel"} dashboard`}, then ${stateEdit}.`;
|
|
3986
|
-
entries.push({
|
|
3987
|
-
category,
|
|
3988
|
-
fix,
|
|
3989
|
-
id,
|
|
3990
|
-
key
|
|
3991
|
-
});
|
|
3992
|
-
}
|
|
3993
|
-
return entries;
|
|
3994
|
-
}
|
|
3995
|
-
function serializeAction({ action, step }) {
|
|
3996
|
-
return {
|
|
3997
|
-
...action.pending === void 0 ? {} : { pending: action.pending },
|
|
3998
|
-
exists: action.exists,
|
|
3999
|
-
kind: action.kind,
|
|
4000
|
-
name: action.name,
|
|
4001
|
-
step,
|
|
4002
|
-
...action.update === void 0 ? {} : { update: action.update }
|
|
4003
|
-
};
|
|
4004
|
-
}
|
|
4005
|
-
function provisionActionStatus({ action }) {
|
|
4006
|
-
return !action.exists ? "create" : action.update ? "update" : action.pending ? "pending" : "exists";
|
|
4007
|
-
}
|
|
4008
|
-
function writeProvisionActions(actions, stdout) {
|
|
4009
|
-
for (const planned of actions) {
|
|
4010
|
-
const { action } = planned;
|
|
4011
|
-
stdout.write(`${provisionActionStatus(planned)}\t${action.kind}\t${action.name}${action.update ? `\t${action.update}` : ""}\n`);
|
|
4012
|
-
}
|
|
4013
|
-
}
|
|
4014
|
-
async function runProvision(args, cliContext, load) {
|
|
4015
|
-
const parsed = parseArgs$1("run", args);
|
|
4016
|
-
const resolved = await resolveHost("run", parsed, cliContext);
|
|
4017
|
-
if ("exitCode" in resolved) return resolved.exitCode;
|
|
4018
|
-
const { host: provider } = resolved;
|
|
4019
|
-
const { env = cliContext.env, rootDir, steps } = await load(provider);
|
|
4020
|
-
const context = await withHostCredentials(provider, {
|
|
4021
|
-
...cliContext,
|
|
4022
|
-
env,
|
|
4023
|
-
rootDir
|
|
4024
|
-
}, resolved.link);
|
|
4025
|
-
if (!parsed.dryRun && !hasHostCredentials(provider, context.env)) {
|
|
4026
|
-
context.stderr.write(`Provision requires ${HOST_CREDENTIALS[provider]}. Dry-run preview does not require credentials (--dry-run).\n`);
|
|
4027
|
-
return 1;
|
|
4028
|
-
}
|
|
4029
|
-
if (!parsed.dryRun) await readProvisionState(context.rootDir);
|
|
4030
|
-
const { actions, checked, warnings } = await planProvision(provider, context, steps, parsed.json);
|
|
4031
|
-
const blocked = !checked && !parsed.dryRun;
|
|
4032
|
-
if (!parsed.json) {
|
|
4033
|
-
if (!checked) context.stdout.write("provision: plan not checked.\n");
|
|
4034
|
-
if (blocked) {
|
|
4035
|
-
context.stderr.write("provision: nothing applied. Fix the warnings above, or preview with --dry-run.\n");
|
|
4036
|
-
return 1;
|
|
4037
|
-
}
|
|
4038
|
-
if (!actions.length) {
|
|
4039
|
-
if (checked) context.stdout.write(`provision: no ${provider} resources to create.\n`);
|
|
4040
|
-
return 0;
|
|
4041
|
-
}
|
|
4042
|
-
writeProvisionActions(actions, context.stdout);
|
|
4043
|
-
}
|
|
4044
|
-
let state = {};
|
|
4045
|
-
if (!parsed.dryRun && !blocked) for (const { action } of actions) {
|
|
4046
|
-
const result = await action.apply();
|
|
4047
|
-
if (result.ids) state = mergeProvisionState(state, result.ids);
|
|
4048
|
-
}
|
|
4049
|
-
const wroteState = Object.keys(state).length > 0;
|
|
4050
|
-
if (wroteState) await writeProvisionState(context.rootDir, state);
|
|
4051
|
-
if (parsed.json) {
|
|
4052
|
-
if (blocked) context.stderr.write("provision: plan not checked, nothing applied. Read warnings in the JSON result.\n");
|
|
4053
|
-
context.stdout.write(`${JSON.stringify({
|
|
4054
|
-
actions: actions.map(serializeAction),
|
|
4055
|
-
checked,
|
|
4056
|
-
ids: state[provider] ?? {},
|
|
4057
|
-
mode: parsed.dryRun ? "dry-run" : "apply",
|
|
4058
|
-
provider,
|
|
4059
|
-
schemaVersion: 1,
|
|
4060
|
-
stateFile: wroteState ? PROVISION_STATE_FILE : null,
|
|
4061
|
-
warnings
|
|
4062
|
-
})}\n`);
|
|
4063
|
-
} else if (wroteState) context.stdout.write(`provision: wrote ids to ${PROVISION_STATE_FILE}\n`);
|
|
4064
|
-
return blocked ? 1 : 0;
|
|
4065
|
-
}
|
|
4066
|
-
async function runProvisionStatus(args, cliContext, load) {
|
|
4067
|
-
const parsed = parseArgs$1("status", args);
|
|
4068
|
-
const resolved = await resolveHost("status", parsed, cliContext);
|
|
4069
|
-
if ("exitCode" in resolved) return resolved.exitCode;
|
|
4070
|
-
const { host: provider } = resolved;
|
|
4071
|
-
const { env = cliContext.env, rootDir, steps } = await load(provider);
|
|
4072
|
-
const context = await withHostCredentials(provider, {
|
|
4073
|
-
...cliContext,
|
|
4074
|
-
env,
|
|
4075
|
-
rootDir
|
|
4076
|
-
}, resolved.link);
|
|
4077
|
-
const recorded = (await readProvisionState(context.rootDir))[provider] ?? {};
|
|
4078
|
-
const undeclared = findUndeclaredEntries(provider, recorded, steps, context.env);
|
|
4079
|
-
const hasCredentials = hasHostCredentials(provider, context.env);
|
|
4080
|
-
const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, steps, parsed.json) : {
|
|
4081
|
-
actions: [],
|
|
4082
|
-
checked: false,
|
|
4083
|
-
warnings: [`provision: plan not checked, missing ${HOST_CREDENTIALS[provider]}.`]
|
|
4084
|
-
};
|
|
4085
|
-
const pending = actions.filter(({ action }) => action.pending ?? !action.exists).length;
|
|
4086
|
-
if (parsed.json) {
|
|
4087
|
-
context.stdout.write(`${JSON.stringify({
|
|
4088
|
-
plan: {
|
|
4089
|
-
actions: actions.map(serializeAction),
|
|
4090
|
-
checked,
|
|
4091
|
-
pending
|
|
4092
|
-
},
|
|
4093
|
-
provider,
|
|
4094
|
-
recorded,
|
|
4095
|
-
schemaVersion: 1,
|
|
4096
|
-
stateFile: PROVISION_STATE_FILE,
|
|
4097
|
-
undeclared,
|
|
4098
|
-
warnings
|
|
4099
|
-
})}\n`);
|
|
4100
|
-
return 0;
|
|
4101
|
-
}
|
|
4102
|
-
const isUndeclared = (category, key) => undeclared.some((entry) => entry.category === category && entry.key === key);
|
|
4103
|
-
const recordedEntries = Object.entries(recorded).flatMap(([category, ids]) => Object.entries(ids).map(([key, id]) => `${category}\t${key}\t${id}${isUndeclared(category, key) ? " not declared" : ""}\n`));
|
|
4104
|
-
if (recordedEntries.length) {
|
|
4105
|
-
context.stdout.write(`recorded ${provider} ids (${PROVISION_STATE_FILE}):\n`);
|
|
4106
|
-
for (const entry of recordedEntries) context.stdout.write(entry);
|
|
4107
|
-
for (const entry of undeclared) context.stdout.write(`fix: ${entry.category} ${JSON.stringify(entry.key)}: ${entry.fix}\n`);
|
|
4108
|
-
} else context.stdout.write(`recorded ${provider} ids: none in ${PROVISION_STATE_FILE}\n`);
|
|
4109
|
-
if (!checked) {
|
|
4110
|
-
if (!hasCredentials) context.stderr.write(`${warnings[0]}\n`);
|
|
4111
|
-
context.stdout.write("plan: not checked\n");
|
|
4112
|
-
return 0;
|
|
4113
|
-
}
|
|
4114
|
-
writeProvisionActions(actions, context.stdout);
|
|
4115
|
-
context.stdout.write(pending ? `plan: ${pending} pending ${pending === 1 ? "action" : "actions"}. Run \`vitehub provision run --host ${provider}\` to apply.\n` : "plan: no pending actions\n");
|
|
4116
|
-
return 0;
|
|
4117
|
-
}
|
|
4118
|
-
/**
|
|
4119
|
-
* Built-in namespace that orchestrates package-contributed Provision Steps. `load` reads the steps of a build for the
|
|
4120
|
-
* `--host` of the command, so `provision run --host cloudflare` plans what `vitehub deploy --host cloudflare` creates.
|
|
4121
|
-
*/
|
|
4122
|
-
function createProvisionNamespace(load) {
|
|
4123
|
-
return {
|
|
4124
|
-
description: "Idempotently create missing provider resources.",
|
|
4125
|
-
features: [{
|
|
4126
|
-
description: "Create missing provider resources for the app's Definitions.",
|
|
4127
|
-
name: "run",
|
|
4128
|
-
run: (args, context) => runProvision(args, context, load),
|
|
4129
|
-
usage: USAGE.run
|
|
4130
|
-
}, {
|
|
4131
|
-
description: "Show recorded provider ids and pending plan actions.",
|
|
4132
|
-
name: "status",
|
|
4133
|
-
run: (args, context) => runProvisionStatus(args, context, load),
|
|
4134
|
-
usage: USAGE.status
|
|
4135
|
-
}],
|
|
4136
|
-
name: "provision"
|
|
4137
|
-
};
|
|
4138
|
-
}
|
|
4139
|
-
export { readProvisionStateSync as $, resolveDeploymentPlan as A, viteCliProjectConfig as At, readConsoleCredential as B, installArgs as C, quoteSupportedInstallSpecifier as Ct, shellQuote as D, createCliDiscoveryNitroCloser as Dt, setupStatus as E, collectViteHubCliContribution as Et, consoleTokenVariable as F, setupFailure as G, isSetupFailure as H, consoleUrlVariable as I, writeSetupJson as J, table as K, defaultConsoleUrl as L, listMatchingFiles as M, isRecord as Mt, consoleCredentialsFile as N, uninstallArgs as O, findViteHubDevServerUrl as Ot, consoleOrigin as P, readProvisionState as Q, loginCommand as R, formatInstallCommand as S, installSpecifier as St, missingProviderOption as T, appUrlError as Tt, readSetupArgs as U, whoamiCommand as V, setupExitCodes as W, PROVISION_STATE_FILE as X, cliErrorDiagnostics as Y, mergeProvisionState as Z, consoleAppUrl as _, featureIds as _t, writeProvisionActions as a, collectOperationContributions as at, listConsoleApps as b, features as bt, createNetlifyApiClient as c, operationCliOptions as ct, planProvisionSteps as d, parseOperationInput as dt, writeProvisionState as et, resolveHostCredentials as f, operationInputJsonSchema as ft, checkProblem as g, featureHosts as gt, checkConsoleApp as h, resolveViteHubProjectRoot as ht, provisionEnv as i, callOperationFromCli as it, hasDefinitionFiles as j, withStdoutOnStderr as jt, hostFromNitroPreset as k, getStableStdoutWrite as kt, createVercelProvisionClient as l, operationCliPath as lt, appsCommand as m, setupCommandNames as mt, isProvisionHost as n, withViteStageEnvironment as nt, createCloudflareApiClient as o, createOperationRegistry as ot, runHostCli as p, reservedOperationNamespaces as pt, writeSetupError as q, provisionActionStatus as r, callOperation as rt, createCloudflareProvisionClient as s, operationCall as st, createProvisionNamespace as t, loadAllEnv as tt, isProvisionRequestError as u, operationsOf as ut, consoleClient as v, featurePackages as vt, installCommand as w, invariant as wt, openConsole as x, impliedFeatures as xt, linkConsoleApp as y, featureSupport as yt, logoutCommand as z };
|