@vite-hub/env 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +288 -23
  2. package/dist/access-B8lSDip4.js +54 -0
  3. package/dist/bridge-Cs9YfQWk.d.ts +447 -0
  4. package/dist/bridge-error-BhJ77age.js +66 -0
  5. package/dist/bridge.d.ts +2 -0
  6. package/dist/bridge.js +354 -0
  7. package/dist/cli-BPp7rdcA.d.ts +159 -0
  8. package/dist/cli-DLpY0QAo.js +669 -0
  9. package/dist/cli.d.ts +41 -0
  10. package/dist/cli.js +2 -0
  11. package/dist/database.d.ts +47 -0
  12. package/dist/database.js +274 -0
  13. package/dist/declarations-C5XR3aKw.d.ts +58 -0
  14. package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
  15. package/dist/index.d.ts +146 -11
  16. package/dist/index.js +240 -7
  17. package/dist/internal/agent.d.ts +5 -0
  18. package/dist/internal/agent.js +22 -0
  19. package/dist/internal/connections.d.ts +18 -0
  20. package/dist/internal/connections.js +31 -0
  21. package/dist/internal/server.d.ts +3 -0
  22. package/dist/internal/server.js +2 -0
  23. package/dist/object-_dlsZ4lP.js +276 -0
  24. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  25. package/dist/operations-X1w--wds.js +30 -0
  26. package/dist/operations.d.ts +37 -0
  27. package/dist/operations.js +833 -0
  28. package/dist/runtime/public-env.d.ts +5 -0
  29. package/dist/runtime/public-env.js +8 -0
  30. package/dist/runtime/server-env.d.ts +22 -0
  31. package/dist/runtime/server-env.js +35 -0
  32. package/dist/schema-DMZ1_yhY.js +360 -0
  33. package/dist/seal.d.ts +17 -0
  34. package/dist/seal.js +52 -0
  35. package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
  36. package/dist/server-ChNL_Xc3.js +1279 -0
  37. package/dist/server-Dd8bjIKd.d.ts +145 -0
  38. package/dist/server.d.ts +3 -8
  39. package/dist/server.js +2 -3
  40. package/dist/virtual-module.d.ts +9 -5
  41. package/dist/virtual.d.ts +1 -1
  42. package/dist/vite.d.ts +79 -21
  43. package/dist/vite.js +1095 -339
  44. package/package.json +81 -28
  45. package/dist/declarations-CoMmvRqH.js +0 -159
  46. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  47. package/dist/errors-C4Xcs6Fi.js +0 -121
  48. package/dist/presets.d.ts +0 -11
  49. package/dist/presets.js +0 -25
  50. package/dist/provider.d.ts +0 -6
  51. package/dist/provider.js +0 -7
  52. package/dist/schema.d.ts +0 -16
  53. package/dist/schema.js +0 -37
  54. package/dist/secret-C2191nAa.d.ts +0 -11
  55. package/dist/secret.d.ts +0 -2
  56. package/dist/server-C16sFc1E.js +0 -303
  57. package/dist/types-CsB6DTGE.d.ts +0 -190
package/dist/vite.js CHANGED
@@ -1,14 +1,18 @@
1
- import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-CoMmvRqH.js";
2
- import { parseSchema } from "./schema.js";
3
- import { a as isAbortError, n as envSourceFailed, o as missingRequiredEnv, r as invalidEnvDeclaration } from "./errors-C4Xcs6Fi.js";
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-B8RFjQ1V.js";
2
+ import { a as schemaModuleReference, i as runtimeValueSchema, n as descriptorVariable, r as env, t as parseSchema } from "./schema-DMZ1_yhY.js";
3
+ import { A as envValueTypeName, E as readViteHubSecret, F as stringValueSchema, I as isEnvSchemaValue, M as parseEnvValue, P as schemaContainsEnum, S as missingRequiredEnv, b as invalidEnvDeclaration, f as invariant, g as runtimeRegistryEntries, h as isRuntimeProviderEntry, m as isRuntimeLiteralEntry, p as isRuntimeEnvEntry, r as describeServerEnv, x as isAbortError, y as envSourceFailed } from "./server-ChNL_Xc3.js";
4
+ import { a as VITEHUB_ENV_SERVER, c as createViteHubEnvImportAliases, d as viteHubEnvAmbientTypesPath, f as viteHubEnvDescriptionModulePath, g as viteHubEnvServerModuleTypesPath, h as viteHubEnvServerModulePath, i as VITEHUB_ENV_PUBLIC_ID, l as isServerEnvironment, m as viteHubEnvPublicModuleTypesPath, o as VITEHUB_ENV_SERVER_ID, p as viteHubEnvPublicModulePath, r as loadAllEnv, s as createNoExternalAddition, t as createEnvCliContributor, u as resolveViteHubProjectRoot } from "./cli-DLpY0QAo.js";
5
+ import { Diagnostic } from "nostics";
4
6
  import { isViteHubError } from "@vite-hub/runtime";
