@vite-hub/env 0.0.4 → 0.1.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 (47) hide show
  1. package/README.md +125 -5
  2. package/dist/access-B3qzBHye.js +54 -0
  3. package/dist/auth.d.ts +32 -0
  4. package/dist/auth.js +44 -0
  5. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  6. package/dist/bridge-error-CFuU5zIz.js +65 -0
  7. package/dist/bridge.d.ts +2 -0
  8. package/dist/bridge.js +192 -0
  9. package/dist/cli-CMQPQbii.js +487 -0
  10. package/dist/cli-DEwcUIe0.d.ts +81 -0
  11. package/dist/cli.d.ts +41 -0
  12. package/dist/cli.js +2 -0
  13. package/dist/database.d.ts +21 -0
  14. package/dist/database.js +183 -0
  15. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  16. package/dist/declarations-DAVgctKD.js +236 -0
  17. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  18. package/dist/http.d.ts +2 -0
  19. package/dist/http.js +122 -0
  20. package/dist/index.d.ts +6 -6
  21. package/dist/index.js +4 -4
  22. package/dist/internal/agent.d.ts +5 -0
  23. package/dist/internal/agent.js +22 -0
  24. package/dist/internal/connections.d.ts +18 -0
  25. package/dist/internal/connections.js +31 -0
  26. package/dist/presets.d.ts +15 -6
  27. package/dist/presets.js +21 -2
  28. package/dist/provider.d.ts +3 -4
  29. package/dist/provider.js +2 -1
  30. package/dist/schema.d.ts +5 -6
  31. package/dist/schema.js +26 -8
  32. package/dist/seal.d.ts +14 -0
  33. package/dist/seal.js +49 -0
  34. package/dist/server-DufVswRJ.js +670 -0
  35. package/dist/server.d.ts +23 -6
  36. package/dist/server.js +2 -3
  37. package/dist/values-D_r6V774.js +148 -0
  38. package/dist/virtual-module.d.ts +7 -3
  39. package/dist/virtual.d.ts +1 -1
  40. package/dist/vite.d.ts +27 -14
  41. package/dist/vite.js +840 -273
  42. package/package.json +81 -17
  43. package/dist/declarations-CoMmvRqH.js +0 -159
  44. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  45. package/dist/errors-C4Xcs6Fi.js +0 -121
  46. package/dist/server-C16sFc1E.js +0 -303
  47. package/dist/types-CsB6DTGE.d.ts +0 -190
package/dist/vite.js CHANGED
@@ -1,14 +1,20 @@
1
- import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-CoMmvRqH.js";
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-CrxjYNYr.js";
2
+ import { a as isEnvSchemaValue, i as stringValueSchema, n as parseEnvValue, o as hasRuntimeType, r as schemaContainsEnum, t as envValueTypeName } from "./values-D_r6V774.js";
3
+ import { n as env, r as runtimeValueSchema, t as descriptorVariable } from "./declarations-DAVgctKD.js";
2
4
  import { parseSchema } from "./schema.js";
3
- import { a as isAbortError, n as envSourceFailed, o as missingRequiredEnv, r as invalidEnvDeclaration } from "./errors-C4Xcs6Fi.js";
5
+ import { _ as readViteHubSecret, c as isRuntimeEnvEntry, d as runtimeRegistryEntries, f as envSourceFailed, h as missingRequiredEnv, l as isRuntimeLiteralEntry, m as isAbortError, p as invalidEnvDeclaration, r as describeServerEnv, u as isRuntimeProviderEntry } from "./server-DufVswRJ.js";
6
+ import { a as createViteHubEnvImportAliases, c as viteHubEnvDescriptionModulePath, d as viteHubEnvServerModulePath, f as viteHubEnvServerModuleTypesPath, i as VITEHUB_ENV_SERVER_ID, l as viteHubEnvPublicModulePath, o as resolveViteHubProjectRoot, r as VITEHUB_ENV_PUBLIC_ID, s as viteHubEnvAmbientTypesPath, t as createEnvCliContributor, u as viteHubEnvPublicModuleTypesPath } from "./cli-CMQPQbii.js";
7
+ import { Diagnostic } from "nostics";
4
8
  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";
