@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
|
@@ -0,0 +1,1391 @@
|
|
|
1
|
+
import { E as internalErrorDiagnostics, T as isRecordOrFunction, c as resolveVercelProvisionConfig, l as resolveHostCredentials, o as planProvisionSteps, s as resolveCloudflareProvisionConfig, w as isRecord } from "./provision-9QsGgeiq.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { dirname, relative, resolve } from "pathe";
|
|
6
|
+
import { mkdir, readFile, 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 { tmpdir } from "node:os";
|
|
10
|
+
import { createBirpc } from "birpc";
|
|
11
|
+
// ../internal/dist/cli.js
|
|
12
|
+
const missingCliVite = Symbol.for("vitehub.cli.missing-vite");
|
|
13
|
+
function rethrowCliViteImportError(error, importer) {
|
|
14
|
+
if (error instanceof Error && Reflect.get(error, "code") === "ERR_MODULE_NOT_FOUND" && error.message === `Cannot find package 'vite' imported from ${importer}`) Object.assign(error, { [missingCliVite]: true });
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
function isCliViteMissing(error) {
|
|
18
|
+
return error instanceof Error && Reflect.get(error, missingCliVite) === true;
|
|
19
|
+
}
|
|
20
|
+
/** Validate an explicit `--url` before sending a Console request. The caller adds the RPC path. */
|
|
21
|
+
function appUrlError(url) {
|
|
22
|
+
let base;
|
|
23
|
+
try {
|
|
24
|
+
base = new URL(url);
|
|
25
|
+
} catch {
|
|
26
|
+
return "--url must be a URL.";
|
|
27
|
+
}
|
|
28
|
+
const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
|
|
29
|
+
if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return "--url must use HTTPS, except for localhost.";
|
|
30
|
+
if (base.username || base.password || base.search || base.hash) return "--url must not contain credentials, a query, or a fragment.";
|
|
31
|
+
const consolePath = /(?:^|\/)_vitehub(?:\/|$)/.exec(base.pathname);
|
|
32
|
+
if (consolePath) return `--url is the app URL, not the Console URL. Pass --url ${`${base.origin}${base.pathname.slice(0, consolePath.index).replace(/\/$/, "")}`}.`;
|
|
33
|
+
}
|
|
34
|
+
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
35
|
+
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
36
|
+
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
37
|
+
const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
|
|
38
|
+
const stdoutRedirectGlobal = globalThis;
|
|
39
|
+
/**
|
|
40
|
+
* Sends `process.stdout` writes to stderr while `run` loads project config.
|
|
41
|
+
* Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
|
|
42
|
+
*/
|
|
43
|
+
async function withStdoutOnStderr(run, stderr = process.stderr) {
|
|
44
|
+
getStableStdoutWrite();
|
|
45
|
+
const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
|
|
46
|
+
let release;
|
|
47
|
+
stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
|
|
48
|
+
release = resolve;
|
|
49
|
+
});
|
|
50
|
+
await previous;
|
|
51
|
+
const write = process.stdout.write;
|
|
52
|
+
if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
|
|
53
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
|
|
54
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
|
|
55
|
+
}
|
|
56
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
|
|
57
|
+
process.stdout.write = ((chunk, encoding, callback) => {
|
|
58
|
+
const done = typeof encoding === "function" ? encoding : callback;
|
|
59
|
+
let called = false;
|
|
60
|
+
const onComplete = (error) => {
|
|
61
|
+
if (called) return;
|
|
62
|
+
called = true;
|
|
63
|
+
done?.(error);
|
|
64
|
+
};
|
|
65
|
+
const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
|
|
66
|
+
if (done && !called) {
|
|
67
|
+
if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
|
|
68
|
+
else if (stderr.write.length < 2) onComplete();
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
});
|
|
72
|
+
try {
|
|
73
|
+
return await run();
|
|
74
|
+
} finally {
|
|
75
|
+
process.stdout.write = write;
|
|
76
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
|
|
77
|
+
release();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
|
|
82
|
+
* Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
|
|
83
|
+
* config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
|
|
84
|
+
* then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
|
|
85
|
+
*/
|
|
86
|
+
function createCliDiscoveryNitroCloser() {
|
|
87
|
+
const instances = [];
|
|
88
|
+
return {
|
|
89
|
+
close: async () => {
|
|
90
|
+
await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
|
|
91
|
+
},
|
|
92
|
+
plugin: {
|
|
93
|
+
name: "vite-hub/cli-discovery-nitro",
|
|
94
|
+
nitro: { setup: (nitro) => {
|
|
95
|
+
instances.push(nitro);
|
|
96
|
+
} }
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** Let Vite load its config normally, without overriding the root declared by the project. */
|
|
101
|
+
function viteCliProjectConfig(rootDir) {
|
|
102
|
+
const configFile = [
|
|
103
|
+
"js",
|
|
104
|
+
"mjs",
|
|
105
|
+
"ts",
|
|
106
|
+
"cjs",
|
|
107
|
+
"mts",
|
|
108
|
+
"cts"
|
|
109
|
+
].map((extension) => resolve$1(rootDir, `vite.config.${extension}`)).find((file) => existsSync(file));
|
|
110
|
+
if (!configFile) return {
|
|
111
|
+
root: rootDir,
|
|
112
|
+
plugins: []
|
|
113
|
+
};
|
|
114
|
+
return {
|
|
115
|
+
configFile,
|
|
116
|
+
plugins: [{
|
|
117
|
+
name: "vite-hub/cli-discovery-root",
|
|
118
|
+
enforce: "pre",
|
|
119
|
+
config: {
|
|
120
|
+
order: "pre",
|
|
121
|
+
handler: ({ root }) => ({ root: resolve$1(rootDir, root || ".") })
|
|
122
|
+
}
|
|
123
|
+
}]
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
async function createNuxtConfigImport(rootDir, kitPath) {
|
|
127
|
+
const require = createRequire(kitPath);
|
|
128
|
+
let jitiPath;
|
|
129
|
+
try {
|
|
130
|
+
jitiPath = require.resolve("jiti", { paths: [dirname$1(kitPath), rootDir] });
|
|
131
|
+
} catch {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const { createJiti } = await import(pathToFileURL(jitiPath).href);
|
|
135
|
+
const jiti = createJiti(join$1(rootDir, "nuxt.config"), { interopDefault: true });
|
|
136
|
+
const files = /* @__PURE__ */ new Set();
|
|
137
|
+
return {
|
|
138
|
+
files,
|
|
139
|
+
async import(id) {
|
|
140
|
+
const before = new Set(Object.keys(require.cache));
|
|
141
|
+
try {
|
|
142
|
+
return await jiti.import(id);
|
|
143
|
+
} finally {
|
|
144
|
+
for (const file of Object.keys(require.cache).filter((file) => !before.has(file))) {
|
|
145
|
+
files.add(file);
|
|
146
|
+
Reflect.deleteProperty(require.cache, file);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** Returns the unredirected process stdout writer for payload output. */
|
|
153
|
+
function getStableStdoutWrite() {
|
|
154
|
+
const current = process.stdout.write;
|
|
155
|
+
if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
|
|
156
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
|
|
157
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
|
|
158
|
+
}
|
|
159
|
+
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
160
|
+
}
|
|
161
|
+
async function resolveContributor(value) {
|
|
162
|
+
return typeof value === "function" ? await value() : value;
|
|
163
|
+
}
|
|
164
|
+
/** Resolves command namespaces and Provision Steps from one contribution per plugin. */
|
|
165
|
+
async function collectViteHubCliContribution(plugins) {
|
|
166
|
+
const namespaces = /* @__PURE__ */ new Map();
|
|
167
|
+
const steps = /* @__PURE__ */ new Map();
|
|
168
|
+
const seeds = /* @__PURE__ */ new Map();
|
|
169
|
+
let publicUrl;
|
|
170
|
+
for (const plugin of plugins) {
|
|
171
|
+
if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
172
|
+
const metadata = plugin.vitehub;
|
|
173
|
+
const contributor = await resolveContributor(metadata?.cli);
|
|
174
|
+
if (!contributor) continue;
|
|
175
|
+
publicUrl ??= contributor.publicUrl;
|
|
176
|
+
for (const namespace of contributor.namespaces) {
|
|
177
|
+
const existing = namespaces.get(namespace.name);
|
|
178
|
+
if (!existing) {
|
|
179
|
+
namespaces.set(namespace.name, {
|
|
180
|
+
...namespace,
|
|
181
|
+
features: [...namespace.features]
|
|
182
|
+
});
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const features = new Map(existing.features.map((feature) => [feature.name, feature]));
|
|
186
|
+
for (const feature of namespace.features) features.set(feature.name, feature);
|
|
187
|
+
existing.features = [...features.values()];
|
|
188
|
+
}
|
|
189
|
+
for (const step of contributor.provision ?? []) steps.set(step.id, step);
|
|
190
|
+
for (const seed of contributor.seeds ?? []) seeds.set(seed.name, seed);
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
namespaces: [...namespaces.values()],
|
|
194
|
+
provision: [...steps.values()],
|
|
195
|
+
seeds: [...seeds.values()],
|
|
196
|
+
...publicUrl ? { publicUrl } : {}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** File in the project root where the running dev server tells commands where it listens. */
|
|
200
|
+
const viteHubDevServerFile = ".vitehub/dev-server.json";
|
|
201
|
+
/** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
|
|
202
|
+
function readViteHubDevServerFile(root) {
|
|
203
|
+
try {
|
|
204
|
+
const value = JSON.parse(readFileSync(join$1(root, viteHubDevServerFile), "utf8"));
|
|
205
|
+
const url = isRecord(value) ? value.url : void 0;
|
|
206
|
+
const served = isRecord(value) ? value.root : void 0;
|
|
207
|
+
return typeof url === "string" && url && typeof served === "string" && served ? {
|
|
208
|
+
root: served,
|
|
209
|
+
url
|
|
210
|
+
} : void 0;
|
|
211
|
+
} catch {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Where a command finds the dev server of its project: the file that the server wrote in a project root, else
|
|
217
|
+
* `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
|
|
218
|
+
*/
|
|
219
|
+
function findViteHubDevServerUrl(roots, env) {
|
|
220
|
+
for (const root of roots) {
|
|
221
|
+
const file = readViteHubDevServerFile(root);
|
|
222
|
+
if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
|
|
223
|
+
}
|
|
224
|
+
return env["VITEHUB_DEV_SERVER_URL"] || void 0;
|
|
225
|
+
}
|
|
226
|
+
// ../internal/dist/vite-DyksG6Kl.js
|
|
227
|
+
const projectRootDirectoryMarkers = [
|
|
228
|
+
["server", "agents"],
|
|
229
|
+
["server", "channels"],
|
|
230
|
+
["server", "connections"],
|
|
231
|
+
["server", "browsers"],
|
|
232
|
+
["server", "emails"],
|
|
233
|
+
["server", "schedules"],
|
|
234
|
+
["server", "workspaces"]
|
|
235
|
+
];
|
|
236
|
+
const projectRootFileMarkers = [
|
|
237
|
+
["package.json"],
|
|
238
|
+
["nuxt.config.ts"],
|
|
239
|
+
["nuxt.config.mts"],
|
|
240
|
+
["nuxt.config.js"],
|
|
241
|
+
["nuxt.config.mjs"]
|
|
242
|
+
];
|
|
243
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
244
|
+
const resolvedRoot = resolve$1(root);
|
|
245
|
+
const temporaryRoot = resolve$1(tmpdir());
|
|
246
|
+
const sharedTemporaryRoot = dirname$1(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
247
|
+
if (options.projectRoot) return resolve$1(resolvedRoot, options.projectRoot);
|
|
248
|
+
if (basename$1(resolvedRoot) === "app") {
|
|
249
|
+
const parent = dirname$1(resolvedRoot);
|
|
250
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
251
|
+
"nuxt.config.ts",
|
|
252
|
+
"nuxt.config.mts",
|
|
253
|
+
"nuxt.config.js",
|
|
254
|
+
"nuxt.config.mjs"
|
|
255
|
+
]))) return parent;
|
|
256
|
+
}
|
|
257
|
+
let current = resolvedRoot;
|
|
258
|
+
while (true) {
|
|
259
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
260
|
+
if (hasProjectRootMarker(current)) return current;
|
|
261
|
+
const parent = dirname$1(current);
|
|
262
|
+
if (parent === current) return resolvedRoot;
|
|
263
|
+
current = parent;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
267
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
268
|
+
if (statSync(resolve$1(root, ...marker)).isDirectory()) return true;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (!isMissingProjectMarker(error)) throw error;
|
|
271
|
+
}
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
function hasProjectRootMarker(root) {
|
|
275
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
276
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
277
|
+
}
|
|
278
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
279
|
+
for (const marker of markers) {
|
|
280
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
281
|
+
try {
|
|
282
|
+
if (statSync(resolve$1(root, ...path)).isFile()) return true;
|
|
283
|
+
} catch (error) {
|
|
284
|
+
if (!isMissingProjectMarker(error)) throw error;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
function isMissingProjectMarker(error) {
|
|
290
|
+
const code = error.code;
|
|
291
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
292
|
+
}
|
|
293
|
+
// ../internal/dist/operation-rpc.js
|
|
294
|
+
/** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
|
|
295
|
+
const operationRpcPath = "/_vitehub/rpc";
|
|
296
|
+
function text(value) {
|
|
297
|
+
return String(value) === value && value ? value : void 0;
|
|
298
|
+
}
|
|
299
|
+
/** Read an untrusted failure body. It keeps only the diagnostic fields, so a stack never passes through. */
|
|
300
|
+
function readOperationRpcError(value) {
|
|
301
|
+
if (!isRecord(value)) return void 0;
|
|
302
|
+
const code = text(value.code);
|
|
303
|
+
const message = text(value.message);
|
|
304
|
+
const status = value.status;
|
|
305
|
+
if (!code || !message || !Number.isInteger(status)) return void 0;
|
|
306
|
+
const failure = {
|
|
307
|
+
code,
|
|
308
|
+
message,
|
|
309
|
+
status: Number(status)
|
|
310
|
+
};
|
|
311
|
+
if (text(value.fix)) failure.fix = text(value.fix);
|
|
312
|
+
if (text(value.docs)) failure.docs = text(value.docs);
|
|
313
|
+
if (isRecord(value.details)) failure.details = value.details;
|
|
314
|
+
return failure;
|
|
315
|
+
}
|
|
316
|
+
/** Read one response message. */
|
|
317
|
+
function readOperationRpcReply(value) {
|
|
318
|
+
if (!isRecord(value) || value.t !== "s") return void 0;
|
|
319
|
+
const id = text(value.i);
|
|
320
|
+
if (Object.hasOwn(value, "e")) {
|
|
321
|
+
const error = readOperationRpcError(value.e);
|
|
322
|
+
return error ? {
|
|
323
|
+
t: "s",
|
|
324
|
+
...id ? { i: id } : {},
|
|
325
|
+
e: error
|
|
326
|
+
} : void 0;
|
|
327
|
+
}
|
|
328
|
+
return id ? {
|
|
329
|
+
t: "s",
|
|
330
|
+
i: id,
|
|
331
|
+
r: value.r
|
|
332
|
+
} : void 0;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Call one operation with birpc over a request and answer transport, such as one HTTP POST per call. `send` posts the
|
|
336
|
+
* JSON message and returns the parsed answer; its own failures, such as a network error or an abort, reject.
|
|
337
|
+
*/
|
|
338
|
+
async function callOperationRpc(name, input, send) {
|
|
339
|
+
let receive;
|
|
340
|
+
let answer;
|
|
341
|
+
const notReply = /* @__PURE__ */ new Error("The answer is not a reply to the operation call.");
|
|
342
|
+
const rpc = createBirpc({}, {
|
|
343
|
+
on: (listener) => {
|
|
344
|
+
receive = listener;
|
|
345
|
+
},
|
|
346
|
+
post: async (message) => {
|
|
347
|
+
answer = await send(JSON.stringify(message));
|
|
348
|
+
const reply = readOperationRpcReply(answer.body);
|
|
349
|
+
if (!reply || reply.i !== void 0 && reply.i !== message.i) throw notReply;
|
|
350
|
+
await receive({
|
|
351
|
+
...reply,
|
|
352
|
+
i: message.i
|
|
353
|
+
});
|
|
354
|
+
},
|
|
355
|
+
proxify: false,
|
|
356
|
+
timeout: -1
|
|
357
|
+
});
|
|
358
|
+
try {
|
|
359
|
+
return {
|
|
360
|
+
ok: true,
|
|
361
|
+
value: await rpc.$call(name, ...input === void 0 ? [] : [input]),
|
|
362
|
+
answer
|
|
363
|
+
};
|
|
364
|
+
} catch (error) {
|
|
365
|
+
if (!answer) throw error;
|
|
366
|
+
if (error === notReply) return {
|
|
367
|
+
ok: false,
|
|
368
|
+
error: void 0,
|
|
369
|
+
answer
|
|
370
|
+
};
|
|
371
|
+
return {
|
|
372
|
+
ok: false,
|
|
373
|
+
error: readOperationRpcError(error),
|
|
374
|
+
answer
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
// ../internal/dist/console-signature.js
|
|
379
|
+
/**
|
|
380
|
+
* Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
|
|
381
|
+
* CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
|
|
382
|
+
* its env cannot sign a request. The module uses only Web Crypto, so it runs in Node, Workers, Deno, and browsers.
|
|
383
|
+
*
|
|
384
|
+
* The signature covers this text, one field per line:
|
|
385
|
+
*
|
|
386
|
+
* ```txt
|
|
387
|
+
* vitehub-signature-v1
|
|
388
|
+
* POST
|
|
389
|
+
* /_vitehub/rpc
|
|
390
|
+
* https://app.example.com
|
|
391
|
+
* 1794400000
|
|
392
|
+
* CONSOLE_3F9A12BC
|
|
393
|
+
* <SHA-256 of the body bytes, base64url>
|
|
394
|
+
* <the x-vitehub-caller header>
|
|
395
|
+
* ```
|
|
396
|
+
*/
|
|
397
|
+
/** The signature header: `key=<NAME>, t=<seconds>, origin=<app origin>, body=<SHA-256>, v1=<signature>`. */
|
|
398
|
+
const consoleSignatureHeader = "x-vitehub-signature";
|
|
399
|
+
/** Who calls, as base64url JSON. The signature covers it. See {@link ConsoleCaller}. */
|
|
400
|
+
const consoleCallerHeader = "x-vitehub-caller";
|
|
401
|
+
/** The first line of the signed text. A new format gets a new tag. */
|
|
402
|
+
const consoleSignatureVersion = "vitehub-signature-v1";
|
|
403
|
+
/** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
|
|
404
|
+
const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
|
|
405
|
+
const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
|
|
406
|
+
const encoder = new TextEncoder();
|
|
407
|
+
new TextDecoder();
|
|
408
|
+
const ed25519 = { name: "Ed25519" };
|
|
409
|
+
const pkcs8Prefix = Uint8Array.of(48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32);
|
|
410
|
+
function base64url(bytes) {
|
|
411
|
+
let binary = "";
|
|
412
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
413
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
414
|
+
}
|
|
415
|
+
/** The bytes of a base64url value, or `undefined` when it is not canonical base64url without padding. */
|
|
416
|
+
function fromBase64url(value) {
|
|
417
|
+
if (!/^[\w-]*$/.test(value) || value.length % 4 === 1) return void 0;
|
|
418
|
+
const bytes = Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
|
|
419
|
+
return base64url(bytes) === value ? bytes : void 0;
|
|
420
|
+
}
|
|
421
|
+
function bytesOf(body) {
|
|
422
|
+
if (typeof body === "string") return encoder.encode(body);
|
|
423
|
+
return body instanceof Uint8Array ? Uint8Array.from(body) : new Uint8Array(body);
|
|
424
|
+
}
|
|
425
|
+
/** The SHA-256 of the exact body bytes, base64url. A request without a body hashes zero bytes. */
|
|
426
|
+
async function consoleBodySha256(body = "") {
|
|
427
|
+
return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytesOf(body))));
|
|
428
|
+
}
|
|
429
|
+
/** The text that the signature covers. Fields are joined with `\n`. */
|
|
430
|
+
function consoleSignedText(fields) {
|
|
431
|
+
return [
|
|
432
|
+
consoleSignatureVersion,
|
|
433
|
+
fields.method.toUpperCase(),
|
|
434
|
+
fields.target,
|
|
435
|
+
fields.origin,
|
|
436
|
+
fields.timestamp,
|
|
437
|
+
fields.key,
|
|
438
|
+
fields.bodySha256,
|
|
439
|
+
fields.caller
|
|
440
|
+
].join("\n");
|
|
441
|
+
}
|
|
442
|
+
/** The path and query of a URL, the part of the request target that the signature covers. */
|
|
443
|
+
function requestTarget(url) {
|
|
444
|
+
return `${url.pathname}${url.search}`;
|
|
445
|
+
}
|
|
446
|
+
/** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
|
|
447
|
+
function isConsoleKeyName(name) {
|
|
448
|
+
return keyNamePattern.test(name);
|
|
449
|
+
}
|
|
450
|
+
async function importPrivateKey(seed) {
|
|
451
|
+
const bytes = fromBase64url(seed.trim());
|
|
452
|
+
if (bytes?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_INVALID();
|
|
453
|
+
const der = new Uint8Array(pkcs8Prefix.length + 32);
|
|
454
|
+
der.set(pkcs8Prefix);
|
|
455
|
+
der.set(bytes, pkcs8Prefix.length);
|
|
456
|
+
return await crypto.subtle.importKey("pkcs8", der, ed25519, false, ["sign"]);
|
|
457
|
+
}
|
|
458
|
+
/** The `x-vitehub-caller` value of a caller: its JSON as base64url. */
|
|
459
|
+
function encodeConsoleCaller(caller) {
|
|
460
|
+
return base64url(encoder.encode(JSON.stringify(caller)));
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Sign one request. `url` is the full URL that the request goes to, and `body` is the exact body that it sends. Returns
|
|
464
|
+
* the two headers to add: `x-vitehub-signature` and `x-vitehub-caller`.
|
|
465
|
+
*/
|
|
466
|
+
async function signConsoleRequest(options) {
|
|
467
|
+
if (!isConsoleKeyName(options.key.name)) throw internalErrorDiagnostics.INTERNAL_CONSOLE_KEY_NAME_INVALID({ name: options.key.name });
|
|
468
|
+
const url = new URL(options.url);
|
|
469
|
+
const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
|
|
470
|
+
const bodySha256 = await consoleBodySha256(options.body);
|
|
471
|
+
const caller = encodeConsoleCaller(options.caller);
|
|
472
|
+
const text = consoleSignedText({
|
|
473
|
+
bodySha256,
|
|
474
|
+
caller,
|
|
475
|
+
key: options.key.name,
|
|
476
|
+
method: options.method,
|
|
477
|
+
origin: url.origin,
|
|
478
|
+
target: requestTarget(url),
|
|
479
|
+
timestamp
|
|
480
|
+
});
|
|
481
|
+
const signature = new Uint8Array(await crypto.subtle.sign(ed25519, await importPrivateKey(options.key.privateKey), encoder.encode(text)));
|
|
482
|
+
return {
|
|
483
|
+
[consoleCallerHeader]: caller,
|
|
484
|
+
[consoleSignatureHeader]: `key=${options.key.name}, t=${timestamp}, origin=${url.origin}, body=${bodySha256}, v1=${base64url(signature)}`
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* The signing key of a CLI from its env: the one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable. Returns `undefined`
|
|
489
|
+
* without one. Throws a coded error when there are several, or when the value is not a 32-byte seed.
|
|
490
|
+
*/
|
|
491
|
+
function readConsoleSigningKey(env) {
|
|
492
|
+
const variables = Object.keys(env).filter((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && env[name]?.trim()).sort();
|
|
493
|
+
if (!variables.length) return void 0;
|
|
494
|
+
if (variables.length > 1) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE({
|
|
495
|
+
prefix: consolePrivateKeyPrefix,
|
|
496
|
+
variables: variables.join(", ")
|
|
497
|
+
});
|
|
498
|
+
const variable = variables[0];
|
|
499
|
+
const name = variable.slice(28);
|
|
500
|
+
const privateKey = env[variable].trim();
|
|
501
|
+
if (!isConsoleKeyName(name) || fromBase64url(privateKey)?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID({ variable });
|
|
502
|
+
return {
|
|
503
|
+
name,
|
|
504
|
+
privateKey
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
// ../internal/dist/standard-schema.js
|
|
508
|
+
function readOwn(value, key) {
|
|
509
|
+
if (value === null || Object(value) !== value) return;
|
|
510
|
+
try {
|
|
511
|
+
return Reflect.get(Object(value), key);
|
|
512
|
+
} catch {
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Read a Standard JSON Schema projection without throwing.
|
|
518
|
+
*
|
|
519
|
+
* Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
|
|
520
|
+
* (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
|
|
521
|
+
*/
|
|
522
|
+
function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
|
|
523
|
+
const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
|
|
524
|
+
const project = readOwn(jsonSchema, direction);
|
|
525
|
+
if (typeof project !== "function") return;
|
|
526
|
+
try {
|
|
527
|
+
const result = project.call(jsonSchema, libraryOptions ? {
|
|
528
|
+
target,
|
|
529
|
+
libraryOptions
|
|
530
|
+
} : { target });
|
|
531
|
+
return isRecordOrFunction(result) ? result : void 0;
|
|
532
|
+
} catch {
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
// ../internal/dist/operation-definition.js
|
|
537
|
+
const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
|
|
538
|
+
const kinds = /* @__PURE__ */ new Set([
|
|
539
|
+
"read",
|
|
540
|
+
"write",
|
|
541
|
+
"destructive"
|
|
542
|
+
]);
|
|
543
|
+
function invalidDefinition(name, reason) {
|
|
544
|
+
return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
|
|
545
|
+
}
|
|
546
|
+
function checkDefinition(definition) {
|
|
547
|
+
if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
|
|
548
|
+
const { name } = definition;
|
|
549
|
+
if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
|
|
550
|
+
if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
|
|
551
|
+
const { section } = definition;
|
|
552
|
+
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 ':'.");
|
|
553
|
+
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.");
|
|
554
|
+
if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
|
|
555
|
+
const input = definition.input;
|
|
556
|
+
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.");
|
|
557
|
+
if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
|
|
558
|
+
const { maxRequestBytes } = definition;
|
|
559
|
+
if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
|
|
560
|
+
if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
|
|
561
|
+
const { mcp } = definition;
|
|
562
|
+
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.");
|
|
563
|
+
}
|
|
564
|
+
/** The default limit of a call, in bytes. */
|
|
565
|
+
const defaultRequestBytes = 65536;
|
|
566
|
+
/** The top-level setup commands of the CLI, such as `vitehub status`. They run before the project config loads. */
|
|
567
|
+
const setupCommandNames = [
|
|
568
|
+
"init",
|
|
569
|
+
"add",
|
|
570
|
+
"remove",
|
|
571
|
+
"status",
|
|
572
|
+
"catalog",
|
|
573
|
+
"link",
|
|
574
|
+
"unlink",
|
|
575
|
+
"deploy",
|
|
576
|
+
"deployments",
|
|
577
|
+
"drain",
|
|
578
|
+
"login",
|
|
579
|
+
"logout",
|
|
580
|
+
"update",
|
|
581
|
+
"whoami",
|
|
582
|
+
"apps"
|
|
583
|
+
];
|
|
584
|
+
/** CLI namespaces owned by built-in commands. */
|
|
585
|
+
const reservedOperationNamespaces = [
|
|
586
|
+
"inspect",
|
|
587
|
+
"provision",
|
|
588
|
+
"seed",
|
|
589
|
+
...setupCommandNames
|
|
590
|
+
];
|
|
591
|
+
function isOperation(value) {
|
|
592
|
+
try {
|
|
593
|
+
checkDefinition(value);
|
|
594
|
+
return true;
|
|
595
|
+
} catch {
|
|
596
|
+
return false;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function isSectionId(section) {
|
|
600
|
+
return typeof section === "string" && section !== "" && !section.includes(":");
|
|
601
|
+
}
|
|
602
|
+
/** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
|
|
603
|
+
function operationInputJsonSchema(operation) {
|
|
604
|
+
return standardJsonSchema(operation.input, "input") ?? { type: "object" };
|
|
605
|
+
}
|
|
606
|
+
// ../internal/dist/operations.js
|
|
607
|
+
/** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
|
|
608
|
+
const operationRpcHeader = "x-vitehub-console";
|
|
609
|
+
/** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
|
|
610
|
+
const operationRootHeader = "x-vitehub-root";
|
|
611
|
+
const operationExpectedRootsHeader = "x-vitehub-expected-roots";
|
|
612
|
+
/** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
|
|
613
|
+
function projectRootHash(root) {
|
|
614
|
+
const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
615
|
+
let first = 3735928559;
|
|
616
|
+
let second = 1103547991;
|
|
617
|
+
for (let index = 0; index < normalized.length; index++) {
|
|
618
|
+
const code = normalized.charCodeAt(index);
|
|
619
|
+
first = Math.imul(first ^ code, 2654435761);
|
|
620
|
+
second = Math.imul(second ^ code, 1597334677);
|
|
621
|
+
}
|
|
622
|
+
first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
|
|
623
|
+
second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
|
|
624
|
+
return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
|
|
625
|
+
}
|
|
626
|
+
/** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
|
|
627
|
+
const operationSurfaceHeader = "x-vitehub-surface";
|
|
628
|
+
/** Generated CLI commands ask the server to check confirmation after it parses the input. */
|
|
629
|
+
const operationConfirmationHeader = "x-vitehub-confirmation";
|
|
630
|
+
function pluginName(plugin) {
|
|
631
|
+
const name = Reflect.get(plugin, "name");
|
|
632
|
+
return String(name) === name && name ? name : "unnamed plugin";
|
|
633
|
+
}
|
|
634
|
+
/** Reads `plugin.vitehub.operations` from resolved Vite plugins. The same module and export from two plugins counts once. */
|
|
635
|
+
async function collectOperationContributions(plugins) {
|
|
636
|
+
const collected = /* @__PURE__ */ new Map();
|
|
637
|
+
for (const plugin of plugins) {
|
|
638
|
+
if (!isRecordOrFunction(plugin) || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
639
|
+
const declared = Reflect.get(Object(Reflect.get(plugin, "vitehub")), "operations");
|
|
640
|
+
if (declared === void 0) continue;
|
|
641
|
+
const entries = declared instanceof Function ? await declared() : declared;
|
|
642
|
+
const owner = pluginName(plugin);
|
|
643
|
+
if (!Array.isArray(entries)) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} sets vitehub.operations, which must be a list of { module, export }.` });
|
|
644
|
+
for (const entry of entries) {
|
|
645
|
+
if (!isRecordOrFunction(entry) || String(entry.module) !== entry.module || !entry.module) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} contributes an operation entry without a module.` });
|
|
646
|
+
const exportName = String(entry.export) === entry.export && entry.export ? entry.export : "default";
|
|
647
|
+
const key = `${entry.module}#${exportName}`;
|
|
648
|
+
if (collected.has(key)) continue;
|
|
649
|
+
collected.set(key, {
|
|
650
|
+
module: entry.module,
|
|
651
|
+
export: exportName,
|
|
652
|
+
plugin: owner,
|
|
653
|
+
...entry.load instanceof Function ? { load: entry.load } : {},
|
|
654
|
+
...entry.runtime === false ? { runtime: false } : {}
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return [...collected.values()];
|
|
659
|
+
}
|
|
660
|
+
/** Operations of one module export, flat. A single operation or an array both work. */
|
|
661
|
+
function operationsOf(value) {
|
|
662
|
+
const list = Array.isArray(value) ? value : [value];
|
|
663
|
+
const operations = [];
|
|
664
|
+
for (const item of list) {
|
|
665
|
+
if (!isOperation(item)) throw invalidDefinition(isRecordOrFunction(item) ? item.name : void 0, "a contributed export must hold defineOperation() results.");
|
|
666
|
+
operations.push(item);
|
|
667
|
+
}
|
|
668
|
+
return operations;
|
|
669
|
+
}
|
|
670
|
+
/** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
|
|
671
|
+
function operationCliPath(operation) {
|
|
672
|
+
const dot = operation.name.indexOf(".");
|
|
673
|
+
const cli = operationCliOptions(operation);
|
|
674
|
+
return {
|
|
675
|
+
command: cli?.command ?? operation.name.slice(dot + 1),
|
|
676
|
+
namespace: cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
/** The CLI options of an operation, or undefined for an operation without options or with `cli: false`. */
|
|
680
|
+
function operationCliOptions(operation) {
|
|
681
|
+
return operation.cli || void 0;
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
|
|
685
|
+
* Claude reject a dot in a tool name. `content.publish` is `content_publish`.
|
|
686
|
+
*/
|
|
687
|
+
function operationToolName(name) {
|
|
688
|
+
return name.replace(/[^\w-]/g, "_");
|
|
689
|
+
}
|
|
690
|
+
/** 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`. */
|
|
691
|
+
function createOperationRegistry(sources) {
|
|
692
|
+
const byName = /* @__PURE__ */ new Map();
|
|
693
|
+
for (const source of sources) for (const operation of source.operations) {
|
|
694
|
+
const existing = byName.get(operation.name);
|
|
695
|
+
if (existing && existing.operation !== operation) {
|
|
696
|
+
const owners = [existing.plugin, source.plugin].filter(Boolean).join(" and ");
|
|
697
|
+
throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] Two operations are named ${JSON.stringify(operation.name)}${owners ? ` (${owners})` : ""}.` });
|
|
698
|
+
}
|
|
699
|
+
byName.set(operation.name, {
|
|
700
|
+
operation,
|
|
701
|
+
...source.plugin ? { plugin: source.plugin } : {}
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
|
|
705
|
+
const commands = /* @__PURE__ */ new Map();
|
|
706
|
+
for (const operation of operations) {
|
|
707
|
+
if (operation.cli === false) continue;
|
|
708
|
+
const { command, namespace } = operationCliPath(operation);
|
|
709
|
+
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.`);
|
|
710
|
+
const key = `${namespace} ${command}`;
|
|
711
|
+
const other = commands.get(key);
|
|
712
|
+
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}\`.` });
|
|
713
|
+
commands.set(key, operation);
|
|
714
|
+
}
|
|
715
|
+
const tools = /* @__PURE__ */ new Map();
|
|
716
|
+
for (const operation of operations) {
|
|
717
|
+
if (operation.mcp === false) continue;
|
|
718
|
+
const tool = operationToolName(operation.name);
|
|
719
|
+
const other = tools.get(tool);
|
|
720
|
+
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)}.` });
|
|
721
|
+
tools.set(tool, operation);
|
|
722
|
+
}
|
|
723
|
+
return {
|
|
724
|
+
get: (name) => byName.get(name)?.operation,
|
|
725
|
+
list: () => [...operations]
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
/** Issues of a failed Standard Schema check as one short line per issue. */
|
|
729
|
+
function describeInputIssues(issues) {
|
|
730
|
+
return issues.slice(0, 5).map((issue) => {
|
|
731
|
+
const path = (issue.path ?? []).map((segment) => String(isRecordOrFunction(segment) && "key" in segment ? segment.key : segment)).join(".");
|
|
732
|
+
return path ? `${path}: ${issue.message}` : issue.message;
|
|
733
|
+
}).join(" ");
|
|
734
|
+
}
|
|
735
|
+
function describeInputFields(schema) {
|
|
736
|
+
const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).map((shape) => {
|
|
737
|
+
if (!isRecordOrFunction(shape) || !isRecordOrFunction(shape.properties)) return void 0;
|
|
738
|
+
const required = Array.isArray(shape.required) ? shape.required : [];
|
|
739
|
+
const fields = Object.keys(shape.properties).map((field) => required.includes(field) ? field : `${field}?`);
|
|
740
|
+
return fields.length ? `{ ${fields.join(", ")} }` : "{}";
|
|
741
|
+
});
|
|
742
|
+
return shapes.every((shape) => shape !== void 0) ? shapes.join(" or ") : void 0;
|
|
743
|
+
}
|
|
744
|
+
/** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
|
|
745
|
+
async function parseOperationInput(operation, input) {
|
|
746
|
+
const result = await operation.input["~standard"].validate(input ?? {});
|
|
747
|
+
if (!result.issues) return result.value;
|
|
748
|
+
const fields = describeInputFields(operationInputJsonSchema(operation));
|
|
749
|
+
const issues = describeInputIssues(result.issues);
|
|
750
|
+
const message = `Invalid input for ${operation.name}. ${issues}${fields ? `${/[.!?]$/.test(issues) ? "" : "."} ${operation.name} takes ${fields}.` : ""}`;
|
|
751
|
+
throw Object.assign(internalErrorDiagnostics.INTERNAL_R0022({ message }), { status: 400 });
|
|
752
|
+
}
|
|
753
|
+
/** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
|
|
754
|
+
function operationCall(operation, input) {
|
|
755
|
+
return {
|
|
756
|
+
kind: operation.kind,
|
|
757
|
+
readOnly: operation.readOnlyWhen?.(input) === true
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
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.";
|
|
761
|
+
/** Headers of an operation call, without a signature. */
|
|
762
|
+
function operationHeaders() {
|
|
763
|
+
const headers = new Headers();
|
|
764
|
+
headers.set("accept", "application/json");
|
|
765
|
+
headers.set("content-type", "application/json");
|
|
766
|
+
headers.set(operationRpcHeader, "1");
|
|
767
|
+
headers.set(operationSurfaceHeader, "cli");
|
|
768
|
+
return headers;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* The headers of one operation call to a deployed app: {@link operationHeaders}, and the signature of `body` when the
|
|
772
|
+
* env has a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. The CLI signs as itself, `via: "cli"`. Throws a `TypeError` for a
|
|
773
|
+
* malformed private key.
|
|
774
|
+
*/
|
|
775
|
+
async function signedOperationHeaders(env, url, body) {
|
|
776
|
+
const headers = operationHeaders();
|
|
777
|
+
const key = readConsoleSigningKey(env);
|
|
778
|
+
if (key) {
|
|
779
|
+
const signed = await signConsoleRequest({
|
|
780
|
+
body,
|
|
781
|
+
caller: { via: "cli" },
|
|
782
|
+
key,
|
|
783
|
+
method: "POST",
|
|
784
|
+
url
|
|
785
|
+
});
|
|
786
|
+
for (const [name, value] of Object.entries(signed)) headers.set(name, value);
|
|
787
|
+
}
|
|
788
|
+
return headers;
|
|
789
|
+
}
|
|
790
|
+
function unreachable(message, status = 503) {
|
|
791
|
+
const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
|
|
792
|
+
return {
|
|
793
|
+
ok: false,
|
|
794
|
+
code: error.code,
|
|
795
|
+
fix: error.fix,
|
|
796
|
+
message,
|
|
797
|
+
status
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
function hasCredentials(env) {
|
|
801
|
+
return Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && Boolean(env[name]));
|
|
802
|
+
}
|
|
803
|
+
/** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
|
|
804
|
+
async function callOperation(target, name, input) {
|
|
805
|
+
let origin = "the ViteHub app";
|
|
806
|
+
try {
|
|
807
|
+
const base = new URL(target.url);
|
|
808
|
+
if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
|
|
809
|
+
const url = new URL(operationRpcPath.slice(1), base);
|
|
810
|
+
origin = url.origin;
|
|
811
|
+
const env = target.roots?.length ? {} : target.env;
|
|
812
|
+
if (!target.authorization) try {
|
|
813
|
+
readConsoleSigningKey(env);
|
|
814
|
+
} catch (error) {
|
|
815
|
+
return {
|
|
816
|
+
ok: false,
|
|
817
|
+
code: "INTERNAL_R0024",
|
|
818
|
+
fix: "Run `vitehub secret console-key` for a new key pair. Set its private key here and its public key on the app.",
|
|
819
|
+
message: error instanceof Error ? error.message : String(error),
|
|
820
|
+
status: 401
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
|
|
824
|
+
const signal = target.signal ?? AbortSignal.timeout(target.timeout ?? 3e4);
|
|
825
|
+
const headers = target.authorization ? operationHeaders() : await signedOperationHeaders(env, url, body);
|
|
826
|
+
if (target.authorization) headers.set("authorization", target.authorization);
|
|
827
|
+
if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
|
|
828
|
+
if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
|
|
829
|
+
signal.throwIfAborted();
|
|
830
|
+
const response = await (target.fetch ?? fetch)(url.href, {
|
|
831
|
+
body,
|
|
832
|
+
headers,
|
|
833
|
+
method: "POST",
|
|
834
|
+
redirect: "manual",
|
|
835
|
+
signal
|
|
836
|
+
});
|
|
837
|
+
const text = await response.text();
|
|
838
|
+
let json;
|
|
839
|
+
try {
|
|
840
|
+
json = text ? JSON.parse(text) : void 0;
|
|
841
|
+
} catch {
|
|
842
|
+
json = void 0;
|
|
843
|
+
}
|
|
844
|
+
return {
|
|
845
|
+
body: json,
|
|
846
|
+
response
|
|
847
|
+
};
|
|
848
|
+
});
|
|
849
|
+
const { response } = outcome.answer;
|
|
850
|
+
const served = response.headers.get(operationRootHeader);
|
|
851
|
+
if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
|
|
852
|
+
const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
|
|
853
|
+
const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
|
|
854
|
+
return {
|
|
855
|
+
ok: false,
|
|
856
|
+
code: error.code,
|
|
857
|
+
fix: error.fix,
|
|
858
|
+
message,
|
|
859
|
+
status: 409
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
if (outcome.ok) return {
|
|
863
|
+
ok: true,
|
|
864
|
+
value: outcome.value
|
|
865
|
+
};
|
|
866
|
+
const failure = outcome.error ?? readOperationRpcError(isRecordOrFunction(outcome.answer.body) ? {
|
|
867
|
+
status: response.status,
|
|
868
|
+
...outcome.answer.body
|
|
869
|
+
} : void 0);
|
|
870
|
+
if (failure) {
|
|
871
|
+
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."}`;
|
|
872
|
+
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;
|
|
873
|
+
return {
|
|
874
|
+
ok: false,
|
|
875
|
+
...failure
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
|
|
879
|
+
return unreachable(`${url.origin} did not answer as a ViteHub app (HTTP ${response.status}). ${response.status === 404 && !target.roots?.length ? "A production build answers ViteHub operations only when `vitehub()` sets `console`. Set it, deploy again, and pass the origin of that app." : "Pass the origin of an app that runs ViteHub."}`, response.status);
|
|
880
|
+
} catch (error) {
|
|
881
|
+
return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
|
|
886
|
+
* started. A call on `--url` goes through the Console when `consoleRoute` finds the app there. Never throws. Without a
|
|
887
|
+
* dev server the result is an `INTERNAL_R0024` failure that says to start one.
|
|
888
|
+
*/
|
|
889
|
+
async function callOperationFromCli(call, name, input) {
|
|
890
|
+
let roots;
|
|
891
|
+
try {
|
|
892
|
+
roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
|
|
893
|
+
} catch {
|
|
894
|
+
roots = [call.rootDir];
|
|
895
|
+
}
|
|
896
|
+
const target = {
|
|
897
|
+
...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
|
|
898
|
+
env: call.env,
|
|
899
|
+
...call.fetch ? { fetch: call.fetch } : {}
|
|
900
|
+
};
|
|
901
|
+
if (call.url && call.consoleRoute && !hasCredentials(call.env)) {
|
|
902
|
+
const signal = AbortSignal.timeout(call.timeout ?? 3e4);
|
|
903
|
+
const route = await call.consoleRoute(call.url, signal);
|
|
904
|
+
return await callOperation({
|
|
905
|
+
...target,
|
|
906
|
+
...route ? { authorization: route.authorization } : {},
|
|
907
|
+
signal,
|
|
908
|
+
url: route?.target ?? call.url
|
|
909
|
+
}, name, input);
|
|
910
|
+
}
|
|
911
|
+
const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
|
|
912
|
+
if (!url) return unreachable(`No dev server is running for ${roots.at(-1)}.`);
|
|
913
|
+
return await callOperation({
|
|
914
|
+
...target,
|
|
915
|
+
...call.url ? {} : { roots },
|
|
916
|
+
...call.timeout ? { timeout: call.timeout } : {},
|
|
917
|
+
url
|
|
918
|
+
}, name, input);
|
|
919
|
+
}
|
|
920
|
+
// ../internal/dist/provision-state.js
|
|
921
|
+
const PROVISION_STATE_FILE = ".vitehub/provision.json";
|
|
922
|
+
function getProvisionStatePath(rootDir) {
|
|
923
|
+
return resolve(rootDir, PROVISION_STATE_FILE);
|
|
924
|
+
}
|
|
925
|
+
async function readProvisionState(rootDir) {
|
|
926
|
+
const path = getProvisionStatePath(rootDir);
|
|
927
|
+
try {
|
|
928
|
+
return parseProvisionState(await readFile(path, "utf8"));
|
|
929
|
+
} catch (cause) {
|
|
930
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
|
|
931
|
+
throw internalErrorDiagnostics.INTERNAL_R0014({
|
|
932
|
+
path,
|
|
933
|
+
cause
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
function readProvisionStateSync(rootDir) {
|
|
938
|
+
const path = getProvisionStatePath(rootDir);
|
|
939
|
+
try {
|
|
940
|
+
return parseProvisionState(readFileSync(path, "utf8"));
|
|
941
|
+
} catch (cause) {
|
|
942
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
|
|
943
|
+
throw internalErrorDiagnostics.INTERNAL_R0014({
|
|
944
|
+
path,
|
|
945
|
+
cause
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
async function writeProvisionState(rootDir, next) {
|
|
950
|
+
const path = getProvisionStatePath(rootDir);
|
|
951
|
+
const merged = mergeProvisionState(await readProvisionState(rootDir), next);
|
|
952
|
+
await mkdir(dirname(path), { recursive: true });
|
|
953
|
+
await writeFile(path, `${JSON.stringify(sortState(merged), null, 2)}\n`, "utf8");
|
|
954
|
+
}
|
|
955
|
+
function mergeProvisionState(base, next) {
|
|
956
|
+
const merged = structuredClone(base);
|
|
957
|
+
for (const provider of Object.keys(next)) {
|
|
958
|
+
const categories = next[provider];
|
|
959
|
+
if (!categories) continue;
|
|
960
|
+
const target = merged[provider] ??= {};
|
|
961
|
+
for (const [category, ids] of Object.entries(categories)) setOwn(target, category, {
|
|
962
|
+
...(Object.hasOwn(target, category) ? target[category] : void 0) ?? {},
|
|
963
|
+
...ids
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
return merged;
|
|
967
|
+
}
|
|
968
|
+
function parseProvisionState(raw) {
|
|
969
|
+
const parsed = JSON.parse(raw);
|
|
970
|
+
if (!isRecord(parsed)) return {};
|
|
971
|
+
const state = {};
|
|
972
|
+
for (const provider of ["cloudflare", "vercel"]) {
|
|
973
|
+
const categories = parsed[provider];
|
|
974
|
+
if (!isRecord(categories)) continue;
|
|
975
|
+
const validCategories = {};
|
|
976
|
+
for (const [category, ids] of Object.entries(categories)) {
|
|
977
|
+
if (!isRecord(ids)) continue;
|
|
978
|
+
const validIds = {};
|
|
979
|
+
for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
|
|
980
|
+
if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
|
|
981
|
+
}
|
|
982
|
+
if (Object.keys(validCategories).length) state[provider] = validCategories;
|
|
983
|
+
}
|
|
984
|
+
return state;
|
|
985
|
+
}
|
|
986
|
+
function setOwn(target, key, value) {
|
|
987
|
+
Object.defineProperty(target, key, {
|
|
988
|
+
configurable: true,
|
|
989
|
+
enumerable: true,
|
|
990
|
+
value,
|
|
991
|
+
writable: true
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
function sortState(state) {
|
|
995
|
+
return sortKeys(state);
|
|
996
|
+
}
|
|
997
|
+
function sortKeys(value) {
|
|
998
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
|
999
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]));
|
|
1000
|
+
}
|
|
1001
|
+
// src/provision.ts
|
|
1002
|
+
const PROVISION_HOSTS = ["cloudflare", "vercel"];
|
|
1003
|
+
const HOST_CREDENTIALS = {
|
|
1004
|
+
cloudflare: "CLOUDFLARE_ACCOUNT_ID and a Cloudflare login (`wrangler login` or CLOUDFLARE_API_TOKEN)",
|
|
1005
|
+
vercel: "VERCEL_TOKEN"
|
|
1006
|
+
};
|
|
1007
|
+
const USAGE = {
|
|
1008
|
+
run: "vitehub provision run [--host <cloudflare|vercel>] [--dry-run] [--json]",
|
|
1009
|
+
status: "vitehub provision status [--host <cloudflare|vercel>] [--json]"
|
|
1010
|
+
};
|
|
1011
|
+
/** Whether ViteHub can provision resources on `host`. Only Cloudflare and Vercel have Provision Steps. */
|
|
1012
|
+
function isProvisionHost(value) {
|
|
1013
|
+
return PROVISION_HOSTS.some((host) => host === value);
|
|
1014
|
+
}
|
|
1015
|
+
function setVariable(env, name, value) {
|
|
1016
|
+
return env[name]?.trim() || !value ? env : {
|
|
1017
|
+
...env,
|
|
1018
|
+
[name]: value
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* The environment of a Provision Step: `env` with the host credentials that `resolveHostCredentials` found, such as a
|
|
1023
|
+
* `wrangler login` token, and the account and project ids of the host link. The selected link wins over environment scope.
|
|
1024
|
+
*/
|
|
1025
|
+
function provisionEnv(env, credentials, link = {}) {
|
|
1026
|
+
if (!credentials.ok) return env;
|
|
1027
|
+
if (credentials.host === "cloudflare") return {
|
|
1028
|
+
...setVariable(setVariable(env, "CLOUDFLARE_API_TOKEN", credentials.token), "CLOUDFLARE_ACCOUNT_ID", credentials.accountId),
|
|
1029
|
+
...link.accountId ? { CLOUDFLARE_ACCOUNT_ID: link.accountId } : {}
|
|
1030
|
+
};
|
|
1031
|
+
if (credentials.host === "vercel") {
|
|
1032
|
+
const teamId = credentials.teamId;
|
|
1033
|
+
const resolved = setVariable(setVariable(env, "VERCEL_TOKEN", credentials.token), "VERCEL_TEAM_ID", teamId);
|
|
1034
|
+
if (!link.accountId && !link.projectId) return resolved;
|
|
1035
|
+
return {
|
|
1036
|
+
...resolved,
|
|
1037
|
+
...link.accountId ? {
|
|
1038
|
+
VERCEL_TEAM_ID: link.accountId.startsWith("team_") ? link.accountId : void 0,
|
|
1039
|
+
VERCEL_ORG_ID: void 0
|
|
1040
|
+
} : {},
|
|
1041
|
+
...link.projectId ? { VERCEL_PROJECT_ID: link.projectId } : {}
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
return env;
|
|
1045
|
+
}
|
|
1046
|
+
function provisionHostEnv(env, credentials, link) {
|
|
1047
|
+
return provisionEnv(link?.host === "vercel" && !link.project.id ? {
|
|
1048
|
+
...env,
|
|
1049
|
+
VERCEL_PROJECT_ID: void 0
|
|
1050
|
+
} : env, credentials, {
|
|
1051
|
+
...link?.account?.id ? { accountId: link.account.id } : {},
|
|
1052
|
+
...link?.project.id ? { projectId: link.project.id } : {}
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
function parseArgs(command, args) {
|
|
1056
|
+
const parsed = {
|
|
1057
|
+
dryRun: false,
|
|
1058
|
+
help: false,
|
|
1059
|
+
json: false
|
|
1060
|
+
};
|
|
1061
|
+
for (let index = 0; index < args.length; index++) {
|
|
1062
|
+
const arg = args[index];
|
|
1063
|
+
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
1064
|
+
else if (arg === "--json") parsed.json = true;
|
|
1065
|
+
else if (arg === "--dry-run" && command === "run") parsed.dryRun = true;
|
|
1066
|
+
else if (arg === "--host") {
|
|
1067
|
+
const host = args[index + 1];
|
|
1068
|
+
if (!host || host.startsWith("-")) parsed.error = "Option --host requires a value.";
|
|
1069
|
+
else {
|
|
1070
|
+
parsed.host = host;
|
|
1071
|
+
index++;
|
|
1072
|
+
}
|
|
1073
|
+
} else if (arg?.startsWith("--host=")) {
|
|
1074
|
+
const host = arg.slice(7);
|
|
1075
|
+
if (!host) parsed.error = "Option --host requires a value.";
|
|
1076
|
+
else parsed.host = host;
|
|
1077
|
+
} else if (arg === "--provider" || arg?.startsWith("--provider=")) {
|
|
1078
|
+
const value = arg === "--provider" ? args[index + 1] : arg.slice(11);
|
|
1079
|
+
const host = value && !value.startsWith("-") ? value : "<cloudflare|vercel>";
|
|
1080
|
+
return {
|
|
1081
|
+
...parsed,
|
|
1082
|
+
error: `Option --provider is now --host.\nfix: run \`vitehub provision ${command} --host ${host}\`.`
|
|
1083
|
+
};
|
|
1084
|
+
} else if (arg) parsed.error = `Unknown provision argument: ${arg}`;
|
|
1085
|
+
}
|
|
1086
|
+
return parsed;
|
|
1087
|
+
}
|
|
1088
|
+
function writeUsage(command, stream) {
|
|
1089
|
+
const lines = command === "run" ? [
|
|
1090
|
+
`Usage: ${USAGE.run}`,
|
|
1091
|
+
"",
|
|
1092
|
+
"Idempotently creates missing host resources for the app's Definitions. `vitehub deploy` runs it before each deploy.",
|
|
1093
|
+
"Uses the credentials of `vitehub deploy`: environment variables first, then the `wrangler login` session.",
|
|
1094
|
+
"Never deletes resources. Changes an existing resource only for a planned update, such as D1 read replication.",
|
|
1095
|
+
"",
|
|
1096
|
+
"Options:",
|
|
1097
|
+
" --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`:",
|
|
1098
|
+
" the default target of .vitehub/link.json, else the only one, else `host` in vitehub().",
|
|
1099
|
+
" --dry-run Print the plan without applying it.",
|
|
1100
|
+
" --json Print one JSON result to stdout.",
|
|
1101
|
+
" -h, --help Show this help."
|
|
1102
|
+
] : [
|
|
1103
|
+
`Usage: ${USAGE.status}`,
|
|
1104
|
+
"",
|
|
1105
|
+
"Shows the ids recorded in .vitehub/provision.json and the actions the current plan would apply.",
|
|
1106
|
+
"Marks recorded ids that no Definition declares, with how to delete them on the host.",
|
|
1107
|
+
"Never creates or deletes provider resources, and never writes Provision State.",
|
|
1108
|
+
"",
|
|
1109
|
+
"Options:",
|
|
1110
|
+
" --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`.",
|
|
1111
|
+
" --json Print one JSON result to stdout.",
|
|
1112
|
+
" -h, --help Show this help."
|
|
1113
|
+
];
|
|
1114
|
+
stream.write(`${lines.join("\n")}\n\n`);
|
|
1115
|
+
}
|
|
1116
|
+
async function resolveHost(command, parsed, context) {
|
|
1117
|
+
if (parsed.help) {
|
|
1118
|
+
writeUsage(command, context.stdout);
|
|
1119
|
+
return { exitCode: 0 };
|
|
1120
|
+
}
|
|
1121
|
+
if (parsed.error) {
|
|
1122
|
+
context.stderr.write(`${parsed.error}\n`);
|
|
1123
|
+
writeUsage(command, context.stderr);
|
|
1124
|
+
return { exitCode: 1 };
|
|
1125
|
+
}
|
|
1126
|
+
let host = parsed.host;
|
|
1127
|
+
let link;
|
|
1128
|
+
if (host === void 0) {
|
|
1129
|
+
const { resolveDefaultDeployTarget } = await import("./deploy-CqR6pJa-.js").then((n) => n.n);
|
|
1130
|
+
try {
|
|
1131
|
+
const target = await resolveDefaultDeployTarget(resolveViteHubProjectRoot(context.rootDir), context.env, `vitehub provision ${command}`);
|
|
1132
|
+
host = target.host;
|
|
1133
|
+
link = target.link;
|
|
1134
|
+
} catch (error) {
|
|
1135
|
+
context.stderr.write(`${(await import("@vite-hub/runtime")).formatRuntimeDiagnosticError(error)}\n`);
|
|
1136
|
+
return { exitCode: 1 };
|
|
1137
|
+
}
|
|
1138
|
+
if (!isProvisionHost(host)) {
|
|
1139
|
+
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`);
|
|
1140
|
+
return { exitCode: 1 };
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
if (!isProvisionHost(host)) {
|
|
1144
|
+
context.stderr.write("Provision requires --host cloudflare|vercel.\n");
|
|
1145
|
+
writeUsage(command, context.stderr);
|
|
1146
|
+
return { exitCode: 1 };
|
|
1147
|
+
}
|
|
1148
|
+
if (parsed.host === "vercel") link = (await (await import("./link-BRNWNqT9.js").then((n) => n.c)).readSetupLinks(context.rootDir)).targets.find((target) => target.host === "vercel");
|
|
1149
|
+
return {
|
|
1150
|
+
host,
|
|
1151
|
+
...link ? { link } : {}
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
function hasHostCredentials(host, env) {
|
|
1155
|
+
return Boolean(host === "cloudflare" ? resolveCloudflareProvisionConfig(env) : resolveVercelProvisionConfig(env));
|
|
1156
|
+
}
|
|
1157
|
+
async function withHostCredentials(host, context, projectRoot, link) {
|
|
1158
|
+
const credentials = await resolveHostCredentials(host, {
|
|
1159
|
+
cwd: host === "vercel" ? projectRoot : context.rootDir,
|
|
1160
|
+
env: context.env,
|
|
1161
|
+
...context.runHostCli ? { run: context.runHostCli } : {}
|
|
1162
|
+
});
|
|
1163
|
+
const target = host === "vercel" ? await (await import("./vercel-B5CJLsT0.js").then((n) => n.c)).resolveVercelTarget(projectRoot, context.env, link) : link;
|
|
1164
|
+
return {
|
|
1165
|
+
...context,
|
|
1166
|
+
env: provisionHostEnv(context.env, credentials, target)
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
async function planProvision(provider, context, steps, json) {
|
|
1170
|
+
return await planProvisionSteps(provider, [...steps], {
|
|
1171
|
+
env: context.env,
|
|
1172
|
+
fetch: globalThis.fetch,
|
|
1173
|
+
logger: {
|
|
1174
|
+
log: (message) => (json ? context.stderr : context.stdout).write(`${message}\n`),
|
|
1175
|
+
warn: (message) => {
|
|
1176
|
+
if (!json) context.stderr.write(`${message}\n`);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
/** The path of the Provision State file of `rootDir` as the user sees it from `cwd`, such as `app/.vitehub/provision.json` in a Nuxt app. */
|
|
1182
|
+
function provisionStateFile(rootDir, cwd) {
|
|
1183
|
+
return relative(cwd, getProvisionStatePath(rootDir));
|
|
1184
|
+
}
|
|
1185
|
+
function findUndeclaredEntries(provider, recorded, steps, env, stateFile) {
|
|
1186
|
+
const categories = /* @__PURE__ */ new Map();
|
|
1187
|
+
const unverifiedDeclarations = /* @__PURE__ */ new Set();
|
|
1188
|
+
const activeDeclarations = /* @__PURE__ */ new Set();
|
|
1189
|
+
for (const step of steps) {
|
|
1190
|
+
if (step.provider !== provider) continue;
|
|
1191
|
+
const described = step.recordedState?.({ env }) ?? [];
|
|
1192
|
+
for (const category of described) categories.set(category.category, category);
|
|
1193
|
+
if (described.some((category) => category.declared.length)) for (const category of described) activeDeclarations.add(category.category);
|
|
1194
|
+
if (described.some((category) => category.declared.some((key) => {
|
|
1195
|
+
const ids = recorded[category.category] ?? {};
|
|
1196
|
+
const id = Object.hasOwn(ids, key) ? ids[key] : void 0;
|
|
1197
|
+
const expected = category.declaredResourceIdentity?.(key);
|
|
1198
|
+
const identity = id === void 0 ? void 0 : category.resourceIdentity ? category.resourceIdentity({
|
|
1199
|
+
id,
|
|
1200
|
+
key
|
|
1201
|
+
}) : id;
|
|
1202
|
+
return expected === void 0 || identity === void 0 || identity !== expected;
|
|
1203
|
+
}))) for (const category of described) unverifiedDeclarations.add(category.category);
|
|
1204
|
+
}
|
|
1205
|
+
const resourceIdentity = (category, key, id) => {
|
|
1206
|
+
const describe = categories.get(category)?.resourceIdentity;
|
|
1207
|
+
return describe ? describe({
|
|
1208
|
+
id,
|
|
1209
|
+
key
|
|
1210
|
+
}) : id;
|
|
1211
|
+
};
|
|
1212
|
+
const isDeclared = (category, key, id) => {
|
|
1213
|
+
const description = categories.get(category);
|
|
1214
|
+
if (!description?.declared.includes(key)) return false;
|
|
1215
|
+
const expected = description.declaredResourceIdentity?.(key);
|
|
1216
|
+
const identity = resourceIdentity(category, key, id);
|
|
1217
|
+
return expected === void 0 || identity === void 0 || identity === expected;
|
|
1218
|
+
};
|
|
1219
|
+
const declaredById = /* @__PURE__ */ new Map();
|
|
1220
|
+
for (const [category, ids] of Object.entries(recorded)) for (const [key, id] of Object.entries(ids)) {
|
|
1221
|
+
const identity = resourceIdentity(category, key, id);
|
|
1222
|
+
if (identity !== void 0 && isDeclared(category, key, id) && !declaredById.has(identity)) declaredById.set(identity, `${category} ${JSON.stringify(key)}`);
|
|
1223
|
+
}
|
|
1224
|
+
const stateEdit = `remove the entry from ${stateFile}`;
|
|
1225
|
+
const entries = [];
|
|
1226
|
+
for (const [category, ids] of Object.entries(recorded)) for (const [key, id] of Object.entries(ids)) {
|
|
1227
|
+
if (isDeclared(category, key, id)) continue;
|
|
1228
|
+
const identity = resourceIdentity(category, key, id);
|
|
1229
|
+
const sharedWith = identity === void 0 ? void 0 : declaredById.get(identity);
|
|
1230
|
+
let fix;
|
|
1231
|
+
if (sharedWith) fix = `${sharedWith} uses the same id, so keep the resource and only ${stateEdit}.`;
|
|
1232
|
+
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.";
|
|
1233
|
+
else fix = `No Definition declares it. If no deployment uses ${id}, ${categories.get(category)?.deleteHint({
|
|
1234
|
+
id,
|
|
1235
|
+
key
|
|
1236
|
+
}) ?? `delete resource ${id} in the ${provider === "cloudflare" ? "Cloudflare" : "Vercel"} dashboard`}, then ${stateEdit}.`;
|
|
1237
|
+
entries.push({
|
|
1238
|
+
category,
|
|
1239
|
+
fix,
|
|
1240
|
+
id,
|
|
1241
|
+
key
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
return entries;
|
|
1245
|
+
}
|
|
1246
|
+
function serializeAction({ action, step }) {
|
|
1247
|
+
return {
|
|
1248
|
+
...action.pending === void 0 ? {} : { pending: action.pending },
|
|
1249
|
+
exists: action.exists,
|
|
1250
|
+
kind: action.kind,
|
|
1251
|
+
name: action.name,
|
|
1252
|
+
step,
|
|
1253
|
+
...action.update === void 0 ? {} : { update: action.update }
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
function provisionActionStatus({ action }) {
|
|
1257
|
+
return !action.exists ? "create" : action.update ? "update" : action.pending ? "pending" : "exists";
|
|
1258
|
+
}
|
|
1259
|
+
function writeProvisionActions(actions, stdout) {
|
|
1260
|
+
for (const planned of actions) {
|
|
1261
|
+
const { action } = planned;
|
|
1262
|
+
stdout.write(`${provisionActionStatus(planned)}\t${action.kind}\t${action.name}${action.update ? `\t${action.update}` : ""}\n`);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
async function runProvision(args, cliContext, load) {
|
|
1266
|
+
const parsed = parseArgs("run", args);
|
|
1267
|
+
const resolved = await resolveHost("run", parsed, cliContext);
|
|
1268
|
+
if ("exitCode" in resolved) return resolved.exitCode;
|
|
1269
|
+
const { host: provider } = resolved;
|
|
1270
|
+
const { env = cliContext.env, rootDir, steps } = await load(provider);
|
|
1271
|
+
const context = await withHostCredentials(provider, {
|
|
1272
|
+
...cliContext,
|
|
1273
|
+
env,
|
|
1274
|
+
rootDir
|
|
1275
|
+
}, cliContext.rootDir, resolved.link);
|
|
1276
|
+
if (!parsed.dryRun && !hasHostCredentials(provider, context.env)) {
|
|
1277
|
+
context.stderr.write(`Provision requires ${HOST_CREDENTIALS[provider]}. Dry-run preview does not require credentials (--dry-run).\n`);
|
|
1278
|
+
return 1;
|
|
1279
|
+
}
|
|
1280
|
+
if (!parsed.dryRun) await readProvisionState(context.rootDir);
|
|
1281
|
+
const { actions, checked, warnings } = await planProvision(provider, context, steps, parsed.json);
|
|
1282
|
+
const blocked = !checked && !parsed.dryRun;
|
|
1283
|
+
if (!parsed.json) {
|
|
1284
|
+
if (!checked) context.stdout.write("provision: plan not checked.\n");
|
|
1285
|
+
if (blocked) {
|
|
1286
|
+
context.stderr.write("provision: nothing applied. Fix the warnings above, or preview with --dry-run.\n");
|
|
1287
|
+
return 1;
|
|
1288
|
+
}
|
|
1289
|
+
if (!actions.length) {
|
|
1290
|
+
if (checked) context.stdout.write(`provision: no ${provider} resources to create.\n`);
|
|
1291
|
+
return 0;
|
|
1292
|
+
}
|
|
1293
|
+
writeProvisionActions(actions, context.stdout);
|
|
1294
|
+
}
|
|
1295
|
+
let state = {};
|
|
1296
|
+
if (!parsed.dryRun && !blocked) for (const { action } of actions) {
|
|
1297
|
+
const result = await action.apply();
|
|
1298
|
+
if (result.ids) state = mergeProvisionState(state, result.ids);
|
|
1299
|
+
}
|
|
1300
|
+
const wroteState = Object.keys(state).length > 0;
|
|
1301
|
+
if (wroteState) await writeProvisionState(context.rootDir, state);
|
|
1302
|
+
if (parsed.json) {
|
|
1303
|
+
if (blocked) context.stderr.write("provision: plan not checked, nothing applied. Read warnings in the JSON result.\n");
|
|
1304
|
+
context.stdout.write(`${JSON.stringify({
|
|
1305
|
+
actions: actions.map(serializeAction),
|
|
1306
|
+
checked,
|
|
1307
|
+
ids: state[provider] ?? {},
|
|
1308
|
+
mode: parsed.dryRun ? "dry-run" : "apply",
|
|
1309
|
+
provider,
|
|
1310
|
+
schemaVersion: 1,
|
|
1311
|
+
stateFile: wroteState ? provisionStateFile(context.rootDir, context.cwd) : null,
|
|
1312
|
+
warnings
|
|
1313
|
+
})}\n`);
|
|
1314
|
+
} else if (wroteState) context.stdout.write(`provision: wrote ids to ${provisionStateFile(context.rootDir, context.cwd)}\n`);
|
|
1315
|
+
return blocked ? 1 : 0;
|
|
1316
|
+
}
|
|
1317
|
+
async function runProvisionStatus(args, cliContext, load) {
|
|
1318
|
+
const parsed = parseArgs("status", args);
|
|
1319
|
+
const resolved = await resolveHost("status", parsed, cliContext);
|
|
1320
|
+
if ("exitCode" in resolved) return resolved.exitCode;
|
|
1321
|
+
const { host: provider } = resolved;
|
|
1322
|
+
const { env = cliContext.env, rootDir, steps } = await load(provider);
|
|
1323
|
+
const context = await withHostCredentials(provider, {
|
|
1324
|
+
...cliContext,
|
|
1325
|
+
env,
|
|
1326
|
+
rootDir
|
|
1327
|
+
}, cliContext.rootDir, resolved.link);
|
|
1328
|
+
const recorded = (await readProvisionState(context.rootDir))[provider] ?? {};
|
|
1329
|
+
const stateFile = provisionStateFile(context.rootDir, context.cwd);
|
|
1330
|
+
const undeclared = findUndeclaredEntries(provider, recorded, steps, context.env, stateFile);
|
|
1331
|
+
const hasCredentials = hasHostCredentials(provider, context.env);
|
|
1332
|
+
const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, steps, parsed.json) : {
|
|
1333
|
+
actions: [],
|
|
1334
|
+
checked: false,
|
|
1335
|
+
warnings: [`provision: plan not checked, missing ${HOST_CREDENTIALS[provider]}.`]
|
|
1336
|
+
};
|
|
1337
|
+
const pending = actions.filter(({ action }) => action.pending ?? !action.exists).length;
|
|
1338
|
+
if (parsed.json) {
|
|
1339
|
+
context.stdout.write(`${JSON.stringify({
|
|
1340
|
+
plan: {
|
|
1341
|
+
actions: actions.map(serializeAction),
|
|
1342
|
+
checked,
|
|
1343
|
+
pending
|
|
1344
|
+
},
|
|
1345
|
+
provider,
|
|
1346
|
+
recorded,
|
|
1347
|
+
schemaVersion: 1,
|
|
1348
|
+
stateFile,
|
|
1349
|
+
undeclared,
|
|
1350
|
+
warnings
|
|
1351
|
+
})}\n`);
|
|
1352
|
+
return 0;
|
|
1353
|
+
}
|
|
1354
|
+
const isUndeclared = (category, key) => undeclared.some((entry) => entry.category === category && entry.key === key);
|
|
1355
|
+
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`));
|
|
1356
|
+
if (recordedEntries.length) {
|
|
1357
|
+
context.stdout.write(`recorded ${provider} ids (${stateFile}):\n`);
|
|
1358
|
+
for (const entry of recordedEntries) context.stdout.write(entry);
|
|
1359
|
+
for (const entry of undeclared) context.stdout.write(`fix: ${entry.category} ${JSON.stringify(entry.key)}: ${entry.fix}\n`);
|
|
1360
|
+
} else context.stdout.write(`recorded ${provider} ids: none in ${stateFile}\n`);
|
|
1361
|
+
if (!checked) {
|
|
1362
|
+
if (!hasCredentials) context.stderr.write(`${warnings[0]}\n`);
|
|
1363
|
+
context.stdout.write("plan: not checked\n");
|
|
1364
|
+
return 0;
|
|
1365
|
+
}
|
|
1366
|
+
writeProvisionActions(actions, context.stdout);
|
|
1367
|
+
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");
|
|
1368
|
+
return 0;
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Built-in namespace that orchestrates package-contributed Provision Steps. `load` reads the steps of a build for the
|
|
1372
|
+
* `--host` of the command, so `provision run --host cloudflare` plans what `vitehub deploy --host cloudflare` creates.
|
|
1373
|
+
*/
|
|
1374
|
+
function createProvisionNamespace(load) {
|
|
1375
|
+
return {
|
|
1376
|
+
description: "Idempotently create missing provider resources.",
|
|
1377
|
+
features: [{
|
|
1378
|
+
description: "Create missing provider resources for the app's Definitions.",
|
|
1379
|
+
name: "run",
|
|
1380
|
+
run: (args, context) => runProvision(args, context, load),
|
|
1381
|
+
usage: USAGE.run
|
|
1382
|
+
}, {
|
|
1383
|
+
description: "Show recorded provider ids and pending plan actions.",
|
|
1384
|
+
name: "status",
|
|
1385
|
+
run: (args, context) => runProvisionStatus(args, context, load),
|
|
1386
|
+
usage: USAGE.status
|
|
1387
|
+
}],
|
|
1388
|
+
name: "provision"
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
export { getStableStdoutWrite as A, setupCommandNames as C, createCliDiscoveryNitroCloser as D, collectViteHubCliContribution as E, rethrowCliViteImportError as M, viteCliProjectConfig as N, createNuxtConfigImport as O, withStdoutOnStderr as P, reservedOperationNamespaces as S, appUrlError as T, operationCliOptions as _, provisionStateFile as a, parseOperationInput as b, mergeProvisionState as c, writeProvisionState as d, callOperation as f, operationCall as g, createOperationRegistry as h, provisionHostEnv as i, isCliViteMissing as j, findViteHubDevServerUrl as k, readProvisionState as l, collectOperationContributions as m, isProvisionHost as n, writeProvisionActions as o, callOperationFromCli as p, provisionActionStatus as r, PROVISION_STATE_FILE as s, createProvisionNamespace as t, readProvisionStateSync as u, operationCliPath as v, resolveViteHubProjectRoot as w, operationInputJsonSchema as x, operationsOf as y };
|