@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.
Files changed (43) hide show
  1. package/README.md +3 -3
  2. package/dist/{access-B8lSDip4.js → access-DIErLk3w.js} +2 -3
  3. package/dist/{bridge-Cs9YfQWk.d.ts → bridge-BWwIooe0.d.ts} +0 -12
  4. package/dist/{bridge-error-BhJ77age.js → bridge-error-DEqzARPJ.js} +1 -3
  5. package/dist/bridge.d.ts +1 -1
  6. package/dist/bridge.js +9 -10
  7. package/dist/{cli-BPp7rdcA.d.ts → cli-B-LW6l_J.d.ts} +1 -6
  8. package/dist/cli-CAlHK5nn.js +1354 -0
  9. package/dist/cli.d.ts +3 -6
  10. package/dist/cli.js +1 -2
  11. package/dist/database.d.ts +2 -4
  12. package/dist/database.js +2 -5
  13. package/dist/{declarations-C5XR3aKw.d.ts → declarations-DNjO52_s.d.ts} +1 -21
  14. package/dist/{schema-C_a0WZyd.js → declarations-meg4Rmgd.js} +43 -105
  15. package/dist/{object-C7Jt4ez2.js → error-diagnostics-5BceFRdD.js} +57 -14
  16. package/dist/{error-diagnostics-DsDPsST_.js → error-diagnostics-BFzFaXcH.js} +2 -4
  17. package/dist/index.d.ts +3 -13
  18. package/dist/index.js +8 -12
  19. package/dist/internal/agent.d.ts +2 -4
  20. package/dist/internal/agent.js +3 -4
  21. package/dist/internal/connections.d.ts +2 -4
  22. package/dist/internal/connections.js +3 -4
  23. package/dist/internal/server.d.ts +2 -2
  24. package/dist/internal/server.js +1 -2
  25. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  26. package/dist/{operations-B1PFpKzy.js → operations-BftegDMd.js} +2 -3
  27. package/dist/operations.d.ts +2 -6
  28. package/dist/operations.js +7 -41
  29. package/dist/runtime/public-env.d.ts +2 -4
  30. package/dist/runtime/public-env.js +2 -3
  31. package/dist/runtime/server-env.d.ts +2 -3
  32. package/dist/runtime/server-env.js +2 -3
  33. package/dist/seal.d.ts +1 -3
  34. package/dist/seal.js +1 -2
  35. package/dist/{secret-DJd-fy5T.js → secret-VhbE53Vm.js} +1 -2
  36. package/dist/{server-CgKAEAE6.d.ts → server-CPEywepM.d.ts} +1 -12
  37. package/dist/{server-B9-8r6MZ.js → server-pTqnkM7n.js} +213 -168
  38. package/dist/server.d.ts +2 -2
  39. package/dist/server.js +1 -2
  40. package/dist/vite.d.ts +5 -17
  41. package/dist/vite.js +20 -37
  42. package/package.json +11 -10
  43. package/dist/cli-C51D6V-M.js +0 -669