9
+ import { readFileSync } from "node:fs";
10
+ import { dirname, isAbsolute, relative, resolve, win32 } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { createHash, randomBytes } from "node:crypto";
13
+ import { chmod, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
9
14
  import { loadEnv } from "vite";
10
15
  import { execFile } from "node:child_process";
11
16
  import { promisify } from "node:util";
17
+ import { ParsedEnvSpecFunctionCall, ParsedEnvSpecKeyValuePair, ParsedEnvSpecStaticValue, parseEnvSpecDotEnvFile } from "@env-spec/parser";
12
18
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
13
19
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
14
20
  function normalizeWindowsPath(input = "") {
@@ -95,75 +101,6 @@ async function writeFileIfChanged(file, contents) {
95
101
  await writeFile(file, contents, "utf8");
96
102
  }
97
103
  //#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
104
  //#region src/core/diagnostics.ts
168
105
  function shouldTraceDiagnostics(option) {
169
106
  return option === "trace" || process.env.VITEHUB_ENV_TRACE === "true";
@@ -237,7 +174,7 @@ function createSourceContext(input) {
237
174
  tag: async () => {
238
175
  const tag = envValue(input.env, ["GIT_TAG"]);
239
176
  if (tag) return tag;
240
- if (input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
177
+ if (Object.hasOwn(input.env, "GITHUB_REF_TYPE") && input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
241
178
  return await gitOutput(input.rootDir, [
242
179
  "describe",
243
180
  "--tags",
@@ -253,16 +190,20 @@ function createSourceContext(input) {
253
190
  }
254
191
  function envValue(env, names) {
255
192
  for (const name of names) {
256
- const value = env[name];
193
+ const value = Object.hasOwn(env, name) ? env[name] : void 0;
257
194
  if (value) return value;
258
195
  }
259
196
  }
260
197
  async function resolveBuildConfig(declarations, input) {
198
+ assertUniqueBuildCanonicalNames(declarations, input.section, input.prefix);
261
199
  const diagnostics = [];
262
200
  const values = {};
263
201
  for (const [key, declaration] of Object.entries(declarations || {})) {
264
- const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, input);
265
- values[key] = result.value;
202
+ const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, {
203
+ ...input,
204
+ prefix: canonicalKey.test(key) ? input.prefix : false
205
+ });
206
+ setOwnValue(values, key, result.value);
266
207
  diagnostics.push(...result.diagnostics);
267
208
  }
268
209
  return {
@@ -271,55 +212,27 @@ async function resolveBuildConfig(declarations, input) {
271
212
  };
272
213
  }
273
214
  async function resolveEnvEntries(declarations, input) {
215
+ assertUniqueBuildCanonicalNames(declarations, input.section, input.prefix);
274
216
  const entries = [];
275
217
  const diagnostics = [];
276
218
  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);
219
+ const result = await resolveBuildDeclaration(declaration, `${input.section}.${key}`, input, canonicalKey.test(key));
307
220
  entries.push({
308
221
  key,
309
222
  masked: declaration.secret,
310
- source: resolvedSource.label,
311
- type,
312
- value
223
+ source: result.source,
224
+ type: result.type ?? declaration.type ?? "undefined",
225
+ value: result.value
313
226
  });
314
227
  diagnostics.push({
315
228
  exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
316
229
  key: `${input.section}.${key}`,
317
230
  masked: declaration.secret,
318
231
  mode: declaration.mode,
319
- source: defaulted ? "default" : resolvedSource.label,
320
- status: defaulted ? "defaulted" : "valid",
232
+ source: result.status === "defaulted" ? "default" : result.source,
233
+ status: result.status,
321
234
  timing: input.timing,
322
- type
235
+ type: result.type ?? declaration.type ?? "undefined"
323
236
  });
324
237
  }
325
238
  return {
@@ -328,44 +241,66 @@ async function resolveEnvEntries(declarations, input) {
328
241
  };
329
242
  }
330
243
  function createRuntimeRegistry(declarations, options = {}) {
331
- return buildRegistry(declarations, options.path ?? "env", options.prefix);
244
+ const path = options.path ?? "env";
245
+ try {
246
+ const registry = buildRegistry(declarations, path, options.prefix);
247
+ assertUniqueCanonicalNames(registry, path);
248
+ return registry;
249
+ } catch (error) {
250
+ if (isClassifiedError(error)) throw error;
251
+ throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
252
+ }
253
+ }
254
+ const canonicalKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
255
+ function claimCanonicalName(owners, canonical, path) {
256
+ if (canonical === void 0) return;
257
+ const owner = owners.get(canonical);
258
+ if (owner !== void 0) throw invalidEnvDeclaration(path, `${path} and ${owner} share the canonical variable name ${canonical}. Rename one, or set hubEnv({ prefix: false }).`);
259
+ owners.set(canonical, path);
260
+ }
261
+ function assertUniqueBuildCanonicalNames(declarations, path, prefix) {
262
+ const owners = /* @__PURE__ */ new Map();
263
+ const visit = (value, valuePath, valuePrefix) => {
264
+ if (isEnvVariableDeclaration(value)) {
265
+ const source = resolveEnvSource(value, valuePath, valuePrefix);
266
+ if (source.kind === "env" && source.canonical !== false) claimCanonicalName(owners, source.canonical, valuePath);
267
+ return;
268
+ }
269
+ if (!isPlainRecord(value)) return;
270
+ for (const [key, child] of Object.entries(value)) visit(child, `${valuePath}.${key}`, canonicalKey.test(key) ? valuePrefix : false);
271
+ };
272
+ visit(declarations, path, prefix);
273
+ }
274
+ function assertUniqueCanonicalNames(registry, path) {
275
+ const owners = /* @__PURE__ */ new Map();
276
+ const visit = (value, valuePath) => {
277
+ if (!isPlainRecord(value)) return;
278
+ const source = value.source;
279
+ if (isPlainRecord(source) && source.kind === "env") {
280
+ if (typeof source.canonical !== "string") return;
281
+ claimCanonicalName(owners, source.canonical, valuePath);
282
+ return;
283
+ }
284
+ if (value.kind === "literal" || isPlainRecord(source)) return;
285
+ for (const [key, child] of Object.entries(value)) visit(child, `${valuePath}.${key}`);
286
+ };
287
+ visit(registry, path);
332
288
  }
333
289
  async function resolveBuildConfigValue(declaration, path, input) {
334
290
  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);
291
+ const result = await resolveBuildDeclaration(declaration, path, input);
357
292
  return {
358
293
  diagnostics: [{
359
294
  exposed: input.exposure,
360
295
  key: path,
361
296
  masked: false,
362
297
  mode: declaration.mode,
363
- source: defaulted ? "default" : resolvedSource.label,
364
- status: defaulted ? "defaulted" : "valid",
298
+ source: result.status === "defaulted" ? "default" : result.source,
299
+ status: result.status,
365
300
  timing: input.timing,
366
- type
301
+ type: result.type ?? declaration.type ?? "undefined"
367
302
  }],
368
- value
303
+ value: result.value
369
304
  };
370
305
  }
371
306
  if (isBuildStaticValue(declaration)) return {
@@ -376,8 +311,11 @@ async function resolveBuildConfigValue(declaration, path, input) {
376
311
  const value = {};
377
312
  const diagnostics = [];
378
313
  for (const [key, child] of Object.entries(declaration)) {
379
- const result = await resolveBuildConfigValue(child, `${path}.${key}`, input);
380
- value[key] = result.value;
314
+ const result = await resolveBuildConfigValue(child, `${path}.${key}`, {
315
+ ...input,
316
+ prefix: canonicalKey.test(key) ? input.prefix : false
317
+ });
318
+ setOwnValue(value, key, result.value);
381
319
  diagnostics.push(...result.diagnostics);
382
320
  }
383
321
  return {
@@ -385,36 +323,114 @@ async function resolveBuildConfigValue(declaration, path, input) {
385
323
  value
386
324
  };
387
325
  }
326
+ async function resolveBuildDeclaration(declaration, path, input, canonical = true) {
327
+ const defaultValue = parseDeclarationDefault(declaration, path);
328
+ const source = resolveEnvSource(declaration, path, canonical ? input.prefix : false);
329
+ const resolvedSource = await resolveSourceValue(source, input.context);
330
+ const defaulted = typeof resolvedSource.value === "undefined";
331
+ const valueForSchema = defaulted ? defaultValue : resolvedSource.value;
332
+ if (typeof valueForSchema === "undefined") {
333
+ if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
334
+ return {
335
+ source: resolvedSource.label,
336
+ status: "missing",
337
+ value: void 0
338
+ };
339
+ }
340
+ const value = parseSchema(declaration.schema, valueForSchema, path);
341
+ const type = declaration.type ?? inferTypeName(value);
342
+ return {
343
+ source: resolvedSource.label,
344
+ status: defaulted ? "defaulted" : "valid",
345
+ type,
346
+ value
347
+ };
348
+ }
349
+ function parseDeclarationDefault(declaration, path) {
350
+ const schema = runtimeValueSchema(declaration);
351
+ return schema && declaration.default !== void 0 ? parseRuntimeDefault(schema, declaration.default, path) : declaration.default;
352
+ }
388
353
  function buildRegistry(declarations, path, prefix) {
389
354
  if (typeof declarations === "undefined") return {};
390
355
  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
356
+ try {
357
+ return Object.fromEntries(Object.entries(declarations).map(([key, value]) => {
358
+ const valuePath = `${path}.${key}`;
359
+ if (!isEnvVariableDeclaration(value)) {
360
+ if (isRuntimeStaticValue(value)) return [key, {
361
+ kind: "literal",
362
+ value
363
+ }];
364
+ if (!isPlainRecord(value)) throw invalidEnvDeclaration(valuePath, `Invalid runtime declaration at ${valuePath}. Use env(), a serializable static value, or a nested object.`);
365
+ return [key, buildRegistry(value, valuePath, canonicalKey.test(key) ? prefix : false)];
366
+ }
367
+ if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
368
+ const source = resolveEnvSource(value, valuePath, canonicalKey.test(key) ? prefix : false);
369
+ if (source.kind !== "env" && source.kind !== "provider") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() or env.provider().`);
370
+ const schema = runtimeValueSchema(value);
371
+ if (!schema) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema. Server Env accepts env(), env.boolean(), env.number(), and env.enum() because runtime parsers must be serializable.`);
372
+ 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.`);
373
+ const type = envValueTypeName(schema);
374
+ 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(), or env.enum() to parse other types.`);
375
+ return [key, {
376
+ default: typeof value.default === "undefined" ? void 0 : parseRuntimeDefault(schema, value.default, valuePath),
377
+ required: value.required,
378
+ schema,
379
+ secret: value.secret,
380
+ source
397
381
  }];
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
- }));
382
+ }));
383
+ } catch (error) {
384
+ if (isClassifiedError(error)) throw error;
385
+ throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
386
+ }
387
+ }
388
+ function isClassifiedError(error) {
389
+ return isViteHubError(error) || error instanceof Diagnostic;
415
390
  }
416
- function resolveEnvSource(declaration, path, prefix = "") {
417
- return declaration.source ?? inferEnvSource(path, prefix);
391
+ function setOwnValue(record, key, value) {
392
+ Object.defineProperty(record, key, {
393
+ configurable: true,
394
+ enumerable: true,
395
+ value,
396
+ writable: true
397
+ });
398
+ }
399
+ function parseRuntimeDefault(schema, value, path) {
400
+ const result = (schema.kind === "boolean" || schema.kind === "number" ? hasRuntimeType(value, schema.kind) : true) ? parseEnvValue(schema, value) : {
401
+ message: `Expected a ${schema.kind} default.`,
402
+ success: false
403
+ };
404
+ if (!result.success) throw envErrorDiagnostics.ENV_R0023({ message: `[vitehub] Invalid default for ${path}: ${result.message}` });
405
+ return result.data;
406
+ }
407
+ /** The default prefix of canonical variable names. */
408
+ const defaultEnvPrefix = "VITEHUB_";
409
+ /**
410
+ * The canonical variable name of a declaration path: the prefix plus the path in upper snake case.
411
+ * `env.server.cliproxy.apiKey` becomes `VITEHUB_CLIPROXY_API_KEY`. `false` disables canonical names.
412
+ */
413
+ function canonicalEnvName(path, prefix = defaultEnvPrefix) {
414
+ return prefix === false ? void 0 : `${prefix}${pathToEnvName(path)}`;
415
+ }
416
+ /**
417
+ * Resolve the source of a declaration. An env source reads the canonical name first, then its
418
+ * conventional names: the explicit `env.source()` names, or the unprefixed path name.
419
+ */
420
+ function resolveEnvSource(declaration, path, prefix = defaultEnvPrefix) {
421
+ const source = declaration.source ?? inferEnvSource(path);
422
+ const canonical = canonicalEnvName(path, prefix);
423
+ if (source.kind !== "env" || canonical === void 0 || source.canonical === false) return source;
424
+ const names = [.../* @__PURE__ */ new Set([canonical, ...source.names ?? [source.name]])];
425
+ return names.length === 1 ? {
426
+ ...source,
427
+ canonical
428
+ } : {
429
+ ...source,
430
+ canonical,
431
+ label: `env:${names.join("|")}`,
432
+ names
433
+ };
418
434
  }
419
435
  function inferTypeName(value) {
420
436
  if (Array.isArray(value)) return "unknown[]";
@@ -435,8 +451,8 @@ async function resolveSourceValue(source, context) {
435
451
  };
436
452
  case "env":
437
453
  for (const name of source.names || [source.name]) {
438
- const value = context.env[name];
439
- if (typeof value !== "undefined") return {
454
+ const value = Object.hasOwn(context.env, name) ? context.env[name] : void 0;
455
+ if (typeof value !== "undefined" && !(source.skipEmpty && value === "")) return {
440
456
  label: `env:${name}`,
441
457
  value
442
458
  };
@@ -484,25 +500,31 @@ async function resolveBuiltInSource(source, resolveSource) {
484
500
  throw envSourceFailed(source, cause);
485
501
  }
486
502
  }
487
- function validateBuildDeclarations(declarations, path) {
503
+ function validateBuildDeclarations(declarations, path, ancestors = /* @__PURE__ */ new Set()) {
488
504
  if (typeof declarations === "undefined") return;
489
505
  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;
506
+ if (ancestors.has(declarations)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Nested environment declarations cannot contain cycles.`);
507
+ ancestors.add(declarations);
508
+ try {
509
+ for (const [key, declaration] of Object.entries(declarations)) {
510
+ const valuePath = `${path}.${key}`;
511
+ if (isEnvVariableDeclaration(declaration)) {
512
+ if (declaration.mode !== "build") throw invalidEnvDeclaration(valuePath, `${valuePath} must use mode: "build".`);
513
+ if (declaration.secret) throw invalidEnvDeclaration(valuePath, `${valuePath} cannot be marked secret because Vite define values are bundled.`);
514
+ continue;
515
+ }
516
+ if (isBuildStaticValue(declaration)) continue;
517
+ validateBuildDeclarations(declaration, valuePath, ancestors);
496
518
  }
497
- if (isBuildStaticValue(declaration)) continue;
498
- validateBuildDeclarations(declaration, valuePath);
519
+ } finally {
520
+ ancestors.delete(declarations);
499
521
  }
500
522
  }
501
523
  function assertEnvVariableDeclaration(path, declaration) {
502
524
  if (!isEnvVariableDeclaration(declaration)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env().`);
503
525
  }
504
- function inferEnvSource(path, prefix) {
505
- const name = `${prefix}${pathToEnvName(path)}`;
526
+ function inferEnvSource(path) {
527
+ const name = pathToEnvName(path);
506
528
  return {
507
529
  kind: "env",
508
530
  label: `env:${name}`,
@@ -517,32 +539,50 @@ function segmentToEnvParts(segment) {
517
539
  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
540
  }
519
541
  function isEnvVariableDeclaration(value) {
520
- return isPlainRecord(value) && value.kind === "env-variable";
542
+ try {
543
+ return isPlainRecord(value) && value.kind === "env-variable";
544
+ } catch {
545
+ return false;
546
+ }
521
547
  }
522
548
  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;
549
+ try {
550
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
551
+ const prototype = Object.getPrototypeOf(value);
552
+ return prototype === null || prototype === Object.prototype;
553
+ } catch {
554
+ return false;
555
+ }
526
556
  }
527
557
  function isRuntimeStaticValue(value) {
528
558
  return isBuildStaticValue(value);
529
559
  }
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;
560
+ function isBuildStaticValue(value, ancestors = /* @__PURE__ */ new Set()) {
561
+ try {
562
+ if (value === null) return true;
563
+ switch (typeof value) {
564
+ case "boolean":
565
+ case "string": return true;
566
+ case "number": return Number.isFinite(value);
567
+ case "object":
568
+ if (!Array.isArray(value)) return false;
569
+ if (ancestors.has(value)) return false;
570
+ ancestors.add(value);
571
+ try {
572
+ for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !isBuildStaticValue(value[index], ancestors)) return false;
573
+ return true;
574
+ } finally {
575
+ ancestors.delete(value);
576
+ }
577
+ default: return false;
578
+ }
579
+ } catch {
580
+ return false;
541
581
  }
542
582
  }
543
583
  async function readPackageJson(rootDir) {
544
584
  const value = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
545
- if (!isPlainRecord(value)) throw new TypeError("package.json must contain an object.");
585
+ if (!isPlainRecord(value)) throw envErrorDiagnostics.ENV_R0012({ message: "package.json must contain an object." });
546
586
  return value;
547
587
  }
548
588
  async function gitOutput(rootDir, args) {
@@ -552,14 +592,435 @@ async function gitOutput(rootDir, args) {
552
592
  function readPath(value, path) {
553
593
  return path.split(".").reduce((current, segment) => {
554
594
  if (typeof current !== "object" || current === null) return;
595
+ if (!Object.hasOwn(current, segment)) return void 0;
555
596
  return current[segment];
556
597
  }, value);
557
598
  }
558
599
  //#endregion
600
+ //#region src/env-schema/profile.ts
601
+ function fail$1(context, reason) {
602
+ throw new Error(`${context.file}:${context.line}${context.key ? ` (${context.key})` : ""}: ${reason}`);
603
+ }
604
+ function locationLine(location, end = false) {
605
+ if (typeof location !== "object" || location === null) return 1;
606
+ const point = end && "end" in location ? location.end : "start" in location ? location.start : void 0;
607
+ if (typeof point === "object" && point !== null && "line" in point && typeof point.line === "number" && Number.isInteger(point.line) && point.line > 0) return point.line;
608
+ return 1;
609
+ }
610
+ function staticValue(node, context) {
611
+ if (!(node instanceof ParsedEnvSpecStaticValue)) fail$1(context, "Only static values are supported");
612
+ const value = node.unescapedValue;
613
+ if (value === void 0 || typeof value === "string" || typeof value === "boolean" || typeof value === "number") return value;
614
+ return fail$1(context, "Unsupported static value");
615
+ }
616
+ function booleanDecorator(decorator, context) {
617
+ const value = staticValue(decorator.value, context);
618
+ if (typeof value !== "boolean") fail$1(context, "Decorator requires a static boolean");
619
+ return value;
620
+ }
621
+ function decorators(nodes, allowed, context) {
622
+ const result = /* @__PURE__ */ new Map();
623
+ for (const node of nodes) {
624
+ const here = {
625
+ ...context,
626
+ line: locationLine(node.data._location)
627
+ };
628
+ if (node.hasInvalidName || !allowed.includes(node.name) || node.strayText || node.isBareFnCall) fail$1(here, "Unsupported or malformed decorator");
629
+ if (result.has(node.name)) fail$1(here, "Duplicate decorator");
630
+ result.set(node.name, node);
631
+ }
632
+ return result;
633
+ }
634
+ function typeArguments(call, allowed, context) {
635
+ const args = /* @__PURE__ */ new Map();
636
+ for (const arg of call.data.args.values) {
637
+ if (!(arg instanceof ParsedEnvSpecKeyValuePair) || !allowed.includes(arg.key)) fail$1(context, "Unsupported type argument");
638
+ if (args.has(arg.key)) fail$1(context, "Duplicate type argument");
639
+ args.set(arg.key, staticValue(arg.value, context));
640
+ }
641
+ return args;
642
+ }
643
+ function numericArgument(args, name, context, length = false) {
644
+ if (!args.has(name)) return void 0;
645
+ const value = args.get(name);
646
+ if (typeof value !== "number" || !Number.isFinite(value) || length && (!Number.isSafeInteger(value) || value < 0)) fail$1(context, "Invalid numeric type argument");
647
+ return value;
648
+ }
649
+ function parseType(decorator, context) {
650
+ if (!decorator) return { kind: "string" };
651
+ return parseTypeNode(decorator.value, context);
652
+ }
653
+ function parseTypeNode(node, context, depth = 0) {
654
+ if (depth > 16) fail$1(context, "Type nesting exceeds 16 levels");
655
+ const name = node instanceof ParsedEnvSpecFunctionCall ? node.name : staticValue(node, context);
656
+ if (name === "array") {
657
+ const args = node instanceof ParsedEnvSpecFunctionCall ? node.data.args.values : [];
658
+ if (args.length > 1 || args[0] instanceof ParsedEnvSpecKeyValuePair) fail$1(context, "Array requires at most one item type");
659
+ return {
660
+ kind: "array",
661
+ ...args.length && { items: parseTypeNode(args[0], context, depth + 1) }
662
+ };
663
+ }
664
+ if (name === "object") {
665
+ if (!(node instanceof ParsedEnvSpecFunctionCall)) return { kind: "object" };
666
+ const entries = /* @__PURE__ */ new Map();
667
+ for (const arg of node.data.args.values) {
668
+ if (!(arg instanceof ParsedEnvSpecKeyValuePair) || !/^[A-Z_$][\w$]*$/i.test(arg.key) || [
669
+ "__proto__",
670
+ "prototype",
671
+ "constructor",
672
+ "__envSchemaUnset"
673
+ ].includes(arg.key)) fail$1(context, "Object requires safe named property types");
674
+ if (entries.has(arg.key)) fail$1(context, "Duplicate object property");
675
+ entries.set(arg.key, parseTypeNode(arg.value, context, depth + 1));
676
+ }
677
+ return {
678
+ kind: "object",
679
+ properties: Object.fromEntries(entries)
680
+ };
681
+ }
682
+ if (name === "enum") {
683
+ if (!(node instanceof ParsedEnvSpecFunctionCall) || node.data.args.values.length === 0) fail$1(context, "Enum requires string choices");
684
+ const values = node.data.args.values.map((arg) => {
685
+ const value = staticValue(arg, context);
686
+ if (typeof value !== "string" || value === "") fail$1(context, "Enum requires nonempty string choices");
687
+ return value;
688
+ });
689
+ if (new Set(values).size !== values.length) fail$1(context, "Duplicate enum choice");
690
+ return {
691
+ kind: "enum",
692
+ values
693
+ };
694
+ }
695
+ if (name === "string") {
696
+ const args = node instanceof ParsedEnvSpecFunctionCall ? typeArguments(node, ["minLength", "maxLength"], context) : /* @__PURE__ */ new Map();
697
+ const minLength = numericArgument(args, "minLength", context, true);
698
+ const maxLength = numericArgument(args, "maxLength", context, true);
699
+ if (minLength !== void 0 && maxLength !== void 0 && minLength > maxLength) fail$1(context, "Minimum length exceeds maximum length");
700
+ return {
701
+ kind: "string",
702
+ ...minLength !== void 0 && { minLength },
703
+ ...maxLength !== void 0 && { maxLength }
704
+ };
705
+ }
706
+ if (name === "number") {
707
+ const args = node instanceof ParsedEnvSpecFunctionCall ? typeArguments(node, [
708
+ "min",
709
+ "max",
710
+ "isInt"
711
+ ], context) : /* @__PURE__ */ new Map();
712
+ const min = numericArgument(args, "min", context);
713
+ const max = numericArgument(args, "max", context);
714
+ const isInt = args.get("isInt");
715
+ if (args.has("isInt") && typeof isInt !== "boolean") fail$1(context, "Integer constraint requires a static boolean");
716
+ if (min !== void 0 && max !== void 0 && min > max) fail$1(context, "Minimum exceeds maximum");
717
+ return {
718
+ kind: "number",
719
+ ...min !== void 0 && { min },
720
+ ...max !== void 0 && { max },
721
+ ...typeof isInt === "boolean" && { isInt }
722
+ };
723
+ }
724
+ if (name === "boolean" || name === "url") {
725
+ if (node instanceof ParsedEnvSpecFunctionCall) typeArguments(node, [], context);
726
+ return { kind: name };
727
+ }
728
+ return fail$1(context, "Unsupported type");
729
+ }
730
+ function lexicalValue(node, context) {
731
+ if (node.data.quote) {
732
+ const value = staticValue(node, context);
733
+ if (typeof value !== "string") fail$1(context, "Invalid quoted default");
734
+ return value;
735
+ }
736
+ const raw = node.data.rawValue;
737
+ if (raw === void 0) return void 0;
738
+ if (typeof raw !== "string") fail$1(context, "Invalid default");
739
+ const value = raw.trim();
740
+ if (!value) return void 0;
741
+ if (/^["'`[{]/.test(value) || /^[A-Z]\w*\(/i.test(value)) fail$1(context, "Unsupported or malformed default expression");
742
+ const decoded = staticValue(node, context);
743
+ return typeof decoded === "string" ? decoded : value;
744
+ }
745
+ function validUrl(value) {
746
+ try {
747
+ return !!new URL(value).protocol;
748
+ } catch {
749
+ return false;
750
+ }
751
+ }
752
+ function matchesStructuredType(value, type) {
753
+ switch (type.kind) {
754
+ case "array": {
755
+ const items = type.items;
756
+ return Array.isArray(value) && (!items || value.every((item) => matchesStructuredType(item, items)));
757
+ }
758
+ case "object": {
759
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
760
+ const properties = type.properties;
761
+ return !properties || Object.keys(value).length === Object.keys(properties).length && Object.entries(properties).every(([key, property]) => {
762
+ const item = value[key];
763
+ return Object.hasOwn(value, key) && item !== void 0 && matchesStructuredType(item, property);
764
+ });
765
+ }
766
+ case "string": return typeof value === "string" && (type.minLength === void 0 || value.length >= type.minLength) && (type.maxLength === void 0 || value.length <= type.maxLength);
767
+ 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);
768
+ case "boolean": return typeof value === "boolean";
769
+ case "enum": return typeof value === "string" && type.values.includes(value);
770
+ case "url": return typeof value === "string" && validUrl(value);
771
+ }
772
+ }
773
+ function parseDefault(value, type, required, context) {
774
+ if (value === void 0) return void 0;
775
+ if (value === "") {
776
+ if (required) fail$1(context, "Required default cannot be empty");
777
+ if (type.kind !== "string") return void 0;
778
+ }
779
+ switch (type.kind) {
780
+ case "array":
781
+ case "object": {
782
+ let parsed;
783
+ try {
784
+ parsed = JSON.parse(value);
785
+ } catch {
786
+ fail$1(context, "Default must be valid JSON");
787
+ }
788
+ if (!isEnvSchemaValue(parsed) || !matchesStructuredType(parsed, type)) fail$1(context, "Default does not match the declared JSON type");
789
+ return parsed;
790
+ }
791
+ case "string":
792
+ 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");
793
+ return value;
794
+ case "number": {
795
+ const text = value.trim();
796
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(text)) fail$1(context, "Default must be a finite decimal number");
797
+ const number = Number(text);
798
+ 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");
799
+ return number;
800
+ }
801
+ case "boolean":
802
+ if (value.trim() === "true" || value.trim() === "1") return true;
803
+ if (value.trim() === "false" || value.trim() === "0") return false;
804
+ return fail$1(context, "Default must be a boolean");
805
+ case "enum":
806
+ if (!type.values.includes(value)) fail$1(context, "Default is not an enum choice");
807
+ return value;
808
+ case "url":
809
+ if (!validUrl(value)) fail$1(context, "Default must be an absolute URL");
810
+ return value;
811
+ }
812
+ }
813
+ function parseEnvSchema(source, filename) {
814
+ let parsed;
815
+ try {
816
+ parsed = parseEnvSpecDotEnvFile(source);
817
+ } catch (error) {
818
+ return fail$1({
819
+ file: filename,
820
+ line: locationLine(typeof error === "object" && error !== null && "location" in error ? error.location : void 0)
821
+ }, "Invalid env-spec syntax");
822
+ }
823
+ const rootContext = {
824
+ file: filename,
825
+ line: 1
826
+ };
827
+ for (const block of parsed.headerBlocks) if (block.decoratorsArray.length && !block.divider) fail$1({
828
+ file: filename,
829
+ line: locationLine(block.data._location)
830
+ }, "Root decorators require a header divider");
831
+ for (const block of parsed.orphanCommentBlocks) if (block.decoratorsArray.length) fail$1({
832
+ file: filename,
833
+ line: locationLine(block.data._location)
834
+ }, "Decorator is not attached to a declaration");
835
+ const root = decorators(parsed.decoratorsArray, ["defaultRequired", "defaultSensitive"], rootContext);
836
+ const defaultRequired = root.get("defaultRequired");
837
+ const defaultSensitive = root.get("defaultSensitive");
838
+ const required = defaultRequired ? booleanDecorator(defaultRequired, rootContext) : true;
839
+ const sensitive = defaultSensitive ? booleanDecorator(defaultSensitive, rootContext) : true;
840
+ const keys = /* @__PURE__ */ new Set();
841
+ return parsed.configItems.map((item) => {
842
+ const line = Math.max(locationLine(item.data._location), ...item.data.preComments.map((comment) => locationLine(comment.data._location, true) + 1));
843
+ const context = {
844
+ file: filename,
845
+ line
846
+ };
847
+ if (!/^[A-Z_]\w*$/i.test(item.key) || item.key.length > 256 || [
848
+ "__proto__",
849
+ "prototype",
850
+ "constructor"
851
+ ].includes(item.key.toLowerCase())) fail$1(context, "Invalid or reserved environment key");
852
+ context.key = item.key;
853
+ if (keys.has(item.key)) fail$1(context, "Duplicate environment key");
854
+ keys.add(item.key);
855
+ const metadata = decorators(item.decoratorsArray, [
856
+ "type",
857
+ "required",
858
+ "optional",
859
+ "sensitive",
860
+ "public",
861
+ "example"
862
+ ], context);
863
+ if (metadata.has("required") && metadata.has("optional")) fail$1(context, "Cannot combine required and optional");
864
+ if (metadata.has("sensitive") && metadata.has("public")) fail$1(context, "Cannot combine sensitive and public");
865
+ const field = {
866
+ key: item.key,
867
+ type: parseType(metadata.get("type"), context),
868
+ required,
869
+ sensitive,
870
+ description: item.description,
871
+ docs: [],
872
+ source: {
873
+ file: filename,
874
+ line
875
+ }
876
+ };
877
+ for (const [name, node] of metadata) if (name === "required") field.required = booleanDecorator(node, context);
878
+ else if (name === "optional") field.required = !booleanDecorator(node, context);
879
+ else if (name === "sensitive") field.sensitive = booleanDecorator(node, context);
880
+ else if (name === "public") field.sensitive = !booleanDecorator(node, context);
881
+ else if (name === "example") {
882
+ const example = staticValue(node.value, context);
883
+ if (typeof example !== "string") fail$1(context, "Example must be a string");
884
+ field.example = example;
885
+ }
886
+ if (item.value !== void 0 && !(item.value instanceof ParsedEnvSpecStaticValue)) fail$1(context, "Dynamic or structured defaults are unsupported");
887
+ const checkedDefault = parseDefault(item.value ? lexicalValue(item.value, context) : void 0, field.type, field.required, context);
888
+ if (checkedDefault !== void 0) field.default = checkedDefault;
889
+ return field;
890
+ });
891
+ }
892
+ //#endregion
893
+ //#region src/env-schema/importer.ts
894
+ function fail(field, reason) {
895
+ const path = field ? `${field.source.file}:${field.source.line} (${field.key})` : "envSchema";
896
+ throw invalidEnvDeclaration(path, `${path}: ${reason}`);
897
+ }
898
+ function outputName(name) {
899
+ return name.split("_").filter(Boolean).map((word, index) => {
900
+ const normalized = word === word.toUpperCase() ? word.toLowerCase() : word;
901
+ return index === 0 ? normalized.charAt(0).toLowerCase() + normalized.slice(1) : normalized.charAt(0).toUpperCase() + normalized.slice(1);
902
+ }).join("");
903
+ }
904
+ function safePath(path, field, publicField) {
905
+ const segments = path.split(".");
906
+ if (!segments.length || publicField && segments.length !== 1 || segments.length > 16 || segments.some((segment) => !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(segment) || [
907
+ "__proto__",
908
+ "prototype",
909
+ "constructor"
910
+ ].includes(segment.toLowerCase()))) fail(field, "Output path must contain safe identifiers; Public Env paths must be flat");
911
+ if ([
912
+ "public",
913
+ "define",
914
+ "server"
915
+ ].includes(segments[0] || "")) fail(field, "Output paths cannot select an Env visibility section");
916
+ return segments;
917
+ }
918
+ function descriptor(field) {
919
+ const type = field.type;
920
+ if (type.kind === "string") return {
921
+ ...type,
922
+ minLength: Math.max(type.minLength ?? 0, field.required ? 1 : 0)
923
+ };
924
+ if (type.kind === "number") return {
925
+ ...type,
926
+ decimal: true
927
+ };
928
+ return type;
929
+ }
930
+ function add(tree, segments, declaration, field) {
931
+ const [head, ...rest] = segments;
932
+ if (!head) return fail(field, "Output path cannot be empty");
933
+ const existing = tree.get(head);
934
+ if (!rest.length) {
935
+ if (existing) fail(field, "Output path collides with another declaration");
936
+ tree.set(head, {
937
+ kind: "field",
938
+ declaration
939
+ });
940
+ return;
941
+ }
942
+ if (existing?.kind === "field") fail(field, "Output path collides with another declaration");
943
+ const children = existing?.children ?? /* @__PURE__ */ new Map();
944
+ tree.set(head, {
945
+ kind: "branch",
946
+ children
947
+ });
948
+ add(children, rest, declaration, field);
949
+ }
950
+ function serverConfig(tree) {
951
+ const result = {};
952
+ for (const [key, node] of tree) Object.defineProperty(result, key, {
953
+ enumerable: true,
954
+ configurable: true,
955
+ writable: true,
956
+ value: node.kind === "field" ? node.declaration : serverConfig(node.children)
957
+ });
958
+ return result;
959
+ }
960
+ /** Import a committed env-spec-v1 contract. Reads schema metadata, never developer env files. */
961
+ function envSchema(file, options = {}) {
962
+ const filename = file instanceof URL ? fileURLToPath(file) : resolve(file);
963
+ const prefix = options.prefix ?? "VITEHUB_";
964
+ 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");
965
+ let source;
966
+ try {
967
+ source = readFileSync(filename, "utf8");
968
+ } catch {
969
+ throw invalidEnvDeclaration(filename, `${filename}: Cannot read environment schema file`);
970
+ }
971
+ let fields;
972
+ try {
973
+ fields = parseEnvSchema(source, filename);
974
+ } catch (error) {
975
+ throw invalidEnvDeclaration(filename, error instanceof Error ? error.message : `${filename}: Invalid environment schema file`);
976
+ }
977
+ const knownKeys = new Set(fields.map((field) => field.key));
978
+ for (const key of Object.keys(options.paths ?? {})) if (!knownKeys.has(key)) fail(void 0, "Path mapping refers to an undeclared schema key");
979
+ const server = /* @__PURE__ */ new Map();
980
+ const publicConfig = {};
981
+ const publicNames = /* @__PURE__ */ new Set();
982
+ for (const field of fields) {
983
+ const publicPrefix = `${prefix}PUBLIC_`;
984
+ const publicField = field.key.startsWith(publicPrefix);
985
+ if (publicField && field.sensitive) fail(field, "A Public Env declaration cannot be sensitive; mark it @public or @sensitive=false");
986
+ if (schemaContainsEnum(field.type) && field.sensitive) fail(field, "A secret enum would expose its allowed values; use a string instead");
987
+ const name = publicField ? field.key.slice(publicPrefix.length) : prefix && field.key.startsWith(prefix) ? field.key.slice(prefix.length) : field.key;
988
+ const mapped = options.paths && Object.hasOwn(options.paths, field.key) ? options.paths[field.key] : outputName(name);
989
+ if (typeof mapped !== "string") fail(field, "Output path must be a string");
990
+ const segments = safePath(mapped, field, publicField);
991
+ const declaration = descriptorVariable(descriptor(field), {
992
+ ...field.default !== void 0 ? { default: field.default } : {},
993
+ mode: publicField ? "build" : "runtime",
994
+ required: field.required,
995
+ secret: field.sensitive,
996
+ source: env.source(field.key, {
997
+ canonical: false,
998
+ skipEmpty: !field.required && field.type.kind !== "string"
999
+ })
1000
+ });
1001
+ if (publicField) {
1002
+ if (publicNames.has(mapped)) fail(field, "Output path collides with another declaration");
1003
+ publicNames.add(mapped);
1004
+ Object.defineProperty(publicConfig, mapped, {
1005
+ enumerable: true,
1006
+ configurable: true,
1007
+ writable: true,
1008
+ value: declaration
1009
+ });
1010
+ } else add(server, segments, declaration, field);
1011
+ }
1012
+ return {
1013
+ public: publicConfig,
1014
+ server: serverConfig(server)
1015
+ };
1016
+ }
1017
+ //#endregion
559
1018
  //#region src/vite.ts
560
1019
  const ENV_VITE_PLUGIN_NAME = "@vite-hub/env/vite";
561
1020
  const ENV_PUBLIC_ID = VITEHUB_ENV_PUBLIC_ID;
562
1021
  const ENV_SERVER_ID = VITEHUB_ENV_SERVER_ID;
1022
+ const ENV_DESCRIPTION_ID = "#vitehub/env/description";
1023
+ const RESOLVED_DESCRIPTION_ID = `\0${ENV_DESCRIPTION_ID}`;
563
1024
  const RESOLVED_PUBLIC_ID = `\0${ENV_PUBLIC_ID}`;
564
1025
  const RESOLVED_SERVER_ID = `\0${ENV_SERVER_ID}`;
565
1026
  const defaultRuntimeImports = {
@@ -567,6 +1028,7 @@ const defaultRuntimeImports = {
567
1028
  server: "@vite-hub/env/server"
568
1029
  };
569
1030
  let envVitePluginSequence = 0;
1031
+ const developmentSecretLocks = /* @__PURE__ */ new Map();
570
1032
  function createEnvImportAliases(options = {}) {
571
1033
  return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
572
1034
  }
@@ -601,7 +1063,7 @@ function hubEnv(options = {}) {
601
1063
  assertConfiguredProviders(registry, resolveProviderModules(options.providers, root));
602
1064
  await prepareEnvGeneratedTypes(root, packageRoot, config?.public, registry, runtimeImports);
603
1065
  };
604
- const resolveState = async (config, mode) => {
1066
+ const resolveState = async (config, mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey) => {
605
1067
  const envConfig = config.env;
606
1068
  validateEnvConfigShape(envConfig, "vite");
607
1069
  const projectRoot = resolveProjectRoot(config.root || process.cwd());
@@ -614,7 +1076,11 @@ function hubEnv(options = {}) {
614
1076
  projectRoot,
615
1077
  providerModules,
616
1078
  publicConfig: {},
617
- serverRegistry: {}
1079
+ publicTypes: {},
1080
+ serverRegistry: {},
1081
+ developmentSecret,
1082
+ developmentSecretGenerated,
1083
+ developmentSecretEnvKey
618
1084
  }
619
1085
  };
620
1086
  const context = createSourceContext({
@@ -650,7 +1116,11 @@ function hubEnv(options = {}) {
650
1116
  projectRoot,
651
1117
  providerModules,
652
1118
  publicConfig,
653
- serverRegistry: registry
1119
+ publicTypes: createPublicTypeEntries(envConfig.public, publicConfig),
1120
+ serverRegistry: registry,
1121
+ developmentSecret,
1122
+ developmentSecretGenerated,
1123
+ developmentSecretEnvKey
654
1124
  }
655
1125
  };
656
1126
  };
@@ -664,17 +1134,35 @@ function hubEnv(options = {}) {
664
1134
  prepareTypes,
665
1135
  resolveProjectRoot
666
1136
  },
1137
+ vitehub: { cli: () => createEnvCliContributor({ resolveProjectRoot }) },
667
1138
  async config(config, env) {
1139
+ let developmentSecret;
1140
+ let developmentSecretGenerated = false;
1141
+ let developmentSecretEnvKey;
1142
+ if (env.command === "serve") {
1143
+ const projectRoot = resolveProjectRoot(config.root || process.cwd());
1144
+ const resolvedSecret = await resolveDevelopmentSecret(projectRoot, loadEnv(env.mode, projectRoot, ""));
1145
+ developmentSecret = resolvedSecret.secret;
1146
+ developmentSecretGenerated = resolvedSecret.generated;
1147
+ developmentSecretEnvKey = resolvedSecret.envKey;
1148
+ if (developmentSecretEnvKey) process.env[developmentSecretEnvKey] = developmentSecret;
1149
+ }
668
1150
  const envConfig = config.env;
669
- const { defineValues, state } = await resolveState(config, env.mode);
1151
+ const { defineValues, state } = await resolveState(config, env.mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey);
670
1152
  buildPublicConfig = state.publicConfig;
671
1153
  serverRegistry = state.serverRegistry;
672
1154
  const configStateId = String(++configStateSequence);
673
1155
  pendingConfigStates.set(configStateId, state);
674
1156
  for (const handler of serverRegistryHandlers) handler(serverRegistry, config);
675
- if (!envConfig) return { [configStateKey]: configStateId };
1157
+ if (!envConfig) return {
1158
+ [configStateKey]: configStateId,
1159
+ __vitehubEnvDevelopmentSecret: developmentSecret,
1160
+ __vitehubEnvDevelopmentSecretEnvKey: developmentSecretEnvKey
1161
+ };
676
1162
  return {
677
1163
  [configStateKey]: configStateId,
1164
+ __vitehubEnvDevelopmentSecret: developmentSecret,
1165
+ __vitehubEnvDevelopmentSecretEnvKey: developmentSecretEnvKey,
678
1166
  define: {
679
1167
  ...Object.fromEntries(Object.entries(defineValues).map(([key, value]) => [key, JSON.stringify(value)])),
680
1168
  ...config.define
@@ -685,9 +1173,22 @@ function hubEnv(options = {}) {
685
1173
  const projectRoot = resolveProjectRoot(config.root);
686
1174
  const configStateId = String(Object.getOwnPropertyDescriptor(config, configStateKey)?.value ?? "");
687
1175
  const state = pendingConfigStates.get(configStateId) ?? resolvedStates.get(projectRoot);
688
- if (!state) throw new Error(`Missing resolved Env state for ${projectRoot}`);
1176
+ if (!state) throw envErrorDiagnostics.ENV_B0001({ message: `Missing resolved Env state for ${projectRoot}` });
689
1177
  pendingConfigStates.delete(configStateId);
690
1178
  resolvedConfigStates.set(config, state);
1179
+ Reflect.defineProperty(config, "__vitehubEnvDevelopmentSecretEnvKey", {
1180
+ configurable: true,
1181
+ value: state.developmentSecretEnvKey
1182
+ });
1183
+ Reflect.defineProperty(config, "__vitehubEnvDevelopmentSecret", {
1184
+ configurable: true,
1185
+ value: state.developmentSecret
1186
+ });
1187
+ const onResolved = config.__vitehubEnvOnResolved;
1188
+ if (onResolved?.length) {
1189
+ await Promise.all(onResolved.map((callback) => callback(state.developmentSecretEnvKey)));
1190
+ onResolved.length = 0;
1191
+ }
691
1192
  for (const environmentConfig of Object.values(config.environments || {})) {
692
1193
  resolvedConfigStates.set(environmentConfig, state);
693
1194
  Reflect.defineProperty(environmentConfig, environmentStateKey, {
@@ -699,7 +1200,8 @@ function hubEnv(options = {}) {
699
1200
  resolvedStates.set(projectRoot, state);
700
1201
  if (state.diagnosticsText) config.logger.info(state.diagnosticsText);
701
1202
  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);
1203
+ const packageRoot = await resolvePackageRoot(config.root, projectRoot);
1204
+ await refreshEnvGeneratedFiles(projectRoot, packageRoot, state.publicConfig, state.publicTypes, state.serverRegistry, runtimeImports, state.providerModules, state.developmentSecretEnvKey, state.developmentSecretGenerated);
703
1205
  });
704
1206
  generatedStateWrites.set(projectRoot, generatedStateWrite);
705
1207
  try {
@@ -714,12 +1216,14 @@ function hubEnv(options = {}) {
714
1216
  const publicConfig = state?.publicConfig ?? buildPublicConfig;
715
1217
  const registry = state?.serverRegistry ?? serverRegistry;
716
1218
  const providerModules = state?.providerModules ?? {};
1219
+ if (id === RESOLVED_DESCRIPTION_ID) return createServerEnvDescriptionModule(registry);
717
1220
  if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(publicConfig);
718
- if (id === RESOLVED_SERVER_ID) return createServerEnvModule(registry, runtimeImports, providerModules);
1221
+ if (id === RESOLVED_SERVER_ID) return createServerEnvModule(registry, runtimeImports, providerModules, void 0, state?.developmentSecretEnvKey, state?.developmentSecretGenerated);
719
1222
  },
720
1223
  resolveId: {
721
1224
  order: "pre",
722
1225
  handler(id) {
1226
+ if (id === ENV_DESCRIPTION_ID) return RESOLVED_DESCRIPTION_ID;
723
1227
  if (id === ENV_PUBLIC_ID) return RESOLVED_PUBLIC_ID;
724
1228
  if (id === ENV_SERVER_ID) return RESOLVED_SERVER_ID;
725
1229
  }
@@ -731,7 +1235,7 @@ function hubEnv(options = {}) {
731
1235
  };
732
1236
  }
733
1237
  async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
734
- const publicTypes = createPreparedPublicTypeEntries(publicConfig);
1238
+ const publicTypes = createPublicTypeEntries(publicConfig);
735
1239
  await Promise.all([
736
1240
  ...packageRoot && packageRoot !== root ? [
737
1241
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(packageRoot), createPublicEnvModuleTypes(publicTypes)),
@@ -740,6 +1244,7 @@ async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverR
740
1244
  ] : [],
741
1245
  writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
742
1246
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
1247
+ writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
743
1248
  writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
744
1249
  ]);
745
1250
  }
@@ -758,34 +1263,105 @@ function resolveRuntimeImports(imports) {
758
1263
  function resolveProviderModules(providers, root) {
759
1264
  const output = {};
760
1265
  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.`);
1266
+ 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." });
1267
+ if (typeof specifier !== "string" || !specifier.trim()) throw envErrorDiagnostics.ENV_B0003({ message: `[vitehub] Env provider ${JSON.stringify(name)} requires a non-empty module specifier.` });
763
1268
  const normalized = specifier.trim();
764
- if (/^(?:\\\\[?.]\\|\/\/[?.]\/)/.test(normalized)) throw new TypeError(`[vitehub] Env provider ${JSON.stringify(name)} uses an unsupported namespaced Windows module path.`);
1269
+ if (/^(?:\\\\[?.]\\|\/\/[?.]\/)/.test(normalized)) throw envErrorDiagnostics.ENV_B0004({ message: `[vitehub] Env provider ${JSON.stringify(name)} uses an unsupported namespaced Windows module path.` });
765
1270
  output[name] = normalized.startsWith(".") ? resolve(root, normalized) : normalized;
766
1271
  }
767
1272
  return output;
768
1273
  }
769
1274
  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;
1275
+ 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.` });
1276
+ }
1277
+ const generatedSecretPattern = /^[0-9a-f]{64}$/;
1278
+ /**
1279
+ * Give the development server a root secret when none is configured, so `deriveSecret()` works without setup.
1280
+ * The secret is kept in `.vitehub/env/secret` with mode 0600 and survives restarts. Builds never generate one.
1281
+ */
1282
+ async function resolveDevelopmentSecret(projectRoot, loadedEnv) {
1283
+ const existing = developmentSecretLocks.get(projectRoot);
1284
+ if (existing) return existing;
1285
+ const pending = resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv);
1286
+ developmentSecretLocks.set(projectRoot, pending);
1287
+ try {
1288
+ return await pending;
1289
+ } finally {
1290
+ if (developmentSecretLocks.get(projectRoot) === pending) developmentSecretLocks.delete(projectRoot);
1291
+ }
1292
+ }
1293
+ async function resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv) {
1294
+ const configured = readViteHubSecret(loadedEnv);
1295
+ const envKey = `VITEHUB_SECRET_${createHash("sha256").update(resolve(projectRoot)).digest("hex").slice(0, 16)}`;
1296
+ if (configured) return {
1297
+ generated: false,
1298
+ secret: configured,
1299
+ envKey
1300
+ };
1301
+ const secretPath = resolve(projectRoot, ".vitehub", "env", "secret");
1302
+ let secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
1303
+ if (!generatedSecretPattern.test(secret)) {
1304
+ await mkdir(dirname(secretPath), { recursive: true });
1305
+ const lockPath = `${secretPath}.lock`;
1306
+ let lock;
1307
+ for (let attempt = 0; attempt < 120 && !lock; attempt++) try {
1308
+ lock = await open(lockPath, "wx", 384);
1309
+ await lock.writeFile(`${process.pid}\n`);
1310
+ } catch (error) {
1311
+ if (error.code !== "EEXIST") throw error;
1312
+ try {
1313
+ const lockStat = await stat(lockPath);
1314
+ const owner = await readFile(lockPath, "utf8").catch(() => "");
1315
+ let ownerAlive = false;
1316
+ const ownerPid = Number.parseInt(owner, 10);
1317
+ if (Number.isInteger(ownerPid) && ownerPid > 0) try {
1318
+ process.kill(ownerPid, 0);
1319
+ ownerAlive = true;
1320
+ } catch (error) {
1321
+ ownerAlive = error.code !== "ESRCH";
1322
+ }
1323
+ if (!ownerAlive && Date.now() - lockStat.mtimeMs > 3e4) {
1324
+ const stalePath = `${lockPath}.${process.pid}.${Date.now()}.stale`;
1325
+ await rename(lockPath, stalePath).catch(() => {});
1326
+ await unlink(stalePath).catch(() => {});
1327
+ }
1328
+ } catch {}
1329
+ await new Promise((resolve) => setTimeout(resolve, 5));
775
1330
  }
776
- if (isLiteralEntry(value) || isEnvEntry(value)) return;
777
- for (const [key, child] of Object.entries(value)) visit(child, `${path}.${key}`);
1331
+ if (!lock) throw new Error(`Timed out waiting for generated secret lock: ${secretPath}`);
1332
+ const replacementPath = `${secretPath}.${process.pid}.${Date.now()}.tmp`;
1333
+ try {
1334
+ secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
1335
+ if (!generatedSecretPattern.test(secret)) {
1336
+ secret = randomBytes(32).toString("hex");
1337
+ await writeFile(replacementPath, secret, {
1338
+ flag: "wx",
1339
+ mode: 384
1340
+ });
1341
+ await rename(replacementPath, secretPath);
1342
+ }
1343
+ } finally {
1344
+ const owned = await lock.stat().then((lockStat) => stat(lockPath).then((pathStat) => lockStat.dev === pathStat.dev && lockStat.ino === pathStat.ino, () => false));
1345
+ await lock.close();
1346
+ if (owned) await unlink(lockPath).catch(() => {});
1347
+ await unlink(replacementPath).catch(() => {});
1348
+ }
1349
+ }
1350
+ await chmod(secretPath, 384);
1351
+ return {
1352
+ generated: true,
1353
+ secret,
1354
+ envKey
778
1355
  };
779
- for (const [key, value] of Object.entries(registry)) visit(value, `env.server.${key}`);
780
1356
  }
781
- async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules) {
782
- const publicTypes = createPublicTypeEntries(publicConfig);
1357
+ async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated) {
783
1358
  await Promise.all([
784
- ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
1359
+ ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
785
1360
  writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
786
1361
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
787
1362
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
788
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
1363
+ writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
1364
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
789
1365
  writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
790
1366
  ]);
791
1367
  }
@@ -794,12 +1370,11 @@ function createAmbientTypesReference(packageRoot, projectRoot) {
794
1370
  const specifier = target.startsWith(".") ? target : `./${target}`;
795
1371
  return `/// <reference path=${JSON.stringify(specifier)} />\n`;
796
1372
  }
797
- function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports, providerModules) {
798
- const publicTypes = createPublicTypeEntries(publicConfig);
1373
+ function packageEnvModuleWrites(root, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated) {
799
1374
  return [
800
1375
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
801
1376
  writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
802
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
1377
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
803
1378
  writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
804
1379
  ];
805
1380
  }
@@ -840,21 +1415,27 @@ function createPublicEnvModuleTypes(publicTypes) {
840
1415
  ""
841
1416
  ].join("\n");
842
1417
  }
843
- function createServerEnvModule(serverRegistry, runtimeImports, providerModules, outputPath) {
1418
+ function createServerEnvModule(serverRegistry, runtimeImports, providerModules, outputPath, developmentSecretEnvKey, developmentSecretGenerated) {
844
1419
  const referenced = referencedProviderNames(serverRegistry);
845
1420
  const providers = Object.entries(providerModules).filter(([name]) => referenced.has(name));
846
1421
  return [
847
- `import { inspectServerEnv as inspectRegistry, loadServerEnv as loadRegistry, resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
1422
+ `import * as envRuntime from ${JSON.stringify(runtimeImports.server)};`,
848
1423
  ...providers.map(([, specifier], index) => `import envProvider${index} from ${JSON.stringify(providerImportSpecifier(specifier, outputPath))};`),
849
1424
  `const registry = JSON.parse(${JSON.stringify(JSON.stringify(serverRegistry))});`,
850
1425
  `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 }); }",
1426
+ createServerEnvDescriptionModule(serverRegistry).trimEnd(),
1427
+ "export const manageServerEnv = envRuntime.createServerEnvManagement?.(registry, providers) ?? (async () => Response.json({ message: \"Env management is unavailable.\" }, { status: 503 }));",
1428
+ "export function useServerEnv(event) { return envRuntime.resolveServerEnv(registry, event); }",
1429
+ `export async function deriveSecret(purpose, event) { return await envRuntime.deriveSecret(purpose, event, undefined, ${JSON.stringify(developmentSecretGenerated)}, ${JSON.stringify(developmentSecretEnvKey)}); }`,
1430
+ "export async function loadServerEnv(event, options) { return await envRuntime.loadServerEnv(registry, event, { ...options, providers }); }",
1431
+ "export async function inspectServerEnv(event, options) { return await envRuntime.inspectServerEnv(registry, event, { ...options, providers }); }",
854
1432
  "export async function runWithServerEnv(event, callback, options) { return await callback(await loadServerEnv(event, options)); }",
855
1433
  ""
856
1434
  ].join("\n");
857
1435
  }
1436
+ function createServerEnvDescriptionModule(serverRegistry) {
1437
+ return `export function describeServerEnv() { return JSON.parse(${JSON.stringify(JSON.stringify(describeServerEnv(serverRegistry)))}); }\n`;
1438
+ }
858
1439
  function providerImportSpecifier(specifier, outputPath) {
859
1440
  const windowsAbsolute = win32.isAbsolute(specifier);
860
1441
  if (!isAbsolute(specifier) && !windowsAbsolute) return specifier;
@@ -879,16 +1460,7 @@ function encodeModulePath(path) {
879
1460
  }
880
1461
  function referencedProviderNames(registry) {
881
1462
  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);
1463
+ for (const { entry } of runtimeRegistryEntries(registry)) if (isRuntimeProviderEntry(entry)) names.add(entry.source.provider);
892
1464
  return names;
893
1465
  }
894
1466
  function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
@@ -900,10 +1472,11 @@ function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
900
1472
  ...createServerTypeFields(serverRegistry, 2),
901
1473
  "}",
902
1474
  "export function useServerEnv(event?: unknown): ServerEnv",
1475
+ "export function deriveSecret(purpose: string, event?: unknown): Promise<string>",
903
1476
  ...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>",
1477
+ `export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ReadonlyServerEnv>`,
1478
+ `export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ServerEnvInspection>`,
1479
+ `export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<T>`,
907
1480
  ""
908
1481
  ].join("\n");
909
1482
  }
@@ -922,10 +1495,11 @@ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
922
1495
  ...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
923
1496
  " }",
924
1497
  " export function useServerEnv(event?: unknown): ServerEnv",
1498
+ " export function deriveSecret(purpose: string, event?: unknown): Promise<string>",
925
1499
  ...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>",
1500
+ ` export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ReadonlyServerEnv>`,
1501
+ ` export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ServerEnvInspection>`,
1502
+ ` export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<T>`,
929
1503
  "}",
930
1504
  ""
931
1505
  ].join("\n");
@@ -933,11 +1507,19 @@ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
933
1507
  function createServerEnvInspectionTypes(indent) {
934
1508
  const prefix = " ".repeat(indent);
935
1509
  return [
1510
+ `${prefix}export interface ServerEnvDescriptionEntry { path?: string; canonicalName?: string; source: "env" | "literal" | "provider"; provider?: string; secret: boolean; required: boolean; hasDefault: boolean; type?: string }`,
1511
+ `${prefix}export interface ServerEnvDescription { entries: readonly ServerEnvDescriptionEntry[] }`,
1512
+ `${prefix}export function describeServerEnv(): ServerEnvDescription`,
1513
+ `${prefix}export function manageServerEnv(request: Request): Promise<Response>`,
936
1514
  `${prefix}export interface ServerEnvInspectionEntry {`,
937
1515
  `${prefix} masked: boolean`,
938
1516
  `${prefix} path?: string`,
1517
+ `${prefix} provider?: string`,
1518
+ `${prefix} required: boolean`,
939
1519
  `${prefix} source: "env" | "literal" | "provider"`,
940
1520
  `${prefix} status: "available" | "defaulted" | "error" | "invalid" | "missing"`,
1521
+ `${prefix} via?: "canonical" | "conventional"`,
1522
+ `${prefix} conflict?: true`,
941
1523
  `${prefix}}`,
942
1524
  `${prefix}export interface ServerEnvInspection {`,
943
1525
  `${prefix} entries: readonly ServerEnvInspectionEntry[]`,
@@ -957,13 +1539,12 @@ function createReadonlyServerEnvTypes(indent, secretType) {
957
1539
  `${prefix} : T`
958
1540
  ];
959
1541
  }
960
- function createPublicTypeEntries(publicConfig) {
961
- return Object.fromEntries(Object.entries(publicConfig).map(([key, value]) => [key, typeof value]));
962
- }
963
- function createPreparedPublicTypeEntries(publicConfig) {
1542
+ function createPublicTypeEntries(publicConfig, resolvedValues) {
964
1543
  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" : ""}`];
1544
+ const valueSchema = runtimeValueSchema(declaration);
1545
+ const fallbackValue = resolvedValues ? resolvedValues[key] : typeof declaration.default === "undefined" ? void 0 : parseSchema(declaration.schema, declaration.default, `env.public.${key}`);
1546
+ const fallbackType = fallbackValue === null ? "null" : fallbackValue === void 0 ? "unknown" : typeof fallbackValue;
1547
+ return [key, `${declaration.type ?? (valueSchema ? envValueTypeName(valueSchema) : void 0) ?? fallbackType}${!declaration.required && typeof declaration.default === "undefined" ? " | undefined" : ""}`];
967
1548
  }));
968
1549
  }
969
1550
  function createPublicTypeFields(publicTypes, indent) {
@@ -978,15 +1559,18 @@ function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
978
1559
  });
979
1560
  }
980
1561
  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";
1562
+ if (isRuntimeLiteralEntry(value)) return literalType(value.value);
1563
+ if (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) {
1564
+ const type = envValueTypeName(value.schema ?? stringValueSchema);
1565
+ return value.secret ? `${secretType}<${type}>` : type;
1566
+ }
983
1567
  const fields = createServerTypeFields(value, indent + 2, secretType);
984
1568
  if (!fields.length) return "Record<string, never>";
985
1569
  const prefix = " ".repeat(indent);
986
1570
  return `{\n${fields.join("\n")}\n${prefix}}`;
987
1571
  }
988
1572
  function isOptionalServerValue(value) {
989
- return (isEnvEntry(value) || isProviderEntry(value)) && !value.required && typeof value.default === "undefined";
1573
+ return (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) && !value.required && typeof value.default === "undefined";
990
1574
  }
991
1575
  function literalType(value) {
992
1576
  if (value === null) return "null";
@@ -998,22 +1582,5 @@ function literalType(value) {
998
1582
  default: return "unknown";
999
1583
  }
1000
1584
  }
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
1585
  //#endregion
1019
- export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createRuntimeRegistry as createRuntimeEnvRegistry, env, hubEnv };
1586
+ export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createRuntimeRegistry as createRuntimeEnvRegistry, env, envSchema, hubEnv };