@vite-hub/env 0.4.1 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{access-B8lSDip4.js → access-DIErLk3w.js} +2 -3
- package/dist/{bridge-Cs9YfQWk.d.ts → bridge-BWwIooe0.d.ts} +0 -12
- package/dist/{bridge-error-BhJ77age.js → bridge-error-DEqzARPJ.js} +1 -3
- package/dist/bridge.d.ts +1 -1
- package/dist/bridge.js +9 -10
- package/dist/{cli-BPp7rdcA.d.ts → cli-B-LW6l_J.d.ts} +1 -6
- package/dist/cli-CAlHK5nn.js +1354 -0
- package/dist/cli.d.ts +3 -6
- package/dist/cli.js +1 -2
- package/dist/database.d.ts +2 -4
- package/dist/database.js +2 -5
- package/dist/{declarations-C5XR3aKw.d.ts → declarations-DNjO52_s.d.ts} +1 -21
- package/dist/{schema-C_a0WZyd.js → declarations-meg4Rmgd.js} +43 -105
- package/dist/{object-C7Jt4ez2.js → error-diagnostics-5BceFRdD.js} +57 -14
- package/dist/{error-diagnostics-DsDPsST_.js → error-diagnostics-BFzFaXcH.js} +2 -4
- package/dist/index.d.ts +3 -13
- package/dist/index.js +8 -12
- package/dist/internal/agent.d.ts +2 -4
- package/dist/internal/agent.js +3 -4
- package/dist/internal/connections.d.ts +2 -4
- package/dist/internal/connections.js +3 -4
- package/dist/internal/server.d.ts +2 -2
- package/dist/internal/server.js +1 -2
- package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
- package/dist/{operations-B1PFpKzy.js → operations-BftegDMd.js} +2 -3
- package/dist/operations.d.ts +2 -6
- package/dist/operations.js +7 -41
- package/dist/runtime/public-env.d.ts +2 -4
- package/dist/runtime/public-env.js +2 -3
- package/dist/runtime/server-env.d.ts +2 -3
- package/dist/runtime/server-env.js +2 -3
- package/dist/seal.d.ts +1 -3
- package/dist/seal.js +1 -2
- package/dist/{secret-DJd-fy5T.js → secret-VhbE53Vm.js} +1 -2
- package/dist/{server-CgKAEAE6.d.ts → server-CPEywepM.d.ts} +1 -12
- package/dist/{server-B9-8r6MZ.js → server-pTqnkM7n.js} +213 -168
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -2
- package/dist/vite.d.ts +5 -17
- package/dist/vite.js +20 -37
- package/package.json +11 -10
- package/dist/cli-C51D6V-M.js +0 -669
|
@@ -0,0 +1,1354 @@
|
|
|
1
|
+
import { a as isRecordOrFunction, i as isRecord, t as internalErrorDiagnostics } from "./error-diagnostics-5BceFRdD.js";
|
|
2
|
+
import { S as readViteHubSecret, a as isBlockingServerEnvEntry, f as invariant, y as deriveViteHubSecret } from "./server-pTqnkM7n.js";
|
|
3
|
+
import { t as envErrorDiagnostics } from "./error-diagnostics-BFzFaXcH.js";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
6
|
+
import * as v from "valibot";
|
|
7
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
8
|
+
import { basename, dirname, join, parse, resolve } from "node:path";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
// ../internal/src/cli.ts
|
|
13
|
+
/** Validate an explicit `--url` before sending a Console request. The caller adds the RPC path. */
|
|
14
|
+
function appUrlError(url) {
|
|
15
|
+
let base;
|
|
16
|
+
try {
|
|
17
|
+
base = new URL(url);
|
|
18
|
+
} catch {
|
|
19
|
+
return "--url must be a URL.";
|
|
20
|
+
}
|
|
21
|
+
const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
|
|
22
|
+
if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return "--url must use HTTPS, except for localhost.";
|
|
23
|
+
if (base.username || base.password || base.search || base.hash) return "--url must not contain credentials, a query, or a fragment.";
|
|
24
|
+
const consolePath = /(?:^|\/)_vitehub(?:\/|$)/.exec(base.pathname);
|
|
25
|
+
if (consolePath) return `--url is the app URL, not the Console URL. Pass --url ${`${base.origin}${base.pathname.slice(0, consolePath.index).replace(/\/$/, "")}`}.`;
|
|
26
|
+
}
|
|
27
|
+
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
28
|
+
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
29
|
+
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
30
|
+
const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
|
|
31
|
+
const stdoutRedirectGlobal = globalThis;
|
|
32
|
+
/**
|
|
33
|
+
* Sends `process.stdout` writes to stderr while `run` loads project config.
|
|
34
|
+
* Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
|
|
35
|
+
*/
|
|
36
|
+
async function withStdoutOnStderr(run, stderr = process.stderr) {
|
|
37
|
+
getStableStdoutWrite();
|
|
38
|
+
const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
|
|
39
|
+
let release;
|
|
40
|
+
stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
|
|
41
|
+
release = resolve;
|
|
42
|
+
});
|
|
43
|
+
await previous;
|
|
44
|
+
const write = process.stdout.write;
|
|
45
|
+
if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
|
|
46
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
|
|
47
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
|
|
48
|
+
}
|
|
49
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
|
|
50
|
+
process.stdout.write = ((chunk, encoding, callback) => {
|
|
51
|
+
const done = typeof encoding === "function" ? encoding : callback;
|
|
52
|
+
let called = false;
|
|
53
|
+
const onComplete = (error) => {
|
|
54
|
+
if (called) return;
|
|
55
|
+
called = true;
|
|
56
|
+
done?.(error);
|
|
57
|
+
};
|
|
58
|
+
const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
|
|
59
|
+
if (done && !called) {
|
|
60
|
+
if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
|
|
61
|
+
else if (stderr.write.length < 2) onComplete();
|
|
62
|
+
}
|
|
63
|
+
return result;
|
|
64
|
+
});
|
|
65
|
+
try {
|
|
66
|
+
return await run();
|
|
67
|
+
} finally {
|
|
68
|
+
process.stdout.write = write;
|
|
69
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
|
|
70
|
+
release();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
|
|
75
|
+
* Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
|
|
76
|
+
* config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
|
|
77
|
+
* then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
|
|
78
|
+
*/
|
|
79
|
+
function createCliDiscoveryNitroCloser() {
|
|
80
|
+
const instances = [];
|
|
81
|
+
return {
|
|
82
|
+
close: async () => {
|
|
83
|
+
await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
|
|
84
|
+
},
|
|
85
|
+
plugin: {
|
|
86
|
+
name: "vite-hub/cli-discovery-nitro",
|
|
87
|
+
nitro: { setup: (nitro) => {
|
|
88
|
+
instances.push(nitro);
|
|
89
|
+
} }
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** Returns the unredirected process stdout writer for payload output. */
|
|
94
|
+
function getStableStdoutWrite() {
|
|
95
|
+
const current = process.stdout.write;
|
|
96
|
+
if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
|
|
97
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
|
|
98
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
|
|
99
|
+
}
|
|
100
|
+
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
101
|
+
}
|
|
102
|
+
/** Writes a command failure: as `{ error }` JSON on stdout with `--json`, else the message and fix on stderr. Returns exit code 1. */
|
|
103
|
+
function writeCliFailure(json, streams, failure) {
|
|
104
|
+
if (json) streams.stdout.write(`${JSON.stringify({ error: failure }, null, 2)}\n`);
|
|
105
|
+
else streams.stderr.write(`${failure.message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
|
|
106
|
+
return 1;
|
|
107
|
+
}
|
|
108
|
+
/** File in the project root where the running dev server tells commands where it listens. */
|
|
109
|
+
const viteHubDevServerFile = ".vitehub/dev-server.json";
|
|
110
|
+
/** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
|
|
111
|
+
function readViteHubDevServerFile(root) {
|
|
112
|
+
try {
|
|
113
|
+
const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
|
|
114
|
+
const url = isRecord(value) ? value.url : void 0;
|
|
115
|
+
const served = isRecord(value) ? value.root : void 0;
|
|
116
|
+
return typeof url === "string" && url && typeof served === "string" && served ? {
|
|
117
|
+
root: served,
|
|
118
|
+
url
|
|
119
|
+
} : void 0;
|
|
120
|
+
} catch {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Where a command finds the dev server of its project: the file that the server wrote in a project root, else
|
|
126
|
+
* `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
|
|
127
|
+
*/
|
|
128
|
+
function findViteHubDevServerUrl(roots, env) {
|
|
129
|
+
for (const root of roots) {
|
|
130
|
+
const file = readViteHubDevServerFile(root);
|
|
131
|
+
if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
|
|
132
|
+
}
|
|
133
|
+
return env["VITEHUB_DEV_SERVER_URL"] || void 0;
|
|
134
|
+
}
|
|
135
|
+
// ../internal/src/build/vite.ts
|
|
136
|
+
const projectRootDirectoryMarkers = [
|
|
137
|
+
["server", "agents"],
|
|
138
|
+
["server", "channels"],
|
|
139
|
+
["server", "connections"],
|
|
140
|
+
["server", "browsers"],
|
|
141
|
+
["server", "emails"],
|
|
142
|
+
["server", "schedules"],
|
|
143
|
+
["server", "workspaces"]
|
|
144
|
+
];
|
|
145
|
+
const projectRootFileMarkers = [
|
|
146
|
+
["package.json"],
|
|
147
|
+
["nuxt.config.ts"],
|
|
148
|
+
["nuxt.config.mts"],
|
|
149
|
+
["nuxt.config.js"],
|
|
150
|
+
["nuxt.config.mjs"]
|
|
151
|
+
];
|
|
152
|
+
const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
|
|
153
|
+
const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
|
|
154
|
+
const VITEHUB_ENV_DESCRIPTION_ID = "#vitehub/env/description";
|
|
155
|
+
function createNoExternalAddition(...packageNames) {
|
|
156
|
+
return (current) => {
|
|
157
|
+
if (current === true) return;
|
|
158
|
+
const values = Array.isArray(current) ? current : [current];
|
|
159
|
+
const missing = packageNames.filter((packageName) => !values.includes(packageName));
|
|
160
|
+
return missing.length ? missing : void 0;
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function isServerEnvironment(name, config) {
|
|
164
|
+
return name === "ssr" || config.consumer === "server";
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Server Env declarations that ViteHub features add before `hubEnv()` builds the registry, such as the Server Env of
|
|
168
|
+
* discovered Channels. The application's `env.server` wins field by field.
|
|
169
|
+
*/
|
|
170
|
+
const VITEHUB_ENV_SERVER = "__vitehubEnvServer";
|
|
171
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
172
|
+
const resolvedRoot = resolve(root);
|
|
173
|
+
const temporaryRoot = resolve(tmpdir());
|
|
174
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
175
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
176
|
+
if (basename(resolvedRoot) === "app") {
|
|
177
|
+
const parent = dirname(resolvedRoot);
|
|
178
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
179
|
+
"nuxt.config.ts",
|
|
180
|
+
"nuxt.config.mts",
|
|
181
|
+
"nuxt.config.js",
|
|
182
|
+
"nuxt.config.mjs"
|
|
183
|
+
]))) return parent;
|
|
184
|
+
}
|
|
185
|
+
let current = resolvedRoot;
|
|
186
|
+
while (true) {
|
|
187
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
188
|
+
if (hasProjectRootMarker(current)) return current;
|
|
189
|
+
const parent = dirname(current);
|
|
190
|
+
if (parent === current) return resolvedRoot;
|
|
191
|
+
current = parent;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
195
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
196
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (!isMissingProjectMarker(error)) throw error;
|
|
199
|
+
}
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
function hasProjectRootMarker(root) {
|
|
203
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
204
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
205
|
+
}
|
|
206
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
207
|
+
for (const marker of markers) {
|
|
208
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
209
|
+
try {
|
|
210
|
+
if (statSync(resolve(root, ...path)).isFile()) return true;
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (!isMissingProjectMarker(error)) throw error;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
function isMissingProjectMarker(error) {
|
|
218
|
+
const code = error.code;
|
|
219
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
220
|
+
}
|
|
221
|
+
function viteHubEnvAmbientTypesPath(root) {
|
|
222
|
+
return resolve(root, ".vitehub", "types", "env.d.ts");
|
|
223
|
+
}
|
|
224
|
+
function viteHubEnvPublicModulePath(root) {
|
|
225
|
+
return resolve(root, ".vitehub", "env", "public.mjs");
|
|
226
|
+
}
|
|
227
|
+
function viteHubEnvPublicModuleTypesPath(root) {
|
|
228
|
+
return resolve(root, ".vitehub", "env", "public.d.ts");
|
|
229
|
+
}
|
|
230
|
+
function viteHubEnvServerModulePath(root) {
|
|
231
|
+
return resolve(root, ".vitehub", "env", "server.mjs");
|
|
232
|
+
}
|
|
233
|
+
function viteHubEnvDescriptionModulePath(root) {
|
|
234
|
+
return resolve(root, ".vitehub", "env", "description.mjs");
|
|
235
|
+
}
|
|
236
|
+
function viteHubEnvServerModuleTypesPath(root) {
|
|
237
|
+
return resolve(root, ".vitehub", "env", "server.d.ts");
|
|
238
|
+
}
|
|
239
|
+
function createViteHubEnvImportAliases(root) {
|
|
240
|
+
return {
|
|
241
|
+
[VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
|
|
242
|
+
[VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root),
|
|
243
|
+
[VITEHUB_ENV_DESCRIPTION_ID]: viteHubEnvDescriptionModulePath(root)
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
// ../../node_modules/.pnpm/birpc@4.2.0/node_modules/birpc/dist/index.mjs
|
|
247
|
+
function createPromiseWithResolvers() {
|
|
248
|
+
let resolve;
|
|
249
|
+
let reject;
|
|
250
|
+
return {
|
|
251
|
+
promise: new Promise((res, rej) => {
|
|
252
|
+
resolve = res;
|
|
253
|
+
reject = rej;
|
|
254
|
+
}),
|
|
255
|
+
resolve,
|
|
256
|
+
reject
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const random = Math.random.bind(Math);
|
|
260
|
+
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
|
261
|
+
function nanoid(size = 21) {
|
|
262
|
+
let id = "";
|
|
263
|
+
let i = size;
|
|
264
|
+
while (i--) id += urlAlphabet[random() * 64 | 0];
|
|
265
|
+
return id;
|
|
266
|
+
}
|
|
267
|
+
const DEFAULT_TIMEOUT = 6e4;
|
|
268
|
+
const defaultSerialize = (i) => i;
|
|
269
|
+
const defaultDeserialize = defaultSerialize;
|
|
270
|
+
const { clearTimeout, setTimeout } = globalThis;
|
|
271
|
+
function createBirpc($functions, options) {
|
|
272
|
+
const { post, on, off = () => {}, eventNames = [], serialize = defaultSerialize, deserialize = defaultDeserialize, resolver, bind = "rpc", timeout = DEFAULT_TIMEOUT, proxify = true } = options;
|
|
273
|
+
let $closed = false;
|
|
274
|
+
const _rpcPromiseMap = /* @__PURE__ */ new Map();
|
|
275
|
+
let _promiseInit;
|
|
276
|
+
let rpc;
|
|
277
|
+
async function _call(method, args, event, optional) {
|
|
278
|
+
if ($closed) throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
|
279
|
+
const req = {
|
|
280
|
+
m: method,
|
|
281
|
+
a: args,
|
|
282
|
+
t: "q"
|
|
283
|
+
};
|
|
284
|
+
if (optional) req.o = true;
|
|
285
|
+
const send = async (_req) => post(serialize(_req));
|
|
286
|
+
if (event) {
|
|
287
|
+
await send(req);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (_promiseInit) try {
|
|
291
|
+
await _promiseInit;
|
|
292
|
+
} finally {
|
|
293
|
+
_promiseInit = void 0;
|
|
294
|
+
}
|
|
295
|
+
let { promise, resolve, reject } = createPromiseWithResolvers();
|
|
296
|
+
const id = nanoid();
|
|
297
|
+
req.i = id;
|
|
298
|
+
let timeoutId;
|
|
299
|
+
async function handler(newReq = req) {
|
|
300
|
+
if (timeout >= 0) {
|
|
301
|
+
timeoutId = setTimeout(() => {
|
|
302
|
+
try {
|
|
303
|
+
if (options.onTimeoutError?.call(rpc, method, args) !== true) throw new Error(`[birpc] timeout on calling "${method}"`);
|
|
304
|
+
} catch (e) {
|
|
305
|
+
reject(e);
|
|
306
|
+
}
|
|
307
|
+
_rpcPromiseMap.delete(id);
|
|
308
|
+
}, timeout);
|
|
309
|
+
if (typeof timeoutId === "object") timeoutId = timeoutId.unref?.();
|
|
310
|
+
}
|
|
311
|
+
_rpcPromiseMap.set(id, {
|
|
312
|
+
resolve,
|
|
313
|
+
reject,
|
|
314
|
+
timeoutId,
|
|
315
|
+
method
|
|
316
|
+
});
|
|
317
|
+
await send(newReq);
|
|
318
|
+
return promise;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
if (options.onRequest) await options.onRequest.call(rpc, req, handler, resolve);
|
|
322
|
+
else await handler();
|
|
323
|
+
} catch (e) {
|
|
324
|
+
if (options.onGeneralError?.call(rpc, e) !== true) throw e;
|
|
325
|
+
return;
|
|
326
|
+
} finally {
|
|
327
|
+
clearTimeout(timeoutId);
|
|
328
|
+
_rpcPromiseMap.delete(id);
|
|
329
|
+
}
|
|
330
|
+
return promise;
|
|
331
|
+
}
|
|
332
|
+
const builtinMethods = {
|
|
333
|
+
$call: (method, ...args) => _call(method, args, false),
|
|
334
|
+
$callOptional: (method, ...args) => _call(method, args, false, true),
|
|
335
|
+
$callEvent: (method, ...args) => _call(method, args, true),
|
|
336
|
+
$callRaw: (options) => _call(options.method, options.args, options.event, options.optional),
|
|
337
|
+
$rejectPendingCalls,
|
|
338
|
+
get $closed() {
|
|
339
|
+
return $closed;
|
|
340
|
+
},
|
|
341
|
+
get $meta() {
|
|
342
|
+
return options.meta;
|
|
343
|
+
},
|
|
344
|
+
$close,
|
|
345
|
+
$functions
|
|
346
|
+
};
|
|
347
|
+
if (proxify) rpc = new Proxy({}, { get(_, method) {
|
|
348
|
+
if (Object.hasOwn(builtinMethods, method)) return builtinMethods[method];
|
|
349
|
+
if (method === "then" && !eventNames.includes("then") && !("then" in $functions)) return void 0;
|
|
350
|
+
const sendEvent = (...args) => _call(method, args, true);
|
|
351
|
+
if (eventNames.includes(method)) {
|
|
352
|
+
sendEvent.asEvent = sendEvent;
|
|
353
|
+
return sendEvent;
|
|
354
|
+
}
|
|
355
|
+
const sendCall = (...args) => _call(method, args, false);
|
|
356
|
+
sendCall.asEvent = sendEvent;
|
|
357
|
+
return sendCall;
|
|
358
|
+
} });
|
|
359
|
+
else rpc = builtinMethods;
|
|
360
|
+
function $close(customError) {
|
|
361
|
+
$closed = true;
|
|
362
|
+
_rpcPromiseMap.forEach(({ reject, method }) => {
|
|
363
|
+
const error = /* @__PURE__ */ new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
|
364
|
+
if (customError) {
|
|
365
|
+
customError.cause ??= error;
|
|
366
|
+
return reject(customError);
|
|
367
|
+
}
|
|
368
|
+
reject(error);
|
|
369
|
+
});
|
|
370
|
+
_rpcPromiseMap.clear();
|
|
371
|
+
off(onMessage);
|
|
372
|
+
}
|
|
373
|
+
function $rejectPendingCalls(handler) {
|
|
374
|
+
const handlerResults = Array.from(_rpcPromiseMap.values()).map(({ method, reject }) => {
|
|
375
|
+
if (!handler) return reject(/* @__PURE__ */ new Error(`[birpc]: rejected pending call "${method}".`));
|
|
376
|
+
return handler({
|
|
377
|
+
method,
|
|
378
|
+
reject
|
|
379
|
+
});
|
|
380
|
+
});
|
|
381
|
+
_rpcPromiseMap.clear();
|
|
382
|
+
return handlerResults;
|
|
383
|
+
}
|
|
384
|
+
async function onMessage(data, ...extra) {
|
|
385
|
+
let msg;
|
|
386
|
+
try {
|
|
387
|
+
msg = deserialize(data);
|
|
388
|
+
} catch (e) {
|
|
389
|
+
if (options.onGeneralError?.call(rpc, e) !== true) throw e;
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (msg.t === "q") {
|
|
393
|
+
const { m: method, a: args, o: optional } = msg;
|
|
394
|
+
let result, error;
|
|
395
|
+
let fn = await (resolver ? resolver.call(rpc, method, $functions[method]) : $functions[method]);
|
|
396
|
+
if (optional) fn ||= () => void 0;
|
|
397
|
+
if (!fn) error = /* @__PURE__ */ new Error(`[birpc] function "${method}" not found`);
|
|
398
|
+
else try {
|
|
399
|
+
result = await fn.apply(bind === "rpc" ? rpc : $functions, args);
|
|
400
|
+
} catch (e) {
|
|
401
|
+
error = e;
|
|
402
|
+
}
|
|
403
|
+
if (msg.i) {
|
|
404
|
+
if (error && options.onFunctionError) {
|
|
405
|
+
if (options.onFunctionError.call(rpc, error, method, args) === true) return;
|
|
406
|
+
}
|
|
407
|
+
if (!error) try {
|
|
408
|
+
await post(serialize({
|
|
409
|
+
t: "s",
|
|
410
|
+
i: msg.i,
|
|
411
|
+
r: result
|
|
412
|
+
}), ...extra);
|
|
413
|
+
return;
|
|
414
|
+
} catch (e) {
|
|
415
|
+
error = e;
|
|
416
|
+
if (options.onGeneralError?.call(rpc, e, method, args) !== true) throw e;
|
|
417
|
+
}
|
|
418
|
+
try {
|
|
419
|
+
await post(serialize({
|
|
420
|
+
t: "s",
|
|
421
|
+
i: msg.i,
|
|
422
|
+
e: error
|
|
423
|
+
}), ...extra);
|
|
424
|
+
} catch (e) {
|
|
425
|
+
if (options.onGeneralError?.call(rpc, e, method, args) !== true) throw e;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
} else {
|
|
429
|
+
const { i: ack, r: result, e: error } = msg;
|
|
430
|
+
const promise = _rpcPromiseMap.get(ack);
|
|
431
|
+
if (promise) {
|
|
432
|
+
clearTimeout(promise.timeoutId);
|
|
433
|
+
if (error) promise.reject(error);
|
|
434
|
+
else promise.resolve(result);
|
|
435
|
+
}
|
|
436
|
+
_rpcPromiseMap.delete(ack);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
_promiseInit = on(onMessage);
|
|
440
|
+
return rpc;
|
|
441
|
+
}
|
|
442
|
+
// ../internal/src/operation-rpc.ts
|
|
443
|
+
/** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
|
|
444
|
+
const operationRpcPath = "/_vitehub/rpc";
|
|
445
|
+
function text(value) {
|
|
446
|
+
return String(value) === value && value ? value : void 0;
|
|
447
|
+
}
|
|
448
|
+
/** Read an untrusted failure body. It keeps only the diagnostic fields, so a stack never passes through. */
|
|
449
|
+
function readOperationRpcError(value) {
|
|
450
|
+
if (!isRecord(value)) return void 0;
|
|
451
|
+
const code = text(value.code);
|
|
452
|
+
const message = text(value.message);
|
|
453
|
+
const status = value.status;
|
|
454
|
+
if (!code || !message || !Number.isInteger(status)) return void 0;
|
|
455
|
+
const failure = {
|
|
456
|
+
code,
|
|
457
|
+
message,
|
|
458
|
+
status: Number(status)
|
|
459
|
+
};
|
|
460
|
+
if (text(value.fix)) failure.fix = text(value.fix);
|
|
461
|
+
if (text(value.docs)) failure.docs = text(value.docs);
|
|
462
|
+
if (isRecord(value.details)) failure.details = value.details;
|
|
463
|
+
return failure;
|
|
464
|
+
}
|
|
465
|
+
/** Read one response message. */
|
|
466
|
+
function readOperationRpcReply(value) {
|
|
467
|
+
if (!isRecord(value) || value.t !== "s") return void 0;
|
|
468
|
+
const id = text(value.i);
|
|
469
|
+
if (Object.hasOwn(value, "e")) {
|
|
470
|
+
const error = readOperationRpcError(value.e);
|
|
471
|
+
return error ? {
|
|
472
|
+
t: "s",
|
|
473
|
+
...id ? { i: id } : {},
|
|
474
|
+
e: error
|
|
475
|
+
} : void 0;
|
|
476
|
+
}
|
|
477
|
+
return id ? {
|
|
478
|
+
t: "s",
|
|
479
|
+
i: id,
|
|
480
|
+
r: value.r
|
|
481
|
+
} : void 0;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Call one operation with birpc over a request and answer transport, such as one HTTP POST per call. `send` posts the
|
|
485
|
+
* JSON message and returns the parsed answer; its own failures, such as a network error or an abort, reject.
|
|
486
|
+
*/
|
|
487
|
+
async function callOperationRpc(name, input, send) {
|
|
488
|
+
let receive;
|
|
489
|
+
let answer;
|
|
490
|
+
const notReply = /* @__PURE__ */ new Error("The answer is not a reply to the operation call.");
|
|
491
|
+
const rpc = createBirpc({}, {
|
|
492
|
+
on: (listener) => {
|
|
493
|
+
receive = listener;
|
|
494
|
+
},
|
|
495
|
+
post: async (message) => {
|
|
496
|
+
answer = await send(JSON.stringify(message));
|
|
497
|
+
const reply = readOperationRpcReply(answer.body);
|
|
498
|
+
if (!reply || reply.i !== void 0 && reply.i !== message.i) throw notReply;
|
|
499
|
+
await receive({
|
|
500
|
+
...reply,
|
|
501
|
+
i: message.i
|
|
502
|
+
});
|
|
503
|
+
},
|
|
504
|
+
proxify: false,
|
|
505
|
+
timeout: -1
|
|
506
|
+
});
|
|
507
|
+
try {
|
|
508
|
+
return {
|
|
509
|
+
ok: true,
|
|
510
|
+
value: await rpc.$call(name, ...input === void 0 ? [] : [input]),
|
|
511
|
+
answer
|
|
512
|
+
};
|
|
513
|
+
} catch (error) {
|
|
514
|
+
if (!answer) throw error;
|
|
515
|
+
if (error === notReply) return {
|
|
516
|
+
ok: false,
|
|
517
|
+
error: void 0,
|
|
518
|
+
answer
|
|
519
|
+
};
|
|
520
|
+
return {
|
|
521
|
+
ok: false,
|
|
522
|
+
error: readOperationRpcError(error),
|
|
523
|
+
answer
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
// ../internal/src/console-signature.ts
|
|
528
|
+
/**
|
|
529
|
+
* Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
|
|
530
|
+
* CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
|
|
531
|
+
* its env cannot sign a request. The module uses only Web Crypto, so it runs in Node, Workers, Deno, and browsers.
|
|
532
|
+
*
|
|
533
|
+
* The signature covers this text, one field per line:
|
|
534
|
+
*
|
|
535
|
+
* ```txt
|
|
536
|
+
* vitehub-signature-v1
|
|
537
|
+
* POST
|
|
538
|
+
* /_vitehub/rpc
|
|
539
|
+
* https://app.example.com
|
|
540
|
+
* 1794400000
|
|
541
|
+
* CONSOLE_3F9A12BC
|
|
542
|
+
* <SHA-256 of the body bytes, base64url>
|
|
543
|
+
* <the x-vitehub-caller header>
|
|
544
|
+
* ```
|
|
545
|
+
*/
|
|
546
|
+
/** The signature header: `key=<NAME>, t=<seconds>, origin=<app origin>, body=<SHA-256>, v1=<signature>`. */
|
|
547
|
+
const consoleSignatureHeader = "x-vitehub-signature";
|
|
548
|
+
/** Who calls, as base64url JSON. The signature covers it. See {@link ConsoleCaller}. */
|
|
549
|
+
const consoleCallerHeader = "x-vitehub-caller";
|
|
550
|
+
/** The first line of the signed text. A new format gets a new tag. */
|
|
551
|
+
const consoleSignatureVersion = "vitehub-signature-v1";
|
|
552
|
+
/** The app reads the public key of the caller `<NAME>` from `VITEHUB_CONSOLE_KEY_<NAME>`. */
|
|
553
|
+
const consolePublicKeyPrefix = "VITEHUB_CONSOLE_KEY_";
|
|
554
|
+
/** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
|
|
555
|
+
const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
|
|
556
|
+
const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
|
|
557
|
+
const encoder = new TextEncoder();
|
|
558
|
+
new TextDecoder();
|
|
559
|
+
const ed25519 = { name: "Ed25519" };
|
|
560
|
+
const pkcs8Prefix = Uint8Array.of(48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32);
|
|
561
|
+
function base64url(bytes) {
|
|
562
|
+
let binary = "";
|
|
563
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
564
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
565
|
+
}
|
|
566
|
+
/** The bytes of a base64url value, or `undefined` when it is not canonical base64url without padding. */
|
|
567
|
+
function fromBase64url(value) {
|
|
568
|
+
if (!/^[\w-]*$/.test(value) || value.length % 4 === 1) return void 0;
|
|
569
|
+
const bytes = Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
|
|
570
|
+
return base64url(bytes) === value ? bytes : void 0;
|
|
571
|
+
}
|
|
572
|
+
function bytesOf(body) {
|
|
573
|
+
if (typeof body === "string") return encoder.encode(body);
|
|
574
|
+
return body instanceof Uint8Array ? Uint8Array.from(body) : new Uint8Array(body);
|
|
575
|
+
}
|
|
576
|
+
/** The SHA-256 of the exact body bytes, base64url. A request without a body hashes zero bytes. */
|
|
577
|
+
async function consoleBodySha256(body = "") {
|
|
578
|
+
return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytesOf(body))));
|
|
579
|
+
}
|
|
580
|
+
/** The text that the signature covers. Fields are joined with `\n`. */
|
|
581
|
+
function consoleSignedText(fields) {
|
|
582
|
+
return [
|
|
583
|
+
consoleSignatureVersion,
|
|
584
|
+
fields.method.toUpperCase(),
|
|
585
|
+
fields.target,
|
|
586
|
+
fields.origin,
|
|
587
|
+
fields.timestamp,
|
|
588
|
+
fields.key,
|
|
589
|
+
fields.bodySha256,
|
|
590
|
+
fields.caller
|
|
591
|
+
].join("\n");
|
|
592
|
+
}
|
|
593
|
+
/** The path and query of a URL, the part of the request target that the signature covers. */
|
|
594
|
+
function requestTarget(url) {
|
|
595
|
+
return `${url.pathname}${url.search}`;
|
|
596
|
+
}
|
|
597
|
+
/** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
|
|
598
|
+
function isConsoleKeyName(name) {
|
|
599
|
+
return keyNamePattern.test(name);
|
|
600
|
+
}
|
|
601
|
+
async function importPrivateKey(seed) {
|
|
602
|
+
const bytes = fromBase64url(seed.trim());
|
|
603
|
+
if (bytes?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_INVALID();
|
|
604
|
+
const der = new Uint8Array(pkcs8Prefix.length + 32);
|
|
605
|
+
der.set(pkcs8Prefix);
|
|
606
|
+
der.set(bytes, pkcs8Prefix.length);
|
|
607
|
+
return await crypto.subtle.importKey("pkcs8", der, ed25519, false, ["sign"]);
|
|
608
|
+
}
|
|
609
|
+
/** A new key pair: the public key for the app, the private key (the seed) for the caller. Both are base64url. */
|
|
610
|
+
async function createConsoleKeyPair() {
|
|
611
|
+
const pair = await crypto.subtle.generateKey(ed25519, true, ["sign", "verify"]);
|
|
612
|
+
invariant("privateKey" in pair, "Ed25519 generateKey() returns a key pair");
|
|
613
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
614
|
+
const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
|
|
615
|
+
return {
|
|
616
|
+
privateKey: base64url(pkcs8.slice(-32)),
|
|
617
|
+
publicKey: base64url(publicKey)
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
/** The `x-vitehub-caller` value of a caller: its JSON as base64url. */
|
|
621
|
+
function encodeConsoleCaller(caller) {
|
|
622
|
+
return base64url(encoder.encode(JSON.stringify(caller)));
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Sign one request. `url` is the full URL that the request goes to, and `body` is the exact body that it sends. Returns
|
|
626
|
+
* the two headers to add: `x-vitehub-signature` and `x-vitehub-caller`.
|
|
627
|
+
*/
|
|
628
|
+
async function signConsoleRequest(options) {
|
|
629
|
+
if (!isConsoleKeyName(options.key.name)) throw internalErrorDiagnostics.INTERNAL_CONSOLE_KEY_NAME_INVALID({ name: options.key.name });
|
|
630
|
+
const url = new URL(options.url);
|
|
631
|
+
const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
|
|
632
|
+
const bodySha256 = await consoleBodySha256(options.body);
|
|
633
|
+
const caller = encodeConsoleCaller(options.caller);
|
|
634
|
+
const text = consoleSignedText({
|
|
635
|
+
bodySha256,
|
|
636
|
+
caller,
|
|
637
|
+
key: options.key.name,
|
|
638
|
+
method: options.method,
|
|
639
|
+
origin: url.origin,
|
|
640
|
+
target: requestTarget(url),
|
|
641
|
+
timestamp
|
|
642
|
+
});
|
|
643
|
+
const signature = new Uint8Array(await crypto.subtle.sign(ed25519, await importPrivateKey(options.key.privateKey), encoder.encode(text)));
|
|
644
|
+
return {
|
|
645
|
+
[consoleCallerHeader]: caller,
|
|
646
|
+
[consoleSignatureHeader]: `key=${options.key.name}, t=${timestamp}, origin=${url.origin}, body=${bodySha256}, v1=${base64url(signature)}`
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* The signing key of a CLI from its env: the one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable. Returns `undefined`
|
|
651
|
+
* without one. Throws a coded error when there are several, or when the value is not a 32-byte seed.
|
|
652
|
+
*/
|
|
653
|
+
function readConsoleSigningKey(env) {
|
|
654
|
+
const variables = Object.keys(env).filter((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && env[name]?.trim()).sort();
|
|
655
|
+
if (!variables.length) return void 0;
|
|
656
|
+
if (variables.length > 1) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE({
|
|
657
|
+
prefix: consolePrivateKeyPrefix,
|
|
658
|
+
variables: variables.join(", ")
|
|
659
|
+
});
|
|
660
|
+
const variable = variables[0];
|
|
661
|
+
const name = variable.slice(28);
|
|
662
|
+
const privateKey = env[variable].trim();
|
|
663
|
+
if (!isConsoleKeyName(name) || fromBase64url(privateKey)?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID({ variable });
|
|
664
|
+
return {
|
|
665
|
+
name,
|
|
666
|
+
privateKey
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
// ../internal/src/operations.ts
|
|
670
|
+
/** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
|
|
671
|
+
const operationRpcHeader = "x-vitehub-console";
|
|
672
|
+
/** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
|
|
673
|
+
const operationRootHeader = "x-vitehub-root";
|
|
674
|
+
const operationExpectedRootsHeader = "x-vitehub-expected-roots";
|
|
675
|
+
/** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
|
|
676
|
+
function projectRootHash(root) {
|
|
677
|
+
const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
678
|
+
let first = 3735928559;
|
|
679
|
+
let second = 1103547991;
|
|
680
|
+
for (let index = 0; index < normalized.length; index++) {
|
|
681
|
+
const code = normalized.charCodeAt(index);
|
|
682
|
+
first = Math.imul(first ^ code, 2654435761);
|
|
683
|
+
second = Math.imul(second ^ code, 1597334677);
|
|
684
|
+
}
|
|
685
|
+
first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
|
|
686
|
+
second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
|
|
687
|
+
return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
|
|
688
|
+
}
|
|
689
|
+
/** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
|
|
690
|
+
const operationSurfaceHeader = "x-vitehub-surface";
|
|
691
|
+
/** Generated CLI commands ask the server to check confirmation after it parses the input. */
|
|
692
|
+
const operationConfirmationHeader = "x-vitehub-confirmation";
|
|
693
|
+
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.";
|
|
694
|
+
/** Headers of an operation call, without a signature. */
|
|
695
|
+
function operationHeaders() {
|
|
696
|
+
const headers = new Headers();
|
|
697
|
+
headers.set("accept", "application/json");
|
|
698
|
+
headers.set("content-type", "application/json");
|
|
699
|
+
headers.set(operationRpcHeader, "1");
|
|
700
|
+
headers.set(operationSurfaceHeader, "cli");
|
|
701
|
+
return headers;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* The headers of one operation call to a deployed app: {@link operationHeaders}, and the signature of `body` when the
|
|
705
|
+
* env has a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. The CLI signs as itself, `via: "cli"`. Throws a `TypeError` for a
|
|
706
|
+
* malformed private key.
|
|
707
|
+
*/
|
|
708
|
+
async function signedOperationHeaders(env, url, body) {
|
|
709
|
+
const headers = operationHeaders();
|
|
710
|
+
const key = readConsoleSigningKey(env);
|
|
711
|
+
if (key) {
|
|
712
|
+
const signed = await signConsoleRequest({
|
|
713
|
+
body,
|
|
714
|
+
caller: { via: "cli" },
|
|
715
|
+
key,
|
|
716
|
+
method: "POST",
|
|
717
|
+
url
|
|
718
|
+
});
|
|
719
|
+
for (const [name, value] of Object.entries(signed)) headers.set(name, value);
|
|
720
|
+
}
|
|
721
|
+
return headers;
|
|
722
|
+
}
|
|
723
|
+
function unreachable(message, status = 503) {
|
|
724
|
+
const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
|
|
725
|
+
return {
|
|
726
|
+
ok: false,
|
|
727
|
+
code: error.code,
|
|
728
|
+
fix: error.fix,
|
|
729
|
+
message,
|
|
730
|
+
status
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
function hasCredentials(env) {
|
|
734
|
+
return Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && Boolean(env[name]));
|
|
735
|
+
}
|
|
736
|
+
/** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
|
|
737
|
+
async function callOperation(target, name, input) {
|
|
738
|
+
let origin = "the ViteHub app";
|
|
739
|
+
try {
|
|
740
|
+
const base = new URL(target.url);
|
|
741
|
+
if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
|
|
742
|
+
const url = new URL(operationRpcPath.slice(1), base);
|
|
743
|
+
origin = url.origin;
|
|
744
|
+
const env = target.roots?.length ? {} : target.env;
|
|
745
|
+
try {
|
|
746
|
+
readConsoleSigningKey(env);
|
|
747
|
+
} catch (error) {
|
|
748
|
+
return {
|
|
749
|
+
ok: false,
|
|
750
|
+
code: "INTERNAL_R0024",
|
|
751
|
+
fix: "Run `vitehub secret console-key` for a new key pair. Set its private key here and its public key on the app.",
|
|
752
|
+
message: error instanceof Error ? error.message : String(error),
|
|
753
|
+
status: 401
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
|
|
757
|
+
const headers = await signedOperationHeaders(env, url, body);
|
|
758
|
+
if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
|
|
759
|
+
if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
|
|
760
|
+
const response = await (target.fetch ?? fetch)(url.href, {
|
|
761
|
+
body,
|
|
762
|
+
headers,
|
|
763
|
+
method: "POST",
|
|
764
|
+
redirect: "manual",
|
|
765
|
+
signal: AbortSignal.timeout(target.timeout ?? 3e4)
|
|
766
|
+
});
|
|
767
|
+
const text = await response.text();
|
|
768
|
+
let json;
|
|
769
|
+
try {
|
|
770
|
+
json = text ? JSON.parse(text) : void 0;
|
|
771
|
+
} catch {
|
|
772
|
+
json = void 0;
|
|
773
|
+
}
|
|
774
|
+
return {
|
|
775
|
+
body: json,
|
|
776
|
+
response
|
|
777
|
+
};
|
|
778
|
+
});
|
|
779
|
+
const { response } = outcome.answer;
|
|
780
|
+
const served = response.headers.get(operationRootHeader);
|
|
781
|
+
if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
|
|
782
|
+
const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
|
|
783
|
+
const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
|
|
784
|
+
return {
|
|
785
|
+
ok: false,
|
|
786
|
+
code: error.code,
|
|
787
|
+
fix: error.fix,
|
|
788
|
+
message,
|
|
789
|
+
status: 409
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
if (outcome.ok) return {
|
|
793
|
+
ok: true,
|
|
794
|
+
value: outcome.value
|
|
795
|
+
};
|
|
796
|
+
const failure = outcome.error ?? readOperationRpcError(isRecordOrFunction(outcome.answer.body) ? {
|
|
797
|
+
status: response.status,
|
|
798
|
+
...outcome.answer.body
|
|
799
|
+
} : void 0);
|
|
800
|
+
if (failure) {
|
|
801
|
+
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."}`;
|
|
802
|
+
if ((failure.status === 401 || failure.status === 403) && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
|
|
803
|
+
return {
|
|
804
|
+
ok: false,
|
|
805
|
+
...failure
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
|
|
809
|
+
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);
|
|
810
|
+
} catch (error) {
|
|
811
|
+
return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
|
|
816
|
+
* started. Never throws. Without a dev server the result is an `INTERNAL_R0024` failure that says to start one.
|
|
817
|
+
*/
|
|
818
|
+
async function callOperationFromCli(call, name, input) {
|
|
819
|
+
let roots;
|
|
820
|
+
try {
|
|
821
|
+
roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
|
|
822
|
+
} catch {
|
|
823
|
+
roots = [call.rootDir];
|
|
824
|
+
}
|
|
825
|
+
const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
|
|
826
|
+
if (!url) return unreachable(`No dev server is running for ${roots.at(-1)}.`);
|
|
827
|
+
return await callOperation({
|
|
828
|
+
...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
|
|
829
|
+
env: call.env,
|
|
830
|
+
...call.fetch ? { fetch: call.fetch } : {},
|
|
831
|
+
...call.url ? {} : { roots },
|
|
832
|
+
...call.timeout ? { timeout: call.timeout } : {},
|
|
833
|
+
url
|
|
834
|
+
}, name, input);
|
|
835
|
+
}
|
|
836
|
+
// ../internal/src/vite-stage.ts
|
|
837
|
+
/**
|
|
838
|
+
* Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
|
|
839
|
+
* logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
|
|
840
|
+
*/
|
|
841
|
+
function loadAllEnv(loadEnv, mode, envDir) {
|
|
842
|
+
const write = process.stderr.write;
|
|
843
|
+
process.stderr.write = () => true;
|
|
844
|
+
try {
|
|
845
|
+
return loadEnv(mode, envDir, "");
|
|
846
|
+
} finally {
|
|
847
|
+
process.stderr.write = write;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const viteStageQueueKey = Symbol.for("vitehub.cli.vite-stage-queue");
|
|
851
|
+
function definedEntries(env) {
|
|
852
|
+
return Object.entries(env).filter((entry) => entry[1] !== void 0);
|
|
853
|
+
}
|
|
854
|
+
function replaceProcessEnv(entries) {
|
|
855
|
+
for (const key of Object.keys(process.env)) delete process.env[key];
|
|
856
|
+
for (const [key, value] of entries) process.env[key] = value;
|
|
857
|
+
}
|
|
858
|
+
async function runStageServer(vite, input, callback) {
|
|
859
|
+
let server;
|
|
860
|
+
const selectedEnvironment = definedEntries(input.env);
|
|
861
|
+
try {
|
|
862
|
+
server = await withStdoutOnStderr(async () => await vite.createServer({
|
|
863
|
+
appType: "custom",
|
|
864
|
+
...input.envDir !== void 0 ? { envDir: input.envDir } : {},
|
|
865
|
+
logLevel: "silent",
|
|
866
|
+
mode: input.stage,
|
|
867
|
+
root: input.rootDir,
|
|
868
|
+
server: {
|
|
869
|
+
hmr: false,
|
|
870
|
+
middlewareMode: true
|
|
871
|
+
}
|
|
872
|
+
}), input.stderr);
|
|
873
|
+
for (const [key, value] of [...Object.entries(loadAllEnv(vite.loadEnv, input.stage, server.config.envDir)), ...selectedEnvironment]) process.env[key] = value;
|
|
874
|
+
return await callback(server);
|
|
875
|
+
} finally {
|
|
876
|
+
await withStdoutOnStderr(async () => await server?.close(), input.stderr);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Run a CLI operation against a Vite Development Server in the selected stage mode.
|
|
881
|
+
*
|
|
882
|
+
* During the callback, `process.env` contains the stage-specific Vite env files
|
|
883
|
+
* (`.env`, `.env.local`, `.env.<stage>`, `.env.<stage>.local`) with `input.env`
|
|
884
|
+
* taking precedence. The previous `process.env` is restored afterwards. Calls run
|
|
885
|
+
* one at a time because `process.env` is process-wide.
|
|
886
|
+
*/
|
|
887
|
+
async function withViteStageServer(vite, input, callback) {
|
|
888
|
+
return await withViteStageEnvironment(input.env, async () => await runStageServer(vite, input, callback));
|
|
889
|
+
}
|
|
890
|
+
/** Load stage config and modules under the same serialized, temporary process environment. */
|
|
891
|
+
async function withViteStageEnvironment(env, callback) {
|
|
892
|
+
const carrier = globalThis;
|
|
893
|
+
const previous = carrier[viteStageQueueKey] ?? Promise.resolve();
|
|
894
|
+
let release;
|
|
895
|
+
carrier[viteStageQueueKey] = new Promise((resolve) => {
|
|
896
|
+
release = resolve;
|
|
897
|
+
});
|
|
898
|
+
await previous;
|
|
899
|
+
const previousEnvironment = definedEntries(process.env);
|
|
900
|
+
const selectedEnvironment = definedEntries(env);
|
|
901
|
+
try {
|
|
902
|
+
replaceProcessEnv(selectedEnvironment);
|
|
903
|
+
return await callback();
|
|
904
|
+
} finally {
|
|
905
|
+
replaceProcessEnv(previousEnvironment);
|
|
906
|
+
release();
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
// src/secret-cli.ts
|
|
910
|
+
const generateUsage = "vitehub secret generate";
|
|
911
|
+
const deriveUsage = "vitehub secret derive <purpose>";
|
|
912
|
+
const consoleKeyUsage = "vitehub secret console-key [name]";
|
|
913
|
+
function help(args) {
|
|
914
|
+
return args.includes("-h") || args.includes("--help");
|
|
915
|
+
}
|
|
916
|
+
function generate(args, context) {
|
|
917
|
+
if (help(args)) {
|
|
918
|
+
context.stdout.write(`Usage: ${generateUsage}\n\nPrint a new random root secret for VITEHUB_SECRET.\n`);
|
|
919
|
+
return 0;
|
|
920
|
+
}
|
|
921
|
+
if (args.length) {
|
|
922
|
+
context.stderr.write(`Unexpected secret generate argument: ${args[0]}\n`);
|
|
923
|
+
return 1;
|
|
924
|
+
}
|
|
925
|
+
context.stdout.write(`${randomBytes(32).toString("base64")}\n`);
|
|
926
|
+
return 0;
|
|
927
|
+
}
|
|
928
|
+
async function derive(args, context) {
|
|
929
|
+
if (help(args)) {
|
|
930
|
+
context.stdout.write([
|
|
931
|
+
`Usage: ${deriveUsage}`,
|
|
932
|
+
"",
|
|
933
|
+
"Print the secret that deriveSecret(<purpose>) returns for VITEHUB_SECRET.",
|
|
934
|
+
"For example, `vitehub secret derive myapp:webhooks` prints the same key on every machine with the same root secret.",
|
|
935
|
+
""
|
|
936
|
+
].join("\n"));
|
|
937
|
+
return 0;
|
|
938
|
+
}
|
|
939
|
+
const [purpose, ...rest] = args;
|
|
940
|
+
if (!purpose || rest.length) {
|
|
941
|
+
context.stderr.write(`Usage: ${deriveUsage}\n`);
|
|
942
|
+
return 1;
|
|
943
|
+
}
|
|
944
|
+
const root = readViteHubSecret(context.env);
|
|
945
|
+
if (!root) {
|
|
946
|
+
context.stderr.write("Set VITEHUB_SECRET to the root secret of the deployment.\n");
|
|
947
|
+
return 1;
|
|
948
|
+
}
|
|
949
|
+
if (root.length < 32) {
|
|
950
|
+
context.stderr.write(`VITEHUB_SECRET must be at least 32 characters.\n`);
|
|
951
|
+
return 1;
|
|
952
|
+
}
|
|
953
|
+
context.stdout.write(`${await deriveViteHubSecret(root, purpose)}\n`);
|
|
954
|
+
return 0;
|
|
955
|
+
}
|
|
956
|
+
async function consoleKey(args, context) {
|
|
957
|
+
if (help(args)) {
|
|
958
|
+
context.stdout.write([
|
|
959
|
+
`Usage: ${consoleKeyUsage}`,
|
|
960
|
+
"",
|
|
961
|
+
"Print a new key pair for signed Console requests. Set the first line on the app (console: true),",
|
|
962
|
+
"and the second line where the CLI runs, such as a CI secret. The name defaults to CLI.",
|
|
963
|
+
""
|
|
964
|
+
].join("\n"));
|
|
965
|
+
return 0;
|
|
966
|
+
}
|
|
967
|
+
const [input = "CLI", ...rest] = args;
|
|
968
|
+
const name = input.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
|
|
969
|
+
if (rest.length || !isConsoleKeyName(name)) {
|
|
970
|
+
context.stderr.write(`Usage: ${consoleKeyUsage}\nThe name has 1 to 64 letters, digits, or underscores.\n`);
|
|
971
|
+
return 1;
|
|
972
|
+
}
|
|
973
|
+
const { privateKey, publicKey } = await createConsoleKeyPair();
|
|
974
|
+
context.stdout.write([
|
|
975
|
+
"# The app: set this variable on the deployment.",
|
|
976
|
+
`${consolePublicKeyPrefix}${name}=${publicKey}`,
|
|
977
|
+
"# The CLI: keep this one secret, such as in a CI secret. Remove the app variable to revoke it.",
|
|
978
|
+
`${consolePrivateKeyPrefix}${name}=${privateKey}`,
|
|
979
|
+
""
|
|
980
|
+
].join("\n"));
|
|
981
|
+
return 0;
|
|
982
|
+
}
|
|
983
|
+
/** `vitehub secret` features. They read only the process env and never load the project. */
|
|
984
|
+
const secretCliFeatures = [
|
|
985
|
+
{
|
|
986
|
+
description: "Print a new random root secret for VITEHUB_SECRET.",
|
|
987
|
+
name: "generate",
|
|
988
|
+
run: async (args, context) => generate(args, context),
|
|
989
|
+
usage: generateUsage
|
|
990
|
+
},
|
|
991
|
+
{
|
|
992
|
+
description: "Print the secret derived from VITEHUB_SECRET for one purpose.",
|
|
993
|
+
name: "derive",
|
|
994
|
+
run: async (args, context) => await derive(args, context),
|
|
995
|
+
usage: deriveUsage
|
|
996
|
+
},
|
|
997
|
+
{
|
|
998
|
+
description: "Print a new key pair for signed Console requests from the CLI.",
|
|
999
|
+
name: "console-key",
|
|
1000
|
+
run: async (args, context) => await consoleKey(args, context),
|
|
1001
|
+
usage: consoleKeyUsage
|
|
1002
|
+
}
|
|
1003
|
+
];
|
|
1004
|
+
// src/cli.ts
|
|
1005
|
+
const defaultEnvCliStage = "development";
|
|
1006
|
+
function usage(command) {
|
|
1007
|
+
return command === "list" ? "vitehub env list [--stage <name> | --url <app>] [--json]" : `vitehub env ${command} [--stage <name>] [--json]`;
|
|
1008
|
+
}
|
|
1009
|
+
function writeUsage(command, stream) {
|
|
1010
|
+
stream.write([
|
|
1011
|
+
`Usage: ${usage(command)}`,
|
|
1012
|
+
"",
|
|
1013
|
+
command === "check" ? "Checks declared Server Env values. Exits with 1 when loadServerEnv() would fail." : "Lists declared Server Env variables and their status. Values are never printed.",
|
|
1014
|
+
"",
|
|
1015
|
+
"Options:",
|
|
1016
|
+
` --stage <name> Load Vite env files for this mode. Defaults to ${defaultEnvCliStage}.`,
|
|
1017
|
+
" Variables from the current process take precedence.",
|
|
1018
|
+
...command === "list" ? [" --url <app> Ask the running app, such as a deployment, for the status of its values."] : [],
|
|
1019
|
+
" --json Print machine-readable output.",
|
|
1020
|
+
" -h, --help Show this help.",
|
|
1021
|
+
""
|
|
1022
|
+
].join("\n"));
|
|
1023
|
+
}
|
|
1024
|
+
function parseArgs(command, args) {
|
|
1025
|
+
const parsed = {
|
|
1026
|
+
help: false,
|
|
1027
|
+
json: false
|
|
1028
|
+
};
|
|
1029
|
+
for (let index = 0; index < args.length; index++) {
|
|
1030
|
+
const arg = args[index];
|
|
1031
|
+
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
1032
|
+
else if (arg === "--json") parsed.json = true;
|
|
1033
|
+
else if (arg === "--stage" || arg.startsWith("--stage=")) {
|
|
1034
|
+
const value = arg === "--stage" ? args[++index] : arg.slice(8);
|
|
1035
|
+
if (!value || value.startsWith("-")) throw envErrorDiagnostics.ENV_R0025({ message: "--stage requires a name." });
|
|
1036
|
+
parsed.stage = value;
|
|
1037
|
+
} else if (command === "list" && (arg === "--url" || arg.startsWith("--url="))) {
|
|
1038
|
+
const value = arg === "--url" ? args[++index] : arg.slice(6);
|
|
1039
|
+
if (!value || value.startsWith("-")) throw envErrorDiagnostics.ENV_R0026({ message: "--url requires the app URL, such as --url https://app.example.com." });
|
|
1040
|
+
parsed.url = value;
|
|
1041
|
+
} else throw envErrorDiagnostics.ENV_R0026({ message: `Unknown option: ${arg}` });
|
|
1042
|
+
}
|
|
1043
|
+
if (parsed.url && parsed.stage) throw envErrorDiagnostics.ENV_R0026({ message: "Pass --stage to read a local stage, or --url to ask the app, not both." });
|
|
1044
|
+
return parsed;
|
|
1045
|
+
}
|
|
1046
|
+
function isInspection(value) {
|
|
1047
|
+
return v.is(v.object({ entries: v.array(v.object({
|
|
1048
|
+
masked: v.boolean(),
|
|
1049
|
+
path: v.optional(v.string()),
|
|
1050
|
+
provider: v.optional(v.string()),
|
|
1051
|
+
required: v.boolean(),
|
|
1052
|
+
source: v.picklist([
|
|
1053
|
+
"env",
|
|
1054
|
+
"literal",
|
|
1055
|
+
"provider"
|
|
1056
|
+
]),
|
|
1057
|
+
status: v.picklist([
|
|
1058
|
+
"available",
|
|
1059
|
+
"defaulted",
|
|
1060
|
+
"error",
|
|
1061
|
+
"invalid",
|
|
1062
|
+
"missing"
|
|
1063
|
+
])
|
|
1064
|
+
})) }), value);
|
|
1065
|
+
}
|
|
1066
|
+
async function createStageModuleLoader(vite, config, allowNuxtFallback = false) {
|
|
1067
|
+
const nitro = createCliDiscoveryNitroCloser();
|
|
1068
|
+
const ws = {
|
|
1069
|
+
...vite.createServerHotChannel(),
|
|
1070
|
+
clients: /* @__PURE__ */ new Set(),
|
|
1071
|
+
handleInvoke: async () => ({ error: {
|
|
1072
|
+
name: "TransportError",
|
|
1073
|
+
message: "WebSocket transport is disabled during Env inspection."
|
|
1074
|
+
} })
|
|
1075
|
+
};
|
|
1076
|
+
const initialized = /* @__PURE__ */ new Set();
|
|
1077
|
+
async function initEnvironment(environment) {
|
|
1078
|
+
await environment.init();
|
|
1079
|
+
initialized.add(environment);
|
|
1080
|
+
}
|
|
1081
|
+
async function closeEnvironment(environment) {
|
|
1082
|
+
if (!environment) return;
|
|
1083
|
+
try {
|
|
1084
|
+
await environment.close();
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
if (initialized.has(environment) || !(error instanceof Error) || error.message !== `${environment.name} environment.pluginContainer called before initialized`) throw error;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
let environment;
|
|
1090
|
+
let fallback;
|
|
1091
|
+
const close = async () => {
|
|
1092
|
+
try {
|
|
1093
|
+
await closeEnvironment(fallback);
|
|
1094
|
+
} finally {
|
|
1095
|
+
try {
|
|
1096
|
+
await closeEnvironment(environment);
|
|
1097
|
+
} finally {
|
|
1098
|
+
try {
|
|
1099
|
+
await ws.close();
|
|
1100
|
+
} finally {
|
|
1101
|
+
await nitro.close();
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
try {
|
|
1107
|
+
const inlineConfig = {
|
|
1108
|
+
...config,
|
|
1109
|
+
plugins: [...config.plugins ?? [], nitro.plugin],
|
|
1110
|
+
vitehubCliDiscovery: true
|
|
1111
|
+
};
|
|
1112
|
+
const resolved = await vite.resolveConfig(inlineConfig, "serve");
|
|
1113
|
+
const created = await resolved.environments.ssr.dev.createEnvironment("ssr", resolved, { ws });
|
|
1114
|
+
environment = created;
|
|
1115
|
+
await initEnvironment(created);
|
|
1116
|
+
let runnable;
|
|
1117
|
+
if (vite.isRunnableDevEnvironment(created)) runnable = created;
|
|
1118
|
+
else {
|
|
1119
|
+
if (!allowNuxtFallback) throw envErrorDiagnostics.ENV_R0030({ message: "The SSR environment does not support runnable imports." });
|
|
1120
|
+
const runnableFallback = vite.createRunnableDevEnvironment("ssr", resolved, {
|
|
1121
|
+
hot: false,
|
|
1122
|
+
options: { dev: { moduleRunnerTransform: true } }
|
|
1123
|
+
});
|
|
1124
|
+
fallback = runnableFallback;
|
|
1125
|
+
await initEnvironment(runnableFallback);
|
|
1126
|
+
runnable = runnableFallback;
|
|
1127
|
+
}
|
|
1128
|
+
return {
|
|
1129
|
+
close,
|
|
1130
|
+
config: resolved,
|
|
1131
|
+
ssrLoadModule: async (url) => await runnable.runner.import(url)
|
|
1132
|
+
};
|
|
1133
|
+
} catch (error) {
|
|
1134
|
+
try {
|
|
1135
|
+
await close();
|
|
1136
|
+
} catch (closeError) {
|
|
1137
|
+
throw new AggregateError([error, closeError], `${formatRuntimeDiagnosticError(error)}\n[vitehub] Env could not close the stage after loading failed.`, { cause: error });
|
|
1138
|
+
}
|
|
1139
|
+
throw error;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
async function inspectStage(input) {
|
|
1143
|
+
const explicitEnv = { ...input.env };
|
|
1144
|
+
const vite = await import("vite");
|
|
1145
|
+
const projectRoot = input.applicationRoot ?? input.rootDir;
|
|
1146
|
+
const hasNuxtConfig = [
|
|
1147
|
+
"js",
|
|
1148
|
+
"mjs",
|
|
1149
|
+
"cjs",
|
|
1150
|
+
"ts",
|
|
1151
|
+
"mts",
|
|
1152
|
+
"cts"
|
|
1153
|
+
].some((extension) => existsSync(join(projectRoot, `nuxt.config.${extension}`)));
|
|
1154
|
+
return await withViteStageServer({
|
|
1155
|
+
loadEnv: vite.loadEnv,
|
|
1156
|
+
async createServer(config) {
|
|
1157
|
+
if (!hasNuxtConfig) return await createStageModuleLoader(vite, config);
|
|
1158
|
+
const require = createRequire(join(projectRoot, "package.json"));
|
|
1159
|
+
const kit = await import(pathToFileURL(require.resolve("nuxt/kit")).href);
|
|
1160
|
+
Object.assign(process.env, loadAllEnv(vite.loadEnv, input.stage, projectRoot));
|
|
1161
|
+
for (const [key, value] of Object.entries(explicitEnv)) if (value !== void 0) process.env[key] = value;
|
|
1162
|
+
const nuxt = await kit.loadNuxt({
|
|
1163
|
+
cwd: projectRoot,
|
|
1164
|
+
dev: true,
|
|
1165
|
+
envName: input.stage,
|
|
1166
|
+
overrides: {
|
|
1167
|
+
devtools: { enabled: false },
|
|
1168
|
+
vite: { mode: input.stage },
|
|
1169
|
+
vitehubCliDiscovery: true
|
|
1170
|
+
},
|
|
1171
|
+
ready: true
|
|
1172
|
+
});
|
|
1173
|
+
try {
|
|
1174
|
+
const server = await createStageModuleLoader(vite, {
|
|
1175
|
+
...nuxt.options.vite,
|
|
1176
|
+
...config,
|
|
1177
|
+
configFile: false
|
|
1178
|
+
}, true);
|
|
1179
|
+
const close = server.close.bind(server);
|
|
1180
|
+
server.close = async () => {
|
|
1181
|
+
try {
|
|
1182
|
+
await close();
|
|
1183
|
+
} finally {
|
|
1184
|
+
await nuxt.close();
|
|
1185
|
+
}
|
|
1186
|
+
};
|
|
1187
|
+
return server;
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
await nuxt.close();
|
|
1190
|
+
throw error;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}, {
|
|
1194
|
+
...input,
|
|
1195
|
+
env: explicitEnv
|
|
1196
|
+
}, async (server) => {
|
|
1197
|
+
const selectedPlugin = server.config.plugins.find((plugin) => plugin.name === "@vite-hub/env/vite");
|
|
1198
|
+
const selectedAPI = v.safeParse(v.object({ resolveProjectRoot: v.function() }), selectedPlugin?.api);
|
|
1199
|
+
if (!selectedAPI.success) throw envErrorDiagnostics.ENV_R0027({ message: "[vitehub] The selected stage does not configure the Env plugin." });
|
|
1200
|
+
const selectedRoot = selectedAPI.output.resolveProjectRoot(server.config.root);
|
|
1201
|
+
if (!v.is(v.string(), selectedRoot)) throw envErrorDiagnostics.ENV_R0027({ message: "[vitehub] The selected Env plugin returned an invalid project root." });
|
|
1202
|
+
const modulePath = viteHubEnvServerModulePath(selectedRoot);
|
|
1203
|
+
const inspect = (await server.ssrLoadModule(pathToFileURL(modulePath).href)).inspectServerEnv;
|
|
1204
|
+
if (!v.is(v.function(), inspect)) throw envErrorDiagnostics.ENV_R0027({ message: `[vitehub] The generated Server Env module does not export inspectServerEnv(): ${modulePath}` });
|
|
1205
|
+
const inspection = await inspect();
|
|
1206
|
+
if (!isInspection(inspection)) throw envErrorDiagnostics.ENV_R0028({ message: "[vitehub] inspectServerEnv() returned an invalid result." });
|
|
1207
|
+
return inspection;
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
function displayPath(entry) {
|
|
1211
|
+
return entry.path?.replace(/^env\.server\./, "") ?? "(undisclosed name)";
|
|
1212
|
+
}
|
|
1213
|
+
function displaySource(entry) {
|
|
1214
|
+
if (entry.source === "provider") return `provider:${entry.provider ?? "unknown"}`;
|
|
1215
|
+
return entry.source === "env" ? "host env" : "literal";
|
|
1216
|
+
}
|
|
1217
|
+
function formatTable(rows) {
|
|
1218
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
1219
|
+
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
|
|
1220
|
+
}
|
|
1221
|
+
function writeReport(command, report, context) {
|
|
1222
|
+
const lines = [`Server Env (stage: ${report.stage})`, ""];
|
|
1223
|
+
if (!report.entries.length) lines.push("No Server Env variables declared.");
|
|
1224
|
+
else lines.push(...formatTable([[
|
|
1225
|
+
"VARIABLE",
|
|
1226
|
+
"STATUS",
|
|
1227
|
+
"SOURCE",
|
|
1228
|
+
"REQUIRED",
|
|
1229
|
+
"SECRET"
|
|
1230
|
+
], ...report.entries.map((entry) => [
|
|
1231
|
+
displayPath(entry),
|
|
1232
|
+
isBlockingServerEnvEntry(entry) ? `${entry.status} !` : entry.status,
|
|
1233
|
+
displaySource(entry),
|
|
1234
|
+
entry.required ? "yes" : "no",
|
|
1235
|
+
entry.masked ? "yes" : "no"
|
|
1236
|
+
])]));
|
|
1237
|
+
const blocking = report.entries.filter(isBlockingServerEnvEntry).length;
|
|
1238
|
+
lines.push("", blocking ? `${blocking} of ${report.entries.length} variables would make loadServerEnv() fail.` : `${report.entries.length} variables checked. Values are not shown.`);
|
|
1239
|
+
if (command === "check") lines.push(report.ok ? "Server Env check passed." : "Server Env check failed.");
|
|
1240
|
+
context.stdout.write(`${lines.join("\n")}\n`);
|
|
1241
|
+
}
|
|
1242
|
+
const appEnvResult = v.looseObject({
|
|
1243
|
+
entries: v.array(v.looseObject({
|
|
1244
|
+
blocking: v.boolean(),
|
|
1245
|
+
path: v.optional(v.string()),
|
|
1246
|
+
provider: v.optional(v.string()),
|
|
1247
|
+
required: v.boolean(),
|
|
1248
|
+
secret: v.boolean(),
|
|
1249
|
+
source: v.picklist([
|
|
1250
|
+
"env",
|
|
1251
|
+
"literal",
|
|
1252
|
+
"provider"
|
|
1253
|
+
]),
|
|
1254
|
+
status: v.string()
|
|
1255
|
+
})),
|
|
1256
|
+
ok: v.boolean()
|
|
1257
|
+
});
|
|
1258
|
+
/** `env list --url`: the `env.inspect` operation of the running app, such as a deployment. Values are never returned. */
|
|
1259
|
+
async function listAppEnv(url, json, context) {
|
|
1260
|
+
const message = appUrlError(url);
|
|
1261
|
+
if (message) return writeCliFailure(json, context, { message });
|
|
1262
|
+
const result = await callOperationFromCli({
|
|
1263
|
+
env: context.env,
|
|
1264
|
+
...context.fetch ? { fetch: context.fetch } : {},
|
|
1265
|
+
rootDir: context.rootDir,
|
|
1266
|
+
url
|
|
1267
|
+
}, "env.inspect", {});
|
|
1268
|
+
if (!result.ok) return writeCliFailure(json, context, {
|
|
1269
|
+
code: result.code,
|
|
1270
|
+
...result.fix ? { fix: result.fix } : {},
|
|
1271
|
+
message: result.message
|
|
1272
|
+
});
|
|
1273
|
+
const parsed = v.safeParse(appEnvResult, result.value);
|
|
1274
|
+
if (!parsed.success) return writeCliFailure(json, context, { message: `The app at ${url} returned an env report that this CLI cannot read.` });
|
|
1275
|
+
if (json) {
|
|
1276
|
+
context.stdout.write(`${JSON.stringify(parsed.output, null, 2)}\n`);
|
|
1277
|
+
return 0;
|
|
1278
|
+
}
|
|
1279
|
+
const { entries } = parsed.output;
|
|
1280
|
+
const lines = [`Server Env (app: ${url})`, ""];
|
|
1281
|
+
if (!entries.length) lines.push("No Server Env variables declared.");
|
|
1282
|
+
else lines.push(...formatTable([[
|
|
1283
|
+
"VARIABLE",
|
|
1284
|
+
"STATUS",
|
|
1285
|
+
"SOURCE",
|
|
1286
|
+
"REQUIRED",
|
|
1287
|
+
"SECRET"
|
|
1288
|
+
], ...entries.map((entry) => [
|
|
1289
|
+
entry.path?.replace(/^env\.server\./, "") ?? "(undisclosed name)",
|
|
1290
|
+
entry.blocking ? `${entry.status} !` : entry.status,
|
|
1291
|
+
entry.source === "provider" ? `provider:${entry.provider ?? "unknown"}` : entry.source === "env" ? "host env" : "literal",
|
|
1292
|
+
entry.required ? "yes" : "no",
|
|
1293
|
+
entry.secret ? "yes" : "no"
|
|
1294
|
+
])]));
|
|
1295
|
+
const blocking = entries.filter((entry) => entry.blocking).length;
|
|
1296
|
+
lines.push("", blocking ? `${blocking} of ${entries.length} variables would make loadServerEnv() fail.` : `${entries.length} variables checked. Values are not shown.`);
|
|
1297
|
+
context.stdout.write(`${lines.join("\n")}\n`);
|
|
1298
|
+
return 0;
|
|
1299
|
+
}
|
|
1300
|
+
async function runEnvCli(command, args, context, options) {
|
|
1301
|
+
let parsed;
|
|
1302
|
+
try {
|
|
1303
|
+
parsed = parseArgs(command, args);
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
1306
|
+
writeUsage(command, context.stderr);
|
|
1307
|
+
return 1;
|
|
1308
|
+
}
|
|
1309
|
+
if (parsed.help) {
|
|
1310
|
+
writeUsage(command, context.stdout);
|
|
1311
|
+
return 0;
|
|
1312
|
+
}
|
|
1313
|
+
if (parsed.url) return await listAppEnv(parsed.url, parsed.json, context);
|
|
1314
|
+
const input = {
|
|
1315
|
+
env: context.env,
|
|
1316
|
+
rootDir: context.rootDir,
|
|
1317
|
+
stderr: context.stderr,
|
|
1318
|
+
stage: parsed.stage ?? defaultEnvCliStage
|
|
1319
|
+
};
|
|
1320
|
+
const inspection = options.inspect ? await options.inspect(input) : await inspectStage({
|
|
1321
|
+
...input,
|
|
1322
|
+
applicationRoot: context.cwd
|
|
1323
|
+
});
|
|
1324
|
+
const report = {
|
|
1325
|
+
entries: inspection.entries,
|
|
1326
|
+
ok: !inspection.entries.some(isBlockingServerEnvEntry),
|
|
1327
|
+
stage: input.stage
|
|
1328
|
+
};
|
|
1329
|
+
if (parsed.json) context.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
1330
|
+
else writeReport(command, report, context);
|
|
1331
|
+
return command === "check" && !report.ok ? 1 : 0;
|
|
1332
|
+
}
|
|
1333
|
+
function createEnvCliContributor(options) {
|
|
1334
|
+
return { namespaces: [{
|
|
1335
|
+
description: "Server Env inspection workflows.",
|
|
1336
|
+
features: [{
|
|
1337
|
+
description: "List declared Server Env variables and their status without values. With --url, ask the running app.",
|
|
1338
|
+
name: "list",
|
|
1339
|
+
run: async (args, context) => await runEnvCli("list", args, context, options),
|
|
1340
|
+
usage: usage("list")
|
|
1341
|
+
}, {
|
|
1342
|
+
description: "Exit with 1 when a required Server Env value is missing or any value is invalid.",
|
|
1343
|
+
name: "check",
|
|
1344
|
+
run: async (args, context) => await runEnvCli("check", args, context, options),
|
|
1345
|
+
usage: usage("check")
|
|
1346
|
+
}],
|
|
1347
|
+
name: "env"
|
|
1348
|
+
}, {
|
|
1349
|
+
description: "Generate the root app secret and print derived secrets.",
|
|
1350
|
+
features: secretCliFeatures,
|
|
1351
|
+
name: "secret"
|
|
1352
|
+
}] };
|
|
1353
|
+
}
|
|
1354
|
+
export { VITEHUB_ENV_SERVER as a, createViteHubEnvImportAliases as c, viteHubEnvAmbientTypesPath as d, viteHubEnvDescriptionModulePath as f, viteHubEnvServerModuleTypesPath as g, viteHubEnvServerModulePath as h, VITEHUB_ENV_PUBLIC_ID as i, isServerEnvironment as l, viteHubEnvPublicModuleTypesPath as m, secretCliFeatures as n, VITEHUB_ENV_SERVER_ID as o, viteHubEnvPublicModulePath as p, loadAllEnv as r, createNoExternalAddition as s, createEnvCliContributor as t, resolveViteHubProjectRoot as u };
|