@vite-hub/env 0.1.0 → 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.
- package/README.md +178 -33
- package/dist/{access-B3qzBHye.js → access-B8lSDip4.js} +1 -1
- package/dist/{bridge-CdNdTN1V.d.ts → bridge-Cs9YfQWk.d.ts} +111 -38
- package/dist/{bridge-error-CFuU5zIz.js → bridge-error-BhJ77age.js} +14 -13
- package/dist/bridge.d.ts +2 -2
- package/dist/bridge.js +168 -6
- package/dist/cli-BPp7rdcA.d.ts +159 -0
- package/dist/{cli-CMQPQbii.js → cli-DLpY0QAo.js} +212 -30
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +1 -1
- package/dist/database.d.ts +29 -3
- package/dist/database.js +106 -15
- package/dist/declarations-C5XR3aKw.d.ts +58 -0
- package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
- package/dist/index.d.ts +145 -10
- package/dist/index.js +240 -7
- package/dist/internal/agent.d.ts +1 -1
- package/dist/internal/agent.js +2 -2
- package/dist/internal/connections.d.ts +1 -1
- package/dist/internal/connections.js +2 -2
- package/dist/internal/server.d.ts +3 -0
- package/dist/internal/server.js +2 -0
- package/dist/object-_dlsZ4lP.js +276 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-X1w--wds.js +30 -0
- package/dist/operations.d.ts +37 -0
- package/dist/operations.js +833 -0
- package/dist/runtime/public-env.d.ts +5 -0
- package/dist/runtime/public-env.js +8 -0
- package/dist/runtime/server-env.d.ts +22 -0
- package/dist/runtime/server-env.js +35 -0
- package/dist/schema-DMZ1_yhY.js +360 -0
- package/dist/seal.d.ts +8 -5
- package/dist/seal.js +9 -6
- package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
- package/dist/server-ChNL_Xc3.js +1279 -0
- package/dist/server-Dd8bjIKd.d.ts +145 -0
- package/dist/server.d.ts +3 -25
- package/dist/server.js +2 -2
- package/dist/virtual-module.d.ts +6 -6
- package/dist/vite.d.ts +59 -14
- package/dist/vite.js +304 -115
- package/package.json +27 -38
- package/dist/auth.d.ts +0 -32
- package/dist/auth.js +0 -44
- package/dist/cli-DEwcUIe0.d.ts +0 -81
- package/dist/declarations-CiRdb1qP.d.ts +0 -32
- package/dist/declarations-DAVgctKD.js +0 -236
- package/dist/error-diagnostics-CrxjYNYr.js +0 -43
- package/dist/http.d.ts +0 -2
- package/dist/http.js +0 -122
- package/dist/presets.d.ts +0 -20
- package/dist/presets.js +0 -44
- package/dist/provider.d.ts +0 -5
- package/dist/provider.js +0 -8
- package/dist/schema.d.ts +0 -15
- package/dist/schema.js +0 -55
- package/dist/secret-C2191nAa.d.ts +0 -11
- package/dist/secret.d.ts +0 -2
- package/dist/server-DufVswRJ.js +0 -670
- package/dist/values-D_r6V774.js +0 -148
package/dist/vite.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
import { t as envErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { a as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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";
|
|
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";
|
|
7
5
|
import { Diagnostic } from "nostics";
|
|
8
6
|
import { isViteHubError } from "@vite-hub/runtime";
|
|
9
|
-
import { readFileSync } from "node:fs";
|
|
7
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
8
|
import { dirname, isAbsolute, relative, resolve, win32 } from "node:path";
|
|
11
9
|
import { fileURLToPath } from "node:url";
|
|
12
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
13
10
|
import { chmod, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
11
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
14
12
|
import { loadEnv } from "vite";
|
|
15
13
|
import { execFile } from "node:child_process";
|
|
16
14
|
import { promisify } from "node:util";
|
|
@@ -22,6 +20,7 @@ function normalizeWindowsPath(input = "") {
|
|
|
22
20
|
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
23
21
|
}
|
|
24
22
|
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
|
23
|
+
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
|
25
24
|
function cwd() {
|
|
26
25
|
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
|
|
27
26
|
return "/";
|
|
@@ -93,8 +92,42 @@ function normalizeString(path, allowAboveRoot) {
|
|
|
93
92
|
const isAbsolute$1 = function(p) {
|
|
94
93
|
return _IS_ABSOLUTE_RE.test(p);
|
|
95
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
|
+
}
|
|
96
128
|
//#endregion
|
|
97
129
|
//#region ../internal/src/definition-catalog.ts
|
|
130
|
+
/** `writeFileIfChangedSync` for async callers. */
|
|
98
131
|
async function writeFileIfChanged(file, contents) {
|
|
99
132
|
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
100
133
|
await mkdir(resolve$1(file, ".."), { recursive: true });
|
|
@@ -122,12 +155,22 @@ function formatDiagnostics(entries, option = "summary") {
|
|
|
122
155
|
//#endregion
|
|
123
156
|
//#region src/core/resolve.ts
|
|
124
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
|
+
]);
|
|
125
168
|
function validateEnvConfigShape(config, _target) {
|
|
126
169
|
if (!config) return;
|
|
127
170
|
const viteConfig = config;
|
|
128
|
-
for (const key of Object.keys(viteConfig)) if (key
|
|
171
|
+
for (const key of Object.keys(viteConfig)) if (!envOptionKeys.has(key)) {
|
|
129
172
|
const path = `env.${key}`;
|
|
130
|
-
throw invalidEnvDeclaration(path, `Invalid declaration at ${path}.
|
|
173
|
+
throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Declare Env in env.public, env.define, and env.server.`);
|
|
131
174
|
}
|
|
132
175
|
for (const [key, declaration] of Object.entries(viteConfig.public || {})) {
|
|
133
176
|
assertEnvVariableDeclaration(`env.public.${key}`, declaration);
|
|
@@ -147,22 +190,20 @@ function createSourceContext(input) {
|
|
|
147
190
|
build: { timestamp: () => (/* @__PURE__ */ new Date()).toISOString() },
|
|
148
191
|
env: input.env,
|
|
149
192
|
git: {
|
|
150
|
-
branch: () =>
|
|
151
|
-
"
|
|
152
|
-
|
|
153
|
-
"
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
]),
|
|
165
|
-
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) => {
|
|
166
207
|
const value = envValue(input.env, ["GIT_SHA", "GITHUB_SHA"]);
|
|
167
208
|
if (value) return options?.short ? value.slice(0, 7) : value;
|
|
168
209
|
return gitOutput(input.rootDir, options?.short ? [
|
|
@@ -243,7 +284,7 @@ async function resolveEnvEntries(declarations, input) {
|
|
|
243
284
|
function createRuntimeRegistry(declarations, options = {}) {
|
|
244
285
|
const path = options.path ?? "env";
|
|
245
286
|
try {
|
|
246
|
-
const registry = buildRegistry(declarations, path, options.prefix);
|
|
287
|
+
const registry = buildRegistry(declarations, path, options.prefix, options.schemaModules === true);
|
|
247
288
|
assertUniqueCanonicalNames(registry, path);
|
|
248
289
|
return registry;
|
|
249
290
|
} catch (error) {
|
|
@@ -324,6 +365,7 @@ async function resolveBuildConfigValue(declaration, path, input) {
|
|
|
324
365
|
};
|
|
325
366
|
}
|
|
326
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.`);
|
|
327
369
|
const defaultValue = parseDeclarationDefault(declaration, path);
|
|
328
370
|
const source = resolveEnvSource(declaration, path, canonical ? input.prefix : false);
|
|
329
371
|
const resolvedSource = await resolveSourceValue(source, input.context);
|
|
@@ -350,7 +392,7 @@ function parseDeclarationDefault(declaration, path) {
|
|
|
350
392
|
const schema = runtimeValueSchema(declaration);
|
|
351
393
|
return schema && declaration.default !== void 0 ? parseRuntimeDefault(schema, declaration.default, path) : declaration.default;
|
|
352
394
|
}
|
|
353
|
-
function buildRegistry(declarations, path, prefix) {
|
|
395
|
+
function buildRegistry(declarations, path, prefix, schemaModules) {
|
|
354
396
|
if (typeof declarations === "undefined") return {};
|
|
355
397
|
if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
|
|
356
398
|
try {
|
|
@@ -362,16 +404,28 @@ function buildRegistry(declarations, path, prefix) {
|
|
|
362
404
|
value
|
|
363
405
|
}];
|
|
364
406
|
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)];
|
|
407
|
+
return [key, buildRegistry(value, valuePath, canonicalKey.test(key) ? prefix : false, schemaModules)];
|
|
366
408
|
}
|
|
367
409
|
if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
|
|
368
410
|
const source = resolveEnvSource(value, valuePath, canonicalKey.test(key) ? prefix : false);
|
|
369
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
|
+
}
|
|
370
424
|
const schema = runtimeValueSchema(value);
|
|
371
|
-
if (!schema) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema. Server Env
|
|
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().`);
|
|
372
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.`);
|
|
373
427
|
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.
|
|
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.`);
|
|
375
429
|
return [key, {
|
|
376
430
|
default: typeof value.default === "undefined" ? void 0 : parseRuntimeDefault(schema, value.default, valuePath),
|
|
377
431
|
required: value.required,
|
|
@@ -397,12 +451,12 @@ function setOwnValue(record, key, value) {
|
|
|
397
451
|
});
|
|
398
452
|
}
|
|
399
453
|
function parseRuntimeDefault(schema, value, path) {
|
|
400
|
-
const result = (schema.kind === "boolean" || schema.kind === "number" ?
|
|
401
|
-
message: `Expected a ${schema.kind} default.`,
|
|
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.`,
|
|
402
456
|
success: false
|
|
403
457
|
};
|
|
404
458
|
if (!result.success) throw envErrorDiagnostics.ENV_R0023({ message: `[vitehub] Invalid default for ${path}: ${result.message}` });
|
|
405
|
-
return result.data;
|
|
459
|
+
return schema.kind === "json" ? value : result.data;
|
|
406
460
|
}
|
|
407
461
|
/** The default prefix of canonical variable names. */
|
|
408
462
|
const defaultEnvPrefix = "VITEHUB_";
|
|
@@ -421,6 +475,7 @@ function resolveEnvSource(declaration, path, prefix = defaultEnvPrefix) {
|
|
|
421
475
|
const source = declaration.source ?? inferEnvSource(path);
|
|
422
476
|
const canonical = canonicalEnvName(path, prefix);
|
|
423
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.");
|
|
424
479
|
const names = [.../* @__PURE__ */ new Set([canonical, ...source.names ?? [source.name]])];
|
|
425
480
|
return names.length === 1 ? {
|
|
426
481
|
...source,
|
|
@@ -452,7 +507,7 @@ async function resolveSourceValue(source, context) {
|
|
|
452
507
|
case "env":
|
|
453
508
|
for (const name of source.names || [source.name]) {
|
|
454
509
|
const value = Object.hasOwn(context.env, name) ? context.env[name] : void 0;
|
|
455
|
-
if (typeof value !== "undefined" &&
|
|
510
|
+
if (typeof value !== "undefined" && value !== "") return {
|
|
456
511
|
label: `env:${name}`,
|
|
457
512
|
value
|
|
458
513
|
};
|
|
@@ -469,14 +524,6 @@ async function resolveSourceValue(source, context) {
|
|
|
469
524
|
label: source.label,
|
|
470
525
|
value: await resolveBuiltInSource(source.label, () => context.git.commit({ short: source.short }))
|
|
471
526
|
};
|
|
472
|
-
case "git-ref": return {
|
|
473
|
-
label: source.label,
|
|
474
|
-
value: await resolveBuiltInSource(source.label, () => context.git.ref())
|
|
475
|
-
};
|
|
476
|
-
case "git-sha": return {
|
|
477
|
-
label: source.label,
|
|
478
|
-
value: await resolveBuiltInSource(source.label, () => context.git.sha({ short: source.short }))
|
|
479
|
-
};
|
|
480
527
|
case "git-tag": return {
|
|
481
528
|
label: source.label,
|
|
482
529
|
value: await resolveBuiltInSource(source.label, () => context.git.tag())
|
|
@@ -599,7 +646,7 @@ function readPath(value, path) {
|
|
|
599
646
|
//#endregion
|
|
600
647
|
//#region src/env-schema/profile.ts
|
|
601
648
|
function fail$1(context, reason) {
|
|
602
|
-
throw
|
|
649
|
+
throw envErrorDiagnostics.ENV_B0006({ message: `${context.file}:${context.line}${context.key ? ` (${context.key})` : ""}: ${reason}` });
|
|
603
650
|
}
|
|
604
651
|
function locationLine(location, end = false) {
|
|
605
652
|
if (typeof location !== "object" || location === null) return 1;
|
|
@@ -972,7 +1019,7 @@ function envSchema(file, options = {}) {
|
|
|
972
1019
|
try {
|
|
973
1020
|
fields = parseEnvSchema(source, filename);
|
|
974
1021
|
} catch (error) {
|
|
975
|
-
throw invalidEnvDeclaration(filename, error instanceof Error ? error.message : `${filename}: Invalid environment schema file
|
|
1022
|
+
throw invalidEnvDeclaration(filename, error instanceof Error ? error.message : `${filename}: Invalid environment schema file`, envErrorDiagnostics.ENV_B0006.is(error) ? error : void 0);
|
|
976
1023
|
}
|
|
977
1024
|
const knownKeys = new Set(fields.map((field) => field.key));
|
|
978
1025
|
for (const key of Object.keys(options.paths ?? {})) if (!knownKeys.has(key)) fail(void 0, "Path mapping refers to an undeclared schema key");
|
|
@@ -989,14 +1036,10 @@ function envSchema(file, options = {}) {
|
|
|
989
1036
|
if (typeof mapped !== "string") fail(field, "Output path must be a string");
|
|
990
1037
|
const segments = safePath(mapped, field, publicField);
|
|
991
1038
|
const declaration = descriptorVariable(descriptor(field), {
|
|
992
|
-
...field.default !== void 0 ? { default: field.default } : {},
|
|
1039
|
+
...field.default !== void 0 ? { default: field.default } : { optional: !field.required },
|
|
993
1040
|
mode: publicField ? "build" : "runtime",
|
|
994
|
-
required: field.required,
|
|
995
1041
|
secret: field.sensitive,
|
|
996
|
-
source: env.source(field.key, {
|
|
997
|
-
canonical: false,
|
|
998
|
-
skipEmpty: !field.required && field.type.kind !== "string"
|
|
999
|
-
})
|
|
1042
|
+
source: env.source(field.key, { canonical: false })
|
|
1000
1043
|
});
|
|
1001
1044
|
if (publicField) {
|
|
1002
1045
|
if (publicNames.has(mapped)) fail(field, "Output path collides with another declaration");
|
|
@@ -1017,18 +1060,45 @@ function envSchema(file, options = {}) {
|
|
|
1017
1060
|
//#endregion
|
|
1018
1061
|
//#region src/vite.ts
|
|
1019
1062
|
const ENV_VITE_PLUGIN_NAME = "@vite-hub/env/vite";
|
|
1063
|
+
const envNoExternal = createNoExternalAddition("@vite-hub/env");
|
|
1020
1064
|
const ENV_PUBLIC_ID = VITEHUB_ENV_PUBLIC_ID;
|
|
1021
1065
|
const ENV_SERVER_ID = VITEHUB_ENV_SERVER_ID;
|
|
1022
1066
|
const ENV_DESCRIPTION_ID = "#vitehub/env/description";
|
|
1023
1067
|
const RESOLVED_DESCRIPTION_ID = `\0${ENV_DESCRIPTION_ID}`;
|
|
1024
|
-
const RESOLVED_PUBLIC_ID =
|
|
1068
|
+
const RESOLVED_PUBLIC_ID = "\0virtual:vitehub/env/public";
|
|
1025
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)$/;
|
|
1026
1072
|
const defaultRuntimeImports = {
|
|
1027
|
-
secret: "@vite-hub/env
|
|
1028
|
-
server: "@vite-hub/env/server"
|
|
1073
|
+
secret: "@vite-hub/env",
|
|
1074
|
+
server: "@vite-hub/env/internal/server"
|
|
1029
1075
|
};
|
|
1030
1076
|
let envVitePluginSequence = 0;
|
|
1031
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");
|
|
1032
1102
|
function createEnvImportAliases(options = {}) {
|
|
1033
1103
|
return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
|
|
1034
1104
|
}
|
|
@@ -1040,7 +1110,22 @@ function createEnvTypeScriptPaths(options = {}) {
|
|
|
1040
1110
|
[ENV_SERVER_ID]: [toTypeScriptPath(viteHubEnvServerModulePath(root))]
|
|
1041
1111
|
};
|
|
1042
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
|
+
}
|
|
1043
1127
|
function hubEnv(options = {}) {
|
|
1128
|
+
validateEnvConfigShape(options, "vite");
|
|
1044
1129
|
let buildPublicConfig = {};
|
|
1045
1130
|
let serverRegistry = {};
|
|
1046
1131
|
const resolvedStates = /* @__PURE__ */ new Map();
|
|
@@ -1053,19 +1138,21 @@ function hubEnv(options = {}) {
|
|
|
1053
1138
|
const serverRegistryHandlers = /* @__PURE__ */ new Set();
|
|
1054
1139
|
const getPublicEnv = () => buildPublicConfig;
|
|
1055
1140
|
const getServerEnvRegistry = () => serverRegistry;
|
|
1056
|
-
const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, {
|
|
1141
|
+
const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, {
|
|
1142
|
+
prefix: options.prefix,
|
|
1143
|
+
schemaModules: true
|
|
1144
|
+
});
|
|
1057
1145
|
const resolveProjectRoot = (viteRoot) => resolveViteHubProjectRoot(resolve(viteRoot), { projectRoot: options.projectRoot });
|
|
1058
1146
|
const runtimeImports = resolveRuntimeImports(options.runtimeImports);
|
|
1059
|
-
const prepareTypes = async (
|
|
1147
|
+
const prepareTypes = async (declarations, viteRoot) => {
|
|
1060
1148
|
const root = resolveProjectRoot(viteRoot);
|
|
1061
1149
|
const packageRoot = await resolvePackageRoot(viteRoot, root);
|
|
1062
|
-
const registry =
|
|
1150
|
+
const registry = createServerEnvRegistry(declarations?.server);
|
|
1063
1151
|
assertConfiguredProviders(registry, resolveProviderModules(options.providers, root));
|
|
1064
|
-
await prepareEnvGeneratedTypes(root, packageRoot,
|
|
1152
|
+
await prepareEnvGeneratedTypes(root, packageRoot, declarations?.public, registry, runtimeImports, resolveSchemaModules(registry, root));
|
|
1065
1153
|
};
|
|
1066
1154
|
const resolveState = async (config, mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey) => {
|
|
1067
|
-
const envConfig = config
|
|
1068
|
-
validateEnvConfigShape(envConfig, "vite");
|
|
1155
|
+
const envConfig = resolveDeclarations(options, config);
|
|
1069
1156
|
const projectRoot = resolveProjectRoot(config.root || process.cwd());
|
|
1070
1157
|
const providerModules = resolveProviderModules(options.providers, projectRoot);
|
|
1071
1158
|
if (!envConfig) return {
|
|
@@ -1075,6 +1162,7 @@ function hubEnv(options = {}) {
|
|
|
1075
1162
|
diagnosticsText: void 0,
|
|
1076
1163
|
projectRoot,
|
|
1077
1164
|
providerModules,
|
|
1165
|
+
schemaModules: {},
|
|
1078
1166
|
publicConfig: {},
|
|
1079
1167
|
publicTypes: {},
|
|
1080
1168
|
serverRegistry: {},
|
|
@@ -1085,7 +1173,7 @@ function hubEnv(options = {}) {
|
|
|
1085
1173
|
};
|
|
1086
1174
|
const context = createSourceContext({
|
|
1087
1175
|
env: {
|
|
1088
|
-
...loadEnv
|
|
1176
|
+
...loadAllEnv(loadEnv, mode, projectRoot),
|
|
1089
1177
|
...process.env
|
|
1090
1178
|
},
|
|
1091
1179
|
mode: "build",
|
|
@@ -1115,6 +1203,7 @@ function hubEnv(options = {}) {
|
|
|
1115
1203
|
diagnosticsText: formatDiagnostics([...publicResult.diagnostics, ...defineResult.diagnostics], options.diagnostics),
|
|
1116
1204
|
projectRoot,
|
|
1117
1205
|
providerModules,
|
|
1206
|
+
schemaModules: resolveSchemaModules(registry, projectRoot),
|
|
1118
1207
|
publicConfig,
|
|
1119
1208
|
publicTypes: createPublicTypeEntries(envConfig.public, publicConfig),
|
|
1120
1209
|
serverRegistry: registry,
|
|
@@ -1128,26 +1217,45 @@ function hubEnv(options = {}) {
|
|
|
1128
1217
|
name: ENV_VITE_PLUGIN_NAME,
|
|
1129
1218
|
api: {
|
|
1130
1219
|
createServerEnvRegistry,
|
|
1220
|
+
deploymentEnv: () => [{
|
|
1221
|
+
names: ["VITEHUB_SECRET"],
|
|
1222
|
+
required: false,
|
|
1223
|
+
secret: true,
|
|
1224
|
+
hasDefault: false,
|
|
1225
|
+
owners: ["env"]
|
|
1226
|
+
}],
|
|
1131
1227
|
getPublicEnv,
|
|
1132
1228
|
getServerEnvRegistry,
|
|
1133
1229
|
onServerEnvRegistry: (handler) => serverRegistryHandlers.add(handler),
|
|
1134
1230
|
prepareTypes,
|
|
1231
|
+
resolveDeclarations: (config) => resolveDeclarations(options, config),
|
|
1135
1232
|
resolveProjectRoot
|
|
1136
1233
|
},
|
|
1137
|
-
vitehub: {
|
|
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
|
+
},
|
|
1138
1246
|
async config(config, env) {
|
|
1139
1247
|
let developmentSecret;
|
|
1140
1248
|
let developmentSecretGenerated = false;
|
|
1141
1249
|
let developmentSecretEnvKey;
|
|
1142
1250
|
if (env.command === "serve") {
|
|
1143
1251
|
const projectRoot = resolveProjectRoot(config.root || process.cwd());
|
|
1144
|
-
const resolvedSecret = await resolveDevelopmentSecret(projectRoot, loadEnv
|
|
1252
|
+
const resolvedSecret = await resolveDevelopmentSecret(projectRoot, loadAllEnv(loadEnv, env.mode, projectRoot));
|
|
1145
1253
|
developmentSecret = resolvedSecret.secret;
|
|
1146
1254
|
developmentSecretGenerated = resolvedSecret.generated;
|
|
1147
1255
|
developmentSecretEnvKey = resolvedSecret.envKey;
|
|
1148
1256
|
if (developmentSecretEnvKey) process.env[developmentSecretEnvKey] = developmentSecret;
|
|
1149
1257
|
}
|
|
1150
|
-
const envConfig = config
|
|
1258
|
+
const envConfig = resolveDeclarations(options, config);
|
|
1151
1259
|
const { defineValues, state } = await resolveState(config, env.mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey);
|
|
1152
1260
|
buildPublicConfig = state.publicConfig;
|
|
1153
1261
|
serverRegistry = state.serverRegistry;
|
|
@@ -1201,7 +1309,7 @@ function hubEnv(options = {}) {
|
|
|
1201
1309
|
if (state.diagnosticsText) config.logger.info(state.diagnosticsText);
|
|
1202
1310
|
const generatedStateWrite = (generatedStateWrites.get(projectRoot) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
1203
1311
|
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);
|
|
1312
|
+
await refreshEnvGeneratedFiles(projectRoot, packageRoot, state.publicConfig, state.publicTypes, state.serverRegistry, runtimeImports, state.providerModules, state.schemaModules, state.developmentSecretEnvKey, state.developmentSecretGenerated);
|
|
1205
1313
|
});
|
|
1206
1314
|
generatedStateWrites.set(projectRoot, generatedStateWrite);
|
|
1207
1315
|
try {
|
|
@@ -1210,42 +1318,51 @@ function hubEnv(options = {}) {
|
|
|
1210
1318
|
if (generatedStateWrites.get(projectRoot) === generatedStateWrite) generatedStateWrites.delete(projectRoot);
|
|
1211
1319
|
}
|
|
1212
1320
|
},
|
|
1213
|
-
load
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
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
|
+
}
|
|
1222
1334
|
},
|
|
1223
1335
|
resolveId: {
|
|
1224
1336
|
order: "pre",
|
|
1337
|
+
filter: { id: ID_PATTERN },
|
|
1225
1338
|
handler(id) {
|
|
1226
1339
|
if (id === ENV_DESCRIPTION_ID) return RESOLVED_DESCRIPTION_ID;
|
|
1227
1340
|
if (id === ENV_PUBLIC_ID) return RESOLVED_PUBLIC_ID;
|
|
1228
1341
|
if (id === ENV_SERVER_ID) return RESOLVED_SERVER_ID;
|
|
1229
1342
|
}
|
|
1230
1343
|
},
|
|
1231
|
-
transform
|
|
1232
|
-
|
|
1233
|
-
|
|
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
|
+
}
|
|
1234
1350
|
}
|
|
1235
1351
|
};
|
|
1236
1352
|
}
|
|
1237
|
-
async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
|
|
1353
|
+
async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports, schemaModules) {
|
|
1238
1354
|
const publicTypes = createPublicTypeEntries(publicConfig);
|
|
1239
1355
|
await Promise.all([
|
|
1240
1356
|
...packageRoot && packageRoot !== root ? [
|
|
1241
1357
|
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(packageRoot), createPublicEnvModuleTypes(publicTypes)),
|
|
1242
|
-
writeFileIfChanged(viteHubEnvServerModuleTypesPath(packageRoot), createServerEnvModuleTypes(serverRegistry, runtimeImports)),
|
|
1358
|
+
writeFileIfChanged(viteHubEnvServerModuleTypesPath(packageRoot), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(packageRoot))),
|
|
1243
1359
|
writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))
|
|
1244
1360
|
] : [],
|
|
1245
|
-
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))),
|
|
1246
1363
|
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
|
|
1247
1364
|
writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
|
|
1248
|
-
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
|
|
1365
|
+
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(root)))
|
|
1249
1366
|
]);
|
|
1250
1367
|
}
|
|
1251
1368
|
function resolveEnvProjectRoot(options) {
|
|
@@ -1274,6 +1391,23 @@ function resolveProviderModules(providers, root) {
|
|
|
1274
1391
|
function assertConfiguredProviders(registry, providers) {
|
|
1275
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.` });
|
|
1276
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
|
+
}
|
|
1277
1411
|
const generatedSecretPattern = /^[0-9a-f]{64}$/;
|
|
1278
1412
|
/**
|
|
1279
1413
|
* Give the development server a root secret when none is configured, so `deriveSecret()` works without setup.
|
|
@@ -1328,7 +1462,7 @@ async function resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv) {
|
|
|
1328
1462
|
} catch {}
|
|
1329
1463
|
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
1330
1464
|
}
|
|
1331
|
-
if (!lock) throw
|
|
1465
|
+
if (!lock) throw envErrorDiagnostics.ENV_B0007({ message: `[vitehub] Timed out waiting for the generated secret lock: ${secretPath}.lock` });
|
|
1332
1466
|
const replacementPath = `${secretPath}.${process.pid}.${Date.now()}.tmp`;
|
|
1333
1467
|
try {
|
|
1334
1468
|
secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
|
|
@@ -1354,15 +1488,16 @@ async function resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv) {
|
|
|
1354
1488
|
envKey
|
|
1355
1489
|
};
|
|
1356
1490
|
}
|
|
1357
|
-
async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated) {
|
|
1491
|
+
async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, schemaModules, developmentSecretEnvKey, developmentSecretGenerated) {
|
|
1358
1492
|
await Promise.all([
|
|
1359
|
-
...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
|
|
1360
|
-
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))),
|
|
1361
1496
|
writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
|
|
1362
1497
|
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
|
|
1363
1498
|
writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
|
|
1364
|
-
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
|
|
1365
|
-
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
|
|
1499
|
+
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, schemaModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
|
|
1500
|
+
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, viteHubEnvServerModuleTypesPath(root)))
|
|
1366
1501
|
]);
|
|
1367
1502
|
}
|
|
1368
1503
|
function createAmbientTypesReference(packageRoot, projectRoot) {
|
|
@@ -1370,12 +1505,12 @@ function createAmbientTypesReference(packageRoot, projectRoot) {
|
|
|
1370
1505
|
const specifier = target.startsWith(".") ? target : `./${target}`;
|
|
1371
1506
|
return `/// <reference path=${JSON.stringify(specifier)} />\n`;
|
|
1372
1507
|
}
|
|
1373
|
-
function packageEnvModuleWrites(root, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated) {
|
|
1508
|
+
function packageEnvModuleWrites(root, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, schemaModules, developmentSecretEnvKey, developmentSecretGenerated) {
|
|
1374
1509
|
return [
|
|
1375
1510
|
writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
|
|
1376
1511
|
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
|
|
1377
|
-
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
|
|
1378
|
-
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)))
|
|
1379
1514
|
];
|
|
1380
1515
|
}
|
|
1381
1516
|
async function resolvePackageRoot(viteRoot, projectRoot) {
|
|
@@ -1415,18 +1550,24 @@ function createPublicEnvModuleTypes(publicTypes) {
|
|
|
1415
1550
|
""
|
|
1416
1551
|
].join("\n");
|
|
1417
1552
|
}
|
|
1418
|
-
function createServerEnvModule(serverRegistry, runtimeImports, providerModules, outputPath, developmentSecretEnvKey, developmentSecretGenerated) {
|
|
1553
|
+
function createServerEnvModule(serverRegistry, runtimeImports, providerModules, schemaModules, outputPath, developmentSecretEnvKey, developmentSecretGenerated) {
|
|
1419
1554
|
const referenced = referencedProviderNames(serverRegistry);
|
|
1420
1555
|
const providers = Object.entries(providerModules).filter(([name]) => referenced.has(name));
|
|
1556
|
+
const schemas = Object.entries(schemaModules);
|
|
1421
1557
|
return [
|
|
1422
1558
|
`import * as envRuntime from ${JSON.stringify(runtimeImports.server)};`,
|
|
1423
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))};`),
|
|
1424
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(", ")} });`] : [],
|
|
1425
1563
|
`const providers = Object.fromEntries([${providers.map(([name], index) => `[${JSON.stringify(name)}, envProvider${index}]`).join(", ")}]);`,
|
|
1426
1564
|
createServerEnvDescriptionModule(serverRegistry).trimEnd(),
|
|
1427
|
-
"export const manageServerEnv = envRuntime.createServerEnvManagement?.(registry, providers) ?? (async () => Response.json({ message: \"Env management is unavailable.\" }, { status: 503 }));",
|
|
1428
1565
|
"export function useServerEnv(event) { return envRuntime.resolveServerEnv(registry, event); }",
|
|
1429
|
-
`export async function deriveSecret(purpose,
|
|
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); }",
|
|
1430
1571
|
"export async function loadServerEnv(event, options) { return await envRuntime.loadServerEnv(registry, event, { ...options, providers }); }",
|
|
1431
1572
|
"export async function inspectServerEnv(event, options) { return await envRuntime.inspectServerEnv(registry, event, { ...options, providers }); }",
|
|
1432
1573
|
"export async function runWithServerEnv(event, callback, options) { return await callback(await loadServerEnv(event, options)); }",
|
|
@@ -1463,24 +1604,64 @@ function referencedProviderNames(registry) {
|
|
|
1463
1604
|
for (const { entry } of runtimeRegistryEntries(registry)) if (isRuntimeProviderEntry(entry)) names.add(entry.source.provider);
|
|
1464
1605
|
return names;
|
|
1465
1606
|
}
|
|
1466
|
-
function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
|
|
1607
|
+
function createServerEnvModuleTypes(serverRegistry, runtimeImports, schemaModules, outputPath) {
|
|
1608
|
+
const schemaTypes = {
|
|
1609
|
+
modules: schemaModules,
|
|
1610
|
+
outputPath
|
|
1611
|
+
};
|
|
1467
1612
|
return [
|
|
1468
1613
|
`import type { SecretEnv } from ${JSON.stringify(runtimeImports.secret)}`,
|
|
1469
1614
|
"",
|
|
1470
1615
|
...createServerEnvInspectionTypes(0),
|
|
1471
1616
|
"export interface ServerEnv {",
|
|
1472
|
-
...createServerTypeFields(serverRegistry, 2),
|
|
1617
|
+
...createServerTypeFields(serverRegistry, 2, schemaTypes),
|
|
1473
1618
|
"}",
|
|
1474
|
-
|
|
1475
|
-
|
|
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`,
|
|
1476
1623
|
...createReadonlyServerEnvTypes(0, "SecretEnv"),
|
|
1477
|
-
`export function loadServerEnv(event?:
|
|
1478
|
-
`export function inspectServerEnv(event?:
|
|
1479
|
-
`export function runWithServerEnv<T>(event:
|
|
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 {}",
|
|
1480
1657
|
""
|
|
1481
1658
|
].join("\n");
|
|
1482
1659
|
}
|
|
1483
|
-
function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
|
|
1660
|
+
function createViteTypes(publicTypes, serverRegistry, runtimeImports, schemaModules, outputPath) {
|
|
1661
|
+
const schemaTypes = {
|
|
1662
|
+
modules: schemaModules,
|
|
1663
|
+
outputPath
|
|
1664
|
+
};
|
|
1484
1665
|
return [
|
|
1485
1666
|
"declare module \"#vitehub/env/public\" {",
|
|
1486
1667
|
" export interface PublicEnv {",
|
|
@@ -1492,14 +1673,16 @@ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
|
|
|
1492
1673
|
"declare module \"#vitehub/env/server\" {",
|
|
1493
1674
|
...createServerEnvInspectionTypes(2),
|
|
1494
1675
|
" export interface ServerEnv {",
|
|
1495
|
-
...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
|
|
1676
|
+
...createServerTypeFields(serverRegistry, 4, schemaTypes, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
|
|
1496
1677
|
" }",
|
|
1497
|
-
|
|
1498
|
-
|
|
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`,
|
|
1499
1682
|
...createReadonlyServerEnvTypes(2, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
|
|
1500
|
-
` export function loadServerEnv(event?:
|
|
1501
|
-
` export function inspectServerEnv(event?:
|
|
1502
|
-
` export function runWithServerEnv<T>(event:
|
|
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>`,
|
|
1503
1686
|
"}",
|
|
1504
1687
|
""
|
|
1505
1688
|
].join("\n");
|
|
@@ -1507,12 +1690,13 @@ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
|
|
|
1507
1690
|
function createServerEnvInspectionTypes(indent) {
|
|
1508
1691
|
const prefix = " ".repeat(indent);
|
|
1509
1692
|
return [
|
|
1510
|
-
`${prefix}export interface ServerEnvDescriptionEntry { path?: string;
|
|
1693
|
+
`${prefix}export interface ServerEnvDescriptionEntry { path?: string; names?: readonly string[]; source: "env" | "literal" | "provider"; provider?: string; secret: boolean; required: boolean; hasDefault: boolean; type?: string }`,
|
|
1511
1694
|
`${prefix}export interface ServerEnvDescription { entries: readonly ServerEnvDescriptionEntry[] }`,
|
|
1512
1695
|
`${prefix}export function describeServerEnv(): ServerEnvDescription`,
|
|
1513
|
-
`${prefix}export function manageServerEnv(request: Request): Promise<Response>`,
|
|
1514
1696
|
`${prefix}export interface ServerEnvInspectionEntry {`,
|
|
1515
1697
|
`${prefix} masked: boolean`,
|
|
1698
|
+
`${prefix} names?: readonly string[]`,
|
|
1699
|
+
`${prefix} name?: string`,
|
|
1516
1700
|
`${prefix} path?: string`,
|
|
1517
1701
|
`${prefix} provider?: string`,
|
|
1518
1702
|
`${prefix} required: boolean`,
|
|
@@ -1551,24 +1735,29 @@ function createPublicTypeFields(publicTypes, indent) {
|
|
|
1551
1735
|
const prefix = " ".repeat(indent);
|
|
1552
1736
|
return Object.entries(publicTypes).map(([key, type]) => `${prefix}${JSON.stringify(key)}: ${type}`);
|
|
1553
1737
|
}
|
|
1554
|
-
function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
|
|
1738
|
+
function createServerTypeFields(registry, indent, schemaTypes, secretType = "SecretEnv") {
|
|
1555
1739
|
const prefix = " ".repeat(indent);
|
|
1556
1740
|
return Object.entries(registry).map(([key, value]) => {
|
|
1557
1741
|
const optional = isOptionalServerValue(value) ? "?" : "";
|
|
1558
|
-
return `${prefix}${JSON.stringify(key)}${optional}: ${serverTypeFor(value, indent, secretType)}`;
|
|
1742
|
+
return `${prefix}${JSON.stringify(key)}${optional}: ${serverTypeFor(value, indent, schemaTypes, secretType)}`;
|
|
1559
1743
|
});
|
|
1560
1744
|
}
|
|
1561
|
-
function serverTypeFor(value, indent, secretType) {
|
|
1745
|
+
function serverTypeFor(value, indent, schemaTypes, secretType) {
|
|
1562
1746
|
if (isRuntimeLiteralEntry(value)) return literalType(value.value);
|
|
1563
1747
|
if (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) {
|
|
1564
|
-
const type = envValueTypeName(value.schema ?? stringValueSchema);
|
|
1748
|
+
const type = value.schemaModule ? schemaOutputType(value.schemaModule.module, value.schemaModule.export, schemaTypes) : envValueTypeName(value.schema ?? stringValueSchema);
|
|
1565
1749
|
return value.secret ? `${secretType}<${type}>` : type;
|
|
1566
1750
|
}
|
|
1567
|
-
const fields = createServerTypeFields(value, indent + 2, secretType);
|
|
1751
|
+
const fields = createServerTypeFields(value, indent + 2, schemaTypes, secretType);
|
|
1568
1752
|
if (!fields.length) return "Record<string, never>";
|
|
1569
1753
|
const prefix = " ".repeat(indent);
|
|
1570
1754
|
return `{\n${fields.join("\n")}\n${prefix}}`;
|
|
1571
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
|
+
}
|
|
1572
1761
|
function isOptionalServerValue(value) {
|
|
1573
1762
|
return (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) && !value.required && typeof value.default === "undefined";
|
|
1574
1763
|
}
|
|
@@ -1583,4 +1772,4 @@ function literalType(value) {
|
|
|
1583
1772
|
}
|
|
1584
1773
|
}
|
|
1585
1774
|
//#endregion
|
|
1586
|
-
export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createRuntimeRegistry as createRuntimeEnvRegistry, env, envSchema, hubEnv };
|
|
1775
|
+
export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createEnvTypes, createRuntimeRegistry as createRuntimeEnvRegistry, env, envSchema, hubEnv };
|