5
- import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
6
- import { basename, dirname, isAbsolute, parse, relative, resolve, win32 } from "node:path";
7
- import { statSync } from "node:fs";
8
- import { tmpdir } from "node:os";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { dirname, isAbsolute, relative, resolve, win32 } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { chmod, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
11
+ import { createHash, randomBytes } from "node:crypto";
9
12
  import { loadEnv } from "vite";
10
13
  import { execFile } from "node:child_process";
11
14
  import { promisify } from "node:util";
15
+ import { ParsedEnvSpecFunctionCall, ParsedEnvSpecKeyValuePair, ParsedEnvSpecStaticValue, parseEnvSpecDotEnvFile } from "@env-spec/parser";
12
16
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
13
17
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
14
18
  function normalizeWindowsPath(input = "") {
@@ -16,6 +20,7 @@ function normalizeWindowsPath(input = "") {
16
20
  return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
17
21
  }
18
22
  const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
23
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
19
24
  function cwd() {
20
25
  if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
21
26
  return "/";
@@ -87,83 +92,48 @@ function normalizeString(path, allowAboveRoot) {
87
92
  const isAbsolute$1 = function(p) {
88
93
  return _IS_ABSOLUTE_RE.test(p);
89
94
  };
95
+ const dirname$1 = function(p) {
96
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
97
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
98
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
99
+ };
100
+ //#endregion
101
+ //#region ../internal/src/build/paths.ts
102
+ function resolveRuntimeModule(packageDir, modulePath) {
103
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
104
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
105
+ }
106
+ const packageDirs = /* @__PURE__ */ new Map();
107
+ function findPackageDir(file) {
108
+ const start = dirname$1(file);
109
+ const cached = packageDirs.get(start);
110
+ if (cached) return cached;
111
+ let dir = start;
112
+ while (!existsSync(resolve$1(dir, "package.json"))) {
113
+ const parent = dirname$1(dir);
114
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
115
+ dir = parent;
116
+ }
117
+ packageDirs.set(start, dir);
118
+ return dir;
119
+ }
120
+ /**
121
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
122
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
123
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
124
+ */
125
+ function ownModule(importMetaUrl, modulePath) {
126
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
127
+ }
90
128
  //#endregion
91
129
  //#region ../internal/src/definition-catalog.ts
130
+ /** `writeFileIfChangedSync` for async callers. */
92
131
  async function writeFileIfChanged(file, contents) {
93
132
  if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
94
133
  await mkdir(resolve$1(file, ".."), { recursive: true });
95
134
  await writeFile(file, contents, "utf8");
96
135
  }
97
136
  //#endregion
98
- //#region ../internal/src/build/vite.ts
99
- const projectRootDirectoryMarkers = [
100
- ["server", "agents"],
101
- ["server", "channels"],
102
- ["server", "browsers"],
103
- ["server", "emails"],
104
- ["server", "schedules"],
105
- ["server", "workspaces"]
106
- ];
107
- const projectRootFileMarkers = [["package.json"]];
108
- const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
109
- const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
110
- function resolveViteHubProjectRoot(root, options = {}) {
111
- const resolvedRoot = resolve(root);
112
- const temporaryRoot = resolve(tmpdir());
113
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
114
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
115
- if (basename(resolvedRoot) === "app") {
116
- const parent = dirname(resolvedRoot);
117
- if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
118
- }
119
- let current = resolvedRoot;
120
- while (true) {
121
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
122
- if (hasProjectRootMarker(current)) return current;
123
- const parent = dirname(current);
124
- if (parent === current) return resolvedRoot;
125
- current = parent;
126
- }
127
- }
128
- function hasProjectRootDirectoryMarker(root) {
129
- for (const marker of projectRootDirectoryMarkers) try {
130
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
131
- } catch (error) {
132
- if (error.code !== "ENOENT") throw error;
133
- }
134
- return false;
135
- }
136
- function hasProjectRootMarker(root) {
137
- if (hasProjectRootDirectoryMarker(root)) return true;
138
- for (const marker of projectRootFileMarkers) try {
139
- if (statSync(resolve(root, ...marker)).isFile()) return true;
140
- } catch (error) {
141
- if (error.code !== "ENOENT") throw error;
142
- }
143
- return false;
144
- }
145
- function viteHubEnvAmbientTypesPath(root) {
146
- return resolve(root, ".vitehub", "types", "env.d.ts");
147
- }
148
- function viteHubEnvPublicModulePath(root) {
149
- return resolve(root, ".vitehub", "env", "public.mjs");
150
- }
151
- function viteHubEnvPublicModuleTypesPath(root) {
152
- return resolve(root, ".vitehub", "env", "public.d.ts");
153
- }
154
- function viteHubEnvServerModulePath(root) {
155
- return resolve(root, ".vitehub", "env", "server.mjs");
156
- }
157
- function viteHubEnvServerModuleTypesPath(root) {
158
- return resolve(root, ".vitehub", "env", "server.d.ts");
159
- }
160
- function createViteHubEnvImportAliases(root) {
161
- return {
162
- [VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
163
- [VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root)
164
- };
165
- }
166
- //#endregion
167
137
  //#region src/core/diagnostics.ts
168
138
  function shouldTraceDiagnostics(option) {
169
139
  return option === "trace" || process.env.VITEHUB_ENV_TRACE === "true";
@@ -185,12 +155,22 @@ function formatDiagnostics(entries, option = "summary") {
185
155
  //#endregion
186
156
  //#region src/core/resolve.ts
187
157
  const execFileAsync = promisify(execFile);
158
+ const envOptionKeys = /* @__PURE__ */ new Set([
159
+ "define",
160
+ "diagnostics",
161
+ "prefix",
162
+ "projectRoot",
163
+ "providers",
164
+ "public",
165
+ "runtimeImports",
166
+ "server"
167
+ ]);
188
168
  function validateEnvConfigShape(config, _target) {
189
169
  if (!config) return;
190
170
  const viteConfig = config;
191
- for (const key of Object.keys(viteConfig)) if (key !== "define" && key !== "public" && key !== "server") {
171
+ for (const key of Object.keys(viteConfig)) if (!envOptionKeys.has(key)) {
192
172
  const path = `env.${key}`;
193
- throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Vite env config only supports env.public, env.define, and env.server.`);
173
+ throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Declare Env in env.public, env.define, and env.server.`);
194
174
  }
195
175
  for (const [key, declaration] of Object.entries(viteConfig.public || {})) {
196
176
  assertEnvVariableDeclaration(`env.public.${key}`, declaration);
@@ -210,22 +190,20 @@ function createSourceContext(input) {
210
190
  build: { timestamp: () => (/* @__PURE__ */ new Date()).toISOString() },
211
191
  env: input.env,
212
192
  git: {
213
- branch: () => gitOutput(input.rootDir, [
214
- "rev-parse",
215
- "--abbrev-ref",
216
- "HEAD"
217
- ]),
218
- commit: (options) => gitOutput(input.rootDir, options?.short ? [
219
- "rev-parse",
220
- "--short",
221
- "HEAD"
222
- ] : ["rev-parse", "HEAD"]),
223
- ref: async () => envValue(input.env, ["GIT_REF_NAME", "GITHUB_REF_NAME"]) ?? await gitOutput(input.rootDir, [
224
- "rev-parse",
225
- "--abbrev-ref",
226
- "HEAD"
227
- ]),
228
- sha: async (options) => {
193
+ branch: async () => {
194
+ const branch = envValue(input.env, ["GIT_BRANCH", "GITHUB_HEAD_REF"]);
195
+ if (branch) return branch;
196
+ if (Object.hasOwn(input.env, "GITHUB_REF_TYPE") && input.env.GITHUB_REF_TYPE === "branch") {
197
+ const refName = envValue(input.env, ["GITHUB_REF_NAME"]);
198
+ if (refName) return refName;
199
+ }
200
+ return gitOutput(input.rootDir, [
201
+ "rev-parse",
202
+ "--abbrev-ref",
203
+ "HEAD"
204
+ ]);
205
+ },
206
+ commit: async (options) => {
229
207
  const value = envValue(input.env, ["GIT_SHA", "GITHUB_SHA"]);
230
208
  if (value) return options?.short ? value.slice(0, 7) : value;
231
209
  return gitOutput(input.rootDir, options?.short ? [
@@ -237,7 +215,7 @@ function createSourceContext(input) {
237
215
  tag: async () => {
238
216
  const tag = envValue(input.env, ["GIT_TAG"]);
239
217
  if (tag) return tag;
240
- if (input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
218
+ if (Object.hasOwn(input.env, "GITHUB_REF_TYPE") && input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
241
219
  return await gitOutput(input.rootDir, [
242
220
  "describe",
243
221
  "--tags",
@@ -253,16 +231,20 @@ function createSourceContext(input) {
253
231
  }
254
232
  function envValue(env, names) {
255
233
  for (const name of names) {
256
- const value = env[name];
234
+ const value = Object.hasOwn(env, name) ? env[name] : void 0;
257
235
  if (value) return value;
258
236
  }
259
237
  }
260
238
  async function resolveBuildConfig(declarations, input) {
239
+ assertUniqueBuildCanonicalNames(declarations, input.section, input.prefix);
261
240
  const diagnostics = [];
262
241
  const values = {};
263
242
  for (const [key, declaration] of Object.entries(declarations || {})) {
264
- const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, input);
265
- values[key] = result.value;
243
+ const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, {
244
+ ...input,
245
+ prefix: canonicalKey.test(key) ? input.prefix : false
246
+ });
247
+ setOwnValue(values, key, result.value);
266
248
  diagnostics.push(...result.diagnostics);
267
249
  }
268
250
  return {
@@ -271,55 +253,27 @@ async function resolveBuildConfig(declarations, input) {
271
253
  };
272
254
  }
273
255
  async function resolveEnvEntries(declarations, input) {
256
+ assertUniqueBuildCanonicalNames(declarations, input.section, input.prefix);
274
257
  const entries = [];
275
258
  const diagnostics = [];
276
259
  for (const [key, declaration] of Object.entries(declarations || {})) {
277
- const source = resolveEnvSource(declaration, `${input.section}.${key}`, input.prefix);
278
- const resolvedSource = await resolveSourceValue(source, input.context);
279
- const defaulted = typeof resolvedSource.value === "undefined";
280
- const valueForSchema = defaulted ? declaration.default : resolvedSource.value;
281
- if (typeof valueForSchema === "undefined") {
282
- if (declaration.required) {
283
- const path = `${input.section}.${key}`;
284
- throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
285
- }
286
- entries.push({
287
- key,
288
- masked: declaration.secret,
289
- source: resolvedSource.label,
290
- type: declaration.type ?? "undefined",
291
- value: void 0
292
- });
293
- diagnostics.push({
294
- exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
295
- key: `${input.section}.${key}`,
296
- masked: declaration.secret,
297
- mode: declaration.mode,
298
- source: resolvedSource.label,
299
- status: "missing",
300
- timing: input.timing,
301
- type: declaration.type ?? "undefined"
302
- });
303
- continue;
304
- }
305
- const value = parseSchema(declaration.schema, valueForSchema, `${input.section}.${key}`);
306
- const type = declaration.type ?? inferTypeName(value);
260
+ const result = await resolveBuildDeclaration(declaration, `${input.section}.${key}`, input, canonicalKey.test(key));
307
261
  entries.push({
308
262
  key,
309
263
  masked: declaration.secret,
310
- source: resolvedSource.label,
311
- type,
312
- value
264
+ source: result.source,
265
+ type: result.type ?? declaration.type ?? "undefined",
266
+ value: result.value
313
267
  });
314
268
  diagnostics.push({
315
269
  exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
316
270
  key: `${input.section}.${key}`,
317
271
  masked: declaration.secret,
318
272
  mode: declaration.mode,
319
- source: defaulted ? "default" : resolvedSource.label,
320
- status: defaulted ? "defaulted" : "valid",
273
+ source: result.status === "defaulted" ? "default" : result.source,
274
+ status: result.status,
321
275
  timing: input.timing,
322
- type
276
+ type: result.type ?? declaration.type ?? "undefined"
323
277
  });
324
278
  }
325
279
  return {
@@ -328,44 +282,66 @@ async function resolveEnvEntries(declarations, input) {
328
282
  };
329
283
  }
330
284
  function createRuntimeRegistry(declarations, options = {}) {
331
- return buildRegistry(declarations, options.path ?? "env", options.prefix);
285
+ const path = options.path ?? "env";
286
+ try {
287
+ const registry = buildRegistry(declarations, path, options.prefix, options.schemaModules === true);
288
+ assertUniqueCanonicalNames(registry, path);
289
+ return registry;
290
+ } catch (error) {
291
+ if (isClassifiedError(error)) throw error;
292
+ throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
293
+ }
294
+ }
295
+ const canonicalKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
296
+ function claimCanonicalName(owners, canonical, path) {
297
+ if (canonical === void 0) return;
298
+ const owner = owners.get(canonical);
299
+ if (owner !== void 0) throw invalidEnvDeclaration(path, `${path} and ${owner} share the canonical variable name ${canonical}. Rename one, or set hubEnv({ prefix: false }).`);
300
+ owners.set(canonical, path);
301
+ }
302
+ function assertUniqueBuildCanonicalNames(declarations, path, prefix) {
303
+ const owners = /* @__PURE__ */ new Map();
304
+ const visit = (value, valuePath, valuePrefix) => {
305
+ if (isEnvVariableDeclaration(value)) {
306
+ const source = resolveEnvSource(value, valuePath, valuePrefix);
307
+ if (source.kind === "env" && source.canonical !== false) claimCanonicalName(owners, source.canonical, valuePath);
308
+ return;
309
+ }
310
+ if (!isPlainRecord(value)) return;
311
+ for (const [key, child] of Object.entries(value)) visit(child, `${valuePath}.${key}`, canonicalKey.test(key) ? valuePrefix : false);
312
+ };
313
+ visit(declarations, path, prefix);
314
+ }
315
+ function assertUniqueCanonicalNames(registry, path) {
316
+ const owners = /* @__PURE__ */ new Map();
317
+ const visit = (value, valuePath) => {
318
+ if (!isPlainRecord(value)) return;
319
+ const source = value.source;
320
+ if (isPlainRecord(source) && source.kind === "env") {
321
+ if (typeof source.canonical !== "string") return;
322
+ claimCanonicalName(owners, source.canonical, valuePath);
323
+ return;
324
+ }
325
+ if (value.kind === "literal" || isPlainRecord(source)) return;
326
+ for (const [key, child] of Object.entries(value)) visit(child, `${valuePath}.${key}`);
327
+ };
328
+ visit(registry, path);
332
329
  }
333
330
  async function resolveBuildConfigValue(declaration, path, input) {
334
331
  if (isEnvVariableDeclaration(declaration)) {
335
- const source = resolveEnvSource(declaration, path, input.prefix);
336
- const resolvedSource = await resolveSourceValue(source, input.context);
337
- const defaulted = typeof resolvedSource.value === "undefined";
338
- const valueForSchema = defaulted ? declaration.default : resolvedSource.value;
339
- if (typeof valueForSchema === "undefined") {
340
- if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
341
- return {
342
- diagnostics: [{
343
- exposed: input.exposure,
344
- key: path,
345
- masked: false,
346
- mode: declaration.mode,
347
- source: resolvedSource.label,
348
- status: "missing",
349
- timing: input.timing,
350
- type: declaration.type ?? "undefined"
351
- }],
352
- value: void 0
353
- };
354
- }
355
- const value = parseSchema(declaration.schema, valueForSchema, path);
356
- const type = declaration.type ?? inferTypeName(value);
332
+ const result = await resolveBuildDeclaration(declaration, path, input);
357
333
  return {
358
334
  diagnostics: [{
359
335
  exposed: input.exposure,
360
336
  key: path,
361
337
  masked: false,
362
338
  mode: declaration.mode,
363
- source: defaulted ? "default" : resolvedSource.label,
364
- status: defaulted ? "defaulted" : "valid",
339
+ source: result.status === "defaulted" ? "default" : result.source,
340
+ status: result.status,
365
341
  timing: input.timing,
366
- type
342
+ type: result.type ?? declaration.type ?? "undefined"
367
343
  }],
368
- value
344
+ value: result.value
369
345
  };
370
346
  }
371
347
  if (isBuildStaticValue(declaration)) return {
@@ -376,8 +352,11 @@ async function resolveBuildConfigValue(declaration, path, input) {
376
352
  const value = {};
377
353
  const diagnostics = [];
378
354
  for (const [key, child] of Object.entries(declaration)) {
379
- const result = await resolveBuildConfigValue(child, `${path}.${key}`, input);
380
- value[key] = result.value;
355
+ const result = await resolveBuildConfigValue(child, `${path}.${key}`, {
356
+ ...input,
357
+ prefix: canonicalKey.test(key) ? input.prefix : false
358
+ });
359
+ setOwnValue(value, key, result.value);
381
360
  diagnostics.push(...result.diagnostics);
382
361
  }
383
362
  return {
@@ -385,36 +364,128 @@ async function resolveBuildConfigValue(declaration, path, input) {
385
364
  value
386
365
  };
387
366
  }
388
- function buildRegistry(declarations, path, prefix) {
367
+ async function resolveBuildDeclaration(declaration, path, input, canonical = true) {
368
+ if (schemaModuleReference(declaration.schema)) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(), which only env.server supports. Build-time values run the schema object itself.`);
369
+ const defaultValue = parseDeclarationDefault(declaration, path);
370
+ const source = resolveEnvSource(declaration, path, canonical ? input.prefix : false);
371
+ const resolvedSource = await resolveSourceValue(source, input.context);
372
+ const defaulted = typeof resolvedSource.value === "undefined";
373
+ const valueForSchema = defaulted ? defaultValue : resolvedSource.value;
374
+ if (typeof valueForSchema === "undefined") {
375
+ if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
376
+ return {
377
+ source: resolvedSource.label,
378
+ status: "missing",
379
+ value: void 0
380
+ };
381
+ }
382
+ const value = parseSchema(declaration.schema, valueForSchema, path);
383
+ const type = declaration.type ?? inferTypeName(value);
384
+ return {
385
+ source: resolvedSource.label,
386
+ status: defaulted ? "defaulted" : "valid",
387
+ type,
388
+ value
389
+ };
390
+ }
391
+ function parseDeclarationDefault(declaration, path) {
392
+ const schema = runtimeValueSchema(declaration);
393
+ return schema && declaration.default !== void 0 ? parseRuntimeDefault(schema, declaration.default, path) : declaration.default;
394
+ }
395
+ function buildRegistry(declarations, path, prefix, schemaModules) {
389
396
  if (typeof declarations === "undefined") return {};
390
397
  if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
391
- return Object.fromEntries(Object.entries(declarations).map(([key, value]) => {
392
- const valuePath = `${path}.${key}`;
393
- if (!isEnvVariableDeclaration(value)) {
394
- if (isRuntimeStaticValue(value)) return [key, {
395
- kind: "literal",
396
- value
398
+ try {
399
+ return Object.fromEntries(Object.entries(declarations).map(([key, value]) => {
400
+ const valuePath = `${path}.${key}`;
401
+ if (!isEnvVariableDeclaration(value)) {
402
+ if (isRuntimeStaticValue(value)) return [key, {
403
+ kind: "literal",
404
+ value
405
+ }];
406
+ if (!isPlainRecord(value)) throw invalidEnvDeclaration(valuePath, `Invalid runtime declaration at ${valuePath}. Use env(), a serializable static value, or a nested object.`);
407
+ return [key, buildRegistry(value, valuePath, canonicalKey.test(key) ? prefix : false, schemaModules)];
408
+ }
409
+ if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
410
+ const source = resolveEnvSource(value, valuePath, canonicalKey.test(key) ? prefix : false);
411
+ if (source.kind !== "env" && source.kind !== "provider") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() or env.provider().`);
412
+ const schemaModule = schemaModuleReference(value.schema);
413
+ if (schemaModule) {
414
+ if (!schemaModules) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses env.schemaFrom(), which only env.server supports.`);
415
+ if (value.type) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses env.schemaFrom(), so its type comes from the schema. Remove the type option.`);
416
+ return [key, {
417
+ default: value.default,
418
+ required: value.required,
419
+ schemaModule,
420
+ secret: value.secret,
421
+ source
422
+ }];
423
+ }
424
+ const schema = runtimeValueSchema(value);
425
+ if (!schema) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema object. Server Env runs in the server build, so export the schema from a module and use env.schemaFrom(), or use env(), env.boolean(), env.number(), env.enum(), env.list(), or env.json().`);
426
+ if (schemaContainsEnum(schema) && value.secret) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} cannot be a secret enum: generated types, the Console, and errors show its allowed values. Use env({ secret: true }) and check the value in server code.`);
427
+ const type = envValueTypeName(schema);
428
+ if (value.type && value.type !== type) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses type ${JSON.stringify(value.type)}, but its parser produces ${type}. Use env.boolean(), env.number(), env.enum(), env.list(), or env.json() to parse other types.`);
429
+ return [key, {
430
+ default: typeof value.default === "undefined" ? void 0 : parseRuntimeDefault(schema, value.default, valuePath),
431
+ required: value.required,
432
+ schema,
433
+ secret: value.secret,
434
+ source
397
435
  }];
398
- if (!isPlainRecord(value)) throw invalidEnvDeclaration(valuePath, `Invalid runtime declaration at ${valuePath}. Use env(), a serializable static value, or a nested object.`);
399
- return [key, buildRegistry(value, valuePath, prefix)];
400
- }
401
- if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
402
- const source = resolveEnvSource(value, valuePath, prefix);
403
- if (source.kind !== "env" && source.kind !== "provider") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() or env.provider().`);
404
- if (!isDefaultStringEnvVariable(value)) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema, but runtime schemas cannot be serialized in v1.`);
405
- if (value.type && value.type !== "string") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses type ${JSON.stringify(value.type)}, but runtime values are strings in v1.`);
406
- return [key, {
407
- default: typeof value.default === "undefined" ? void 0 : parseSchema(defaultStringSchema, value.default, valuePath),
408
- required: value.required,
409
- schema: { kind: "string" },
410
- secret: value.secret,
411
- source,
412
- type: value.type
413
- }];
414
- }));
436
+ }));
437
+ } catch (error) {
438
+ if (isClassifiedError(error)) throw error;
439
+ throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
440
+ }
441
+ }
442
+ function isClassifiedError(error) {
443
+ return isViteHubError(error) || error instanceof Diagnostic;
415
444
  }
416
- function resolveEnvSource(declaration, path, prefix = "") {
417
- return declaration.source ?? inferEnvSource(path, prefix);
445
+ function setOwnValue(record, key, value) {
446
+ Object.defineProperty(record, key, {
447
+ configurable: true,
448
+ enumerable: true,
449
+ value,
450
+ writable: true
451
+ });
452
+ }
453
+ function parseRuntimeDefault(schema, value, path) {
454
+ const result = (schema.kind === "boolean" || schema.kind === "number" ? typeof value === schema.kind : schema.kind === "list" ? Array.isArray(value) : true) ? parseEnvValue(schema, value) : {
455
+ message: `Expected a ${schema.kind === "list" ? "array" : schema.kind} default.`,
456
+ success: false
457
+ };
458
+ if (!result.success) throw envErrorDiagnostics.ENV_R0023({ message: `[vitehub] Invalid default for ${path}: ${result.message}` });
459
+ return schema.kind === "json" ? value : result.data;
460
+ }
461
+ /** The default prefix of canonical variable names. */
462
+ const defaultEnvPrefix = "VITEHUB_";
463
+ /**
464
+ * The canonical variable name of a declaration path: the prefix plus the path in upper snake case.
465
+ * `env.server.cliproxy.apiKey` becomes `VITEHUB_CLIPROXY_API_KEY`. `false` disables canonical names.
466
+ */
467
+ function canonicalEnvName(path, prefix = defaultEnvPrefix) {
468
+ return prefix === false ? void 0 : `${prefix}${pathToEnvName(path)}`;
469
+ }
470
+ /**
471
+ * Resolve the source of a declaration. An env source reads the canonical name first, then its
472
+ * conventional names: the explicit `env.source()` names, or the unprefixed path name.
473
+ */
474
+ function resolveEnvSource(declaration, path, prefix = defaultEnvPrefix) {
475
+ const source = declaration.source ?? inferEnvSource(path);
476
+ const canonical = canonicalEnvName(path, prefix);
477
+ if (source.kind !== "env" || canonical === void 0 || source.canonical === false) return source;
478
+ if (canonical === "VITEHUB_HOST") throw invalidEnvDeclaration(path, "VITEHUB_HOST is reserved for deployment host selection. Use env.source(\"APP_HOST\", { canonical: false }) for an application host value, or change the Env prefix.");
479
+ const names = [.../* @__PURE__ */ new Set([canonical, ...source.names ?? [source.name]])];
480
+ return names.length === 1 ? {
481
+ ...source,
482
+ canonical
483
+ } : {
484
+ ...source,
485
+ canonical,
486
+ label: `env:${names.join("|")}`,
487
+ names
488
+ };
418
489
  }
419
490
  function inferTypeName(value) {
420
491
  if (Array.isArray(value)) return "unknown[]";
@@ -435,8 +506,8 @@ async function resolveSourceValue(source, context) {
435
506
  };
436
507
  case "env":
437
508
  for (const name of source.names || [source.name]) {
438
- const value = context.env[name];
439
- if (typeof value !== "undefined") return {
509
+ const value = Object.hasOwn(context.env, name) ? context.env[name] : void 0;
510
+ if (typeof value !== "undefined" && value !== "") return {
440
511
  label: `env:${name}`,
441
512
  value
442
513
  };
@@ -453,14 +524,6 @@ async function resolveSourceValue(source, context) {
453
524
  label: source.label,
454
525
  value: await resolveBuiltInSource(source.label, () => context.git.commit({ short: source.short }))
455
526
  };
456
- case "git-ref": return {
457
- label: source.label,
458
- value: await resolveBuiltInSource(source.label, () => context.git.ref())
459
- };
460
- case "git-sha": return {
461
- label: source.label,
462
- value: await resolveBuiltInSource(source.label, () => context.git.sha({ short: source.short }))
463
- };
464
527
  case "git-tag": return {
465
528
  label: source.label,
466
529
  value: await resolveBuiltInSource(source.label, () => context.git.tag())
@@ -484,25 +547,31 @@ async function resolveBuiltInSource(source, resolveSource) {
484
547
  throw envSourceFailed(source, cause);
485
548
  }
486
549
  }
487
- function validateBuildDeclarations(declarations, path) {
550
+ function validateBuildDeclarations(declarations, path, ancestors = /* @__PURE__ */ new Set()) {
488
551
  if (typeof declarations === "undefined") return;
489
552
  if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
490
- for (const [key, declaration] of Object.entries(declarations)) {
491
- const valuePath = `${path}.${key}`;
492
- if (isEnvVariableDeclaration(declaration)) {
493
- if (declaration.mode !== "build") throw invalidEnvDeclaration(valuePath, `${valuePath} must use mode: "build".`);
494
- if (declaration.secret) throw invalidEnvDeclaration(valuePath, `${valuePath} cannot be marked secret because Vite define values are bundled.`);
495
- continue;
553
+ if (ancestors.has(declarations)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Nested environment declarations cannot contain cycles.`);
554
+ ancestors.add(declarations);
555
+ try {
556
+ for (const [key, declaration] of Object.entries(declarations)) {
557
+ const valuePath = `${path}.${key}`;
558
+ if (isEnvVariableDeclaration(declaration)) {
559
+ if (declaration.mode !== "build") throw invalidEnvDeclaration(valuePath, `${valuePath} must use mode: "build".`);
560
+ if (declaration.secret) throw invalidEnvDeclaration(valuePath, `${valuePath} cannot be marked secret because Vite define values are bundled.`);
561
+ continue;
562
+ }
563
+ if (isBuildStaticValue(declaration)) continue;
564
+ validateBuildDeclarations(declaration, valuePath, ancestors);
496
565
  }
497
- if (isBuildStaticValue(declaration)) continue;
498
- validateBuildDeclarations(declaration, valuePath);
566
+ } finally {
567
+ ancestors.delete(declarations);
499
568
  }
500
569
  }
501
570
  function assertEnvVariableDeclaration(path, declaration) {
502
571
  if (!isEnvVariableDeclaration(declaration)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env().`);
503
572
  }
504
- function inferEnvSource(path, prefix) {
505
- const name = `${prefix}${pathToEnvName(path)}`;
573
+ function inferEnvSource(path) {
574
+ const name = pathToEnvName(path);
506
575
  return {
507
576
  kind: "env",
508
577
  label: `env:${name}`,
@@ -517,32 +586,50 @@ function segmentToEnvParts(segment) {
517
586
  return segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").split("_").map((part) => part.toUpperCase()).filter(Boolean);
518
587
  }
519
588
  function isEnvVariableDeclaration(value) {
520
- return isPlainRecord(value) && value.kind === "env-variable";
589
+ try {
590
+ return isPlainRecord(value) && value.kind === "env-variable";
591
+ } catch {
592
+ return false;
593
+ }
521
594
  }
522
595
  function isPlainRecord(value) {
523
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
524
- const prototype = Object.getPrototypeOf(value);
525
- return prototype === null || prototype === Object.prototype;
596
+ try {
597
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
598
+ const prototype = Object.getPrototypeOf(value);
599
+ return prototype === null || prototype === Object.prototype;
600
+ } catch {
601
+ return false;
602
+ }
526
603
  }
527
604
  function isRuntimeStaticValue(value) {
528
605
  return isBuildStaticValue(value);
529
606
  }
530
- function isBuildStaticValue(value) {
531
- if (value === null) return true;
532
- switch (typeof value) {
533
- case "boolean":
534
- case "string": return true;
535
- case "number": return Number.isFinite(value);
536
- case "object":
537
- if (!Array.isArray(value)) return false;
538
- for (let index = 0; index < value.length; index += 1) if (!(index in value) || !isBuildStaticValue(value[index])) return false;
539
- return true;
540
- default: return false;
607
+ function isBuildStaticValue(value, ancestors = /* @__PURE__ */ new Set()) {
608
+ try {
609
+ if (value === null) return true;
610
+ switch (typeof value) {
611
+ case "boolean":
612
+ case "string": return true;
613
+ case "number": return Number.isFinite(value);
614
+ case "object":
615
+ if (!Array.isArray(value)) return false;
616
+ if (ancestors.has(value)) return false;
617
+ ancestors.add(value);
618
+ try {
619
+ for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !isBuildStaticValue(value[index], ancestors)) return false;
620
+ return true;
621
+ } finally {
622
+ ancestors.delete(value);
623
+ }
624
+ default: return false;
625
+ }
626
+ } catch {
627
+ return false;
541
628
  }
542
629
  }
543
630
  async function readPackageJson(rootDir) {
544
631
  const value = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
545
- if (!isPlainRecord(value)) throw new TypeError("package.json must contain an object.");
632
+ if (!isPlainRecord(value)) throw envErrorDiagnostics.ENV_R0012({ message: "package.json must contain an object." });
546
633
  return value;
547
634
  }
548
635
  async function gitOutput(rootDir, args) {
@@ -552,21 +639,466 @@ async function gitOutput(rootDir, args) {
552
639
  function readPath(value, path) {
553
640
  return path.split(".").reduce((current, segment) => {
554
641
  if (typeof current !== "object" || current === null) return;
642
+ if (!Object.hasOwn(current, segment)) return void 0;
555
643
  return current[segment];
556
644
  }, value);
557
645
  }
558
646
  //#endregion
647
+ //#region src/env-schema/profile.ts
648
+ function fail$1(context, reason) {
649
+ throw envErrorDiagnostics.ENV_B0006({ message: `${context.file}:${context.line}${context.key ? ` (${context.key})` : ""}: ${reason}` });
650
+ }
651
+ function locationLine(location, end = false) {
652
+ if (typeof location !== "object" || location === null) return 1;
653
+ const point = end && "end" in location ? location.end : "start" in location ? location.start : void 0;
654
+ if (typeof point === "object" && point !== null && "line" in point && typeof point.line === "number" && Number.isInteger(point.line) && point.line > 0) return point.line;
655
+ return 1;
656
+ }
657
+ function staticValue(node, context) {
658
+ if (!(node instanceof ParsedEnvSpecStaticValue)) fail$1(context, "Only static values are supported");
659
+ const value = node.unescapedValue;
660
+ if (value === void 0 || typeof value === "string" || typeof value === "boolean" || typeof value === "number") return value;
661
+ return fail$1(context, "Unsupported static value");
662
+ }
663
+ function booleanDecorator(decorator, context) {
664
+ const value = staticValue(decorator.value, context);
665
+ if (typeof value !== "boolean") fail$1(context, "Decorator requires a static boolean");
666
+ return value;
667
+ }
668
+ function decorators(nodes, allowed, context) {
669
+ const result = /* @__PURE__ */ new Map();
670
+ for (const node of nodes) {
671
+ const here = {
672
+ ...context,
673
+ line: locationLine(node.data._location)
674
+ };
675
+ if (node.hasInvalidName || !allowed.includes(node.name) || node.strayText || node.isBareFnCall) fail$1(here, "Unsupported or malformed decorator");
676
+ if (result.has(node.name)) fail$1(here, "Duplicate decorator");
677
+ result.set(node.name, node);
678
+ }
679
+ return result;
680
+ }
681
+ function typeArguments(call, allowed, context) {
682
+ const args = /* @__PURE__ */ new Map();
683
+ for (const arg of call.data.args.values) {
684
+ if (!(arg instanceof ParsedEnvSpecKeyValuePair) || !allowed.includes(arg.key)) fail$1(context, "Unsupported type argument");
685
+ if (args.has(arg.key)) fail$1(context, "Duplicate type argument");
686
+ args.set(arg.key, staticValue(arg.value, context));
687
+ }
688
+ return args;
689
+ }
690
+ function numericArgument(args, name, context, length = false) {
691
+ if (!args.has(name)) return void 0;
692
+ const value = args.get(name);
693
+ if (typeof value !== "number" || !Number.isFinite(value) || length && (!Number.isSafeInteger(value) || value < 0)) fail$1(context, "Invalid numeric type argument");
694
+ return value;
695
+ }
696
+ function parseType(decorator, context) {
697
+ if (!decorator) return { kind: "string" };
698
+ return parseTypeNode(decorator.value, context);
699
+ }
700
+ function parseTypeNode(node, context, depth = 0) {
701
+ if (depth > 16) fail$1(context, "Type nesting exceeds 16 levels");
702
+ const name = node instanceof ParsedEnvSpecFunctionCall ? node.name : staticValue(node, context);
703
+ if (name === "array") {
704
+ const args = node instanceof ParsedEnvSpecFunctionCall ? node.data.args.values : [];
705
+ if (args.length > 1 || args[0] instanceof ParsedEnvSpecKeyValuePair) fail$1(context, "Array requires at most one item type");
706
+ return {
707
+ kind: "array",
708
+ ...args.length && { items: parseTypeNode(args[0], context, depth + 1) }
709
+ };
710
+ }
711
+ if (name === "object") {
712
+ if (!(node instanceof ParsedEnvSpecFunctionCall)) return { kind: "object" };
713
+ const entries = /* @__PURE__ */ new Map();
714
+ for (const arg of node.data.args.values) {
715
+ if (!(arg instanceof ParsedEnvSpecKeyValuePair) || !/^[A-Z_$][\w$]*$/i.test(arg.key) || [
716
+ "__proto__",
717
+ "prototype",
718
+ "constructor",
719
+ "__envSchemaUnset"
720
+ ].includes(arg.key)) fail$1(context, "Object requires safe named property types");
721
+ if (entries.has(arg.key)) fail$1(context, "Duplicate object property");
722
+ entries.set(arg.key, parseTypeNode(arg.value, context, depth + 1));
723
+ }
724
+ return {
725
+ kind: "object",
726
+ properties: Object.fromEntries(entries)
727
+ };
728
+ }
729
+ if (name === "enum") {
730
+ if (!(node instanceof ParsedEnvSpecFunctionCall) || node.data.args.values.length === 0) fail$1(context, "Enum requires string choices");
731
+ const values = node.data.args.values.map((arg) => {
732
+ const value = staticValue(arg, context);
733
+ if (typeof value !== "string" || value === "") fail$1(context, "Enum requires nonempty string choices");
734
+ return value;
735
+ });
736
+ if (new Set(values).size !== values.length) fail$1(context, "Duplicate enum choice");
737
+ return {
738
+ kind: "enum",
739
+ values
740
+ };
741
+ }
742
+ if (name === "string") {
743
+ const args = node instanceof ParsedEnvSpecFunctionCall ? typeArguments(node, ["minLength", "maxLength"], context) : /* @__PURE__ */ new Map();
744
+ const minLength = numericArgument(args, "minLength", context, true);
745
+ const maxLength = numericArgument(args, "maxLength", context, true);
746
+ if (minLength !== void 0 && maxLength !== void 0 && minLength > maxLength) fail$1(context, "Minimum length exceeds maximum length");
747
+ return {
748
+ kind: "string",
749
+ ...minLength !== void 0 && { minLength },
750
+ ...maxLength !== void 0 && { maxLength }
751
+ };
752
+ }
753
+ if (name === "number") {
754
+ const args = node instanceof ParsedEnvSpecFunctionCall ? typeArguments(node, [
755
+ "min",
756
+ "max",
757
+ "isInt"
758
+ ], context) : /* @__PURE__ */ new Map();
759
+ const min = numericArgument(args, "min", context);
760
+ const max = numericArgument(args, "max", context);
761
+ const isInt = args.get("isInt");
762
+ if (args.has("isInt") && typeof isInt !== "boolean") fail$1(context, "Integer constraint requires a static boolean");
763
+ if (min !== void 0 && max !== void 0 && min > max) fail$1(context, "Minimum exceeds maximum");
764
+ return {
765
+ kind: "number",
766
+ ...min !== void 0 && { min },
767
+ ...max !== void 0 && { max },
768
+ ...typeof isInt === "boolean" && { isInt }
769
+ };
770
+ }
771
+ if (name === "boolean" || name === "url") {
772
+ if (node instanceof ParsedEnvSpecFunctionCall) typeArguments(node, [], context);
773
+ return { kind: name };
774
+ }
775
+ return fail$1(context, "Unsupported type");
776
+ }
777
+ function lexicalValue(node, context) {
778
+ if (node.data.quote) {
779
+ const value = staticValue(node, context);
780
+ if (typeof value !== "string") fail$1(context, "Invalid quoted default");
781
+ return value;
782
+ }
783
+ const raw = node.data.rawValue;
784
+ if (raw === void 0) return void 0;
785
+ if (typeof raw !== "string") fail$1(context, "Invalid default");
786
+ const value = raw.trim();
787
+ if (!value) return void 0;
788
+ if (/^["'`[{]/.test(value) || /^[A-Z]\w*\(/i.test(value)) fail$1(context, "Unsupported or malformed default expression");
789
+ const decoded = staticValue(node, context);
790
+ return typeof decoded === "string" ? decoded : value;
791
+ }
792
+ function validUrl(value) {
793
+ try {
794
+ return !!new URL(value).protocol;
795
+ } catch {
796
+ return false;
797
+ }
798
+ }
799
+ function matchesStructuredType(value, type) {
800
+ switch (type.kind) {
801
+ case "array": {
802
+ const items = type.items;
803
+ return Array.isArray(value) && (!items || value.every((item) => matchesStructuredType(item, items)));
804
+ }
805
+ case "object": {
806
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
807
+ const properties = type.properties;
808
+ return !properties || Object.keys(value).length === Object.keys(properties).length && Object.entries(properties).every(([key, property]) => {
809
+ const item = value[key];
810
+ return Object.hasOwn(value, key) && item !== void 0 && matchesStructuredType(item, property);
811
+ });
812
+ }
813
+ case "string": return typeof value === "string" && (type.minLength === void 0 || value.length >= type.minLength) && (type.maxLength === void 0 || value.length <= type.maxLength);
814
+ case "number": return typeof value === "number" && (!type.isInt || Number.isSafeInteger(value)) && (type.min === void 0 || value >= type.min) && (type.max === void 0 || value <= type.max);
815
+ case "boolean": return typeof value === "boolean";
816
+ case "enum": return typeof value === "string" && type.values.includes(value);
817
+ case "url": return typeof value === "string" && validUrl(value);
818
+ }
819
+ }
820
+ function parseDefault(value, type, required, context) {
821
+ if (value === void 0) return void 0;
822
+ if (value === "") {
823
+ if (required) fail$1(context, "Required default cannot be empty");
824
+ if (type.kind !== "string") return void 0;
825
+ }
826
+ switch (type.kind) {
827
+ case "array":
828
+ case "object": {
829
+ let parsed;
830
+ try {
831
+ parsed = JSON.parse(value);
832
+ } catch {
833
+ fail$1(context, "Default must be valid JSON");
834
+ }
835
+ if (!isEnvSchemaValue(parsed) || !matchesStructuredType(parsed, type)) fail$1(context, "Default does not match the declared JSON type");
836
+ return parsed;
837
+ }
838
+ case "string":
839
+ if (type.minLength !== void 0 && value.length < type.minLength || type.maxLength !== void 0 && value.length > type.maxLength) fail$1(context, "Default violates string length constraints");
840
+ return value;
841
+ case "number": {
842
+ const text = value.trim();
843
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(text)) fail$1(context, "Default must be a finite decimal number");
844
+ const number = Number(text);
845
+ if (!Number.isFinite(number) || type.isInt && !Number.isSafeInteger(number) || type.min !== void 0 && number < type.min || type.max !== void 0 && number > type.max) fail$1(context, "Default violates number constraints");
846
+ return number;
847
+ }
848
+ case "boolean":
849
+ if (value.trim() === "true" || value.trim() === "1") return true;
850
+ if (value.trim() === "false" || value.trim() === "0") return false;
851
+ return fail$1(context, "Default must be a boolean");
852
+ case "enum":
853
+ if (!type.values.includes(value)) fail$1(context, "Default is not an enum choice");
854
+ return value;
855
+ case "url":
856
+ if (!validUrl(value)) fail$1(context, "Default must be an absolute URL");
857
+ return value;
858
+ }
859
+ }
860
+ function parseEnvSchema(source, filename) {
861
+ let parsed;
862
+ try {
863
+ parsed = parseEnvSpecDotEnvFile(source);
864
+ } catch (error) {
865
+ return fail$1({
866
+ file: filename,
867
+ line: locationLine(typeof error === "object" && error !== null && "location" in error ? error.location : void 0)
868
+ }, "Invalid env-spec syntax");
869
+ }
870
+ const rootContext = {
871
+ file: filename,
872
+ line: 1
873
+ };
874
+ for (const block of parsed.headerBlocks) if (block.decoratorsArray.length && !block.divider) fail$1({
875
+ file: filename,
876
+ line: locationLine(block.data._location)
877
+ }, "Root decorators require a header divider");
878
+ for (const block of parsed.orphanCommentBlocks) if (block.decoratorsArray.length) fail$1({
879
+ file: filename,
880
+ line: locationLine(block.data._location)
881
+ }, "Decorator is not attached to a declaration");
882
+ const root = decorators(parsed.decoratorsArray, ["defaultRequired", "defaultSensitive"], rootContext);
883
+ const defaultRequired = root.get("defaultRequired");
884
+ const defaultSensitive = root.get("defaultSensitive");
885
+ const required = defaultRequired ? booleanDecorator(defaultRequired, rootContext) : true;
886
+ const sensitive = defaultSensitive ? booleanDecorator(defaultSensitive, rootContext) : true;
887
+ const keys = /* @__PURE__ */ new Set();
888
+ return parsed.configItems.map((item) => {
889
+ const line = Math.max(locationLine(item.data._location), ...item.data.preComments.map((comment) => locationLine(comment.data._location, true) + 1));
890
+ const context = {
891
+ file: filename,
892
+ line
893
+ };
894
+ if (!/^[A-Z_]\w*$/i.test(item.key) || item.key.length > 256 || [
895
+ "__proto__",
896
+ "prototype",
897
+ "constructor"
898
+ ].includes(item.key.toLowerCase())) fail$1(context, "Invalid or reserved environment key");
899
+ context.key = item.key;
900
+ if (keys.has(item.key)) fail$1(context, "Duplicate environment key");
901
+ keys.add(item.key);
902
+ const metadata = decorators(item.decoratorsArray, [
903
+ "type",
904
+ "required",
905
+ "optional",
906
+ "sensitive",
907
+ "public",
908
+ "example"
909
+ ], context);
910
+ if (metadata.has("required") && metadata.has("optional")) fail$1(context, "Cannot combine required and optional");
911
+ if (metadata.has("sensitive") && metadata.has("public")) fail$1(context, "Cannot combine sensitive and public");
912
+ const field = {
913
+ key: item.key,
914
+ type: parseType(metadata.get("type"), context),
915
+ required,
916
+ sensitive,
917
+ description: item.description,
918
+ docs: [],
919
+ source: {
920
+ file: filename,
921
+ line
922
+ }
923
+ };
924
+ for (const [name, node] of metadata) if (name === "required") field.required = booleanDecorator(node, context);
925
+ else if (name === "optional") field.required = !booleanDecorator(node, context);
926
+ else if (name === "sensitive") field.sensitive = booleanDecorator(node, context);
927
+ else if (name === "public") field.sensitive = !booleanDecorator(node, context);
928
+ else if (name === "example") {
929
+ const example = staticValue(node.value, context);
930
+ if (typeof example !== "string") fail$1(context, "Example must be a string");
931
+ field.example = example;
932
+ }
933
+ if (item.value !== void 0 && !(item.value instanceof ParsedEnvSpecStaticValue)) fail$1(context, "Dynamic or structured defaults are unsupported");
934
+ const checkedDefault = parseDefault(item.value ? lexicalValue(item.value, context) : void 0, field.type, field.required, context);
935
+ if (checkedDefault !== void 0) field.default = checkedDefault;
936
+ return field;
937
+ });
938
+ }
939
+ //#endregion
940
+ //#region src/env-schema/importer.ts
941
+ function fail(field, reason) {
942
+ const path = field ? `${field.source.file}:${field.source.line} (${field.key})` : "envSchema";
943
+ throw invalidEnvDeclaration(path, `${path}: ${reason}`);
944
+ }
945
+ function outputName(name) {
946
+ return name.split("_").filter(Boolean).map((word, index) => {
947
+ const normalized = word === word.toUpperCase() ? word.toLowerCase() : word;
948
+ return index === 0 ? normalized.charAt(0).toLowerCase() + normalized.slice(1) : normalized.charAt(0).toUpperCase() + normalized.slice(1);
949
+ }).join("");
950
+ }
951
+ function safePath(path, field, publicField) {
952
+ const segments = path.split(".");
953
+ if (!segments.length || publicField && segments.length !== 1 || segments.length > 16 || segments.some((segment) => !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(segment) || [
954
+ "__proto__",
955
+ "prototype",
956
+ "constructor"
957
+ ].includes(segment.toLowerCase()))) fail(field, "Output path must contain safe identifiers; Public Env paths must be flat");
958
+ if ([
959
+ "public",
960
+ "define",
961
+ "server"
962
+ ].includes(segments[0] || "")) fail(field, "Output paths cannot select an Env visibility section");
963
+ return segments;
964
+ }
965
+ function descriptor(field) {
966
+ const type = field.type;
967
+ if (type.kind === "string") return {
968
+ ...type,
969
+ minLength: Math.max(type.minLength ?? 0, field.required ? 1 : 0)
970
+ };
971
+ if (type.kind === "number") return {
972
+ ...type,
973
+ decimal: true
974
+ };
975
+ return type;
976
+ }
977
+ function add(tree, segments, declaration, field) {
978
+ const [head, ...rest] = segments;
979
+ if (!head) return fail(field, "Output path cannot be empty");
980
+ const existing = tree.get(head);
981
+ if (!rest.length) {
982
+ if (existing) fail(field, "Output path collides with another declaration");
983
+ tree.set(head, {
984
+ kind: "field",
985
+ declaration
986
+ });
987
+ return;
988
+ }
989
+ if (existing?.kind === "field") fail(field, "Output path collides with another declaration");
990
+ const children = existing?.children ?? /* @__PURE__ */ new Map();
991
+ tree.set(head, {
992
+ kind: "branch",
993
+ children
994
+ });
995
+ add(children, rest, declaration, field);
996
+ }
997
+ function serverConfig(tree) {
998
+ const result = {};
999
+ for (const [key, node] of tree) Object.defineProperty(result, key, {
1000
+ enumerable: true,
1001
+ configurable: true,
1002
+ writable: true,
1003
+ value: node.kind === "field" ? node.declaration : serverConfig(node.children)
1004
+ });
1005
+ return result;
1006
+ }
1007
+ /** Import a committed env-spec-v1 contract. Reads schema metadata, never developer env files. */
1008
+ function envSchema(file, options = {}) {
1009
+ const filename = file instanceof URL ? fileURLToPath(file) : resolve(file);
1010
+ const prefix = options.prefix ?? "VITEHUB_";
1011
+ if (prefix && (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(prefix) || prefix.length > 128)) fail(void 0, "Prefix must be a portable environment name prefix");
1012
+ let source;
1013
+ try {
1014
+ source = readFileSync(filename, "utf8");
1015
+ } catch {
1016
+ throw invalidEnvDeclaration(filename, `${filename}: Cannot read environment schema file`);
1017
+ }
1018
+ let fields;
1019
+ try {
1020
+ fields = parseEnvSchema(source, filename);
1021
+ } catch (error) {
1022
+ throw invalidEnvDeclaration(filename, error instanceof Error ? error.message : `${filename}: Invalid environment schema file`, envErrorDiagnostics.ENV_B0006.is(error) ? error : void 0);
1023
+ }
1024
+ const knownKeys = new Set(fields.map((field) => field.key));
1025
+ for (const key of Object.keys(options.paths ?? {})) if (!knownKeys.has(key)) fail(void 0, "Path mapping refers to an undeclared schema key");
1026
+ const server = /* @__PURE__ */ new Map();
1027
+ const publicConfig = {};
1028
+ const publicNames = /* @__PURE__ */ new Set();
1029
+ for (const field of fields) {
1030
+ const publicPrefix = `${prefix}PUBLIC_`;
1031
+ const publicField = field.key.startsWith(publicPrefix);
1032
+ if (publicField && field.sensitive) fail(field, "A Public Env declaration cannot be sensitive; mark it @public or @sensitive=false");
1033
+ if (schemaContainsEnum(field.type) && field.sensitive) fail(field, "A secret enum would expose its allowed values; use a string instead");
1034
+ const name = publicField ? field.key.slice(publicPrefix.length) : prefix && field.key.startsWith(prefix) ? field.key.slice(prefix.length) : field.key;
1035
+ const mapped = options.paths && Object.hasOwn(options.paths, field.key) ? options.paths[field.key] : outputName(name);
1036
+ if (typeof mapped !== "string") fail(field, "Output path must be a string");
1037
+ const segments = safePath(mapped, field, publicField);
1038
+ const declaration = descriptorVariable(descriptor(field), {
1039
+ ...field.default !== void 0 ? { default: field.default } : { optional: !field.required },
1040
+ mode: publicField ? "build" : "runtime",
1041
+ secret: field.sensitive,
1042
+ source: env.source(field.key, { canonical: false })
1043
+ });
1044
+ if (publicField) {
1045
+ if (publicNames.has(mapped)) fail(field, "Output path collides with another declaration");
1046
+ publicNames.add(mapped);
1047
+ Object.defineProperty(publicConfig, mapped, {
1048
+ enumerable: true,
1049
+ configurable: true,
1050
+ writable: true,
1051
+ value: declaration
1052
+ });
1053
+ } else add(server, segments, declaration, field);
1054
+ }
1055
+ return {
1056
+ public: publicConfig,
1057
+ server: serverConfig(server)
1058
+ };
1059
+ }
1060
+ //#endregion
559
1061
  //#region src/vite.ts
560
1062
  const ENV_VITE_PLUGIN_NAME = "@vite-hub/env/vite";
1063
+ const envNoExternal = createNoExternalAddition("@vite-hub/env");
561
1064
  const ENV_PUBLIC_ID = VITEHUB_ENV_PUBLIC_ID;
562
1065
  const ENV_SERVER_ID = VITEHUB_ENV_SERVER_ID;
563
- const RESOLVED_PUBLIC_ID = `\0${ENV_PUBLIC_ID}`;
1066
+ const ENV_DESCRIPTION_ID = "#vitehub/env/description";
1067
+ const RESOLVED_DESCRIPTION_ID = `\0${ENV_DESCRIPTION_ID}`;
1068
+ const RESOLVED_PUBLIC_ID = "\0virtual:vitehub/env/public";
564
1069
  const RESOLVED_SERVER_ID = `\0${ENV_SERVER_ID}`;
1070
+ const ID_PATTERN = /^#vitehub\/env\/(?:description|public|server)$/;
1071
+ const RESOLVED_ID_PATTERN = /^\0(?:#vitehub\/env\/(?:description|server)|virtual:vitehub\/env\/public)$/;
565
1072
  const defaultRuntimeImports = {
566
- secret: "@vite-hub/env/secret",
567
- server: "@vite-hub/env/server"
1073
+ secret: "@vite-hub/env",
1074
+ server: "@vite-hub/env/internal/server"
568
1075
  };
569
1076
  let envVitePluginSequence = 0;
1077
+ const developmentSecretLocks = /* @__PURE__ */ new Map();
1078
+ function isDeclarationGroup(value) {
1079
+ return Object.prototype.toString.call(value) === "[object Object]" && Reflect.get(Object(value), "kind") !== "env-variable";
1080
+ }
1081
+ function resolveDeclarations(options, config) {
1082
+ const contributed = Reflect.get(config, VITEHUB_ENV_SERVER);
1083
+ let server = options.server;
1084
+ if (isDeclarationGroup(contributed)) {
1085
+ server = { ...contributed };
1086
+ for (const [key, value] of Object.entries(options.server ?? {})) {
1087
+ const base = server[key];
1088
+ server[key] = isDeclarationGroup(base) && isDeclarationGroup(value) ? {
1089
+ ...base,
1090
+ ...value
1091
+ } : value;
1092
+ }
1093
+ }
1094
+ if (!options.define && !options.public && !server) return void 0;
1095
+ return {
1096
+ ...options.define ? { define: options.define } : {},
1097
+ ...options.public ? { public: options.public } : {},
1098
+ ...server ? { server } : {}
1099
+ };
1100
+ }
1101
+ const operationsModule = ownModule(import.meta.url, "operations");
570
1102
  function createEnvImportAliases(options = {}) {
571
1103
  return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
572
1104
  }
@@ -578,7 +1110,22 @@ function createEnvTypeScriptPaths(options = {}) {
578
1110
  [ENV_SERVER_ID]: [toTypeScriptPath(viteHubEnvServerModulePath(root))]
579
1111
  };
580
1112
  }
1113
+ /**
1114
+ * Returns the declarations that the Vite Integration writes to `.vitehub/types/env.d.ts` for an `env` config: the
1115
+ * `PublicEnv` and `ServerEnv` types of `#vitehub/env/public` and `#vitehub/env/server`. A TypeScript host that does
1116
+ * not run Vite, such as a test or a docs check, can write them itself.
1117
+ */
1118
+ function createEnvTypes(config, options = {}) {
1119
+ validateEnvConfigShape(config, "vite");
1120
+ const root = resolve(options.projectRoot ?? process.cwd());
1121
+ const registry = createRuntimeRegistry(config?.server, {
1122
+ prefix: options.prefix,
1123
+ schemaModules: true
1124
+ });
1125
+ return createViteTypes(createPublicTypeEntries(config?.public), registry, resolveRuntimeImports(options.runtimeImports), resolveSchemaModules(registry, root), viteHubEnvAmbientTypesPath(root));
1126
+ }
581
1127
  function hubEnv(options = {}) {
1128
+ validateEnvConfigShape(options, "vite");
582
1129
  let buildPublicConfig = {};
583
1130
  let serverRegistry = {};
584
1131
  const resolvedStates = /* @__PURE__ */ new Map();
@@ -591,19 +1138,21 @@ function hubEnv(options = {}) {
591
1138
  const serverRegistryHandlers = /* @__PURE__ */ new Set();
592
1139
  const getPublicEnv = () => buildPublicConfig;
593
1140
  const getServerEnvRegistry = () => serverRegistry;
594
- const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, { prefix: options.prefix });
1141
+ const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, {
1142
+ prefix: options.prefix,
1143
+ schemaModules: true
1144
+ });
595
1145
  const resolveProjectRoot = (viteRoot) => resolveViteHubProjectRoot(resolve(viteRoot), { projectRoot: options.projectRoot });
596
1146
  const runtimeImports = resolveRuntimeImports(options.runtimeImports);
597
- const prepareTypes = async (config, viteRoot) => {
1147
+ const prepareTypes = async (declarations, viteRoot) => {
598
1148
  const root = resolveProjectRoot(viteRoot);
599
1149
  const packageRoot = await resolvePackageRoot(viteRoot, root);
600
- const registry = createRuntimeRegistry(config?.server, { prefix: options.prefix });
1150
+ const registry = createServerEnvRegistry(declarations?.server);
601
1151
  assertConfiguredProviders(registry, resolveProviderModules(options.providers, root));
602
- await prepareEnvGeneratedTypes(root, packageRoot, config?.public, registry, runtimeImports);
1152
+ await prepareEnvGeneratedTypes(root, packageRoot, declarations?.public, registry, runtimeImports, resolveSchemaModules(registry, root));
603
1153
  };
604
- const resolveState = async (config, mode) => {
605
- const envConfig = config.env;
606
- validateEnvConfigShape(envConfig, "vite");
1154
+ const resolveState = async (config, mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey) => {
1155
+ const envConfig = resolveDeclarations(options, config);
607
1156
  const projectRoot = resolveProjectRoot(config.root || process.cwd());
608
1157
  const providerModules = resolveProviderModules(options.providers, projectRoot);
609
1158
  if (!envConfig) return {
@@ -613,13 +1162,18 @@ function hubEnv(options = {}) {
613
1162
  diagnosticsText: void 0,
614
1163
  projectRoot,
615
1164
  providerModules,
1165
+ schemaModules: {},
616
1166
  publicConfig: {},
617
- serverRegistry: {}
1167
+ publicTypes: {},
1168
+ serverRegistry: {},
1169
+ developmentSecret,
1170
+ developmentSecretGenerated,
1171
+ developmentSecretEnvKey
618
1172
  }
619
1173
  };
620
1174
  const context = createSourceContext({
621
1175
  env: {
622
- ...loadEnv(mode, projectRoot, ""),
1176
+ ...loadAllEnv(loadEnv, mode, projectRoot),
623
1177
  ...process.env
624
1178
  },
625
1179
  mode: "build",
@@ -649,8 +1203,13 @@ function hubEnv(options = {}) {
649
1203
  diagnosticsText: formatDiagnostics([...publicResult.diagnostics, ...defineResult.diagnostics], options.diagnostics),
650
1204
  projectRoot,
651
1205
  providerModules,
1206
+ schemaModules: resolveSchemaModules(registry, projectRoot),
652
1207
  publicConfig,
653
- serverRegistry: registry
1208
+ publicTypes: createPublicTypeEntries(envConfig.public, publicConfig),
1209
+ serverRegistry: registry,
1210
+ developmentSecret,
1211
+ developmentSecretGenerated,
1212
+ developmentSecretEnvKey
654
1213
  }
655
1214
  };
656
1215
  };
@@ -658,23 +1217,60 @@ function hubEnv(options = {}) {
658
1217
  name: ENV_VITE_PLUGIN_NAME,
659
1218
  api: {
660
1219
  createServerEnvRegistry,
1220
+ deploymentEnv: () => [{
1221
+ names: ["VITEHUB_SECRET"],
1222
+ required: false,
1223
+ secret: true,
1224
+ hasDefault: false,
1225
+ owners: ["env"]
1226
+ }],
661
1227
  getPublicEnv,
662
1228
  getServerEnvRegistry,
663
1229
  onServerEnvRegistry: (handler) => serverRegistryHandlers.add(handler),
664
1230
  prepareTypes,
1231
+ resolveDeclarations: (config) => resolveDeclarations(options, config),
665
1232
  resolveProjectRoot
666
1233
  },
1234
+ vitehub: {
1235
+ cli: () => createEnvCliContributor({ resolveProjectRoot }),
1236
+ operations: [{
1237
+ export: "envOperations",
1238
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).envOperations,
1239
+ module: operationsModule
1240
+ }]
1241
+ },
1242
+ configEnvironment(name, config) {
1243
+ if (!isServerEnvironment(name, config)) return;
1244
+ return { resolve: { noExternal: envNoExternal(config.resolve?.noExternal) } };
1245
+ },
667
1246
  async config(config, env) {
668
- const envConfig = config.env;
669
- const { defineValues, state } = await resolveState(config, env.mode);
1247
+ let developmentSecret;
1248
+ let developmentSecretGenerated = false;
1249
+ let developmentSecretEnvKey;
1250
+ if (env.command === "serve") {
1251
+ const projectRoot = resolveProjectRoot(config.root || process.cwd());
1252
+ const resolvedSecret = await resolveDevelopmentSecret(projectRoot, loadAllEnv(loadEnv, env.mode, projectRoot));
1253
+ developmentSecret = resolvedSecret.secret;
1254
+ developmentSecretGenerated = resolvedSecret.generated;
1255
+ developmentSecretEnvKey = resolvedSecret.envKey;
1256
+ if (developmentSecretEnvKey) process.env[developmentSecretEnvKey] = developmentSecret;
1257
+ }
1258
+ const envConfig = resolveDeclarations(options, config);
1259
+ const { defineValues, state } = await resolveState(config, env.mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey);
670
1260
  buildPublicConfig = state.publicConfig;
671
1261
  serverRegistry = state.serverRegistry;
672
1262
  const configStateId = String(++configStateSequence);
673
1263
  pendingConfigStates.set(configStateId, state);
674
1264
  for (const handler of serverRegistryHandlers) handler(serverRegistry, config);
675
- if (!envConfig) return { [configStateKey]: configStateId };
1265
+ if (!envConfig) return {
1266
+ [configStateKey]: configStateId,
1267
+ __vitehubEnvDevelopmentSecret: developmentSecret,
1268
+ __vitehubEnvDevelopmentSecretEnvKey: developmentSecretEnvKey
1269
+ };
676
1270
  return {
677
1271
  [configStateKey]: configStateId,
1272
+ __vitehubEnvDevelopmentSecret: developmentSecret,
1273
+ __vitehubEnvDevelopmentSecretEnvKey: developmentSecretEnvKey,
678
1274
  define: {
679
1275
  ...Object.fromEntries(Object.entries(defineValues).map(([key, value]) => [key, JSON.stringify(value)])),
680
1276
  ...config.define
@@ -685,9 +1281,22 @@ function hubEnv(options = {}) {
685
1281
  const projectRoot = resolveProjectRoot(config.root);
686
1282
  const configStateId = String(Object.getOwnPropertyDescriptor(config, configStateKey)?.value ?? "");
687
1283
  const state = pendingConfigStates.get(configStateId) ?? resolvedStates.get(projectRoot);
688
- if (!state) throw new Error(`Missing resolved Env state for ${projectRoot}`);
1284
+ if (!state) throw envErrorDiagnostics.ENV_B0001({ message: `Missing resolved Env state for ${projectRoot}` });
689
1285
  pendingConfigStates.delete(configStateId);
690
1286
  resolvedConfigStates.set(config, state);
1287
+ Reflect.defineProperty(config, "__vitehubEnvDevelopmentSecretEnvKey", {
1288
+ configurable: true,
1289
+ value: state.developmentSecretEnvKey
1290
+ });
1291
+ Reflect.defineProperty(config, "__vitehubEnvDevelopmentSecret", {
1292
+ configurable: true,
1293
+ value: state.developmentSecret
1294
+ });
1295
+ const onResolved = config.__vitehubEnvOnResolved;
1296
+ if (onResolved?.length) {
1297
+ await Promise.all(onResolved.map((callback) => callback(state.developmentSecretEnvKey)));
1298
+ onResolved.length = 0;
1299
+ }
691
1300
  for (const environmentConfig of Object.values(config.environments || {})) {
692
1301
  resolvedConfigStates.set(environmentConfig, state);
693
1302
  Reflect.defineProperty(environmentConfig, environmentStateKey, {
@@ -699,7 +1308,8 @@ function hubEnv(options = {}) {
699
1308
  resolvedStates.set(projectRoot, state);
700
1309
  if (state.diagnosticsText) config.logger.info(state.diagnosticsText);
701
1310
  const generatedStateWrite = (generatedStateWrites.get(projectRoot) ?? Promise.resolve()).catch(() => void 0).then(async () => {
702
- await refreshEnvGeneratedFiles(projectRoot, await resolvePackageRoot(config.root, projectRoot), state.publicConfig, state.serverRegistry, runtimeImports, state.providerModules);
1311
+ const packageRoot = await resolvePackageRoot(config.root, projectRoot);
1312
+ await refreshEnvGeneratedFiles(projectRoot, packageRoot, state.publicConfig, state.publicTypes, state.serverRegistry, runtimeImports, state.providerModules, state.schemaModules, state.developmentSecretEnvKey, state.developmentSecretGenerated);
703
1313
  });
704
1314
  generatedStateWrites.set(projectRoot, generatedStateWrite);
705
1315
  try {
@@ -708,39 +1318,51 @@ function hubEnv(options = {}) {
708
1318
  if (generatedStateWrites.get(projectRoot) === generatedStateWrite) generatedStateWrites.delete(projectRoot);
709
1319
  }
710
1320
  },
711
- load(id) {
712
- const viteConfig = this?.environment?.config;
713
- const state = (viteConfig ? Reflect.get(viteConfig, environmentStateKey) : void 0) ?? (viteConfig ? resolvedConfigStates.get(viteConfig) : void 0) ?? (viteConfig?.root ? resolvedStates.get(resolveProjectRoot(viteConfig.root)) : void 0) ?? (viteConfig?.root ? Array.from(pendingConfigStates.values()).findLast((state) => state.projectRoot === resolveProjectRoot(viteConfig.root)) : void 0) ?? Array.from(resolvedStates.values()).at(-1) ?? Array.from(pendingConfigStates.values()).at(-1);
714
- const publicConfig = state?.publicConfig ?? buildPublicConfig;
715
- const registry = state?.serverRegistry ?? serverRegistry;
716
- const providerModules = state?.providerModules ?? {};
717
- if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(publicConfig);
718
- if (id === RESOLVED_SERVER_ID) return createServerEnvModule(registry, runtimeImports, providerModules);
1321
+ load: {
1322
+ filter: { id: RESOLVED_ID_PATTERN },
1323
+ handler(id) {
1324
+ const viteConfig = this?.environment?.config;
1325
+ const state = (viteConfig ? Reflect.get(viteConfig, environmentStateKey) : void 0) ?? (viteConfig ? resolvedConfigStates.get(viteConfig) : void 0) ?? (viteConfig?.root ? resolvedStates.get(resolveProjectRoot(viteConfig.root)) : void 0) ?? (viteConfig?.root ? Array.from(pendingConfigStates.values()).findLast((state) => state.projectRoot === resolveProjectRoot(viteConfig.root)) : void 0) ?? Array.from(resolvedStates.values()).at(-1) ?? Array.from(pendingConfigStates.values()).at(-1);
1326
+ const publicConfig = state?.publicConfig ?? buildPublicConfig;
1327
+ const registry = state?.serverRegistry ?? serverRegistry;
1328
+ const providerModules = state?.providerModules ?? {};
1329
+ const schemaModules = state?.schemaModules ?? {};
1330
+ if (id === RESOLVED_DESCRIPTION_ID) return createServerEnvDescriptionModule(registry);
1331
+ if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(publicConfig);
1332
+ if (id === RESOLVED_SERVER_ID) return createServerEnvModule(registry, runtimeImports, providerModules, schemaModules, void 0, state?.developmentSecretEnvKey, state?.developmentSecretGenerated);
1333
+ }
719
1334
  },
720
1335
  resolveId: {
721
1336
  order: "pre",
1337
+ filter: { id: ID_PATTERN },
722
1338
  handler(id) {
1339
+ if (id === ENV_DESCRIPTION_ID) return RESOLVED_DESCRIPTION_ID;
723
1340
  if (id === ENV_PUBLIC_ID) return RESOLVED_PUBLIC_ID;
724
1341
  if (id === ENV_SERVER_ID) return RESOLVED_SERVER_ID;
725
1342
  }
726
1343
  },
727
- transform(code) {
728
- if (!code.includes("/* @vitehub-env */") || !code.includes(ENV_SERVER_ID)) return;
729
- return code.replace(/\/\* @vite-ignore \*\/\s*\/\* @vitehub-env \*\/\s*[\w$]+/g, JSON.stringify(ENV_SERVER_ID));
1344
+ transform: {
1345
+ filter: { code: "/* @vitehub-env */" },
1346
+ handler(code) {
1347
+ if (!code.includes("/* @vitehub-env */") || !code.includes(ENV_SERVER_ID)) return;
1348
+ return code.replace(/\/\* @vite-ignore \*\/\s*\/\* @vitehub-env \*\/\s*[\w$]+/g, JSON.stringify(ENV_SERVER_ID));
1349
+ }
730
1350
  }
731
1351
  };
732
1352
  }
733
- async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
734
- const publicTypes = createPreparedPublicTypeEntries(publicConfig);
1353
+ async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports, schemaModules) {
1354
+ const publicTypes = createPublicTypeEntries(publicConfig);
735
1355
  await Promise.all([
736
1356
  ...packageRoot && packageRoot !== root ? [
737
1357
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(packageRoot), createPublicEnvModuleTypes(publicTypes)),
738
- writeFileIfChanged(viteHubEnvServerModuleTypesPath(packageRoot), createServerEnvModuleTypes(serverRegistry, runtimeImports)),
1358
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(packageRoot), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(packageRoot))),
739
1359
  writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))
740
1360
  ] : [],
741
- writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
1361
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, viteHubEnvAmbientTypesPath(root))),
1362
+ writeFileIfChanged(envAccessorTypesPath(root), createEnvAccessorTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, envAccessorTypesPath(root))),
742
1363
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
743
- writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
1364
+ writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
1365
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(root)))
744
1366
  ]);
745
1367
  }
746
1368
  function resolveEnvProjectRoot(options) {
@@ -758,35 +1380,124 @@ function resolveRuntimeImports(imports) {
758
1380
  function resolveProviderModules(providers, root) {
759
1381
  const output = {};
760
1382
  for (const [name, specifier] of Object.entries(providers || {})) {
761
- if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)) throw new TypeError("[vitehub] Env provider names must start with a letter and contain only letters, numbers, underscores, or hyphens.");
762
- if (typeof specifier !== "string" || !specifier.trim()) throw new TypeError(`[vitehub] Env provider ${JSON.stringify(name)} requires a non-empty module specifier.`);
1383
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)) throw envErrorDiagnostics.ENV_B0002({ message: "[vitehub] Env provider names must start with a letter and contain only letters, numbers, underscores, or hyphens." });
1384
+ if (typeof specifier !== "string" || !specifier.trim()) throw envErrorDiagnostics.ENV_B0003({ message: `[vitehub] Env provider ${JSON.stringify(name)} requires a non-empty module specifier.` });
763
1385
  const normalized = specifier.trim();
764
- if (/^(?:\\\\[?.]\\|\/\/[?.]\/)/.test(normalized)) throw new TypeError(`[vitehub] Env provider ${JSON.stringify(name)} uses an unsupported namespaced Windows module path.`);
1386
+ if (/^(?:\\\\[?.]\\|\/\/[?.]\/)/.test(normalized)) throw envErrorDiagnostics.ENV_B0004({ message: `[vitehub] Env provider ${JSON.stringify(name)} uses an unsupported namespaced Windows module path.` });
765
1387
  output[name] = normalized.startsWith(".") ? resolve(root, normalized) : normalized;
766
1388
  }
767
1389
  return output;
768
1390
  }
769
1391
  function assertConfiguredProviders(registry, providers) {
770
- const visit = (value, path) => {
771
- if (!isRecord(value)) return;
772
- if (isProviderEntry(value)) {
773
- if (!Object.hasOwn(providers, value.source.provider)) throw new TypeError(`[vitehub] ${path} references Env provider ${JSON.stringify(value.source.provider)}, but hubEnv({ providers }) does not configure it.`);
774
- return;
1392
+ for (const { entry, path } of runtimeRegistryEntries(registry)) if (isRuntimeProviderEntry(entry) && !Object.hasOwn(providers, entry.source.provider)) throw envErrorDiagnostics.ENV_B0005({ message: `[vitehub] ${path} references Env provider ${JSON.stringify(entry.source.provider)}, but hubEnv({ providers }) does not configure it.` });
1393
+ }
1394
+ /** Map each `env.schemaFrom()` specifier to the module the server build imports. Relative specifiers resolve from the project root. */
1395
+ function resolveSchemaModules(registry, root) {
1396
+ const output = {};
1397
+ for (const { entry } of runtimeRegistryEntries(registry)) {
1398
+ if (!(isRuntimeEnvEntry(entry) || isRuntimeProviderEntry(entry)) || !entry.schemaModule) continue;
1399
+ const specifier = entry.schemaModule.module;
1400
+ output[specifier] = specifier.startsWith(".") ? resolve(root, specifier) : specifier;
1401
+ }
1402
+ return output;
1403
+ }
1404
+ /** A type-only import specifier for a schema module, relative to the generated declaration file. */
1405
+ function schemaModuleTypeSpecifier(specifier, outputPath) {
1406
+ const typed = specifier.replace(/\.([cm]?)tsx?$/, ".$1js");
1407
+ if (!isAbsolute(typed)) return typed;
1408
+ const target = relative(dirname(outputPath), typed).replace(/\\/g, "/");
1409
+ return target.startsWith(".") ? target : `./${target}`;
1410
+ }
1411
+ const generatedSecretPattern = /^[0-9a-f]{64}$/;
1412
+ /**
1413
+ * Give the development server a root secret when none is configured, so `deriveSecret()` works without setup.
1414
+ * The secret is kept in `.vitehub/env/secret` with mode 0600 and survives restarts. Builds never generate one.
1415
+ */
1416
+ async function resolveDevelopmentSecret(projectRoot, loadedEnv) {
1417
+ const existing = developmentSecretLocks.get(projectRoot);
1418
+ if (existing) return existing;
1419
+ const pending = resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv);
1420
+ developmentSecretLocks.set(projectRoot, pending);
1421
+ try {
1422
+ return await pending;
1423
+ } finally {
1424
+ if (developmentSecretLocks.get(projectRoot) === pending) developmentSecretLocks.delete(projectRoot);
1425
+ }
1426
+ }
1427
+ async function resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv) {
1428
+ const configured = readViteHubSecret(loadedEnv);
1429
+ const envKey = `VITEHUB_SECRET_${createHash("sha256").update(resolve(projectRoot)).digest("hex").slice(0, 16)}`;
1430
+ if (configured) return {
1431
+ generated: false,
1432
+ secret: configured,
1433
+ envKey
1434
+ };
1435
+ const secretPath = resolve(projectRoot, ".vitehub", "env", "secret");
1436
+ let secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
1437
+ if (!generatedSecretPattern.test(secret)) {
1438
+ await mkdir(dirname(secretPath), { recursive: true });
1439
+ const lockPath = `${secretPath}.lock`;
1440
+ let lock;
1441
+ for (let attempt = 0; attempt < 120 && !lock; attempt++) try {
1442
+ lock = await open(lockPath, "wx", 384);
1443
+ await lock.writeFile(`${process.pid}\n`);
1444
+ } catch (error) {
1445
+ if (error.code !== "EEXIST") throw error;
1446
+ try {
1447
+ const lockStat = await stat(lockPath);
1448
+ const owner = await readFile(lockPath, "utf8").catch(() => "");
1449
+ let ownerAlive = false;
1450
+ const ownerPid = Number.parseInt(owner, 10);
1451
+ if (Number.isInteger(ownerPid) && ownerPid > 0) try {
1452
+ process.kill(ownerPid, 0);
1453
+ ownerAlive = true;
1454
+ } catch (error) {
1455
+ ownerAlive = error.code !== "ESRCH";
1456
+ }
1457
+ if (!ownerAlive && Date.now() - lockStat.mtimeMs > 3e4) {
1458
+ const stalePath = `${lockPath}.${process.pid}.${Date.now()}.stale`;
1459
+ await rename(lockPath, stalePath).catch(() => {});
1460
+ await unlink(stalePath).catch(() => {});
1461
+ }
1462
+ } catch {}
1463
+ await new Promise((resolve) => setTimeout(resolve, 5));
775
1464
  }
776
- if (isLiteralEntry(value) || isEnvEntry(value)) return;
777
- for (const [key, child] of Object.entries(value)) visit(child, `${path}.${key}`);
1465
+ if (!lock) throw envErrorDiagnostics.ENV_B0007({ message: `[vitehub] Timed out waiting for the generated secret lock: ${secretPath}.lock` });
1466
+ const replacementPath = `${secretPath}.${process.pid}.${Date.now()}.tmp`;
1467
+ try {
1468
+ secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
1469
+ if (!generatedSecretPattern.test(secret)) {
1470
+ secret = randomBytes(32).toString("hex");
1471
+ await writeFile(replacementPath, secret, {
1472
+ flag: "wx",
1473
+ mode: 384
1474
+ });
1475
+ await rename(replacementPath, secretPath);
1476
+ }
1477
+ } finally {
1478
+ const owned = await lock.stat().then((lockStat) => stat(lockPath).then((pathStat) => lockStat.dev === pathStat.dev && lockStat.ino === pathStat.ino, () => false));
1479
+ await lock.close();
1480
+ if (owned) await unlink(lockPath).catch(() => {});
1481
+ await unlink(replacementPath).catch(() => {});
1482
+ }
1483
+ }
1484
+ await chmod(secretPath, 384);
1485
+ return {
1486
+ generated: true,
1487
+ secret,
1488
+ envKey
778
1489
  };
779
- for (const [key, value] of Object.entries(registry)) visit(value, `env.server.${key}`);
780
1490
  }
781
- async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules) {
782
- const publicTypes = createPublicTypeEntries(publicConfig);
1491
+ async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, schemaModules, developmentSecretEnvKey, developmentSecretGenerated) {
783
1492
  await Promise.all([
784
- ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
785
- writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
1493
+ ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, schemaModules, developmentSecretEnvKey, developmentSecretGenerated), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
1494
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, viteHubEnvAmbientTypesPath(root))),
1495
+ writeFileIfChanged(envAccessorTypesPath(root), createEnvAccessorTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, envAccessorTypesPath(root))),
786
1496
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
787
1497
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
788
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
789
- writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
1498
+ writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
1499
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, schemaModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
1500
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(root)))
790
1501
  ]);
791
1502
  }
792
1503
  function createAmbientTypesReference(packageRoot, projectRoot) {
@@ -794,13 +1505,12 @@ function createAmbientTypesReference(packageRoot, projectRoot) {
794
1505
  const specifier = target.startsWith(".") ? target : `./${target}`;
795
1506
  return `/// <reference path=${JSON.stringify(specifier)} />\n`;
796
1507
  }
797
- function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports, providerModules) {
798
- const publicTypes = createPublicTypeEntries(publicConfig);
1508
+ function packageEnvModuleWrites(root, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, schemaModules, developmentSecretEnvKey, developmentSecretGenerated) {
799
1509
  return [
800
1510
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
801
1511
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
802
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
803
- writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
1512
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, schemaModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
1513
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(root)))
804
1514
  ];
805
1515
  }
806
1516
  async function resolvePackageRoot(viteRoot, projectRoot) {
@@ -840,21 +1550,33 @@ function createPublicEnvModuleTypes(publicTypes) {
840
1550
  ""
841
1551
  ].join("\n");
842
1552
  }
843
- function createServerEnvModule(serverRegistry, runtimeImports, providerModules, outputPath) {
1553
+ function createServerEnvModule(serverRegistry, runtimeImports, providerModules, schemaModules, outputPath, developmentSecretEnvKey, developmentSecretGenerated) {
844
1554
  const referenced = referencedProviderNames(serverRegistry);
845
1555
  const providers = Object.entries(providerModules).filter(([name]) => referenced.has(name));
1556
+ const schemas = Object.entries(schemaModules);
846
1557
  return [
847
- `import { inspectServerEnv as inspectRegistry, loadServerEnv as loadRegistry, resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
1558
+ `import * as envRuntime from ${JSON.stringify(runtimeImports.server)};`,
848
1559
  ...providers.map(([, specifier], index) => `import envProvider${index} from ${JSON.stringify(providerImportSpecifier(specifier, outputPath))};`),
1560
+ ...schemas.map(([, specifier], index) => `import * as envSchemas${index} from ${JSON.stringify(providerImportSpecifier(specifier, outputPath))};`),
849
1561
  `const registry = JSON.parse(${JSON.stringify(JSON.stringify(serverRegistry))});`,
1562
+ ...schemas.length ? [`envRuntime.bindServerEnvSchemas(registry, { ${schemas.map(([name], index) => `${JSON.stringify(name)}: envSchemas${index}`).join(", ")} });`] : [],
850
1563
  `const providers = Object.fromEntries([${providers.map(([name], index) => `[${JSON.stringify(name)}, envProvider${index}]`).join(", ")}]);`,
851
- "export function useServerEnv(event) { return resolveServerEnv(registry, event); }",
852
- "export async function loadServerEnv(event, options) { return await loadRegistry(registry, event, { ...options, providers }); }",
853
- "export async function inspectServerEnv(event, options) { return await inspectRegistry(registry, event, { ...options, providers }); }",
1564
+ createServerEnvDescriptionModule(serverRegistry).trimEnd(),
1565
+ "export function useServerEnv(event) { return envRuntime.resolveServerEnv(registry, event); }",
1566
+ `export async function deriveSecret(purpose, options) { return await envRuntime.deriveSecret(purpose, options, { envKey: ${JSON.stringify(developmentSecretEnvKey)}, generated: ${JSON.stringify(developmentSecretGenerated)} }); }`,
1567
+ `let sealing;`,
1568
+ `function useSealing() { return sealing ??= envRuntime.createSealing((purpose, event, root) => envRuntime.deriveSecret(purpose, { event, root }, { envKey: ${JSON.stringify(developmentSecretEnvKey)}, generated: root === undefined && ${JSON.stringify(developmentSecretGenerated)} })); }`,
1569
+ "export async function seal(purpose, value, options) { return await useSealing().seal(purpose, value, options); }",
1570
+ "export async function unseal(purpose, sealed, options) { return await useSealing().unseal(purpose, sealed, options); }",
1571
+ "export async function loadServerEnv(event, options) { return await envRuntime.loadServerEnv(registry, event, { ...options, providers }); }",
1572
+ "export async function inspectServerEnv(event, options) { return await envRuntime.inspectServerEnv(registry, event, { ...options, providers }); }",
854
1573
  "export async function runWithServerEnv(event, callback, options) { return await callback(await loadServerEnv(event, options)); }",
855
1574
  ""
856
1575
  ].join("\n");
857
1576
  }
1577
+ function createServerEnvDescriptionModule(serverRegistry) {
1578
+ return `export function describeServerEnv() { return JSON.parse(${JSON.stringify(JSON.stringify(describeServerEnv(serverRegistry)))}); }\n`;
1579
+ }
858
1580
  function providerImportSpecifier(specifier, outputPath) {
859
1581
  const windowsAbsolute = win32.isAbsolute(specifier);
860
1582
  if (!isAbsolute(specifier) && !windowsAbsolute) return specifier;
@@ -879,35 +1601,67 @@ function encodeModulePath(path) {
879
1601
  }
880
1602
  function referencedProviderNames(registry) {
881
1603
  const names = /* @__PURE__ */ new Set();
882
- const visit = (value) => {
883
- if (!isRecord(value)) return;
884
- if (isProviderEntry(value)) {
885
- names.add(value.source.provider);
886
- return;
887
- }
888
- if (isLiteralEntry(value) || isEnvEntry(value)) return;
889
- for (const child of Object.values(value)) visit(child);
890
- };
891
- for (const value of Object.values(registry)) visit(value);
1604
+ for (const { entry } of runtimeRegistryEntries(registry)) if (isRuntimeProviderEntry(entry)) names.add(entry.source.provider);
892
1605
  return names;
893
1606
  }
894
- function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
1607
+ function createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, outputPath) {
1608
+ const schemaTypes = {
1609
+ modules: schemaModules,
1610
+ outputPath
1611
+ };
895
1612
  return [
896
1613
  `import type { SecretEnv } from ${JSON.stringify(runtimeImports.secret)}`,
897
1614
  "",
898
1615
  ...createServerEnvInspectionTypes(0),
899
1616
  "export interface ServerEnv {",
900
- ...createServerTypeFields(serverRegistry, 2),
1617
+ ...createServerTypeFields(serverRegistry, 2, schemaTypes),
901
1618
  "}",
902
- "export function useServerEnv(event?: unknown): ServerEnv",
1619
+ `export function useServerEnv(event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext): ServerEnv`,
1620
+ `export function deriveSecret(purpose: string, options?: { event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext; root?: string }): Promise<string>`,
1621
+ `export const seal: typeof import(${JSON.stringify(runtimeImports.server)}).seal`,
1622
+ `export const unseal: typeof import(${JSON.stringify(runtimeImports.server)}).unseal`,
903
1623
  ...createReadonlyServerEnvTypes(0, "SecretEnv"),
904
- "export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ReadonlyServerEnv>",
905
- "export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ServerEnvInspection>",
906
- "export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal }): Promise<T>",
1624
+ `export function loadServerEnv(event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ReadonlyServerEnv>`,
1625
+ `export function inspectServerEnv(event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ServerEnvInspection>`,
1626
+ `export function runWithServerEnv<T>(event: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext | undefined, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<T>`,
1627
+ ""
1628
+ ].join("\n");
1629
+ }
1630
+ function envAccessorTypesPath(root) {
1631
+ return resolve(root, ".vitehub", "types", "env-accessors.d.ts");
1632
+ }
1633
+ /**
1634
+ * Types `useServerEnv()` and `usePublicEnv()` of the Env root with the declared fields. The file is a module, so its
1635
+ * `declare module` blocks augment the package instead of replacing it.
1636
+ */
1637
+ function createEnvAccessorTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, outputPath) {
1638
+ const schemaTypes = {
1639
+ modules: schemaModules,
1640
+ outputPath
1641
+ };
1642
+ const block = (moduleName) => [
1643
+ `declare module ${JSON.stringify(moduleName)} {`,
1644
+ " interface PublicEnv {",
1645
+ ...createPublicTypeFields(publicTypes, 4),
1646
+ " }",
1647
+ " interface ServerEnv {",
1648
+ ...createServerTypeFields(serverRegistry, 4, schemaTypes, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
1649
+ " }",
1650
+ "}"
1651
+ ];
1652
+ return [
1653
+ ...block("@vite-hub/env"),
1654
+ ...block("vite-hub/env"),
1655
+ "",
1656
+ "export {}",
907
1657
  ""
908
1658
  ].join("\n");
909
1659
  }
910
- function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
1660
+ function createViteTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, outputPath) {
1661
+ const schemaTypes = {
1662
+ modules: schemaModules,
1663
+ outputPath
1664
+ };
911
1665
  return [
912
1666
  "declare module \"#vitehub/env/public\" {",
913
1667
  " export interface PublicEnv {",
@@ -919,13 +1673,16 @@ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
919
1673
  "declare module \"#vitehub/env/server\" {",
920
1674
  ...createServerEnvInspectionTypes(2),
921
1675
  " export interface ServerEnv {",
922
- ...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
1676
+ ...createServerTypeFields(serverRegistry, 4, schemaTypes, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
923
1677
  " }",
924
- " export function useServerEnv(event?: unknown): ServerEnv",
1678
+ ` export function useServerEnv(event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext): ServerEnv`,
1679
+ ` export function deriveSecret(purpose: string, options?: { event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext; root?: string }): Promise<string>`,
1680
+ ` export const seal: typeof import(${JSON.stringify(runtimeImports.server)}).seal`,
1681
+ ` export const unseal: typeof import(${JSON.stringify(runtimeImports.server)}).unseal`,
925
1682
  ...createReadonlyServerEnvTypes(2, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
926
- " export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ReadonlyServerEnv>",
927
- " export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ServerEnvInspection>",
928
- " export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal }): Promise<T>",
1683
+ ` export function loadServerEnv(event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ReadonlyServerEnv>`,
1684
+ ` export function inspectServerEnv(event?: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ServerEnvInspection>`,
1685
+ ` export function runWithServerEnv<T>(event: import(${JSON.stringify(runtimeImports.server)}).ViteHubContext | undefined, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<T>`,
929
1686
  "}",
930
1687
  ""
931
1688
  ].join("\n");
@@ -933,11 +1690,20 @@ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
933
1690
  function createServerEnvInspectionTypes(indent) {
934
1691
  const prefix = " ".repeat(indent);
935
1692
  return [
1693
+ `${prefix}export interface ServerEnvDescriptionEntry { path?: string; names?: readonly string[]; source: "env" | "literal" | "provider"; provider?: string; secret: boolean; required: boolean; hasDefault: boolean; type?: string }`,
1694
+ `${prefix}export interface ServerEnvDescription { entries: readonly ServerEnvDescriptionEntry[] }`,
1695
+ `${prefix}export function describeServerEnv(): ServerEnvDescription`,
936
1696
  `${prefix}export interface ServerEnvInspectionEntry {`,
937
1697
  `${prefix} masked: boolean`,
1698
+ `${prefix} names?: readonly string[]`,
1699
+ `${prefix} name?: string`,
938
1700
  `${prefix} path?: string`,
1701
+ `${prefix} provider?: string`,
1702
+ `${prefix} required: boolean`,
939
1703
  `${prefix} source: "env" | "literal" | "provider"`,
940
1704
  `${prefix} status: "available" | "defaulted" | "error" | "invalid" | "missing"`,
1705
+ `${prefix} via?: "canonical" | "conventional"`,
1706
+ `${prefix} conflict?: true`,
941
1707
  `${prefix}}`,
942
1708
  `${prefix}export interface ServerEnvInspection {`,
943
1709
  `${prefix} entries: readonly ServerEnvInspectionEntry[]`,
@@ -957,36 +1723,43 @@ function createReadonlyServerEnvTypes(indent, secretType) {
957
1723
  `${prefix} : T`
958
1724
  ];
959
1725
  }
960
- function createPublicTypeEntries(publicConfig) {
961
- return Object.fromEntries(Object.entries(publicConfig).map(([key, value]) => [key, typeof value]));
962
- }
963
- function createPreparedPublicTypeEntries(publicConfig) {
1726
+ function createPublicTypeEntries(publicConfig, resolvedValues) {
964
1727
  return Object.fromEntries(Object.entries(publicConfig ?? {}).map(([key, declaration]) => {
965
- const parsedDefault = typeof declaration.default === "undefined" ? void 0 : parseSchema(declaration.schema, declaration.default, `env.public.${key}`);
966
- return [key, `${declaration.type ?? (isDefaultStringEnvVariable(declaration) ? "string" : void 0) ?? (parsedDefault === null ? "null" : typeof parsedDefault === "undefined" ? "unknown" : typeof parsedDefault)}${!declaration.required && typeof declaration.default === "undefined" ? " | undefined" : ""}`];
1728
+ const valueSchema = runtimeValueSchema(declaration);
1729
+ const fallbackValue = resolvedValues ? resolvedValues[key] : typeof declaration.default === "undefined" ? void 0 : parseSchema(declaration.schema, declaration.default, `env.public.${key}`);
1730
+ const fallbackType = fallbackValue === null ? "null" : fallbackValue === void 0 ? "unknown" : typeof fallbackValue;
1731
+ return [key, `${declaration.type ?? (valueSchema ? envValueTypeName(valueSchema) : void 0) ?? fallbackType}${!declaration.required && typeof declaration.default === "undefined" ? " | undefined" : ""}`];
967
1732
  }));
968
1733
  }
969
1734
  function createPublicTypeFields(publicTypes, indent) {
970
1735
  const prefix = " ".repeat(indent);
971
1736
  return Object.entries(publicTypes).map(([key, type]) => `${prefix}${JSON.stringify(key)}: ${type}`);
972
1737
  }
973
- function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
1738
+ function createServerTypeFields(registry, indent, schemaTypes, secretType = "SecretEnv") {
974
1739
  const prefix = " ".repeat(indent);
975
1740
  return Object.entries(registry).map(([key, value]) => {
976
1741
  const optional = isOptionalServerValue(value) ? "?" : "";
977
- return `${prefix}${JSON.stringify(key)}${optional}: ${serverTypeFor(value, indent, secretType)}`;
1742
+ return `${prefix}${JSON.stringify(key)}${optional}: ${serverTypeFor(value, indent, schemaTypes, secretType)}`;
978
1743
  });
979
1744
  }
980
- function serverTypeFor(value, indent, secretType) {
981
- if (isLiteralEntry(value)) return literalType(value.value);
982
- if (isEnvEntry(value) || isProviderEntry(value)) return value.secret ? `${secretType}<string>` : "string";
983
- const fields = createServerTypeFields(value, indent + 2, secretType);
1745
+ function serverTypeFor(value, indent, schemaTypes, secretType) {
1746
+ if (isRuntimeLiteralEntry(value)) return literalType(value.value);
1747
+ if (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) {
1748
+ const type = value.schemaModule ? schemaOutputType(value.schemaModule.module, value.schemaModule.export, schemaTypes) : envValueTypeName(value.schema ?? stringValueSchema);
1749
+ return value.secret ? `${secretType}<${type}>` : type;
1750
+ }
1751
+ const fields = createServerTypeFields(value, indent + 2, schemaTypes, secretType);
984
1752
  if (!fields.length) return "Record<string, never>";
985
1753
  const prefix = " ".repeat(indent);
986
1754
  return `{\n${fields.join("\n")}\n${prefix}}`;
987
1755
  }
1756
+ /** Infer the output from optional Standard Schema type metadata, falling back to unknown when it is absent. */
1757
+ function schemaOutputType(specifier, exportName, schemaTypes) {
1758
+ const module = schemaModuleTypeSpecifier(schemaTypes.modules[specifier] ?? specifier, schemaTypes.outputPath);
1759
+ return `typeof import(${JSON.stringify(module)})[${JSON.stringify(exportName)}] extends { readonly "~standard": { readonly types?: { readonly output: infer Output } | undefined } } ? Output : unknown`;
1760
+ }
988
1761
  function isOptionalServerValue(value) {
989
- return (isEnvEntry(value) || isProviderEntry(value)) && !value.required && typeof value.default === "undefined";
1762
+ return (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) && !value.required && typeof value.default === "undefined";
990
1763
  }
991
1764
  function literalType(value) {
992
1765
  if (value === null) return "null";
@@ -998,22 +1771,5 @@ function literalType(value) {
998
1771
  default: return "unknown";
999
1772
  }
1000
1773
  }
1001
- function isLiteralEntry(value) {
1002
- if (!isRecord(value)) return false;
1003
- return value.kind === "literal";
1004
- }
1005
- function isEnvEntry(value) {
1006
- if (!isRecord(value)) return false;
1007
- const record = value;
1008
- return isRecord(record.source) && record.source.kind === "env" && typeof record.required === "boolean" && typeof record.secret === "boolean";
1009
- }
1010
- function isProviderEntry(value) {
1011
- if (!isRecord(value)) return false;
1012
- const record = value;
1013
- return isRecord(record.source) && record.source.kind === "provider" && typeof record.source.provider === "string";
1014
- }
1015
- function isRecord(value) {
1016
- return typeof value === "object" && value !== null && !Array.isArray(value);
1017
- }
1018
1774
  //#endregion
1019
- export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createRuntimeRegistry as createRuntimeEnvRegistry, env, hubEnv };
1775
+ export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createEnvTypes, createRuntimeRegistry as createRuntimeEnvRegistry, env, envSchema, hubEnv };