@@ -1,669 +0,0 @@
1
- import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
2
- import { C as deriveViteHubSecret, E as readViteHubSecret, a as isBlockingServerEnvEntry, f as invariant } from "./server-B9-8r6MZ.js";
3
- import { createRequire } from "node:module";
4
- import * as v from "valibot";
5
- import { existsSync, statSync } from "node:fs";
6
- import { basename, dirname, join, parse, resolve } from "node:path";
7
- import { pathToFileURL } from "node:url";
8
- import { tmpdir } from "node:os";
9
- import { randomBytes } from "node:crypto";
10
- //#region ../internal/src/cli.ts
11
- const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
12
- const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
13
- const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
14
- const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
15
- const stdoutRedirectGlobal = globalThis;
16
- /**
17
- * Sends `process.stdout` writes to stderr while `run` loads project config.
18
- * Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
19
- */
20
- async function withStdoutOnStderr(run, stderr = process.stderr) {
21
- getStableStdoutWrite();
22
- const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
23
- let release;
24
- stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
25
- release = resolve;
26
- });
27
- await previous;
28
- const write = process.stdout.write;
29
- if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
30
- stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
31
- stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
32
- }
33
- stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
34
- process.stdout.write = ((chunk, encoding, callback) => {
35
- const done = typeof encoding === "function" ? encoding : callback;
36
- let called = false;
37
- const onComplete = (error) => {
38
- if (called) return;
39
- called = true;
40
- done?.(error);
41
- };
42
- const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
43
- if (done && !called) {
44
- if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
45
- else if (stderr.write.length < 2) onComplete();
46
- }
47
- return result;
48
- });
49
- try {
50
- return await run();
51
- } finally {
52
- process.stdout.write = write;
53
- stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
54
- release();
55
- }
56
- }
57
- /**
58
- * A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
59
- * Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
60
- * config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
61
- * then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
62
- */
63
- function createCliDiscoveryNitroCloser() {
64
- const instances = [];
65
- return {
66
- close: async () => {
67
- await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
68
- },
69
- plugin: {
70
- name: "vite-hub/cli-discovery-nitro",
71
- nitro: { setup: (nitro) => {
72
- instances.push(nitro);
73
- } }
74
- }
75
- };
76
- }
77
- /** Returns the unredirected process stdout writer for payload output. */
78
- function getStableStdoutWrite() {
79
- const current = process.stdout.write;
80
- if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
81
- stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
82
- stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
83
- }
84
- return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
85
- }
86
- //#endregion
87
- //#region ../internal/src/build/vite.ts
88
- const projectRootDirectoryMarkers = [
89
- ["server", "agents"],
90
- ["server", "channels"],
91
- ["server", "connections"],
92
- ["server", "browsers"],
93
- ["server", "emails"],
94
- ["server", "schedules"],
95
- ["server", "workspaces"]
96
- ];
97
- const projectRootFileMarkers = [
98
- ["package.json"],
99
- ["nuxt.config.ts"],
100
- ["nuxt.config.mts"],
101
- ["nuxt.config.js"],
102
- ["nuxt.config.mjs"]
103
- ];
104
- const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
105
- const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
106
- const VITEHUB_ENV_DESCRIPTION_ID = "#vitehub/env/description";
107
- function createNoExternalAddition(...packageNames) {
108
- return (current) => {
109
- if (current === true) return;
110
- const values = Array.isArray(current) ? current : [current];
111
- const missing = packageNames.filter((packageName) => !values.includes(packageName));
112
- return missing.length ? missing : void 0;
113
- };
114
- }
115
- function isServerEnvironment(name, config) {
116
- return name === "ssr" || config.consumer === "server";
117
- }
118
- /**
119
- * Server Env declarations that ViteHub features add before `hubEnv()` builds the registry, such as the Server Env of
120
- * discovered Channels. The application's `env.server` wins field by field.
121
- */
122
- const VITEHUB_ENV_SERVER = "__vitehubEnvServer";
123
- function resolveViteHubProjectRoot(root, options = {}) {
124
- const resolvedRoot = resolve(root);
125
- const temporaryRoot = resolve(tmpdir());
126
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
127
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
128
- if (basename(resolvedRoot) === "app") {
129
- const parent = dirname(resolvedRoot);
130
- if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
131
- "nuxt.config.ts",
132
- "nuxt.config.mts",
133
- "nuxt.config.js",
134
- "nuxt.config.mjs"
135
- ]))) return parent;
136
- }
137
- let current = resolvedRoot;
138
- while (true) {
139
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
140
- if (hasProjectRootMarker(current)) return current;
141
- const parent = dirname(current);
142
- if (parent === current) return resolvedRoot;
143
- current = parent;
144
- }
145
- }
146
- function hasProjectRootDirectoryMarker(root) {
147
- for (const marker of projectRootDirectoryMarkers) try {
148
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
149
- } catch (error) {
150
- if (error.code !== "ENOENT") throw error;
151
- }
152
- return false;
153
- }
154
- function hasProjectRootMarker(root) {
155
- if (hasProjectRootDirectoryMarker(root)) return true;
156
- return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
157
- }
158
- function hasProjectRootFileMarker(root, markers) {
159
- for (const marker of markers) {
160
- const path = Array.isArray(marker) ? marker : [marker];
161
- try {
162
- if (statSync(resolve(root, ...path)).isFile()) return true;
163
- } catch (error) {
164
- if (error.code !== "ENOENT") throw error;
165
- }
166
- }
167
- return false;
168
- }
169
- function viteHubEnvAmbientTypesPath(root) {
170
- return resolve(root, ".vitehub", "types", "env.d.ts");
171
- }
172
- function viteHubEnvPublicModulePath(root) {
173
- return resolve(root, ".vitehub", "env", "public.mjs");
174
- }
175
- function viteHubEnvPublicModuleTypesPath(root) {
176
- return resolve(root, ".vitehub", "env", "public.d.ts");
177
- }
178
- function viteHubEnvServerModulePath(root) {
179
- return resolve(root, ".vitehub", "env", "server.mjs");
180
- }
181
- function viteHubEnvDescriptionModulePath(root) {
182
- return resolve(root, ".vitehub", "env", "description.mjs");
183
- }
184
- function viteHubEnvServerModuleTypesPath(root) {
185
- return resolve(root, ".vitehub", "env", "server.d.ts");
186
- }
187
- function createViteHubEnvImportAliases(root) {
188
- return {
189
- [VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
190
- [VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root),
191
- [VITEHUB_ENV_DESCRIPTION_ID]: viteHubEnvDescriptionModulePath(root)
192
- };
193
- }
194
- //#endregion
195
- //#region ../internal/src/vite-stage.ts
196
- /**
197
- * Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
198
- * logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
199
- */
200
- function loadAllEnv(loadEnv, mode, envDir) {
201
- const write = process.stderr.write;
202
- process.stderr.write = () => true;
203
- try {
204
- return loadEnv(mode, envDir, "");
205
- } finally {
206
- process.stderr.write = write;
207
- }
208
- }
209
- const viteStageQueueKey = Symbol.for("vitehub.cli.vite-stage-queue");
210
- function definedEntries(env) {
211
- return Object.entries(env).filter((entry) => entry[1] !== void 0);
212
- }
213
- function replaceProcessEnv(entries) {
214
- for (const key of Object.keys(process.env)) delete process.env[key];
215
- for (const [key, value] of entries) process.env[key] = value;
216
- }
217
- async function runStageServer(vite, input, callback) {
218
- let server;
219
- const selectedEnvironment = definedEntries(input.env);
220
- try {
221
- server = await withStdoutOnStderr(async () => await vite.createServer({
222
- appType: "custom",
223
- ...input.envDir !== void 0 ? { envDir: input.envDir } : {},
224
- logLevel: "silent",
225
- mode: input.stage,
226
- root: input.rootDir,
227
- server: {
228
- hmr: false,
229
- middlewareMode: true
230
- }
231
- }), input.stderr);
232
- for (const [key, value] of [...Object.entries(loadAllEnv(vite.loadEnv, input.stage, server.config.envDir)), ...selectedEnvironment]) process.env[key] = value;
233
- return await callback(server);
234
- } finally {
235
- await withStdoutOnStderr(async () => await server?.close(), input.stderr);
236
- }
237
- }
238
- /**
239
- * Run a CLI operation against a Vite Development Server in the selected stage mode.
240
- *
241
- * During the callback, `process.env` contains the stage-specific Vite env files
242
- * (`.env`, `.env.local`, `.env.<stage>`, `.env.<stage>.local`) with `input.env`
243
- * taking precedence. The previous `process.env` is restored afterwards. Calls run
244
- * one at a time because `process.env` is process-wide.
245
- */
246
- async function withViteStageServer(vite, input, callback) {
247
- return await withViteStageEnvironment(input.env, async () => await runStageServer(vite, input, callback));
248
- }
249
- /** Load stage config and modules under the same serialized, temporary process environment. */
250
- async function withViteStageEnvironment(env, callback) {
251
- const carrier = globalThis;
252
- const previous = carrier[viteStageQueueKey] ?? Promise.resolve();
253
- let release;
254
- carrier[viteStageQueueKey] = new Promise((resolve) => {
255
- release = resolve;
256
- });
257
- await previous;
258
- const previousEnvironment = definedEntries(process.env);
259
- const selectedEnvironment = definedEntries(env);
260
- try {
261
- replaceProcessEnv(selectedEnvironment);
262
- return await callback();
263
- } finally {
264
- replaceProcessEnv(previousEnvironment);
265
- release();
266
- }
267
- }
268
- //#endregion
269
- //#region ../internal/src/console-signature.ts
270
- /** The app reads the public key of the caller `<NAME>` from `VITEHUB_CONSOLE_KEY_<NAME>`. */
271
- const consolePublicKeyPrefix = "VITEHUB_CONSOLE_KEY_";
272
- /** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
273
- const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
274
- const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
275
- new TextEncoder();
276
- new TextDecoder();
277
- const ed25519 = { name: "Ed25519" };
278
- function base64url(bytes) {
279
- let binary = "";
280
- for (const byte of bytes) binary += String.fromCharCode(byte);
281
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
282
- }
283
- /** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
284
- function isConsoleKeyName(name) {
285
- return keyNamePattern.test(name);
286
- }
287
- /** A new key pair: the public key for the app, the private key (the seed) for the caller. Both are base64url. */
288
- async function createConsoleKeyPair() {
289
- const pair = await crypto.subtle.generateKey(ed25519, true, ["sign", "verify"]);
290
- invariant("privateKey" in pair, "Ed25519 generateKey() returns a key pair");
291
- const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
292
- const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
293
- return {
294
- privateKey: base64url(pkcs8.slice(-32)),
295
- publicKey: base64url(publicKey)
296
- };
297
- }
298
- //#endregion
299
- //#region src/secret-cli.ts
300
- const generateUsage = "vitehub secret generate";
301
- const deriveUsage = "vitehub secret derive <purpose>";
302
- const consoleKeyUsage = "vitehub secret console-key [name]";
303
- function help(args) {
304
- return args.includes("-h") || args.includes("--help");
305
- }
306
- function generate(args, context) {
307
- if (help(args)) {
308
- context.stdout.write(`Usage: ${generateUsage}\n\nPrint a new random root secret for VITEHUB_SECRET.\n`);
309
- return 0;
310
- }
311
- if (args.length) {
312
- context.stderr.write(`Unexpected secret generate argument: ${args[0]}\n`);
313
- return 1;
314
- }
315
- context.stdout.write(`${randomBytes(32).toString("base64")}\n`);
316
- return 0;
317
- }
318
- async function derive(args, context) {
319
- if (help(args)) {
320
- context.stdout.write([
321
- `Usage: ${deriveUsage}`,
322
- "",
323
- "Print the secret that deriveSecret(<purpose>) returns for VITEHUB_SECRET.",
324
- "For example, `vitehub secret derive myapp:webhooks` prints the same key on every machine with the same root secret.",
325
- ""
326
- ].join("\n"));
327
- return 0;
328
- }
329
- const [purpose, ...rest] = args;
330
- if (!purpose || rest.length) {
331
- context.stderr.write(`Usage: ${deriveUsage}\n`);
332
- return 1;
333
- }
334
- const root = readViteHubSecret(context.env);
335
- if (!root) {
336
- context.stderr.write("Set VITEHUB_SECRET to the root secret of the deployment.\n");
337
- return 1;
338
- }
339
- if (root.length < 32) {
340
- context.stderr.write(`VITEHUB_SECRET must be at least 32 characters.\n`);
341
- return 1;
342
- }
343
- context.stdout.write(`${await deriveViteHubSecret(root, purpose)}\n`);
344
- return 0;
345
- }
346
- /**
347
- * Print a new Ed25519 key pair for signed Console requests: the public key line for the app, and the private key line
348
- * for the machine or CI job that calls it with `--url`. The name defaults to `CLI`.
349
- */
350
- async function consoleKey(args, context) {
351
- if (help(args)) {
352
- context.stdout.write([
353
- `Usage: ${consoleKeyUsage}`,
354
- "",
355
- "Print a new key pair for signed Console requests. Set the first line on the app (console: true),",
356
- "and the second line where the CLI runs, such as a CI secret. The name defaults to CLI.",
357
- ""
358
- ].join("\n"));
359
- return 0;
360
- }
361
- const [input = "CLI", ...rest] = args;
362
- const name = input.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
363
- if (rest.length || !isConsoleKeyName(name)) {
364
- context.stderr.write(`Usage: ${consoleKeyUsage}\nThe name has 1 to 64 letters, digits, or underscores.\n`);
365
- return 1;
366
- }
367
- const { privateKey, publicKey } = await createConsoleKeyPair();
368
- context.stdout.write([
369
- "# The app: set this variable on the deployment.",
370
- `${consolePublicKeyPrefix}${name}=${publicKey}`,
371
- "# The CLI: keep this one secret, such as in a CI secret. Remove the app variable to revoke it.",
372
- `${consolePrivateKeyPrefix}${name}=${privateKey}`,
373
- ""
374
- ].join("\n"));
375
- return 0;
376
- }
377
- /** `vitehub secret` features. They read only the process env and never load the project. */
378
- const secretCliFeatures = [
379
- {
380
- description: "Print a new random root secret for VITEHUB_SECRET.",
381
- name: "generate",
382
- run: async (args, context) => generate(args, context),
383
- usage: generateUsage
384
- },
385
- {
386
- description: "Print the secret derived from VITEHUB_SECRET for one purpose.",
387
- name: "derive",
388
- run: async (args, context) => await derive(args, context),
389
- usage: deriveUsage
390
- },
391
- {
392
- description: "Print a new key pair for signed Console requests from the CLI.",
393
- name: "console-key",
394
- run: async (args, context) => await consoleKey(args, context),
395
- usage: consoleKeyUsage
396
- }
397
- ];
398
- //#endregion
399
- //#region src/cli.ts
400
- /** CLI discovery resolves Vite config in development mode, so the default stage matches it. */
401
- const defaultEnvCliStage = "development";
402
- function usage(command) {
403
- return `vitehub env ${command} [--stage <name>] [--json]`;
404
- }
405
- function writeUsage(command, stream) {
406
- stream.write([
407
- `Usage: ${usage(command)}`,
408
- "",
409
- 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.",
410
- "",
411
- "Options:",
412
- ` --stage <name> Load Vite env files for this mode. Defaults to ${defaultEnvCliStage}.`,
413
- " Variables from the current process take precedence.",
414
- " --json Print machine-readable output.",
415
- " -h, --help Show this help.",
416
- ""
417
- ].join("\n"));
418
- }
419
- function parseArgs(args) {
420
- const parsed = {
421
- help: false,
422
- json: false
423
- };
424
- for (let index = 0; index < args.length; index++) {
425
- const arg = args[index];
426
- if (arg === "-h" || arg === "--help") parsed.help = true;
427
- else if (arg === "--json") parsed.json = true;
428
- else if (arg === "--stage" || arg.startsWith("--stage=")) {
429
- const value = arg === "--stage" ? args[++index] : arg.slice(8);
430
- if (!value || value.startsWith("-")) throw envErrorDiagnostics.ENV_R0025({ message: "--stage requires a name." });
431
- parsed.stage = value;
432
- } else throw envErrorDiagnostics.ENV_R0026({ message: `Unknown option: ${arg}` });
433
- }
434
- return parsed;
435
- }
436
- function isInspection(value) {
437
- return v.is(v.object({ entries: v.array(v.object({
438
- masked: v.boolean(),
439
- path: v.optional(v.string()),
440
- provider: v.optional(v.string()),
441
- required: v.boolean(),
442
- source: v.picklist([
443
- "env",
444
- "literal",
445
- "provider"
446
- ]),
447
- status: v.picklist([
448
- "available",
449
- "defaulted",
450
- "error",
451
- "invalid",
452
- "missing"
453
- ])
454
- })) }), value);
455
- }
456
- /**
457
- * Resolves the stage config and loads modules in its SSR environment. A dev server would also start every other
458
- * environment, such as Nitro's dev worker, and the check never uses them.
459
- */
460
- async function createStageModuleLoader(vite, config, allowNuxtFallback = false) {
461
- const nitro = createCliDiscoveryNitroCloser();
462
- const ws = {
463
- ...vite.createServerHotChannel(),
464
- clients: /* @__PURE__ */ new Set(),
465
- handleInvoke: async () => ({ error: {
466
- name: "TransportError",
467
- message: "WebSocket transport is disabled during Env inspection."
468
- } })
469
- };
470
- let environment;
471
- let fallback;
472
- const close = async () => {
473
- try {
474
- await fallback?.close();
475
- } finally {
476
- try {
477
- await environment?.close();
478
- } finally {
479
- try {
480
- await ws.close();
481
- } finally {
482
- await nitro.close();
483
- }
484
- }
485
- }
486
- };
487
- try {
488
- const resolved = await vite.resolveConfig({
489
- ...config,
490
- plugins: [...config.plugins ?? [], nitro.plugin]
491
- }, "serve");
492
- environment = await resolved.environments.ssr.dev.createEnvironment("ssr", resolved, { ws });
493
- await environment.init();
494
- let runnable;
495
- if (vite.isRunnableDevEnvironment(environment)) runnable = environment;
496
- else {
497
- if (!allowNuxtFallback) throw envErrorDiagnostics.ENV_R0030({ message: "The SSR environment does not support runnable imports." });
498
- fallback = vite.createRunnableDevEnvironment("ssr", resolved, {
499
- hot: false,
500
- options: { dev: { moduleRunnerTransform: true } }
501
- });
502
- await fallback.init();
503
- runnable = fallback;
504
- }
505
- return {
506
- close,
507
- config: resolved,
508
- ssrLoadModule: async (url) => await runnable.runner.import(url)
509
- };
510
- } catch (error) {
511
- await close().catch(() => {});
512
- throw error;
513
- }
514
- }
515
- async function inspectStage(input) {
516
- const explicitEnv = { ...input.env };
517
- const vite = await import("vite");
518
- const projectRoot = input.applicationRoot ?? input.rootDir;
519
- const hasNuxtConfig = [
520
- "js",
521
- "mjs",
522
- "cjs",
523
- "ts",
524
- "mts",
525
- "cts"
526
- ].some((extension) => existsSync(join(projectRoot, `nuxt.config.${extension}`)));
527
- return await withViteStageServer({
528
- loadEnv: vite.loadEnv,
529
- async createServer(config) {
530
- if (!hasNuxtConfig) return await createStageModuleLoader(vite, config);
531
- const require = createRequire(join(projectRoot, "package.json"));
532
- const kit = await import(pathToFileURL(require.resolve("nuxt/kit")).href);
533
- Object.assign(process.env, loadAllEnv(vite.loadEnv, input.stage, projectRoot));
534
- for (const [key, value] of Object.entries(explicitEnv)) if (value !== void 0) process.env[key] = value;
535
- const nuxt = await kit.loadNuxt({
536
- cwd: projectRoot,
537
- dev: true,
538
- envName: input.stage,
539
- overrides: {
540
- devtools: { enabled: false },
541
- vite: { mode: input.stage },
542
- vitehubCliDiscovery: true
543
- },
544
- ready: true
545
- });
546
- try {
547
- const server = await createStageModuleLoader(vite, {
548
- ...nuxt.options.vite,
549
- ...config,
550
- configFile: false
551
- }, true);
552
- const close = server.close.bind(server);
553
- server.close = async () => {
554
- try {
555
- await close();
556
- } finally {
557
- await nuxt.close();
558
- }
559
- };
560
- return server;
561
- } catch (error) {
562
- await nuxt.close();
563
- throw error;
564
- }
565
- }
566
- }, {
567
- ...input,
568
- env: explicitEnv
569
- }, async (server) => {
570
- const selectedPlugin = server.config.plugins.find((plugin) => plugin.name === "@vite-hub/env/vite");
571
- const selectedAPI = v.safeParse(v.object({ resolveProjectRoot: v.function() }), selectedPlugin?.api);
572
- if (!selectedAPI.success) throw envErrorDiagnostics.ENV_R0027({ message: "[vitehub] The selected stage does not configure the Env plugin." });
573
- const selectedRoot = selectedAPI.output.resolveProjectRoot(server.config.root);
574
- if (!v.is(v.string(), selectedRoot)) throw envErrorDiagnostics.ENV_R0027({ message: "[vitehub] The selected Env plugin returned an invalid project root." });
575
- const modulePath = viteHubEnvServerModulePath(selectedRoot);
576
- const inspect = (await server.ssrLoadModule(pathToFileURL(modulePath).href)).inspectServerEnv;
577
- if (!v.is(v.function(), inspect)) throw envErrorDiagnostics.ENV_R0027({ message: `[vitehub] The generated Server Env module does not export inspectServerEnv(): ${modulePath}` });
578
- const inspection = await inspect();
579
- if (!isInspection(inspection)) throw envErrorDiagnostics.ENV_R0028({ message: "[vitehub] inspectServerEnv() returned an invalid result." });
580
- return inspection;
581
- });
582
- }
583
- function displayPath(entry) {
584
- return entry.path?.replace(/^env\.server\./, "") ?? "(undisclosed name)";
585
- }
586
- function displaySource(entry) {
587
- if (entry.source === "provider") return `provider:${entry.provider ?? "unknown"}`;
588
- return entry.source === "env" ? "host env" : "literal";
589
- }
590
- function formatTable(rows) {
591
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
592
- return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
593
- }
594
- function writeReport(command, report, context) {
595
- const lines = [`Server Env (stage: ${report.stage})`, ""];
596
- if (!report.entries.length) lines.push("No Server Env variables declared.");
597
- else lines.push(...formatTable([[
598
- "VARIABLE",
599
- "STATUS",
600
- "SOURCE",
601
- "REQUIRED",
602
- "SECRET"
603
- ], ...report.entries.map((entry) => [
604
- displayPath(entry),
605
- isBlockingServerEnvEntry(entry) ? `${entry.status} !` : entry.status,
606
- displaySource(entry),
607
- entry.required ? "yes" : "no",
608
- entry.masked ? "yes" : "no"
609
- ])]));
610
- const blocking = report.entries.filter(isBlockingServerEnvEntry).length;
611
- lines.push("", blocking ? `${blocking} of ${report.entries.length} variables would make loadServerEnv() fail.` : `${report.entries.length} variables checked. Values are not shown.`);
612
- if (command === "check") lines.push(report.ok ? "Server Env check passed." : "Server Env check failed.");
613
- context.stdout.write(`${lines.join("\n")}\n`);
614
- }
615
- async function runEnvCli(command, args, context, options) {
616
- let parsed;
617
- try {
618
- parsed = parseArgs(args);
619
- } catch (error) {
620
- context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
621
- writeUsage(command, context.stderr);
622
- return 1;
623
- }
624
- if (parsed.help) {
625
- writeUsage(command, context.stdout);
626
- return 0;
627
- }
628
- const input = {
629
- env: context.env,
630
- rootDir: context.rootDir,
631
- stderr: context.stderr,
632
- stage: parsed.stage ?? defaultEnvCliStage
633
- };
634
- const inspection = options.inspect ? await options.inspect(input) : await inspectStage({
635
- ...input,
636
- applicationRoot: context.cwd
637
- });
638
- const report = {
639
- entries: inspection.entries,
640
- ok: !inspection.entries.some(isBlockingServerEnvEntry),
641
- stage: input.stage
642
- };
643
- if (parsed.json) context.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
644
- else writeReport(command, report, context);
645
- return command === "check" && !report.ok ? 1 : 0;
646
- }
647
- function createEnvCliContributor(options) {
648
- return { namespaces: [{
649
- description: "Server Env inspection workflows.",
650
- features: [{
651
- description: "List declared Server Env variables and their status without values.",
652
- name: "inspect",
653
- run: async (args, context) => await runEnvCli("inspect", args, context, options),
654
- usage: usage("inspect")
655
- }, {
656
- description: "Exit with 1 when a required Server Env value is missing or any value is invalid.",
657
- name: "check",
658
- run: async (args, context) => await runEnvCli("check", args, context, options),
659
- usage: usage("check")
660
- }],
661
- name: "env"
662
- }, {
663
- description: "Generate the root app secret and print derived secrets.",
664
- features: secretCliFeatures,
665
- name: "secret"
666
- }] };
667
- }
668
- //#endregion
669
- 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 };